ARES - authorized red-team engagement automation with dashboard, campaign scope, module orchestration, OPSEC controls, encrypted vault, and reporting.
Python active-directorycloud-securitydefensive-validationfastapigood-first-issuemitre-attackopsecreactred-teamreportingsecurity
Implement C-LIVE-v1 execution lifecycle
Mafifrizi5669724e6dbe
diff --git a/QUICKSTART.md b/QUICKSTART.mdindex 3c9e0ee..febc19a 100644--- a/QUICKSTART.md+++ b/QUICKSTART.md@@ -434,11 +434,12 @@ SQLite or PostgreSQL database requires adoption, stop all workers and follow`alembic stamp`: only audited unversioned generations 6 and 7 are supported, andSQLite adoption requires a retained verified backup.-The current managed head is revision `0009`. Upgrading to it installs-authoritative refresh-token families and deliberately invalidates existing-browser bearer sessions. Stop every worker, take the required backup, upgrade,-deploy the matching backend and frontend together, and have operators sign in-again. Revision `0009` is forward-only; do not run mixed `0008`/`0009` workers.+The current managed head is revision `0010`. It adds an authoritative+execution-lifecycle persistence catalog but does not activate a gateway or+disable legacy execution. Stop every process, take the required backup, run the+canonical upgrade, and deploy the matching 0010-aware backend. Mixed+`0009`/`0010` processes are unsupported. Revision `0009` remains the historical+refresh-family rollout that invalidated existing browser bearer sessions.The browser transport uses a host-only HttpOnly refresh cookie and a readableCSRF cookie/header pair. Access tokens remain in memory, API keys remain the@@ -446,4 +447,5 @@ automation credential, and refresh tokens are no longer returned in JSON orstored in `sessionStorage`. Deploy the matching backend and frontend together,drain existing WebSockets, and require existing users to sign in again. Arollback replaces both components together and does not downgrade the database;-there is no revision `0010` for this transport-only change.+the transport rollout itself remains revision `0009`; revision `0010` is the+separate additive lifecycle-persistence release.diff --git a/ares/api/rbac.py b/ares/api/rbac.pyindex 8554606..b1124aa 100644--- a/ares/api/rbac.py+++ b/ares/api/rbac.py@@ -69,6 +69,12 @@ class AuthenticatedUser:def has_api_scope(self, *allowed: str) -> bool:return bool(set(allowed).intersection(self.api_key_scopes))+ @property+ def canonical_user_id(self) -> str | None:+ """Return the immutable bearer identity; usernames are never identity."""+ source = self.websocket_ticket_source+ return source.user_id if source is not None else None+@propertydef operator_role(self) -> OperatorRole:"""Convert string role to OperatorRole enum (safe — defaults to REPORTER)."""@@ -206,6 +212,103 @@ async def resolve_bearer_principal()+async def revalidate_bearer_principal(+ source: BearerTicketSource,+ *,+ db: Any,+) -> PrincipalDecision:+ """Revalidate retained non-secret bearer facts without retaining the token."""+ if type(source) is not BearerTicketSource:+ return PrincipalDecision(PrincipalDecisionStatus.INVALID)+ if source.expires_at <= datetime.now(timezone.utc):+ return PrincipalDecision(PrincipalDecisionStatus.INVALID)+ if db is None:+ return PrincipalDecision(PrincipalDecisionStatus.BACKEND_UNAVAILABLE)+ try:+ row = await db.resolve_access_token_principal(+ source.subject,+ source.jti,+ source.family_id,+ source.auth_epoch,+ )+ except Exception as exc:+ logger.warning(+ "auth_backend_principal_revalidation_failed",+ error_type=type(exc).__name__,+ )+ return PrincipalDecision(PrincipalDecisionStatus.BACKEND_UNAVAILABLE)+ if not isinstance(row, Mapping):+ return PrincipalDecision(PrincipalDecisionStatus.INVALID)+ user_id = row.get("id")+ username = row.get("username")+ role = row.get("role")+ row_epoch = row.get("auth_epoch")+ if (+ user_id != source.user_id+ or username != source.subject+ or role not in _VALID_PRINCIPAL_ROLES+ or type(row_epoch) is not int+ or row_epoch != source.auth_epoch+ ):+ return PrincipalDecision(PrincipalDecisionStatus.INVALID)+ return PrincipalDecision(+ PrincipalDecisionStatus.AUTHORIZED,+ AuthoritativePrincipal(+ user_id=source.user_id,+ username=source.subject,+ role=str(role),+ websocket_ticket_source=source,+ ),+ )+++async def resolve_execution_actor_authority_revision(+ db: Any,+ user_id: str,+) -> int | None:+ """Read the current lifecycle actor revision without widening DB APIs.++ The lifecycle store deliberately keeps authority derivation internal. The+ live coordinator nevertheless needs the already-persisted actor revision+ for its point-in-time QUEUED transition. Keep this read-only adapter here,+ beside bearer revalidation, and fail closed for unknown database backends.+ """+ try:+ if db.__class__.__module__ == "ares.db.database":+ connection = db._require_connected()+ async with connection.execute(+ "SELECT revision FROM execution_actor_authority_revisions "+ "WHERE user_id=?",+ (user_id,),+ ) as cursor:+ row = await cursor.fetchone()+ value = None if row is None else row["revision"]+ elif db.__class__.__module__ == "ares.db.postgres":+ pool = db._pool+ if pool is None:+ return None+ async with pool.acquire() as connection:+ value = await connection.fetchval(+ "SELECT revision FROM execution_actor_authority_revisions "+ "WHERE user_id=$1",+ user_id,+ )+ else:+ resolver = getattr(db, "resolve_execution_actor_authority_revision", None)+ if not callable(resolver):+ return None+ value = await resolver(user_id)+ except Exception as exc:+ logger.warning(+ "execution_actor_authority_revision_lookup_failed",+ error_type=type(exc).__name__,+ )+ return None+ if type(value) is not int or not 0 <= value < 9_007_199_254_740_991:+ return None+ return value++RATE_LIMITS: dict[str, int] = {"global": 60,"auth": 10,@@ -511,6 +614,40 @@ def require_operator() -> Any:return require_role("operator", "team_lead")+def require_live_operator() -> Any:+ """Bearer-only live authority with an explicit API-key denial."""++ async def _check(+ request: Request,+ actor: AuthenticatedUser | None = Depends(get_current_user),+ ) -> AuthenticatedUser:+ if actor is None:+ if request.headers.get("X-API-Key"):+ raise HTTPException(+ status_code=status.HTTP_403_FORBIDDEN,+ detail="api_key_execution_denied",+ )+ raise HTTPException(+ status_code=status.HTTP_401_UNAUTHORIZED,+ detail="Not authenticated",+ headers={"WWW-Authenticate": "Bearer"},+ )+ if actor.role not in {"operator", "team_lead"}:+ raise HTTPException(+ status_code=status.HTTP_403_FORBIDDEN,+ detail="live_execution_role_denied",+ )+ if actor.websocket_ticket_source is None or actor.canonical_user_id is None:+ raise HTTPException(+ status_code=status.HTTP_401_UNAUTHORIZED,+ detail="Not authenticated",+ headers={"WWW-Authenticate": "Bearer"},+ )+ return actor++ return _check++def require_team_lead() -> Any:return require_role("team_lead")diff --git a/ares/api/server.py b/ares/api/server.pyindex 1c30de2..0771790 100644--- a/ares/api/server.py+++ b/ares/api/server.py@@ -23,6 +23,7 @@ from dataclasses import dataclass, fieldfrom pathlib import Pathfrom typing import Anyfrom urllib.parse import unquote+from uuid import UUIDfrom fastapi import (Depends,@@ -53,8 +54,11 @@ from ares.api.rbac import (get_current_user,rate_limit,require_any_auth,+ require_live_operator,require_operator,require_team_lead,+ resolve_execution_actor_authority_revision,+ revalidate_bearer_principal,)from ares.core.browser_sessions import (BrowserRequestContext,@@ -69,6 +73,14 @@ from ares.core.browser_sessions import (from ares.core.campaign import Campaign, Findingfrom ares.core.config import AresSettings, get_settingsfrom ares.core.engine import AresEngine+from ares.core.execution_admission import (+ DispatchDispositionV1,+ DispatchOutcomeV1,+ DispatchRequestV1,+ ExecutionAdmissionCoordinatorV1,+ RevalidatedPrincipalV1,+ canonical_intent_digest,+)from ares.core.logger import get_loggerfrom ares.core.security import create_access_tokenfrom ares.core.token_sessions import (@@ -78,8 +90,10 @@ from ares.core.token_sessions import ()from ares.core.tracing import get_current_trace_id, instrument_fastapi, setup_tracingfrom ares.db.database import AresDatabase+from ares.db.execution_lifecycle import FixedResult, TrustedPrincipalfrom ares.db.websocket_tickets import (ApiKeyTicketSource,+ BearerTicketSource,ConsumedWebSocketTicket,WebSocketTicketPrincipal,is_canonical_websocket_ticket,@@ -324,6 +338,62 @@ async def _get_engagement_lock() -> asyncio.Lock:return _engagement_lock+class _CLiveRuntime:+ """One process-local store with request-scoped coordinator callbacks."""++ def __init__(self, db: Any, engine: Any) -> None:+ self.db = db+ self.engine = engine+ self.store = db.execution_lifecycle_store()++ def bind(+ self,+ actor: AuthenticatedUser,+ ) -> tuple[TrustedPrincipal, ExecutionAdmissionCoordinatorV1]:+ source = actor.websocket_ticket_source+ if type(source) is not BearerTicketSource:+ raise HTTPException(+ status_code=401,+ detail="Not authenticated",+ headers={"WWW-Authenticate": "Bearer"},+ )+ principal = TrustedPrincipal(source.user_id, source.user_id)++ async def revalidate(+ candidate: TrustedPrincipal,+ campaign_id: str,+ module_id: str,+ ) -> RevalidatedPrincipalV1 | None:+ del campaign_id, module_id+ if candidate is not principal:+ return None+ decision = await revalidate_bearer_principal(source, db=self.db)+ if (+ decision.status is not PrincipalDecisionStatus.AUTHORIZED+ or decision.principal is None+ or decision.principal.user_id != principal.user_id+ or decision.principal.role not in {"operator", "team_lead"}+ ):+ return None+ revision = await resolve_execution_actor_authority_revision(+ self.db,+ principal.user_id,+ )+ if revision is None:+ return None+ return RevalidatedPrincipalV1(+ principal=principal,+ authority_revision=revision,+ role=decision.principal.role,+ )++ return principal, ExecutionAdmissionCoordinatorV1(+ self.store,+ self.engine,+ revalidate,+ )++# ── Lifespan ──────────────────────────────────────────────────────────────────@@ -358,6 +428,7 @@ async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:_engine = AresEngine(settings=settings, db=_db)_engine.load_modules()app.state.engine = _engine+ app.state.c_live_runtime = _CLiveRuntime(_db, _engine)# ── Redis rate limiter (optional) ────────────────────────────────────if settings.ares_redis_url:@@ -419,6 +490,7 @@ async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:# Graceful shutdown — cancel background task before closing DB_cleanup_task.cancel()await asyncio.gather(_cleanup_task, return_exceptions=True)+ app.state.c_live_runtime = Noneawait _db.close()logger.info("ARES API shutdown complete")@@ -525,7 +597,18 @@ app.add_middleware(allow_origins=_cors_origins,allow_credentials=False,allow_methods=["GET", "POST", "PUT", "DELETE", "PATCH"],- allow_headers=["Authorization", "Content-Type", "X-API-Key", "X-ARES-CSRF"],+ allow_headers=[+ "Authorization",+ "Content-Type",+ "Idempotency-Key",+ "X-API-Key",+ "X-ARES-CSRF",+ ],+ expose_headers=[+ "X-ARES-Attempt-Id",+ "X-ARES-Logical-Execution-Id",+ "X-ARES-Submission-Id",+ ],)app.add_middleware(TrustedHostMiddleware,@@ -634,6 +717,184 @@ def get_engine(request: Request) -> AresEngine:return engine+def get_c_live_runtime(request: Request) -> Any:+ """Return the lifespan-owned store wrapper; never create one per request."""+ runtime = getattr(request.app.state, "c_live_runtime", None)+ if runtime is None or not callable(getattr(runtime, "bind", None)):+ raise HTTPException(503, "Execution admission is not ready")+ return runtime+++_C_LIVE_IDEMPOTENCY_HEADER = "Idempotency-Key"+_C_LIVE_SECRET_NAMES = frozenset(+ {+ "access_key",+ "api_key",+ "credential",+ "krbtgt_hash",+ "lm_hash",+ "nt_hash",+ "password",+ "private_key",+ "secret",+ "secret_key",+ "ssh_pass",+ "token",+ }+)+++def _require_c_live_idempotency_key(request: Request) -> str:+ values = request.headers.getlist(_C_LIVE_IDEMPOTENCY_HEADER)+ if not values or (len(values) == 1 and values[0] == ""):+ raise HTTPException(status_code=422, detail="idempotency_key_required")+ if len(values) != 1:+ raise HTTPException(status_code=422, detail="idempotency_key_invalid")+ value = values[0]+ try:+ parsed = UUID(value)+ except (AttributeError, TypeError, ValueError):+ raise HTTPException(status_code=422, detail="idempotency_key_invalid") from None+ if parsed.version != 4 or str(parsed) != value:+ raise HTTPException(status_code=422, detail="idempotency_key_invalid")+ return value+++def _contains_c_live_raw_secret(value: Any, *, field_name: str = "") -> bool:+ from pydantic import SecretStr++ if isinstance(value, SecretStr):+ return bool(value.get_secret_value())+ normalized = field_name.strip().lower().replace("-", "_")+ if normalized in _C_LIVE_SECRET_NAMES and value not in (None, "", (), [], {}):+ return True+ if isinstance(value, Mapping):+ return any(+ _contains_c_live_raw_secret(item, field_name=str(key))+ for key, item in value.items()+ )+ if isinstance(value, (list, tuple)):+ return any(+ _contains_c_live_raw_secret(item, field_name=field_name)+ for item in value+ )+ return False+++def _c_live_descriptor_gate(module_id: str, role: str) -> str | None:+ """Production-only descriptor gate; tests may replace this private seam."""+ from ares.modules.descriptors import get_descriptor++ descriptor = get_descriptor(module_id)+ if descriptor is None or not descriptor.future_gateway_eligible:+ return "descriptor_unavailable"+ minimum_role = descriptor.minimum_role.value+ if minimum_role == "team_lead" and role != "team_lead":+ return "execution_not_dispatchable"+ return None+++def _c_live_identity_payload(outcome: DispatchOutcomeV1) -> dict[str, str]:+ identity = outcome.identity+ if identity is None:+ return {}+ return {+ "submission_id": identity.submission_id,+ "logical_execution_id": identity.logical_execution_id,+ "attempt_id": identity.attempt_id,+ }+++def _c_live_identity_headers(outcome: DispatchOutcomeV1) -> dict[str, str]:+ identity = outcome.identity+ if identity is None:+ return {}+ return {+ "X-ARES-Submission-Id": identity.submission_id,+ "X-ARES-Logical-Execution-Id": identity.logical_execution_id,+ "X-ARES-Attempt-Id": identity.attempt_id,+ }+++def _c_live_fixed_result(outcome: DispatchOutcomeV1) -> FixedResult:+ value = outcome.lifecycle_result+ return value if type(value) is FixedResult else FixedResult(str(value))+++def _c_live_error_response(+ outcome: DispatchOutcomeV1,+ *,+ override: str | None = None,+) -> JSONResponse:+ result = _c_live_fixed_result(outcome)+ if override == "descriptor_unavailable":+ status_code, error_type = 409, "descriptor_unavailable"+ elif override == "execution_not_dispatchable":+ status_code, error_type = 409, "execution_not_dispatchable"+ elif (+ outcome.disposition is DispatchDispositionV1.INDETERMINATE+ or (outcome.effect_started and not outcome.terminal_committed)+ ):+ status_code, error_type = 503, "execution_settlement_unconfirmed"+ elif outcome.disposition is DispatchDispositionV1.REPLAYED or result in {+ FixedResult.REPLAYED,+ FixedResult.REPLAYED_BOUND_CHILD,+ FixedResult.REPLAYED_CLOSED,+ }:+ status_code, error_type = 409, "execution_replayed_no_redispatch"+ elif result is FixedResult.CONFLICT_OPERATION:+ status_code, error_type = 409, "idempotency_conflict"+ elif result is FixedResult.INVALID_CONTRACT:+ status_code, error_type = 422, "invalid_contract"+ elif result is FixedResult.AUTHORITY_STALE:+ status_code, error_type = 409, "execution_authority_stale"+ elif result is FixedResult.CAPACITY_UNAVAILABLE:+ status_code, error_type = 429, "execution_capacity_unavailable"+ elif result is FixedResult.INCONSISTENT_BUDGET_SET:+ status_code, error_type = 503, "execution_budget_set_unavailable"+ elif result is FixedResult.NOT_FOUND_OR_PURGED:+ status_code, error_type = 410, "execution_not_found_or_purged"+ elif result is FixedResult.INVARIANT_FAILURE:+ status_code, error_type = 500, "execution_invariant_failure"+ else:+ status_code, error_type = 409, "execution_not_dispatchable"+ content: dict[str, Any] = {+ "code": status_code,+ "detail": error_type,+ "type": error_type,+ "result": result.value,+ "redispatched": False,+ "outcome": "unavailable",+ }+ identity = _c_live_identity_payload(outcome)+ if identity:+ content["execution"] = identity+ return JSONResponse(+ status_code=status_code,+ content=content,+ headers=_c_live_identity_headers(outcome),+ )+++def _c_live_unavailable_response(error_type: str) -> JSONResponse:+ return JSONResponse(+ status_code=409,+ content={+ "code": 409,+ "detail": error_type,+ "type": error_type,+ "result": FixedResult.CONFLICT_STATE.value,+ "redispatched": False,+ "outcome": "unavailable",+ },+ )+++def _apply_c_live_identity_headers(response: Response, outcome: DispatchOutcomeV1) -> None:+ for name, value in _c_live_identity_headers(outcome).items():+ response.headers[name] = value++async def get_current_user_or_apikey(request: Request,bearer: AuthenticatedUser | None = Depends(get_current_user),@@ -1567,6 +1828,65 @@ def _collect_plan_module_ids_for_authorization(return sorted(set(module_ids))+def _prepare_c_live_plan_children(+ plan: Any,+ global_params: Mapping[str, Any],+) -> list[dict[str, Any]]:+ """Validate and freeze the complete ordered fan-out before any effect."""+ from pydantic import ValidationError as PydanticValidationError++ from ares.modules.params import validate_module_params++ children: list[dict[str, Any]] = []+ occurrences: dict[str, int] = {}+ absolute_ordinal = 0+ for stage_ordinal, stage in enumerate(plan.stages):+ stage_params = stage.get("params", {})+ if not isinstance(stage_params, Mapping):+ raise HTTPException(status_code=422, detail="Invalid plan: stage params must be a map")+ for module_ordinal, module_id in enumerate(stage["modules"]):+ raw_module_params = stage_params.get(module_id, {})+ if not isinstance(raw_module_params, Mapping):+ raise HTTPException(+ status_code=422,+ detail=f"Invalid plan params for module {module_id!r}",+ )+ raw_params = {**dict(global_params), **dict(raw_module_params)}+ if _contains_c_live_raw_secret(raw_params):+ raise HTTPException(status_code=422, detail="raw_secret_material_forbidden")+ try:+ validated_params = validate_module_params(module_id, raw_params)+ except PydanticValidationError as exc:+ errors = [+ {"field": ".".join(str(item) for item in error["loc"]), "msg": error["msg"]}+ for error in exc.errors()+ ]+ raise HTTPException(+ status_code=422,+ detail={+ "message": f"Invalid params for module {module_id!r}",+ "errors": errors,+ },+ ) from None+ if _contains_c_live_raw_secret(validated_params):+ raise HTTPException(status_code=422, detail="raw_secret_material_forbidden")+ occurrence = occurrences.get(module_id, 0)+ occurrences[module_id] = occurrence + 1+ children.append(+ {+ "module_id": module_id,+ "raw_parameters": validated_params,+ "occurrence": occurrence,+ "stage_ordinal": stage_ordinal,+ "decision_ordinal": 0,+ "module_ordinal": module_ordinal,+ "absolute_ordinal": absolute_ordinal,+ }+ )+ absolute_ordinal += 1+ return children++def _require_high_noise_module_access(module_ids: Iterable[Any],actor: AuthenticatedUser,@@ -1610,17 +1930,22 @@ async def run_module(module_id: str,body: RunRequest,request: Request,- actor: AuthenticatedUser = Depends(require_operator()),+ response: Response,+ actor: AuthenticatedUser = Depends(require_live_operator()),_rate: None = Depends(rate_limit("module_run")),engine: AresEngine = Depends(get_engine),db: AresDatabase = Depends(get_db),+ c_live_runtime: Any = Depends(get_c_live_runtime),) -> dict[str, Any]:- """Run module. HIGH_NOISE requires team_lead. Rate limited: 20/min."""+ """Dispatch one live module only through durable v3 admission."""if isinstance(engine, AresEngine):engine.bind_database(db)- # Use the engine's already-loaded registry — avoids rescanning disk on every request.- _require_high_noise_module_access([module_id], actor, engine)+ campaign = await db.get_campaign(body.campaign_id)+ if not campaign:+ raise HTTPException(404, "Campaign not found")++ raw_params = dict(body.params)# Validate params against Pydantic schemafrom pydantic import ValidationError as PydanticValidationError@@ -1648,54 +1973,60 @@ async def run_module("message": f"Invalid params for module {module_id!r}","errors": errors,},- )- # Replace raw params with validated (type-coerced, secret-wrapped) params- body = body.model_copy(update={"params": validated_params})-- campaign = await db.get_campaign(body.campaign_id)- if not campaign:- raise HTTPException(404, "Campaign not found")- await _require_campaign_access(campaign, actor)-- # Reconstruct Campaign object from DB row.- c_obj = _campaign_from_db_row(campaign)-- # Unwrap SecretStr objects → plain strings before handing to modules.- # Pydantic wraps secret fields after validation; libraries like impacket / ldap3- # expect plain str — passing SecretStr causes silent auth failures.- from pydantic import SecretStr as _SecretStr-- def _unwrap_secrets(params: dict) -> dict:- return {- k: (v.get_secret_value() if isinstance(v, _SecretStr) else v)- for k, v in params.items()- }-- safe_params = _unwrap_secrets(body.params)-+ ) from None# Dry-run: validate + preview without touching targetif getattr(body, "dry_run", False):- return engine.dry_run_module(module_id, safe_params)+ return engine.dry_run_module(module_id, validated_params)- # The DB-bound engine owns finding, credential, module-run, audit, and- # telemetry persistence. Keeping this route read/response-only prevents- # duplicate rows for API-triggered executions.- result = await engine.run_module(- module_id, c_obj, safe_params, actor_role=actor.role+ idempotency_key = _require_c_live_idempotency_key(request)+ if _contains_c_live_raw_secret(raw_params) or _contains_c_live_raw_secret(+ validated_params+ ):+ raise HTTPException(status_code=422, detail="raw_secret_material_forbidden")+ descriptor_result = _c_live_descriptor_gate(module_id, actor.role)+ if descriptor_result is not None:+ return _c_live_unavailable_response(descriptor_result)++ c_obj = _campaign_from_db_row(campaign)+ principal, coordinator = c_live_runtime.bind(actor)+ outcome = await coordinator.execute_module(+ principal,+ DispatchRequestV1(+ campaign_id=body.campaign_id,+ module_id=module_id,+ ingress_code="api_module",+ idempotency_key=idempotency_key,+ raw_parameters=validated_params,+ whole_intent_digest=canonical_intent_digest(+ {+ "campaign_id": body.campaign_id,+ "module_id": module_id,+ "params": raw_params,+ }+ ),+ ),+ c_obj,)+ if (+ outcome.disposition is not DispatchDispositionV1.TERMINAL+ or not outcome.terminal_committed+ or outcome.module_result is None+ ):+ return _c_live_error_response(outcome)- # Broadcast to WebSocket subscribersawait _broadcast_event(body.campaign_id,{"type": "module_complete","module_id": module_id,- "findings": len(result.findings),- "status": result.status,+ "findings": len(outcome.module_result.findings),+ "status": outcome.module_result.status,},)-- return _safe_module_result_payload(result)+ _apply_c_live_identity_headers(response, outcome)+ payload = _safe_module_result_payload(outcome.module_result)+ payload["execution"] = _c_live_identity_payload(outcome)+ return payload# ── WebSocket ─────────────────────────────────────────────────────────────────@@ -1822,153 +2153,131 @@ def _strategy_llm_configuration_error(backend: str) -> str:return ""[email protected]("/strategy/engage", tags=["strategy"], status_code=202)+def _strategy_test_plan(body: AutonomousEngagementRequest) -> dict[str, Any] | None:+ """Private pure-plan seam. Production always returns non-dispatchable."""+ del body+ return None++[email protected]("/strategy/engage", tags=["strategy"], status_code=200)async def start_autonomous_engagement(body: AutonomousEngagementRequest,- actor: AuthenticatedUser = Depends(require_operator()),+ request: Request,+ response: Response,+ actor: AuthenticatedUser = Depends(require_live_operator()),+ _rate: None = Depends(rate_limit("module_run")),+ engine: AresEngine = Depends(get_engine),+ db: AresDatabase = Depends(get_db),+ c_live_runtime: Any = Depends(get_c_live_runtime),) -> dict:- """- Start an autonomous multi-round red team engagement via StrategyEngine.- Uses AI planning + EDR bypass + coverage prediction in a continuous loop.- Returns immediately — monitor via WebSocket /ws/campaigns/{id}/events.- ConstitutionEnforcer enforces authorizations list server-side.- """- if not _db or not _engine:- raise HTTPException(status_code=503, detail="Engine or database not available")-- # FIX 3: ALWAYS_REQUIRE_AUTH modules need team_lead role- from ares.strategy.enforcer import ALWAYS_REQUIRE_AUTH-- restricted = [m for m in body.authorizations if m in ALWAYS_REQUIRE_AUTH]- if restricted and actor.role != "team_lead":- raise HTTPException(- status_code=403,- detail=(- f"Authorizing {restricted} requires team_lead role. "- f"Current role: {actor.role!r}. "- "Contact your team lead to run this engagement."- ),- )-- for backend in (body.llm_backend, body.secondary_backend):- if backend:- config_error = _strategy_llm_configuration_error(backend)- if config_error:- raise HTTPException(status_code=422, detail=config_error)-- campaign_data = await _db.get_campaign(body.campaign_id)+ """Synchronously dispatch only a pre-supplied pure deterministic test plan."""+ campaign_data = await db.get_campaign(body.campaign_id)if not campaign_data:raise HTTPException(status_code=404, detail=f"Campaign {body.campaign_id!r} not found")- await _require_campaign_access(campaign_data, actor)+ idempotency_key = _require_c_live_idempotency_key(request)+ plan_data = _strategy_test_plan(body)+ if plan_data is None:+ return _c_live_unavailable_response("descriptor_unavailable")+ if not isinstance(plan_data, Mapping):+ raise HTTPException(status_code=422, detail="invalid_contract")+ from ares.core.engine import ExecutionPlan++ _collect_plan_module_ids_for_authorization(plan_data)+ try:+ plan = ExecutionPlan.from_dict(dict(plan_data))+ except Exception as exc:+ raise HTTPException(status_code=422, detail=f"Invalid plan: {exc}") from None+ children = _prepare_c_live_plan_children(plan, {})+ if not children:+ return _c_live_error_response(+ DispatchOutcomeV1(+ DispatchDispositionV1.NON_DISPATCHABLE,+ None,+ FixedResult.INVALID_CONTRACT,+ None,+ )+ )+ for child in children:+ child["decision_ordinal"] = child["stage_ordinal"]+ descriptor_result = _c_live_descriptor_gate(child["module_id"], actor.role)+ if descriptor_result is not None:+ return _c_live_unavailable_response(descriptor_result)++ whole_intent_digest = canonical_intent_digest(+ {+ "campaign_id": body.campaign_id,+ "request": body.model_dump(mode="json"),+ "strategy_plan": plan_data,+ }+ )campaign = (_campaign_from_db_row(campaign_data)if isinstance(campaign_data, dict)else campaign_data)-- # FIX 2: Concurrent engagement limit — atomic via asyncio.Lock (Issue 14)- _max = int(os.environ.get("ARES_MAX_ENGAGEMENTS", _MAX_CONCURRENT_ENGAGEMENTS))- _lock = await _get_engagement_lock()- async with _lock:- active_for_campaign = sum(- 1 for cid in _active_engagements.values() if cid == body.campaign_id+ principal, coordinator = c_live_runtime.bind(actor)+ result_rows: list[dict[str, Any]] = []+ final_outcome: DispatchOutcomeV1 | None = None+ for child in children:+ outcome = await coordinator.execute_module(+ principal,+ DispatchRequestV1(+ campaign_id=body.campaign_id,+ module_id=child["module_id"],+ ingress_code="strategy",+ idempotency_key=idempotency_key,+ raw_parameters=child["raw_parameters"],+ whole_intent_digest=whole_intent_digest,+ occurrence=child["occurrence"],+ stage_ordinal=child["stage_ordinal"],+ decision_ordinal=child["decision_ordinal"],+ module_ordinal=child["module_ordinal"],+ ),+ campaign,)- # Per-campaign limit: one active engagement at a time per campaign- if active_for_campaign >= 1:- raise HTTPException(- status_code=429,- detail=(- f"Campaign {body.campaign_id!r} already has an active engagement. "- "Wait for it to complete before starting a new one."- ),- )- # Global limit- if len(_active_engagements) >= _max:- raise HTTPException(- status_code=429,- detail=(- f"Maximum concurrent engagements ({_max}) reached. "- "Wait for an active engagement to complete or increase "- "ARES_MAX_ENGAGEMENTS env var."+ if (+ outcome.disposition is not DispatchDispositionV1.TERMINAL+ or not outcome.terminal_committed+ or outcome.module_result is None+ ):+ return _c_live_error_response(outcome)+ result_rows.append(+ {+ "module_id": child["module_id"],+ "occurrence": child["occurrence"],+ "stage_ordinal": child["stage_ordinal"],+ "decision_ordinal": child["decision_ordinal"],+ "module_ordinal": child["module_ordinal"],+ "status": (+ outcome.module_result.status.value+ if hasattr(outcome.module_result.status, "value")+ else str(outcome.module_result.status)),- )- # Register inside lock — atomically with checks above- import time as _time_reg-- engagement_id = f"engage_{body.campaign_id[:8]}_{int(_time_reg.time())}"- _active_engagements[engagement_id] = body.campaign_id- # Enforce campaign ownership — same as all other campaign endpoints- async def _run() -> None:- from ares.strategy import OperatorNotifier, StrategyEngine-- async def _notify(msg: dict) -> None:- await _broadcast_event(- body.campaign_id,- {"type": "strategy_event", "data": msg},- )-- notifier = OperatorNotifier(notify_fn=_notify)- se = StrategyEngine(- ares_engine=_engine, settings=get_settings(), notifier=notifier+ "findings_count": len(outcome.module_result.findings),+ "error": outcome.module_result.error,+ "duration_ms": outcome.module_result.duration_ms,+ "execution": _c_live_identity_payload(outcome),+ })- try:- result = await se.run_autonomous_engagement(- campaign=campaign,- goal=body.goal,- max_rounds=body.max_rounds,- max_detection_probability=body.max_detection_probability,- confidence_threshold=body.confidence_threshold,- llm_backend=body.llm_backend,- secondary_backend=body.secondary_backend,- adversarial_sim=body.adversarial_sim,- actor_role=actor.role,- authorizations=body.authorizations,- forbidden_modules=set(body.forbidden_modules),- allow_persistence=body.allow_persistence,- )- await _notify(- {- "event": "engagement_complete",- "engagement_id": engagement_id,- "final_status": result.final_status,- "rounds": result.total_rounds,- "detection_score": result.final_detection_score,- "succeeded": result.modules_succeeded,- }- )- except Exception as exc:- logger.error(- "autonomous_engagement_failed",- error_type=type(exc).__name__,- )- await _notify(- {- "event": "engagement_error",- "engagement_id": engagement_id,- "error": str(exc)[:200],- }- )- finally:- async with _lock:- _active_engagements.pop(engagement_id, None)- _engagement_tasks.pop(engagement_id, None)-- _engagement_tasks[engagement_id] = asyncio.create_task(- _run(), name=f"ares-strategy-{engagement_id}"+ final_outcome = outcome+ await _broadcast_event(+ body.campaign_id,+ {+ "type": "strategy_complete",+ "modules_run": len(result_rows),+ "status": "completed",+ },)+ if final_outcome is not None:+ _apply_c_live_identity_headers(response, final_outcome)return {- "engagement_id": engagement_id,- "status": "started",+ "status": "completed","campaign_id": body.campaign_id,"goal": body.goal,- "max_rounds": body.max_rounds,- "authorizations": body.authorizations,- "note": (- "Running in background. Monitor via WebSocket "- "/ws/campaigns/{campaign_id}/events for strategy_event updates."- ),+ "modules_run": len(result_rows),+ "children": result_rows,}@@ -2753,10 +3062,12 @@ async def run_campaign_plan(campaign_id: str,body: PlanRunRequest,request: Request,- actor: AuthenticatedUser = Depends(require_operator()),+ response: Response,+ actor: AuthenticatedUser = Depends(require_live_operator()),_rate: None = Depends(rate_limit("module_run")),engine: AresEngine = Depends(get_engine),db: AresDatabase = Depends(get_db),+ c_live_runtime: Any = Depends(get_c_live_runtime),) -> dict[str, Any]:"""Execute (or dry-run) a full ExecutionPlan against a campaign.@@ -2770,37 +3081,102 @@ async def run_campaign_plan(campaign = await db.get_campaign(campaign_id)if not campaign:raise HTTPException(404, "Campaign not found")- await _require_campaign_access(campaign, actor)from ares.core.engine import ExecutionPlan- plan_module_ids = _collect_plan_module_ids_for_authorization(body.plan)+ _collect_plan_module_ids_for_authorization(body.plan)try:plan = ExecutionPlan.from_dict(body.plan)except Exception as exc:- raise HTTPException(422, f"Invalid plan: {exc}")-- _require_high_noise_module_access(plan_module_ids, actor, engine)+ raise HTTPException(422, f"Invalid plan: {exc}") from Noneif body.dry_run:return engine.dry_run_plan(plan, body.global_params)+ idempotency_key = _require_c_live_idempotency_key(request)+ children = _prepare_c_live_plan_children(plan, body.global_params)+ if not children:+ return _c_live_error_response(+ DispatchOutcomeV1(+ DispatchDispositionV1.NON_DISPATCHABLE,+ None,+ FixedResult.INVALID_CONTRACT,+ None,+ )+ )+ for child in children:+ descriptor_result = _c_live_descriptor_gate(child["module_id"], actor.role)+ if descriptor_result is not None:+ return _c_live_unavailable_response(descriptor_result)++ whole_intent_digest = canonical_intent_digest(+ {+ "campaign_id": campaign_id,+ "global_params": body.global_params,+ "plan": body.plan,+ }+ )c_obj = _campaign_from_db_row(campaign)- results = await engine.run_plan(plan, c_obj, body.global_params, actor_role=actor.role)- return {- "campaign_id": campaign_id,- "modules_run": len(results),- "results": {- mid: {+ principal, coordinator = c_live_runtime.bind(actor)+ result_rows: list[dict[str, Any]] = []+ final_outcome: DispatchOutcomeV1 | None = None+ for child in children:+ outcome = await coordinator.execute_module(+ principal,+ DispatchRequestV1(+ campaign_id=campaign_id,+ module_id=child["module_id"],+ ingress_code="api_campaign_plan",+ idempotency_key=idempotency_key,+ raw_parameters=child["raw_parameters"],+ whole_intent_digest=whole_intent_digest,+ occurrence=child["occurrence"],+ stage_ordinal=child["stage_ordinal"],+ decision_ordinal=child["decision_ordinal"],+ module_ordinal=child["module_ordinal"],+ ),+ c_obj,+ )+ if (+ outcome.disposition is not DispatchDispositionV1.TERMINAL+ or not outcome.terminal_committed+ or outcome.module_result is None+ ):+ return _c_live_error_response(outcome)+ await _broadcast_event(+ campaign_id,+ {+ "type": "module_complete",+ "module_id": child["module_id"],+ "findings": len(outcome.module_result.findings),+ "status": outcome.module_result.status,+ },+ )+ result_rows.append(+ {+ "module_id": child["module_id"],+ "occurrence": child["occurrence"],+ "stage_ordinal": child["stage_ordinal"],+ "decision_ordinal": child["decision_ordinal"],+ "module_ordinal": child["module_ordinal"],"status": (- r.status.value if hasattr(r.status, "value") else str(r.status)+ outcome.module_result.status.value+ if hasattr(outcome.module_result.status, "value")+ else str(outcome.module_result.status)),- "findings_count": len(r.findings),- "error": r.error,- "duration_ms": r.duration_ms,+ "findings_count": len(outcome.module_result.findings),+ "error": outcome.module_result.error,+ "duration_ms": outcome.module_result.duration_ms,+ "execution": _c_live_identity_payload(outcome),}- for mid, r in results.items()- },+ )+ final_outcome = outcome+ if final_outcome is not None:+ _apply_c_live_identity_headers(response, final_outcome)+ return {+ "campaign_id": campaign_id,+ "modules_run": len(result_rows),+ "children": result_rows,}diff --git a/ares/cli/typer_main.py b/ares/cli/typer_main.pyindex 2836280..0ac7b7f 100644--- a/ares/cli/typer_main.py+++ b/ares/cli/typer_main.py@@ -22,25 +22,32 @@ Usage:from __future__ import annotationsimport asyncio+import getpassimport jsonimport osimport shutilimport signalimport socket+import sslimport subprocessimport sysimport threadingimport time+import uuidimport webbrowser+from collections.abc import Callablefrom pathlib import Path-from typing import Any, Callable, Optional+from typing import Any, Optional+from urllib import error as urllib_error+from urllib import parse as urllib_parse+from urllib import request as urllib_requestimport typer+from rich import print as rprintfrom rich.console import Console-from rich.table import Table-from rich.panel import Panelfrom rich.markup import escape-from rich import print as rprint+from rich.panel import Panel+from rich.table import Tableapp = typer.Typer(name = "ares",@@ -61,6 +68,175 @@ console = Console()PYTHON_MIN_VERSION = (3, 10)PYTHON_MAX_VERSION_EXCLUSIVE = (3, 13)AD_IMPACKET_TESTED_PYTHON = (3, 12)+_C_LIVE_LOOPBACK_HOSTS = frozenset({"localhost", "127.0.0.1", "::1"})+_C_LIVE_MAX_RESPONSE_BYTES = 1_048_576+++class _CLiveCliError(RuntimeError):+ """Fixed, non-sensitive C-LIVE CLI transport failure."""+++class _CLiveRejectRedirects(urllib_request.HTTPRedirectHandler):+ def redirect_request(+ self,+ req: Any,+ fp: Any,+ code: int,+ msg: str,+ headers: Any,+ newurl: str,+ ) -> None:+ del req, fp, code, msg, headers, newurl+ return None+++def _c_live_api_url() -> tuple[str, bool]:+ """Return the exact configured API origin and whether verified TLS is required."""+ value = os.getenv("ARES_API_URL")+ if type(value) is not str or not value or value != value.strip():+ raise _CLiveCliError("c-live-cli:api-url-missing-or-invalid")+ try:+ parsed = urllib_parse.urlsplit(value)+ host = parsed.hostname+ port = parsed.port+ except (TypeError, ValueError):+ raise _CLiveCliError("c-live-cli:api-url-missing-or-invalid") from None+ if (+ parsed.scheme not in {"http", "https"}+ or host is None+ or parsed.username is not None+ or parsed.password is not None+ or parsed.path not in {"", "/"}+ or parsed.query+ or parsed.fragment+ ):+ raise _CLiveCliError("c-live-cli:api-url-missing-or-invalid")+ host = host.lower()+ if parsed.scheme == "http" and host not in _C_LIVE_LOOPBACK_HOSTS:+ raise _CLiveCliError("c-live-cli:tls-required")+ if ":" in host:+ authority = f"[{host}]"+ else:+ authority = host+ if port is not None:+ authority = f"{authority}:{port}"+ return f"{parsed.scheme}://{authority}", parsed.scheme == "https"+++def _c_live_bearer() -> str:+ """Read bearer authority from the environment or a protected prompt only."""+ token = os.getenv("ARES_ACCESS_TOKEN")+ if token is None:+ token = getpass.getpass("ARES bearer token: ")+ if (+ type(token) is not str+ or not token+ or token != token.strip()+ or len(token.encode("utf-8")) > 16_384+ or any(ord(character) < 0x21 or ord(character) == 0x7F for character in token)+ ):+ raise _CLiveCliError("c-live-cli:bearer-missing-or-invalid")+ return token+++def _c_live_idempotency_key(value: str | None) -> str:+ """Validate a supplied UUIDv4 or generate and display one exactly once."""+ if value in {None, ""}:+ generated = str(uuid.uuid4())+ console.print(f"[cyan]Idempotency-Key:[/] {generated}")+ return generated+ if type(value) is not str:+ raise _CLiveCliError("c-live-cli:idempotency-key-invalid")+ try:+ parsed = uuid.UUID(value)+ except (AttributeError, ValueError):+ raise _CLiveCliError("c-live-cli:idempotency-key-invalid") from None+ if parsed.version != 4 or str(parsed) != value:+ raise _CLiveCliError("c-live-cli:idempotency-key-invalid")+ return value+++def _c_live_http_post(path: str, body: dict[str, Any], key: str | None) -> dict[str, Any]:+ """Perform exactly one bearer HTTP POST; transport retry is caller-owned."""+ base_url, use_tls = _c_live_api_url()+ bearer = _c_live_bearer()+ idempotency_key = _c_live_idempotency_key(key)+ if type(path) is not str or not path.startswith("/") or path.startswith("//"):+ raise _CLiveCliError("c-live-cli:path-invalid")+ try:+ data = json.dumps(+ body,+ sort_keys=True,+ separators=(",", ":"),+ ensure_ascii=False,+ allow_nan=False,+ ).encode("utf-8")+ except (TypeError, ValueError):+ raise _CLiveCliError("c-live-cli:request-invalid") from None++ outgoing = urllib_request.Request( # noqa: S310 - origin is strictly constrained above+ f"{base_url}{path}",+ data=data,+ headers={+ "Accept": "application/json",+ "Authorization": f"Bearer {bearer}",+ "Content-Type": "application/json",+ "Idempotency-Key": idempotency_key,+ },+ method="POST",+ )+ handlers: list[Any] = [_CLiveRejectRedirects()]+ if use_tls:+ handlers.append(urllib_request.HTTPSHandler(context=ssl.create_default_context()))+ opener = urllib_request.build_opener(*handlers)+ try:+ with opener.open(outgoing, timeout=30) as response: # noqa: S310+ raw = response.read(_C_LIVE_MAX_RESPONSE_BYTES + 1)+ status = int(response.status)+ except urllib_error.HTTPError as exc:+ status = int(exc.code)+ raw = exc.read(_C_LIVE_MAX_RESPONSE_BYTES + 1)+ if len(raw) > _C_LIVE_MAX_RESPONSE_BYTES:+ raise _CLiveCliError(f"c-live-cli:http-{status}:response-too-large") from None+ try:+ decoded = json.loads(raw.decode("utf-8")) if raw else {}+ except (UnicodeDecodeError, json.JSONDecodeError):+ decoded = {}+ code = decoded.get("code") if isinstance(decoded, dict) else None+ safe_code = (+ code+ if type(code) is str+ and 1 <= len(code) <= 64+ and all(character.isalnum() or character in "_-" for character in code)+ else "request-rejected"+ )+ raise _CLiveCliError(f"c-live-cli:http-{status}:{safe_code}") from None+ except (urllib_error.URLError, TimeoutError, OSError):+ raise _CLiveCliError("c-live-cli:transport-unavailable") from None+ finally:+ bearer = ""++ if len(raw) > _C_LIVE_MAX_RESPONSE_BYTES:+ raise _CLiveCliError("c-live-cli:response-too-large")+ try:+ decoded = json.loads(raw.decode("utf-8")) if raw else {}+ except (UnicodeDecodeError, json.JSONDecodeError):+ raise _CLiveCliError("c-live-cli:response-invalid") from None+ return {+ "status": status,+ "body": decoded,+ "idempotency_key": idempotency_key,+ }+++def _display_c_live_http_result(result: dict[str, Any]) -> None:+ body = result.get("body")+ console.print(+ Panel(+ json.dumps(body, indent=2, sort_keys=True, default=str),+ title=f"C-LIVE HTTP {result.get('status', 'unknown')}",+ )+ )def _python_minor(version_info: object | None = None) -> tuple[int, int]:@@ -425,33 +601,38 @@ def module_info(def module_run(module_id: str = typer.Argument(..., help="Module ID"),target: str = typer.Option(..., "--target", "-t", help="Target host"),- campaign_id: str = typer.Option("", "--campaign", "-c"),+ campaign_id: str = typer.Option(..., "--campaign", "-c"),domain: str = typer.Option("", "--domain", "-d"),profile: str = typer.Option("normal", "--profile", "-p"),dry_run: bool = typer.Option(False, "--dry-run", help="Simulate without network"),param: list[str] = typer.Option([], "--param", help="k=v params (repeatable)"),+ idempotency_key: str = typer.Option(+ "", "--idempotency-key", help="Canonical lowercase UUIDv4 reused for transport retry"+ ),) -> None:- """Run a single module against a target."""- from ares.cli._store import get_store- store = get_store()-+ """Submit one module request to the authenticated ARES HTTP API."""params: dict = {}for p in param:if "=" in p:k, v = p.split("=", 1)params[k.strip()] = v.strip()- cid = campaign_id or store.active_campaign_id() or "adhoc"-with console.status(f"[cyan]Running {module_id} → {target}...[/]"):result = asyncio.run(_run_module(- module_id, target, cid, domain, profile, dry_run, params+ module_id,+ target,+ campaign_id,+ domain,+ profile,+ dry_run,+ params,+ idempotency_key,))if result:- _display_result(module_id, result)+ _display_c_live_http_result(result)else:- console.print("[red]Module returned no result[/]")+ raise typer.Exit(1)@module_app.command("install")@@ -491,13 +672,16 @@ def chain_execute(goal: str = typer.Option(..., "--goal", "-g",help="Goal: domain_admin | data_exfil | cloud_access | full_compromise"),target: str = typer.Option(..., "--target", "-t", help="Primary target"),- campaign_id: str = typer.Option("", "--campaign", "-c"),+ campaign_id: str = typer.Option(..., "--campaign", "-c"),domain: str = typer.Option("", "--domain", "-d", help="AD domain (CORP.LOCAL)"),profile: str = typer.Option("normal", "--profile", "-p"),dry_run: bool = typer.Option(False, "--dry-run"),show_plan: bool = typer.Option(False, "--plan-only", help="Show plan without executing"),+ idempotency_key: str = typer.Option(+ "", "--idempotency-key", help="Canonical lowercase UUIDv4 reused for transport retry"+ ),) -> None:- """Execute a goal-based attack chain."""+ """Submit a deterministic ordered chain to the authenticated ARES HTTP API."""console.print(Panel(f"[bold]Goal:[/] {goal}\n"f"[bold]Target:[/] {target}\n"@@ -513,7 +697,18 @@ def chain_execute(if not confirm:raise typer.Abort()- asyncio.run(_run_chain(goal, target, campaign_id, domain, profile, dry_run, show_plan))+ asyncio.run(+ _run_chain(+ goal,+ target,+ campaign_id,+ domain,+ profile,+ dry_run,+ show_plan,+ idempotency_key,+ )+ )@chain_app.command("list")@@ -813,39 +1008,29 @@ async def _run_module(profile: str,dry_run: bool,params: dict,-) -> dict | None:- """Inner async runner for module execution."""+ idempotency_key: str | None = None,+) -> dict[str, Any] | None:+ """Submit a module request without importing or constructing module code."""try:- from ares.core.campaign import Campaign, NoiseProfile, ScopeEntry- from ares.core.config import AresSettings- from ares.core.noise import NoiseController- from ares.core.context import ExecutionContext- from ares.core.di import AresContainer-- container = AresContainer.for_test()- settings = container.settings()- noise_profiles = {- "stealth": NoiseProfile.STEALTH,- "normal": NoiseProfile.NORMAL,- "aggressive": NoiseProfile.AGGRESSIVE,- }- campaign = Campaign(- id=campaign_id, name="adhoc",- scope=[ScopeEntry(cidr="0.0.0.0/0")],- noise_profile=noise_profiles.get(profile, NoiseProfile.NORMAL),- operator="operator",+ request_params = dict(params)+ request_params.update(+ {+ "target": target,+ "domain": domain,+ "noise_profile": profile,+ })- ctx = ExecutionContext.build(- campaign=campaign, target=target,- module_id=module_id, domain=domain,- params=params, dry_run=dry_run,+ return _c_live_http_post(+ f"/modules/{urllib_parse.quote(module_id, safe='')}/run",+ {+ "campaign_id": campaign_id,+ "params": request_params,+ "dry_run": bool(dry_run),+ },+ idempotency_key,)- module = container.build_module(module_id, campaign)- await module.validate(ctx)- result = await module.execute(ctx)- return result.to_dict()- except Exception as exc:- console.print(f"[red]Module error:[/] {exc}")+ except _CLiveCliError as exc:+ console.print(f"[red]{exc}[/]")return None@@ -857,39 +1042,27 @@ async def _run_chain(profile: str,dry_run: bool,show_plan: bool,+ idempotency_key: str | None = None,) -> None:"""- Execute a goal-based attack chain via GoalEngine.- Displays step-by-step progress with Rich tables.+ Submit one complete deterministic chain without local module execution."""from rich.table import Table as RTable- from rich.live import Live- import time- # ── 1. Build plan ───────────────────────────────────────────────────+ # Static goal definitions provide a complete, ordered chain without+ # invoking GoalEngine planning callbacks or loading executable modules.try:- from ares.goal.engine import GoalEngine, Goal as GoalEnum, GOAL_DEFINITIONS- from ares.state.target_state import OperatorSession- from ares.core.plugin.loader import ModuleRegistry+ from ares.goal.engine import GOAL_DEFINITIONS, Goal as GoalEnum- goal_enum = GoalEnum(goal) if goal in [g.value for g in GoalEnum] else GoalEnum.DOMAIN_ADMIN- registry = ModuleRegistry()- session = OperatorSession(campaign_id=campaign_id or "adhoc")- engine = GoalEngine(registry=registry, session=session)-- ctx = {- "dc": target,- "domain": domain,- "target": target,- "noise_profile": profile,- }- plan = engine.plan(goal_enum, context=ctx)-- except (ImportError, ValueError) as exc:- console.print(f"[red]Chain planning error:[/] {exc}")+ goal_enum = GoalEnum(goal)+ modules = tuple(GOAL_DEFINITIONS[goal_enum].preferred_chain)+ except (ImportError, KeyError, ValueError):+ console.print("[red]c-live-cli:chain-intent-invalid[/]")+ return+ if not modules or any(type(module_id) is not str or not module_id for module_id in modules):+ console.print("[red]c-live-cli:chain-intent-invalid[/]")return- # ── 2. Show plan ────────────────────────────────────────────────────plan_table = RTable(title=f"Attack Plan — [{goal}]", show_lines=True)plan_table.add_column("#", width=4, style="dim")plan_table.add_column("Module", width=24, style="cyan")@@ -897,76 +1070,44 @@ async def _run_chain(plan_table.add_column("OpSec", width=12, style="yellow")plan_table.add_column("Status", width=12)- step_statuses = ["[dim]pending[/]"] * len(plan.steps)- for i, step in enumerate(plan.steps):- cls = registry.get(step.module_id)- opsec = getattr(getattr(cls, "OPSEC_LEVEL", None), "value", "medium") if cls else "—"+ for i, module_id in enumerate(modules, start=1):plan_table.add_row(- str(step.step_num), step.module_id,- step.reason[:46], opsec, step_statuses[i],+ str(i), module_id, "deterministic configured chain", "—", "[dim]pending[/]",)console.print(plan_table)+ estimated_duration_min = min(len(modules) * 3, 60)console.print(- f"\n[dim]Estimated duration: ~{plan.estimated_duration_min} min · "- f"Steps: {len(plan.steps)} · Goal: {goal}[/]\n"+ f"\n[dim]Estimated duration: ~{estimated_duration_min} min · "+ f"Steps: {len(modules)} · Goal: {goal}[/]\n")if show_plan:return-- if dry_run:- console.print("[yellow]● Dry run — plan shown above, no execution.[/]")+ plan_body = {+ "stages": [+ {"name": f"step-{ordinal}", "modules": [module_id]}+ for ordinal, module_id in enumerate(modules)+ ]+ }+ try:+ result = _c_live_http_post(+ f"/campaigns/{urllib_parse.quote(campaign_id, safe='')}/run",+ {+ "plan": plan_body,+ "global_params": {+ "target": target,+ "domain": domain,+ "noise_profile": profile,+ },+ "dry_run": bool(dry_run),+ },+ idempotency_key,+ )+ except _CLiveCliError as exc:+ console.print(f"[red]{exc}[/]")return-- # ── 3. Execute step-by-step ─────────────────────────────────────────- console.print(f"[bold]Executing {len(plan.steps)} steps...[/]\n")-- results: list[dict] = []- t_start = time.monotonic()-- for i, step in enumerate(plan.steps):- with console.status(- f"[cyan][{i+1}/{len(plan.steps)}] Running {step.module_id} → {target}...[/]"- ):- step_result = await _run_module(- step.module_id, target, campaign_id,- domain, profile, False, step.params,- )-- status_ok = step_result and step_result.get("status") == "success"- status_icon = "[green]✓[/]" if status_ok else "[yellow]⚠[/]"- status_label = "[green]success[/]" if status_ok else "[yellow]partial[/]"-- if step_result:- finds = step_result.get("findings", 0)- creds = step_result.get("new_credentials", 0)- console.print(- f" {status_icon} [cyan]{step.module_id}[/] "- f"findings: [bold]{finds}[/] creds: [bold]{creds}[/] "- + ("[red]error: " + str(step_result.get("error", ""))[:40] + "[/]"- if step_result.get("error") else "")- )- results.append(step_result)- else:- console.print(f" [red]✗[/] [cyan]{step.module_id}[/] [red]no result[/]")-- # ── 4. Summary ──────────────────────────────────────────────────────- total_finds = sum(r.get("findings", 0) for r in results)- total_creds = sum(r.get("new_credentials", 0) for r in results)- achieved = engine.check_goal_achieved(- goal_enum # type: ignore[arg-type]- )-- console.print(Panel(- f"[bold]Goal:[/] {goal}\n"- f"[bold]Achieved:[/] {'[green]YES ✓[/]' if achieved else '[yellow]Partial[/]'}\n"- f"[bold]Steps run:[/] {len(results)}/{len(plan.steps)}\n"- f"[bold]Findings:[/] {total_finds}\n"- f"[bold]Credentials:[/] {total_creds}\n"- f"[bold]Duration:[/] {time.monotonic()-t_start:.1f}s",- title="[bold green]⛓ Chain Complete[/]" if achieved else "[bold yellow]⛓ Chain Partial[/]",- ))+ _display_c_live_http_result(result)async def _generate_report(@@ -2170,64 +2311,51 @@ def goal_run(dc: str = typer.Option("", "--dc", help="Domain Controller IP"),domain: str = typer.Option("", "--domain", help="AD domain (CORP.LOCAL)"),dry_run: bool = typer.Option(False, "--dry-run", help="Show plan without executing"),+ idempotency_key: str = typer.Option(+ "", "--idempotency-key", help="Canonical lowercase UUIDv4 reused for transport retry"+ ),) -> None:- """Plan and execute a goal-based attack chain autonomously."""- import asyncio- from ares.core.config import get_settings- from ares.db.database import AresDatabase- from ares.core.plugin.loader import PluginLoader- from ares.state.target_state import OperatorSession- from ares.goal.engine import GoalEngine, Goal-- async def _run() -> None:- s = get_settings()- async with await AresDatabase.create(s.db_path, s.encryption_key_value) as db:- campaign = await db.get_campaign(campaign_id)- if not campaign:- console.print(f"[red]Campaign {campaign_id!r} not found[/red]")- raise typer.Exit(1)-- registry = PluginLoader().load_all()- session = OperatorSession(campaign_id=campaign_id, operator="cli")- engine = GoalEngine(registry=registry, session=session)-- context: dict = {}- if dc: context["dc"] = dc- if domain: context["domain"] = domain-- plan = engine.plan(goal, context)-- # Display plan- table = Table(title=f"[bold]Attack Plan — {goal}[/bold]", show_lines=True)- table.add_column("Step", style="cyan", width=5)- table.add_column("Module", style="green")- table.add_column("Reason")- table.add_column("Params", style="dim")- for step in plan.steps:- table.add_row(- str(step.step_num),- step.module_id,- step.reason,- ", ".join(f"{k}={v}" for k, v in step.params.items() if v),- )- console.print(table)- console.print(f"\n[dim]Estimated duration: {plan.estimated_duration_min} min[/dim]")-- if dry_run:- console.print("[yellow]Dry-run mode — no modules executed.[/yellow]")- return+ """Preview locally or submit one goal request to the authenticated API."""+ del dc, domain # Strategy API owns target context for the selected campaign.+ try:+ from ares.goal.engine import GOAL_DEFINITIONS, Goal as GoalEnum++ goal_enum = GoalEnum(goal)+ modules = tuple(GOAL_DEFINITIONS[goal_enum].preferred_chain)+ except (ImportError, KeyError, ValueError):+ console.print("[red]c-live-cli:goal-intent-invalid[/]")+ raise typer.Exit(1) from None+ if not modules or any(type(module_id) is not str or not module_id for module_id in modules):+ console.print("[red]c-live-cli:goal-intent-invalid[/]")+ raise typer.Exit(1)- from ares.core.campaign import Campaign as CM- c_obj = CM(**{k: v for k, v in campaign.items() if k in CM.model_fields})- results = await engine.execute(plan, c_obj)+ table = Table(title=f"[bold]Goal Preview — {goal}[/bold]", show_lines=True)+ table.add_column("Step", style="cyan", width=5)+ table.add_column("Module", style="green")+ table.add_column("Reason")+ for ordinal, module_id in enumerate(modules, start=1):+ table.add_row(str(ordinal), module_id, "deterministic configured chain")+ console.print(table)+ console.print(f"\n[dim]Estimated duration: {min(len(modules) * 3, 60)} min[/dim]")- achieved = results.get("achieved", False)- if achieved:- console.print(f"\n[bold green]✅ Goal '{goal}' ACHIEVED[/bold green]")- else:- console.print(f"\n[yellow]⚠️ Goal '{goal}' not fully achieved — check results[/yellow]")+ if dry_run:+ console.print("[yellow]Preview only — no HTTP request or module code executed.[/yellow]")+ return- asyncio.run(_run())+ try:+ result = _c_live_http_post(+ "/strategy/engage",+ {+ "campaign_id": campaign_id,+ "goal": goal_enum.value,+ "llm_backend": "local",+ },+ idempotency_key,+ )+ except _CLiveCliError as exc:+ console.print(f"[red]{exc}[/]")+ raise typer.Exit(1) from None+ _display_c_live_http_result(result)@goal_app.command("list")diff --git a/ares/core/engine.py b/ares/core/engine.pyindex 1d65829..c1a6eed 100644--- a/ares/core/engine.py+++ b/ares/core/engine.py@@ -2,6 +2,7 @@ARES Async EngineFull async orchestration with parallel module execution."""+from __future__ import annotationsimport asyncio@@ -9,7 +10,7 @@ import reimport timefrom dataclasses import dataclass, fieldfrom enum import Enum-from typing import Any, Callable, Coroutine+from typing import TYPE_CHECKING, Any, Callable, Coroutinefrom ares.core.logger import get_logger@@ -17,24 +18,36 @@ from pydantic import BaseModelfrom ares.core.campaign import Campaign, Findingfrom ares.core.config import AresSettings, get_settingsfrom ares.core.context import ExecutionContext-from ares.core.errors import AresError+from ares.core.errors import AresError, NetworkErrorfrom ares.core.logger import audit, setup_loggerfrom ares.core.noise import NoiseControllerfrom ares.core.notifier import build_notifier_from_settingsfrom ares.core.plugin.loader import ModuleRegistry, PluginLoaderfrom ares.core.runtime_state import CampaignRuntimeState, CampaignRuntimeStateStorefrom ares.core.validator import FindingValidator, ValidationResult, build_default_validator-logger = get_logger("ares.engine")+from ares.core.execution_admission import (+ AdmittedDispatchContextV1,+ AdmittedPlanContextV1,+ consume_dispatch_context,+ consume_plan_context,+ consume_terminal_commit_context,+ mark_effect_started,+)++if TYPE_CHECKING:+ pass+logger = get_logger("ares.engine")class ModuleStatus(str, Enum):PENDING = "pending"RUNNING = "running"- DONE = "done"- FAILED = "failed"+ DONE = "done"+ FAILED = "failed"SKIPPED = "skipped"TIMEOUT = "timeout"+ CANCELLED = "cancelled"MODULE_OUTCOMES = (@@ -97,7 +110,10 @@ def normalize_module_outcome(if findings:return "confirmed_findings", f"{len(findings)} confirmed finding(s) returned."- if "krb_ap_err_skew" in str(error or "").lower() or "clock skew too great" in str(error or "").lower():+ if (+ "krb_ap_err_skew" in str(error or "").lower()+ or "clock skew too great" in str(error or "").lower()+ ):return ("operator_error","Kerberos clock skew too great; sync the operator host and domain controller time, then rerun.",@@ -128,7 +144,9 @@ def normalize_module_outcome(for marker in ("timed out", "timeout", "unreachable", "connection refused", "network")):outcome = "network_error"- default_message = "The module could not complete because the target or network was unavailable."+ default_message = (+ "The module could not complete because the target or network was unavailable."+ )elif any(marker in loweredfor marker in (@@ -176,16 +194,23 @@ def redact_module_params(module_id: str, params: dict[str, Any]) -> dict[str, Anmodel = MODULE_PARAMS.get(module_id)if model:secret_fields = {- name- for name, field in model.schema_for_api().items()- if field.get("secret")+ name for name, field in model.schema_for_api().items() if field.get("secret")}except (ImportError, AttributeError):passsecret_names = secret_fields | {- "password", "secret", "token", "api_key", "private_key",- "nt_hash", "lm_hash", "krbtgt_hash", "ssh_pass", "access_key", "secret_key",+ "password",+ "secret",+ "token",+ "api_key",+ "private_key",+ "nt_hash",+ "lm_hash",+ "krbtgt_hash",+ "ssh_pass",+ "access_key",+ "secret_key",}def _copy(name: str, value: Any) -> Any:@@ -203,15 +228,15 @@ def redact_module_params(module_id: str, params: dict[str, Any]) -> dict[str, Anclass EngineModuleResult(BaseModel):- module_id: str- status: ModuleStatus = ModuleStatus.DONE- findings: list[Finding] = []+ module_id: str+ status: ModuleStatus = ModuleStatus.DONE+ findings: list[Finding] = []validation_results: list[ValidationResult] = []- raw_output: dict[str, Any] = {}- error: str | None = None- duration_ms: float = 0.0- outcome: str = ""- outcome_message: str = ""+ raw_output: dict[str, Any] = {}+ error: str | None = None+ duration_ms: float = 0.0+ outcome: str = ""+ outcome_message: str = ""operator_next_steps: list[str] = []def model_post_init(self, __context: Any) -> None:@@ -229,7 +254,10 @@ class EngineModuleResult(BaseModel):self.operator_next_steps = ["Synchronize the operator host and domain controller clocks, then rerun the module."]- elif self.outcome == "network_error" and "before a hash was confirmed" in self.outcome_message.lower():+ elif (+ self.outcome == "network_error"+ and "before a hash was confirmed" in self.outcome_message.lower()+ ):self.operator_next_steps = ["Verify DC/KDC reachability on port 88, clock synchronization, Kerberos service health, and account/SPN validity, then rerun."]@@ -252,13 +280,14 @@ class ExecutionPlan:.add_stage("cloud", ["cloud.aws", "cloud.azure", "cloud.gcp"]))"""+stages: list[dict[str, Any]] = field(default_factory=list)def add_stage(self,- name: str,+ name: str,module_ids: list[str],- params: dict[str, dict[str, Any]] | None = None,+ params: dict[str, dict[str, Any]] | None = None,) -> "ExecutionPlan":self.stages.append({"name": name, "modules": module_ids, "params": params or {}})return self@@ -276,18 +305,17 @@ class ExecutionPlan:@dataclassclass ProgressEvent:- stage: str- module_id: str- status: ModuleStatus+ stage: str+ module_id: str+ status: ModuleStatusfinding_count: int = 0- error: str | None = None- duration_ms: float = 0.0+ error: str | None = None+ duration_ms: float = 0.0ProgressCallback = Callable[[ProgressEvent], Coroutine[Any, Any, None]]-def _estimate_stage_duration(module_count: int) -> str:"""Rough wall-clock estimate for a stage in dry-run preview.@@ -301,17 +329,19 @@ def _estimate_stage_duration(module_count: int) -> str:return f"~{secs // 60}m {secs % 60}s" if secs >= 60 else f"~{secs}s"-def _fire_and_log(coro, label: str = "background_task") -> None:"""Schedule a fire-and-forget coroutine that logs exceptions instead of silently dropping them."""import asyncio as _aio+async def _wrapper() -> None:try:await coroexcept Exception as _exc:logger.warning("background_task_error", task=label, error=str(_exc)[:120])+_aio.create_task(_wrapper())+class AresEngine:"""ARES Async Engine.@@ -323,18 +353,20 @@ class AresEngine:def __init__(self,- settings: AresSettings | None = None,- validator: FindingValidator | None = None,- db: Any | None = None,+ settings: AresSettings | None = None,+ validator: FindingValidator | None = None,+ db: Any | None = None,max_parallel: int = 5,) -> None:- self.settings = settings or get_settings()- self.validator = validator or build_default_validator()- self.db = db+ self.settings = settings or get_settings()+ self.validator = validator or build_default_validator()+ self.db = dbself.max_parallel = max_parallel- self._registry: ModuleRegistry | None = None- self._semaphore: asyncio.Semaphore | None = None- self.notifier = build_notifier_from_settings(self.settings)+ self._registry: ModuleRegistry | None = None+ self._semaphore: asyncio.Semaphore | None = None+ self._admitted_dispatch_contexts: dict[str, tuple[str, ...]] = {}+ self._admission_store_id: int | None = None+ self.notifier = build_notifier_from_settings(self.settings)from ares.telemetry.collector import get_collectorself.telemetry = get_collector()@@ -344,6 +376,50 @@ class AresEngine:)setup_logger(self.settings.ares_log_level, self.settings.ares_log_file)+ def _bind_admission_store(self, store: object) -> None:+ """Bind this engine to exactly one lifecycle store for its process lifetime."""+ store_id = id(store)+ if self._admission_store_id is None:+ self._admission_store_id = store_id+ return+ if self._admission_store_id != store_id:+ raise PermissionError("engine is already bound to a different admission store")++ def _register_admitted_dispatch_context(self, context: AdmittedDispatchContextV1) -> None:+ """Register one coordinator nonce and all of its sealed work bindings."""+ self._bind_admission_store_id(context._store_id)+ self._admitted_dispatch_contexts[context._dispatch_nonce] = (+ context.campaign_id,+ context.submission_id,+ context.logical_execution_id,+ context.attempt_id,+ context.module_id,+ str(context.attempt_revision),+ str(context._store_id),+ context._signature,+ )++ def _bind_admission_store_id(self, store_id: int) -> None:+ if self._admission_store_id is None:+ self._admission_store_id = store_id+ return+ if self._admission_store_id != store_id:+ raise PermissionError("dispatch context belongs to a different admission store")++ def _consume_registered_dispatch_context(self, context: AdmittedDispatchContextV1) -> bool:+ """Atomically consume the coordinator-scoped work registration."""+ expected = self._admitted_dispatch_contexts.pop(context._dispatch_nonce, None)+ return expected == (+ context.campaign_id,+ context.submission_id,+ context.logical_execution_id,+ context.attempt_id,+ context.module_id,+ str(context.attempt_revision),+ str(context._store_id),+ context._signature,+ )+# ── Loading ────────────────────────────────────────────────────────────def load_modules(self, external_dir: str | None = None) -> int:@@ -399,88 +475,114 @@ class AresEngine:async def run_module(self,- module_id: str,- campaign: Campaign,- params: dict[str, Any],+ module_id: str,+ campaign: Campaign,+ params: dict[str, Any],skip_validation: bool = False,- timeout_seconds: int = 120,- actor_role: str = "operator",+ timeout_seconds: int = 120,+ actor_role: str = "operator",+ dispatch_context: AdmittedDispatchContextV1 | None = None,) -> EngineModuleResult:+ try:+ admitted_context = consume_dispatch_context(+ dispatch_context,+ consumer=self,+ campaign_id=campaign.id,+ module_id=module_id,+ )+ except PermissionError as exc:+ return EngineModuleResult(+ module_id=module_id,+ status=ModuleStatus.FAILED,+ error=str(exc),+ )runtime_state = await self.ensure_campaign_runtime(campaign)if module_id not in self.registry:- return await self._finalize_module_result(campaign, module_id, EngineModuleResult(+ return EngineModuleResult(module_id=module_id,status=ModuleStatus.FAILED,error=f"Module '{module_id}' not found. Run: ares module list",- ))+ )# ── RBAC check — role must be allowed to run this module ──────────from ares.collab.manager import can_role_run_module+if not can_role_run_module(actor_role, module_id, self.registry):- audit("module_rbac_denied", actor=campaign.operator,- detail=f"role={actor_role} module={module_id}")- return await self._finalize_module_result(campaign, module_id, EngineModuleResult(+ audit(+ "module_rbac_denied",+ actor=campaign.operator,+ detail=f"role={actor_role} module={module_id}",+ )+ return EngineModuleResult(module_id=module_id,status=ModuleStatus.FAILED,- error=(f"Role '{actor_role}' is not permitted to run "- f"'{module_id}'. Check ROLE_PERMISSIONS in collab/manager.py."),- ))+ error=(+ f"Role '{actor_role}' is not permitted to run "+ f"'{module_id}'. Check ROLE_PERMISSIONS in collab/manager.py."+ ),+ )# ── Scope pre-check — enforce before any module code runs ────────# Cloud/reporting modules use API credentials, not host IPs — skip scope check_NO_SCOPE_CATEGORIES = {"cloud", "reporting", "recon"}_target = params.get("target", "") or params.get("dc", "") or params.get("host", "")- _module_category = (self.registry.get(module_id) or type("", (), {"MODULE_CATEGORY": ""})).MODULE_CATEGORY+ _module_category = (+ self.registry.get(module_id) or type("", (), {"MODULE_CATEGORY": ""})+ ).MODULE_CATEGORYif _target and _module_category not in _NO_SCOPE_CATEGORIES:if not campaign.is_in_scope(_target):from ares.core.errors import ScopeError- audit("module_scope_violation", actor=campaign.operator,- detail=f"module={module_id} target={_target!r} not in scope")- return await self._finalize_module_result(campaign, module_id, EngineModuleResult(++ audit(+ "module_scope_violation",+ actor=campaign.operator,+ detail=f"module={module_id} target={_target!r} not in scope",+ )+ return EngineModuleResult(module_id=module_id,status=ModuleStatus.FAILED,error=f"Target {_target!r} is not in campaign scope {[s.cidr for s in campaign.scope]}. "- "Add the target CIDR to scope or use a different target.",- ))+ "Add the target CIDR to scope or use a different target.",+ )- cls = self.registry.get(module_id)- noise = NoiseController(campaign)+ cls = self.registry.get(module_id)+ noise = NoiseController(campaign)instance = cls(settings=self.settings, campaign=campaign, noise=noise) # type: ignore[misc]# Respect per-module timeout if declared (MODULE_TIMEOUT_SECONDS)module_timeout = getattr(instance.__class__, "MODULE_TIMEOUT_SECONDS", None)- effective_timeout = (- module_timeout if module_timeout is not None else timeout_seconds- )+ effective_timeout = module_timeout if module_timeout is not None else timeout_secondsif effective_timeout != timeout_seconds:- logger.debug("engine_using_module_timeout",- module_id=module_id,- timeout=effective_timeout)+ logger.debug(+ "engine_using_module_timeout", module_id=module_id, timeout=effective_timeout+ )- audit("module_run_start", actor=campaign.operator,- detail=f"module={module_id} campaign={campaign.id[:8]}")+ audit(+ "module_run_start",+ actor=campaign.operator,+ detail=f"module={module_id} campaign={campaign.id[:8]}",+ )t0 = time.monotonic()try:# Build ExecutionContext — new v0.9.0+ interfacectx = ExecutionContext.build(- campaign = campaign,- target = params.get("dc") or params.get("host") or params.get("target", ""),- module_id = module_id,- domain = params.get("domain", ""),- params = params,- operator = campaign.operator,+ campaign=campaign,+ target=params.get("dc") or params.get("host") or params.get("target", ""),+ module_id=module_id,+ domain=params.get("domain", ""),+ params=params,+ operator=campaign.operator,credentials=runtime_state.safe_credentials(),- session = runtime_state.session,- vault = runtime_state.vault,+ session=runtime_state.session,+ vault=runtime_state.vault,artifact_store=runtime_state.artifact_store,runtime_state=runtime_state,- settings = self.settings,- noise = noise,- telemetry = runtime_state.telemetry,+ settings=self.settings,+ noise=noise,+ telemetry=runtime_state.telemetry,)-# ── validate() before execute() ───────────────────────────# Always call validate() first — lets modules fail fast with# informative errors before any network activity happens.@@ -493,47 +595,51 @@ class AresEngine:)except asyncio.TimeoutError:duration_ms = round((time.monotonic() - t0) * 1000, 2)- audit("module_validation_failed", actor=campaign.operator,- detail=f"module={module_id} reason=timeout")- return await self._finalize_module_result(campaign, module_id, EngineModuleResult(- module_id = module_id,- status = ModuleStatus.FAILED,- error = f"Module '{module_id}' validate() timed out (>10s)",- duration_ms = duration_ms,- ))+ audit(+ "module_validation_failed",+ actor=campaign.operator,+ detail=f"module={module_id} reason=timeout",+ )+ return EngineModuleResult(+ module_id=module_id,+ status=ModuleStatus.FAILED,+ error=f"Module '{module_id}' validate() timed out (>10s)",+ duration_ms=duration_ms,+ )except Exception as val_exc:duration_ms = round((time.monotonic() - t0) * 1000, 2)err_msg = str(val_exc)- logger.warning("engine_module_validation_failed",- module_id=module_id, error=err_msg[:200])- audit("module_validation_failed", actor=campaign.operator,- detail=f"module={module_id} error={err_msg[:100]}")- return await self._finalize_module_result(campaign, module_id, EngineModuleResult(- module_id = module_id,- status = ModuleStatus.FAILED,- error = f"Validation failed: {err_msg[:300]}",- duration_ms = duration_ms,- ))+ logger.warning(+ "engine_module_validation_failed", module_id=module_id, error=err_msg[:200]+ )+ audit(+ "module_validation_failed",+ actor=campaign.operator,+ detail=f"module={module_id} error={err_msg[:100]}",+ )+ return EngineModuleResult(+ module_id=module_id,+ status=ModuleStatus.FAILED,+ error=f"Validation failed: {err_msg[:300]}",+ duration_ms=duration_ms,+ )# ── end validate ───────────────────────────────────────────# Call execute(ctx) — preferred interface.# Falls back to run(**ctx.params) via BaseModule.execute() default# for modules that haven't migrated yet.+ mark_effect_started(admitted_context)execute_coro = instance.execute(ctx)- module_result = await asyncio.wait_for(- execute_coro, timeout=effective_timeout- )+ module_result = await asyncio.wait_for(execute_coro, timeout=effective_timeout)findings = module_result.findings- raw = module_result.raw+ raw = module_result.rawexcept asyncio.TimeoutError:logger.error("engine_timed_out_s",module_id=module_id,timeout_seconds=effective_timeout,)- _last_exc: Exception = asyncio.TimeoutError(- f"Timed out after {effective_timeout}s"- )+ _last_exc: Exception = asyncio.TimeoutError(f"Timed out after {effective_timeout}s")_action = AresError.RETRYexcept AresError as exc:logger.warning("engine_areserror", module_id=module_id, action=exc.action, exc=exc)@@ -547,75 +653,24 @@ class AresEngine:_last_exc = None_action = None- # ── Retry logic ───────────────────────────────────────────────────- # Track whether the *original* failure was a timeout — if retries also- # fail (possibly with a different exception), we still report TIMEOUT- # so callers can distinguish "module timed out repeatedly" from "module crashed".+ # Automatic engine retries are forbidden. A retry is a fresh durable+ # child attempt and is owned exclusively by the admission coordinator._was_timeout = isinstance(_last_exc, asyncio.TimeoutError)- if _last_exc is not None and _action == AresError.RETRY:- MAX_RETRIES = 2- for attempt in range(1, MAX_RETRIES + 1):- wait = 2 ** attempt # 2s, 4s- logger.info("engine_retry_in_s", module_id=module_id, attempt=attempt, MAX_RETRIES=MAX_RETRIES, wait=wait)- await asyncio.sleep(wait)- try:- # Re-instantiate module fresh — previous coroutine is exhausted/timed-out- module2 = cls(- settings=self.settings,- campaign=campaign,- noise=noise,- )- # Rebuild ctx — same as initial attempt, use execute() not run()- ctx2 = ExecutionContext.build(- campaign = campaign,- target = params.get("dc") or params.get("host") or params.get("target", ""),- module_id = module_id,- domain = params.get("domain", ""),- params = params,- operator = campaign.operator,- credentials=runtime_state.safe_credentials(),- session = runtime_state.session,- vault = runtime_state.vault,- artifact_store=runtime_state.artifact_store,- runtime_state=runtime_state,- settings = self.settings,- noise = noise,- telemetry = runtime_state.telemetry,- )- module_result2 = await asyncio.wait_for(- module2.execute(ctx2), timeout=effective_timeout- )- findings = module_result2.findings- raw = module_result2.raw- _last_exc = None- break- except asyncio.TimeoutError as te:- _last_exc = te- _was_timeout = True- logger.warning(- "engine_retry_timed_out",- module_id=module_id,- attempt=attempt,- timeout_seconds=effective_timeout,- )- except AresError as re:- _last_exc = re- _action = re.action- logger.warning("engine_retry_failed", module_id=module_id, attempt=attempt, re=re)- if _action != AresError.RETRY:- break- except Exception as re:- _last_exc = re- logger.warning("engine_retry_failed", module_id=module_id, attempt=attempt, re=re)if _last_exc is not None:- status = (ModuleStatus.TIMEOUT if _was_timeout- else ModuleStatus.FAILED)- return await self._finalize_module_result(campaign, module_id, EngineModuleResult(- module_id=module_id, status=status,+ status = ModuleStatus.TIMEOUT if _was_timeout else ModuleStatus.FAILED+ typed_outcome = "network_error" if isinstance(_last_exc, NetworkError) else ""+ typed_message = (+ redact_error_message(str(_last_exc)[:300]) or "" if typed_outcome else ""+ )+ return EngineModuleResult(+ module_id=module_id,+ status=status,error=str(_last_exc)[:300],duration_ms=round((time.monotonic() - t0) * 1000, 2),- ))+ outcome=typed_outcome,+ outcome_message=typed_message,+ )duration_ms = round((time.monotonic() - t0) * 1000, 2)@@ -623,11 +678,13 @@ class AresEngine:validation_results: list[ValidationResult] = []if not skip_validation:# Run all validations in parallel too- validation_results = list(await asyncio.gather(- *[self.validator.validate(f, raw) for f in findings]- ))+ validation_results = list(+ await asyncio.gather(*[self.validator.validate(f, raw) for f in findings])+ )- # Persist confirmed findings+ # Prepare confirmed findings without persistence, publication, campaign+ # mutation, or artifact normalization. Those effects are released only+ # after the coordinator durably commits the terminal attempt.confirmed: list[Finding] = []from ares.core.cvss import enrich_finding_with_cvssfrom ares.core.tracing import get_current_trace_id@@ -640,101 +697,62 @@ class AresEngine:enrich_finding_with_cvss(f)if trace_id:f.trace_id = trace_id- campaign.add_finding(f)confirmed.append(f)- if self.db:- try:- await self.db.save_finding(campaign.id, f, module_id)- except Exception as e:- logger.warning("engine_db_save_failed_for_finding", e=e)- # Webhook alert for qualifying findings- if self.notifier and self.notifier.should_notify(f.severity):- asyncio.create_task(- self.notifier.notify_finding(f, campaign)- )- # Dashboard live feed — non-blocking broadcast- try:- from ares.api.dashboard.app import broadcast_finding as _dash_broadcast- _fire_and_log(_dash_broadcast({- "event": "finding_discovered",- "campaign_id": campaign.id,- "title": f.title,- "severity": f.severity.value,- "confidence": f.confidence,- "mitre_technique": f.mitre_technique,- "host": f.host,- "module_id": f.module_id,- "timestamp": f.discovered_at.isoformat()- if hasattr(f, "discovered_at") and f.discovered_at- else None,- }))- except Exception:- pass # dashboard not loaded — silently skipfp_count = len(findings) - len(confirmed)- audit("module_run_complete", actor=campaign.operator,- detail=(f"module={module_id} ms={duration_ms} "- f"confirmed={len(confirmed)} fp={fp_count}"))-- # ── Persist vault credentials to DB ───────────────────────────────- if self.db and runtime_state.vault is not None:- try:- await self._persist_vault_credentials(campaign)- except Exception as _ve:- logger.warning("engine_vault_persist_failed",- module_id=module_id, error=str(_ve)[:100])-- # ── Auto-normalize raw output into ArtifactStore ──────────────────- artifact_count = 0- try:- from ares.normalize.artifacts import ArtifactNormalizer- cls_ref = self.registry.get(module_id)- outputs = getattr(cls_ref, "OUTPUTS", []) if cls_ref else []- if outputs and raw:- normalizer = ArtifactNormalizer()- artifact_count = normalizer.normalize(- module_id=module_id,- outputs=outputs,- raw=raw,- store=runtime_state.artifact_store,- )- if artifact_count > 0:- logger.debug(- "artifacts_normalized",- module=module_id,- count=artifact_count,- )- except Exception as _norm_exc:- logger.debug("artifact_normalization_skipped", error=str(_norm_exc)[:80])-- if self.db:- await self._persist_runtime_hosts(campaign, runtime_state)- await self._persist_runtime_graph(campaign, runtime_state)+ audit(+ "module_run_complete",+ actor=campaign.operator,+ detail=(+ f"module={module_id} ms={duration_ms} confirmed={len(confirmed)} fp={fp_count}"+ ),+ )- return await self._finalize_module_result(campaign, module_id, EngineModuleResult(- module_id=module_id, status=ModuleStatus.DONE,+ return EngineModuleResult(+ module_id=module_id,+ status=ModuleStatus.DONE,findings=confirmed,validation_results=validation_results,- raw_output=raw, duration_ms=duration_ms,- ))+ raw_output=raw,+ duration_ms=duration_ms,+ )# ── Parallel plan ──────────────────────────────────────────────────────async def run_plan(self,- plan: ExecutionPlan,- campaign: Campaign,- global_params: dict[str, Any] | None = None,- skip_validation: bool = False,- timeout_per_module: int = 120,- on_progress: ProgressCallback | None = None,- actor_role: str = "operator",+ plan: ExecutionPlan,+ campaign: Campaign,+ global_params: dict[str, Any] | None = None,+ skip_validation: bool = False,+ timeout_per_module: int = 120,+ on_progress: ProgressCallback | None = None,+ actor_role: str = "operator",+ dispatch_context: AdmittedPlanContextV1 | None = None,) -> dict[str, EngineModuleResult]:"""Run all stages.Within each stage: modules execute CONCURRENTLY (bounded by max_parallel semaphore).Between stages: sequential (later stages can depend on earlier recon)."""+ module_ids_in_order = tuple(plan.all_module_ids())+ try:+ admitted_children = consume_plan_context(+ dispatch_context,+ consumer=self,+ campaign_id=campaign.id,+ module_ids=module_ids_in_order,+ )+ except PermissionError as exc:+ return {+ module_id: EngineModuleResult(+ module_id=module_id,+ status=ModuleStatus.FAILED,+ error=str(exc),+ )+ for module_id in module_ids_in_order+ }+ child_iterator = iter(admitted_children)self._semaphore = asyncio.Semaphore(self.max_parallel)results: dict[str, EngineModuleResult] = {}gp = global_params or {}@@ -743,9 +761,9 @@ class AresEngine:logger.info("engine_plan_start_stages_modules", total_mods=total_mods)for stage in plan.stages:- name = stage["name"]+ name = stage["name"]module_ids = stage["modules"]- sp = stage.get("params", {})+ sp = stage.get("params", {})logger.info("engine_stage_modules_parallel", name=name)@@ -759,6 +777,7 @@ class AresEngine:stage_name=name,on_progress=on_progress,actor_role=actor_role,+ dispatch_context=next(child_iterator),)for mid in module_ids]@@ -767,11 +786,16 @@ class AresEngine:stage_results: list[EngineModuleResult] = []for mid, res in zip(module_ids, raw_results):if isinstance(res, Exception):- logger.error("engine_raised_unhandled_exception", mid=mid, res=res, exc_info=res)- stage_results.append(EngineModuleResult(- module_id=mid, status=ModuleStatus.FAILED,- error=f"Unhandled: {res!s}"[:200],- ))+ logger.error(+ "engine_raised_unhandled_exception", mid=mid, res=res, exc_info=res+ )+ stage_results.append(+ EngineModuleResult(+ module_id=mid,+ status=ModuleStatus.FAILED,+ error=f"Unhandled: {res!s}"[:200],+ )+ )else:stage_results.append(res)for mid, res in zip(module_ids, stage_results):@@ -784,6 +808,7 @@ class AresEngine:if "network.pivot" in results and results["network.pivot"].status == ModuleStatus.DONE:try:from ares.modules.network.pivot import _PIVOT_MANAGERS+campaign_id = campaign.idif campaign_id in _PIVOT_MANAGERS:pm = _PIVOT_MANAGERS[campaign_id]@@ -802,19 +827,22 @@ class AresEngine:_PIVOT_MANAGERS.pop(campaign_id, None)logger.info("engine_pivot_teardown", campaign_id=campaign_id[:8])except Exception as teardown_exc:- logger.warning("engine_pivot_teardown_failed",- error=str(teardown_exc)[:80])+ logger.warning("engine_pivot_teardown_failed", error=str(teardown_exc)[:80])# ALWAYS clean up credential artifacts — regardless of which modules ran.# This runs unconditionally to prevent accumulation in 24/7 operation.try:from ares.core.security import cleanup_credential_artifacts+cleaned = cleanup_credential_artifacts(campaign.id)# Also clean global-scope artifacts (created outside campaign context)cleaned += cleanup_credential_artifacts()if cleaned:- logger.info("engine_credential_artifacts_cleaned",- count=cleaned, campaign_id=campaign.id[:8])+ logger.info(+ "engine_credential_artifacts_cleaned",+ count=cleaned,+ campaign_id=campaign.id[:8],+ )except Exception:pass@@ -843,15 +871,17 @@ class AresEngine:for req in getattr(cls, "REQUIRES", []):if req not in available_outputs:suggested = provider_map.get(req, "unknown")- warnings_out.append({- "module_id": mid,- "missing_requirement": req,- "suggested_provider": suggested,- "message": (- f"'{mid}' requires '{req}' — "- f"add '{suggested}' to an earlier stage first"- ),- })+ warnings_out.append(+ {+ "module_id": mid,+ "missing_requirement": req,+ "suggested_provider": suggested,+ "message": (+ f"'{mid}' requires '{req}' — "+ f"add '{suggested}' to an earlier stage first"+ ),+ }+ )for mid in stage.get("modules", []):cls = self.registry.get(mid)if cls:@@ -861,7 +891,7 @@ class AresEngine:def dry_run_plan(self,- plan: "ExecutionPlan",+ plan: "ExecutionPlan",global_params: dict[str, Any] | None = None,) -> dict[str, Any]:"""@@ -878,102 +908,120 @@ class AresEngine:POST /campaigns/{id}/run {"dry_run": true}ares module run-plan --plan plan.json --dry-run"""- gp = global_params or {}+ gp = global_params or {}dep_warnings = self.check_plan_dependencies(plan)- stages_out: list[dict[str, Any]] = []+ stages_out: list[dict[str, Any]] = []param_errors: list[dict[str, str]] = []for stage in plan.stages:- name = stage.get("name", "unnamed")- mids = stage.get("modules", [])- sp = stage.get("params", {})+ name = stage.get("name", "unnamed")+ mids = stage.get("modules", [])+ sp = stage.get("params", {})stage_info: dict[str, Any] = {- "stage": name,- "modules": [],+ "stage": name,+ "modules": [],"estimated_duration": _estimate_stage_duration(len(mids)),}for mid in mids:cls = self.registry.get(mid)if not cls:- param_errors.append({"module_id": mid, "field": "(module)",- "error": f"Module '{mid}' not found in registry"})- stage_info["modules"].append({- "module_id": mid,- "status": "not_found",- "dry_run_status": "dry_run_unsupported",- "validated_params_summary": redact_module_params(mid, {**gp, **sp.get(mid, {})}),- "missing_params": [],- "missing_dependencies": [],- "would_execute": False,- "warnings": ["The module is not present in the loaded registry."],- "operator_next_steps": ["Refresh the module catalog or check module installation."],- })+ param_errors.append(+ {+ "module_id": mid,+ "field": "(module)",+ "error": f"Module '{mid}' not found in registry",+ }+ )+ stage_info["modules"].append(+ {+ "module_id": mid,+ "status": "not_found",+ "dry_run_status": "dry_run_unsupported",+ "validated_params_summary": redact_module_params(+ mid, {**gp, **sp.get(mid, {})}+ ),+ "missing_params": [],+ "missing_dependencies": [],+ "would_execute": False,+ "warnings": ["The module is not present in the loaded registry."],+ "operator_next_steps": [+ "Refresh the module catalog or check module installation."+ ],+ }+ )continuemerged = {**gp, **sp.get(mid, {})}mod_errors: list[str] = []try:from ares.modules.params import MODULE_PARAMS+model_cls = MODULE_PARAMS.get(mid)if model_cls:for fname, field_info in model_cls.model_fields.items():if field_info.is_required() and fname not in merged:mod_errors.append(fname)- param_errors.append({- "module_id": mid,- "field": fname,- "error": f"Required param '{fname}' not provided",- })+ param_errors.append(+ {+ "module_id": mid,+ "field": fname,+ "error": f"Required param '{fname}' not provided",+ }+ )except ImportError:passopsec = getattr(cls, "OPSEC_LEVEL", "?")dry_run_supported = bool(getattr(cls, "DRY_RUN_SUPPORTED", True))module_dry_status = (- "dry_run_blocked" if mod_errors- else "dry_run_ok" if dry_run_supported+ "dry_run_blocked"+ if mod_errors+ else "dry_run_ok"+ if dry_run_supportedelse "dry_run_unsupported")- stage_info["modules"].append({- "module_id": mid,- "opsec_level": opsec.value if hasattr(opsec, "value") else str(opsec),- "requires": getattr(cls, "REQUIRES", []),- "outputs": getattr(cls, "OUTPUTS", []),- "mitre": getattr(cls, "MITRE_TECHNIQUES", []),- "missing_params": mod_errors,- "status": "error" if mod_errors else "ready",- "dry_run_status": module_dry_status,- "validated_params_summary": redact_module_params(mid, merged),- "missing_dependencies": [],- "would_execute": module_dry_status == "dry_run_ok",- "warnings": [- "Dry-run validates the plan only; no module code contacts a target."- ],- "operator_next_steps": [- "Review parameters and campaign scope before live execution."- ],- })+ stage_info["modules"].append(+ {+ "module_id": mid,+ "opsec_level": opsec.value if hasattr(opsec, "value") else str(opsec),+ "requires": getattr(cls, "REQUIRES", []),+ "outputs": getattr(cls, "OUTPUTS", []),+ "mitre": getattr(cls, "MITRE_TECHNIQUES", []),+ "missing_params": mod_errors,+ "status": "error" if mod_errors else "ready",+ "dry_run_status": module_dry_status,+ "validated_params_summary": redact_module_params(mid, merged),+ "missing_dependencies": [],+ "would_execute": module_dry_status == "dry_run_ok",+ "warnings": [+ "Dry-run validates the plan only; no module code contacts a target."+ ],+ "operator_next_steps": [+ "Review parameters and campaign scope before live execution."+ ],+ }+ )stages_out.append(stage_info)return {"dry_run": True,"status": "dry_run_blocked" if param_errors else "dry_run_ok",- "plan": stages_out,+ "plan": stages_out,"param_validation": {- "ok": len(param_errors) == 0,+ "ok": len(param_errors) == 0,"errors": param_errors,},"dependency_check": {- "ok": len(dep_warnings) == 0,+ "ok": len(dep_warnings) == 0,"warnings": dep_warnings,},"summary": {- "total_stages": len(plan.stages),+ "total_stages": len(plan.stages),"total_modules": len(plan.all_module_ids()),- "ready_to_run": len(param_errors) == 0,+ "ready_to_run": len(param_errors) == 0,},}@@ -1011,7 +1059,9 @@ class AresEngine:"missing_dependencies": [],"would_execute": False,"warnings": ["This module does not advertise a safe dry-run path."],- "operator_next_steps": ["Review the module documentation before an authorized live run."],+ "operator_next_steps": [+ "Review the module documentation before an authorized live run."+ ],}missing = list(missing_params or [])@@ -1046,6 +1096,89 @@ class AresEngine:],}+ async def _finalize_committed_module_result(+ self,+ campaign: Campaign,+ module_id: str,+ result: EngineModuleResult,+ dispatch_context: AdmittedDispatchContextV1,+ ) -> EngineModuleResult:+ """Release persistence and broadcasts only after durable terminal commit."""+ consume_terminal_commit_context(+ dispatch_context,+ consumer=self,+ campaign_id=campaign.id,+ module_id=module_id,+ )+ runtime_state = await self.ensure_campaign_runtime(campaign)++ for finding in result.findings:+ campaign.add_finding(finding)+ if self.db:+ try:+ await self.db.save_finding(campaign.id, finding, module_id)+ except Exception as exc:+ logger.warning("engine_db_save_failed_for_finding", error=str(exc)[:120])+ if self.notifier and self.notifier.should_notify(finding.severity):+ asyncio.create_task(self.notifier.notify_finding(finding, campaign))+ try:+ from ares.api.dashboard.app import broadcast_finding as dashboard_broadcast++ _fire_and_log(+ dashboard_broadcast(+ {+ "event": "finding_discovered",+ "campaign_id": campaign.id,+ "title": finding.title,+ "severity": finding.severity.value,+ "confidence": finding.confidence,+ "mitre_technique": finding.mitre_technique,+ "host": finding.host,+ "module_id": finding.module_id,+ "timestamp": (+ finding.discovered_at.isoformat()+ if getattr(finding, "discovered_at", None)+ else None+ ),+ }+ ),+ "committed_finding_broadcast",+ )+ except Exception:+ pass++ if self.db and runtime_state.vault is not None:+ try:+ await self._persist_vault_credentials(campaign)+ except Exception as exc:+ logger.warning(+ "engine_vault_persist_failed",+ module_id=module_id,+ error=str(exc)[:100],+ )++ try:+ from ares.normalize.artifacts import ArtifactNormalizer++ module_class = self.registry.get(module_id)+ outputs = getattr(module_class, "OUTPUTS", []) if module_class else []+ if outputs and result.raw_output:+ normalized = ArtifactNormalizer().normalize(+ module_id=module_id,+ outputs=outputs,+ raw=result.raw_output,+ store=runtime_state.artifact_store,+ )+ if normalized:+ logger.debug("artifacts_normalized", module=module_id, count=normalized)+ except Exception as exc:+ logger.debug("artifact_normalization_skipped", error=str(exc)[:80])++ if self.db:+ await self._persist_runtime_hosts(campaign, runtime_state)+ await self._persist_runtime_graph(campaign, runtime_state)+ return await self._finalize_module_result(campaign, module_id, result)+async def _finalize_module_result(self,campaign: Campaign,@@ -1100,7 +1233,9 @@ class AresEngine:if result.findings:self.telemetry.record_finding(len(result.findings))except Exception as exc:- logger.debug("engine_telemetry_record_failed", module_id=module_id, error=str(exc)[:120])+ logger.debug(+ "engine_telemetry_record_failed", module_id=module_id, error=str(exc)[:120]+ )return resultasync def _persist_runtime_hosts(@@ -1131,18 +1266,20 @@ class AresEngine:if not host.ip_address:continuetry:- await self.db.upsert_host(Host(- campaign_id=campaign.id,- ip_address=host.ip_address,- hostname=host.hostname or None,- fqdn=host.fqdn or None,- os=host.os or None,- os_version=host.os_version or None,- domain=host.domain or None,- is_dc=host.is_dc,- open_ports=list(host.open_ports),- tags=list(host.tags),- ))+ await self.db.upsert_host(+ Host(+ campaign_id=campaign.id,+ ip_address=host.ip_address,+ hostname=host.hostname or None,+ fqdn=host.fqdn or None,+ os=host.os or None,+ os_version=host.os_version or None,+ domain=host.domain or None,+ is_dc=host.is_dc,+ open_ports=list(host.open_ports),+ tags=list(host.tags),+ )+ )except Exception as exc:logger.debug("engine_host_persist_failed",@@ -1190,6 +1327,7 @@ class AresEngine:return 0from ares.db.database import DBCredential+saved = 0for cred_id, cred in vault._store.items():try:@@ -1201,40 +1339,39 @@ class AresEngine:else str(cred.secret_enc))db_cred = DBCredential(- id = cred.id,- campaign_id = campaign.id,- host_id = getattr(cred, "source_host", None) or None,- username = cred.username,- cred_type = (+ id=cred.id,+ campaign_id=campaign.id,+ host_id=getattr(cred, "source_host", None) or None,+ username=cred.username,+ cred_type=(cred.cred_type.valueif hasattr(cred.cred_type, "value")else str(cred.cred_type)),- secret = secret_enc,- domain = getattr(cred, "domain", ""),- source_module = getattr(cred, "source_module", ""),- notes = getattr(cred, "notes", ""),+ secret=secret_enc,+ domain=getattr(cred, "domain", ""),+ source_module=getattr(cred, "source_module", ""),+ notes=getattr(cred, "notes", ""),)await self.db.save_credential_preencrypted(db_cred)saved += 1except Exception as exc:- logger.debug("vault_persist_cred_failed",- cred_id=cred_id[:8], error=str(exc)[:80])+ logger.debug("vault_persist_cred_failed", cred_id=cred_id[:8], error=str(exc)[:80])if saved:- logger.debug("vault_persisted",- campaign=campaign.id[:8], count=saved)+ logger.debug("vault_persisted", campaign=campaign.id[:8], count=saved)return savedasync def _guarded_run(self,- module_id: str,- campaign: Campaign,- params: dict[str, Any],+ module_id: str,+ campaign: Campaign,+ params: dict[str, Any],skip_validation: bool,timeout_seconds: int,- stage_name: str,- on_progress: ProgressCallback | None,- actor_role: str,+ stage_name: str,+ on_progress: ProgressCallback | None,+ actor_role: str,+ dispatch_context: AdmittedDispatchContextV1,) -> EngineModuleResult:if self._semaphore is None:raise RuntimeError(@@ -1242,10 +1379,13 @@ class AresEngine:)async with self._semaphore:if on_progress:- await on_progress(ProgressEvent(- stage=stage_name, module_id=module_id,- status=ModuleStatus.RUNNING,- ))+ await on_progress(+ ProgressEvent(+ stage=stage_name,+ module_id=module_id,+ status=ModuleStatus.RUNNING,+ )+ )result = await self.run_module(module_id,campaign,@@ -1253,17 +1393,22 @@ class AresEngine:skip_validation,timeout_seconds,actor_role=actor_role,+ dispatch_context=dispatch_context,)if on_progress:- await on_progress(ProgressEvent(- stage=stage_name, module_id=module_id,- status=result.status,- finding_count=len(result.confirmed_findings),- error=result.error,- duration_ms=result.duration_ms,- ))+ await on_progress(+ ProgressEvent(+ stage=stage_name,+ module_id=module_id,+ status=result.status,+ finding_count=len(result.confirmed_findings),+ error=result.error,+ duration_ms=result.duration_ms,+ )+ )return result+# Backward-compat aliasModuleResult = EngineModuleResult # noqa@@ -1274,99 +1419,189 @@ CAMPAIGN_TEMPLATES: dict[str, dict] = {"internal_pentest": {"description": "Standard internal network penetration test","stages": [- {"name": "recon", "modules": [- "network.port_scan", "network.service_detect",- "recon.fingerprint", "network.dns_enum",- ]},- {"name": "ad_enum", "modules": [- "ad.enum_users", "ad.enum_spn", "ad.enum_computers",- "ad.enum_acl",- ]},- {"name": "credential_attack", "modules": [- "ad.kerberoast", "ad.asreproast",- ]},- {"name": "credential_crack", "modules": [- "credential.crack",- ]},- {"name": "lateral_movement", "modules": [- "credential.reuse", "lateral.smb_relay",- "lateral.ntlm_relay",- ]},+ {+ "name": "recon",+ "modules": [+ "network.port_scan",+ "network.service_detect",+ "recon.fingerprint",+ "network.dns_enum",+ ],+ },+ {+ "name": "ad_enum",+ "modules": [+ "ad.enum_users",+ "ad.enum_spn",+ "ad.enum_computers",+ "ad.enum_acl",+ ],+ },+ {+ "name": "credential_attack",+ "modules": [+ "ad.kerberoast",+ "ad.asreproast",+ ],+ },+ {+ "name": "credential_crack",+ "modules": [+ "credential.crack",+ ],+ },+ {+ "name": "lateral_movement",+ "modules": [+ "credential.reuse",+ "lateral.smb_relay",+ "lateral.ntlm_relay",+ ],+ },],},"ad_full_compromise": {"description": "Full Active Directory compromise — recon to domain admin","stages": [- {"name": "recon", "modules": [- "recon.fingerprint", "ad.enum_users", "ad.enum_spn",- "ad.enum_computers", "ad.enum_acl",- ]},- {"name": "credential_harvest", "modules": [- "ad.kerberoast", "ad.asreproast", "ad.laps_enum",- ]},- {"name": "crack_and_reuse", "modules": [- "credential.crack", "credential.reuse",- "credential.pass_the_hash",- ]},- {"name": "escalation", "modules": [- "ad.delegation_abuse", "ad.adcs", "ad.sccm",- ]},- {"name": "domain_admin", "modules": [- "ad.dcsync", "credential.golden_ticket",- ]},+ {+ "name": "recon",+ "modules": [+ "recon.fingerprint",+ "ad.enum_users",+ "ad.enum_spn",+ "ad.enum_computers",+ "ad.enum_acl",+ ],+ },+ {+ "name": "credential_harvest",+ "modules": [+ "ad.kerberoast",+ "ad.asreproast",+ "ad.laps_enum",+ ],+ },+ {+ "name": "crack_and_reuse",+ "modules": [+ "credential.crack",+ "credential.reuse",+ "credential.pass_the_hash",+ ],+ },+ {+ "name": "escalation",+ "modules": [+ "ad.delegation_abuse",+ "ad.adcs",+ "ad.sccm",+ ],+ },+ {+ "name": "domain_admin",+ "modules": [+ "ad.dcsync",+ "credential.golden_ticket",+ ],+ },],},"cloud_assessment": {"description": "Multi-cloud security assessment — AWS, Azure, GCP","stages": [- {"name": "cloud_enum", "modules": [- "cloud.aws", "cloud.azure", "cloud.gcp", "cloud.azure_ad",- ]},- {"name": "cloud_privesc", "modules": [- "cloud.aws_privesc",- ]},- {"name": "federation", "modules": [- "cloud.identity_federation_abuse",- ]},+ {+ "name": "cloud_enum",+ "modules": [+ "cloud.aws",+ "cloud.azure",+ "cloud.gcp",+ "cloud.azure_ad",+ ],+ },+ {+ "name": "cloud_privesc",+ "modules": [+ "cloud.aws_privesc",+ ],+ },+ {+ "name": "federation",+ "modules": [+ "cloud.identity_federation_abuse",+ ],+ },],},"assumed_breach": {"description": "Assumed breach — start with valid creds, test lateral + escalation","stages": [- {"name": "situational_awareness", "modules": [- "recon.fingerprint", "ad.enum_users", "ad.enum_computers",- "ad.enum_acl",- ]},- {"name": "escalation", "modules": [- "ad.kerberoast", "ad.adcs", "ad.delegation_abuse",- "ad.sccm",- ]},- {"name": "lateral", "modules": [- "lateral.smb_relay", "lateral.ntlm_relay",- "credential.reuse",- "lateral.wmiexec", "lateral.dcom",- ]},- {"name": "post_exploit", "modules": [- "windows.lsass_dump", "windows.dpapi",- "exfil.smb_shares", "exfil.secrets_scan",- ]},+ {+ "name": "situational_awareness",+ "modules": [+ "recon.fingerprint",+ "ad.enum_users",+ "ad.enum_computers",+ "ad.enum_acl",+ ],+ },+ {+ "name": "escalation",+ "modules": [+ "ad.kerberoast",+ "ad.adcs",+ "ad.delegation_abuse",+ "ad.sccm",+ ],+ },+ {+ "name": "lateral",+ "modules": [+ "lateral.smb_relay",+ "lateral.ntlm_relay",+ "credential.reuse",+ "lateral.wmiexec",+ "lateral.dcom",+ ],+ },+ {+ "name": "post_exploit",+ "modules": [+ "windows.lsass_dump",+ "windows.dpapi",+ "exfil.smb_shares",+ "exfil.secrets_scan",+ ],+ },],},"linux_pentest": {"description": "Linux infrastructure penetration test","stages": [- {"name": "recon", "modules": [- "network.port_scan", "network.service_detect",- "recon.fingerprint",- ]},- {"name": "privesc", "modules": [- "linux.privesc", "linux.kernel_suggester",- "linux.service_hijack", "linux.ld_preload",- ]},- {"name": "post_exploit", "modules": [- "linux.container", "linux.nfs_escape",- "exfil.secrets_scan",- ]},+ {+ "name": "recon",+ "modules": [+ "network.port_scan",+ "network.service_detect",+ "recon.fingerprint",+ ],+ },+ {+ "name": "privesc",+ "modules": [+ "linux.privesc",+ "linux.kernel_suggester",+ "linux.service_hijack",+ "linux.ld_preload",+ ],+ },+ {+ "name": "post_exploit",+ "modules": [+ "linux.container",+ "linux.nfs_escape",+ "exfil.secrets_scan",+ ],+ },],},}@@ -1380,9 +1615,12 @@ def get_campaign_template(name: str) -> dict | None:def list_campaign_templates() -> list[dict]:"""Return list of available campaign templates with descriptions."""return [- {"name": k, "description": v["description"],- "stages": len(v["stages"]),- "modules": sum(len(s["modules"]) for s in v["stages"])}+ {+ "name": k,+ "description": v["description"],+ "stages": len(v["stages"]),+ "modules": sum(len(s["modules"]) for s in v["stages"]),+ }for k, v in CAMPAIGN_TEMPLATES.items()]@@ -1397,9 +1635,7 @@ def plan_from_template(name: str, custom_params: dict | None = None) -> "Executi"""template = CAMPAIGN_TEMPLATES.get(name)if not template:- raise ValueError(- f"Unknown template '{name}'. Available: {list(CAMPAIGN_TEMPLATES.keys())}"- )+ raise ValueError(f"Unknown template '{name}'. Available: {list(CAMPAIGN_TEMPLATES.keys())}")plan = ExecutionPlan()for stage in template["stages"]:plan.add_stage(diff --git a/ares/core/execution_admission.py b/ares/core/execution_admission.pynew file mode 100644index 0000000..484a7a7--- /dev/null+++ b/ares/core/execution_admission.py@@ -0,0 +1,1201 @@+"""C-LIVE-v1 fail-closed admission coordinator.++This module is the only first-party bridge from durable lifecycle admission to+the in-process execution engine. It deliberately does not make descriptors+eligible: the generation-11 policy/catalog gate remains authoritative.+"""++from __future__ import annotations++import asyncio+import hashlib+import hmac+import inspect+import json+import secrets+from dataclasses import dataclass+from enum import Enum+from typing import TYPE_CHECKING, Any, Awaitable, Callable, Mapping, Protocol++from ares.db.execution_lifecycle import (+ AdmissionIntentV3,+ AttemptState,+ FixedResult,+ OperationResult,+ OutcomeCode,+ RetryIntentV3,+ TerminalCommitIntentV3,+ TransitionRequest,+ TrustedPrincipal,+ canonical_operation_binding_digest,+ valid_uuid,+)++if TYPE_CHECKING:+ from ares.core.campaign import Campaign+ from ares.core.engine import AresEngine, EngineModuleResult+++C_LIVE_SUBMISSION_DOMAIN = "ares.c-live.v1.submission"+C_LIVE_LOGICAL_DOMAIN = "ares.c-live.v1.logical"+C_LIVE_ATTEMPT_DOMAIN = "ares.c-live.v1.attempt"+C_LIVE_OPERATION_DOMAIN = "ares.c-live.v1.operation"+C_LIVE_PLAN_CHILD_DOMAIN = "ares.c-live.v1.plan-child"+C_LIVE_STRATEGY_CHILD_DOMAIN = "ares.c-live.v1.strategy-child"+C_LIVE_RETRY_CHILD_DOMAIN = "ares.c-live.v1.retry-child"+C_LIVE_RESULT_DOMAIN = b"ares.c-live.v1.execution-result\x00"++_CHILD_DOMAINS = frozenset(+ {+ C_LIVE_PLAN_CHILD_DOMAIN,+ C_LIVE_STRATEGY_CHILD_DOMAIN,+ C_LIVE_RETRY_CHILD_DOMAIN,+ }+)+_ISSUER = object()+_PROCESS_SEAL_KEY = secrets.token_bytes(32)+++def _uuid_from_digest(digest: str) -> str:+ """Return the lifecycle-compatible deterministic UUID projection."""+ if type(digest) is not str or len(digest) != 64:+ raise ValueError("C-LIVE digest must be a lowercase SHA-256 value")+ try:+ int(digest, 16)+ except ValueError as exc:+ raise ValueError("C-LIVE digest must be a lowercase SHA-256 value") from exc+ if digest != digest.lower():+ raise ValueError("C-LIVE digest must be a lowercase SHA-256 value")+ return f"{digest[:8]}-{digest[8:12]}-4{digest[13:16]}-8{digest[17:20]}-{digest[20:32]}"+++def derive_c_live_uuid(+ domain: str,+ fields: tuple[tuple[str, str | int | bool | None], ...],+) -> str:+ """Derive one UUID from the existing typed-length lifecycle framing."""+ return _uuid_from_digest(canonical_operation_binding_digest(domain, fields))+++def derive_submission_id(campaign_id: str, ingress_code: str, idempotency_key: str) -> str:+ """Submission namespace: campaign + ingress + client Idempotency-Key."""+ return derive_c_live_uuid(+ C_LIVE_SUBMISSION_DOMAIN,+ (+ ("campaign_id", campaign_id),+ ("ingress_code", ingress_code),+ ("idempotency_key", idempotency_key),+ ),+ )+++def derive_logical_execution_id(+ campaign_id: str,+ submission_id: str,+ *,+ whole_intent_digest: str | None = None,+) -> str:+ fields: tuple[tuple[str, str | int | bool | None], ...] = (+ ("campaign_id", campaign_id),+ ("submission_id", submission_id),+ )+ if whole_intent_digest is not None:+ fields += (("whole_intent_digest", whole_intent_digest),)+ return derive_c_live_uuid(+ C_LIVE_LOGICAL_DOMAIN,+ fields,+ )+++def derive_attempt_id(+ parent_id: str,+ module_id: str,+ *,+ occurrence: int = 0,+ stage_ordinal: int = 0,+ decision_ordinal: int = 0,+ module_ordinal: int = 0,+ domain: str = C_LIVE_ATTEMPT_DOMAIN,+) -> str:+ if domain not in _CHILD_DOMAINS | {C_LIVE_ATTEMPT_DOMAIN}:+ raise ValueError("Unsupported C-LIVE attempt domain")+ return derive_c_live_uuid(+ domain,+ (+ ("parent_id", parent_id),+ ("occurrence", occurrence),+ ("stage_ordinal", stage_ordinal),+ ("decision_ordinal", decision_ordinal),+ ("module_ordinal", module_ordinal),+ ("module_id", module_id),+ ),+ )+++def derive_child_submission_id(+ parent_submission_id: str,+ module_id: str,+ *,+ occurrence: int,+ stage_ordinal: int,+ decision_ordinal: int,+ module_ordinal: int,+ domain: str,+) -> str:+ """Project one child submission from the shared HTTP submission authority."""+ if not valid_uuid(parent_submission_id) or domain not in _CHILD_DOMAINS:+ raise ValueError("invalid C-LIVE child identity authority")+ return derive_attempt_id(+ parent_submission_id,+ module_id,+ occurrence=occurrence,+ stage_ordinal=stage_ordinal,+ decision_ordinal=decision_ordinal,+ module_ordinal=module_ordinal,+ domain=domain,+ )+++def derive_operation_id(+ attempt_id: str,+ action: str,+ *,+ ordinal: int = 0,+) -> str:+ """Derive a stable operation authority from attempt + fixed action."""+ return derive_c_live_uuid(+ C_LIVE_OPERATION_DOMAIN,+ (+ ("attempt_id", attempt_id),+ ("action", action),+ ("ordinal", ordinal),+ ),+ )+++def canonical_intent_digest(value: Any) -> str:+ try:+ encoded = json.dumps(+ value,+ sort_keys=True,+ separators=(",", ":"),+ ensure_ascii=False,+ allow_nan=False,+ ).encode("utf-8")+ except (TypeError, ValueError) as exc:+ raise ValueError("C-LIVE intent must be canonical JSON") from exc+ return hashlib.sha256(b"ares.c-live.v1.intent\x00" + encoded).hexdigest()+++@dataclass(frozen=True, slots=True)+class RevalidatedPrincipalV1:+ """Point-in-time bearer authority returned by the route revalidator."""++ principal: TrustedPrincipal+ authority_revision: int+ role: str+++class DispatchDispositionV1(str, Enum):+ TERMINAL = "terminal"+ REPLAYED = "replayed"+ NON_DISPATCHABLE = "non_dispatchable"+ CONFLICT = "conflict"+ INDETERMINATE = "indeterminate"+++@dataclass(frozen=True, slots=True)+class DispatchRequestV1:+ campaign_id: str+ module_id: str+ ingress_code: str+ idempotency_key: str+ raw_parameters: Mapping[str, Any]+ whole_intent_digest: str+ occurrence: int = 0+ stage_ordinal: int = 0+ decision_ordinal: int = 0+ module_ordinal: int = 0+ credential_ids: tuple[str, ...] = ()+ approval_ref: str | None = None+ noise_units: int = 0+ exfiltration_units: int = 0+ timeout_seconds: int = 120+ skip_validation: bool = False+++@dataclass(frozen=True, slots=True)+class DispatchIdentityV1:+ submission_id: str+ logical_execution_id: str+ attempt_id: str+ admission_operation_id: str+ queue_operation_id: str+ dispatch_operation_id: str+ start_operation_id: str+ owner_ref: str+++@dataclass(frozen=True, slots=True)+class DispatchOutcomeV1:+ disposition: DispatchDispositionV1+ identity: DispatchIdentityV1 | None+ lifecycle_result: FixedResult+ revision: int | None+ module_result: Any = None+ effect_started: bool = False+ terminal_committed: bool = False+++class _LifecycleStoreV1(Protocol):+ async def create_initial_execution_v3(+ self, principal: TrustedPrincipal, intent: AdmissionIntentV3+ ) -> OperationResult: ...++ async def create_retry_attempt_v3(+ self, principal: TrustedPrincipal, intent: RetryIntentV3+ ) -> OperationResult: ...++ async def transition_attempt(self, request: TransitionRequest) -> OperationResult: ...++ async def enter_settlement_pending(self, request: TransitionRequest) -> OperationResult: ...++ async def commit_terminal_attempt_v3(+ self, intent: TerminalCommitIntentV3+ ) -> OperationResult: ...+++RevalidateCallbackV1 = Callable[+ [TrustedPrincipal, str, str],+ RevalidatedPrincipalV1 | None | Awaitable[RevalidatedPrincipalV1 | None],+]+++def _seal_signature(parts: tuple[str, ...]) -> str:+ value = "\x00".join(parts).encode("utf-8")+ return hmac.new(_PROCESS_SEAL_KEY, value, hashlib.sha256).hexdigest()+++class AdmittedDispatchContextV1:+ """Coordinator-issued, process-local, single-use RUNNING capability."""++ __slots__ = (+ "campaign_id",+ "submission_id",+ "logical_execution_id",+ "attempt_id",+ "module_id",+ "attempt_revision",+ "_consumer_id",+ "_store_id",+ "_dispatch_nonce",+ "_signature",+ "_consumed",+ "_effect_started",+ "_settlement_proof",+ "_terminal_committed",+ "_finalized",+ )++ def __init__(+ self,+ *,+ campaign_id: str,+ submission_id: str,+ logical_execution_id: str,+ attempt_id: str,+ module_id: str,+ attempt_revision: int,+ consumer: object,+ store: object,+ _issuer: object,+ ) -> None:+ if _issuer is not _ISSUER:+ raise TypeError("dispatch contexts are coordinator-created only")+ self.campaign_id = campaign_id+ self.submission_id = submission_id+ self.logical_execution_id = logical_execution_id+ self.attempt_id = attempt_id+ self.module_id = module_id+ self.attempt_revision = attempt_revision+ self._consumer_id = id(consumer)+ self._store_id = id(store)+ self._dispatch_nonce = secrets.token_hex(32)+ self._consumed = False+ self._effect_started = False+ self._settlement_proof = "none"+ self._terminal_committed = False+ self._finalized = False+ self._signature = _seal_signature(self._parts())+ register = getattr(consumer, "_register_admitted_dispatch_context", None)+ if callable(register):+ register(self)++ def _parts(self) -> tuple[str, ...]:+ return (+ self.campaign_id,+ self.submission_id,+ self.logical_execution_id,+ self.attempt_id,+ self.module_id,+ str(self.attempt_revision),+ str(self._consumer_id),+ str(self._store_id),+ self._dispatch_nonce,+ )++ def __repr__(self) -> str:+ return "<AdmittedDispatchContextV1 sealed>"++ def __reduce__(self) -> Any:+ raise TypeError("dispatch contexts are not serializable")++ def __reduce_ex__(self, protocol: int) -> Any:+ del protocol+ raise TypeError("dispatch contexts are not serializable")+++class AdmittedPlanContextV1:+ """Single-use whole-plan seal containing an ordered child capability tuple."""++ __slots__ = (+ "campaign_id",+ "whole_intent_digest",+ "children",+ "_consumer_id",+ "_signature",+ "_consumed",+ )++ def __init__(+ self,+ *,+ campaign_id: str,+ whole_intent_digest: str,+ children: tuple[AdmittedDispatchContextV1, ...],+ consumer: object,+ _issuer: object,+ ) -> None:+ if _issuer is not _ISSUER:+ raise TypeError("plan contexts are coordinator-created only")+ self.campaign_id = campaign_id+ self.whole_intent_digest = whole_intent_digest+ self.children = children+ self._consumer_id = id(consumer)+ self._consumed = False+ self._signature = _seal_signature(+ (+ campaign_id,+ whole_intent_digest,+ str(self._consumer_id),+ *(child._signature for child in children),+ )+ )++ def __repr__(self) -> str:+ return "<AdmittedPlanContextV1 sealed>"++ def __reduce__(self) -> Any:+ raise TypeError("plan contexts are not serializable")++ def __reduce_ex__(self, protocol: int) -> Any:+ del protocol+ raise TypeError("plan contexts are not serializable")+++def consume_dispatch_context(+ context: object,+ *,+ consumer: object,+ campaign_id: str,+ module_id: str,+) -> AdmittedDispatchContextV1:+ """Validate and consume a sealed capability before any module code runs."""+ if type(context) is not AdmittedDispatchContextV1:+ raise PermissionError("live module execution requires a sealed admission context")+ try:+ registry_consumer = getattr(consumer, "_consume_registered_dispatch_context", None)+ registration_valid = callable(registry_consumer) and registry_consumer(context)+ valid = (+ registration_valid+ and hmac.compare_digest(context._signature, _seal_signature(context._parts()))+ and context._consumer_id == id(consumer)+ and context.campaign_id == campaign_id+ and context.module_id == module_id+ and context.attempt_revision == 3+ and not context._consumed+ )+ except (AttributeError, TypeError, ValueError):+ valid = False+ if not valid:+ raise PermissionError("dispatch context is stale, transferred, fabricated, or already used")+ context._consumed = True+ return context+++def mark_effect_started(context: AdmittedDispatchContextV1) -> None:+ if type(context) is not AdmittedDispatchContextV1 or not context._consumed:+ raise PermissionError("effect boundary requires a consumed dispatch context")+ context._effect_started = True+++def mark_terminal_committed(context: AdmittedDispatchContextV1) -> None:+ if type(context) is not AdmittedDispatchContextV1 or not context._consumed:+ raise PermissionError("terminal commit requires a consumed dispatch context")+ context._terminal_committed = True+++def consume_terminal_commit_context(+ context: object,+ *,+ consumer: object,+ campaign_id: str,+ module_id: str,+) -> AdmittedDispatchContextV1:+ if type(context) is not AdmittedDispatchContextV1:+ raise PermissionError("committed result publication requires a sealed context")+ valid = (+ hmac.compare_digest(context._signature, _seal_signature(context._parts()))+ and context._consumer_id == id(consumer)+ and context.campaign_id == campaign_id+ and context.module_id == module_id+ and context._consumed+ and context._terminal_committed+ and not context._finalized+ )+ if not valid:+ raise PermissionError("terminal context is stale, transferred, or not committed")+ context._finalized = True+ return context+++def dispatch_effect_started(context: AdmittedDispatchContextV1) -> bool:+ return type(context) is AdmittedDispatchContextV1 and bool(context._effect_started)+++def _mark_test_settlement_proof(+ context: AdmittedDispatchContextV1,+ proof: str,+) -> None:+ """Private proof seam; production engine timeouts never call this helper."""+ if (+ type(context) is not AdmittedDispatchContextV1+ or not context._consumed+ or proof not in {"cancellation_no_result_ack", "timeout_termination_ack"}+ ):+ raise PermissionError("invalid settlement proof")+ context._settlement_proof = proof+++def _settlement_proof(context: AdmittedDispatchContextV1) -> str:+ if type(context) is not AdmittedDispatchContextV1 or not context._consumed:+ return "none"+ return context._settlement_proof+++def consume_plan_context(+ context: object,+ *,+ consumer: object,+ campaign_id: str,+ module_ids: tuple[str, ...],+) -> tuple[AdmittedDispatchContextV1, ...]:+ if type(context) is not AdmittedPlanContextV1:+ raise PermissionError("live plan execution requires a sealed plan context")+ was_consumed = context._consumed+ context._consumed = True+ valid = not (+ was_consumed+ or context._consumer_id != id(consumer)+ or context.campaign_id != campaign_id+ or tuple(child.module_id for child in context.children) != module_ids+ or not hmac.compare_digest(+ context._signature,+ _seal_signature(+ (+ context.campaign_id,+ context.whole_intent_digest,+ str(context._consumer_id),+ *(child._signature for child in context.children),+ )+ ),+ )+ )+ if not valid:+ registry_consumer = getattr(consumer, "_consume_registered_dispatch_context", None)+ if callable(registry_consumer):+ for child in context.children:+ try:+ registry_consumer(child)+ child._consumed = True+ except (AttributeError, TypeError, ValueError):+ pass+ raise PermissionError("plan context is stale, transferred, or already used")+ return context.children+++def _issue_dispatch_context(+ *,+ consumer: object,+ store: object,+ identity: DispatchIdentityV1,+ campaign_id: str,+ module_id: str,+) -> AdmittedDispatchContextV1:+ return AdmittedDispatchContextV1(+ campaign_id=campaign_id,+ submission_id=identity.submission_id,+ logical_execution_id=identity.logical_execution_id,+ attempt_id=identity.attempt_id,+ module_id=module_id,+ attempt_revision=3,+ consumer=consumer,+ store=store,+ _issuer=_ISSUER,+ )+++def _mint_test_dispatch_context(+ consumer: object,+ campaign_id: str,+ module_id: str,+ *,+ store: object | None = None,+ ordinal: int = 0,+) -> AdmittedDispatchContextV1:+ """Private test seam; production coordinators never call this shortcut."""+ store = store if store is not None else consumer+ idempotency_key = _uuid_from_digest(+ hashlib.sha256(f"test-idempotency:{ordinal}".encode("ascii")).hexdigest()+ )+ submission_id = derive_submission_id(campaign_id, "direct_engine", idempotency_key)+ logical_id = derive_logical_execution_id(campaign_id, submission_id)+ attempt_id = derive_attempt_id(logical_id, module_id, module_ordinal=ordinal)+ identity = DispatchIdentityV1(+ submission_id,+ logical_id,+ attempt_id,+ derive_operation_id(attempt_id, "admission"),+ derive_operation_id(attempt_id, "queue"),+ derive_operation_id(attempt_id, "dispatch"),+ derive_operation_id(attempt_id, "start"),+ derive_operation_id(attempt_id, "dispatch-owner"),+ )+ return _issue_dispatch_context(+ consumer=consumer,+ store=store,+ identity=identity,+ campaign_id=campaign_id,+ module_id=module_id,+ )+++def _mint_test_plan_context(+ consumer: object,+ campaign_id: str,+ module_ids: tuple[str, ...],+) -> AdmittedPlanContextV1:+ children = tuple(+ _mint_test_dispatch_context(consumer, campaign_id, module_id, ordinal=ordinal)+ for ordinal, module_id in enumerate(module_ids)+ )+ return AdmittedPlanContextV1(+ campaign_id=campaign_id,+ whole_intent_digest=canonical_intent_digest(list(module_ids)),+ children=children,+ consumer=consumer,+ _issuer=_ISSUER,+ )+++def _validate_request(request: DispatchRequestV1) -> bool:+ return (+ type(request) is DispatchRequestV1+ and valid_uuid(request.campaign_id)+ and type(request.module_id) is str+ and bool(request.module_id)+ and type(request.ingress_code) is str+ and type(request.idempotency_key) is str+ and valid_uuid(request.idempotency_key)+ and type(request.whole_intent_digest) is str+ and len(request.whole_intent_digest) == 64+ and request.whole_intent_digest == request.whole_intent_digest.lower()+ and all(character in "0123456789abcdef" for character in request.whole_intent_digest)+ and isinstance(request.raw_parameters, Mapping)+ and all(+ type(value) is int and 0 <= value <= 9_007_199_254_740_991+ for value in (+ request.occurrence,+ request.stage_ordinal,+ request.decision_ordinal,+ request.module_ordinal,+ request.noise_units,+ request.exfiltration_units,+ )+ )+ and type(request.timeout_seconds) is int+ and 1 <= request.timeout_seconds <= 86_400+ and type(request.skip_validation) is bool+ )+++def _identity(request: DispatchRequestV1, *, parent_id: str | None = None) -> DispatchIdentityV1:+ root_submission_id = derive_submission_id(+ request.campaign_id, request.ingress_code, request.idempotency_key+ )+ attempt_domain = {+ "api_campaign_plan": C_LIVE_PLAN_CHILD_DOMAIN,+ "goal_api": C_LIVE_PLAN_CHILD_DOMAIN,+ "goal_cli": C_LIVE_PLAN_CHILD_DOMAIN,+ "cli_chain": C_LIVE_PLAN_CHILD_DOMAIN,+ "strategy": C_LIVE_STRATEGY_CHILD_DOMAIN,+ }.get(request.ingress_code, C_LIVE_ATTEMPT_DOMAIN)+ if parent_id is not None:+ attempt_domain = C_LIVE_RETRY_CHILD_DOMAIN+ submission_id = root_submission_id+ if attempt_domain in {C_LIVE_PLAN_CHILD_DOMAIN, C_LIVE_STRATEGY_CHILD_DOMAIN}:+ submission_id = derive_child_submission_id(+ root_submission_id,+ request.module_id,+ occurrence=request.occurrence,+ stage_ordinal=request.stage_ordinal,+ decision_ordinal=request.decision_ordinal,+ module_ordinal=request.module_ordinal,+ domain=attempt_domain,+ )+ logical_id = derive_logical_execution_id(+ request.campaign_id,+ submission_id,+ whole_intent_digest=(+ request.whole_intent_digest+ if attempt_domain in {C_LIVE_PLAN_CHILD_DOMAIN, C_LIVE_STRATEGY_CHILD_DOMAIN}+ else None+ ),+ )+ attempt_id = derive_attempt_id(+ parent_id or logical_id,+ request.module_id,+ occurrence=request.occurrence,+ stage_ordinal=request.stage_ordinal,+ decision_ordinal=request.decision_ordinal,+ module_ordinal=request.module_ordinal,+ domain=attempt_domain,+ )+ return DispatchIdentityV1(+ submission_id=submission_id,+ logical_execution_id=logical_id,+ attempt_id=attempt_id,+ admission_operation_id=derive_operation_id(attempt_id, "admission"),+ queue_operation_id=derive_operation_id(attempt_id, "queue"),+ dispatch_operation_id=derive_operation_id(attempt_id, "dispatch"),+ start_operation_id=derive_operation_id(attempt_id, "start"),+ owner_ref=derive_operation_id(attempt_id, "dispatch-owner"),+ )+++async def _await_revalidation(+ callback: RevalidateCallbackV1,+ principal: TrustedPrincipal,+ campaign_id: str,+ module_id: str,+) -> RevalidatedPrincipalV1 | None:+ try:+ value = callback(principal, campaign_id, module_id)+ if inspect.isawaitable(value):+ value = await value+ except Exception:+ return None+ if (+ type(value) is not RevalidatedPrincipalV1+ or type(value.principal) is not TrustedPrincipal+ or value.principal.subject_ref != principal.subject_ref+ or value.principal.user_id != principal.user_id+ or type(value.authority_revision) is not int+ or not 0 <= value.authority_revision < 9_007_199_254_740_991+ or value.role not in {"operator", "team_lead"}+ ):+ return None+ return value+++def _disposition(result: FixedResult) -> DispatchDispositionV1:+ if result in {+ FixedResult.REPLAYED,+ FixedResult.REPLAYED_BOUND_CHILD,+ FixedResult.REPLAYED_CLOSED,+ }:+ return DispatchDispositionV1.REPLAYED+ if result in {+ FixedResult.CONFLICT_OPERATION,+ FixedResult.CONFLICT_REVISION,+ FixedResult.CONFLICT_STATE,+ FixedResult.CONFLICT_OWNER,+ FixedResult.CONFLICT_GENERATION,+ }:+ return DispatchDispositionV1.CONFLICT+ return DispatchDispositionV1.NON_DISPATCHABLE+++def _execution_result_digest(result: Any) -> str:+ if hasattr(result, "model_dump"):+ value = result.model_dump(mode="json")+ else:+ value = result+ encoded = json.dumps(+ value,+ sort_keys=True,+ separators=(",", ":"),+ ensure_ascii=False,+ allow_nan=False,+ default=str,+ ).encode("utf-8")+ return hashlib.sha256(C_LIVE_RESULT_DOMAIN + encoded).hexdigest()+++class ExecutionAdmissionCoordinatorV1:+ """At-most-once, fail-closed coordinator for one known module attempt."""++ def __init__(+ self,+ store: _LifecycleStoreV1,+ engine: AresEngine,+ revalidate: RevalidateCallbackV1,+ *,+ lease_duration_ms: int = 30_000,+ ) -> None:+ if type(lease_duration_ms) is not int or not 1_000 <= lease_duration_ms <= 86_400_000:+ raise ValueError("invalid C-LIVE lease duration")+ self._store = store+ self._engine = engine+ self._revalidate = revalidate+ self._lease_duration_ms = lease_duration_ms+ bind_store = getattr(engine, "_bind_admission_store", None)+ if not callable(bind_store):+ raise TypeError("engine does not implement the sealed admission boundary")+ bind_store(store)++ async def execute_module(+ self,+ principal: TrustedPrincipal,+ request: DispatchRequestV1,+ campaign: Campaign,+ ) -> DispatchOutcomeV1:+ if not _validate_request(request) or getattr(campaign, "id", None) != request.campaign_id:+ return DispatchOutcomeV1(+ DispatchDispositionV1.NON_DISPATCHABLE,+ None,+ FixedResult.INVALID_CONTRACT,+ None,+ )+ identity = _identity(request)+ admission = await self._store.create_initial_execution_v3(+ principal,+ AdmissionIntentV3(+ logical_execution_id=identity.logical_execution_id,+ submission_id=identity.submission_id,+ attempt_id=identity.attempt_id,+ outbox_id=None,+ publication_key=None,+ campaign_id=request.campaign_id,+ module_id=request.module_id,+ ingress_code=request.ingress_code,+ operation_id=identity.admission_operation_id,+ evaluation_mode="live",+ raw_parameters=dict(request.raw_parameters),+ credential_ids=request.credential_ids,+ approval_ref=request.approval_ref,+ noise_units=request.noise_units,+ exfiltration_units=request.exfiltration_units,+ ),+ )+ if admission.result is not FixedResult.APPLIED or admission.revision != 0:+ return DispatchOutcomeV1(+ _disposition(admission.result), identity, admission.result, admission.revision+ )+ revalidated = await _await_revalidation(+ self._revalidate, principal, request.campaign_id, request.module_id+ )+ if revalidated is None:+ return DispatchOutcomeV1(+ DispatchDispositionV1.NON_DISPATCHABLE,+ identity,+ FixedResult.AUTHORITY_STALE,+ 0,+ )+ return await self._advance_and_execute(identity, request, campaign, revalidated)++ async def retry_module(+ self,+ principal: TrustedPrincipal,+ request: DispatchRequestV1,+ campaign: Campaign,+ *,+ logical_execution_id: str,+ parent_attempt_id: str,+ expected_parent_revision: int,+ ) -> DispatchOutcomeV1:+ """Create and own exactly one durable retry child; replay never dispatches."""+ if (+ not _validate_request(request)+ or getattr(campaign, "id", None) != request.campaign_id+ or not valid_uuid(logical_execution_id)+ or not valid_uuid(parent_attempt_id)+ or type(expected_parent_revision) is not int+ or not 0 <= expected_parent_revision < 9_007_199_254_740_991+ ):+ return DispatchOutcomeV1(+ DispatchDispositionV1.NON_DISPATCHABLE,+ None,+ FixedResult.INVALID_CONTRACT,+ None,+ )+ identity = _identity(request, parent_id=parent_attempt_id)+ identity = DispatchIdentityV1(+ identity.submission_id,+ logical_execution_id,+ identity.attempt_id,+ derive_operation_id(identity.attempt_id, "retry-admission"),+ identity.queue_operation_id,+ identity.dispatch_operation_id,+ identity.start_operation_id,+ identity.owner_ref,+ )+ created = await self._store.create_retry_attempt_v3(+ principal,+ RetryIntentV3(+ logical_execution_id=logical_execution_id,+ parent_attempt_id=parent_attempt_id,+ child_attempt_id=identity.attempt_id,+ outbox_id=None,+ publication_key=None,+ operation_id=identity.admission_operation_id,+ expected_parent_revision=expected_parent_revision,+ evaluation_mode="live",+ raw_parameters=dict(request.raw_parameters),+ credential_ids=request.credential_ids,+ approval_ref=request.approval_ref,+ noise_units=request.noise_units,+ exfiltration_units=request.exfiltration_units,+ ),+ )+ if created.result is not FixedResult.APPLIED or created.revision != 0:+ return DispatchOutcomeV1(+ _disposition(created.result), identity, created.result, created.revision+ )+ revalidated = await _await_revalidation(+ self._revalidate, principal, request.campaign_id, request.module_id+ )+ if revalidated is None:+ return DispatchOutcomeV1(+ DispatchDispositionV1.NON_DISPATCHABLE,+ identity,+ FixedResult.AUTHORITY_STALE,+ 0,+ )+ return await self._advance_and_execute(identity, request, campaign, revalidated)++ async def _advance_and_execute(+ self,+ identity: DispatchIdentityV1,+ request: DispatchRequestV1,+ campaign: Campaign,+ revalidated: RevalidatedPrincipalV1,+ ) -> DispatchOutcomeV1:+ queue = await self._store.transition_attempt(+ TransitionRequest(+ identity.attempt_id,+ 0,+ AttemptState.QUEUED,+ identity.queue_operation_id,+ campaign_id=request.campaign_id,+ actor_subject_ref=revalidated.principal.subject_ref,+ actor_user_id=revalidated.principal.user_id,+ actor_authority_revision=revalidated.authority_revision,+ )+ )+ if queue.result is not FixedResult.APPLIED or queue.revision != 1:+ return DispatchOutcomeV1(+ _disposition(queue.result), identity, queue.result, queue.revision+ )+ dispatch = await self._store.transition_attempt(+ TransitionRequest(+ identity.attempt_id,+ 1,+ AttemptState.DISPATCHING,+ identity.dispatch_operation_id,+ owner_ref=identity.owner_ref,+ lease_generation=1,+ lease_duration_ms=self._lease_duration_ms,+ campaign_id=request.campaign_id,+ )+ )+ if dispatch.result is not FixedResult.APPLIED or dispatch.revision != 2:+ return DispatchOutcomeV1(+ _disposition(dispatch.result), identity, dispatch.result, dispatch.revision+ )+ running = await self._store.transition_attempt(+ TransitionRequest(+ identity.attempt_id,+ 2,+ AttemptState.RUNNING,+ identity.start_operation_id,+ owner_ref=identity.owner_ref,+ lease_generation=1,+ campaign_id=request.campaign_id,+ )+ )+ if running.result is not FixedResult.APPLIED or running.revision != 3:+ return DispatchOutcomeV1(+ _disposition(running.result), identity, running.result, running.revision+ )++ context = _issue_dispatch_context(+ consumer=self._engine,+ store=self._store,+ identity=identity,+ campaign_id=request.campaign_id,+ module_id=request.module_id,+ )+ try:+ module_result = await self._engine.run_module(+ request.module_id,+ campaign,+ dict(request.raw_parameters),+ skip_validation=request.skip_validation,+ timeout_seconds=request.timeout_seconds,+ actor_role=revalidated.role,+ dispatch_context=context,+ )+ except asyncio.CancelledError:+ await self._park_uncertain_after_cancellation(identity, request, context)+ raise+ except (KeyboardInterrupt, SystemExit, GeneratorExit):+ raise+ except Exception:+ return await self._park_uncertain(identity, request, context)++ from ares.core.engine import ModuleStatus++ proof = _settlement_proof(context)+ if module_result.status is ModuleStatus.CANCELLED and proof != "cancellation_no_result_ack":+ return await self._park_uncertain(+ identity, request, context, module_result=module_result+ )+ if module_result.status is ModuleStatus.TIMEOUT and proof != "timeout_termination_ack":+ return await self._park_uncertain(+ identity, request, context, module_result=module_result+ )+ if module_result.status is ModuleStatus.CANCELLED:+ cancelling = await self._store.transition_attempt(+ TransitionRequest(+ identity.attempt_id,+ 3,+ AttemptState.CANCELLING,+ derive_operation_id(identity.attempt_id, "cancel-request"),+ owner_ref=identity.owner_ref,+ lease_generation=1,+ campaign_id=request.campaign_id,+ )+ )+ if cancelling.result is not FixedResult.APPLIED or cancelling.revision != 4:+ return await self._park_uncertain(+ identity, request, context, module_result=module_result+ )+ outcome = OutcomeCode.CONFIRMED_CANCELLED_NO_RESULT+ result_digest = None+ terminal_revision = 4+ elif module_result.status is ModuleStatus.TIMEOUT:+ outcome = OutcomeCode.CONFIRMED_TIMEOUT_TERMINATED+ result_digest = None+ terminal_revision = 3+ elif module_result.status is ModuleStatus.DONE:+ outcome = OutcomeCode.CONFIRMED_SUCCESS+ result_digest = _execution_result_digest(module_result)+ terminal_revision = 3+ else:+ outcome = OutcomeCode.CONFIRMED_FAILURE+ result_digest = _execution_result_digest(module_result)+ terminal_revision = 3++ try:+ terminal = await self._store.commit_terminal_attempt_v3(+ TerminalCommitIntentV3(+ logical_execution_id=identity.logical_execution_id,+ campaign_id=request.campaign_id,+ attempt_id=identity.attempt_id,+ expected_attempt_revision=terminal_revision,+ outcome_code=outcome,+ noise_actual=0,+ exfiltration_actual=0,+ concurrency_actual=0,+ execution_result_digest=result_digest,+ outputs=(),+ )+ )+ except asyncio.CancelledError:+ await self._park_uncertain_after_cancellation(+ identity,+ request,+ context,+ module_result=module_result,+ expected_revision=terminal_revision,+ )+ raise+ except (KeyboardInterrupt, SystemExit, GeneratorExit):+ raise+ except Exception:+ return await self._park_uncertain(+ identity,+ request,+ context,+ module_result=module_result,+ expected_revision=terminal_revision,+ )+ if terminal.result is FixedResult.APPLIED and terminal.revision != terminal_revision + 1:+ return await self._park_uncertain(+ identity,+ request,+ context,+ module_result=module_result,+ expected_revision=terminal_revision,+ fallback_result=OperationResult(+ FixedResult.INVARIANT_FAILURE, terminal.revision+ ),+ result_override=OperationResult(+ FixedResult.INVARIANT_FAILURE, terminal.revision+ ),+ )+ if terminal.result is not FixedResult.APPLIED:+ return await self._park_uncertain(+ identity,+ request,+ context,+ module_result=module_result,+ expected_revision=terminal_revision,+ fallback_result=terminal,+ )+ mark_terminal_committed(context)+ committed = await self._engine._finalize_committed_module_result(+ campaign, request.module_id, module_result, context+ )+ return DispatchOutcomeV1(+ DispatchDispositionV1.TERMINAL,+ identity,+ terminal.result,+ terminal.revision,+ committed,+ dispatch_effect_started(context),+ True,+ )++ async def _park_uncertain_after_cancellation(+ self,+ identity: DispatchIdentityV1,+ request: DispatchRequestV1,+ context: AdmittedDispatchContextV1,+ *,+ module_result: Any = None,+ expected_revision: int = 3,+ ) -> None:+ """Bound and own settlement parking before propagating task cancellation."""+ parking = asyncio.create_task(+ self._park_uncertain(+ identity,+ request,+ context,+ module_result=module_result,+ expected_revision=expected_revision,+ ),+ name=f"c-live-settlement-pending-{identity.attempt_id}",+ )+ try:+ await asyncio.wait_for(asyncio.shield(parking), timeout=5.0)+ except (asyncio.TimeoutError, asyncio.CancelledError):+ parking.cancel()+ try:+ await parking+ except BaseException:+ pass+ except Exception:+ # The original cancellation remains authoritative. Parking is a+ # best-effort bounded safety write and never becomes an HTTP result.+ pass++ async def _park_uncertain(+ self,+ identity: DispatchIdentityV1,+ request: DispatchRequestV1,+ context: AdmittedDispatchContextV1,+ *,+ module_result: Any = None,+ expected_revision: int = 3,+ fallback_result: OperationResult | None = None,+ result_override: OperationResult | None = None,+ ) -> DispatchOutcomeV1:+ operation_id = derive_operation_id(identity.attempt_id, "settlement-pending")+ outbox_id = derive_operation_id(identity.attempt_id, "settlement-pending-outbox")+ publication_key = derive_operation_id(identity.attempt_id, "settlement-pending-publication")+ try:+ parked = await self._store.enter_settlement_pending(+ TransitionRequest(+ identity.attempt_id,+ expected_revision,+ AttemptState.SETTLEMENT_PENDING,+ operation_id,+ owner_ref=identity.owner_ref,+ lease_generation=1,+ cancellation_request_revision=(+ expected_revision if expected_revision == 4 else None+ ),+ authoritative_proof="unresolved",+ outbox_id=outbox_id,+ publication_key=publication_key,+ campaign_id=request.campaign_id,+ )+ )+ except (KeyboardInterrupt, SystemExit, GeneratorExit, asyncio.CancelledError):+ raise+ except Exception:+ parked = (+ fallback_result+ if fallback_result is not None+ else OperationResult(FixedResult.INVARIANT_FAILURE, None)+ )+ if parked.result is not FixedResult.APPLIED and fallback_result is not None:+ parked = fallback_result+ reported = result_override if result_override is not None else parked+ return DispatchOutcomeV1(+ DispatchDispositionV1.INDETERMINATE,+ identity,+ reported.result,+ reported.revision,+ module_result,+ dispatch_effect_started(context),+ False,+ )+++__all__ = [+ "AdmittedDispatchContextV1",+ "AdmittedPlanContextV1",+ "C_LIVE_ATTEMPT_DOMAIN",+ "C_LIVE_LOGICAL_DOMAIN",+ "C_LIVE_OPERATION_DOMAIN",+ "C_LIVE_PLAN_CHILD_DOMAIN",+ "C_LIVE_RETRY_CHILD_DOMAIN",+ "C_LIVE_STRATEGY_CHILD_DOMAIN",+ "C_LIVE_SUBMISSION_DOMAIN",+ "DispatchDispositionV1",+ "DispatchIdentityV1",+ "DispatchOutcomeV1",+ "DispatchRequestV1",+ "ExecutionAdmissionCoordinatorV1",+ "RevalidatedPrincipalV1",+ "canonical_intent_digest",+ "derive_attempt_id",+ "derive_child_submission_id",+ "derive_c_live_uuid",+ "derive_logical_execution_id",+ "derive_operation_id",+ "derive_submission_id",+]diff --git a/ares/db/database.py b/ares/db/database.pyindex 7ac4ce2..e64712e 100644--- a/ares/db/database.py+++ b/ares/db/database.py@@ -2,21 +2,24 @@ARES Database — async SQLite via aiosqlite.All credential/token content encrypted at rest via Fernet."""+from __future__ import annotationsimport asyncio+import hashlibimport jsonimport reimport secretsimport uuidfrom collections.abc import Callablefrom dataclasses import dataclass, field-from datetime import datetime, timezone, timedelta+from datetime import datetime, timedelta, timezonefrom pathlib import Pathfrom typing import Any, Awaitable, TypeVarfrom urllib.parse import unquoteimport aiosqlite+from ares.core.logger import get_loggerfrom ares.core.token_sessions import (FAMILY_ABSOLUTE_LIFETIME_DAYS,@@ -33,13 +36,21 @@ from ares.core.token_sessions import (generate_refresh_token,hash_refresh_token,)+from ares.db.execution_lifecycle import (+ SYSTEM_PRINCIPAL_SUBJECT_REF,+ ExecutionLifecycleStore,+ FixedResult,+ OperationResult,+ valid_uuid,+ validate_sqlite_admission_authority_catalog_async,+)from ares.db.websocket_tickets import (+ WEBSOCKET_TICKET_TTL_SECONDS,ApiKeyTicketSource,BearerTicketSource,ConsumedWebSocketTicket,WebSocketTicketCredentialKind,WebSocketTicketPrincipal,- WEBSOCKET_TICKET_TTL_SECONDS,format_sqlite_utc,generate_websocket_ticket,hash_websocket_ticket,@@ -51,6 +62,21 @@ from ares.db.websocket_tickets import (logger = get_logger("ares.db")+_CAMPAIGN_DELETE_OPERATION_DOMAIN = b"ares.campaign-delete.compat-operation.v1\x00"+++def _campaign_delete_operation_id(campaign_id: str) -> str:+ """Derive the stable UUIDv4-shaped identity for an implicit delete operation."""+ digest = bytearray(+ hashlib.sha256(_CAMPAIGN_DELETE_OPERATION_DOMAIN + campaign_id.encode("utf-8")).digest()[+ :16+ ]+ )+ digest[6] = (digest[6] & 0x0F) | 0x40+ digest[8] = (digest[8] & 0x3F) | 0x80+ return str(uuid.UUID(bytes=bytes(digest)))++from ares.core.campaign import Campaign, Findingfrom ares.core.security import DataEncryptor, hash_password, verify_passwordfrom ares.db.schema import CREATE_TABLES, SCHEMA_VERSION@@ -251,10 +277,7 @@ def _extract_named_checks(table_sql: str) -> tuple[dict[str, str], int]:character = table_sql[index]if quote is not None:if character == quote:- if (- index + 1 < len(table_sql)- and table_sql[index + 1] == quote- ):+ if index + 1 < len(table_sql) and table_sql[index + 1] == quote:index += 1else:quote = None@@ -271,9 +294,7 @@ def _extract_named_checks(table_sql: str) -> tuple[dict[str, str], int]:index += 1if depth != 0 or name in checks:return {}, check_count- checks[name] = _normalize_sql_fragment(- table_sql[expression_start:index]- )+ checks[name] = _normalize_sql_fragment(table_sql[expression_start:index])return checks, check_count@@ -344,14 +365,9 @@ def _extract_named_foreign_keys(if opening < 0 or closing <= opening:return {}foreign_keys: dict[str, tuple[str, str, str, str, str]] = {}- for raw_fragment in _split_sql_list(table_sql[opening + 1:closing]):+ for raw_fragment in _split_sql_list(table_sql[opening + 1 : closing]):fragment = _normalize_sql_fragment(raw_fragment)- fragment = (- fragment.replace('"', "")- .replace("`", "")- .replace("[", "")- .replace("]", "")- )+ fragment = fragment.replace('"', "").replace("`", "").replace("[", "").replace("]", "")name_match = re.search(r"""\bconstraint\s+(?:"([^"]+)"|`([^`]+)`|\[([^\]]+)\]|@@ -362,11 +378,7 @@ def _extract_named_foreign_keys()if name_match is None:continue- name = next(- group- for group in name_match.groups()- if group is not None- ).lower()+ name = next(group for group in name_match.groups() if group is not None).lower()if name not in _WEBSOCKET_TICKET_FOREIGN_KEY_NAMES:continuetable_level = re.search(@@ -394,9 +406,7 @@ def _extract_named_foreign_keys(if local_match is None or reference_match is None:return {}local_column = next(- group- for group in local_match.groups()- if group is not None+ group for group in local_match.groups() if group is not None).lower()target_table, target_column = reference_match.groups()if name in foreign_keys:@@ -449,10 +459,7 @@ def _remove_suppressed_cancellations(if task is None:return 0removed = 0- while (- removed < caught_cancellations- and task.cancelling() > cancellation_baseline- ):+ while removed < caught_cancellations and task.cancelling() > cancellation_baseline:task.uncancel()removed += 1return removed@@ -530,53 +537,58 @@ def _normalize_sqlite_target(db_path: str) -> tuple[str, bool, str]:# ── Domain models ─────────────────────────────────────────────────────────────+@dataclassclass Host:"""Domain model for a discovered host. Consistent with Campaign/Finding (Pydantic)."""- campaign_id: str- ip_address: str- hostname: str | None = None- fqdn: str | None = None- os: str | None = None- os_version: str | None = None- domain: str | None = None- is_dc: bool = False- open_ports: list[int] = field(default_factory=list)- tags: list[str] = field(default_factory=list)- id: str = field(default_factory=lambda: str(uuid.uuid4()))++ campaign_id: str+ ip_address: str+ hostname: str | None = None+ fqdn: str | None = None+ os: str | None = None+ os_version: str | None = None+ domain: str | None = None+ is_dc: bool = False+ open_ports: list[int] = field(default_factory=list)+ tags: list[str] = field(default_factory=list)+ id: str = field(default_factory=lambda: str(uuid.uuid4()))@dataclassclass DBCredential:"""Domain model for a stored credential. Consistent with vault Credential model."""- campaign_id: str- username: str- cred_type: str- secret: str | None = None- domain: str | None = None- host_id: str | None = None- source_module: str | None = None- notes: str = ""- id: str = field(default_factory=lambda: str(uuid.uuid4()))++ campaign_id: str+ username: str+ cred_type: str+ secret: str | None = None+ domain: str | None = None+ host_id: str | None = None+ source_module: str | None = None+ notes: str = ""+ id: str = field(default_factory=lambda: str(uuid.uuid4()))@dataclassclass Loot:"""Domain model for collected loot (files, tokens, keys)."""- campaign_id: str- loot_type: str- name: str- description: str = ""- content: str | bytes | None = None- host_id: str | None = None- path_on_target: str | None = None- source_module: str | None = None- tags: list[str] = field(default_factory=list)- id: str = field(default_factory=lambda: str(uuid.uuid4()))++ campaign_id: str+ loot_type: str+ name: str+ description: str = ""+ content: str | bytes | None = None+ host_id: str | None = None+ path_on_target: str | None = None+ source_module: str | None = None+ tags: list[str] = field(default_factory=list)+ id: str = field(default_factory=lambda: str(uuid.uuid4()))# ── Database ──────────────────────────────────────────────────────────────────+class AresDatabase:"""Async SQLite database wrapper with encryption support."""@@ -663,9 +675,7 @@ class AresDatabase:cancellation_baseline = _cancel_count()caught_cancellations = [0]- open_task = asyncio.ensure_future(- self._open_primary_connection()- )+ open_task = asyncio.ensure_future(self._open_primary_connection())self._name_owned_task(open_task, "ares-sqlite-primary-connect")connection = await _await_task_completion(open_task,@@ -714,7 +724,7 @@ class AresDatabase:cls,db_path: "str | Path" = "ares.db",encryption_key: str | None = None,- ) -> "AresDatabase | PostgresDatabase": # type: ignore[return]+ ) -> "AresDatabase | PostgresDatabase": # type: ignore[return]"""Factory that returns the correct backend based on db_path / DATABASE_URL.@@ -726,20 +736,20 @@ class AresDatabase:"""# Resolve database URL: explicit arg wins, then env varimport os as _os+url = str(db_path)if not url or url == "ares.db":url = _os.environ.get("ARES_DATABASE_URL", url)if url.startswith(("postgresql", "postgres")):from ares.db.postgres import PostgresDatabase- return await PostgresDatabase.create(- dsn=url, encryption_key=encryption_key- )++ return await PostgresDatabase.create(dsn=url, encryption_key=encryption_key)# SQLite path — strip dialect prefix if presentfor prefix in ("sqlite+aiosqlite:///", "sqlite:///"):if url.startswith(prefix):- url = url[len(prefix):]+ url = url[len(prefix) :]db = cls(url, encryption_key)return await db.connect()@@ -759,22 +769,16 @@ class AresDatabase:)except AdoptionFailure as exc:if exc.exit_code == AdoptionExit.MANAGED_METADATA:- raise RuntimeError(- "Invalid managed SQLite database metadata"- ) from None+ raise RuntimeError("Invalid managed SQLite database metadata") from Noneraise RuntimeError("Incompatible SQLite database catalog") from Noneif ownership.diagnostic.startswith("ARES-M2B-ADOPTION-READY:"):raise RuntimeError("SQLite database adoption is required")- if ownership.diagnostic == "ARES-M2B-ALREADY-MANAGED:0009":+ if ownership.diagnostic == "ARES-M2B-ALREADY-MANAGED:0011":+ await validate_sqlite_admission_authority_catalog_async(self._conn)returnif ownership.exit_code == AdoptionExit.MIGRATION_REQUIRED:- if ownership.predecessor not in {- f"{revision:04d}" for revision in range(1, 9)- }:- raise RuntimeError(- "Invalid managed SQLite database metadata"- )+ raise RuntimeError("SQLite schema migration is required")elif ownership.diagnostic != "ARES-M2B-EMPTY-DATABASE":raise RuntimeError("Incompatible SQLite database catalog")@@ -785,23 +789,24 @@ class AresDatabase:self._db_path,)except AdoptionFailure:- raise RuntimeError(- "SQLite managed initialization failed"- ) from None- if managed.diagnostic != "ARES-M2B-ALREADY-MANAGED:0009":+ raise RuntimeError("SQLite managed initialization failed") from None+ if managed.diagnostic != "ARES-M2B-ALREADY-MANAGED:0011":raise RuntimeError("SQLite managed initialization failed")+ await validate_sqlite_admission_authority_catalog_async(self._conn)returnasync with self._conn.execute(- "SELECT 1 FROM sqlite_master "- "WHERE type='table' AND name='websocket_tickets'"+ "SELECT 1 FROM sqlite_master WHERE type='table' AND name='websocket_tickets'") as cursor:ticket_table_exists = await cursor.fetchone() is not None+ runtime_catalog_exists = Falseif ticket_table_exists:await self._validate_websocket_ticket_schema()+ await validate_sqlite_admission_authority_catalog_async(self._conn)+ runtime_catalog_exists = Truealembic_applied = await self._run_alembic_migrations()- if not alembic_applied:+ if not alembic_applied and not runtime_catalog_exists:schema_body_marker = "PRAGMA foreign_keys = ON;"if CREATE_TABLES.count(schema_body_marker) != 1:raise RuntimeError("SQLite schema bootstrap is unavailable")@@ -810,16 +815,16 @@ class AresDatabase:maxsplit=1,)[1]try:- await self._conn.executescript(- f"BEGIN IMMEDIATE;\n{schema_body}"- )+ await self._conn.executescript(f"BEGIN IMMEDIATE;\n{schema_body}")await self._validate_websocket_ticket_schema()+ await validate_sqlite_admission_authority_catalog_async(self._conn)await self._conn.commit()except BaseException:await self._conn.rollback()raiseawait self._reconcile_sqlite_schema()await self._validate_websocket_ticket_schema()+ await validate_sqlite_admission_authority_catalog_async(self._conn)logger.info("db_ready",database=self._database_label,@@ -874,22 +879,13 @@ class AresDatabase:if connection is None:raise RuntimeError("Database not connected")- async with connection.execute(- "PRAGMA index_list(websocket_tickets)"- ) as cursor:+ async with connection.execute("PRAGMA index_list(websocket_tickets)") as cursor:index_rows = await cursor.fetchall()- primary_index_rows = tuple(- row- for row in index_rows- if str(row["origin"]).lower() == "pk"- )+ primary_index_rows = tuple(row for row in index_rows if str(row["origin"]).lower() == "pk")if len(primary_index_rows) != 1:raise RuntimeError("Incompatible WebSocket ticket schema")primary_index_row = primary_index_rows[0]- if (- int(primary_index_row["unique"]) != 1- or int(primary_index_row["partial"]) != 0- ):+ if int(primary_index_row["unique"]) != 1 or int(primary_index_row["partial"]) != 0:raise RuntimeError("Incompatible WebSocket ticket schema")primary_index_name = str(primary_index_row["name"])if not primary_index_name:@@ -907,40 +903,31 @@ class AresDatabase:expected_index_definitions = {"idx_ws_tickets_api_key": frozenset({- "createindexidx_ws_tickets_api_key"- "onwebsocket_tickets(api_key_id)",- "createindexifnotexistsidx_ws_tickets_api_key"- "onwebsocket_tickets(api_key_id)",+ "createindexidx_ws_tickets_api_keyonwebsocket_tickets(api_key_id)",+ "createindexifnotexistsidx_ws_tickets_api_keyonwebsocket_tickets(api_key_id)",}),"idx_ws_tickets_campaign": frozenset({- "createindexidx_ws_tickets_campaign"- "onwebsocket_tickets(campaign_id)",- "createindexifnotexistsidx_ws_tickets_campaign"- "onwebsocket_tickets(campaign_id)",+ "createindexidx_ws_tickets_campaignonwebsocket_tickets(campaign_id)",+ "createindexifnotexistsidx_ws_tickets_campaignonwebsocket_tickets(campaign_id)",}),"idx_ws_tickets_expires": frozenset({- "createindexidx_ws_tickets_expires"- "onwebsocket_tickets(expires_at)",- "createindexifnotexistsidx_ws_tickets_expires"- "onwebsocket_tickets(expires_at)",+ "createindexidx_ws_tickets_expiresonwebsocket_tickets(expires_at)",+ "createindexifnotexistsidx_ws_tickets_expiresonwebsocket_tickets(expires_at)",}),"idx_ws_tickets_user": frozenset({- "createindexidx_ws_tickets_user"- "onwebsocket_tickets(user_id)",- "createindexifnotexistsidx_ws_tickets_user"- "onwebsocket_tickets(user_id)",+ "createindexidx_ws_tickets_useronwebsocket_tickets(user_id)",+ "createindexifnotexistsidx_ws_tickets_useronwebsocket_tickets(user_id)",}),"idx_ws_tickets_bearer_family": frozenset({- "createindexidx_ws_tickets_bearer_family"- "onwebsocket_tickets(bearer_family_id)",+ "createindexidx_ws_tickets_bearer_familyonwebsocket_tickets(bearer_family_id)","createindexifnotexistsidx_ws_tickets_bearer_family""onwebsocket_tickets(bearer_family_id)",}@@ -991,9 +978,7 @@ class AresDatabase:):raise RuntimeError("Incompatible WebSocket ticket schema")- async with connection.execute(- "PRAGMA table_xinfo(websocket_tickets)"- ) as cursor:+ async with connection.execute("PRAGMA table_xinfo(websocket_tickets)") as cursor:columns = await cursor.fetchall()actual_columns = tuple((@@ -1010,9 +995,7 @@ class AresDatabase:if actual_columns != _WEBSOCKET_TICKET_COLUMNS:raise RuntimeError("Incompatible WebSocket ticket schema")- async with connection.execute(- "PRAGMA foreign_key_list(websocket_tickets)"- ) as cursor:+ async with connection.execute("PRAGMA foreign_key_list(websocket_tickets)") as cursor:foreign_keys = tuple(sorted((@@ -1037,9 +1020,7 @@ class AresDatabase:for row in index_rows:index_name = str(row["name"])quoted_name = index_name.replace('"', '""')- async with connection.execute(- f'PRAGMA index_xinfo("{quoted_name}")'- ) as cursor:+ async with connection.execute(f'PRAGMA index_xinfo("{quoted_name}")') as cursor:index_columns = tuple((int(index_row["seqno"]),@@ -1116,27 +1097,18 @@ class AresDatabase:),),}- if (- primary_index != expected_primary_index- or actual_indexes != expected_indexes- ):+ if primary_index != expected_primary_index or actual_indexes != expected_indexes:raise RuntimeError("Incompatible WebSocket ticket schema")async with connection.execute(- "SELECT sql FROM sqlite_master "- "WHERE type='table' AND name='websocket_tickets'"+ "SELECT sql FROM sqlite_master WHERE type='table' AND name='websocket_tickets'") as cursor:table_row = await cursor.fetchone()table_sql = str(table_row["sql"] if table_row else "")normalized_table_sql = _normalize_sql_fragment(table_sql)- if (- not normalized_table_sql.startswith(- "createtablewebsocket_tickets("- )- and not normalized_table_sql.startswith(- "createtableifnotexistswebsocket_tickets("- )- ):+ if not normalized_table_sql.startswith(+ "createtablewebsocket_tickets("+ ) and not normalized_table_sql.startswith("createtableifnotexistswebsocket_tickets("):raise RuntimeError("Incompatible WebSocket ticket schema")if ("withoutrowid" in normalized_table_sql@@ -1154,25 +1126,15 @@ class AresDatabase:name: _normalize_sql_fragment(expression)for name, expression in _WEBSOCKET_TICKET_CHECKS.items()}- if named_checks != expected_checks or check_count != len(- expected_checks- ):+ if named_checks != expected_checks or check_count != len(expected_checks):raise RuntimeError("Incompatible WebSocket ticket schema")expected_constraint_names = tuple(- sorted(- set(expected_checks)- | _WEBSOCKET_TICKET_FOREIGN_KEY_NAMES- )+ sorted(set(expected_checks) | _WEBSOCKET_TICKET_FOREIGN_KEY_NAMES))- if tuple(sorted(_extract_named_constraints(table_sql))) != (- expected_constraint_names- ):+ if tuple(sorted(_extract_named_constraints(table_sql))) != (expected_constraint_names):raise RuntimeError("Incompatible WebSocket ticket schema")- if (- _extract_named_foreign_keys(table_sql)- != _WEBSOCKET_TICKET_NAMED_FOREIGN_KEYS- ):+ if _extract_named_foreign_keys(table_sql) != _WEBSOCKET_TICKET_NAMED_FOREIGN_KEYS:raise RuntimeError("Incompatible WebSocket ticket schema")async def _run_alembic_migrations(self) -> bool:@@ -1197,9 +1159,7 @@ class AresDatabase:def _upgrade() -> None:with migration_config() as configured:alembic_cfg: AlembicConfig = configured- alembic_cfg.cmd_opts = SimpleNamespace(- x=[f"db_url={db_url}"]- )+ alembic_cfg.cmd_opts = SimpleNamespace(x=[f"db_url={db_url}"])alembic_command.upgrade(alembic_cfg, "head")await loop.run_in_executor(@@ -1216,8 +1176,7 @@ class AresDatabase:raise RuntimeError("SQLite managed initialization failed") from Noneexcept Exception as exc:raise RuntimeError(- "SQLite managed initialization failed "- f"[{type(exc).__name__}]"+ f"SQLite managed initialization failed [{type(exc).__name__}]") from None# ── Backup / export ───────────────────────────────────────────────────────@@ -1246,9 +1205,7 @@ class AresDatabase:backup_dir.mkdir(parents=True, exist_ok=True)output_path = str(backup_dir / f"ares_export_{ts}.json")- async with self._conn.execute(- "SELECT * FROM campaigns ORDER BY created_at DESC"- ) as cur:+ async with self._conn.execute("SELECT * FROM campaigns ORDER BY created_at DESC") as cur:campaigns = [dict(r) for r in await cur.fetchall()]for campaign in campaigns:@@ -1273,8 +1230,7 @@ class AresDatabase:with open(output_path, "w") as fh:json.dump(export, fh, indent=2, default=str)- logger.info("db_export_complete", path=output_path,- campaigns=len(campaigns))+ logger.info("db_export_complete", path=output_path, campaigns=len(campaigns))return output_pathasync def close(self) -> None:@@ -1289,9 +1245,7 @@ class AresDatabase:returncancellation_baseline = _cancel_count()caught_cancellations = [0]- close_task = asyncio.ensure_future(- self._close_primary_connection(connection)- )+ close_task = asyncio.ensure_future(self._close_primary_connection(connection))self._name_owned_task(close_task, "ares-sqlite-primary-close")try:await _await_task_completion(@@ -1314,7 +1268,8 @@ class AresDatabase:# ── Campaigns ─────────────────────────────────────────────────────────────async def save_campaign(self, c: Campaign) -> None:- await self._conn.execute("""+ await self._conn.execute(+ """INSERT INTO campaigns(id,name,client,operator,noise_profile,status,scope_json,targets_json,notes)VALUES(?,?,?,?,?,?,?,?,?)ON CONFLICT(id) DO UPDATE SET@@ -1323,16 +1278,23 @@ class AresDatabase:scope_json=excluded.scope_json, targets_json=excluded.targets_json,notes=excluded.notes,updated_at=datetime('now')- """, (c.id, c.name, c.client, c.operator, c.noise_profile.value,- c.status.value if hasattr(c.status, 'value') else str(c.status),- json.dumps([s.model_dump() for s in c.scope]),- json.dumps(c.targets), c.notes))+ """,+ (+ c.id,+ c.name,+ c.client,+ c.operator,+ c.noise_profile.value,+ c.status.value if hasattr(c.status, "value") else str(c.status),+ json.dumps([s.model_dump() for s in c.scope]),+ json.dumps(c.targets),+ c.notes,+ ),+ )await self._conn.commit()async def get_campaign(self, campaign_id: str) -> dict[str, Any] | None:- async with self._conn.execute(- "SELECT * FROM campaigns WHERE id=?", (campaign_id,)- ) as cur:+ async with self._conn.execute("SELECT * FROM campaigns WHERE id=?", (campaign_id,)) as cur:row = await cur.fetchone()return dict(row) if row else None@@ -1360,64 +1322,318 @@ class AresDatabase:return rows, totalasync def delete_campaign(self, campaign_id: str) -> bool:+ """Delete once through the stable compatibility receipt authority."""+ result = await self.delete_campaign_lifecycle(campaign_id)+ return result.result is FixedResult.APPLIED++ async def delete_campaign_lifecycle(+ self,+ campaign_id: str,+ *,+ operation_id: str | None = None,+ lifecycle_operation_id: str | None = None,+ principal_kind: str = "system",+ principal_subject_ref: str | None = None,+ principal_user_id: str | None = None,+ principal_authority_revision: int | None = None,+ ) -> OperationResult:+ """Delete a campaign with explicit immutable operation/principal binding."""+ if (+ operation_id is not None+ and lifecycle_operation_id is not None+ and operation_id != lifecycle_operation_id+ ):+ return OperationResult(FixedResult.INVALID_CONTRACT, None)+ resolved_operation_id = operation_id if operation_id is not None else lifecycle_operation_id+ if resolved_operation_id is None:+ if not valid_uuid(campaign_id):+ return OperationResult(FixedResult.INVALID_CONTRACT, None)+ resolved_operation_id = _campaign_delete_operation_id(campaign_id)+ if principal_subject_ref is None:+ if principal_kind != "system":+ return OperationResult(FixedResult.INVALID_CONTRACT, None)+ principal_subject_ref = SYSTEM_PRINCIPAL_SUBJECT_REF++ store = ExecutionLifecycleStore(self._conn, "sqlite")try:- await self._conn.execute("BEGIN")+ receipt_spec = store._receipt_spec(+ operation_id=resolved_operation_id,+ operation_code="campaign_delete",+ campaign_id=campaign_id,+ primary_target_id=campaign_id,+ principal_kind=principal_kind,+ principal_subject_ref=principal_subject_ref,+ principal_user_id=principal_user_id,+ principal_authority_revision=principal_authority_revision,+ )+ except ValueError:+ return OperationResult(FixedResult.INVALID_CONTRACT, None)++ async with store._transaction() as connection:+ await store._acquire_transaction_key(connection, resolved_operation_id)+ replay = await store._classify_receipt(connection, receipt_spec, current_revision=None)+ if replay is not None:+ return replay+ await store._acquire_transaction_key(connection, campaign_id)+ async with connection.execute(+ "SELECT singleton_id FROM execution_gateway_state WHERE singleton_id=1"+ ) as cursor:+ await cursor.fetchone()+ async with connection.execute(+ "SELECT id FROM campaigns WHERE id=?", (campaign_id,)+ ) as cursor:+ if await cursor.fetchone() is None:+ return OperationResult(FixedResult.NOT_FOUND_OR_PURGED, None)for statement in (- "DELETE FROM loot WHERE campaign_id=?",- "DELETE FROM credentials WHERE campaign_id=?",- "DELETE FROM hosts WHERE campaign_id=?",- "DELETE FROM findings WHERE campaign_id=?",+ "SELECT campaign_id FROM campaign_execution_authority_revisions "+ "WHERE campaign_id=?",+ "SELECT actor_user_id FROM campaign_execution_actor_grants "+ "WHERE campaign_id=? ORDER BY actor_user_id",+ "SELECT campaign_id FROM campaign_execution_destination_authorities "+ "WHERE campaign_id=?",+ "SELECT id FROM execution_approval_authorities WHERE campaign_id=? ORDER BY id",+ "SELECT id FROM logical_executions WHERE campaign_id=? ORDER BY id",+ "SELECT id FROM execution_attempts WHERE campaign_id=? ORDER BY ordinal,id",+ "SELECT attempt_id || ':' || CAST(ordinal AS TEXT) "+ "FROM execution_attempt_destination_observations "+ "WHERE campaign_id=? ORDER BY attempt_id,ordinal",+ "SELECT attempt_id || ':' || CAST(ordinal AS TEXT) "+ "FROM execution_attempt_credential_observations "+ "WHERE campaign_id=? ORDER BY attempt_id,ordinal",+ "SELECT id FROM campaign_execution_budgets WHERE campaign_id=? "+ "ORDER BY budget_kind,id",+ "SELECT id FROM campaign_execution_budget_ledger WHERE campaign_id=? "+ "ORDER BY budget_kind,id",+ "SELECT id FROM hosts WHERE campaign_id=? ORDER BY ip_address,id",+ "SELECT id FROM findings WHERE campaign_id=? ORDER BY id",+ "SELECT id FROM credentials WHERE campaign_id=? ORDER BY id",+ "SELECT id FROM loot WHERE campaign_id=? ORDER BY id",+ "SELECT id FROM execution_output_links WHERE campaign_id=? ORDER BY id",+ "SELECT id FROM execution_publication_outbox WHERE campaign_id=? ORDER BY id",):- await self._conn.execute(statement, (campaign_id,))- async with self._conn.execute(- "DELETE FROM campaigns WHERE id=?", (campaign_id,)+ async with connection.execute(statement, (campaign_id,)) as cursor:+ await cursor.fetchall()+ async with connection.execute(+ "SELECT 1 FROM execution_attempts WHERE campaign_id=? "+ "AND state IN ('accepted','queued','dispatching','running','cancelling',"+ "'settlement_pending') LIMIT 1",+ (campaign_id,),+ ) as cursor:+ if await cursor.fetchone() is not None:+ raise RuntimeError("Campaign lifecycle deletion is blocked")+ async with connection.execute(+ "SELECT 1 FROM logical_executions WHERE campaign_id=? "+ "AND closed_at IS NULL LIMIT 1",+ (campaign_id,),+ ) as cursor:+ if await cursor.fetchone() is not None:+ raise RuntimeError("Campaign lifecycle deletion is blocked")+ async with connection.execute(+ "SELECT 1 FROM execution_publication_outbox WHERE campaign_id=? "+ "AND publication_state='claimed' LIMIT 1",+ (campaign_id,),+ ) as cursor:+ if await cursor.fetchone() is not None:+ raise RuntimeError("Campaign lifecycle deletion is blocked")+ async with connection.execute(+ "SELECT id FROM execution_attempts WHERE campaign_id=? ORDER BY ordinal DESC",+ (campaign_id,),+ ) as cursor:+ attempt_ids = tuple(str(row[0]) for row in await cursor.fetchall())++ async def delete_exact(statement: str, expected: tuple[str, ...]) -> None:+ async with connection.execute(statement, (campaign_id,)) as cursor:+ observed = tuple(sorted(str(row[0]) for row in await cursor.fetchall()))+ if observed != tuple(sorted(expected)):+ raise RuntimeError("Campaign lifecycle deletion invariant failed")++ identities: dict[str, tuple[str, ...]] = {}+ for key, statement in (+ ("links", "SELECT id FROM execution_output_links WHERE campaign_id=?"),+ ("outbox", "SELECT id FROM execution_publication_outbox WHERE campaign_id=?"),+ ("approvals", "SELECT id FROM execution_attempt_approvals WHERE campaign_id=?"),+ (+ "approval_authorities",+ "SELECT id FROM execution_approval_authorities WHERE campaign_id=?",+ ),+ (+ "destination_observations",+ "SELECT attempt_id || ':' || CAST(ordinal AS TEXT) "+ "FROM execution_attempt_destination_observations WHERE campaign_id=?",+ ),+ (+ "credential_observations",+ "SELECT attempt_id || ':' || CAST(ordinal AS TEXT) "+ "FROM execution_attempt_credential_observations WHERE campaign_id=?",+ ),+ ("ledgers", "SELECT id FROM campaign_execution_budget_ledger WHERE campaign_id=?"),+ ("logical", "SELECT id FROM logical_executions WHERE campaign_id=?"),+ ("budgets", "SELECT id FROM campaign_execution_budgets WHERE campaign_id=?"),+ (+ "actor_grants",+ "SELECT actor_user_id FROM campaign_execution_actor_grants WHERE campaign_id=?",+ ),+ (+ "destination_authorities",+ "SELECT campaign_id FROM campaign_execution_destination_authorities "+ "WHERE campaign_id=?",+ ),+ ):+ async with connection.execute(statement, (campaign_id,)) as cursor:+ identities[key] = tuple(str(row[0]) for row in await cursor.fetchall())+ await delete_exact(+ "DELETE FROM execution_output_links WHERE campaign_id=? RETURNING id",+ identities["links"],+ )+ await delete_exact(+ "DELETE FROM execution_publication_outbox WHERE campaign_id=? RETURNING id",+ identities["outbox"],+ )+ await delete_exact(+ "DELETE FROM execution_attempt_approvals WHERE campaign_id=? RETURNING id",+ identities["approvals"],+ )+ await delete_exact(+ "DELETE FROM execution_approval_authorities WHERE campaign_id=? RETURNING id",+ identities["approval_authorities"],+ )+ await delete_exact(+ "DELETE FROM execution_attempt_destination_observations WHERE campaign_id=? "+ "RETURNING attempt_id || ':' || CAST(ordinal AS TEXT)",+ identities["destination_observations"],+ )+ await delete_exact(+ "DELETE FROM execution_attempt_credential_observations WHERE campaign_id=? "+ "RETURNING attempt_id || ':' || CAST(ordinal AS TEXT)",+ identities["credential_observations"],+ )+ await delete_exact(+ "DELETE FROM campaign_execution_budget_ledger WHERE campaign_id=? RETURNING id",+ identities["ledgers"],+ )+ for attempt_id in attempt_ids:+ async with connection.execute(+ "DELETE FROM execution_attempts WHERE id=? RETURNING id", (attempt_id,)+ ) as cursor:+ row = await cursor.fetchone()+ if row is None or str(row[0]) != attempt_id:+ raise RuntimeError("Campaign lifecycle deletion invariant failed")+ await delete_exact(+ "DELETE FROM logical_executions WHERE campaign_id=? RETURNING id",+ identities["logical"],+ )+ await delete_exact(+ "DELETE FROM campaign_execution_budgets WHERE campaign_id=? RETURNING id",+ identities["budgets"],+ )+ await delete_exact(+ "DELETE FROM campaign_execution_actor_grants WHERE campaign_id=? "+ "RETURNING actor_user_id",+ identities["actor_grants"],+ )+ await delete_exact(+ "DELETE FROM campaign_execution_destination_authorities WHERE campaign_id=? "+ "RETURNING campaign_id",+ identities["destination_authorities"],+ )+ async with connection.execute(+ "DELETE FROM campaign_execution_authority_revisions WHERE campaign_id=? "+ "RETURNING campaign_id",+ (campaign_id,),+ ) as cursor:+ authority_rows = await cursor.fetchall()+ if len(authority_rows) > 1:+ raise RuntimeError("Campaign lifecycle deletion invariant failed")+ for statement in (+ "DELETE FROM loot WHERE campaign_id=? RETURNING id",+ "DELETE FROM credentials WHERE campaign_id=? RETURNING id",+ "DELETE FROM hosts WHERE campaign_id=? RETURNING id",+ "DELETE FROM findings WHERE campaign_id=? RETURNING id",+ ):+ async with connection.execute(statement, (campaign_id,)) as cursor:+ await cursor.fetchall()+ await store._insert_receipt(+ connection,+ receipt_spec,+ result=FixedResult.APPLIED,+ exact_replay_code=FixedResult.REPLAYED,+ result_identity=campaign_id,+ result_revision=None,+ result_fields=(("deleted", True),),+ )+ async with connection.execute(+ "DELETE FROM campaigns WHERE id=? RETURNING id", (campaign_id,)) as cur:- changed = cur.rowcount- await self._conn.commit()- return changed > 0- except Exception:- await self._conn.rollback()- raise+ deleted_campaign = await cur.fetchall()+ if len(deleted_campaign) != 1 or str(deleted_campaign[0][0]) != campaign_id:+ raise RuntimeError("Campaign lifecycle deletion invariant failed")+ return OperationResult(FixedResult.APPLIED, None)# ── Findings ──────────────────────────────────────────────────────────────async def save_finding(self, campaign_id: str, f: Finding, module_id: str = "") -> None:"""FIX: module_id sekarang opsional (default '')."""- await self._conn.execute("""- INSERT OR REPLACE INTO findings+ await self._conn.execute(+ """+ INSERT INTO findings(id,campaign_id,module_id,title,description,severity,cvss_score,cvss_vector,confidence,mitre_technique,mitre_tactic,evidence_json,remediation,host,trace_id,validated,false_positive)VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)- """, (f.id, campaign_id, module_id or getattr(f, "module_id", ""),- f.title, f.description,- f.severity.value if hasattr(f.severity, "value") else str(f.severity),- getattr(f, "cvss_score", 0.0), getattr(f, "cvss_vector", ""),- f.confidence, f.mitre_technique, f.mitre_tactic,- json.dumps(f.evidence), f.remediation, f.host,- getattr(f, "trace_id", ""), int(bool(getattr(f, "validated", False))),- int(bool(getattr(f, "false_positive", False)))))+ ON CONFLICT(id) DO UPDATE SET+ module_id=excluded.module_id,title=excluded.title,+ description=excluded.description,severity=excluded.severity,+ cvss_score=excluded.cvss_score,cvss_vector=excluded.cvss_vector,+ confidence=excluded.confidence,mitre_technique=excluded.mitre_technique,+ mitre_tactic=excluded.mitre_tactic,evidence_json=excluded.evidence_json,+ remediation=excluded.remediation,host=excluded.host,+ trace_id=excluded.trace_id,validated=excluded.validated,+ false_positive=excluded.false_positive+ """,+ (+ f.id,+ campaign_id,+ module_id or getattr(f, "module_id", ""),+ f.title,+ f.description,+ f.severity.value if hasattr(f.severity, "value") else str(f.severity),+ getattr(f, "cvss_score", 0.0),+ getattr(f, "cvss_vector", ""),+ f.confidence,+ f.mitre_technique,+ f.mitre_tactic,+ json.dumps(f.evidence),+ f.remediation,+ f.host,+ getattr(f, "trace_id", ""),+ int(bool(getattr(f, "validated", False))),+ int(bool(getattr(f, "false_positive", False))),+ ),+ )await self._conn.commit()async def list_findings(self,campaign_id: str,- page: int = 1,- per_page: int = 50,- severity: str | None = None,+ page: int = 1,+ per_page: int = 50,+ severity: str | None = None,false_positive: bool | None = None,- validated: bool | None = None,+ validated: bool | None = None,) -> tuple[list[dict[str, Any]], int]:conditions = ["campaign_id=?"]params_list: list[Any] = [campaign_id]if severity:- conditions.append("severity=?"); params_list.append(severity)+ conditions.append("severity=?")+ params_list.append(severity)if false_positive is not None:- conditions.append("false_positive=?"); params_list.append(int(false_positive))+ conditions.append("false_positive=?")+ params_list.append(int(false_positive))if validated is not None:- conditions.append("validated=?"); params_list.append(int(validated))+ conditions.append("validated=?")+ params_list.append(int(validated))- where = " AND ".join(conditions)+ where = " AND ".join(conditions)offset = (page - 1) * per_pageasync with self._conn.execute(@@ -1427,14 +1643,14 @@ class AresDatabase:async with self._conn.execute(f"SELECT * FROM findings WHERE {where} ORDER BY discovered_at DESC LIMIT ? OFFSET ?",- params_list + [per_page, offset]+ params_list + [per_page, offset],) as cur:rows = [dict(r) for r in await cur.fetchall()]return rows, totalasync def get_findings(self,- campaign_id: str,+ campaign_id: str,confirmed_only: bool = False,) -> list[dict[str, Any]]:"""Return flat list of all findings for a campaign (no pagination)."""@@ -1458,7 +1674,12 @@ class AresDatabase:) as cur:rows = await cur.fetchall()stats: dict[str, Any] = {- "total": 0, "critical": 0, "high": 0, "medium": 0, "low": 0, "info": 0,+ "total": 0,+ "critical": 0,+ "high": 0,+ "medium": 0,+ "low": 0,+ "info": 0,}for r in rows:sev = r["severity"]@@ -1491,10 +1712,7 @@ class AresDatabase:(period,),) as cur:rows = await cur.fetchall()- series = [- {"date": str(row["finding_date"]), "count": int(row["n"])}- for row in rows- ]+ series = [{"date": str(row["finding_date"]), "count": int(row["n"])} for row in rows]return {"period": period,"label": "Security signals this cycle",@@ -1548,12 +1766,8 @@ class AresDatabase:index = max(0, min(len(durations) - 1, int(len(durations) * fraction + 0.999999) - 1))return round(durations[index], 1)- recent_cutoff = (- datetime.now(timezone.utc) - timedelta(seconds=60)- ).isoformat()- recent_runs = sum(- 1 for row in run_rows if str(row["completed_at"]) >= recent_cutoff- )+ recent_cutoff = (datetime.now(timezone.utc) - timedelta(seconds=60)).isoformat()+ recent_runs = sum(1 for row in run_rows if str(row["completed_at"]) >= recent_cutoff)async with self._conn.execute("""@@ -1592,22 +1806,23 @@ class AresDatabase:async def campaign_summary(self, campaign_id: str) -> dict[str, Any]:"""High-level stats for a campaign."""findings = await self.get_findings(campaign_id)- hosts = await self.get_hosts(campaign_id)- creds = await self.get_credentials(campaign_id)- loot = await self.get_loot(campaign_id)+ hosts = await self.get_hosts(campaign_id)+ creds = await self.get_credentials(campaign_id)+ loot = await self.get_loot(campaign_id)return {- "campaign_id": campaign_id,- "findings": findings,- "finding_count": len(findings),- "host_count": len(hosts),+ "campaign_id": campaign_id,+ "findings": findings,+ "finding_count": len(findings),+ "host_count": len(hosts),"credential_count": len(creds),- "loot_count": len(loot),+ "loot_count": len(loot),}# ── Hosts ─────────────────────────────────────────────────────────────────async def upsert_host(self, h: Host) -> str:- await self._conn.execute("""+ await self._conn.execute(+ """INSERT INTO hosts(id,campaign_id,ip_address,hostname,fqdn,os,os_version,domain,is_dc,open_ports_json,tags_json)VALUES(?,?,?,?,?,?,?,?,?,?,?)@@ -1615,11 +1830,31 @@ class AresDatabase:hostname=excluded.hostname, fqdn=excluded.fqdn, os=excluded.os,is_dc=excluded.is_dc, open_ports_json=excluded.open_ports_json,tags_json=excluded.tags_json, last_seen=datetime('now')- """, (h.id, h.campaign_id, h.ip_address, h.hostname, h.fqdn,- h.os, h.os_version, h.domain, int(h.is_dc),- json.dumps(h.open_ports), json.dumps(h.tags)))+ """,+ (+ h.id,+ h.campaign_id,+ h.ip_address,+ h.hostname,+ h.fqdn,+ h.os,+ h.os_version,+ h.domain,+ int(h.is_dc),+ json.dumps(h.open_ports),+ json.dumps(h.tags),+ ),+ )+ async with self._conn.execute(+ "SELECT id FROM hosts WHERE campaign_id=? AND ip_address=?",+ (h.campaign_id, h.ip_address),+ ) as cursor:+ row = await cursor.fetchone()+ if row is None:+ await self._conn.rollback()+ raise RuntimeError("Canonical host persistence failed")await self._conn.commit()- return h.id+ return str(row["id"])async def get_hosts(self, campaign_id: str) -> list[dict]:"""FIX: method getter yang sebelumnya tidak ada."""@@ -1632,12 +1867,29 @@ class AresDatabase:# ── Credentials ───────────────────────────────────────────────────────────async def save_credential(self, c: DBCredential) -> None:- await self._conn.execute("""- INSERT OR REPLACE INTO credentials+ await self._conn.execute(+ """+ INSERT INTO credentials(id,campaign_id,host_id,username,secret_enc,cred_type,domain,source_module,notes)VALUES(?,?,?,?,?,?,?,?,?)- """, (c.id, c.campaign_id, c.host_id, c.username,- self._enc_val(c.secret), c.cred_type, c.domain, c.source_module, c.notes))+ ON CONFLICT(id) DO UPDATE SET+ host_id=excluded.host_id,username=excluded.username,+ secret_enc=excluded.secret_enc,cred_type=excluded.cred_type,+ domain=excluded.domain,source_module=excluded.source_module,+ notes=excluded.notes+ """,+ (+ c.id,+ c.campaign_id,+ c.host_id,+ c.username,+ self._enc_val(c.secret),+ c.cred_type,+ c.domain,+ c.source_module,+ c.notes,+ ),+ )await self._conn.commit()async def save_credential_preencrypted(self, c: DBCredential) -> None:@@ -1647,7 +1899,8 @@ class AresDatabase:Uses INSERT OR IGNORE so re-running after a crash doesn't overwriteexisting secrets with the same ID."""- await self._conn.execute("""+ await self._conn.execute(+ """INSERT INTO credentials(id,campaign_id,host_id,username,secret_enc,cred_type,domain,source_module,notes)VALUES(?,?,?,?,?,?,?,?,?)@@ -1655,9 +1908,19 @@ class AresDatabase:secret_enc = excluded.secret_enc,source_module = excluded.source_module,notes = excluded.notes- """, (c.id, c.campaign_id, c.host_id, c.username,- c.secret, # already vault-encrypted — store verbatim- c.cred_type, c.domain, c.source_module, c.notes))+ """,+ (+ c.id,+ c.campaign_id,+ c.host_id,+ c.username,+ c.secret, # already vault-encrypted — store verbatim+ c.cred_type,+ c.domain,+ c.source_module,+ c.notes,+ ),+ )await self._conn.commit()async def load_credentials_raw(self, campaign_id: str) -> list[dict]:@@ -1668,7 +1931,7 @@ class AresDatabase:"""async with self._conn.execute("SELECT * FROM credentials WHERE campaign_id=? ORDER BY captured_at DESC",- (campaign_id,)+ (campaign_id,),) as cur:return [dict(r) for r in await cur.fetchall()]@@ -1692,16 +1955,37 @@ class AresDatabase:async def save_loot(self, l: Loot) -> None:content_str = json.dumps(l.content) if isinstance(l.content, (dict, list)) else l.content- await self._conn.execute("""- INSERT OR REPLACE INTO loot+ await self._conn.execute(+ """+ INSERT INTO loot(id,campaign_id,host_id,loot_type,name,description,content_enc,path_on_target,source_module,tags_json)VALUES(?,?,?,?,?,?,?,?,?,?)- """, (l.id, l.campaign_id, l.host_id, l.loot_type, l.name, l.description,- self._enc_val(content_str), l.path_on_target, l.source_module,- json.dumps(l.tags)))+ ON CONFLICT(id) DO UPDATE SET+ host_id=excluded.host_id,loot_type=excluded.loot_type,+ name=excluded.name,description=excluded.description,+ content_enc=excluded.content_enc,path_on_target=excluded.path_on_target,+ source_module=excluded.source_module,tags_json=excluded.tags_json+ """,+ (+ l.id,+ l.campaign_id,+ l.host_id,+ l.loot_type,+ l.name,+ l.description,+ self._enc_val(content_str),+ l.path_on_target,+ l.source_module,+ json.dumps(l.tags),+ ),+ )await self._conn.commit()+ def execution_lifecycle_store(self) -> ExecutionLifecycleStore:+ """Return the additive internal lifecycle persistence primitive."""+ return ExecutionLifecycleStore(self._conn, "sqlite")+async def get_loot(self, campaign_id: str, decrypt: bool = False) -> list[dict]:"""FIX: method getter yang sebelumnya tidak ada."""async with self._conn.execute(@@ -1769,11 +2053,17 @@ class AresDatabase:# ── Audit log ─────────────────────────────────────────────────────────────- async def audit(self, actor: str, action: str, detail: str = "",- campaign_id: str | None = None, module_id: str | None = None) -> None:+ async def audit(+ self,+ actor: str,+ action: str,+ detail: str = "",+ campaign_id: str | None = None,+ module_id: str | None = None,+ ) -> None:await self._conn.execute("INSERT INTO audit_log(campaign_id,actor,action,detail,module_id) VALUES(?,?,?,?,?)",- (campaign_id, actor, action, detail, module_id)+ (campaign_id, actor, action, detail, module_id),)await self._conn.commit()@@ -1785,7 +2075,7 @@ class AresDatabase:user_id = str(uuid.uuid4())await self._conn.execute("INSERT INTO users(id,username,hashed_password,role,created_by) VALUES(?,?,?,?,?)",- (user_id, username, hash_password(password), role, created_by)+ (user_id, username, hash_password(password), role, created_by),)await self._conn.commit()logger.info("user_created", username=username, role=role, by=created_by)@@ -1853,9 +2143,7 @@ class AresDatabase:return userasync def user_exists(self, username: str) -> bool:- async with self._conn.execute(- "SELECT 1 FROM users WHERE username=?", (username,)- ) as cur:+ async with self._conn.execute("SELECT 1 FROM users WHERE username=?", (username,)) as cur:return (await cur.fetchone()) is not Noneasync def update_password(self, user_id: str, new_hash: str) -> None:@@ -1877,28 +2165,32 @@ class AresDatabase:n = (await cur.fetchone())["n"]if n == 0:await self.create_user("admin", admin_password, "team_lead", "bootstrap")- logger.warning("default_admin_created",- msg="CHANGE admin password immediately: POST /auth/change-password")+ logger.warning(+ "default_admin_created",+ msg="CHANGE admin password immediately: POST /auth/change-password",+ )return Truereturn False# ── API Keys (v5) ─────────────────────────────────────────────────────────async def create_api_key(- self, user_id: str, name: str, scopes: str = "read",+ self,+ user_id: str,+ name: str,+ scopes: str = "read",expires_days: int | None = None,) -> tuple[str, str]:- raw_key = "ares_" + secrets.token_urlsafe(40)+ raw_key = "ares_" + secrets.token_urlsafe(40)key_prefix = raw_key[:12]- key_id = str(uuid.uuid4())+ key_id = str(uuid.uuid4())expires_at = Noneif expires_days:- expires_at = (datetime.now(timezone.utc) +- timedelta(days=expires_days)).isoformat()+ expires_at = (datetime.now(timezone.utc) + timedelta(days=expires_days)).isoformat()await self._conn.execute("INSERT INTO api_keys(id,user_id,name,key_hash,key_prefix,scopes,expires_at) ""VALUES(?,?,?,?,?,?,?)",- (key_id, user_id, name, hash_password(raw_key), key_prefix, scopes, expires_at)+ (key_id, user_id, name, hash_password(raw_key), key_prefix, scopes, expires_at),)await self._conn.commit()logger.info("api_key_created", user_id=user_id, name=name, prefix=key_prefix)@@ -1920,7 +2212,7 @@ class AresDatabase:AND julianday(ak.expires_at) > julianday('now')))""",- (prefix,)+ (prefix,),) as cur:rows = [dict(r) for r in await cur.fetchall()]@@ -1959,14 +2251,15 @@ class AresDatabase:async def list_api_keys(self, user_id: str) -> list[dict[str, Any]]:async with self._conn.execute("SELECT id,name,key_prefix,scopes,is_active,last_used,expires_at,created_at "- "FROM api_keys WHERE user_id=? AND is_active=1 ORDER BY created_at DESC", (user_id,)+ "FROM api_keys WHERE user_id=? AND is_active=1 ORDER BY created_at DESC",+ (user_id,),) as cur:return [dict(r) for r in await cur.fetchall()]async def revoke_api_key(self, key_id: str, user_id: str) -> bool:async with self._conn.execute("UPDATE api_keys SET is_active=0 WHERE id=? AND user_id=? AND is_active=1",- (key_id, user_id)+ (key_id, user_id),) as cur:changed = cur.rowcountawait self._conn.commit()@@ -2032,9 +2325,7 @@ class AresDatabase:try:open_cancellation_baseline = _cancel_count()open_cancellations = [0]- open_task = asyncio.ensure_future(- self._open_websocket_ticket_connection()- )+ open_task = asyncio.ensure_future(self._open_websocket_ticket_connection())self._name_owned_task(open_task,"ares-sqlite-websocket-ticket-connect",@@ -2074,11 +2365,7 @@ class AresDatabase:committed = Truetransaction_started = Falseexcept BaseException:- if (- connection is not None- and transaction_started- and not committed- ):+ if connection is not None and transaction_started and not committed:cleanup_cancellation_baseline = _cancel_count()cleanup_cancellations = [0]cleanup_action = (@@ -2096,14 +2383,10 @@ class AresDatabase:finally:if connection is not None:close_cancellation_baseline = (- commit_cancellation_baseline- if committed- else _cancel_count()+ commit_cancellation_baseline if committed else _cancel_count())close_cancellations = (- commit_cancellations- if committed- else noncommit_close_cancellations+ commit_cancellations if committed else noncommit_close_cancellations)await self._finish_websocket_ticket_cleanup(connection.close(),@@ -2393,9 +2676,7 @@ class AresDatabase:or handle.bearer_auth_epoch is None):return None- source_expiry = format_sqlite_utc(- handle.bearer_expires_at- )+ source_expiry = format_sqlite_utc(handle.bearer_expires_at)async with connection.execute("""SELECT u.id, u.username, u.role@@ -2436,9 +2717,7 @@ class AresDatabase:),) as cursor:row = await cursor.fetchone()- if row is None or not is_valid_websocket_principal_role(- row["role"]- ):+ if row is None or not is_valid_websocket_principal_role(row["role"]):return Nonereturn WebSocketTicketPrincipal(user_id=row["id"],@@ -2448,8 +2727,7 @@ class AresDatabase:)if (- handle.credential_kind- is not WebSocketTicketCredentialKind.API_KEY+ handle.credential_kind is not WebSocketTicketCredentialKind.API_KEYor handle.api_key_id is Noneor handle.required_scope != "read"):@@ -2495,9 +2773,7 @@ class AresDatabase:),) as cursor:row = await cursor.fetchone()- if row is None or not is_valid_websocket_principal_role(- row["role"]- ):+ if row is None or not is_valid_websocket_principal_role(row["role"]):return Nonescopes = normalize_api_key_scopes(row["scopes"])if not set(scopes).intersection({"read", "write", "admin"}):@@ -2659,16 +2935,20 @@ class AresDatabase:(username,),) as cursor:row = await cursor.fetchone()- if row is None or int(row["is_active"]) != 1 or not verify_password(- password, row["hashed_password"]+ if (+ row is None+ or int(row["is_active"]) != 1+ or not verify_password(password, row["hashed_password"])):return SessionIssueResult(SessionIssueStatus.INVALID)- family_id, raw_token, absolute_expiry = (- await self._insert_initial_family_token_with_expiry(- tx,- user_id=row["id"],- auth_epoch=int(row["auth_epoch"]),- )+ (+ family_id,+ raw_token,+ absolute_expiry,+ ) = await self._insert_initial_family_token_with_expiry(+ tx,+ user_id=row["id"],+ auth_epoch=int(row["auth_epoch"]),)access_token = token_factory({@@ -2702,20 +2982,19 @@ class AresDatabase:return await self._run_refresh_family_transaction(_login)- async def _legacy_create_refresh_token(- self, user_id: str, expires_days: int = 30- ) -> str:+ async def _legacy_create_refresh_token(self, user_id: str, expires_days: int = 30) -> str:import hashlib+# Generate cryptographically strong random token- raw_token = secrets.token_urlsafe(48) # 384 bits — URL-safe, client sees this+ raw_token = secrets.token_urlsafe(48) # 384 bits — URL-safe, client sees thistoken_hash = hashlib.sha256(raw_token.encode()).hexdigest() # stored in DBexpires_at = (datetime.now(timezone.utc) + timedelta(days=expires_days)).isoformat()await self._conn.execute("INSERT INTO refresh_tokens(id,user_id,expires_at) VALUES(?,?,?)",- (token_hash, user_id, expires_at)+ (token_hash, user_id, expires_at),)await self._conn.commit()- return raw_token # client gets raw; DB stores only hash+ return raw_token # client gets raw; DB stores only hashasync def _open_refresh_rotation_connection(self) -> aiosqlite.Connection:return await aiosqlite.connect(@@ -2949,9 +3228,7 @@ class AresDatabase:try:open_cancellation_baseline = _cancel_count()open_cancellations = [0]- open_task = asyncio.ensure_future(- self._open_refresh_rotation_connection()- )+ open_task = asyncio.ensure_future(self._open_refresh_rotation_connection())self._name_owned_task(open_task,"ares-sqlite-refresh-connect",@@ -3010,9 +3287,7 @@ class AresDatabase:row = dict(row)new_raw = secrets.token_urlsafe(48)new_hash = hashlib.sha256(new_raw.encode()).hexdigest()- expires_at = (- datetime.now(timezone.utc) + timedelta(days=30)- ).isoformat()+ expires_at = (datetime.now(timezone.utc) + timedelta(days=30)).isoformat()await self._insert_refresh_successor(tx,new_hash,@@ -3043,9 +3318,7 @@ class AresDatabase:cleanup_cancellation_baseline = _cancel_count()cleanup_cancellations = [0]cleanup_action = (- "rollback_after_commit_failure"- if commit_started- else "rollback_before_commit"+ "rollback_after_commit_failure" if commit_started else "rollback_before_commit")await self._finish_refresh_rotation_cleanup(tx.rollback(),@@ -3057,14 +3330,10 @@ class AresDatabase:finally:if tx is not None:close_cancellation_baseline = (- commit_cancellation_baseline- if committed- else _cancel_count()+ commit_cancellation_baseline if committed else _cancel_count())close_cancellations = (- commit_cancellations- if committed- else noncommit_close_cancellations+ commit_cancellations if committed else noncommit_close_cancellations)await self._finish_refresh_rotation_cleanup(tx.close(),@@ -3165,8 +3434,7 @@ class AresDatabase:reason="logout_current",)await tx.execute(- "INSERT OR IGNORE INTO revoked_access_tokens(jti,user_id,expires_at) "- "VALUES(?,?,?)",+ "INSERT OR IGNORE INTO revoked_access_tokens(jti,user_id,expires_at) VALUES(?,?,?)",(jti, user_id, format_sqlite_utc(expires_at)),)if changed:@@ -3212,8 +3480,7 @@ class AresDatabase:else "logout_cookie_replay_family_revoked")await tx.execute(- "INSERT INTO audit_log(actor,action,detail) VALUES("- "'auth-system',?,'')",+ "INSERT INTO audit_log(actor,action,detail) VALUES('auth-system',?,'')",(action,),)return SessionRevocationResult(SessionRevocationStatus.REVOKED)@@ -3230,23 +3497,18 @@ class AresDatabase:) -> SessionRevocationResult:async def _revoke(tx: aiosqlite.Connection) -> SessionRevocationResult:async with tx.execute(- "UPDATE users SET auth_epoch=auth_epoch+1 "- "WHERE id=? AND is_active=1",+ "UPDATE users SET auth_epoch=auth_epoch+1 WHERE id=? AND is_active=1",(user_id,),) as cursor:if cursor.rowcount != 1:return SessionRevocationResult(SessionRevocationStatus.INVALID)- await self._revoke_family_rows(- tx, user_id=user_id, reason="logout_all"- )+ await self._revoke_family_rows(tx, user_id=user_id, reason="logout_all")await tx.execute(- "INSERT OR IGNORE INTO revoked_access_tokens(jti,user_id,expires_at) "- "VALUES(?,?,?)",+ "INSERT OR IGNORE INTO revoked_access_tokens(jti,user_id,expires_at) VALUES(?,?,?)",(jti, user_id, format_sqlite_utc(expires_at)),)await tx.execute(- "INSERT INTO audit_log(actor,action,detail) VALUES("- "'auth-system','logout_all','')"+ "INSERT INTO audit_log(actor,action,detail) VALUES('auth-system','logout_all','')")return SessionRevocationResult(SessionRevocationStatus.REVOKED)@@ -3281,8 +3543,7 @@ class AresDatabase:return Falseawait self._revoke_family_rows(tx, user_id=user_id, reason=reason)await tx.execute(- "INSERT INTO audit_log(actor,action,detail) VALUES("- "'auth-system',?,'')",+ "INSERT INTO audit_log(actor,action,detail) VALUES('auth-system',?,'')",(reason,),)return True@@ -3291,9 +3552,7 @@ class AresDatabase:async def revoke_all_refresh_tokens(self, user_id: str) -> None:async def _revoke(tx: aiosqlite.Connection) -> None:- await self._revoke_family_rows(- tx, user_id=user_id, reason="operator_revoke"- )+ await self._revoke_family_rows(tx, user_id=user_id, reason="operator_revoke")await self._run_refresh_family_transaction(_revoke)@@ -3306,21 +3565,29 @@ class AresDatabase:async def save_bypass_outcome(self,technique_id: str,- edr_vendor: str,- edr_version: str,- success: bool,- campaign_id: str,- notes: str = "",+ edr_vendor: str,+ edr_version: str,+ success: bool,+ campaign_id: str,+ notes: str = "",) -> None:"""Persist bypass technique outcome for cross-session learning."""import time as _time+try:await self._conn.execute("""INSERT INTO bypass_outcomes(technique_id, edr_vendor, edr_version, success, campaign_id, notes, ts)VALUES (?, ?, ?, ?, ?, ?, ?)""",- (technique_id, edr_vendor, edr_version,- int(success), campaign_id, notes[:500], _time.time()),+ (+ technique_id,+ edr_vendor,+ edr_version,+ int(success),+ campaign_id,+ notes[:500],+ _time.time(),+ ),)await self._conn.commit()except Exception:@@ -3330,22 +3597,30 @@ class AresDatabase:"""INSERT INTO bypass_outcomes(technique_id, edr_vendor, edr_version, success, campaign_id, notes, ts)VALUES (?, ?, ?, ?, ?, ?, ?)""",- (technique_id, edr_vendor, edr_version,- int(success), campaign_id, notes[:500], _time.time()),+ (+ technique_id,+ edr_vendor,+ edr_version,+ int(success),+ campaign_id,+ notes[:500],+ _time.time(),+ ),)await self._conn.commit()async def get_bypass_success_rate(self,technique_id: str,- edr_vendor: str,- min_samples: int = 3,+ edr_vendor: str,+ min_samples: int = 3,) -> float | None:"""Return historical success rate for a bypass technique against an EDR vendor.Returns None if fewer than min_samples recorded."""import time as _time+try:async with self._conn.execute("""SELECT COUNT(*) as total, COALESCE(SUM(success), 0) as successes@@ -3377,16 +3652,15 @@ class AresDatabase:)await self._conn.commit()-async def purge_expired_tokens(self) -> int:async with self._conn.execute(- "DELETE FROM refresh_token_families "- "WHERE julianday(retain_until) <= julianday('now')"+ "DELETE FROM refresh_token_families WHERE julianday(retain_until) <= julianday('now')") as cur:n = cur.rowcountawait self._conn.commit()await self.purge_expired_websocket_tickets()return n+# Backward-compat aliasCredential = DBCredential # noqadiff --git a/ares/db/execution_lifecycle.py b/ares/db/execution_lifecycle.pynew file mode 100644index 0000000..7f57930--- /dev/null+++ b/ares/db/execution_lifecycle.py@@ -0,0 +1,14180 @@+# ruff: noqa: E501, S608+"""Authoritative revision-0010 execution-lifecycle persistence primitives.++This module is additive and has no live execution consumer. It owns the exact+SQLite/PostgreSQL lifecycle catalog, fixed persistence enums, sanitized CAS+results, and internal stores used by migration and persistence tests. It never+accepts raw module parameters, destinations, credentials, evidence, exception+text, URLs, or DSNs.+"""++from __future__ import annotations++import asyncio+import hashlib+import ipaddress+import json+import re+import struct+from collections.abc import AsyncIterator, Awaitable, Callable, Mapping, Sequence+from contextlib import asynccontextmanager, suppress+from dataclasses import dataclass+from enum import Enum, IntEnum+from typing import Any, Final++RUNTIME_GENERATION: Final = 10+LEGACY_SCHEMA_VERSION: Final = 9+REQUEST_CONTRACT_VERSION: Final = 1+POLICY_CONTRACT_VERSION: Final = 1+DESCRIPTOR_CONTRACT_VERSION: Final = "ares.module-descriptor.v2"+MASK_VERSION: Final = 1+MAX_I53: Final = 9_007_199_254_740_991+MIN_TIMEOUT_MS: Final = 1_000+MAX_TIMEOUT_MS: Final = 86_400_000+RECOVERY_WINDOW_MS: Final = 86_400_000+OUTBOX_LEASE_MS: Final = 60_000+SYSTEM_PRINCIPAL_SUBJECT_REF: Final = "004cb934-3a47-4cd0-b0cb-a5b18df76a48"+PRINCIPAL_KINDS: Final[tuple[str, ...]] = ("actor", "resolver", "worker", "system")+++LIFECYCLE_LOCK_ORDER = (+ "transaction_key",+ "gateway",+ "authority",+ "logical_execution",+ "attempt",+ "approval",+ "budget",+ "ledger",+ "output_target",+ "output_link",+ "outbox",+ "operation_receipt",+)+++class AttemptState(str, Enum):+ REJECTED = "rejected"+ BLOCKED = "blocked"+ ACCEPTED = "accepted"+ QUEUED = "queued"+ DISPATCHING = "dispatching"+ RUNNING = "running"+ CANCELLING = "cancelling"+ SETTLEMENT_PENDING = "settlement_pending"+ SUCCEEDED = "succeeded"+ PARTIAL = "partial"+ FAILED = "failed"+ SKIPPED = "skipped"+ CANCELLED = "cancelled"+ TIMED_OUT = "timed_out"+ INDETERMINATE = "indeterminate"+++class OutcomeCode(str, Enum):+ POLICY_REJECTED = "policy_rejected"+ POLICY_BLOCKED = "policy_blocked"+ CONFIRMED_SUCCESS = "confirmed_success"+ CONFIRMED_PARTIAL = "confirmed_partial"+ ORCHESTRATION_SKIPPED = "orchestration_skipped"+ CONFIRMED_CANCELLED_NO_RESULT = "confirmed_cancelled_no_result"+ CONFIRMED_TIMEOUT_TERMINATED = "confirmed_timeout_terminated"+ UNKNOWN_AFTER_RECOVERY = "unknown_after_recovery"+ CONFIRMED_FAILURE_NO_DISPATCH = "confirmed_failure_no_dispatch"+ CONFIRMED_FAILURE = "confirmed_failure"+++class FixedResult(str, Enum):+ APPLIED = "applied"+ REPLAYED = "replayed"+ REPLAYED_BOUND_CHILD = "replayed_bound_child"+ REPLAYED_CLOSED = "replayed_closed"+ SUPERSEDED = "superseded"+ NOT_FOUND_OR_PURGED = "not_found_or_purged"+ ALREADY_EXISTS = "already_exists"+ ALREADY_CLOSED = "already_closed"+ RETRY_AUTHORITY_UNRESOLVED = "retry_authority_unresolved"+ AUTHORITY_STALE = "authority_stale"+ CAPACITY_UNAVAILABLE = "capacity_unavailable"+ INCONSISTENT_BUDGET_SET = "inconsistent_budget_set"+ CONFLICT_STATE = "conflict_state"+ CONFLICT_REVISION = "conflict_revision"+ CONFLICT_OWNER = "conflict_owner"+ CONFLICT_GENERATION = "conflict_generation"+ CONFLICT_OPERATION = "conflict_operation"+ INVALID_CONTRACT = "invalid_contract"+ INVARIANT_FAILURE = "invariant_failure"+++class PolicyReasonBit(IntEnum):+ INVALID_CONTRACT = 1+ INCONSISTENT_CONTRACT = 2+ INVALID_REQUEST = 4+ DESCRIPTOR_UNTRUSTED = 8+ DESCRIPTOR_BINDING_INVALID = 16+ DESCRIPTOR_INCOMPLETE = 32+ STATIC_POLICY_UNAVAILABLE = 64+ AUTHORITY_RESOLUTION_REQUIRED = 128+ STALE_AUTHORITY = 256+ ACTOR_UNAUTHENTICATED = 512+ ACTOR_INACTIVE = 1_024+ CAMPAIGN_INACTIVE = 2_048+ CAMPAIGN_UNAUTHORIZED = 4_096+ INSUFFICIENT_ROLE = 8_192+ HIGH_NOISE_ROLE_REQUIRED = 16_384+ APPROVAL_REQUIRED = 32_768+ APPROVAL_STALE = 65_536+ APPROVAL_BINDING_INVALID = 131_072+ CAPABILITY_REQUIRED = 262_144+ DESTINATION_RESOLUTION_REQUIRED = 524_288+ DESTINATION_OUT_OF_SCOPE = 1_048_576+ CREDENTIAL_AUTHORITY_REQUIRED = 2_097_152+ CREDENTIAL_AUTHORITY_STALE = 4_194_304+ RAW_CREDENTIAL_FORBIDDEN = 8_388_608+ AMBIENT_CREDENTIAL_FORBIDDEN = 16_777_216+ CREDENTIAL_HANDLE_POLICY_VIOLATION = 33_554_432+ BUDGET_AUTHORITY_REQUIRED = 67_108_864+ BUDGET_AUTHORITY_STALE = 134_217_728+ BUDGET_CAPACITY_UNAVAILABLE = 268_435_456+ DESCRIPTOR_BLOCKED = 536_870_912+ PREVIEW_NOT_READY = 1_073_741_824+ LIFECYCLE_NOT_READY = 2_147_483_648+ RESULT_AUTHORITY_NOT_READY = 4_294_967_296+ TRANSPORT_NOT_READY = 8_589_934_592+ FUTURE_GATEWAY_INELIGIBLE = 17_179_869_184+++CAPABILITY_BITS_V1: Final[dict[str, int]] = {+ "network": 1,+ "execution": 2,+ "filesystem": 4,+ "process": 8,+}+DESCRIPTOR_BLOCKER_BITS_V1: Final[dict[str, int]] = {+ "ambient_credentials_forbidden": 1,+ "cancellation_ownership_unproven": 2,+ "dynamic_destination_unbounded": 4,+ "default_factory_unevaluated": 8,+ "llm_egress_policy_required": 16,+ "lifecycle_contract_unproven": 32,+ "raw_credential_input": 64,+ "result_authority_unproven": 128,+ "sensitive_nonempty_default": 256,+}++LEGAL_TRANSITIONS: Final[frozenset[tuple[AttemptState, AttemptState]]] = frozenset(+ {+ (AttemptState.ACCEPTED, AttemptState.QUEUED),+ (AttemptState.ACCEPTED, AttemptState.DISPATCHING),+ (AttemptState.ACCEPTED, AttemptState.CANCELLING),+ (AttemptState.ACCEPTED, AttemptState.SKIPPED),+ (AttemptState.ACCEPTED, AttemptState.FAILED),+ (AttemptState.QUEUED, AttemptState.DISPATCHING),+ (AttemptState.QUEUED, AttemptState.CANCELLING),+ (AttemptState.QUEUED, AttemptState.SKIPPED),+ (AttemptState.QUEUED, AttemptState.FAILED),+ (AttemptState.DISPATCHING, AttemptState.RUNNING),+ (AttemptState.DISPATCHING, AttemptState.CANCELLING),+ (AttemptState.DISPATCHING, AttemptState.FAILED),+ (AttemptState.DISPATCHING, AttemptState.SETTLEMENT_PENDING),+ (AttemptState.RUNNING, AttemptState.CANCELLING),+ (AttemptState.RUNNING, AttemptState.SUCCEEDED),+ (AttemptState.RUNNING, AttemptState.PARTIAL),+ (AttemptState.RUNNING, AttemptState.FAILED),+ (AttemptState.RUNNING, AttemptState.TIMED_OUT),+ (AttemptState.RUNNING, AttemptState.SETTLEMENT_PENDING),+ (AttemptState.CANCELLING, AttemptState.SUCCEEDED),+ (AttemptState.CANCELLING, AttemptState.PARTIAL),+ (AttemptState.CANCELLING, AttemptState.FAILED),+ (AttemptState.CANCELLING, AttemptState.CANCELLED),+ (AttemptState.CANCELLING, AttemptState.TIMED_OUT),+ (AttemptState.CANCELLING, AttemptState.SETTLEMENT_PENDING),+ (AttemptState.SETTLEMENT_PENDING, AttemptState.SUCCEEDED),+ (AttemptState.SETTLEMENT_PENDING, AttemptState.PARTIAL),+ (AttemptState.SETTLEMENT_PENDING, AttemptState.FAILED),+ (AttemptState.SETTLEMENT_PENDING, AttemptState.CANCELLED),+ (AttemptState.SETTLEMENT_PENDING, AttemptState.TIMED_OUT),+ (AttemptState.SETTLEMENT_PENDING, AttemptState.INDETERMINATE),+ }+)++LIFECYCLE_TABLES: Final[tuple[str, ...]] = (+ "logical_executions",+ "execution_attempts",+ "execution_actor_authority_revisions",+ "campaign_execution_authority_revisions",+ "campaign_execution_budgets",+ "execution_attempt_approvals",+ "campaign_execution_budget_ledger",+ "execution_output_links",+ "execution_publication_outbox",+ "execution_operation_receipts",+ "execution_gateway_state",+)++OPERATION_CODES: Final[tuple[str, ...]] = (+ "actor_authority_ensure",+ "actor_authority_invalidate",+ "campaign_authority_ensure",+ "campaign_authority_invalidate",+ "budget_configure",+ "budget_reserve",+ "budget_settle",+ "admission",+ "retry",+ "queue",+ "dispatch",+ "start",+ "cancellation_request",+ "cancellation_acknowledgement",+ "timeout",+ "settlement_pending",+ "lease_loss",+ "recovery_succeeded",+ "recovery_partial",+ "recovery_failed",+ "recovery_cancelled",+ "recovery_timed_out",+ "recovery_indeterminate",+ "terminal_succeeded",+ "terminal_partial",+ "terminal_failed",+ "terminal_skipped",+ "close_without_retry",+ "outbox_insert",+ "outbox_claim",+ "outbox_reclaim",+ "outbox_renew",+ "outbox_publish",+ "outbox_retryable_failure",+ "outbox_nonretryable_failure",+ "outbox_poison",+ "outbox_purge",+ "campaign_delete",+)++_RECEIPT_NO_EXPECTED_REVISION_CODES: Final[frozenset[str]] = frozenset(+ {+ "actor_authority_ensure",+ "campaign_authority_ensure",+ "budget_configure",+ "admission",+ "outbox_insert",+ "campaign_delete",+ }+)+_RECEIPT_TWO_EXPECTED_REVISION_CODES: Final[frozenset[str]] = frozenset(+ {"budget_reserve", "budget_settle"}+)+_RECEIPT_OUTBOX_OWNER_CODES: Final[frozenset[str]] = frozenset(+ {+ "outbox_claim",+ "outbox_reclaim",+ "outbox_renew",+ "outbox_publish",+ "outbox_retryable_failure",+ "outbox_nonretryable_failure",+ }+)+_RECEIPT_OUTBOX_NO_OWNER_CODES: Final[frozenset[str]] = frozenset(+ {"outbox_insert", "outbox_poison", "outbox_purge"}+)++# Generation 11 is deliberately additive. The generation-10 constants above are+# migration authority for revision 0010 and must never be widened in place.+RUNTIME_GENERATION_V11: Final = 11+ADMISSION_AUTHORITY_CONTRACT_V2: Final = 2+ADMISSION_AUTHORITY_CONTRACT_V3: Final = 3+TERMINAL_COMMIT_CONTRACT_VERSION_V3: Final = 3+MAX_TERMINAL_OUTPUTS_V3: Final = 256+DESTINATION_NORMALIZATION_VERSION: Final = 1+GATEWAY_AUTHORITY_TARGET_ID: Final = "05f6658b-0a58-4ce7-8ccf-0f30c1185103"++_TERMINAL_COMMIT_OPERATION_ID_DOMAIN_V3: Final = "terminal-commit-operation-id.v3"+_TERMINAL_COMMIT_ACTION_V3: Final = "commit-known-settled"+_TERMINAL_COMMIT_REQUEST_DOMAIN_V3: Final = "execution-terminal-commit.v3.request"+_TERMINAL_COMMIT_RESULT_DOMAIN_V3: Final = "execution-terminal-commit.v3.result"+_TERMINAL_COMMIT_LOCK_ORDER_V3: Final[tuple[str, ...]] = (+ "operation_transaction_key",+ "receipt_classification",+ "logical_execution_transaction_key",+ "attempt_transaction_key",+ "attempt",+ "ledger",+ "budget",+ "logical_execution",+ "output_target",+ "output_link",+ "outbox",+ "operation_receipt",+)++V11_AUTHORITY_TABLES: Final[tuple[str, ...]] = (+ "campaign_execution_actor_grants",+ "campaign_execution_destination_authorities",+ "execution_approval_authorities",+ "execution_attempt_destination_observations",+ "execution_attempt_credential_observations",+)++_V11_RESERVED_CAMPAIGN_EXECUTION_RELATIONS: Final[frozenset[str]] = frozenset(+ {+ "campaign_execution_actor_grants",+ "campaign_execution_authority_revisions",+ "campaign_execution_budget_ledger",+ "campaign_execution_budgets",+ "campaign_execution_destination_authorities",+ }+)++V11_ADDITIVE_OPERATION_CODES: Final[tuple[str, ...]] = (+ "gateway_authority_update",+ "actor_authority_activate",+ "actor_authority_update",+ "actor_authority_revoke",+ "campaign_authority_activate",+ "campaign_authority_update",+ "campaign_authority_revoke",+ "campaign_actor_grant_put",+ "campaign_actor_grant_revoke",+ "destination_authority_update",+ "destination_authority_revoke",+ "credential_authority_update",+ "credential_authority_revoke",+ "approval_authority_grant",+ "approval_authority_revoke",+)+V11_OPERATION_CODES: Final[tuple[str, ...]] = OPERATION_CODES + V11_ADDITIVE_OPERATION_CODES+_V11_RECEIPT_NO_EXPECTED_REVISION_CODES: Final[frozenset[str]] = (+ _RECEIPT_NO_EXPECTED_REVISION_CODES | {"approval_authority_grant"}+)+_V11_RECEIPT_OPTIONAL_EXPECTED_REVISION_CODES: Final[frozenset[str]] = frozenset(+ {"campaign_actor_grant_put"}+)++_UUID_SQLITE = (+ "length({c})=36 AND substr({c},9,1)='-' AND substr({c},14,1)='-' "+ "AND substr({c},19,1)='-' AND substr({c},24,1)='-' "+ "AND substr({c},15,1)='4' AND substr({c},20,1) IN ('8','9','a','b') "+ "AND lower({c})={c} AND length(replace({c},'-',''))=32 "+ "AND replace({c},'-','') NOT GLOB '*[^0-9a-f]*'"+)+_UUID_POSTGRES = (+ "{c} ~ '^[0-9a-f]{{8}}-[0-9a-f]{{4}}-4[0-9a-f]{{3}}-[89ab][0-9a-f]{{3}}-[0-9a-f]{{12}}$'"+)+_H64_SQLITE = "length({c})=64 AND lower({c})={c} AND {c} NOT GLOB '*[^0-9a-f]*'"+_H64_POSTGRES = "{c} ~ '^[0-9a-f]{{64}}$'"+_S128_SQLITE = (+ "length({c}) BETWEEN 1 AND 128 AND substr({c},1,1) GLOB '[a-z]' "+ "AND {c} NOT GLOB '*[^a-z0-9_.:-]*'"+)+_S128_POSTGRES = "char_length({c}) BETWEEN 1 AND 128 AND {c} ~ '^[a-z][a-z0-9_.:-]{{0,127}}$'"+++def _uuid_check(column: str, dialect: str) -> str:+ template = _UUID_POSTGRES if dialect == "postgresql" else _UUID_SQLITE+ return template.format(c=column)+++def _h64_check(column: str, dialect: str) -> str:+ template = _H64_POSTGRES if dialect == "postgresql" else _H64_SQLITE+ return template.format(c=column)+++def _s128_check(column: str, dialect: str) -> str:+ template = _S128_POSTGRES if dialect == "postgresql" else _S128_SQLITE+ return template.format(c=column)+++def _in(column: str, values: Sequence[str]) -> str:+ return f"{column} IN (" + ",".join(f"'{value}'" for value in values) + ")"+++def _distinct_nullable(columns: Sequence[str]) -> str:+ pairs = (+ f"({left} IS NULL OR {right} IS NULL OR {left}<>{right})"+ for index, left in enumerate(columns)+ for right in columns[index + 1 :]+ )+ return " AND ".join(pairs)+++INGRESS_CODES: Final[tuple[str, ...]] = (+ "api_module",+ "api_campaign_plan",+ "strategy",+ "goal_api",+ "goal_cli",+ "cli_module",+ "cli_chain",+ "sdk",+ "direct_engine",+ "collaboration",+ "worker_controller",+ "redis_cluster",+ "isolated_subprocess",+ "checkpoint_resume",+ "replay",+ "scheduled_background",+)+NOISE_CLASSES: Final[tuple[str, ...]] = ("silent", "local", "low", "medium", "high_noise")+APPROVAL_POLICIES: Final[tuple[str, ...]] = ("none", "attempt_bound")+EXTERNAL_EFFECT_CLASSES: Final[tuple[str, ...]] = (+ "read_only",+ "conditionally_mutating",+ "mutating",+ "local_analysis",+ "planning",+ "billable_nondeterministic_egress",+)+IDEMPOTENCY_CLASSES: Final[tuple[str, ...]] = (+ "proven_idempotent",+ "proven_non_idempotent",+ "conditional",+ "unproven_current_contract",+)+RETRY_POLICIES: Final[tuple[str, ...]] = (+ "after_revalidation",+ "blocked_unproven_prior_attempt",+ "never",+)+RETRY_DISPOSITIONS: Final[tuple[str, ...]] = (+ "not_applicable",+ "eligible",+ "forbidden",+ "child_bound",+ "closed_without_retry",+)+CANCELLATION_OWNERSHIP: Final[tuple[str, ...]] = (+ "owned",+ "not_applicable",+ "unproven_current_contract",+)+COMPENSATION_CLASSES: Final[tuple[str, ...]] = (+ "not_applicable",+ "supported",+ "unsupported",+ "unproven_current_contract",+)+TIMEOUT_ORIGINS: Final[tuple[str, ...]] = (+ "module_defined_bounded",+ "observed_legacy_engine_default",+ "unsupported_or_unbounded",+)+TIMEOUT_SETTLEMENTS: Final[tuple[str, ...]] = ("proven", "unproven_current_contract")+POLICY_VERDICTS: Final[tuple[str, ...]] = (+ "rejected",+ "blocked",+ "preview_ready",+ "live_candidate",+)+ACTOR_ROLES: Final[tuple[str, ...]] = ("reporter", "operator", "team_lead", "admin")+MINIMUM_ROLES: Final[tuple[str, ...]] = ("operator", "team_lead", "admin")+++def lifecycle_ddl(dialect: str) -> tuple[str, ...]:+ """Return the ordered exact generation-10 DDL for one supported dialect."""+ if dialect not in {"sqlite", "postgresql"}:+ raise ValueError("Unsupported lifecycle dialect")+ integer = "BIGINT" if dialect == "postgresql" else "INTEGER"+ boolean = "BOOLEAN" if dialect == "postgresql" else "INTEGER"+ false = "FALSE" if dialect == "postgresql" else "0"+ true = "TRUE" if dialect == "postgresql" else "1"+ bool_check = "{c} IN (FALSE,TRUE)" if dialect == "postgresql" else "{c} IN (0,1)"+ pending_default = "'pending'"+ now_ms = (+ "floor(extract(epoch FROM clock_timestamp())*1000)::bigint"+ if dialect == "postgresql"+ else "CAST((julianday('now')-2440587.5)*86400000 AS INTEGER)"+ )++ def uuid(column: str) -> str:+ return _uuid_check(column, dialect)++ def h64(column: str) -> str:+ return _h64_check(column, dialect)++ def s128(column: str) -> str:+ return _s128_check(column, dialect)++ def b(column: str) -> str:+ return bool_check.format(c=column)++ logical = f"""+CREATE TABLE logical_executions (+ id TEXT NOT NULL CONSTRAINT pk_logical_executions PRIMARY KEY,+ submission_id TEXT NOT NULL,+ campaign_id TEXT NOT NULL,+ actor_subject_ref TEXT NOT NULL,+ actor_user_id TEXT,+ module_id TEXT NOT NULL,+ ingress_code TEXT NOT NULL,+ admission_operation_id TEXT NOT NULL,+ submission_binding_contract_version {integer} NOT NULL,+ submission_request_binding_digest TEXT NOT NULL,+ submission_result_code TEXT NOT NULL,+ submission_exact_replay_code TEXT NOT NULL,+ submission_result_binding_digest TEXT NOT NULL,+ highest_attempt_ordinal {integer} NOT NULL DEFAULT 0,+ revision {integer} NOT NULL DEFAULT 0,+ created_at {integer} NOT NULL DEFAULT ({now_ms}),+ closure_operation_id TEXT,+ closure_authority_subject_ref TEXT,+ closure_authority_user_id TEXT,+ closure_authority_revision {integer},+ closing_attempt_id TEXT,+ closed_at {integer},+ CONSTRAINT uq_le_campaign_id UNIQUE (campaign_id,id),+ CONSTRAINT uq_le_campaign_submission UNIQUE (campaign_id,submission_id),+ CONSTRAINT ck_le_id CHECK ({uuid("id")}),+ CONSTRAINT ck_le_submission_id CHECK ({uuid("submission_id")}),+ CONSTRAINT ck_le_campaign_id CHECK ({uuid("campaign_id")}),+ CONSTRAINT ck_le_actor_subject CHECK ({uuid("actor_subject_ref")}),+ CONSTRAINT ck_le_actor_user CHECK (actor_user_id IS NULL OR ({uuid("actor_user_id")})),+ CONSTRAINT ck_le_module_id CHECK ({s128("module_id")}),+ CONSTRAINT ck_le_ingress CHECK ({_in("ingress_code", INGRESS_CODES)}),+ CONSTRAINT ck_le_admission_operation CHECK ({uuid("admission_operation_id")}),+ CONSTRAINT ck_le_submission_contract CHECK (submission_binding_contract_version=2),+ CONSTRAINT ck_le_submission_request_digest CHECK ({h64("submission_request_binding_digest")}),+ CONSTRAINT ck_le_submission_result_code CHECK (submission_result_code='applied'),+ CONSTRAINT ck_le_submission_replay_code CHECK (submission_exact_replay_code='replayed'),+ CONSTRAINT ck_le_submission_result_digest CHECK ({h64("submission_result_binding_digest")}),+ CONSTRAINT ck_le_bounds CHECK (+ highest_attempt_ordinal BETWEEN 0 AND {MAX_I53}+ AND revision BETWEEN 0 AND {MAX_I53}+ AND created_at BETWEEN 0 AND {MAX_I53}+ AND (closed_at IS NULL OR closed_at BETWEEN created_at AND {MAX_I53})+ ),+ CONSTRAINT ck_le_closure_operation CHECK (+ closure_operation_id IS NULL OR ({uuid("closure_operation_id")})+ ),+ CONSTRAINT ck_le_closure_subject CHECK (+ closure_authority_subject_ref IS NULL OR ({uuid("closure_authority_subject_ref")})+ ),+ CONSTRAINT ck_le_closure_user CHECK (+ closure_authority_user_id IS NULL OR ({uuid("closure_authority_user_id")})+ ),+ CONSTRAINT ck_le_closing_attempt CHECK (+ closing_attempt_id IS NULL OR ({uuid("closing_attempt_id")})+ ),+ CONSTRAINT ck_le_closure_shape CHECK (+ (+ closure_operation_id IS NULL+ AND closure_authority_subject_ref IS NULL+ AND closure_authority_user_id IS NULL+ AND closure_authority_revision IS NULL+ AND closing_attempt_id IS NULL+ AND closed_at IS NULL+ ) OR (+ closure_operation_id IS NOT NULL+ AND closure_authority_subject_ref IS NOT NULL+ AND closure_authority_revision BETWEEN 0 AND {MAX_I53}+ AND closing_attempt_id IS NOT NULL+ AND closed_at IS NOT NULL+ )+ ),+ CONSTRAINT fk_le_campaign FOREIGN KEY (campaign_id)+ REFERENCES campaigns(id) ON UPDATE NO ACTION ON DELETE NO ACTION+ DEFERRABLE INITIALLY DEFERRED,+ CONSTRAINT fk_le_actor_user FOREIGN KEY (actor_user_id)+ REFERENCES users(id) ON UPDATE NO ACTION ON DELETE SET NULL+ DEFERRABLE INITIALLY DEFERRED,+ CONSTRAINT fk_le_closure_user FOREIGN KEY (closure_authority_user_id)+ REFERENCES users(id) ON UPDATE NO ACTION ON DELETE SET NULL+ DEFERRABLE INITIALLY DEFERRED+ {"," if dialect == "sqlite" else ""}+ {"CONSTRAINT fk_le_closing_attempt FOREIGN KEY (id,closing_attempt_id) REFERENCES execution_attempts(logical_execution_id,id) ON UPDATE NO ACTION ON DELETE NO ACTION DEFERRABLE INITIALLY DEFERRED" if dialect == "sqlite" else ""}+)"""++ states = tuple(state.value for state in AttemptState)+ outcomes = tuple(value.value for value in OutcomeCode)+ attempts = f"""+CREATE TABLE execution_attempts (+ id TEXT NOT NULL CONSTRAINT pk_execution_attempts PRIMARY KEY,+ logical_execution_id TEXT NOT NULL,+ campaign_id TEXT NOT NULL,+ ordinal {integer} NOT NULL,+ parent_attempt_id TEXT,+ revision {integer} NOT NULL DEFAULT 0,+ state TEXT NOT NULL,+ closes_logical {boolean} NOT NULL DEFAULT {false},+ actor_subject_ref TEXT NOT NULL,+ actor_user_id TEXT,+ actor_authority_revision {integer} NOT NULL,+ campaign_authority_revision {integer} NOT NULL,+ destination_authority_revision {integer} NOT NULL,+ credential_authority_revision {integer} NOT NULL,+ request_contract_version {integer} NOT NULL,+ evaluation_mode TEXT NOT NULL,+ request_structure_valid {boolean} NOT NULL,+ canonicalization_complete {boolean} NOT NULL,+ unknown_fields_absent {boolean} NOT NULL,+ alternate_transport_absent {boolean} NOT NULL,+ bounded_shape_valid {boolean} NOT NULL,+ request_shape_units {integer} NOT NULL,+ descriptor_contract_version TEXT NOT NULL,+ descriptor_semantic_digest TEXT NOT NULL,+ catalog_digest TEXT NOT NULL,+ trusted_first_party_binding {boolean} NOT NULL,+ descriptor_binding_current {boolean} NOT NULL,+ descriptor_complete {boolean} NOT NULL,+ static_policy_evaluable {boolean} NOT NULL,+ minimum_role TEXT NOT NULL,+ noise_class TEXT NOT NULL,+ approval_policy TEXT NOT NULL,+ capability_mask_version {integer} NOT NULL,+ required_capability_mask {integer} NOT NULL,+ descriptor_blocker_mask_version {integer} NOT NULL,+ descriptor_blocker_mask {integer} NOT NULL,+ preview_ready {boolean} NOT NULL,+ lifecycle_ready {boolean} NOT NULL,+ result_authority_ready {boolean} NOT NULL,+ transport_ready {boolean} NOT NULL,+ future_gateway_eligible {boolean} NOT NULL,+ authority_snapshots_complete {boolean} NOT NULL,+ authority_revisions_current {boolean} NOT NULL,+ actor_authenticated {boolean} NOT NULL,+ actor_active {boolean} NOT NULL,+ actor_role TEXT NOT NULL,+ campaign_active {boolean} NOT NULL,+ actor_campaign_authorized {boolean} NOT NULL,+ approval_present {boolean} NOT NULL,+ approval_current {boolean} NOT NULL,+ approval_exactly_bound {boolean} NOT NULL,+ granted_capability_mask {integer} NOT NULL,+ destination_extraction_complete {boolean} NOT NULL,+ destinations_in_scope {boolean} NOT NULL,+ credential_authority_resolved {boolean} NOT NULL,+ credential_authority_current {boolean} NOT NULL,+ opaque_handles_only {boolean} NOT NULL,+ permitted_handle_kinds_only {boolean} NOT NULL,+ raw_credentials_absent {boolean} NOT NULL,+ ambient_credentials_absent {boolean} NOT NULL,+ budget_authority_resolved {boolean} NOT NULL,+ budget_authority_current {boolean} NOT NULL,+ budget_capacity_available {boolean} NOT NULL,+ gateway_mode_snapshot TEXT NOT NULL,+ gateway_decision_code TEXT NOT NULL,+ policy_evaluation_state TEXT NOT NULL,+ policy_contract_version {integer} NOT NULL,+ policy_verdict TEXT,+ policy_reason_mask_version {integer},+ policy_reason_mask {integer},+ external_effect_class TEXT NOT NULL,+ idempotency_class TEXT NOT NULL,+ retry_policy TEXT NOT NULL,+ retry_disposition TEXT NOT NULL,+ cancellation_ownership TEXT NOT NULL,+ compensation_class TEXT NOT NULL,+ timeout_origin TEXT NOT NULL,+ timeout_limit_ms {integer} NOT NULL,+ timeout_settlement TEXT NOT NULL,+ outcome_code TEXT,+ error_action_code TEXT NOT NULL,+ settlement_state TEXT NOT NULL,+ settlement_proof_code TEXT NOT NULL,+ termination_confirmed {boolean} NOT NULL,+ dispatch_owner_ref TEXT,+ lease_generation {integer} NOT NULL DEFAULT 0,+ dispatch_lease_duration_ms {integer},+ lease_expires_at {integer},+ lease_invalidated_at {integer},+ queue_operation_id TEXT,+ dispatch_operation_id TEXT,+ start_operation_id TEXT,+ cancellation_request_operation_id TEXT,+ cancellation_request_revision {integer},+ cancellation_ack_operation_id TEXT,+ timeout_operation_id TEXT,+ settlement_pending_operation_id TEXT,+ terminal_operation_id TEXT,+ resolver_subject_ref TEXT,+ resolver_user_id TEXT,+ resolver_authority_revision {integer},+ bounded_recovery_proof_code TEXT,+ created_at {integer} NOT NULL DEFAULT ({now_ms}),+ accepted_at {integer},+ queued_at {integer},+ dispatching_at {integer},+ started_at {integer},+ cancellation_requested_at {integer},+ cancellation_acknowledged_at {integer},+ timeout_observed_at {integer},+ settlement_pending_at {integer},+ recovery_deadline_at {integer},+ retry_child_bound_at {integer},+ finished_at {integer},+ settled_at {integer},+ CONSTRAINT uq_ea_logical_ordinal UNIQUE (logical_execution_id,ordinal),+ CONSTRAINT uq_ea_logical_id UNIQUE (logical_execution_id,id),+ CONSTRAINT uq_ea_campaign_id UNIQUE (campaign_id,id),+ CONSTRAINT ck_ea_id CHECK ({uuid("id")}),+ CONSTRAINT ck_ea_logical_campaign CHECK (+ ({uuid("logical_execution_id")}) AND ({uuid("campaign_id")})+ ),+ CONSTRAINT ck_ea_parent CHECK (parent_attempt_id IS NULL OR ({uuid("parent_attempt_id")})),+ CONSTRAINT ck_ea_actor_refs CHECK (+ ({uuid("actor_subject_ref")})+ AND (actor_user_id IS NULL OR ({uuid("actor_user_id")}))+ ),+ CONSTRAINT ck_ea_contract_versions CHECK (+ request_contract_version=1+ AND policy_contract_version=1+ AND descriptor_contract_version='ares.module-descriptor.v2'+ AND capability_mask_version=1+ AND descriptor_blocker_mask_version=1+ AND (policy_reason_mask_version IS NULL OR policy_reason_mask_version=1)+ ),+ CONSTRAINT ck_ea_digests CHECK (+ ({h64("descriptor_semantic_digest")}) AND ({h64("catalog_digest")})+ ),+ CONSTRAINT ck_ea_operation_ids CHECK (+ (queue_operation_id IS NULL OR ({uuid("queue_operation_id")}))+ AND (dispatch_operation_id IS NULL OR ({uuid("dispatch_operation_id")}))+ AND (start_operation_id IS NULL OR ({uuid("start_operation_id")}))+ AND (cancellation_request_operation_id IS NULL OR ({+ uuid("cancellation_request_operation_id")+ }))+ AND (cancellation_ack_operation_id IS NULL OR ({uuid("cancellation_ack_operation_id")}))+ AND (timeout_operation_id IS NULL OR ({uuid("timeout_operation_id")}))+ AND (settlement_pending_operation_id IS NULL OR ({uuid("settlement_pending_operation_id")}))+ AND (terminal_operation_id IS NULL OR ({uuid("terminal_operation_id")}))+ AND (resolver_subject_ref IS NULL OR ({uuid("resolver_subject_ref")}))+ AND (resolver_user_id IS NULL OR ({uuid("resolver_user_id")}))+ AND {+ _distinct_nullable(+ (+ "queue_operation_id",+ "dispatch_operation_id",+ "start_operation_id",+ "cancellation_request_operation_id",+ "cancellation_ack_operation_id",+ "timeout_operation_id",+ "settlement_pending_operation_id",+ "terminal_operation_id",+ )+ )+ }+ ),+ CONSTRAINT ck_ea_state CHECK ({_in("state", states)}),+ CONSTRAINT ck_ea_booleans CHECK (+ {+ " AND ".join(+ b(name)+ for name in (+ "closes_logical",+ "request_structure_valid",+ "canonicalization_complete",+ "unknown_fields_absent",+ "alternate_transport_absent",+ "bounded_shape_valid",+ "trusted_first_party_binding",+ "descriptor_binding_current",+ "descriptor_complete",+ "static_policy_evaluable",+ "preview_ready",+ "lifecycle_ready",+ "result_authority_ready",+ "transport_ready",+ "future_gateway_eligible",+ "authority_snapshots_complete",+ "authority_revisions_current",+ "actor_authenticated",+ "actor_active",+ "campaign_active",+ "actor_campaign_authorized",+ "approval_present",+ "approval_current",+ "approval_exactly_bound",+ "destination_extraction_complete",+ "destinations_in_scope",+ "credential_authority_resolved",+ "credential_authority_current",+ "opaque_handles_only",+ "permitted_handle_kinds_only",+ "raw_credentials_absent",+ "ambient_credentials_absent",+ "budget_authority_resolved",+ "budget_authority_current",+ "budget_capacity_available",+ "termination_confirmed",+ )+ )+ }+ ),+ CONSTRAINT ck_ea_numeric_bounds CHECK (+ ordinal BETWEEN 0 AND {MAX_I53}+ AND revision BETWEEN 0 AND {MAX_I53}+ AND actor_authority_revision BETWEEN 0 AND {MAX_I53}+ AND campaign_authority_revision BETWEEN 0 AND {MAX_I53}+ AND destination_authority_revision BETWEEN 0 AND {MAX_I53}+ AND credential_authority_revision BETWEEN 0 AND {MAX_I53}+ AND request_shape_units BETWEEN 0 AND 4096+ AND required_capability_mask BETWEEN 0 AND 15+ AND granted_capability_mask BETWEEN 0 AND 15+ AND descriptor_blocker_mask BETWEEN 0 AND 511+ AND (policy_reason_mask IS NULL OR policy_reason_mask BETWEEN 0 AND 34359738367)+ AND timeout_limit_ms BETWEEN {MIN_TIMEOUT_MS} AND {MAX_TIMEOUT_MS}+ AND lease_generation BETWEEN 0 AND {MAX_I53}+ ),+ CONSTRAINT ck_ea_timestamps CHECK (+ created_at BETWEEN 0 AND {MAX_I53}+ AND (accepted_at IS NULL OR accepted_at BETWEEN created_at AND {MAX_I53})+ AND (queued_at IS NULL OR queued_at BETWEEN created_at AND {MAX_I53})+ AND (dispatching_at IS NULL OR dispatching_at BETWEEN created_at AND {MAX_I53})+ AND (started_at IS NULL OR started_at BETWEEN created_at AND {MAX_I53})+ AND (cancellation_requested_at IS NULL OR cancellation_requested_at BETWEEN created_at AND {+ MAX_I53+ })+ AND (cancellation_acknowledged_at IS NULL OR cancellation_acknowledged_at BETWEEN created_at AND {+ MAX_I53+ })+ AND (timeout_observed_at IS NULL OR timeout_observed_at BETWEEN created_at AND {MAX_I53})+ AND (settlement_pending_at IS NULL OR settlement_pending_at BETWEEN created_at AND {+ MAX_I53+ })+ AND (recovery_deadline_at IS NULL OR recovery_deadline_at BETWEEN created_at AND {MAX_I53})+ AND (retry_child_bound_at IS NULL OR retry_child_bound_at BETWEEN created_at AND {MAX_I53})+ AND (finished_at IS NULL OR finished_at BETWEEN created_at AND {MAX_I53})+ AND (settled_at IS NULL OR settled_at BETWEEN created_at AND {MAX_I53})+ AND (lease_invalidated_at IS NULL OR lease_invalidated_at BETWEEN created_at AND {MAX_I53})+ ),+ CONSTRAINT ck_ea_enums CHECK (+ {_in("evaluation_mode", ("preview", "live"))}+ AND {_in("minimum_role", MINIMUM_ROLES)}+ AND {_in("actor_role", ACTOR_ROLES)}+ AND {_in("noise_class", NOISE_CLASSES)}+ AND {_in("approval_policy", APPROVAL_POLICIES)}+ AND {_in("external_effect_class", EXTERNAL_EFFECT_CLASSES)}+ AND {_in("idempotency_class", IDEMPOTENCY_CLASSES)}+ AND {_in("retry_policy", RETRY_POLICIES)}+ AND {_in("retry_disposition", RETRY_DISPOSITIONS)}+ AND {_in("cancellation_ownership", CANCELLATION_OWNERSHIP)}+ AND {_in("compensation_class", COMPENSATION_CLASSES)}+ AND {_in("timeout_origin", TIMEOUT_ORIGINS)}+ AND {_in("timeout_settlement", TIMEOUT_SETTLEMENTS)}+ AND {+ _in(+ "gateway_mode_snapshot",+ ("disabled", "shadow_candidate", "enforced", "emergency_disabled"),+ )+ }+ AND {_in("gateway_decision_code", ("none", "emergency_disabled"))}+ AND {_in("policy_evaluation_state", ("evaluated", "not_evaluated"))}+ AND (policy_verdict IS NULL OR {_in("policy_verdict", POLICY_VERDICTS)})+ AND (outcome_code IS NULL OR {_in("outcome_code", outcomes)})+ AND {+ _in(+ "error_action_code",+ (+ "none",+ "retry",+ "skip",+ "fallback",+ "abort",+ "pause",+ "credential_lockout",+ "credential_expired",+ "host_unreachable",+ "rate_limited",+ "dependency_unavailable",+ "operator_cancel",+ "timeout",+ "worker_loss",+ "recovery_required",+ ),+ )+ }+ AND {+ _in(+ "settlement_state",+ (+ "not_applicable",+ "reserved",+ "active",+ "recovery_pending",+ "settled",+ "operator_resolved",+ ),+ )+ }+ AND {+ _in(+ "settlement_proof_code",+ (+ "none",+ "no_dispatch",+ "local_completion",+ "process_group_exit",+ "worker_terminal_ack",+ "external_settlement_ack",+ "cancellation_no_result_ack",+ "timeout_termination_ack",+ "bounded_recovery_exhausted",+ "unresolved",+ ),+ )+ }+ AND (bounded_recovery_proof_code IS NULL OR {+ _in(+ "bounded_recovery_proof_code",+ (+ "owner_late_terminal_ack",+ "process_exit_observed",+ "provider_settlement_ack",+ "cancellation_no_result_ack",+ "timeout_termination_ack",+ "recovery_sources_exhausted",+ ),+ )+ })+ ),+ CONSTRAINT ck_ea_policy_shape CHECK (+ (+ gateway_mode_snapshot='emergency_disabled'+ AND gateway_decision_code='emergency_disabled'+ AND state='blocked'+ AND policy_evaluation_state='not_evaluated'+ AND policy_verdict IS NULL+ AND policy_reason_mask_version IS NULL+ AND policy_reason_mask IS NULL+ ) OR (+ gateway_mode_snapshot<>'emergency_disabled'+ AND gateway_decision_code='none'+ AND policy_evaluation_state='evaluated'+ AND policy_verdict IS NOT NULL+ AND policy_reason_mask_version=1+ AND policy_reason_mask IS NOT NULL+ )+ ),+ CONSTRAINT ck_ea_policy_state_binding CHECK (+ (state='rejected' AND policy_evaluation_state='evaluated' AND policy_verdict='rejected')+ OR (state='blocked' AND (+ (policy_evaluation_state='evaluated' AND policy_verdict IN ('blocked','preview_ready'))+ OR (gateway_mode_snapshot='emergency_disabled' AND policy_evaluation_state='not_evaluated' AND policy_verdict IS NULL)+ ))+ OR (state NOT IN ('rejected','blocked')+ AND evaluation_mode='live'+ AND gateway_mode_snapshot='enforced'+ AND gateway_decision_code='none'+ AND policy_evaluation_state='evaluated'+ AND policy_verdict='live_candidate'+ AND policy_reason_mask_version=1+ AND policy_reason_mask=0+ AND descriptor_blocker_mask=0)+ ),+ CONSTRAINT ck_ea_live_admission_facts CHECK (+ state IN ('rejected','blocked') OR (+ request_structure_valid={true}+ AND canonicalization_complete={true}+ AND unknown_fields_absent={true}+ AND alternate_transport_absent={true}+ AND bounded_shape_valid={true}+ AND trusted_first_party_binding={true}+ AND descriptor_binding_current={true}+ AND descriptor_complete={true}+ AND static_policy_evaluable={true}+ AND preview_ready={true}+ AND lifecycle_ready={true}+ AND result_authority_ready={true}+ AND transport_ready={true}+ AND future_gateway_eligible={true}+ AND authority_snapshots_complete={true}+ AND authority_revisions_current={true}+ AND actor_authenticated={true}+ AND actor_active={true}+ AND campaign_active={true}+ AND actor_campaign_authorized={true}+ AND destination_extraction_complete={true}+ AND destinations_in_scope={true}+ AND credential_authority_resolved={true}+ AND credential_authority_current={true}+ AND opaque_handles_only={true}+ AND permitted_handle_kinds_only={true}+ AND raw_credentials_absent={true}+ AND ambient_credentials_absent={true}+ AND budget_authority_resolved={true}+ AND budget_authority_current={true}+ AND budget_capacity_available={true}+ AND (+ (minimum_role='operator' AND actor_role IN ('operator','team_lead','admin'))+ OR (minimum_role='team_lead' AND actor_role IN ('team_lead','admin'))+ OR (minimum_role='admin' AND actor_role='admin')+ )+ AND (noise_class<>'high_noise' OR actor_role IN ('team_lead','admin'))+ AND ((granted_capability_mask & required_capability_mask)=required_capability_mask)+ AND (+ (approval_policy='none' AND approval_present={false} AND approval_current={+ false+ } AND approval_exactly_bound={false})+ OR (approval_policy='attempt_bound' AND approval_present={+ true+ } AND approval_current={true} AND approval_exactly_bound={true})+ )+ )+ ),+ CONSTRAINT ck_ea_outcome CHECK (+ (state='rejected' AND outcome_code='policy_rejected')+ OR (state='blocked' AND outcome_code='policy_blocked')+ OR (state='succeeded' AND outcome_code='confirmed_success')+ OR (state='partial' AND outcome_code='confirmed_partial')+ OR (state='skipped' AND outcome_code='orchestration_skipped')+ OR (state='cancelled' AND outcome_code='confirmed_cancelled_no_result')+ OR (state='timed_out' AND outcome_code='confirmed_timeout_terminated')+ OR (state='indeterminate' AND outcome_code='unknown_after_recovery')+ OR (state='failed' AND outcome_code IN ('confirmed_failure_no_dispatch','confirmed_failure'))+ OR (state IN ('accepted','queued','dispatching','running','cancelling','settlement_pending') AND outcome_code IS NULL)+ ),+ CONSTRAINT ck_ea_capabilities CHECK (+ state IN ('rejected','blocked')+ OR ((granted_capability_mask & required_capability_mask)=required_capability_mask)+ ),+ CONSTRAINT ck_ea_retry CHECK (+ retry_disposition<>'eligible'+ OR (+ state IN ('failed','timed_out')+ AND closes_logical={false}+ AND external_effect_class='read_only'+ AND idempotency_class='proven_idempotent'+ AND retry_policy='after_revalidation'+ AND (+ (+ start_operation_id IS NULL+ AND outcome_code='confirmed_failure_no_dispatch'+ AND settlement_state='not_applicable'+ AND settlement_proof_code='no_dispatch'+ AND termination_confirmed={false}+ ) OR (+ start_operation_id IS NOT NULL+ AND settlement_state='settled'+ AND settlement_proof_code NOT IN ('none','no_dispatch','unresolved')+ AND termination_confirmed={true}+ )+ )+ )+ ),+ CONSTRAINT ck_ea_lease_shape CHECK (+ (+ dispatch_operation_id IS NULL+ AND dispatch_owner_ref IS NULL+ AND lease_generation=0+ AND dispatch_lease_duration_ms IS NULL+ AND lease_expires_at IS NULL+ AND lease_invalidated_at IS NULL+ AND start_operation_id IS NULL+ ) OR (+ dispatch_operation_id IS NOT NULL+ AND dispatch_owner_ref IS NOT NULL+ AND ({uuid("dispatch_owner_ref")})+ AND lease_generation BETWEEN 1 AND {MAX_I53}+ AND dispatch_lease_duration_ms BETWEEN {MIN_TIMEOUT_MS} AND {MAX_TIMEOUT_MS}+ AND lease_expires_at BETWEEN 0 AND {MAX_I53}+ AND dispatching_at IS NOT NULL+ AND lease_expires_at<=dispatching_at+timeout_limit_ms+ )+ ),+ CONSTRAINT ck_ea_dispatch_history_state CHECK (+ (+ dispatch_operation_id IS NULL+ AND state NOT IN ('dispatching','running','succeeded','partial','timed_out','settlement_pending')+ ) OR (+ dispatch_operation_id IS NOT NULL+ AND (+ (state IN ('dispatching','running','cancelling') AND lease_invalidated_at IS NULL)+ OR (state IN ('succeeded','partial','failed','cancelled','timed_out','indeterminate','settlement_pending') AND lease_invalidated_at IS NOT NULL)+ )+ AND (start_operation_id IS NOT NULL OR state NOT IN ('running','succeeded','partial','timed_out'))+ )+ ),+ CONSTRAINT ck_ea_state_history CHECK (+ (state IN ('rejected','blocked')+ AND accepted_at IS NULL AND queue_operation_id IS NULL+ AND dispatch_operation_id IS NULL AND start_operation_id IS NULL+ AND cancellation_request_operation_id IS NULL)+ OR (state='accepted'+ AND accepted_at IS NOT NULL AND queue_operation_id IS NULL+ AND dispatch_operation_id IS NULL AND start_operation_id IS NULL+ AND cancellation_request_operation_id IS NULL)+ OR (state='queued'+ AND accepted_at IS NOT NULL AND queue_operation_id IS NOT NULL+ AND dispatch_operation_id IS NULL AND start_operation_id IS NULL+ AND cancellation_request_operation_id IS NULL)+ OR (state='dispatching'+ AND accepted_at IS NOT NULL AND dispatch_operation_id IS NOT NULL+ AND start_operation_id IS NULL AND cancellation_request_operation_id IS NULL)+ OR (state='running'+ AND accepted_at IS NOT NULL AND dispatch_operation_id IS NOT NULL+ AND start_operation_id IS NOT NULL AND cancellation_request_operation_id IS NULL)+ OR (state='cancelling'+ AND accepted_at IS NOT NULL AND cancellation_request_operation_id IS NOT NULL+ AND ((dispatch_operation_id IS NULL AND start_operation_id IS NULL)+ OR dispatch_operation_id IS NOT NULL))+ OR state IN ('settlement_pending','succeeded','partial','failed','skipped','cancelled','timed_out','indeterminate')+ ),+ CONSTRAINT ck_ea_history_dnf CHECK (+ (state IN ('rejected','blocked')+ AND accepted_at IS NULL AND queue_operation_id IS NULL+ AND dispatch_operation_id IS NULL AND start_operation_id IS NULL+ AND cancellation_request_operation_id IS NULL+ AND settlement_pending_operation_id IS NULL+ AND terminal_operation_id IS NOT NULL)+ OR (state='accepted'+ AND accepted_at IS NOT NULL AND queue_operation_id IS NULL+ AND dispatch_operation_id IS NULL AND start_operation_id IS NULL+ AND cancellation_request_operation_id IS NULL+ AND settlement_pending_operation_id IS NULL)+ OR (state='queued'+ AND accepted_at IS NOT NULL AND queue_operation_id IS NOT NULL+ AND dispatch_operation_id IS NULL AND start_operation_id IS NULL+ AND cancellation_request_operation_id IS NULL+ AND settlement_pending_operation_id IS NULL)+ OR (state='dispatching'+ AND accepted_at IS NOT NULL AND dispatch_operation_id IS NOT NULL+ AND start_operation_id IS NULL+ AND cancellation_request_operation_id IS NULL+ AND settlement_pending_operation_id IS NULL+ AND lease_invalidated_at IS NULL)+ OR (state='running'+ AND accepted_at IS NOT NULL AND dispatch_operation_id IS NOT NULL+ AND start_operation_id IS NOT NULL+ AND cancellation_request_operation_id IS NULL+ AND settlement_pending_operation_id IS NULL+ AND lease_invalidated_at IS NULL)+ OR (state='cancelling'+ AND accepted_at IS NOT NULL+ AND cancellation_request_operation_id IS NOT NULL+ AND settlement_pending_operation_id IS NULL+ AND (+ (dispatch_operation_id IS NULL AND start_operation_id IS NULL+ AND lease_invalidated_at IS NULL)+ OR (dispatch_operation_id IS NOT NULL AND start_operation_id IS NULL+ AND lease_invalidated_at IS NULL)+ OR (dispatch_operation_id IS NOT NULL AND start_operation_id IS NOT NULL+ AND lease_invalidated_at IS NULL)+ ))+ OR (state='settlement_pending'+ AND dispatch_operation_id IS NOT NULL+ AND settlement_pending_operation_id IS NOT NULL+ AND lease_invalidated_at IS NOT NULL+ AND terminal_operation_id IS NULL+ AND cancellation_ack_operation_id IS NULL+ AND timeout_operation_id IS NULL)+ OR (state IN ('succeeded','partial')+ AND dispatch_operation_id IS NOT NULL+ AND start_operation_id IS NOT NULL+ AND lease_invalidated_at IS NOT NULL+ AND ((cancellation_request_operation_id IS NULL+ AND terminal_operation_id IS NOT NULL+ AND cancellation_ack_operation_id IS NULL)+ OR (cancellation_request_operation_id IS NOT NULL+ AND cancellation_ack_operation_id IS NOT NULL+ AND terminal_operation_id IS NULL)))+ OR (state='failed'+ AND (+ (dispatch_operation_id IS NULL AND start_operation_id IS NULL+ AND lease_invalidated_at IS NULL+ AND outcome_code='confirmed_failure_no_dispatch')+ OR (dispatch_operation_id IS NOT NULL AND start_operation_id IS NULL+ AND lease_invalidated_at IS NOT NULL+ AND outcome_code='confirmed_failure_no_dispatch')+ OR (dispatch_operation_id IS NOT NULL AND start_operation_id IS NOT NULL+ AND lease_invalidated_at IS NOT NULL+ AND outcome_code='confirmed_failure')+ )+ AND ((cancellation_request_operation_id IS NULL+ AND terminal_operation_id IS NOT NULL+ AND cancellation_ack_operation_id IS NULL)+ OR (cancellation_request_operation_id IS NOT NULL+ AND cancellation_ack_operation_id IS NOT NULL+ AND terminal_operation_id IS NULL)))+ OR (state='skipped'+ AND dispatch_operation_id IS NULL AND start_operation_id IS NULL+ AND cancellation_request_operation_id IS NULL+ AND terminal_operation_id IS NOT NULL)+ OR (state='cancelled'+ AND cancellation_ack_operation_id IS NOT NULL+ AND terminal_operation_id IS NULL+ AND ((cancellation_request_operation_id IS NOT NULL+ AND dispatch_operation_id IS NULL AND start_operation_id IS NULL+ AND lease_invalidated_at IS NULL)+ OR (dispatch_operation_id IS NOT NULL+ AND lease_invalidated_at IS NOT NULL)))+ OR (state='timed_out'+ AND dispatch_operation_id IS NOT NULL+ AND start_operation_id IS NOT NULL+ AND lease_invalidated_at IS NOT NULL+ AND timeout_operation_id IS NOT NULL+ AND terminal_operation_id IS NULL)+ OR (state='indeterminate'+ AND dispatch_operation_id IS NOT NULL+ AND settlement_pending_operation_id IS NOT NULL+ AND lease_invalidated_at IS NOT NULL+ AND terminal_operation_id IS NOT NULL)+ ),+ CONSTRAINT ck_ea_cancellation_shape CHECK (+ (+ cancellation_request_operation_id IS NULL+ AND cancellation_request_revision IS NULL+ AND cancellation_requested_at IS NULL+ ) OR (+ cancellation_request_operation_id IS NOT NULL+ AND cancellation_request_revision BETWEEN 1 AND {MAX_I53}+ AND cancellation_requested_at BETWEEN created_at AND {MAX_I53}+ )+ ),+ CONSTRAINT ck_ea_operation_shape CHECK (+ (queue_operation_id IS NULL)=(queued_at IS NULL)+ AND (dispatch_operation_id IS NULL)=(dispatching_at IS NULL)+ AND (start_operation_id IS NULL)=(started_at IS NULL)+ AND (cancellation_ack_operation_id IS NULL)=(cancellation_acknowledged_at IS NULL)+ AND (timeout_operation_id IS NULL)=(timeout_observed_at IS NULL)+ AND (settlement_pending_operation_id IS NULL)=(settlement_pending_at IS NULL)+ AND (settlement_pending_at IS NULL)=(recovery_deadline_at IS NULL)+ AND (settlement_pending_at IS NULL OR recovery_deadline_at=settlement_pending_at+{+ RECOVERY_WINDOW_MS+ })+ AND (accepted_at IS NULL OR accepted_at>=created_at)+ AND (queued_at IS NULL OR (accepted_at IS NOT NULL AND queued_at>=accepted_at))+ AND (dispatching_at IS NULL OR (accepted_at IS NOT NULL AND dispatching_at>=accepted_at AND (queued_at IS NULL OR dispatching_at>=queued_at)))+ AND (started_at IS NULL OR (dispatching_at IS NOT NULL AND started_at>=dispatching_at))+ AND (cancellation_requested_at IS NULL OR (accepted_at IS NOT NULL AND cancellation_requested_at>=accepted_at))+ AND (cancellation_acknowledged_at IS NULL OR (+ COALESCE(cancellation_requested_at,settlement_pending_at) IS NOT NULL+ AND cancellation_acknowledged_at>=COALESCE(cancellation_requested_at,settlement_pending_at)+ ))+ AND (timeout_observed_at IS NULL OR (started_at IS NOT NULL AND timeout_observed_at>=started_at))+ AND (settlement_pending_at IS NULL OR (dispatching_at IS NOT NULL AND settlement_pending_at>=dispatching_at))+ AND (finished_at IS NULL OR finished_at>=COALESCE(settlement_pending_at,cancellation_requested_at,started_at,dispatching_at,queued_at,accepted_at,created_at))+ AND (settled_at IS NULL OR (finished_at IS NOT NULL AND settled_at>=finished_at))+ ),+ CONSTRAINT ck_ea_terminal_operation CHECK (+ (state IN ('rejected','blocked','succeeded','partial','failed','skipped','indeterminate')+ AND cancellation_ack_operation_id IS NULL+ AND timeout_operation_id IS NULL+ AND terminal_operation_id IS NOT NULL)+ OR (state='cancelled' AND cancellation_ack_operation_id IS NOT NULL AND terminal_operation_id IS NULL)+ OR (state='timed_out' AND timeout_operation_id IS NOT NULL AND terminal_operation_id IS NULL)+ OR (state IN ('accepted','queued','dispatching','running','cancelling','settlement_pending') AND terminal_operation_id IS NULL)+ OR (state IN ('succeeded','partial','failed') AND cancellation_ack_operation_id IS NOT NULL AND terminal_operation_id IS NULL)+ ),+ CONSTRAINT ck_ea_terminal_times CHECK (+ (state IN ('rejected','blocked','succeeded','partial','failed','skipped','cancelled','timed_out','indeterminate')+ AND finished_at IS NOT NULL AND settled_at IS NOT NULL)+ OR (state IN ('accepted','queued','dispatching','running','cancelling','settlement_pending')+ AND finished_at IS NULL AND settled_at IS NULL)+ ),+ CONSTRAINT ck_ea_recovery_shape CHECK (+ (state='settlement_pending'+ AND settlement_pending_operation_id IS NOT NULL+ AND lease_invalidated_at IS NOT NULL+ AND settlement_state='recovery_pending'+ AND settlement_proof_code='unresolved'+ AND termination_confirmed={false})+ OR state<>'settlement_pending'+ ),+ CONSTRAINT ck_ea_resolver_shape CHECK (+ (state='indeterminate'+ AND resolver_subject_ref IS NOT NULL+ AND resolver_authority_revision BETWEEN 0 AND {MAX_I53}+ AND bounded_recovery_proof_code='recovery_sources_exhausted')+ OR (state<>'indeterminate'+ AND resolver_subject_ref IS NULL+ AND resolver_user_id IS NULL+ AND resolver_authority_revision IS NULL+ AND bounded_recovery_proof_code IS NULL)+ ),+ CONSTRAINT fk_ea_logical_campaign FOREIGN KEY (campaign_id,logical_execution_id)+ REFERENCES logical_executions(campaign_id,id)+ ON UPDATE NO ACTION ON DELETE NO ACTION DEFERRABLE INITIALLY DEFERRED,+ CONSTRAINT fk_ea_parent FOREIGN KEY (logical_execution_id,parent_attempt_id)+ REFERENCES execution_attempts(logical_execution_id,id)+ ON UPDATE NO ACTION ON DELETE NO ACTION DEFERRABLE INITIALLY DEFERRED,+ CONSTRAINT fk_ea_actor_user FOREIGN KEY (actor_user_id)+ REFERENCES users(id) ON UPDATE NO ACTION ON DELETE SET NULL+ DEFERRABLE INITIALLY DEFERRED,+ CONSTRAINT fk_ea_resolver_user FOREIGN KEY (resolver_user_id)+ REFERENCES users(id) ON UPDATE NO ACTION ON DELETE SET NULL+ DEFERRABLE INITIALLY DEFERRED+)"""++ actor_authority = f"""+CREATE TABLE execution_actor_authority_revisions (+ user_id TEXT NOT NULL CONSTRAINT pk_eaar PRIMARY KEY,+ revision {integer} NOT NULL DEFAULT 0,+ latest_operation_id TEXT NOT NULL,+ latest_operation_base_revision {integer} NOT NULL DEFAULT 0,+ latest_operation_code TEXT NOT NULL,+ updated_at {integer} NOT NULL DEFAULT ({now_ms}),+ CONSTRAINT ck_eaar_user CHECK ({uuid("user_id")}),+ CONSTRAINT ck_eaar_operation CHECK ({uuid("latest_operation_id")}),+ CONSTRAINT ck_eaar_shape CHECK (+ revision BETWEEN 0 AND {MAX_I53}+ AND latest_operation_base_revision BETWEEN 0 AND {MAX_I53}+ AND latest_operation_code IN ('ensure','invalidate')+ AND ((revision=0 AND latest_operation_code='ensure' AND latest_operation_base_revision=0)+ OR (revision>=1 AND latest_operation_base_revision=revision-1))+ AND updated_at BETWEEN 0 AND {MAX_I53}+ ),+ CONSTRAINT fk_eaar_user FOREIGN KEY (user_id) REFERENCES users(id)+ ON UPDATE NO ACTION ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED+)"""++ campaign_authority = f"""+CREATE TABLE campaign_execution_authority_revisions (+ campaign_id TEXT NOT NULL CONSTRAINT pk_cear PRIMARY KEY,+ revision {integer} NOT NULL DEFAULT 0,+ latest_operation_id TEXT NOT NULL,+ latest_operation_base_revision {integer} NOT NULL DEFAULT 0,+ latest_operation_code TEXT NOT NULL,+ updated_at {integer} NOT NULL DEFAULT ({now_ms}),+ CONSTRAINT ck_cear_operation CHECK ({uuid("latest_operation_id")}),+ CONSTRAINT ck_cear_campaign CHECK ({uuid("campaign_id")}),+ CONSTRAINT ck_cear_shape CHECK (+ revision BETWEEN 0 AND {MAX_I53}+ AND latest_operation_base_revision BETWEEN 0 AND {MAX_I53}+ AND latest_operation_code IN ('ensure','invalidate')+ AND ((revision=0 AND latest_operation_code='ensure' AND latest_operation_base_revision=0)+ OR (revision>=1 AND latest_operation_base_revision=revision-1))+ AND updated_at BETWEEN 0 AND {MAX_I53}+ ),+ CONSTRAINT fk_cear_campaign FOREIGN KEY (campaign_id) REFERENCES campaigns(id)+ ON UPDATE NO ACTION ON DELETE NO ACTION DEFERRABLE INITIALLY DEFERRED+)"""++ budgets = f"""+CREATE TABLE campaign_execution_budgets (+ id TEXT NOT NULL CONSTRAINT pk_ceb PRIMARY KEY,+ campaign_id TEXT NOT NULL,+ budget_kind TEXT NOT NULL,+ capacity_units {integer} NOT NULL,+ reserved_units {integer} NOT NULL DEFAULT 0,+ consumed_units {integer} NOT NULL DEFAULT 0,+ revision {integer} NOT NULL DEFAULT 0,+ latest_operation_id TEXT NOT NULL,+ latest_operation_base_revision {integer} NOT NULL DEFAULT 0,+ latest_operation_code TEXT NOT NULL,+ created_at {integer} NOT NULL DEFAULT ({now_ms}),+ updated_at {integer} NOT NULL DEFAULT ({now_ms}),+ CONSTRAINT uq_ceb_campaign_kind UNIQUE (campaign_id,budget_kind),+ CONSTRAINT uq_ceb_campaign_id_kind UNIQUE (campaign_id,id,budget_kind),+ CONSTRAINT ck_ceb_id CHECK ({uuid("id")}),+ CONSTRAINT ck_ceb_campaign CHECK ({uuid("campaign_id")}),+ CONSTRAINT ck_ceb_operation CHECK ({uuid("latest_operation_id")}),+ CONSTRAINT ck_ceb_shape CHECK (+ budget_kind IN ('noise','exfiltration','concurrency')+ AND capacity_units BETWEEN 0 AND {MAX_I53}+ AND reserved_units BETWEEN 0 AND {MAX_I53}+ AND consumed_units BETWEEN 0 AND {MAX_I53}+ AND reserved_units+consumed_units<=capacity_units+ AND (budget_kind<>'concurrency' OR capacity_units>=1)+ AND revision BETWEEN 0 AND {MAX_I53}+ AND latest_operation_base_revision BETWEEN 0 AND {MAX_I53}+ AND latest_operation_code IN ('configure','reserve','settle')+ AND ((revision=0 AND latest_operation_code='configure' AND latest_operation_base_revision=0)+ OR (revision>=1 AND latest_operation_base_revision=revision-1))+ AND created_at BETWEEN 0 AND {MAX_I53}+ AND updated_at BETWEEN created_at AND {MAX_I53}+ ),+ CONSTRAINT fk_ceb_campaign FOREIGN KEY (campaign_id) REFERENCES campaigns(id)+ ON UPDATE NO ACTION ON DELETE NO ACTION DEFERRABLE INITIALLY DEFERRED+)"""++ approvals = f"""+CREATE TABLE execution_attempt_approvals (+ id TEXT NOT NULL CONSTRAINT pk_eaa PRIMARY KEY,+ attempt_id TEXT NOT NULL,+ campaign_id TEXT NOT NULL,+ approval_ref TEXT NOT NULL,+ approver_subject_ref TEXT NOT NULL,+ approver_user_id TEXT,+ authority_revision {integer} NOT NULL,+ binding_digest TEXT NOT NULL,+ bound_at {integer} NOT NULL DEFAULT ({now_ms}),+ CONSTRAINT uq_eaa_attempt UNIQUE (attempt_id),+ CONSTRAINT uq_eaa_approval_ref UNIQUE (approval_ref),+ CONSTRAINT ck_eaa_ids CHECK (+ ({uuid("id")}) AND ({uuid("attempt_id")}) AND ({uuid("campaign_id")})+ AND ({uuid("approval_ref")})+ AND ({uuid("approver_subject_ref")})+ AND (approver_user_id IS NULL OR ({uuid("approver_user_id")}))+ ),+ CONSTRAINT ck_eaa_digest CHECK ({h64("binding_digest")}),+ CONSTRAINT ck_eaa_bounds CHECK (+ authority_revision BETWEEN 0 AND {MAX_I53}+ AND bound_at BETWEEN 0 AND {MAX_I53}+ ),+ CONSTRAINT fk_eaa_attempt FOREIGN KEY (campaign_id,attempt_id)+ REFERENCES execution_attempts(campaign_id,id)+ ON UPDATE NO ACTION ON DELETE NO ACTION DEFERRABLE INITIALLY DEFERRED,+ CONSTRAINT fk_eaa_user FOREIGN KEY (approver_user_id) REFERENCES users(id)+ ON UPDATE NO ACTION ON DELETE SET NULL DEFERRABLE INITIALLY DEFERRED+)"""++ ledger = f"""+CREATE TABLE campaign_execution_budget_ledger (+ id TEXT NOT NULL CONSTRAINT pk_cebl PRIMARY KEY,+ attempt_id TEXT NOT NULL,+ campaign_id TEXT NOT NULL,+ budget_id TEXT NOT NULL,+ budget_kind TEXT NOT NULL,+ reservation_units {integer} NOT NULL,+ consumed_units {integer} NOT NULL DEFAULT 0,+ disposition TEXT NOT NULL,+ budget_revision_reserved {integer} NOT NULL,+ budget_revision_settled {integer},+ reserved_at {integer} NOT NULL DEFAULT ({now_ms}),+ settled_at {integer},+ CONSTRAINT uq_cebl_attempt_kind UNIQUE (attempt_id,budget_kind),+ CONSTRAINT uq_cebl_budget_attempt UNIQUE (budget_id,attempt_id),+ CONSTRAINT ck_cebl_ids CHECK (({uuid("id")}) AND ({uuid("attempt_id")}) AND ({uuid("campaign_id")}) AND ({uuid("budget_id")})),+ CONSTRAINT ck_cebl_shape CHECK (+ budget_kind IN ('noise','exfiltration','concurrency')+ AND reservation_units BETWEEN 0 AND {MAX_I53}+ AND consumed_units BETWEEN 0 AND reservation_units+ AND disposition IN ('held','released','consumed')+ AND budget_revision_reserved BETWEEN 0 AND {MAX_I53}+ AND (budget_revision_settled IS NULL OR budget_revision_settled BETWEEN 0 AND {MAX_I53})+ AND reserved_at BETWEEN 0 AND {MAX_I53}+ AND (settled_at IS NULL OR settled_at BETWEEN reserved_at AND {MAX_I53})+ AND ((disposition='held' AND consumed_units=0 AND budget_revision_settled IS NULL AND settled_at IS NULL)+ OR (disposition='released' AND consumed_units=0 AND budget_revision_settled IS NOT NULL AND settled_at IS NOT NULL)+ OR (disposition='consumed' AND budget_revision_settled IS NOT NULL AND settled_at IS NOT NULL))+ AND (budget_kind<>'concurrency' OR (reservation_units=1 AND consumed_units=0 AND disposition<>'consumed'))+ ),+ CONSTRAINT fk_cebl_attempt FOREIGN KEY (campaign_id,attempt_id)+ REFERENCES execution_attempts(campaign_id,id)+ ON UPDATE NO ACTION ON DELETE NO ACTION DEFERRABLE INITIALLY DEFERRED,+ CONSTRAINT fk_cebl_budget FOREIGN KEY (campaign_id,budget_id,budget_kind)+ REFERENCES campaign_execution_budgets(campaign_id,id,budget_kind)+ ON UPDATE NO ACTION ON DELETE NO ACTION DEFERRABLE INITIALLY DEFERRED+)"""++ links = f"""+CREATE TABLE execution_output_links (+ id TEXT NOT NULL CONSTRAINT pk_eol PRIMARY KEY,+ attempt_id TEXT NOT NULL,+ campaign_id TEXT NOT NULL,+ finding_id TEXT,+ credential_id TEXT,+ host_id TEXT,+ loot_id TEXT,+ created_at {integer} NOT NULL DEFAULT ({now_ms}),+ CONSTRAINT ck_eol_ids CHECK (+ ({uuid("id")}) AND ({uuid("attempt_id")}) AND ({uuid("campaign_id")})+ AND (finding_id IS NULL OR ({uuid("finding_id")}))+ AND (credential_id IS NULL OR ({uuid("credential_id")}))+ AND (host_id IS NULL OR ({uuid("host_id")}))+ AND (loot_id IS NULL OR ({uuid("loot_id")}))+ ),+ CONSTRAINT ck_eol_exactly_one CHECK (+ (CASE WHEN finding_id IS NOT NULL THEN 1 ELSE 0 END)+ +(CASE WHEN credential_id IS NOT NULL THEN 1 ELSE 0 END)+ +(CASE WHEN host_id IS NOT NULL THEN 1 ELSE 0 END)+ +(CASE WHEN loot_id IS NOT NULL THEN 1 ELSE 0 END)=1+ ),+ CONSTRAINT ck_eol_created CHECK (created_at BETWEEN 0 AND {MAX_I53}),+ CONSTRAINT fk_eol_attempt FOREIGN KEY (campaign_id,attempt_id)+ REFERENCES execution_attempts(campaign_id,id)+ ON UPDATE NO ACTION ON DELETE NO ACTION DEFERRABLE INITIALLY DEFERRED,+ CONSTRAINT fk_eol_finding FOREIGN KEY (campaign_id,finding_id)+ REFERENCES findings(campaign_id,id)+ ON UPDATE NO ACTION ON DELETE NO ACTION DEFERRABLE INITIALLY DEFERRED,+ CONSTRAINT fk_eol_credential FOREIGN KEY (campaign_id,credential_id)+ REFERENCES credentials(campaign_id,id)+ ON UPDATE NO ACTION ON DELETE NO ACTION DEFERRABLE INITIALLY DEFERRED,+ CONSTRAINT fk_eol_host FOREIGN KEY (campaign_id,host_id)+ REFERENCES hosts(campaign_id,id)+ ON UPDATE NO ACTION ON DELETE NO ACTION DEFERRABLE INITIALLY DEFERRED,+ CONSTRAINT fk_eol_loot FOREIGN KEY (campaign_id,loot_id)+ REFERENCES loot(campaign_id,id)+ ON UPDATE NO ACTION ON DELETE NO ACTION DEFERRABLE INITIALLY DEFERRED+)"""++ outbox = f"""+CREATE TABLE execution_publication_outbox (+ id TEXT NOT NULL CONSTRAINT pk_epo PRIMARY KEY,+ publication_key TEXT NOT NULL,+ attempt_id TEXT NOT NULL,+ campaign_id TEXT NOT NULL,+ event_code TEXT NOT NULL,+ is_attempt_terminal {boolean} NOT NULL,+ finding_count {integer} NOT NULL DEFAULT 0,+ credential_count {integer} NOT NULL DEFAULT 0,+ host_count {integer} NOT NULL DEFAULT 0,+ artifact_count {integer} NOT NULL DEFAULT 0,+ publication_state TEXT NOT NULL DEFAULT {pending_default},+ delivery_attempt_count {integer} NOT NULL DEFAULT 0,+ available_at {integer},+ claim_owner_ref TEXT,+ lease_generation {integer} NOT NULL DEFAULT 0,+ claimed_at {integer},+ lease_expires_at {integer},+ published_at {integer},+ poisoned_at {integer},+ failure_code TEXT,+ claim_revision {integer} NOT NULL DEFAULT 0,+ latest_operation_id TEXT NOT NULL,+ latest_operation_code TEXT NOT NULL,+ latest_operation_base_revision {integer} NOT NULL,+ created_at {integer} NOT NULL DEFAULT ({now_ms}),+ CONSTRAINT uq_epo_publication_key UNIQUE (publication_key),+ CONSTRAINT uq_epo_attempt_event UNIQUE (attempt_id,event_code),+ CONSTRAINT ck_epo_ids CHECK (+ ({uuid("id")}) AND ({uuid("publication_key")}) AND ({uuid("attempt_id")})+ AND ({uuid("campaign_id")})+ AND ({uuid("latest_operation_id")})+ AND (claim_owner_ref IS NULL OR ({uuid("claim_owner_ref")}))+ ),+ CONSTRAINT ck_epo_event CHECK ({_in("event_code", ("recovery_required", "execution_rejected", "execution_blocked", "execution_succeeded", "execution_partial", "execution_failed", "execution_skipped", "execution_cancelled", "execution_timed_out", "execution_indeterminate", "logical_execution_closed"))}),+ CONSTRAINT ck_epo_counts CHECK (+ finding_count BETWEEN 0 AND {MAX_I53}+ AND credential_count BETWEEN 0 AND {MAX_I53}+ AND host_count BETWEEN 0 AND {MAX_I53}+ AND artifact_count BETWEEN 0 AND {MAX_I53}+ AND (event_code IN ('execution_succeeded','execution_partial')+ OR (finding_count=0 AND credential_count=0 AND host_count=0 AND artifact_count=0))+ AND (event_code<>'execution_partial'+ OR finding_count+credential_count+host_count+artifact_count>=1)+ ),+ CONSTRAINT ck_epo_terminal_flag CHECK (+ ({b("is_attempt_terminal")}) AND+ ((event_code IN ('execution_rejected','execution_blocked','execution_succeeded','execution_partial','execution_failed','execution_skipped','execution_cancelled','execution_timed_out','execution_indeterminate') AND is_attempt_terminal={true})+ OR (event_code IN ('recovery_required','logical_execution_closed') AND is_attempt_terminal={false}))+ ),+ CONSTRAINT ck_epo_state CHECK ({_in("publication_state", ("pending", "claimed", "published", "poisoned"))}),+ CONSTRAINT ck_epo_failure CHECK (failure_code IS NULL OR {_in("failure_code", ("delivery_retryable", "delivery_nonretryable", "delivery_attempt_limit"))}),+ CONSTRAINT ck_epo_latest_code CHECK ({_in("latest_operation_code", ("insert", "claim", "reclaim", "renew", "publish", "retryable_failure", "nonretryable_failure", "poison"))}),+ CONSTRAINT ck_epo_bounds CHECK (+ delivery_attempt_count BETWEEN 0 AND 20+ AND lease_generation BETWEEN 0 AND {MAX_I53}+ AND claim_revision BETWEEN 0 AND {MAX_I53}+ AND latest_operation_base_revision BETWEEN 0 AND {MAX_I53}+ AND created_at BETWEEN 0 AND {MAX_I53}+ AND (available_at IS NULL OR available_at BETWEEN created_at AND {MAX_I53})+ AND (claimed_at IS NULL OR claimed_at BETWEEN created_at AND {MAX_I53})+ AND (lease_expires_at IS NULL OR lease_expires_at BETWEEN created_at AND {MAX_I53})+ AND (published_at IS NULL OR published_at BETWEEN created_at AND {MAX_I53})+ AND (poisoned_at IS NULL OR poisoned_at BETWEEN created_at AND {MAX_I53})+ ),+ CONSTRAINT ck_epo_insert_shape CHECK (+ latest_operation_code<>'insert'+ OR (latest_operation_id=publication_key AND latest_operation_base_revision=0 AND claim_revision=0)+ ),+ CONSTRAINT ck_epo_state_shape CHECK (+ (publication_state='pending'+ AND claim_owner_ref IS NULL AND lease_expires_at IS NULL+ AND published_at IS NULL AND poisoned_at IS NULL+ AND ((delivery_attempt_count=0 AND claimed_at IS NULL AND failure_code IS NULL AND available_at IS NOT NULL)+ OR (delivery_attempt_count BETWEEN 1 AND 19 AND claimed_at IS NOT NULL AND failure_code='delivery_retryable' AND available_at IS NOT NULL)))+ OR (publication_state='claimed'+ AND delivery_attempt_count BETWEEN 1 AND 20+ AND claim_owner_ref IS NOT NULL AND claimed_at IS NOT NULL AND lease_expires_at IS NOT NULL+ AND available_at IS NULL AND failure_code IS NULL AND published_at IS NULL AND poisoned_at IS NULL)+ OR (publication_state='published'+ AND claim_owner_ref IS NULL AND lease_expires_at IS NULL AND available_at IS NULL+ AND claimed_at IS NOT NULL AND published_at IS NOT NULL AND poisoned_at IS NULL AND failure_code IS NULL)+ OR (publication_state='poisoned'+ AND claim_owner_ref IS NULL AND lease_expires_at IS NULL AND available_at IS NULL+ AND claimed_at IS NOT NULL AND published_at IS NULL AND poisoned_at IS NOT NULL AND failure_code IS NOT NULL)+ ),+ CONSTRAINT fk_epo_attempt FOREIGN KEY (campaign_id,attempt_id)+ REFERENCES execution_attempts(campaign_id,id)+ ON UPDATE NO ACTION ON DELETE NO ACTION DEFERRABLE INITIALLY DEFERRED+)"""++ receipts = f"""+CREATE TABLE execution_operation_receipts (+ operation_id TEXT NOT NULL CONSTRAINT pk_eor PRIMARY KEY,+ operation_code TEXT NOT NULL,+ campaign_id TEXT,+ primary_target_id TEXT NOT NULL,+ secondary_target_id TEXT,+ principal_kind TEXT NOT NULL,+ principal_subject_ref TEXT NOT NULL,+ principal_user_id TEXT,+ principal_authority_revision_present {boolean} NOT NULL,+ principal_authority_revision {integer},+ binding_contract_version {integer} NOT NULL,+ request_binding_digest TEXT NOT NULL,+ expected_revision_present {boolean} NOT NULL,+ expected_revision {integer},+ secondary_expected_revision_present {boolean} NOT NULL,+ secondary_expected_revision {integer},+ owner_ref TEXT,+ lease_generation {integer},+ result_code TEXT NOT NULL,+ exact_replay_code TEXT NOT NULL,+ result_binding_digest TEXT NOT NULL,+ result_identity TEXT,+ result_revision_present {boolean} NOT NULL,+ result_revision {integer},+ secondary_result_identity TEXT,+ secondary_result_revision_present {boolean} NOT NULL,+ secondary_result_revision {integer},+ created_at {integer} NOT NULL DEFAULT ({now_ms}),+ CONSTRAINT ck_eor_ids CHECK (+ ({uuid("operation_id")})+ AND (campaign_id IS NULL OR ({uuid("campaign_id")}))+ AND ({uuid("primary_target_id")})+ AND (secondary_target_id IS NULL OR ({uuid("secondary_target_id")}))+ AND ({uuid("principal_subject_ref")})+ AND (principal_user_id IS NULL OR ({uuid("principal_user_id")}))+ AND (owner_ref IS NULL OR ({uuid("owner_ref")}))+ AND (result_identity IS NULL OR ({uuid("result_identity")}))+ AND (secondary_result_identity IS NULL OR ({uuid("secondary_result_identity")}))+ ),+ CONSTRAINT ck_eor_operation_code CHECK ({_in("operation_code", OPERATION_CODES)}),+ CONSTRAINT ck_eor_principal_kind CHECK ({_in("principal_kind", PRINCIPAL_KINDS)}),+ CONSTRAINT ck_eor_principal_shape CHECK (+ (+ principal_kind IN ('actor','resolver')+ AND principal_user_id IS NOT NULL+ AND principal_authority_revision_present={true}+ AND principal_authority_revision IS NOT NULL+ ) OR (+ principal_kind IN ('worker','system')+ AND principal_user_id IS NULL+ AND principal_authority_revision_present={false}+ AND principal_authority_revision IS NULL+ )+ ),+ CONSTRAINT ck_eor_system_principal CHECK (+ principal_kind<>'system'+ OR principal_subject_ref='{SYSTEM_PRINCIPAL_SUBJECT_REF}'+ ),+ CONSTRAINT ck_eor_contract CHECK (binding_contract_version=2),+ CONSTRAINT ck_eor_request_digest CHECK ({h64("request_binding_digest")}),+ CONSTRAINT ck_eor_result_code CHECK ({_in("result_code", tuple(value.value for value in FixedResult))}),+ CONSTRAINT ck_eor_exact_replay_code CHECK ({_in("exact_replay_code", ("replayed", "replayed_bound_child", "replayed_closed"))}),+ CONSTRAINT ck_eor_result_digest CHECK ({h64("result_binding_digest")}),+ CONSTRAINT ck_eor_presence CHECK (+ (expected_revision_present={true}) = (expected_revision IS NOT NULL)+ AND (secondary_expected_revision_present={true}) = (secondary_expected_revision IS NOT NULL)+ AND (result_revision_present={true}) = (result_revision IS NOT NULL)+ AND (secondary_result_revision_present={true}) = (secondary_result_revision IS NOT NULL)+ ),+ CONSTRAINT ck_eor_operation_shape CHECK (+ (+ operation_code IN (+ 'actor_authority_ensure','campaign_authority_ensure','budget_configure',+ 'admission','outbox_insert','campaign_delete'+ )+ AND expected_revision_present={false}+ AND secondary_expected_revision_present={false}+ ) OR (+ operation_code IN (+ 'actor_authority_invalidate','campaign_authority_invalidate','retry',+ 'queue','dispatch','start','cancellation_request',+ 'cancellation_acknowledgement','timeout','settlement_pending','lease_loss',+ 'recovery_succeeded','recovery_partial','recovery_failed',+ 'recovery_cancelled','recovery_timed_out','recovery_indeterminate',+ 'terminal_succeeded','terminal_partial','terminal_failed','terminal_skipped',+ 'close_without_retry','outbox_claim','outbox_reclaim','outbox_renew',+ 'outbox_publish','outbox_retryable_failure','outbox_nonretryable_failure',+ 'outbox_poison','outbox_purge'+ )+ AND expected_revision_present={true}+ AND secondary_expected_revision_present={false}+ ) OR (+ operation_code IN ('budget_reserve','budget_settle')+ AND expected_revision_present={true}+ AND secondary_expected_revision_present={true}+ )+ ),+ CONSTRAINT ck_eor_outbox_owner_shape CHECK (+ (+ operation_code IN (+ 'outbox_claim','outbox_reclaim','outbox_renew','outbox_publish',+ 'outbox_retryable_failure','outbox_nonretryable_failure'+ )+ AND owner_ref IS NOT NULL+ AND lease_generation IS NOT NULL+ ) OR (+ operation_code IN ('outbox_insert','outbox_poison','outbox_purge')+ AND owner_ref IS NULL+ AND lease_generation IS NULL+ ) OR operation_code NOT IN (+ 'outbox_insert','outbox_claim','outbox_reclaim','outbox_renew','outbox_publish',+ 'outbox_retryable_failure','outbox_nonretryable_failure','outbox_poison',+ 'outbox_purge'+ )+ ),+ CONSTRAINT ck_eor_bounds CHECK (+ (expected_revision IS NULL OR expected_revision BETWEEN 0 AND {MAX_I53})+ AND (secondary_expected_revision IS NULL OR secondary_expected_revision BETWEEN 0 AND {MAX_I53})+ AND (lease_generation IS NULL OR lease_generation BETWEEN 0 AND {MAX_I53})+ AND (result_revision IS NULL OR result_revision BETWEEN 0 AND {MAX_I53})+ AND (secondary_result_revision IS NULL OR secondary_result_revision BETWEEN 0 AND {MAX_I53})+ AND created_at BETWEEN 0 AND {MAX_I53}+ ),+ CONSTRAINT ck_eor_owner_generation CHECK (+ (owner_ref IS NULL AND lease_generation IS NULL)+ OR (owner_ref IS NOT NULL AND lease_generation IS NOT NULL)+ )+)"""++ if dialect == "postgresql":+ receipt_immutability = (+ "CREATE FUNCTION execution_operation_receipt_immutable() RETURNS trigger "+ "LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION "+ "'immutable execution operation receipt' USING ERRCODE='55000'; END $$",+ "CREATE TRIGGER trg_eor_immutable BEFORE UPDATE OR DELETE "+ "ON execution_operation_receipts FOR EACH ROW "+ "EXECUTE FUNCTION execution_operation_receipt_immutable()",+ )+ else:+ receipt_immutability = (+ "CREATE TRIGGER trg_eor_immutable_update BEFORE UPDATE "+ "ON execution_operation_receipts BEGIN "+ "SELECT RAISE(ABORT,'immutable execution operation receipt'); END",+ "CREATE TRIGGER trg_eor_immutable_delete BEFORE DELETE "+ "ON execution_operation_receipts BEGIN "+ "SELECT RAISE(ABORT,'immutable execution operation receipt'); END",+ )++ gateway = f"""+CREATE TABLE execution_gateway_state (+ singleton_id {integer} NOT NULL CONSTRAINT pk_egs PRIMARY KEY,+ mode TEXT NOT NULL,+ catalog_digest TEXT,+ activation_revision {integer},+ activation_at {integer},+ revision {integer} NOT NULL DEFAULT 0,+ updated_at {integer} NOT NULL DEFAULT ({now_ms}),+ CONSTRAINT ck_egs_singleton CHECK (singleton_id=1),+ CONSTRAINT ck_egs_mode CHECK ({_in("mode", ("disabled", "shadow_candidate", "enforced", "emergency_disabled"))}),+ CONSTRAINT ck_egs_digest CHECK (catalog_digest IS NULL OR ({h64("catalog_digest")})),+ CONSTRAINT ck_egs_shape CHECK (+ (mode='disabled' AND catalog_digest IS NULL AND activation_revision IS NULL AND activation_at IS NULL AND revision=0)+ OR (mode IN ('shadow_candidate','enforced','emergency_disabled')+ AND catalog_digest IS NOT NULL+ AND activation_revision BETWEEN 1 AND {MAX_I53}+ AND activation_at BETWEEN 0 AND {MAX_I53}+ AND revision BETWEEN 1 AND {MAX_I53})+ )+)"""++ statements: list[str] = [logical, attempts]+ if dialect == "postgresql":+ statements.append(+ "ALTER TABLE logical_executions ADD CONSTRAINT fk_le_closing_attempt "+ "FOREIGN KEY (id,closing_attempt_id) "+ "REFERENCES execution_attempts(logical_execution_id,id) "+ "ON UPDATE NO ACTION ON DELETE NO ACTION DEFERRABLE INITIALLY DEFERRED"+ )+ statements.extend([actor_authority, campaign_authority, budgets, approvals, ledger])++ if dialect == "postgresql":+ statements.extend(+ [+ "ALTER TABLE findings ADD CONSTRAINT uq_findings_campaign_id_id UNIQUE (campaign_id,id)",+ "ALTER TABLE credentials ADD CONSTRAINT uq_credentials_campaign_id_id UNIQUE (campaign_id,id)",+ "ALTER TABLE hosts ADD CONSTRAINT uq_hosts_campaign_id_id UNIQUE (campaign_id,id)",+ "ALTER TABLE loot ADD CONSTRAINT uq_loot_campaign_id_id UNIQUE (campaign_id,id)",+ ]+ )+ else:+ statements.extend(+ [+ "CREATE UNIQUE INDEX uq_findings_campaign_id_id ON findings(campaign_id,id)",+ "CREATE UNIQUE INDEX uq_credentials_campaign_id_id ON credentials(campaign_id,id)",+ "CREATE UNIQUE INDEX uq_hosts_campaign_id_id ON hosts(campaign_id,id)",+ "CREATE UNIQUE INDEX uq_loot_campaign_id_id ON loot(campaign_id,id)",+ ]+ )+ statements.extend([links, outbox, receipts, *receipt_immutability, gateway])+ statements.extend(+ [+ "CREATE UNIQUE INDEX uq_le_closure_operation ON logical_executions(closure_operation_id) WHERE closure_operation_id IS NOT NULL",+ "CREATE INDEX ix_le_campaign_created ON logical_executions(campaign_id,created_at,id)",+ "CREATE UNIQUE INDEX uq_ea_one_child ON execution_attempts(logical_execution_id,parent_attempt_id) WHERE parent_attempt_id IS NOT NULL",+ "CREATE INDEX ix_ea_dispatch_lease ON execution_attempts(state,lease_expires_at,id) WHERE state IN ('dispatching','running','cancelling')",+ "CREATE INDEX ix_ea_recovery_deadline ON execution_attempts(state,recovery_deadline_at,id) WHERE state='settlement_pending'",+ "CREATE INDEX ix_ea_logical_state ON execution_attempts(logical_execution_id,state,ordinal)",+ "CREATE UNIQUE INDEX uq_eaar_latest_operation ON execution_actor_authority_revisions(latest_operation_id)",+ "CREATE UNIQUE INDEX uq_cear_latest_operation ON campaign_execution_authority_revisions(latest_operation_id)",+ "CREATE INDEX ix_cebl_budget ON campaign_execution_budget_ledger(budget_id,disposition,attempt_id)",+ "CREATE INDEX ix_eol_attempt ON execution_output_links(attempt_id)",+ "CREATE UNIQUE INDEX uq_eol_attempt_finding ON execution_output_links(attempt_id,finding_id) WHERE finding_id IS NOT NULL",+ "CREATE UNIQUE INDEX uq_eol_attempt_credential ON execution_output_links(attempt_id,credential_id) WHERE credential_id IS NOT NULL",+ "CREATE UNIQUE INDEX uq_eol_attempt_host ON execution_output_links(attempt_id,host_id) WHERE host_id IS NOT NULL",+ "CREATE UNIQUE INDEX uq_eol_attempt_loot ON execution_output_links(attempt_id,loot_id) WHERE loot_id IS NOT NULL",+ "CREATE INDEX ix_eol_finding ON execution_output_links(campaign_id,finding_id) WHERE finding_id IS NOT NULL",+ "CREATE INDEX ix_eol_credential ON execution_output_links(campaign_id,credential_id) WHERE credential_id IS NOT NULL",+ "CREATE INDEX ix_eol_host ON execution_output_links(campaign_id,host_id) WHERE host_id IS NOT NULL",+ "CREATE INDEX ix_eol_loot ON execution_output_links(campaign_id,loot_id) WHERE loot_id IS NOT NULL",+ "CREATE UNIQUE INDEX uq_epo_one_terminal ON execution_publication_outbox(attempt_id) WHERE is_attempt_terminal="+ + true,+ "CREATE INDEX ix_epo_available ON execution_publication_outbox(publication_state,available_at,id)",+ "CREATE INDEX ix_epo_lease ON execution_publication_outbox(publication_state,lease_expires_at,id)",+ "CREATE INDEX ix_epo_retention ON execution_publication_outbox(publication_state,published_at,poisoned_at,id)",+ "CREATE INDEX ix_eor_campaign_created ON execution_operation_receipts(campaign_id,created_at,operation_id)",+ "CREATE INDEX ix_eor_primary_target ON execution_operation_receipts(primary_target_id,operation_code,created_at)",+ "CREATE INDEX ix_eor_principal_created ON execution_operation_receipts(principal_kind,principal_subject_ref,created_at,operation_id)",+ "INSERT INTO execution_gateway_state(singleton_id,mode,revision) VALUES(1,'disabled',0)",+ ]+ )+ return tuple(statement.strip() for statement in statements)+++SQLITE_LIFECYCLE_DDL: Final[tuple[str, ...]] = lifecycle_ddl("sqlite")+POSTGRES_LIFECYCLE_DDL: Final[tuple[str, ...]] = lifecycle_ddl("postgresql")+++def _v11_receipt_create_statement(dialect: str) -> str:+ """Return the generation-10 receipt table widened only for v11 codes."""+ source = POSTGRES_LIFECYCLE_DDL if dialect == "postgresql" else SQLITE_LIFECYCLE_DDL+ statement = next(+ item for item in source if item.startswith("CREATE TABLE execution_operation_receipts")+ )+ statement = statement.replace(+ _in("operation_code", OPERATION_CODES),+ _in("operation_code", V11_OPERATION_CODES),+ 1,+ )+ statement = statement.replace(+ "'admission','outbox_insert','campaign_delete'\n )",+ "'admission','outbox_insert','campaign_delete','approval_authority_grant'\n )",+ 1,+ )+ one_revision = ",".join(+ repr(value)+ for value in V11_ADDITIVE_OPERATION_CODES+ if value not in {"approval_authority_grant", "campaign_actor_grant_put"}+ )+ statement = statement.replace(+ "'outbox_poison','outbox_purge'\n )",+ "'outbox_poison','outbox_purge'," + one_revision + "\n )",+ 1,+ )+ statement = statement.replace(+ ") OR (\n operation_code IN ('budget_reserve','budget_settle')",+ ") OR (\n operation_code='campaign_actor_grant_put'\n"+ " AND secondary_expected_revision_present="+ + ("FALSE" if dialect == "postgresql" else "0")+ + "\n ) OR (\n operation_code IN ('budget_reserve','budget_settle')",+ 1,+ )+ if _in("operation_code", V11_OPERATION_CODES) not in statement:+ raise RuntimeError("Invalid generation-11 receipt DDL")+ return statement+++def admission_authority_v11_ddl(dialect: str) -> tuple[str, ...]:+ """Return additive generation-11 admission-authority DDL.++ Generation-10 objects are altered only through new columns and two widened+ receipt checks. Historical receipt bytes and all v10 digest semantics stay+ untouched.+ """+ if dialect not in {"sqlite", "postgresql"}:+ raise ValueError("Unsupported admission-authority dialect")+ integer = "BIGINT" if dialect == "postgresql" else "INTEGER"+ now_ms = (+ "floor(extract(epoch FROM clock_timestamp())*1000)::bigint"+ if dialect == "postgresql"+ else "CAST((julianday('now')-2440587.5)*86400000 AS INTEGER)"+ )++ def uuid(column: str) -> str:+ return _uuid_check(column, dialect)++ def h64(column: str) -> str:+ return _h64_check(column, dialect)++ zero_digest = "0" * 64++ statements: list[str] = [+ "ALTER TABLE logical_executions ADD COLUMN admission_authority_contract_version "+ f"{integer} NOT NULL DEFAULT 2 CHECK (admission_authority_contract_version IN (2,3))",+ "ALTER TABLE logical_executions ADD COLUMN canonical_principal_user_id TEXT "+ f"CHECK (canonical_principal_user_id IS NULL OR ({uuid('canonical_principal_user_id')}))",+ "ALTER TABLE logical_executions ADD COLUMN immutable_intent_digest TEXT "+ f"CHECK (immutable_intent_digest IS NULL OR ({h64('immutable_intent_digest')}))",+ "ALTER TABLE logical_executions ADD COLUMN immutable_work_digest TEXT "+ f"CHECK (immutable_work_digest IS NULL OR ({h64('immutable_work_digest')}))",+ "ALTER TABLE execution_attempts ADD COLUMN authority_contract_version "+ f"{integer} NOT NULL DEFAULT 2 CHECK (authority_contract_version IN (2,3))",+ "ALTER TABLE execution_attempts ADD COLUMN trusted_principal_subject_ref TEXT "+ f"CHECK (trusted_principal_subject_ref IS NULL OR ({uuid('trusted_principal_subject_ref')}))",+ "ALTER TABLE execution_attempts ADD COLUMN trusted_principal_user_id TEXT "+ f"CHECK (trusted_principal_user_id IS NULL OR ({uuid('trusted_principal_user_id')}))",+ "ALTER TABLE execution_attempts ADD COLUMN immutable_intent_digest TEXT "+ f"CHECK (immutable_intent_digest IS NULL OR ({h64('immutable_intent_digest')}))",+ "ALTER TABLE execution_attempts ADD COLUMN immutable_work_digest TEXT "+ f"CHECK (immutable_work_digest IS NULL OR ({h64('immutable_work_digest')}))",+ "ALTER TABLE execution_attempts ADD COLUMN gateway_revision "+ f"{integer} CHECK (gateway_revision IS NULL OR gateway_revision BETWEEN 0 AND {MAX_I53})",+ "ALTER TABLE execution_attempts ADD COLUMN gateway_activation_revision "+ f"{integer} CHECK (gateway_activation_revision IS NULL OR gateway_activation_revision BETWEEN 0 AND {MAX_I53})",+ "ALTER TABLE execution_attempts ADD COLUMN campaign_actor_grant_revision "+ f"{integer} CHECK (campaign_actor_grant_revision IS NULL OR campaign_actor_grant_revision BETWEEN 0 AND {MAX_I53})",+ "ALTER TABLE execution_attempts ADD COLUMN destination_authority_binding_digest TEXT "+ f"CHECK (destination_authority_binding_digest IS NULL OR ({h64('destination_authority_binding_digest')}))",+ "ALTER TABLE execution_attempts ADD COLUMN credential_authority_binding_digest TEXT "+ f"CHECK (credential_authority_binding_digest IS NULL OR ({h64('credential_authority_binding_digest')}))",+ "ALTER TABLE execution_attempts ADD COLUMN approval_authority_binding_digest TEXT "+ f"CHECK (approval_authority_binding_digest IS NULL OR ({h64('approval_authority_binding_digest')}))",+ ]+ for table in (+ "execution_actor_authority_revisions",+ "campaign_execution_authority_revisions",+ ):+ statements.extend(+ [+ f"ALTER TABLE {table} ADD COLUMN authority_state TEXT NOT NULL DEFAULT 'active' "+ "CHECK (authority_state IN ('active','revoked'))",+ f"ALTER TABLE {table} ADD COLUMN authority_revision {integer} NOT NULL DEFAULT 0 "+ f"CHECK (authority_revision BETWEEN 0 AND {MAX_I53})",+ f"ALTER TABLE {table} ADD COLUMN authority_binding_digest TEXT NOT NULL "+ f"DEFAULT '{zero_digest}' CHECK ({h64('authority_binding_digest')})",+ f"ALTER TABLE {table} ADD COLUMN authority_latest_operation_id TEXT "+ f"CHECK (authority_latest_operation_id IS NULL OR ({uuid('authority_latest_operation_id')}))",+ f"ALTER TABLE {table} ADD COLUMN authority_latest_operation_base_revision {integer} "+ f"CHECK (authority_latest_operation_base_revision IS NULL OR authority_latest_operation_base_revision BETWEEN 0 AND {MAX_I53})",+ f"ALTER TABLE {table} ADD COLUMN authority_latest_operation_code TEXT "+ "CHECK (authority_latest_operation_code IS NULL OR authority_latest_operation_code IN ('activate','update','revoke'))",+ ]+ )+ statements.extend(+ [+ "ALTER TABLE credentials ADD COLUMN execution_authority_state TEXT NOT NULL DEFAULT 'active' "+ "CHECK (execution_authority_state IN ('active','revoked'))",+ "ALTER TABLE credentials ADD COLUMN execution_authority_revision "+ f"{integer} NOT NULL DEFAULT 0 CHECK (execution_authority_revision BETWEEN 0 AND {MAX_I53})",+ "ALTER TABLE credentials ADD COLUMN execution_authority_binding_digest TEXT NOT NULL "+ f"DEFAULT '{zero_digest}' CHECK ({h64('execution_authority_binding_digest')})",+ "ALTER TABLE credentials ADD COLUMN execution_authority_latest_operation_id TEXT "+ f"CHECK (execution_authority_latest_operation_id IS NULL OR ({uuid('execution_authority_latest_operation_id')}))",+ "ALTER TABLE credentials ADD COLUMN execution_authority_latest_operation_base_revision "+ f"{integer} CHECK (execution_authority_latest_operation_base_revision IS NULL OR execution_authority_latest_operation_base_revision BETWEEN 0 AND {MAX_I53})",+ "ALTER TABLE credentials ADD COLUMN execution_authority_latest_operation_code TEXT "+ "CHECK (execution_authority_latest_operation_code IS NULL OR execution_authority_latest_operation_code IN ('update','revoke'))",+ ]+ )++ statements.extend(+ [+ f"""CREATE TABLE campaign_execution_actor_grants (+ campaign_id TEXT NOT NULL,+ actor_user_id TEXT NOT NULL,+ authority_state TEXT NOT NULL,+ revision {integer} NOT NULL DEFAULT 0,+ binding_digest TEXT NOT NULL,+ latest_operation_id TEXT NOT NULL,+ latest_operation_base_revision {integer} NOT NULL,+ latest_operation_code TEXT NOT NULL,+ created_at {integer} NOT NULL DEFAULT ({now_ms}),+ updated_at {integer} NOT NULL DEFAULT ({now_ms}),+ CONSTRAINT pk_ceag PRIMARY KEY (campaign_id,actor_user_id),+ CONSTRAINT ck_ceag_ids CHECK (({uuid("campaign_id")}) AND ({uuid("actor_user_id")}) AND ({uuid("latest_operation_id")})),+ CONSTRAINT ck_ceag_digest CHECK ({h64("binding_digest")}),+ CONSTRAINT ck_ceag_shape CHECK (authority_state IN ('active','revoked') AND revision BETWEEN 0 AND {MAX_I53} AND latest_operation_base_revision BETWEEN 0 AND {MAX_I53} AND latest_operation_code IN ('put','revoke') AND ((revision=0 AND latest_operation_code='put' AND latest_operation_base_revision=0) OR (revision>=1 AND latest_operation_base_revision=revision-1)) AND ((authority_state='active' AND latest_operation_code='put') OR authority_state='revoked') AND created_at BETWEEN 0 AND {MAX_I53} AND updated_at BETWEEN created_at AND {MAX_I53}),+ CONSTRAINT fk_ceag_campaign FOREIGN KEY (campaign_id) REFERENCES campaigns(id) ON UPDATE NO ACTION ON DELETE NO ACTION DEFERRABLE INITIALLY DEFERRED,+ CONSTRAINT fk_ceag_actor FOREIGN KEY (actor_user_id) REFERENCES users(id) ON UPDATE NO ACTION ON DELETE NO ACTION DEFERRABLE INITIALLY DEFERRED+)""",+ f"""CREATE TABLE campaign_execution_destination_authorities (+ campaign_id TEXT NOT NULL CONSTRAINT pk_ceda PRIMARY KEY,+ authority_state TEXT NOT NULL,+ revision {integer} NOT NULL DEFAULT 0,+ normalization_version {integer} NOT NULL,+ destination_count {integer} NOT NULL,+ destination_set_digest TEXT NOT NULL,+ binding_digest TEXT NOT NULL,+ latest_operation_id TEXT NOT NULL,+ latest_operation_base_revision {integer} NOT NULL,+ latest_operation_code TEXT NOT NULL,+ created_at {integer} NOT NULL DEFAULT ({now_ms}),+ updated_at {integer} NOT NULL DEFAULT ({now_ms}),+ CONSTRAINT ck_ceda_ids CHECK (({uuid("campaign_id")}) AND ({uuid("latest_operation_id")})),+ CONSTRAINT ck_ceda_digests CHECK (({h64("destination_set_digest")}) AND ({h64("binding_digest")})),+ CONSTRAINT ck_ceda_shape CHECK (authority_state IN ('active','revoked') AND revision BETWEEN 0 AND {MAX_I53} AND normalization_version={DESTINATION_NORMALIZATION_VERSION} AND destination_count BETWEEN 0 AND 4096 AND latest_operation_base_revision BETWEEN 0 AND {MAX_I53} AND latest_operation_code IN ('update','revoke') AND ((revision=0 AND latest_operation_code='update' AND latest_operation_base_revision=0) OR (revision>=1 AND latest_operation_base_revision=revision-1)) AND ((authority_state='active' AND latest_operation_code='update') OR authority_state='revoked') AND created_at BETWEEN 0 AND {MAX_I53} AND updated_at BETWEEN created_at AND {MAX_I53}),+ CONSTRAINT fk_ceda_campaign FOREIGN KEY (campaign_id) REFERENCES campaigns(id) ON UPDATE NO ACTION ON DELETE NO ACTION DEFERRABLE INITIALLY DEFERRED+)""",+ f"""CREATE TABLE execution_approval_authorities (+ id TEXT NOT NULL CONSTRAINT pk_eapa PRIMARY KEY,+ approval_ref TEXT NOT NULL,+ campaign_id TEXT NOT NULL,+ submission_id TEXT NOT NULL,+ attempt_id TEXT NOT NULL,+ actor_subject_ref TEXT NOT NULL,+ actor_user_id TEXT NOT NULL,+ module_id TEXT NOT NULL,+ approver_subject_ref TEXT NOT NULL,+ approver_user_id TEXT,+ authority_state TEXT NOT NULL,+ revision {integer} NOT NULL DEFAULT 0,+ granted_capability_mask {integer} NOT NULL,+ descriptor_semantic_digest TEXT NOT NULL,+ binding_digest TEXT NOT NULL,+ latest_operation_id TEXT NOT NULL,+ latest_operation_base_revision {integer} NOT NULL,+ latest_operation_code TEXT NOT NULL,+ created_at {integer} NOT NULL DEFAULT ({now_ms}),+ updated_at {integer} NOT NULL DEFAULT ({now_ms}),+ consumed_at {integer},+ CONSTRAINT uq_eapa_ref UNIQUE (approval_ref),+ CONSTRAINT uq_eapa_attempt UNIQUE (attempt_id),+ CONSTRAINT ck_eapa_ids CHECK (({uuid("id")}) AND ({uuid("approval_ref")}) AND ({uuid("campaign_id")}) AND ({uuid("submission_id")}) AND ({uuid("attempt_id")}) AND ({uuid("actor_subject_ref")}) AND ({uuid("actor_user_id")}) AND ({uuid("approver_subject_ref")}) AND (approver_user_id IS NULL OR ({uuid("approver_user_id")})) AND ({uuid("latest_operation_id")})),+ CONSTRAINT ck_eapa_module CHECK ({_s128_check("module_id", dialect)}),+ CONSTRAINT ck_eapa_digests CHECK (({h64("descriptor_semantic_digest")}) AND ({h64("binding_digest")})),+ CONSTRAINT ck_eapa_shape CHECK (authority_state IN ('active','revoked','consumed') AND revision BETWEEN 0 AND {MAX_I53} AND granted_capability_mask BETWEEN 0 AND 15 AND latest_operation_base_revision BETWEEN 0 AND {MAX_I53} AND latest_operation_code IN ('grant','revoke','consume') AND ((revision=0 AND latest_operation_code='grant' AND latest_operation_base_revision=0) OR (revision>=1 AND latest_operation_base_revision=revision-1)) AND ((authority_state='active' AND latest_operation_code='grant' AND consumed_at IS NULL) OR (authority_state='revoked' AND latest_operation_code='revoke' AND consumed_at IS NULL) OR (authority_state='consumed' AND latest_operation_code='consume' AND consumed_at BETWEEN created_at AND {MAX_I53})) AND created_at BETWEEN 0 AND {MAX_I53} AND updated_at BETWEEN created_at AND {MAX_I53}),+ CONSTRAINT fk_eapa_campaign FOREIGN KEY (campaign_id) REFERENCES campaigns(id) ON UPDATE NO ACTION ON DELETE NO ACTION DEFERRABLE INITIALLY DEFERRED,+ CONSTRAINT fk_eapa_approver FOREIGN KEY (approver_user_id) REFERENCES users(id) ON UPDATE NO ACTION ON DELETE SET NULL DEFERRABLE INITIALLY DEFERRED+)""",+ f"""CREATE TABLE execution_attempt_destination_observations (+ attempt_id TEXT NOT NULL,+ campaign_id TEXT NOT NULL,+ ordinal {integer} NOT NULL,+ destination_ref_digest TEXT NOT NULL,+ authority_revision {integer} NOT NULL,+ normalization_version {integer} NOT NULL,+ observed_at {integer} NOT NULL DEFAULT ({now_ms}),+ CONSTRAINT pk_eado PRIMARY KEY (attempt_id,ordinal),+ CONSTRAINT uq_eado_attempt_destination UNIQUE (attempt_id,destination_ref_digest),+ CONSTRAINT ck_eado_ids CHECK (({uuid("attempt_id")}) AND ({uuid("campaign_id")})),+ CONSTRAINT ck_eado_ref CHECK ({h64("destination_ref_digest")}),+ CONSTRAINT ck_eado_shape CHECK (ordinal BETWEEN 0 AND 4095 AND authority_revision BETWEEN 0 AND {MAX_I53} AND normalization_version={DESTINATION_NORMALIZATION_VERSION} AND observed_at BETWEEN 0 AND {MAX_I53}),+ CONSTRAINT fk_eado_attempt FOREIGN KEY (campaign_id,attempt_id) REFERENCES execution_attempts(campaign_id,id) ON UPDATE NO ACTION ON DELETE NO ACTION DEFERRABLE INITIALLY DEFERRED+)""",+ f"""CREATE TABLE execution_attempt_credential_observations (+ attempt_id TEXT NOT NULL,+ campaign_id TEXT NOT NULL,+ ordinal {integer} NOT NULL,+ credential_id TEXT NOT NULL,+ authority_revision {integer} NOT NULL,+ binding_digest TEXT NOT NULL,+ observed_at {integer} NOT NULL DEFAULT ({now_ms}),+ CONSTRAINT pk_eaco PRIMARY KEY (attempt_id,ordinal),+ CONSTRAINT uq_eaco_attempt_credential UNIQUE (attempt_id,credential_id),+ CONSTRAINT ck_eaco_ids CHECK (({uuid("attempt_id")}) AND ({uuid("campaign_id")}) AND ({uuid("credential_id")})),+ CONSTRAINT ck_eaco_digest CHECK ({h64("binding_digest")}),+ CONSTRAINT ck_eaco_shape CHECK (ordinal BETWEEN 0 AND 4095 AND authority_revision BETWEEN 0 AND {MAX_I53} AND observed_at BETWEEN 0 AND {MAX_I53}),+ CONSTRAINT fk_eaco_attempt FOREIGN KEY (campaign_id,attempt_id) REFERENCES execution_attempts(campaign_id,id) ON UPDATE NO ACTION ON DELETE NO ACTION DEFERRABLE INITIALLY DEFERRED+)""",+ "CREATE UNIQUE INDEX uq_ceag_latest_operation ON campaign_execution_actor_grants(latest_operation_id)",+ "CREATE INDEX ix_ceag_actor_state ON campaign_execution_actor_grants(actor_user_id,authority_state,campaign_id)",+ "CREATE UNIQUE INDEX uq_ceda_latest_operation ON campaign_execution_destination_authorities(latest_operation_id)",+ "CREATE UNIQUE INDEX uq_eapa_latest_operation ON execution_approval_authorities(latest_operation_id)",+ "CREATE INDEX ix_eapa_campaign_state ON execution_approval_authorities(campaign_id,authority_state,id)",+ "CREATE INDEX ix_eado_campaign_attempt ON execution_attempt_destination_observations(campaign_id,attempt_id,ordinal)",+ "CREATE INDEX ix_eaco_campaign_attempt ON execution_attempt_credential_observations(campaign_id,attempt_id,ordinal)",+ "CREATE INDEX ix_credentials_execution_authority ON credentials(campaign_id,execution_authority_state,id)",+ ]+ )++ if dialect == "postgresql":+ widened = _v11_receipt_create_statement(dialect)+ operation_check = re.search(+ r"CONSTRAINT ck_eor_operation_code CHECK \((.*?)\),\n", widened, re.S+ )+ shape_check = re.search(+ r"CONSTRAINT ck_eor_operation_shape CHECK \((.*?)\),\n CONSTRAINT ck_eor_outbox_owner_shape",+ widened,+ re.S,+ )+ if operation_check is None or shape_check is None:+ raise RuntimeError("Invalid generation-11 receipt checks")+ statements.extend(+ [+ "ALTER TABLE execution_operation_receipts DROP CONSTRAINT ck_eor_operation_code",+ "ALTER TABLE execution_operation_receipts ADD CONSTRAINT ck_eor_operation_code CHECK ("+ + operation_check.group(1)+ + ")",+ "ALTER TABLE execution_operation_receipts DROP CONSTRAINT ck_eor_operation_shape",+ "ALTER TABLE execution_operation_receipts ADD CONSTRAINT ck_eor_operation_shape CHECK ("+ + shape_check.group(1)+ + ")",+ ]+ )+ else:+ receipt_columns = (+ "operation_id,operation_code,campaign_id,primary_target_id,secondary_target_id,"+ "principal_kind,principal_subject_ref,principal_user_id,"+ "principal_authority_revision_present,principal_authority_revision,"+ "binding_contract_version,request_binding_digest,expected_revision_present,"+ "expected_revision,secondary_expected_revision_present,secondary_expected_revision,"+ "owner_ref,lease_generation,result_code,exact_replay_code,result_binding_digest,"+ "result_identity,result_revision_present,result_revision,secondary_result_identity,"+ "secondary_result_revision_present,secondary_result_revision,created_at"+ )+ statements.extend(+ [+ "DROP TRIGGER trg_eor_immutable_update",+ "DROP TRIGGER trg_eor_immutable_delete",+ "ALTER TABLE execution_operation_receipts RENAME TO execution_operation_receipts_v10",+ _v11_receipt_create_statement(dialect),+ "INSERT INTO execution_operation_receipts("+ + receipt_columns+ + ") SELECT "+ + receipt_columns+ + " FROM execution_operation_receipts_v10",+ "DROP TABLE execution_operation_receipts_v10",+ "CREATE TRIGGER trg_eor_immutable_update BEFORE UPDATE ON execution_operation_receipts BEGIN SELECT RAISE(ABORT,'immutable execution operation receipt'); END",+ "CREATE TRIGGER trg_eor_immutable_delete BEFORE DELETE ON execution_operation_receipts BEGIN SELECT RAISE(ABORT,'immutable execution operation receipt'); END",+ "CREATE INDEX ix_eor_campaign_created ON execution_operation_receipts(campaign_id,created_at,operation_id)",+ "CREATE INDEX ix_eor_primary_target ON execution_operation_receipts(primary_target_id,operation_code,created_at)",+ "CREATE INDEX ix_eor_principal_created ON execution_operation_receipts(principal_kind,principal_subject_ref,created_at,operation_id)",+ ]+ )+ return tuple(statement.strip() for statement in statements)+++SQLITE_ADMISSION_AUTHORITY_V11_DDL: Final[tuple[str, ...]] = admission_authority_v11_ddl("sqlite")+POSTGRES_ADMISSION_AUTHORITY_V11_DDL: Final[tuple[str, ...]] = admission_authority_v11_ddl(+ "postgresql"+)+++def _postgres_catalog_object_names() -> tuple[frozenset[str], frozenset[str]]:+ constraints: set[str] = set()+ indexes: set[str] = set()+ for statement in POSTGRES_LIFECYCLE_DDL:+ table_match = re.match(r"CREATE TABLE ([a-z0-9_]+)", statement)+ alter_match = re.match(r"ALTER TABLE ([a-z0-9_]+)", statement)+ relation = (+ table_match.group(1)+ if table_match is not None+ else alter_match.group(1)+ if alter_match is not None+ else None+ )+ if relation in LIFECYCLE_TABLES:+ constraints.update(re.findall(r"\bCONSTRAINT ([a-z0-9_]+)\b", statement))+ index_match = re.match(+ r"CREATE (?:UNIQUE )?INDEX ([a-z0-9_]+) ON ([a-z0-9_]+)",+ statement,+ )+ if index_match is not None and index_match.group(2) in LIFECYCLE_TABLES:+ indexes.add(index_match.group(1))+ indexes.update(name for name in constraints if name.startswith(("pk_", "uq_")))+ return frozenset(constraints), frozenset(indexes)+++_POSTGRES_LIFECYCLE_CONSTRAINT_NAMES, _POSTGRES_LIFECYCLE_INDEX_NAMES = (+ _postgres_catalog_object_names()+)+_POSTGRES_BASE_CANDIDATE_INDEX_NAMES: Final[frozenset[str]] = frozenset(+ {+ "uq_findings_campaign_id_id",+ "uq_credentials_campaign_id_id",+ "uq_hosts_campaign_id_id",+ "uq_loot_campaign_id_id",+ }+)++_POSTGRES_CATALOG_FACTS_SQL: Final = r"""+WITH lifecycle_relations AS (+ SELECT c.oid,c.relname,n.nspname,c.relkind,c.relpersistence,c.relispartition,+ c.relrowsecurity,c.relforcerowsecurity,c.reloptions,c.relam+ FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace+ WHERE n.nspname=current_schema()+ AND (+ c.relname=ANY(__NAMES__)+ OR c.relname LIKE 'execution\_%' ESCAPE '\'+ OR c.relname LIKE 'logical\_execution%' ESCAPE '\'+ OR c.relname LIKE 'campaign\_execution%' ESCAPE '\'+ OR c.relname=ANY(__BASE_NAMES__)+ )+), facts AS (+ SELECT jsonb_build_object(+ 'kind','relation','schema',r.nspname,'name',r.relname,+ 'relkind',r.relkind::text,'persistence',r.relpersistence::text,+ 'partition',r.relispartition,'rls',r.relrowsecurity,+ 'forced_rls',r.relforcerowsecurity,'options',r.reloptions+ )::text AS fact+ FROM lifecycle_relations r+ UNION ALL+ SELECT jsonb_build_object(+ 'kind','column','relation',r.relname,'ordinal',a.attnum,'name',a.attname,+ 'type',pg_catalog.format_type(a.atttypid,a.atttypmod),'dimensions',a.attndims,+ 'not_null',a.attnotnull,+ 'default',pg_get_expr(d.adbin,d.adrelid,false),+ 'identity',a.attidentity::text,'generated',a.attgenerated::text,+ 'collation',coll.collname+ )::text+ FROM lifecycle_relations r+ JOIN pg_attribute a ON a.attrelid=r.oid AND a.attnum>0 AND NOT a.attisdropped+ LEFT JOIN pg_attrdef d ON d.adrelid=a.attrelid AND d.adnum=a.attnum+ LEFT JOIN pg_collation coll ON coll.oid=NULLIF(a.attcollation,0)+ WHERE r.relkind IN ('r','p')+ UNION ALL+ SELECT jsonb_build_object(+ 'kind','constraint','relation',r.relname,'name',con.conname,+ 'type',con.contype::text,'definition',pg_get_constraintdef(con.oid,false),+ 'local_keys',con.conkey::text,'referenced_schema',rn.nspname,+ 'referenced_relation',rr.relname,'referenced_keys',con.confkey::text,+ 'match',con.confmatchtype::text,'update',con.confupdtype::text,+ 'delete',con.confdeltype::text,'deferrable',con.condeferrable,+ 'deferred',con.condeferred,'validated',con.convalidated+ )::text+ FROM lifecycle_relations r+ JOIN pg_constraint con ON con.conrelid=r.oid+ LEFT JOIN pg_class rr ON rr.oid=con.confrelid+ LEFT JOIN pg_namespace rn ON rn.oid=rr.relnamespace+ UNION ALL+ SELECT jsonb_build_object(+ 'kind','index','relation',r.relname,'name',idx.relname,+ 'unique',i.indisunique,'primary',i.indisprimary,'valid',i.indisvalid,+ 'ready',i.indisready,'method',am.amname,'keys',i.indkey::text,+ 'key_count',i.indnkeyatts,'attribute_count',i.indnatts,+ 'classes',ARRAY(+ SELECT opc_ns.nspname||'.'||opc.opcname+ FROM generate_series(0,i.indnkeyatts-1) AS position+ JOIN pg_opclass opc ON opc.oid=i.indclass[position]+ JOIN pg_namespace opc_ns ON opc_ns.oid=opc.opcnamespace+ ORDER BY position+ )::text,+ 'collations',ARRAY(+ SELECT CASE WHEN i.indcollation[position]=0 THEN ''+ ELSE col_ns.nspname||'.'||col.collname END+ FROM generate_series(0,i.indnkeyatts-1) AS position+ LEFT JOIN pg_collation col ON col.oid=NULLIF(i.indcollation[position],0)+ LEFT JOIN pg_namespace col_ns ON col_ns.oid=col.collnamespace+ ORDER BY position+ )::text,+ 'options',i.indoption::text,'expressions',pg_get_expr(i.indexprs,i.indrelid,false),+ 'predicate',pg_get_expr(i.indpred,i.indrelid,false),+ 'definition',pg_get_indexdef(i.indexrelid,0,false)+ )::text+ FROM lifecycle_relations r+ JOIN pg_index i ON i.indrelid=r.oid+ JOIN pg_class idx ON idx.oid=i.indexrelid+ JOIN pg_am am ON am.oid=idx.relam+ UNION ALL+ SELECT jsonb_build_object(+ 'kind','index','relation',base.relname,'name',r.relname,+ 'unique',i.indisunique,'primary',i.indisprimary,'valid',i.indisvalid,+ 'ready',i.indisready,'method',am.amname,'keys',i.indkey::text,+ 'key_count',i.indnkeyatts,'attribute_count',i.indnatts,+ 'classes',ARRAY(+ SELECT opc_ns.nspname||'.'||opc.opcname+ FROM generate_series(0,i.indnkeyatts-1) AS position+ JOIN pg_opclass opc ON opc.oid=i.indclass[position]+ JOIN pg_namespace opc_ns ON opc_ns.oid=opc.opcnamespace+ ORDER BY position+ )::text,+ 'collations',ARRAY(+ SELECT CASE WHEN i.indcollation[position]=0 THEN ''+ ELSE col_ns.nspname||'.'||col.collname END+ FROM generate_series(0,i.indnkeyatts-1) AS position+ LEFT JOIN pg_collation col ON col.oid=NULLIF(i.indcollation[position],0)+ LEFT JOIN pg_namespace col_ns ON col_ns.oid=col.collnamespace+ ORDER BY position+ )::text,+ 'options',i.indoption::text,'expressions',pg_get_expr(i.indexprs,i.indrelid,false),+ 'predicate',pg_get_expr(i.indpred,i.indrelid,false),+ 'definition',pg_get_indexdef(i.indexrelid,0,false)+ )::text+ FROM lifecycle_relations r+ JOIN pg_index i ON i.indexrelid=r.oid+ JOIN pg_class base ON base.oid=i.indrelid+ JOIN pg_am am ON am.oid=r.relam+ WHERE r.relname=ANY(__BASE_NAMES__)+ UNION ALL+ SELECT jsonb_build_object(+ 'kind','trigger','relation',r.relname,'name',t.tgname,+ 'definition',pg_get_triggerdef(t.oid,false),'enabled',t.tgenabled::text,+ 'internal',t.tgisinternal+ )::text+ FROM lifecycle_relations r JOIN pg_trigger t ON t.tgrelid=r.oid+ WHERE NOT t.tgisinternal+ UNION ALL+ SELECT jsonb_build_object(+ 'kind','function','schema',n.nspname,'name',p.proname,+ 'identity_arguments',pg_get_function_identity_arguments(p.oid),+ 'result',pg_get_function_result(p.oid),+ 'language',l.lanname,'security_definer',p.prosecdef,+ 'leakproof',p.proleakproof,'volatility',p.provolatile::text,+ 'parallel',p.proparallel::text,+ 'definition',pg_get_functiondef(p.oid)+ )::text+ FROM pg_proc p+ JOIN pg_namespace n ON n.oid=p.pronamespace+ JOIN pg_language l ON l.oid=p.prolang+ WHERE n.nspname=current_schema()+ AND p.proname='execution_operation_receipt_immutable'+ UNION ALL+ SELECT jsonb_build_object(+ 'kind','policy','relation',r.relname,'name',p.polname,+ 'permissive',p.polpermissive,'roles',p.polroles::text,'command',p.polcmd::text,+ 'using',pg_get_expr(p.polqual,p.polrelid,false),+ 'check',pg_get_expr(p.polwithcheck,p.polrelid,false)+ )::text+ FROM lifecycle_relations r JOIN pg_policy p ON p.polrelid=r.oid+ UNION ALL+ SELECT jsonb_build_object(+ 'kind','rule','relation',r.relname,'name',rw.rulename,+ 'event',rw.ev_type::text,'instead',rw.is_instead,+ 'definition',pg_get_ruledef(rw.oid,false)+ )::text+ FROM lifecycle_relations r JOIN pg_rewrite rw ON rw.ev_class=r.oid+ WHERE rw.rulename<>'_RETURN'+ UNION ALL+ SELECT jsonb_build_object(+ 'kind','inheritance','relation',r.relname,+ 'parent_schema',pn.nspname,'parent',p.relname,'sequence',inh.inhseqno+ )::text+ FROM lifecycle_relations r+ JOIN pg_inherits inh ON inh.inhrelid=r.oid+ JOIN pg_class p ON p.oid=inh.inhparent+ JOIN pg_namespace pn ON pn.oid=p.relnamespace+ UNION ALL+ SELECT jsonb_build_object(+ 'kind','gateway','singleton_id',singleton_id,'mode',mode,+ 'catalog_digest',catalog_digest,'activation_revision',activation_revision,+ 'activation_at',activation_at,'revision',revision+ )::text+ FROM execution_gateway_state+)+SELECT fact FROM facts ORDER BY fact+"""++# Filled from the exact PostgreSQL-16 catalog produced by the literal revision-0010 DDL.+_POSTGRES_CATALOG_FINGERPRINT_V1: Final = (+ "6e3e4c1249d08b524e2f856aaefd86905fb57d51492384fa683b050222c3f250"+)+++def postgresql_catalog_fingerprint(facts: Sequence[object]) -> str:+ encoded = bytearray(b"ares.execution-lifecycle.pg-catalog.v1\x00")+ for fact in sorted(str(value) for value in facts):+ value = fact.encode("utf-8")+ encoded.extend(struct.pack(">I", len(value)))+ encoded.extend(value)+ return hashlib.sha256(encoded).hexdigest()+++def sqlite_lifecycle_script() -> str:+ return ";\n".join(SQLITE_LIFECYCLE_DDL) + ";\n"+++def sqlite_lifecycle_runtime_script() -> str:+ """Return idempotent runtime-bootstrap DDL with the identical catalog."""+ statements: list[str] = []+ for statement in SQLITE_LIFECYCLE_DDL:+ if statement.startswith("CREATE TABLE "):+ statement = statement.replace("CREATE TABLE ", "CREATE TABLE IF NOT EXISTS ", 1)+ elif statement.startswith("CREATE UNIQUE INDEX "):+ statement = statement.replace(+ "CREATE UNIQUE INDEX ", "CREATE UNIQUE INDEX IF NOT EXISTS ", 1+ )+ elif statement.startswith("CREATE INDEX "):+ statement = statement.replace("CREATE INDEX ", "CREATE INDEX IF NOT EXISTS ", 1)+ elif statement.startswith("CREATE TRIGGER "):+ statement = statement.replace("CREATE TRIGGER ", "CREATE TRIGGER IF NOT EXISTS ", 1)+ elif statement.startswith("INSERT INTO execution_gateway_state"):+ statement = statement.replace("INSERT INTO", "INSERT OR IGNORE INTO", 1)+ statements.append(statement)+ return ";\n".join(statements) + ";\n"+++def sqlite_admission_authority_runtime_script() -> str:+ """Return the exact additive generation-11 SQLite runtime script."""+ return ";\n".join(SQLITE_ADMISSION_AUTHORITY_V11_DDL) + ";\n"+++def canonical_operation_binding_digest(+ domain: str,+ fields: tuple[tuple[str, str | int | bool | None], ...],+) -> str:+ """Hash an explicitly ordered, typed, reduced lifecycle fact sequence."""+ if (+ type(domain) is not str+ or re.fullmatch(r"[a-z][a-z0-9_.:-]{0,127}", domain) is None+ or type(fields) is not tuple+ ):+ raise ValueError("Invalid operation binding contract")+ encoded = bytearray(b"ares.execution-operation-binding.v2\x00")+ seen: set[str] = set()++ def frame(value: bytes) -> None:+ encoded.extend(struct.pack(">I", len(value)))+ encoded.extend(value)++ frame(domain.encode("ascii"))+ for item in fields:+ if type(item) is not tuple or len(item) != 2:+ raise ValueError("Invalid operation binding contract")+ name, value = item+ if (+ type(name) is not str+ or re.fullmatch(r"[a-z][a-z0-9_]{0,127}", name) is None+ or name in seen+ ):+ raise ValueError("Invalid operation binding contract")+ seen.add(name)+ frame(name.encode("ascii"))+ if value is None:+ encoded.extend(b"n")+ elif type(value) is bool:+ encoded.extend(b"b\x01" if value else b"b\x00")+ elif type(value) is int:+ if not 0 <= value <= MAX_I53:+ raise ValueError("Invalid operation binding contract")+ encoded.extend(b"i")+ frame(value.to_bytes(8, "big", signed=False))+ elif type(value) is str:+ encoded.extend(b"s")+ frame(value.encode("utf-8"))+ else:+ raise ValueError("Invalid operation binding contract")+ return hashlib.sha256(encoded).hexdigest()+++@dataclass(frozen=True, slots=True, repr=False, eq=False)+class _ReceiptSpec:+ operation_id: str+ operation_code: str+ campaign_id: str | None+ primary_target_id: str+ secondary_target_id: str | None+ principal_kind: str+ principal_subject_ref: str+ principal_user_id: str | None+ principal_authority_revision: int | None+ request_binding_digest: str+ expected_revision: int | None+ secondary_expected_revision: int | None+ owner_ref: str | None+ lease_generation: int | None++ __hash__ = None+++@dataclass(frozen=True, slots=True, repr=False, eq=False)+class TransitionRequest:+ attempt_id: str+ expected_revision: int+ target_state: AttemptState+ operation_id: str+ owner_ref: str | None = None+ lease_generation: int | None = None+ lease_duration_ms: int | None = None+ cancellation_request_revision: int | None = None+ outcome_code: OutcomeCode | None = None+ authoritative_proof: str = "none"+ resolver_subject_ref: str | None = None+ resolver_user_id: str | None = None+ resolver_authority_revision: int | None = None+ outbox_id: str | None = None+ publication_key: str | None = None+ campaign_id: str | None = None+ actor_subject_ref: str | None = None+ actor_user_id: str | None = None+ actor_authority_revision: int | None = None++ __hash__ = None+++@dataclass(frozen=True, slots=True, repr=False, eq=False)+class OutboxMutation:+ outbox_id: str+ expected_revision: int+ operation_id: str+ owner_ref: str | None = None+ lease_generation: int | None = None+ campaign_id: str | None = None+ attempt_id: str | None = None+ publication_key: str | None = None+ event_code: str | None = None+ purge_poisoned: bool | None = None++ __hash__ = None+++@dataclass(frozen=True, slots=True, repr=False, eq=False)+class OperationResult:+ result: FixedResult+ revision: int | None++ __hash__ = None++ def __bool__(self) -> bool:+ return self.result in {+ FixedResult.APPLIED,+ FixedResult.REPLAYED,+ FixedResult.REPLAYED_BOUND_CHILD,+ FixedResult.REPLAYED_CLOSED,+ }+++@dataclass(frozen=True, slots=True, repr=False, eq=False)+class BudgetConfiguration:+ campaign_id: str+ noise_budget_id: str+ noise_capacity: int+ exfiltration_budget_id: str+ exfiltration_capacity: int+ concurrency_budget_id: str+ concurrency_capacity: int+ operation_id: str+ principal_kind: str | None = "system"+ principal_subject_ref: str | None = SYSTEM_PRINCIPAL_SUBJECT_REF+ principal_user_id: str | None = None+ principal_authority_revision: int | None = None++ __hash__ = None+++@dataclass(frozen=True, slots=True, repr=False, eq=False)+class BudgetReservation:+ campaign_id: str+ attempt_id: str+ noise_budget_id: str+ noise_ledger_id: str+ noise_units: int+ noise_expected_revision: int+ exfiltration_budget_id: str+ exfiltration_ledger_id: str+ exfiltration_units: int+ exfiltration_expected_revision: int+ concurrency_budget_id: str+ concurrency_ledger_id: str+ concurrency_expected_revision: int+ operation_id: str+ principal_kind: str | None = "system"+ principal_subject_ref: str | None = SYSTEM_PRINCIPAL_SUBJECT_REF+ principal_user_id: str | None = None+ principal_authority_revision: int | None = None++ __hash__ = None+++@dataclass(frozen=True, slots=True, repr=False, eq=False)+class BudgetSettlement:+ campaign_id: str+ attempt_id: str+ noise_budget_id: str+ noise_units: int+ noise_actual: int+ noise_expected_revision: int+ exfiltration_budget_id: str+ exfiltration_units: int+ exfiltration_actual: int+ exfiltration_expected_revision: int+ concurrency_budget_id: str+ concurrency_expected_revision: int+ operation_id: str+ principal_kind: str | None = "system"+ principal_subject_ref: str | None = SYSTEM_PRINCIPAL_SUBJECT_REF+ principal_user_id: str | None = None+ principal_authority_revision: int | None = None++ __hash__ = None+++@dataclass(frozen=True, slots=True, repr=False, eq=False)+class _PreparedTerminalV3BudgetSettlement:+ request: BudgetSettlement+ entries: tuple[tuple[str, str, str, int, int, int, str], ...]+++@dataclass(frozen=True, slots=True, repr=False, eq=False)+class ClosureRequest:+ logical_execution_id: str+ attempt_id: str+ outbox_id: str+ expected_attempt_revision: int+ operation_id: str+ authority_subject_ref: str+ authority_user_id: str+ authority_revision: int+ campaign_id: str | None = None++ __hash__ = None+++@dataclass(frozen=True, slots=True, repr=False, eq=False)+class AttemptPolicySnapshot:+ actor_authority_revision: int+ campaign_authority_revision: int+ destination_authority_revision: int+ credential_authority_revision: int+ evaluation_mode: str+ request_structure_valid: bool+ canonicalization_complete: bool+ unknown_fields_absent: bool+ alternate_transport_absent: bool+ bounded_shape_valid: bool+ request_shape_units: int+ descriptor_semantic_digest: str+ catalog_digest: str+ trusted_first_party_binding: bool+ descriptor_binding_current: bool+ descriptor_complete: bool+ static_policy_evaluable: bool+ minimum_role: str+ noise_class: str+ approval_policy: str+ required_capability_mask: int+ descriptor_blocker_mask: int+ preview_ready: bool+ lifecycle_ready: bool+ result_authority_ready: bool+ transport_ready: bool+ future_gateway_eligible: bool+ authority_snapshots_complete: bool+ authority_revisions_current: bool+ actor_authenticated: bool+ actor_active: bool+ actor_role: str+ campaign_active: bool+ actor_campaign_authorized: bool+ approval_present: bool+ approval_current: bool+ approval_exactly_bound: bool+ granted_capability_mask: int+ destination_extraction_complete: bool+ destinations_in_scope: bool+ credential_authority_resolved: bool+ credential_authority_current: bool+ opaque_handles_only: bool+ permitted_handle_kinds_only: bool+ raw_credentials_absent: bool+ ambient_credentials_absent: bool+ budget_authority_resolved: bool+ budget_authority_current: bool+ budget_capacity_available: bool+ gateway_mode_snapshot: str+ gateway_decision_code: str+ policy_evaluation_state: str+ policy_verdict: str | None+ policy_reason_mask: int | None+ external_effect_class: str+ idempotency_class: str+ retry_policy: str+ retry_disposition: str+ cancellation_ownership: str+ compensation_class: str+ timeout_origin: str+ timeout_limit_ms: int+ timeout_settlement: str++ __hash__ = None+++_SNAPSHOT_BINDING_FIELDS: Final[tuple[str, ...]] = (+ "actor_authority_revision",+ "campaign_authority_revision",+ "destination_authority_revision",+ "credential_authority_revision",+ "evaluation_mode",+ "request_structure_valid",+ "canonicalization_complete",+ "unknown_fields_absent",+ "alternate_transport_absent",+ "bounded_shape_valid",+ "request_shape_units",+ "descriptor_semantic_digest",+ "catalog_digest",+ "trusted_first_party_binding",+ "descriptor_binding_current",+ "descriptor_complete",+ "static_policy_evaluable",+ "minimum_role",+ "noise_class",+ "approval_policy",+ "required_capability_mask",+ "descriptor_blocker_mask",+ "preview_ready",+ "lifecycle_ready",+ "result_authority_ready",+ "transport_ready",+ "future_gateway_eligible",+ "authority_snapshots_complete",+ "authority_revisions_current",+ "actor_authenticated",+ "actor_active",+ "actor_role",+ "campaign_active",+ "actor_campaign_authorized",+ "approval_present",+ "approval_current",+ "approval_exactly_bound",+ "granted_capability_mask",+ "destination_extraction_complete",+ "destinations_in_scope",+ "credential_authority_resolved",+ "credential_authority_current",+ "opaque_handles_only",+ "permitted_handle_kinds_only",+ "raw_credentials_absent",+ "ambient_credentials_absent",+ "budget_authority_resolved",+ "budget_authority_current",+ "budget_capacity_available",+ "gateway_mode_snapshot",+ "gateway_decision_code",+ "policy_evaluation_state",+ "policy_verdict",+ "policy_reason_mask",+ "external_effect_class",+ "idempotency_class",+ "retry_policy",+ "retry_disposition",+ "cancellation_ownership",+ "compensation_class",+ "timeout_origin",+ "timeout_limit_ms",+ "timeout_settlement",+)+++def _snapshot_binding_values(+ snapshot: AttemptPolicySnapshot,+) -> tuple[tuple[str, str | int | bool | None], ...]:+ return (+ ("request_contract_version", REQUEST_CONTRACT_VERSION),+ ("policy_contract_version", POLICY_CONTRACT_VERSION),+ ("descriptor_contract_version", DESCRIPTOR_CONTRACT_VERSION),+ ("capability_mask_version", MASK_VERSION),+ ("descriptor_blocker_mask_version", MASK_VERSION),+ (+ "policy_reason_mask_version",+ MASK_VERSION if snapshot.policy_reason_mask is not None else None,+ ),+ ) + tuple((name, getattr(snapshot, name)) for name in _SNAPSHOT_BINDING_FIELDS)+++@dataclass(frozen=True, slots=True, repr=False, eq=False)+class ApprovalBinding:+ approval_id: str+ approval_ref: str+ approver_subject_ref: str+ approver_user_id: str | None+ authority_revision: int+ binding_digest: str++ __hash__ = None+++@dataclass(frozen=True, slots=True, repr=False, eq=False)+class AdmissionRequest:+ logical_execution_id: str+ submission_id: str+ attempt_id: str+ outbox_id: str | None+ publication_key: str | None+ campaign_id: str+ actor_subject_ref: str+ actor_user_id: str+ module_id: str+ ingress_code: str+ initial_state: AttemptState+ operation_id: str+ snapshot: AttemptPolicySnapshot+ approval: ApprovalBinding | None = None+ budgets: BudgetReservation | None = None++ __hash__ = None+++@dataclass(frozen=True, slots=True, repr=False, eq=False)+class RetryRequest:+ logical_execution_id: str+ parent_attempt_id: str+ child: AdmissionRequest+ expected_parent_revision: int++ __hash__ = None+++@dataclass(frozen=True, slots=True, repr=False, eq=False)+class TrustedPrincipal:+ """Opaque actor identity handle; every fact is re-resolved by the store."""++ subject_ref: str+ user_id: str++ __hash__ = None+++@dataclass(frozen=True, slots=True, repr=False, eq=False)+class AdmissionIntentV3:+ """Canonical immutable caller intent; authority facts are never caller supplied."""++ logical_execution_id: str+ submission_id: str+ attempt_id: str+ outbox_id: str | None+ publication_key: str | None+ campaign_id: str+ module_id: str+ ingress_code: str+ operation_id: str+ evaluation_mode: str+ raw_parameters: Mapping[str, Any]+ credential_ids: tuple[str, ...] = ()+ approval_ref: str | None = None+ noise_units: int = 0+ exfiltration_units: int = 0++ __hash__ = None+++@dataclass(frozen=True, slots=True, repr=False, eq=False)+class RetryIntentV3:+ logical_execution_id: str+ parent_attempt_id: str+ child_attempt_id: str+ outbox_id: str | None+ publication_key: str | None+ operation_id: str+ expected_parent_revision: int+ evaluation_mode: str+ raw_parameters: Mapping[str, Any]+ credential_ids: tuple[str, ...] = ()+ approval_ref: str | None = None+ noise_units: int = 0+ exfiltration_units: int = 0++ __hash__ = None+++@dataclass(frozen=True, slots=True, repr=False, eq=False)+class ApprovalAuthorityGrant:+ operation_id: str+ approval_id: str+ approval_ref: str+ campaign_id: str+ submission_id: str+ attempt_id: str+ actor_subject_ref: str+ actor_user_id: str+ module_id: str+ granted_capability_mask: int++ __hash__ = None+++@dataclass(frozen=True, slots=True, repr=False, eq=False)+class GatewayAuthorityMutation:+ operation_id: str+ expected_revision: int+ mode: str++ __hash__ = None+++@dataclass(frozen=True, slots=True, repr=False, eq=False)+class ActorAuthorityMutation:+ operation_id: str+ actor_user_id: str+ expected_revision: int++ __hash__ = None+++@dataclass(frozen=True, slots=True, repr=False, eq=False)+class CampaignAuthorityMutation:+ operation_id: str+ campaign_id: str+ expected_revision: int++ __hash__ = None+++@dataclass(frozen=True, slots=True, repr=False, eq=False)+class CampaignActorGrantMutation:+ operation_id: str+ campaign_id: str+ actor_user_id: str+ expected_revision: int | None++ __hash__ = None+++@dataclass(frozen=True, slots=True, repr=False, eq=False)+class DestinationAuthorityMutation:+ operation_id: str+ campaign_id: str+ expected_revision: int++ __hash__ = None+++@dataclass(frozen=True, slots=True, repr=False, eq=False)+class CredentialAuthorityMutation:+ operation_id: str+ credential_id: str+ expected_revision: int++ __hash__ = None+++@dataclass(frozen=True, slots=True, repr=False, eq=False)+class ApprovalAuthorityMutation:+ operation_id: str+ approval_id: str+ expected_revision: int++ __hash__ = None+++@dataclass(frozen=True, slots=True, repr=False, eq=False)+class _ResolvedPrincipal:+ subject_ref: str+ user_id: str+ role: str+ auth_epoch: int+ authority_revision: int+ binding_digest: str+++@dataclass(frozen=True, slots=True, repr=False, eq=False)+class _PreparedAdmissionV3:+ canonical_parameters: Mapping[str, Any]+ destination_refs: tuple[tuple[str, str], ...]+ immutable_intent_digest: str+ immutable_work_digest: str+++@dataclass(frozen=True, slots=True, repr=False, eq=False)+class _ResolvedAdmissionV3:+ principal: _ResolvedPrincipal+ snapshot: AttemptPolicySnapshot+ approval: ApprovalBinding | None+ budgets: BudgetReservation | None+ destination_binding_digest: str+ credential_binding_digest: str+ approval_binding_digest: str | None+ gateway_revision: int+ gateway_activation_revision: int | None+ grant_revision: int+ destination_observations: tuple[tuple[str, int], ...]+ credential_observations: tuple[tuple[str, int, str], ...]+++class OutputKind(str, Enum):+ FINDING = "finding"+ CREDENTIAL = "credential"+ HOST = "host"+ ARTIFACT = "artifact"+++@dataclass(frozen=True, slots=True, repr=False, eq=False)+class OutputObservation:+ link_id: str+ kind: OutputKind+ target_id: str++ __hash__ = None+++@dataclass(frozen=True, slots=True, repr=False, eq=False)+class TerminalCommitIntentV3:+ """Known-settled terminal facts accepted only from the sealed coordinator."""++ logical_execution_id: str+ campaign_id: str+ attempt_id: str+ expected_attempt_revision: int+ outcome_code: OutcomeCode+ noise_actual: int+ exfiltration_actual: int+ concurrency_actual: int+ execution_result_digest: str | None+ outputs: tuple[OutputObservation, ...] = ()++ __hash__ = None+++@dataclass(frozen=True, slots=True, repr=False, eq=False)+class TerminalCommitRequest:+ logical_execution_id: str+ campaign_id: str+ outbox_id: str+ publication_key: str+ transition: TransitionRequest+ budgets: BudgetSettlement+ outputs: tuple[OutputObservation, ...] = ()++ __hash__ = None+++class _AbortOperationError(Exception):+ def __init__(self, result: OperationResult) -> None:+ self.result = result+++@dataclass(frozen=True, slots=True)+class _CleanupOutcome:+ error: BaseException | None+ cancellation: asyncio.CancelledError | None+++async def _await_owned_cleanup(+ operation: Awaitable[Any],+ *,+ name: str,+) -> _CleanupOutcome:+ async def _capture() -> BaseException | None:+ try:+ await operation+ except BaseException as error:+ return error+ return None++ task = asyncio.create_task(_capture(), name=name)+ cancellation: asyncio.CancelledError | None = None+ while True:+ try:+ error = await asyncio.shield(task)+ except asyncio.CancelledError as caught:+ if cancellation is None:+ cancellation = caught+ continue+ return _CleanupOutcome(error, cancellation)+++def _record_cleanup_failure(primary: BaseException, action: str) -> None:+ note = f"Execution lifecycle cleanup failed [{action}]"+ add_note = getattr(primary, "add_note", None)+ if callable(add_note):+ with suppress(BaseException):+ add_note(note)+++_UUID_RE = re.compile(r"[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\Z")+++def valid_uuid(value: object) -> bool:+ return type(value) is str and _UUID_RE.fullmatch(value) is not None+++def validate_transition_request(request: object) -> FixedResult | None:+ if type(request) is not TransitionRequest:+ return FixedResult.INVALID_CONTRACT+ if not valid_uuid(request.attempt_id) or not valid_uuid(request.operation_id):+ return FixedResult.INVALID_CONTRACT+ if type(request.expected_revision) is not int or not 0 <= request.expected_revision <= MAX_I53:+ return FixedResult.INVALID_CONTRACT+ if type(request.target_state) is not AttemptState:+ return FixedResult.INVALID_CONTRACT+ if request.owner_ref is not None and not valid_uuid(request.owner_ref):+ return FixedResult.INVALID_CONTRACT+ if request.lease_generation is not None and (+ type(request.lease_generation) is not int or not 1 <= request.lease_generation <= MAX_I53+ ):+ return FixedResult.INVALID_CONTRACT+ if (request.owner_ref is None) != (request.lease_generation is None):+ return FixedResult.INVALID_CONTRACT+ if request.lease_duration_ms is not None and (+ type(request.lease_duration_ms) is not int+ or not MIN_TIMEOUT_MS <= request.lease_duration_ms <= MAX_TIMEOUT_MS+ ):+ return FixedResult.INVALID_CONTRACT+ if request.cancellation_request_revision is not None and (+ type(request.cancellation_request_revision) is not int+ or not 1 <= request.cancellation_request_revision <= MAX_I53+ ):+ return FixedResult.INVALID_CONTRACT+ if request.outcome_code is not None and type(request.outcome_code) is not OutcomeCode:+ return FixedResult.INVALID_CONTRACT+ if type(request.authoritative_proof) is not str or request.authoritative_proof not in {+ "none",+ "no_dispatch",+ "local_completion",+ "process_group_exit",+ "worker_terminal_ack",+ "external_settlement_ack",+ "cancellation_no_result_ack",+ "timeout_termination_ack",+ "bounded_recovery_exhausted",+ "unresolved",+ }:+ return FixedResult.INVALID_CONTRACT+ resolver_present = any(+ value is not None+ for value in (+ request.resolver_subject_ref,+ request.resolver_user_id,+ request.resolver_authority_revision,+ )+ )+ if resolver_present and (+ not valid_uuid(request.resolver_subject_ref)+ or not valid_uuid(request.resolver_user_id)+ or type(request.resolver_authority_revision) is not int+ or not 0 <= request.resolver_authority_revision <= MAX_I53+ or request.owner_ref is not None+ ):+ return FixedResult.INVALID_CONTRACT+ if request.outbox_id is not None and not valid_uuid(request.outbox_id):+ return FixedResult.INVALID_CONTRACT+ if request.publication_key is not None and not valid_uuid(request.publication_key):+ return FixedResult.INVALID_CONTRACT+ if not valid_uuid(request.campaign_id):+ return FixedResult.INVALID_CONTRACT+ actor_present = any(+ value is not None+ for value in (+ request.actor_subject_ref,+ request.actor_user_id,+ request.actor_authority_revision,+ )+ )+ if resolver_present or request.owner_ref is not None:+ if actor_present:+ return FixedResult.INVALID_CONTRACT+ elif (+ not valid_uuid(request.actor_subject_ref)+ or not valid_uuid(request.actor_user_id)+ or type(request.actor_authority_revision) is not int+ or not 0 <= request.actor_authority_revision <= MAX_I53+ ):+ return FixedResult.INVALID_CONTRACT+ return None+++def retry_delay_ms(delivery_attempt_count: object) -> int | None:+ """Return the literal bounded retry delay for attempts 1 through 19."""+ if type(delivery_attempt_count) is not int or not 1 <= delivery_attempt_count <= 19:+ return None+ mapping = (+ 1_000,+ 2_000,+ 4_000,+ 8_000,+ 16_000,+ 32_000,+ 64_000,+ 128_000,+ 256_000,+ 512_000,+ 600_000,+ 600_000,+ 600_000,+ 600_000,+ 600_000,+ 600_000,+ 600_000,+ 600_000,+ 600_000,+ )+ return mapping[delivery_attempt_count - 1]+++def _question_to_postgres(sql: str) -> str:+ parts = sql.split("?")+ if len(parts) == 1:+ return sql+ result = parts[0]+ for index, part in enumerate(parts[1:], 1):+ result += f"${index}{part}"+ return result+++class ExecutionLifecycleStore:+ """Internal additive CAS store for an aiosqlite connection or asyncpg pool."""++ def __init__(self, backend: Any, dialect: str) -> None:+ if dialect not in {"sqlite", "postgresql"}:+ raise ValueError("Unsupported lifecycle dialect")+ self._backend = backend+ self._dialect = dialect++ @staticmethod+ def _valid_expected_revision(value: object, *, optional: bool = False) -> bool:+ return (optional and value is None) or (type(value) is int and 0 <= value < MAX_I53)++ @staticmethod+ def _actor_authority_binding(+ user_id: str,+ username: str,+ role: str,+ is_active: bool,+ auth_epoch: int,+ ) -> str:+ return canonical_operation_binding_digest(+ "actor-authority",+ (+ ("user_id", user_id),+ ("username", username),+ ("role", role),+ ("is_active", is_active),+ ("auth_epoch", auth_epoch),+ ),+ )++ @staticmethod+ def _credential_authority_binding(row: Any) -> str:+ return canonical_operation_binding_digest(+ "credential-authority",+ (+ ("credential_id", str(ExecutionLifecycleStore._value(row, "id", 0))),+ ("campaign_id", str(ExecutionLifecycleStore._value(row, "campaign_id", 1))),+ ("host_id", ExecutionLifecycleStore._value(row, "host_id", 2)),+ ("username", str(ExecutionLifecycleStore._value(row, "username", 3))),+ ("credential_type", str(ExecutionLifecycleStore._value(row, "cred_type", 4))),+ ("domain", ExecutionLifecycleStore._value(row, "domain", 5)),+ ("source_module", ExecutionLifecycleStore._value(row, "source_module", 6)),+ ),+ )++ @staticmethod+ def _campaign_authority_binding(row: Any, destination_binding_digest: str) -> str:+ return canonical_operation_binding_digest(+ "campaign-authority",+ (+ ("campaign_id", str(ExecutionLifecycleStore._value(row, "id", 0))),+ ("operator", str(ExecutionLifecycleStore._value(row, "operator", 1))),+ ("status", str(ExecutionLifecycleStore._value(row, "status", 2))),+ ("noise_profile", str(ExecutionLifecycleStore._value(row, "noise_profile", 3))),+ ("destination_binding_digest", destination_binding_digest),+ ),+ )++ @staticmethod+ def _grant_authority_binding(+ campaign_id: str,+ actor_user_id: str,+ authority_state: str,+ ) -> str:+ return canonical_operation_binding_digest(+ "campaign-actor-grant",+ (+ ("campaign_id", campaign_id),+ ("actor_user_id", actor_user_id),+ ("authority_state", authority_state),+ ),+ )++ async def _v11_authority_revision_current(+ self,+ connection: Any,+ *,+ revision: int,+ latest_operation_id: object,+ latest_operation_base_revision: object,+ latest_operation_code: object,+ operation_prefix: str,+ campaign_id: str | None,+ target_id: str,+ destination_baseline: bool = False,+ ) -> bool:+ if revision == 0:+ if destination_baseline:+ return (+ valid_uuid(latest_operation_id)+ and latest_operation_base_revision == 0+ and latest_operation_code == "update"+ )+ return (+ latest_operation_id is None+ and latest_operation_base_revision is None+ and latest_operation_code is None+ )+ if (+ revision < 1+ or not valid_uuid(latest_operation_id)+ or type(latest_operation_base_revision) is not int+ or latest_operation_base_revision != revision - 1+ or latest_operation_code not in {"activate", "update", "revoke"}+ or (+ operation_prefix == "destination_authority_" and latest_operation_code == "activate"+ )+ ):+ return False+ receipt = await self._fetchrow(+ connection,+ "SELECT operation_code,campaign_id,primary_target_id,"+ "expected_revision_present,expected_revision,result_code,"+ "result_revision_present,result_revision "+ "FROM execution_operation_receipts WHERE operation_id=?",+ (latest_operation_id,),+ )+ return receipt is not None and (+ self._value(receipt, "operation_code", 0)+ == operation_prefix + str(latest_operation_code)+ and self._value(receipt, "campaign_id", 1) == campaign_id+ and self._value(receipt, "primary_target_id", 2) == target_id+ and bool(self._value(receipt, "expected_revision_present", 3))+ and self._value(receipt, "expected_revision", 4) == latest_operation_base_revision+ and self._value(receipt, "result_code", 5) == FixedResult.APPLIED.value+ and bool(self._value(receipt, "result_revision_present", 6))+ and self._value(receipt, "result_revision", 7) == revision+ )++ @staticmethod+ def _approval_authority_binding(+ row: Any,+ *,+ authority_state: str | None = None,+ ) -> str:+ return canonical_operation_binding_digest(+ "approval-authority",+ (+ ("approval_ref", str(ExecutionLifecycleStore._value(row, "approval_ref", 1))),+ ("submission_id", str(ExecutionLifecycleStore._value(row, "submission_id", 8))),+ ("attempt_id", str(ExecutionLifecycleStore._value(row, "attempt_id", 9))),+ (+ "actor_subject_ref",+ str(ExecutionLifecycleStore._value(row, "actor_subject_ref", 10)),+ ),+ (+ "actor_user_id",+ str(ExecutionLifecycleStore._value(row, "actor_user_id", 11)),+ ),+ ("module_id", str(ExecutionLifecycleStore._value(row, "module_id", 12))),+ (+ "granted_capability_mask",+ int(ExecutionLifecycleStore._value(row, "granted_capability_mask", 13)),+ ),+ (+ "descriptor_semantic_digest",+ str(ExecutionLifecycleStore._value(row, "descriptor_semantic_digest", 14)),+ ),+ (+ "approver_subject_ref",+ str(ExecutionLifecycleStore._value(row, "approver_subject_ref", 2)),+ ),+ (+ "approver_user_id",+ ExecutionLifecycleStore._value(row, "approver_user_id", 3),+ ),+ (+ "authority_state",+ authority_state+ if authority_state is not None+ else str(ExecutionLifecycleStore._value(row, "authority_state", 6)),+ ),+ ),+ )++ @staticmethod+ def _canonical_destination_values(+ scope_json: object,+ targets_json: object,+ ) -> tuple[str, ...]:+ try:+ scope = json.loads(str(scope_json))+ targets = json.loads(str(targets_json))+ except (TypeError, ValueError, json.JSONDecodeError):+ raise ValueError("Invalid destination authority") from None+ if type(scope) is not list or type(targets) is not list:+ raise ValueError("Invalid destination authority")+ values: set[str] = set()+ for entry in scope:+ if type(entry) is not dict or set(entry) - {"cidr", "description"}:+ raise ValueError("Invalid destination authority")+ cidr = entry.get("cidr")+ if type(cidr) is not str:+ raise ValueError("Invalid destination authority")+ try:+ value = str(ipaddress.ip_network(cidr, strict=False))+ except ValueError:+ raise ValueError("Invalid destination authority") from None+ values.add("scope:" + value)+ for item in targets:+ if type(item) is not str:+ raise ValueError("Invalid destination authority")+ value = item.strip()+ try:+ value = (+ str(ipaddress.ip_network(value, strict=False))+ if "/" in value+ else str(ipaddress.ip_address(value))+ )+ except ValueError:+ value = value.lower().rstrip(".")+ if re.fullmatch(r"[a-z0-9][a-z0-9._-]{0,2047}", value) is None:+ raise ValueError("Invalid destination authority") from None+ values.add("target:" + value)+ return tuple(sorted(values))++ @staticmethod+ def _destination_authority_facts(values: tuple[str, ...]) -> tuple[int, str, str]:+ encoded = bytearray(b"ares.destination-set.v1\x00")+ for value in values:+ item = value.encode("utf-8")+ encoded.extend(len(item).to_bytes(4, "big"))+ encoded.extend(item)+ digest = hashlib.sha256(encoded).hexdigest()+ binding = canonical_operation_binding_digest(+ "destination-authority",+ (+ ("normalization_version", DESTINATION_NORMALIZATION_VERSION),+ ("destination_count", len(values)),+ ("destination_set_digest", digest),+ ),+ )+ return len(values), digest, binding++ @staticmethod+ def _raw_credential_material_present(+ values: object,+ fields: Sequence[Any],+ ) -> bool:+ """Reject caller-supplied secret material; v3 accepts opaque IDs only."""+ if not isinstance(values, Mapping):+ return False+ for spec in fields:+ name = getattr(spec, "name", None)+ if type(name) is not str or name not in values:+ continue+ value = values[name]+ nonempty = (+ value is not None and value != "" and value != () and value != [] and value != {}+ )+ sensitivity = getattr(getattr(spec, "sensitivity", None), "value", None)+ if nonempty and (+ sensitivity == "secret" or bool(getattr(spec, "legacy_schema_secret", False))+ ):+ return True+ nested = getattr(spec, "nested_fields", ())+ if nested and ExecutionLifecycleStore._raw_credential_material_present(value, nested):+ return True+ return False++ @staticmethod+ def _destination_is_allowed(requested: str, allowed: tuple[str, ...]) -> bool:+ kind, separator, canonical = requested.partition("|")+ if not separator or kind not in {"host", "domain", "network_endpoint"}:+ return False+ requested = canonical+ if requested in allowed:+ return True+ if not requested.startswith("target:"):+ return False+ candidate = requested.removeprefix("target:")+ try:+ if "/" in candidate:+ candidate_network = ipaddress.ip_network(candidate, strict=False)+ return any(+ candidate_network.subnet_of(+ ipaddress.ip_network(item.removeprefix("scope:"), strict=False)+ )+ for item in allowed+ if item.startswith("scope:")+ )+ candidate_address = ipaddress.ip_address(candidate)+ return any(+ candidate_address in ipaddress.ip_network(item.removeprefix("scope:"), strict=False)+ for item in allowed+ if item.startswith("scope:")+ )+ except ValueError:+ return False++ @staticmethod+ def _valid_initial_v3_intent_shape(intent: object) -> bool:+ return not (+ type(intent) is not AdmissionIntentV3+ or not all(+ valid_uuid(value)+ for value in (+ intent.logical_execution_id,+ intent.submission_id,+ intent.attempt_id,+ intent.campaign_id,+ intent.operation_id,+ )+ )+ or (intent.outbox_id is not None and not valid_uuid(intent.outbox_id))+ or (intent.publication_key is not None and not valid_uuid(intent.publication_key))+ or (intent.outbox_id is None) != (intent.publication_key is None)+ or intent.evaluation_mode not in {"preview", "live"}+ or intent.ingress_code not in INGRESS_CODES+ or type(intent.credential_ids) is not tuple+ or len(intent.credential_ids) > 256+ or len(set(intent.credential_ids)) != len(intent.credential_ids)+ or not all(valid_uuid(value) for value in intent.credential_ids)+ or (intent.approval_ref is not None and not valid_uuid(intent.approval_ref))+ or type(intent.noise_units) is not int+ or not 0 <= intent.noise_units <= MAX_I53+ or type(intent.exfiltration_units) is not int+ or not 0 <= intent.exfiltration_units <= MAX_I53+ or not isinstance(intent.raw_parameters, Mapping)+ )++ @staticmethod+ def _prepared_admission(intent: AdmissionIntentV3) -> _PreparedAdmissionV3 | None:+ if not ExecutionLifecycleStore._valid_initial_v3_intent_shape(intent):+ return None+ try:+ from ares.modules.descriptors import (+ canonicalize_parameters,+ extract_destinations,+ require_descriptor,+ )++ descriptor = require_descriptor(intent.module_id)+ if ExecutionLifecycleStore._raw_credential_material_present(+ intent.raw_parameters,+ descriptor.parameter_fields,+ ):+ return None+ canonical = canonicalize_parameters(intent.module_id, intent.raw_parameters)+ values = {key: canonical.values[key] for key in sorted(canonical.values)}+ extracted = extract_destinations(intent.module_id, canonical)+ destination_refs = tuple(+ sorted(+ {+ (item.kind.value, str(item.value).strip().lower())+ for item in extracted+ if str(item.value).strip()+ }+ )+ )+ canonical_json = json.dumps(+ values,+ sort_keys=True,+ separators=(",", ":"),+ ensure_ascii=False,+ default=str,+ )+ copied_values = json.loads(canonical_json)+ parameter_digest = hashlib.sha256(canonical_json.encode("utf-8")).hexdigest()+ credential_ids_digest = hashlib.sha256(+ "\x00".join(intent.credential_ids).encode("ascii")+ ).hexdigest()+ work_digest = canonical_operation_binding_digest(+ "admission-immutable-work",+ (+ ("campaign_id", intent.campaign_id),+ ("module_id", intent.module_id),+ ("ingress_code", intent.ingress_code),+ ("evaluation_mode", intent.evaluation_mode),+ ("parameter_digest", parameter_digest),+ ("credential_ids_digest", credential_ids_digest),+ ("noise_units", intent.noise_units),+ ("exfiltration_units", intent.exfiltration_units),+ ),+ )+ immutable_digest = ExecutionLifecycleStore._initial_v3_replay_digest(intent)+ if immutable_digest is None:+ return None+ except (TypeError, ValueError, RuntimeError):+ return None+ return _PreparedAdmissionV3(+ copied_values,+ destination_refs,+ immutable_digest,+ work_digest,+ )++ @staticmethod+ def _descriptor_policy_facts(descriptor: Any) -> tuple[str, str, str, int, int]:+ capability_names = {+ "cap_net": 1,+ "cap_exec": 2,+ "cap_fs": 4,+ "cap_process": 8,+ }+ blocker_names = {+ "AMBIENT_CREDENTIALS_FORBIDDEN": 1,+ "CANCELLATION_OWNERSHIP_UNPROVEN": 2,+ "DYNAMIC_DESTINATION_UNBOUNDED": 4,+ "DEFAULT_FACTORY_UNEVALUATED": 8,+ "LLM_EGRESS_POLICY_REQUIRED": 16,+ "LIFECYCLE_CONTRACT_UNPROVEN": 32,+ "RAW_CREDENTIAL_INPUT": 64,+ "RESULT_AUTHORITY_UNPROVEN": 128,+ "SENSITIVE_NONEMPTY_DEFAULT": 256,+ }+ required_mask = 0+ for capability in descriptor.required_capabilities:+ if capability.value not in capability_names:+ raise _AbortOperationError(OperationResult(FixedResult.AUTHORITY_STALE, None))+ required_mask |= capability_names[capability.value]+ blocker_mask = 0+ for blocker in descriptor.blocker_codes:+ blocker_mask |= blocker_names.get(blocker.value, 0)+ return (+ descriptor.minimum_role.value,+ descriptor.opsec.value,+ "attempt_bound" if descriptor.explicit_attempt_approval else "none",+ required_mask,+ blocker_mask,+ )++ async def _resolve_admission_v3(+ self,+ connection: Any,+ principal: TrustedPrincipal,+ intent: AdmissionIntentV3,+ prepared: _PreparedAdmissionV3,+ *,+ suffix: str,+ reserve_budgets: bool = True,+ ) -> _ResolvedAdmissionV3 | None:+ from ares.modules.descriptors import get_descriptor++ # Generation-11 admission has one intersection lock order. The gateway+ # precedes the mutable principal, campaign, grant, descriptor/catalog,+ # destination, credential, approval, and budget authorities.+ gateway = await self._fetchrow(+ connection,+ "SELECT mode,catalog_digest,activation_revision,revision "+ "FROM execution_gateway_state WHERE singleton_id=1" + suffix,+ (),+ )+ resolved = await self._resolve_principal(connection, principal, suffix=suffix)+ if resolved is None:+ raise _AbortOperationError(OperationResult(FixedResult.AUTHORITY_STALE, None))+ campaign = await self._fetchrow(+ connection,+ "SELECT c.id,c.operator,c.status,c.noise_profile,ca.authority_state,"+ "ca.authority_revision,ca.authority_binding_digest,"+ "ca.authority_latest_operation_id,"+ "ca.authority_latest_operation_base_revision,"+ "ca.authority_latest_operation_code "+ "FROM campaigns c JOIN campaign_execution_authority_revisions ca "+ "ON ca.campaign_id=c.id WHERE c.id=?" + suffix,+ (intent.campaign_id,),+ )+ grant = await self._fetchrow(+ connection,+ "SELECT authority_state,revision,binding_digest "+ "FROM campaign_execution_actor_grants "+ "WHERE campaign_id=? AND actor_user_id=?" + suffix,+ (intent.campaign_id, resolved.user_id),+ )+ descriptor = get_descriptor(intent.module_id)+ if descriptor is None:+ raise _AbortOperationError(OperationResult(FixedResult.INVALID_CONTRACT, None))+ destination = await self._fetchrow(+ connection,+ "SELECT authority_state,revision,normalization_version,destination_count,"+ "destination_set_digest,binding_digest,latest_operation_id,"+ "latest_operation_base_revision,latest_operation_code FROM "+ "campaign_execution_destination_authorities WHERE campaign_id=?" + suffix,+ (intent.campaign_id,),+ )+ if gateway is None or campaign is None or grant is None or destination is None:+ raise _AbortOperationError(OperationResult(FixedResult.AUTHORITY_STALE, None))+ destination_state = str(self._value(destination, "authority_state", 0))+ destination_revision = int(self._value(destination, "revision", 1))+ destination_binding = str(self._value(destination, "binding_digest", 5))+ destination_revision_current = await self._v11_authority_revision_current(+ connection,+ revision=destination_revision,+ latest_operation_id=self._value(destination, "latest_operation_id", 6),+ latest_operation_base_revision=self._value(+ destination, "latest_operation_base_revision", 7+ ),+ latest_operation_code=self._value(destination, "latest_operation_code", 8),+ operation_prefix="destination_authority_",+ campaign_id=intent.campaign_id,+ target_id=intent.campaign_id,+ destination_baseline=True,+ )+ credential_rows: list[Any] = []+ for credential_id in sorted(intent.credential_ids):+ credential_suffix = " FOR UPDATE OF c" if self._dialect == "postgresql" else ""+ row = await self._fetchrow(+ connection,+ "SELECT c.id,c.campaign_id,c.host_id,c.username,c.cred_type,c.domain,"+ "c.source_module,c.execution_authority_state,"+ "c.execution_authority_revision,c.execution_authority_binding_digest,"+ "c.execution_authority_latest_operation_id,"+ "c.execution_authority_latest_operation_base_revision,"+ "c.execution_authority_latest_operation_code "+ "FROM credentials c WHERE c.id=?" + credential_suffix,+ (credential_id,),+ )+ if row is None:+ raise _AbortOperationError(OperationResult(FixedResult.AUTHORITY_STALE, None))+ host_id = self._value(row, "host_id", 2)+ if host_id is not None:+ host = await self._fetchrow(+ connection,+ "SELECT campaign_id FROM hosts WHERE id=?" + suffix,+ (host_id,),+ )+ if host is None or self._value(host, "campaign_id", 0) != intent.campaign_id:+ raise _AbortOperationError(OperationResult(FixedResult.AUTHORITY_STALE, None))+ credential_rows.append(row)+ credential_bindings_current = True+ for row in credential_rows:+ revision = int(self._value(row, "execution_authority_revision", 8))+ credential_id = str(self._value(row, "id", 0))+ revision_current = await self._v11_authority_revision_current(+ connection,+ revision=revision,+ latest_operation_id=self._value(row, "execution_authority_latest_operation_id", 10),+ latest_operation_base_revision=self._value(+ row, "execution_authority_latest_operation_base_revision", 11+ ),+ latest_operation_code=self._value(+ row, "execution_authority_latest_operation_code", 12+ ),+ operation_prefix="credential_authority_",+ campaign_id=intent.campaign_id,+ target_id=credential_id,+ )+ credential_bindings_current = credential_bindings_current and (+ str(self._value(row, "campaign_id", 1)) == intent.campaign_id+ and self._value(row, "execution_authority_binding_digest", 9)+ == self._credential_authority_binding(row)+ and revision_current+ )+ credentials_current = credential_bindings_current and all(+ self._value(row, "execution_authority_state", 7) == "active" for row in credential_rows+ )+ credential_observations = tuple(+ (+ str(self._value(row, "id", 0)),+ int(self._value(row, "execution_authority_revision", 8)),+ str(self._value(row, "execution_authority_binding_digest", 9)),+ )+ for row in credential_rows+ )+ credential_binding = canonical_operation_binding_digest(+ "admission-credential-observations",+ (+ ("credential_count", len(credential_observations)),+ (+ "credential_observations_digest",+ hashlib.sha256(+ "\x00".join(+ f"{item[0]}:{item[1]}:{item[2]}" for item in credential_observations+ ).encode("utf-8")+ ).hexdigest(),+ ),+ ),+ )+ approval_row = None+ if intent.approval_ref is not None:+ approval_row = await self._fetchrow(+ connection,+ "SELECT id,approval_ref,approver_subject_ref,approver_user_id,revision,"+ "binding_digest,authority_state,campaign_id,submission_id,attempt_id,"+ "actor_subject_ref,actor_user_id,module_id,granted_capability_mask,"+ "descriptor_semantic_digest FROM execution_approval_authorities "+ "WHERE approval_ref=?" + suffix,+ (intent.approval_ref,),+ )+ approval = (+ None+ if approval_row is None+ else ApprovalBinding(+ str(self._value(approval_row, "id", 0)),+ str(self._value(approval_row, "approval_ref", 1)),+ str(self._value(approval_row, "approver_subject_ref", 2)),+ self._value(approval_row, "approver_user_id", 3),+ int(self._value(approval_row, "revision", 4)),+ str(self._value(approval_row, "binding_digest", 5)),+ )+ )+ approval_current = bool(+ approval_row is not None+ and self._value(approval_row, "authority_state", 6) == "active"+ and self._value(approval_row, "campaign_id", 7) == intent.campaign_id+ and self._value(approval_row, "submission_id", 8) == intent.submission_id+ and self._value(approval_row, "attempt_id", 9) == intent.attempt_id+ and self._value(approval_row, "actor_subject_ref", 10) == resolved.subject_ref+ and self._value(approval_row, "actor_user_id", 11) == resolved.user_id+ and self._value(approval_row, "module_id", 12) == intent.module_id+ and self._value(approval_row, "descriptor_semantic_digest", 14)+ == descriptor.semantic_digest+ and self._value(approval_row, "binding_digest", 5)+ == self._approval_authority_binding(approval_row)+ )+ granted_mask = (+ 0+ if approval_row is None+ else int(self._value(approval_row, "granted_capability_mask", 13))+ )+ minimum_role, noise_class, approval_policy, capability_mask, blocker_mask = (+ self._descriptor_policy_facts(descriptor)+ )+ if approval_policy == "none" and intent.approval_ref is not None:+ raise _AbortOperationError(OperationResult(FixedResult.INVALID_CONTRACT, None))+ credential_kind_map = {+ "cleartext": {"password", "vault_record"},+ "ntlm": {"ntlm_hash", "hash_material", "vault_record"},+ "krb5_tgs": {"hash_material", "vault_record"},+ "krb5_asrep": {"hash_material", "vault_record"},+ "krb5_tgt": {"vault_record"},+ "ssh_key": {"ssh_private_key", "vault_record"},+ "api_key": {"api_token", "vault_record"},+ "jwt": {"api_token", "vault_record"},+ "certificate": {"vault_record"},+ "cookie": {"vault_record"},+ }+ policy_state = descriptor.credential_policy.state.value+ allowed_kinds = {item.value for item in descriptor.credential_policy.allowed_handle_kinds}+ credential_policy_current = not descriptor.credential_policy.ambient_dependencies and (+ (policy_state == "not_applicable" and not credential_rows)+ or (+ policy_state == "supported"+ and all(+ bool(+ credential_kind_map.get(str(self._value(row, "cred_type", 4)), set())+ & allowed_kinds+ )+ for row in credential_rows+ )+ )+ )+ destination_values: set[str] = set()+ for kind, value in prepared.destination_refs:+ normalized = self._canonical_destination_values(+ json.dumps([]),+ json.dumps([value]),+ )+ if len(normalized) != 1:+ raise _AbortOperationError(OperationResult(FixedResult.INVALID_CONTRACT, None))+ destination_values.add(kind + "|" + normalized[0])+ allowed_values = self._canonical_destination_values(+ # The persisted aggregate is the authority; current campaign bytes are+ # reduced again to prove the aggregate remains current.+ await self._scalar_campaign_value(connection, intent.campaign_id, "scope_json", suffix),+ await self._scalar_campaign_value(+ connection, intent.campaign_id, "targets_json", suffix+ ),+ )+ current_count, current_digest, current_binding = self._destination_authority_facts(+ allowed_values+ )+ destinations_current = (+ destination_state == "active"+ and int(self._value(destination, "normalization_version", 2))+ == DESTINATION_NORMALIZATION_VERSION+ and int(self._value(destination, "destination_count", 3)) == current_count+ and self._value(destination, "destination_set_digest", 4) == current_digest+ and destination_binding == current_binding+ )+ destinations_in_scope = all(+ self._destination_is_allowed(item, allowed_values) for item in destination_values+ )+ gateway_mode = str(self._value(gateway, "mode", 0))+ gateway_mode_current = gateway_mode in {+ "disabled",+ "shadow_candidate",+ "enforced",+ "emergency_disabled",+ }+ gateway_revision = int(self._value(gateway, "revision", 3))+ gateway_activation_revision = self._value(gateway, "activation_revision", 2)+ gateway_revision_current = (+ gateway_revision == 0 and gateway_activation_revision is None+ if gateway_mode == "disabled"+ else gateway_revision >= 1 and gateway_activation_revision == gateway_revision+ )+ catalog_digest = self._descriptor_catalog_digest()+ gateway_catalog_current = (+ self._value(gateway, "catalog_digest", 1) is None+ if gateway_mode == "disabled"+ else self._value(gateway, "catalog_digest", 1) == catalog_digest+ )+ campaign_binding = self._campaign_authority_binding(campaign, destination_binding)+ campaign_binding_current = (+ self._value(campaign, "authority_binding_digest", 6) == campaign_binding+ )+ campaign_revision_current = await self._v11_authority_revision_current(+ connection,+ revision=int(self._value(campaign, "authority_revision", 5)),+ latest_operation_id=self._value(campaign, "authority_latest_operation_id", 7),+ latest_operation_base_revision=self._value(+ campaign, "authority_latest_operation_base_revision", 8+ ),+ latest_operation_code=self._value(campaign, "authority_latest_operation_code", 9),+ operation_prefix="campaign_authority_",+ campaign_id=intent.campaign_id,+ target_id=intent.campaign_id,+ )+ campaign_active = self._value(campaign, "authority_state", 4) == "active" and self._value(+ campaign, "status", 2+ ) in {"created", "running"}+ grant_state = str(self._value(grant, "authority_state", 0))+ grant_active = grant_state == "active" and self._value(+ grant, "binding_digest", 2+ ) == self._grant_authority_binding(+ intent.campaign_id,+ resolved.user_id,+ "active",+ )+ if (+ not gateway_mode_current+ or not gateway_revision_current+ or not gateway_catalog_current+ or not campaign_binding_current+ or not campaign_revision_current+ or not campaign_active+ or not grant_active+ or not destinations_current+ or not destination_revision_current+ or not credentials_current+ or (intent.approval_ref is not None and not approval_current)+ ):+ raise _AbortOperationError(OperationResult(FixedResult.AUTHORITY_STALE, None))+ if gateway_mode == "emergency_disabled":+ initial_verdict, reason_mask = None, None+ evaluation_state = "not_evaluated"+ gateway_decision = "emergency_disabled"+ else:+ from ares.core.execution_policy import (+ ApprovalPolicy,+ AuthorityFactsV1,+ BlockerBits,+ CapabilityBits,+ DescriptorFactsV1,+ EvaluationMode,+ NoiseClass,+ PolicyInputV1,+ PolicyReason,+ PolicyVerdict,+ RequestFactsV1,+ RoleRank,+ evaluate_policy,+ )++ if resolved.role not in {"reporter", "operator", "team_lead", "admin"}:+ raise _AbortOperationError(OperationResult(FixedResult.AUTHORITY_STALE, None))+ # ``reporter`` is a persisted lifecycle role outside the pure+ # policy kernel's RoleRank domain. Evaluate it with the least+ # privileged representable rank so descriptor/request rejection+ # keeps precedence, then apply the exact lifecycle role ceiling.+ role = {+ "reporter": RoleRank.OPERATOR,+ "operator": RoleRank.OPERATOR,+ "team_lead": RoleRank.TEAM_LEAD,+ "admin": RoleRank.ADMIN,+ }[resolved.role]+ minimum = {+ "operator": RoleRank.OPERATOR,+ "team_lead": RoleRank.TEAM_LEAD,+ "admin": RoleRank.ADMIN,+ }[minimum_role]+ decision = evaluate_policy(+ PolicyInputV1(+ RequestFactsV1(+ 1,+ EvaluationMode(intent.evaluation_mode),+ True,+ True,+ True,+ True,+ True,+ len(prepared.canonical_parameters),+ ),+ DescriptorFactsV1(+ 1,+ True,+ True,+ descriptor.descriptor_complete,+ True,+ minimum,+ NoiseClass(noise_class),+ ApprovalPolicy(approval_policy),+ CapabilityBits(capability_mask),+ BlockerBits(blocker_mask),+ descriptor.descriptor_complete,+ descriptor.idempotency.value != "unproven_current_contract",+ True,+ True,+ descriptor.future_gateway_eligible,+ ),+ AuthorityFactsV1(+ 1,+ True,+ True,+ True,+ True,+ role,+ campaign_active,+ grant_active,+ approval_row is not None,+ approval_current,+ approval_current,+ CapabilityBits(granted_mask),+ True,+ destinations_in_scope,+ True,+ credentials_current,+ True,+ credential_policy_current,+ True,+ not descriptor.credential_policy.ambient_dependencies,+ True,+ True,+ True,+ ),+ )+ )+ initial_verdict = decision.verdict.value+ reasons = decision.reasons+ if resolved.role == "reporter" and initial_verdict != "rejected":+ initial_verdict = PolicyVerdict.BLOCKED.value+ reasons = (PolicyReason.INSUFFICIENT_ROLE,)+ # The policy enum values and lifecycle mask names are intentionally+ # one-to-one. Sum is equivalent to OR because every bit is unique.+ reason_mask = sum(int(PolicyReasonBit[reason.name]) for reason in reasons)+ if gateway_mode in {"disabled", "shadow_candidate"} and (+ initial_verdict in {"preview_ready", "live_candidate"}+ ):+ initial_verdict = "blocked"+ reason_mask |= int(PolicyReasonBit.AUTHORITY_RESOLUTION_REQUIRED)+ evaluation_state = "evaluated"+ gateway_decision = "none"+ live_candidate = (+ gateway_mode == "enforced" and initial_verdict == "live_candidate" and reason_mask == 0+ )+ budgets = (+ await self._resolve_budget_reservation_v3(connection, resolved, intent, suffix=suffix)+ if reserve_budgets and live_candidate+ else None+ )+ snapshot = AttemptPolicySnapshot(+ resolved.authority_revision,+ int(self._value(campaign, "authority_revision", 5)),+ destination_revision,+ max((row[1] for row in credential_observations), default=0),+ intent.evaluation_mode,+ True,+ True,+ True,+ True,+ True,+ len(prepared.canonical_parameters),+ descriptor.semantic_digest,+ catalog_digest,+ True,+ True,+ descriptor.descriptor_complete,+ True,+ minimum_role,+ noise_class,+ approval_policy,+ capability_mask,+ blocker_mask,+ descriptor.descriptor_complete,+ descriptor.idempotency.value != "unproven_current_contract",+ True,+ True,+ descriptor.future_gateway_eligible,+ True,+ gateway_revision_current and gateway_catalog_current,+ True,+ True,+ resolved.role,+ campaign_active,+ grant_active,+ approval_row is not None,+ approval_current,+ approval_current,+ granted_mask,+ True,+ destinations_in_scope,+ True,+ credentials_current,+ True,+ credential_policy_current,+ True,+ not descriptor.credential_policy.ambient_dependencies,+ (budgets is not None) if live_candidate else True,+ (budgets is not None) if live_candidate else True,+ (budgets is not None) if live_candidate else True,+ gateway_mode,+ gateway_decision,+ evaluation_state,+ initial_verdict,+ reason_mask,+ descriptor.external_effect.value,+ descriptor.idempotency.value,+ descriptor.retry_eligibility.value,+ "not_applicable" if live_candidate else "closed_without_retry",+ descriptor.cancellation_ownership.value,+ descriptor.compensation.value,+ descriptor.timeout.source.value,+ descriptor.timeout.seconds * 1000,+ descriptor.timeout.settlement.value,+ )+ return _ResolvedAdmissionV3(+ resolved,+ snapshot,+ approval if live_candidate else None,+ budgets if live_candidate else None,+ destination_binding,+ credential_binding,+ None if approval is None else approval.binding_digest,+ gateway_revision,+ gateway_activation_revision,+ int(self._value(grant, "revision", 1)),+ tuple(+ (+ canonical_operation_binding_digest(+ "destination-observation",+ (+ ("normalization_version", DESTINATION_NORMALIZATION_VERSION),+ ("destination_kind", value.partition("|")[0]),+ ("canonical_destination", value.partition("|")[2]),+ ),+ ),+ destination_revision,+ )+ for value in sorted(destination_values)+ ),+ credential_observations,+ )++ async def _scalar_campaign_value(+ self, connection: Any, campaign_id: str, column: str, suffix: str+ ) -> Any:+ if column not in {"scope_json", "targets_json"}:+ raise ValueError("Invalid campaign authority column")+ row = await self._fetchrow(+ connection,+ f"SELECT {column} FROM campaigns WHERE id=?" + suffix,+ (campaign_id,),+ )+ if row is None:+ raise ValueError("Missing campaign authority")+ return self._value(row, column, 0)++ async def _resolve_budget_reservation_v3(+ self,+ connection: Any,+ principal: _ResolvedPrincipal,+ intent: AdmissionIntentV3,+ *,+ suffix: str,+ ) -> BudgetReservation | None:+ rows = await self._fetchall(+ connection,+ "SELECT id,budget_kind,capacity_units,reserved_units,consumed_units,revision,"+ "latest_operation_id,latest_operation_base_revision,latest_operation_code "+ "FROM campaign_execution_budgets WHERE campaign_id=? ORDER BY CASE budget_kind "+ "WHEN 'noise' THEN 1 WHEN 'exfiltration' THEN 2 WHEN 'concurrency' THEN 3 END" + suffix,+ (intent.campaign_id,),+ )+ by_kind = {str(self._value(row, "budget_kind", 1)): row for row in rows}+ if set(by_kind) != {"noise", "exfiltration", "concurrency"}:+ raise _AbortOperationError(OperationResult(FixedResult.AUTHORITY_STALE, None))+ latest_operation_ids = tuple(+ sorted({str(self._value(row, "latest_operation_id", 6)) for row in rows})+ )+ receipt_rows = await self._fetchall(+ connection,+ "SELECT operation_id,operation_code,campaign_id,result_code,"+ "result_revision_present,result_revision "+ "FROM execution_operation_receipts WHERE operation_id IN ("+ + ",".join("?" for _ in latest_operation_ids)+ + ")",+ latest_operation_ids,+ )+ receipts = {str(self._value(row, "operation_id", 0)): row for row in receipt_rows}+ receipt_code_for_latest_code = {+ "configure": "budget_configure",+ "reserve": "budget_reserve",+ "settle": "budget_settle",+ }+ for row in rows:+ revision = int(self._value(row, "revision", 5))+ latest_operation_id = str(self._value(row, "latest_operation_id", 6))+ base_revision = int(self._value(row, "latest_operation_base_revision", 7))+ latest_operation_code = str(self._value(row, "latest_operation_code", 8))+ receipt = receipts.get(latest_operation_id)+ if (+ base_revision != (0 if revision == 0 else revision - 1)+ or receipt is None+ or self._value(receipt, "operation_code", 1)+ != receipt_code_for_latest_code.get(latest_operation_code)+ or self._value(receipt, "campaign_id", 2) != intent.campaign_id+ or self._value(receipt, "result_code", 3) != FixedResult.APPLIED.value+ or not bool(self._value(receipt, "result_revision_present", 4))+ or self._value(receipt, "result_revision", 5) != revision+ ):+ raise _AbortOperationError(OperationResult(FixedResult.AUTHORITY_STALE, None))+ requested = {+ "noise": intent.noise_units,+ "exfiltration": intent.exfiltration_units,+ "concurrency": 1,+ }+ for kind, units in requested.items():+ row = by_kind[kind]+ if int(self._value(row, "reserved_units", 3)) + int(+ self._value(row, "consumed_units", 4)+ ) + units > int(self._value(row, "capacity_units", 2)):+ raise _AbortOperationError(+ OperationResult(+ FixedResult.CAPACITY_UNAVAILABLE,+ int(self._value(row, "revision", 5)),+ )+ )++ def derived(label: str) -> str:+ digest = hashlib.sha256(+ (intent.operation_id + "\x00" + label).encode("ascii")+ ).hexdigest()+ return (+ digest[:8]+ + "-"+ + digest[8:12]+ + "-4"+ + digest[13:16]+ + "-8"+ + digest[17:20]+ + "-"+ + digest[20:32]+ )++ return BudgetReservation(+ intent.campaign_id,+ intent.attempt_id,+ str(self._value(by_kind["noise"], "id", 0)),+ derived("noise-ledger"),+ intent.noise_units,+ int(self._value(by_kind["noise"], "revision", 5)),+ str(self._value(by_kind["exfiltration"], "id", 0)),+ derived("exfiltration-ledger"),+ intent.exfiltration_units,+ int(self._value(by_kind["exfiltration"], "revision", 5)),+ str(self._value(by_kind["concurrency"], "id", 0)),+ derived("concurrency-ledger"),+ int(self._value(by_kind["concurrency"], "revision", 5)),+ derived("budget-operation"),+ "actor",+ principal.subject_ref,+ principal.user_id,+ principal.authority_revision,+ )++ async def _resolve_principal(+ self,+ connection: Any,+ principal: object,+ *,+ suffix: str,+ ) -> _ResolvedPrincipal | None:+ if (+ type(principal) is not TrustedPrincipal+ or not valid_uuid(principal.subject_ref)+ or not valid_uuid(principal.user_id)+ or principal.subject_ref != principal.user_id+ ):+ return None+ row = await self._fetchrow(+ connection,+ "SELECT u.id,u.username,u.role,u.is_active,u.auth_epoch,a.authority_state,"+ "a.authority_revision,a.authority_binding_digest,"+ "a.authority_latest_operation_id,"+ "a.authority_latest_operation_base_revision,"+ "a.authority_latest_operation_code "+ "FROM users u JOIN execution_actor_authority_revisions a ON a.user_id=u.id "+ "WHERE u.id=?" + suffix,+ (principal.user_id,),+ )+ if row is None:+ return None+ binding = self._actor_authority_binding(+ str(self._value(row, "id", 0)),+ str(self._value(row, "username", 1)),+ str(self._value(row, "role", 2)),+ bool(self._value(row, "is_active", 3)),+ int(self._value(row, "auth_epoch", 4)),+ )+ if (+ not bool(self._value(row, "is_active", 3))+ or self._value(row, "authority_state", 5) != "active"+ or self._value(row, "authority_binding_digest", 7) != binding+ or not await self._v11_authority_revision_current(+ connection,+ revision=int(self._value(row, "authority_revision", 6)),+ latest_operation_id=self._value(row, "authority_latest_operation_id", 8),+ latest_operation_base_revision=self._value(+ row, "authority_latest_operation_base_revision", 9+ ),+ latest_operation_code=self._value(row, "authority_latest_operation_code", 10),+ operation_prefix="actor_authority_",+ campaign_id=None,+ target_id=principal.user_id,+ )+ ):+ return None+ return _ResolvedPrincipal(+ principal.subject_ref,+ principal.user_id,+ str(self._value(row, "role", 2)),+ int(self._value(row, "auth_epoch", 4)),+ int(self._value(row, "authority_revision", 6)),+ binding,+ )++ async def _principal_can_mutate_campaign(+ self,+ connection: Any,+ principal: _ResolvedPrincipal,+ campaign_id: str,+ *,+ suffix: str,+ ) -> bool:+ if principal.role == "admin":+ return True+ if principal.role != "team_lead":+ return False+ row = await self._fetchrow(+ connection,+ "SELECT c.operator,u.username FROM campaigns c JOIN users u ON u.id=? "+ "WHERE c.id=?" + suffix,+ (principal.user_id, campaign_id),+ )+ return bool(+ row is not None and self._value(row, "operator", 0) == self._value(row, "username", 1)+ )++ async def _v11_actor_receipt_spec(+ self,+ connection: Any,+ principal: TrustedPrincipal,+ *,+ suffix: str,+ operation_id: str,+ operation_code: str,+ campaign_id: str | None,+ primary_target_id: str,+ secondary_target_id: str | None = None,+ expected_revision: int | None,+ fields: tuple[tuple[str, str | int | bool | None], ...] = (),+ ) -> tuple[_ReceiptSpec, _ResolvedPrincipal | None] | None:+ """Construct receipt-first v11 authority binding without trusting caller facts."""+ prior = await self._receipt_row(connection, operation_id)+ resolved: _ResolvedPrincipal | None = None+ if prior is not None and bool(+ self._value(prior, "principal_authority_revision_present", 7)+ ):+ authority_revision = int(self._value(prior, "principal_authority_revision", 8))+ else:+ gateway = await self._fetchrow(+ connection,+ "SELECT singleton_id FROM execution_gateway_state WHERE singleton_id=1" + suffix,+ (),+ )+ if gateway is None:+ return None+ resolved = await self._resolve_principal(connection, principal, suffix=suffix)+ if resolved is None:+ return None+ authority_revision = resolved.authority_revision+ try:+ spec = self._receipt_spec(+ operation_id=operation_id,+ operation_code=operation_code,+ campaign_id=campaign_id,+ primary_target_id=primary_target_id,+ secondary_target_id=secondary_target_id,+ principal_kind="actor",+ principal_subject_ref=principal.subject_ref,+ principal_user_id=principal.user_id,+ principal_authority_revision=authority_revision,+ expected_revision=expected_revision,+ fields=fields,+ )+ except (AttributeError, ValueError):+ return None+ return spec, resolved++ @staticmethod+ def _valid_trusted_principal(principal: object) -> bool:+ return (+ type(principal) is TrustedPrincipal+ and valid_uuid(principal.subject_ref)+ and valid_uuid(principal.user_id)+ and principal.subject_ref == principal.user_id+ )++ @staticmethod+ def _canonical_untrusted_parameters_digest(value: object) -> str | None:+ if not isinstance(value, Mapping):+ return None+ try:+ serialized = json.dumps(+ value,+ sort_keys=True,+ separators=(",", ":"),+ ensure_ascii=False,+ allow_nan=False,+ )+ except (TypeError, ValueError):+ return None+ return hashlib.sha256(serialized.encode("utf-8")).hexdigest()++ @classmethod+ def _initial_v3_replay_digest(cls, intent: object) -> str | None:+ if type(intent) is not AdmissionIntentV3:+ return None+ raw_digest = cls._canonical_untrusted_parameters_digest(intent.raw_parameters)+ if raw_digest is None:+ return None+ try:+ credential_ids_digest = hashlib.sha256(+ "\x00".join(intent.credential_ids).encode("ascii")+ ).hexdigest()+ return canonical_operation_binding_digest(+ "admission-immutable-intent",+ (+ ("logical_execution_id", intent.logical_execution_id),+ ("submission_id", intent.submission_id),+ ("attempt_id", intent.attempt_id),+ ("operation_id", intent.operation_id),+ ("outbox_id", intent.outbox_id),+ ("publication_key", intent.publication_key),+ ("campaign_id", intent.campaign_id),+ ("module_id", intent.module_id),+ ("ingress_code", intent.ingress_code),+ ("evaluation_mode", intent.evaluation_mode),+ ("raw_parameters_digest", raw_digest),+ ("credential_ids_digest", credential_ids_digest),+ ("approval_ref", intent.approval_ref),+ ("noise_units", intent.noise_units),+ ("exfiltration_units", intent.exfiltration_units),+ ),+ )+ except (AttributeError, TypeError, ValueError):+ return None++ @staticmethod+ def _derived_v3_uuid(operation_id: str, label: str) -> str:+ digest = hashlib.sha256((operation_id + "\x00" + label).encode("ascii")).hexdigest()+ return (+ digest[:8]+ + "-"+ + digest[8:12]+ + "-4"+ + digest[13:16]+ + "-8"+ + digest[17:20]+ + "-"+ + digest[20:32]+ )++ def _retry_v3_receipt_spec(+ self,+ principal: TrustedPrincipal,+ intent: RetryIntentV3,+ *,+ campaign_id: str | None,+ authority_revision: int,+ ) -> _ReceiptSpec | None:+ raw_digest = self._canonical_untrusted_parameters_digest(intent.raw_parameters)+ if raw_digest is None:+ return None+ credential_ids_digest = hashlib.sha256(+ "\x00".join(intent.credential_ids).encode("ascii")+ ).hexdigest()+ try:+ return self._receipt_spec(+ operation_id=intent.operation_id,+ operation_code="retry",+ campaign_id=campaign_id,+ primary_target_id=intent.parent_attempt_id,+ secondary_target_id=intent.child_attempt_id,+ principal_kind="actor",+ principal_subject_ref=principal.subject_ref,+ principal_user_id=principal.user_id,+ principal_authority_revision=authority_revision,+ expected_revision=intent.expected_parent_revision,+ fields=(+ ("logical_execution_id", intent.logical_execution_id),+ ("child_outbox_id", intent.outbox_id),+ ("child_publication_key", intent.publication_key),+ ("evaluation_mode", intent.evaluation_mode),+ ("raw_parameters_digest", raw_digest),+ ("credential_ids_digest", credential_ids_digest),+ ("approval_ref", intent.approval_ref),+ ("noise_units", intent.noise_units),+ ("exfiltration_units", intent.exfiltration_units),+ ),+ )+ except ValueError:+ return None++ @asynccontextmanager+ async def _transaction(self) -> AsyncIterator[Any]:+ if self._dialect == "sqlite":+ begin = await _await_owned_cleanup(+ self._backend.execute("BEGIN IMMEDIATE"), name="lifecycle-sqlite-begin"+ )+ if begin.error is not None:+ primary = begin.cancellation or begin.error+ if begin.cancellation is not None:+ _record_cleanup_failure(primary, "sqlite-begin")+ raise primary+ if begin.cancellation is not None:+ rollback = await _await_owned_cleanup(+ self._backend.rollback(), name="lifecycle-sqlite-rollback"+ )+ if rollback.error is not None:+ _record_cleanup_failure(begin.cancellation, "sqlite-rollback")+ raise begin.cancellation+ try:+ yield self._backend+ except BaseException as error:+ rollback = await _await_owned_cleanup(+ self._backend.rollback(), name="lifecycle-sqlite-rollback"+ )+ if rollback.error is not None:+ _record_cleanup_failure(error, "sqlite-rollback")+ raise+ commit = await _await_owned_cleanup(+ self._backend.commit(), name="lifecycle-sqlite-commit"+ )+ if commit.error is not None:+ primary = commit.cancellation or commit.error+ if commit.cancellation is not None:+ _record_cleanup_failure(primary, "sqlite-commit")+ rollback = await _await_owned_cleanup(+ self._backend.rollback(), name="lifecycle-sqlite-rollback"+ )+ if rollback.error is not None:+ _record_cleanup_failure(primary, "sqlite-rollback")+ raise primary+ if commit.cancellation is not None:+ raise commit.cancellation+ return+ connection = await self._backend.acquire()+ try:+ transaction = connection.transaction()+ await transaction.start()+ try:+ yield connection+ except BaseException as error:+ rollback = await _await_owned_cleanup(+ transaction.rollback(), name="lifecycle-postgresql-rollback"+ )+ if rollback.error is not None:+ _record_cleanup_failure(error, "postgresql-rollback")+ raise+ commit = await _await_owned_cleanup(+ transaction.commit(), name="lifecycle-postgresql-commit"+ )+ if commit.error is not None or commit.cancellation is not None:+ primary = commit.cancellation or commit.error+ if commit.error is not None and commit.cancellation is not None:+ _record_cleanup_failure(primary, "postgresql-commit")+ raise primary+ except BaseException as error:+ release = await _await_owned_cleanup(+ self._backend.release(connection), name="lifecycle-postgresql-release"+ )+ if release.error is not None:+ _record_cleanup_failure(error, "postgresql-release")+ raise+ release = await _await_owned_cleanup(+ self._backend.release(connection), name="lifecycle-postgresql-release"+ )+ if release.error is not None or release.cancellation is not None:+ primary = release.cancellation or release.error+ if release.error is not None and release.cancellation is not None:+ _record_cleanup_failure(primary, "postgresql-release")+ raise primary++ async def _fetchrow(self, connection: Any, sql: str, params: Sequence[Any]) -> Any:+ if self._dialect == "postgresql":+ return await connection.fetchrow(_question_to_postgres(sql), *params)+ cursor = await connection.execute(sql, params)+ return await cursor.fetchone()++ async def _execute(self, connection: Any, sql: str, params: Sequence[Any]) -> None:+ """Execute non-truth-bearing SQL; callers must not infer affected rows."""+ if self._dialect == "postgresql":+ await connection.execute(_question_to_postgres(sql), *params)+ else:+ await connection.execute(sql, params)++ async def _fetchall(self, connection: Any, sql: str, params: Sequence[Any]) -> Sequence[Any]:+ if self._dialect == "postgresql":+ return await connection.fetch(_question_to_postgres(sql), *params)+ cursor = await connection.execute(sql, params)+ return await cursor.fetchall()++ async def _returning_rows(+ self, connection: Any, sql: str, params: Sequence[Any]+ ) -> tuple[Any, ...]:+ if " RETURNING " not in sql.upper():+ raise _AbortOperationError(OperationResult(FixedResult.INVARIANT_FAILURE, None))+ if self._dialect == "postgresql":+ rows = await connection.fetch(_question_to_postgres(sql), *params)+ return tuple(rows)+ cursor = await connection.execute(sql, params)+ rows = tuple(await cursor.fetchall())+ changes_cursor = await connection.execute("SELECT changes() AS affected_rows", ())+ changes_row = await changes_cursor.fetchone()+ if changes_row is None or int(self._value(changes_row, "affected_rows", 0)) != len(rows):+ raise _AbortOperationError(OperationResult(FixedResult.INVARIANT_FAILURE, None))+ return rows++ async def cas_update_one(+ self,+ connection: Any,+ sql: str,+ params: Sequence[Any],+ *,+ identity: str,+ post_revision: int,+ identity_column: str = "id",+ revision_column: str = "revision",+ zero_classifier: Callable[[], Awaitable[OperationResult]] | None,+ ) -> Any | None:+ rows = await self._returning_rows(connection, sql, params)+ if not rows:+ if zero_classifier is not None:+ result = await zero_classifier()+ if type(result) is not OperationResult or result.result is FixedResult.APPLIED:+ raise _AbortOperationError(OperationResult(FixedResult.INVARIANT_FAILURE, None))+ raise _AbortOperationError(result)+ return None+ if len(rows) != 1:+ raise _AbortOperationError(OperationResult(FixedResult.INVARIANT_FAILURE, None))+ row = rows[0]+ if (+ self._value(row, identity_column, 0) != identity+ or int(self._value(row, revision_column, 1)) != post_revision+ ):+ raise _AbortOperationError(OperationResult(FixedResult.INVARIANT_FAILURE, None))+ return row++ async def insert_or_validate_binding(+ self,+ connection: Any,+ sql: str,+ params: Sequence[Any],+ *,+ identity: str,+ revision: int,+ identity_column: str = "id",+ revision_column: str = "revision",+ ) -> Any | None:+ return await self.cas_update_one(+ connection,+ sql,+ params,+ identity=identity,+ post_revision=revision,+ identity_column=identity_column,+ revision_column=revision_column,+ zero_classifier=None,+ )++ async def update_exact_set(+ self,+ connection: Any,+ sql: str,+ params: Sequence[Any],+ *,+ expected: tuple[tuple[str, Any], ...],+ zero_classifier: Callable[[], Awaitable[OperationResult]] | None,+ ) -> Any | None:+ rows = await self._returning_rows(connection, sql, params)+ if not rows:+ if zero_classifier is not None:+ result = await zero_classifier()+ if type(result) is not OperationResult or result.result is FixedResult.APPLIED:+ raise _AbortOperationError(OperationResult(FixedResult.INVARIANT_FAILURE, None))+ raise _AbortOperationError(result)+ return None+ if len(rows) != 1:+ raise _AbortOperationError(OperationResult(FixedResult.INVARIANT_FAILURE, None))+ row = rows[0]+ if any(+ self._value(row, name, index) != value for index, (name, value) in enumerate(expected)+ ):+ raise _AbortOperationError(OperationResult(FixedResult.INVARIANT_FAILURE, None))+ return row++ async def delete_exact_set(+ self,+ connection: Any,+ sql: str,+ params: Sequence[Any],+ *,+ expected_identities: tuple[str, ...],+ zero_classifier: Callable[[], Awaitable[OperationResult]] | None,+ ) -> tuple[Any, ...] | None:+ rows = await self._returning_rows(connection, sql, params)+ if not rows:+ if zero_classifier is not None:+ result = await zero_classifier()+ if type(result) is not OperationResult or result.result is FixedResult.APPLIED:+ raise _AbortOperationError(OperationResult(FixedResult.INVARIANT_FAILURE, None))+ raise _AbortOperationError(result)+ return None+ observed = tuple(sorted(str(self._value(row, "id", 0)) for row in rows))+ if observed != tuple(sorted(expected_identities)):+ raise _AbortOperationError(OperationResult(FixedResult.INVARIANT_FAILURE, None))+ return rows++ @asynccontextmanager+ async def _savepoint(self, connection: Any) -> AsyncIterator[None]:+ await self._execute(connection, "SAVEPOINT lifecycle_compound", ())+ try:+ yield+ except BaseException as error:+ rollback = await _await_owned_cleanup(+ self._execute(connection, "ROLLBACK TO SAVEPOINT lifecycle_compound", ()),+ name="lifecycle-savepoint-rollback",+ )+ if rollback.error is not None:+ _record_cleanup_failure(error, "savepoint-rollback")+ else:+ release = await _await_owned_cleanup(+ self._execute(connection, "RELEASE SAVEPOINT lifecycle_compound", ()),+ name="lifecycle-savepoint-release",+ )+ if release.error is not None:+ _record_cleanup_failure(error, "savepoint-release")+ raise+ release = await _await_owned_cleanup(+ self._execute(connection, "RELEASE SAVEPOINT lifecycle_compound", ()),+ name="lifecycle-savepoint-release",+ )+ if release.error is not None or release.cancellation is not None:+ primary = release.cancellation or release.error+ if release.error is not None and release.cancellation is not None:+ _record_cleanup_failure(primary, "savepoint-release")+ raise primary++ async def _receipt_row(self, connection: Any, operation_id: str) -> Any:+ suffix = " FOR UPDATE" if self._dialect == "postgresql" else ""+ return await self._fetchrow(+ connection,+ "SELECT operation_code,campaign_id,primary_target_id,secondary_target_id,"+ "principal_kind,principal_subject_ref,principal_user_id,"+ "principal_authority_revision_present,principal_authority_revision,"+ "binding_contract_version,request_binding_digest,expected_revision_present,"+ "expected_revision,secondary_expected_revision_present,"+ "secondary_expected_revision,owner_ref,lease_generation,result_code,"+ "exact_replay_code,result_binding_digest,result_identity,"+ "result_revision_present,result_revision,secondary_result_identity,"+ "secondary_result_revision_present,secondary_result_revision "+ "FROM execution_operation_receipts WHERE operation_id=?" + suffix,+ (operation_id,),+ )++ def _receipt_matches(self, row: Any, spec: _ReceiptSpec) -> bool:+ expected = (+ spec.operation_code,+ spec.campaign_id,+ spec.primary_target_id,+ spec.secondary_target_id,+ spec.principal_kind,+ spec.principal_subject_ref,+ spec.principal_user_id,+ spec.principal_authority_revision is not None,+ spec.principal_authority_revision,+ 2,+ spec.request_binding_digest,+ spec.expected_revision is not None,+ spec.expected_revision,+ spec.secondary_expected_revision is not None,+ spec.secondary_expected_revision,+ spec.owner_ref,+ spec.lease_generation,+ )+ return all(+ self._value(row, name, index) == value+ for index, (name, value) in enumerate(+ zip(+ (+ "operation_code",+ "campaign_id",+ "primary_target_id",+ "secondary_target_id",+ "principal_kind",+ "principal_subject_ref",+ "principal_user_id",+ "principal_authority_revision_present",+ "principal_authority_revision",+ "binding_contract_version",+ "request_binding_digest",+ "expected_revision_present",+ "expected_revision",+ "secondary_expected_revision_present",+ "secondary_expected_revision",+ "owner_ref",+ "lease_generation",+ ),+ expected,+ strict=True,+ )+ )+ )++ async def _receipt_primary_target_conflicts(+ self,+ connection: Any,+ operation_id: str,+ primary_target_id: str,+ ) -> bool:+ row = await self._fetchrow(+ connection,+ "SELECT primary_target_id FROM execution_operation_receipts WHERE operation_id = ?",+ (operation_id,),+ )+ return (+ row is not None and str(self._value(row, "primary_target_id", 0)) != primary_target_id+ )++ async def _classify_receipt(+ self,+ connection: Any,+ spec: _ReceiptSpec,+ *,+ current_revision: int | None,+ exact_result: FixedResult = FixedResult.REPLAYED,+ current_result_fields: tuple[tuple[str, str | int | bool | None], ...] | None = None,+ ) -> OperationResult | None:+ row = await self._receipt_row(connection, spec.operation_id)+ del exact_result, current_result_fields+ if row is None:+ return None+ if not self._receipt_matches(row, spec):+ return OperationResult(FixedResult.CONFLICT_OPERATION, current_revision)+ result_revision = (+ self._value(row, "result_revision", 22)+ if bool(self._value(row, "result_revision_present", 21))+ else None+ )+ stored_result = self._value(row, "result_code", 17)+ if stored_result != FixedResult.APPLIED.value:+ return OperationResult(FixedResult(stored_result), result_revision)+ replay_code = FixedResult(str(self._value(row, "exact_replay_code", 18)))+ return OperationResult(replay_code, result_revision)++ async def _classify_zero_row(+ self,+ connection: Any,+ *,+ table: str,+ identity_column: str,+ identity: str,+ revision_column: str | None = None,+ checks: tuple[tuple[str, tuple[Any, ...], FixedResult], ...] = (),+ missing_result: FixedResult = FixedResult.NOT_FOUND_OR_PURGED,+ matched_result: FixedResult = FixedResult.INVARIANT_FAILURE,+ receipt_spec: _ReceiptSpec | None = None,+ authority_columns: tuple[str, str, str] | None = None,+ authority_before_checks: bool = False,+ expected_authority_user_id: str | None = None,+ expected_authority_revision: int | None = None,+ expected_authority_role: str | None = None,+ ) -> OperationResult:+ if receipt_spec is not None:+ receipt_result = await self._classify_receipt(+ connection,+ receipt_spec,+ current_revision=receipt_spec.expected_revision,+ )+ if receipt_result is not None:+ return receipt_result+ suffix = " FOR UPDATE" if self._dialect == "postgresql" else ""+ columns = tuple(+ dict.fromkeys(+ column+ for column in (+ revision_column,+ *(name for name, _values, _result in checks),+ *(() if authority_columns is None else authority_columns),+ )+ if column is not None+ )+ )+ projection = ",".join(columns) if columns else identity_column+ row = await self._fetchrow(+ connection,+ f"SELECT {projection} FROM {table} WHERE {identity_column}=?" + suffix,+ (identity,),+ )+ revision = (+ None+ if row is None or revision_column is None+ else int(self._value(row, revision_column, columns.index(revision_column)))+ )+ if row is None:+ return OperationResult(missing_result, None)++ async def classify_authority() -> OperationResult | None:+ if authority_columns is None:+ return None+ user_column, authority_revision_column, role_column = authority_columns+ user_id = (+ expected_authority_user_id+ if expected_authority_user_id is not None+ else self._value(row, user_column, columns.index(user_column))+ )+ authority_revision = (+ expected_authority_revision+ if expected_authority_revision is not None+ else self._value(+ row,+ authority_revision_column,+ columns.index(authority_revision_column),+ )+ )+ authority_role = (+ expected_authority_role+ if expected_authority_role is not None+ else self._value(row, role_column, columns.index(role_column))+ )+ authority = await self._fetchrow(+ connection,+ "SELECT u.id,u.role,u.is_active,a.revision FROM users u "+ "JOIN execution_actor_authority_revisions a ON a.user_id=u.id "+ "WHERE u.id=?" + suffix,+ (user_id,),+ )+ if not (+ authority is not None+ and self._value(authority, "id", 0) == user_id+ and self._value(authority, "role", 1) == authority_role+ and bool(self._value(authority, "is_active", 2))+ and self._value(authority, "revision", 3) == authority_revision+ ):+ return OperationResult(FixedResult.AUTHORITY_STALE, revision)+ return None++ if authority_before_checks:+ authority_result = await classify_authority()+ if authority_result is not None:+ return authority_result+ for column, expected_values, result in checks:+ if self._value(row, column, columns.index(column)) not in expected_values:+ return OperationResult(result, revision)+ if not authority_before_checks:+ authority_result = await classify_authority()+ if authority_result is not None:+ return authority_result+ return OperationResult(matched_result, revision)++ async def _classify_zero_budget(+ self,+ connection: Any,+ *,+ budget_id: str,+ campaign_id: str,+ budget_kind: str,+ expected_revision: int,+ required_units: int,+ operation: str,+ ) -> OperationResult:+ suffix = " FOR UPDATE" if self._dialect == "postgresql" else ""+ row = await self._fetchrow(+ connection,+ "SELECT campaign_id,budget_kind,capacity_units,reserved_units,consumed_units,revision "+ "FROM campaign_execution_budgets WHERE id=?" + suffix,+ (budget_id,),+ )+ if row is None or (+ self._value(row, "campaign_id", 0) != campaign_id+ or self._value(row, "budget_kind", 1) != budget_kind+ ):+ return OperationResult(FixedResult.INCONSISTENT_BUDGET_SET, None)+ revision = int(self._value(row, "revision", 5))+ if revision != expected_revision:+ return OperationResult(FixedResult.CONFLICT_REVISION, revision)+ reserved = int(self._value(row, "reserved_units", 3))+ if operation == "reserve" and reserved + int(+ self._value(row, "consumed_units", 4)+ ) + required_units > int(self._value(row, "capacity_units", 2)):+ return OperationResult(FixedResult.CAPACITY_UNAVAILABLE, revision)+ if operation == "settle" and reserved < required_units:+ return OperationResult(FixedResult.INCONSISTENT_BUDGET_SET, revision)+ if operation not in {"reserve", "settle"}:+ return OperationResult(FixedResult.INVARIANT_FAILURE, None)+ return OperationResult(FixedResult.INVARIANT_FAILURE, None)++ async def _classify_zero_transition(+ self,+ connection: Any,+ *,+ row: Any,+ current: AttemptState,+ request: TransitionRequest,+ receipt_spec: _ReceiptSpec | None,+ guarded_dispatch: bool,+ require_unexpired_lease: bool,+ ) -> OperationResult:+ checks: tuple[tuple[str, tuple[Any, ...], FixedResult], ...] = (+ ("revision", (request.expected_revision,), FixedResult.CONFLICT_REVISION),+ ("state", (current.value,), FixedResult.CONFLICT_STATE),+ )+ if guarded_dispatch:+ checks += (+ ("dispatch_owner_ref", (request.owner_ref,), FixedResult.CONFLICT_OWNER),+ (+ "lease_generation",+ (request.lease_generation,),+ FixedResult.CONFLICT_GENERATION,+ ),+ )+ if require_unexpired_lease:+ checks += (+ (+ "lease_expires_at",+ (self._value(row, "lease_expires_at", 9),),+ FixedResult.CONFLICT_STATE,+ ),+ )+ if current is AttemptState.CANCELLING:+ checks += (+ (+ "cancellation_request_revision",+ (request.cancellation_request_revision,),+ FixedResult.CONFLICT_REVISION,+ ),+ )+ result = await self._classify_zero_row(+ connection,+ table="execution_attempts",+ identity_column="id",+ identity=request.attempt_id,+ revision_column="revision",+ checks=checks,+ receipt_spec=receipt_spec,+ authority_columns=(+ "actor_user_id",+ "actor_authority_revision",+ "actor_role",+ ),+ )+ if result.result is not FixedResult.INVARIANT_FAILURE or not require_unexpired_lease:+ return result+ lease_expires_at = self._value(row, "lease_expires_at", 9)+ current_time = await self._fetchrow(connection, f"SELECT {self._now_sql} AS value", ())+ if lease_expires_at is None or int(self._value(current_time, "value", 0)) >= int(+ lease_expires_at+ ):+ return OperationResult(FixedResult.CONFLICT_STATE, request.expected_revision)+ return result++ async def _classify_zero_ledger(+ self,+ connection: Any,+ *,+ ledger_id: str,+ attempt_id: str,+ budget_kind: str,+ ) -> OperationResult:+ suffix = " FOR UPDATE" if self._dialect == "postgresql" else ""+ row = await self._fetchrow(+ connection,+ "SELECT attempt_id,budget_kind,disposition "+ "FROM campaign_execution_budget_ledger WHERE id=?" + suffix,+ (ledger_id,),+ )+ if row is None or (+ self._value(row, "attempt_id", 0) != attempt_id+ or self._value(row, "budget_kind", 1) != budget_kind+ ):+ return OperationResult(FixedResult.INCONSISTENT_BUDGET_SET, None)+ if self._value(row, "disposition", 2) != "held":+ return OperationResult(FixedResult.CONFLICT_OPERATION, None)+ return OperationResult(FixedResult.INVARIANT_FAILURE, None)++ async def _classify_zero_outbox(+ self,+ connection: Any,+ *,+ outbox_id: str,+ expected_revision: int,+ expected_state: str,+ expected_owner: str | None = None,+ expected_generation: int | None = None,+ expected_lease_expires_at: int | None = None,+ time_requirement: str | None = None,+ expected_delivery_count: int | None = None,+ maximum_delivery_count: int | None = None,+ ) -> OperationResult:+ suffix = " FOR UPDATE" if self._dialect == "postgresql" else ""+ row = await self._fetchrow(+ connection,+ "SELECT publication_state,claim_revision,claim_owner_ref,lease_generation,"+ "lease_expires_at,delivery_attempt_count,available_at "+ "FROM execution_publication_outbox WHERE id=?" + suffix,+ (outbox_id,),+ )+ if row is None:+ return OperationResult(FixedResult.NOT_FOUND_OR_PURGED, None)+ revision = int(self._value(row, "claim_revision", 1))+ if revision != expected_revision:+ return OperationResult(FixedResult.CONFLICT_REVISION, revision)+ if self._value(row, "publication_state", 0) != expected_state:+ return OperationResult(FixedResult.CONFLICT_STATE, revision)+ if expected_owner is not None and self._value(row, "claim_owner_ref", 2) != expected_owner:+ return OperationResult(FixedResult.CONFLICT_OWNER, revision)+ if (+ expected_generation is not None+ and int(self._value(row, "lease_generation", 3)) != expected_generation+ ):+ return OperationResult(FixedResult.CONFLICT_GENERATION, revision)+ if (+ expected_lease_expires_at is not None+ and self._value(row, "lease_expires_at", 4) != expected_lease_expires_at+ ):+ return OperationResult(FixedResult.CONFLICT_STATE, revision)+ delivery_count = int(self._value(row, "delivery_attempt_count", 5))+ if expected_delivery_count is not None and delivery_count != expected_delivery_count:+ return OperationResult(FixedResult.CONFLICT_STATE, revision)+ if maximum_delivery_count is not None and delivery_count >= maximum_delivery_count:+ return OperationResult(FixedResult.CONFLICT_STATE, revision)+ if time_requirement is not None:+ time_row = await self._fetchrow(connection, f"SELECT {self._now_sql} AS value", ())+ current_time = int(self._value(time_row, "value", 0))+ if time_requirement == "available":+ boundary = self._value(row, "available_at", 6)+ valid = boundary is not None and current_time >= int(boundary)+ else:+ boundary = self._value(row, "lease_expires_at", 4)+ valid = boundary is not None and (+ current_time >= int(boundary)+ if time_requirement == "expired"+ else current_time < int(boundary)+ )+ if not valid or time_requirement not in {"available", "expired", "unexpired"}:+ return OperationResult(FixedResult.CONFLICT_STATE, revision)+ return OperationResult(FixedResult.INVARIANT_FAILURE, None)++ async def _insert_receipt(+ self,+ connection: Any,+ spec: _ReceiptSpec,+ *,+ result: FixedResult,+ exact_replay_code: FixedResult = FixedResult.REPLAYED,+ result_identity: str | None,+ result_revision: int | None,+ secondary_result_identity: str | None = None,+ secondary_result_revision: int | None = None,+ result_fields: tuple[tuple[str, str | int | bool | None], ...] = (),+ ) -> None:+ receipt_result_fields = (+ ("exact_replay_code", exact_replay_code.value),+ ("result_identity_present", result_identity is not None),+ ("result_identity", result_identity),+ ("result_revision_present", result_revision is not None),+ ("result_revision", result_revision),+ ("secondary_result_identity_present", secondary_result_identity is not None),+ ("secondary_result_identity", secondary_result_identity),+ ("secondary_result_revision_present", secondary_result_revision is not None),+ ("secondary_result_revision", secondary_result_revision),+ )+ result_digest = canonical_operation_binding_digest(+ spec.operation_code + ".result",+ (("result_code", result.value),) + receipt_result_fields + result_fields,+ )+ row = await self.insert_or_validate_binding(+ connection,+ "INSERT INTO execution_operation_receipts("+ "operation_id,operation_code,campaign_id,primary_target_id,secondary_target_id,"+ "principal_kind,principal_subject_ref,principal_user_id,"+ "principal_authority_revision_present,principal_authority_revision,"+ "binding_contract_version,request_binding_digest,expected_revision_present,"+ "expected_revision,secondary_expected_revision_present,"+ "secondary_expected_revision,owner_ref,lease_generation,result_code,"+ "exact_replay_code,result_binding_digest,result_identity,"+ "result_revision_present,result_revision,secondary_result_identity,"+ "secondary_result_revision_present,secondary_result_revision) "+ "VALUES(?,?,?,?,?,?,?,?,?,?,2,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) "+ "ON CONFLICT(operation_id) DO NOTHING RETURNING operation_id,binding_contract_version",+ (+ spec.operation_id,+ spec.operation_code,+ spec.campaign_id,+ spec.primary_target_id,+ spec.secondary_target_id,+ spec.principal_kind,+ spec.principal_subject_ref,+ spec.principal_user_id,+ spec.principal_authority_revision is not None,+ spec.principal_authority_revision,+ spec.request_binding_digest,+ spec.expected_revision is not None,+ spec.expected_revision,+ spec.secondary_expected_revision is not None,+ spec.secondary_expected_revision,+ spec.owner_ref,+ spec.lease_generation,+ result.value,+ exact_replay_code.value,+ result_digest,+ result_identity,+ result_revision is not None,+ result_revision,+ secondary_result_identity,+ secondary_result_revision is not None,+ secondary_result_revision,+ ),+ identity=spec.operation_id,+ revision=2,+ identity_column="operation_id",+ revision_column="binding_contract_version",+ )+ if row is None:+ raise _AbortOperationError(OperationResult(FixedResult.CONFLICT_OPERATION, None))++ async def _insert_terminal_v3_receipt(+ self,+ connection: Any,+ spec: _ReceiptSpec,+ *,+ result_identity: str,+ result_revision: int,+ secondary_result_identity: str,+ secondary_result_revision: int,+ result_fields: tuple[tuple[str, str | int | bool | None], ...],+ ) -> None:+ receipt_result_fields: tuple[tuple[str, str | int | bool | None], ...] = (+ ("exact_replay_code", FixedResult.REPLAYED.value),+ ("result_identity_present", True),+ ("result_identity", result_identity),+ ("result_revision_present", True),+ ("result_revision", result_revision),+ ("secondary_result_identity_present", True),+ ("secondary_result_identity", secondary_result_identity),+ ("secondary_result_revision_present", True),+ ("secondary_result_revision", secondary_result_revision),+ )+ result_digest = canonical_operation_binding_digest(+ _TERMINAL_COMMIT_RESULT_DOMAIN_V3,+ (("result_code", FixedResult.APPLIED.value),) + receipt_result_fields + result_fields,+ )+ row = await self.insert_or_validate_binding(+ connection,+ "INSERT INTO execution_operation_receipts("+ "operation_id,operation_code,campaign_id,primary_target_id,secondary_target_id,"+ "principal_kind,principal_subject_ref,principal_user_id,"+ "principal_authority_revision_present,principal_authority_revision,"+ "binding_contract_version,request_binding_digest,expected_revision_present,"+ "expected_revision,secondary_expected_revision_present,"+ "secondary_expected_revision,owner_ref,lease_generation,result_code,"+ "exact_replay_code,result_binding_digest,result_identity,"+ "result_revision_present,result_revision,secondary_result_identity,"+ "secondary_result_revision_present,secondary_result_revision) "+ "VALUES(?,?,?,?,?,?,?,?,?,?,2,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) "+ "ON CONFLICT(operation_id) DO NOTHING RETURNING operation_id,binding_contract_version",+ (+ spec.operation_id,+ spec.operation_code,+ spec.campaign_id,+ spec.primary_target_id,+ spec.secondary_target_id,+ spec.principal_kind,+ spec.principal_subject_ref,+ spec.principal_user_id,+ False,+ None,+ spec.request_binding_digest,+ True,+ spec.expected_revision,+ False,+ None,+ None,+ None,+ FixedResult.APPLIED.value,+ FixedResult.REPLAYED.value,+ result_digest,+ result_identity,+ True,+ result_revision,+ secondary_result_identity,+ True,+ secondary_result_revision,+ ),+ identity=spec.operation_id,+ revision=2,+ identity_column="operation_id",+ revision_column="binding_contract_version",+ )+ if row is None:+ raise _AbortOperationError(OperationResult(FixedResult.CONFLICT_OPERATION, None))++ @property+ def _now_sql(self) -> str:+ return (+ "floor(extract(epoch FROM clock_timestamp())*1000)::bigint"+ if self._dialect == "postgresql"+ else "CAST((julianday('now')-2440587.5)*86400000 AS INTEGER)"+ )++ @staticmethod+ def _valid_nonnegative_i53(value: object) -> bool:+ return type(value) is int and 0 <= value <= MAX_I53++ @staticmethod+ def _value(row: Any, name: str, index: int) -> Any:+ try:+ return row[name]+ except (KeyError, TypeError, IndexError):+ return row[index]++ @staticmethod+ def _valid_principal_binding(request: object) -> bool:+ kind = getattr(request, "principal_kind", None)+ subject = getattr(request, "principal_subject_ref", None)+ user_id = getattr(request, "principal_user_id", None)+ authority_revision = getattr(request, "principal_authority_revision", None)+ if kind not in PRINCIPAL_KINDS or not valid_uuid(subject):+ return False+ if kind in {"actor", "resolver"}:+ return (+ valid_uuid(user_id)+ and type(authority_revision) is int+ and 0 <= authority_revision <= MAX_I53+ )+ return (+ user_id is None+ and authority_revision is None+ and (kind != "system" or subject == SYSTEM_PRINCIPAL_SUBJECT_REF)+ )++ @staticmethod+ def _principal_binding(request: object) -> tuple[str, str, str | None, int | None]:+ return (+ str(request.principal_kind), # type: ignore[attr-defined]+ str(request.principal_subject_ref), # type: ignore[attr-defined]+ request.principal_user_id, # type: ignore[attr-defined]+ request.principal_authority_revision, # type: ignore[attr-defined]+ )++ def _receipt_spec(+ self,+ *,+ operation_id: str,+ operation_code: str,+ campaign_id: str | None,+ primary_target_id: str,+ secondary_target_id: str | None = None,+ principal_kind: str = "system",+ principal_subject_ref: str = SYSTEM_PRINCIPAL_SUBJECT_REF,+ principal_user_id: str | None = None,+ principal_authority_revision: int | None = None,+ expected_revision: int | None = None,+ secondary_expected_revision: int | None = None,+ owner_ref: str | None = None,+ lease_generation: int | None = None,+ fields: tuple[tuple[str, str | int | bool | None], ...] = (),+ ) -> _ReceiptSpec:+ no_expected_codes = _V11_RECEIPT_NO_EXPECTED_REVISION_CODES+ two_expected_codes = _RECEIPT_TWO_EXPECTED_REVISION_CODES+ expected_shape_valid = (+ expected_revision is None and secondary_expected_revision is None+ if operation_code in no_expected_codes+ else expected_revision is not None and secondary_expected_revision is not None+ if operation_code in two_expected_codes+ else secondary_expected_revision is None+ if operation_code in _V11_RECEIPT_OPTIONAL_EXPECTED_REVISION_CODES+ else expected_revision is not None and secondary_expected_revision is None+ )+ owner_shape_valid = (+ owner_ref is not None and lease_generation is not None+ if operation_code in _RECEIPT_OUTBOX_OWNER_CODES+ else owner_ref is None and lease_generation is None+ if operation_code in _RECEIPT_OUTBOX_NO_OWNER_CODES+ else True+ )+ if (+ not valid_uuid(operation_id)+ or operation_code not in V11_OPERATION_CODES+ or not expected_shape_valid+ or not owner_shape_valid+ or not valid_uuid(primary_target_id)+ or (campaign_id is not None and not valid_uuid(campaign_id))+ or (secondary_target_id is not None and not valid_uuid(secondary_target_id))+ or principal_kind not in PRINCIPAL_KINDS+ or not valid_uuid(principal_subject_ref)+ or (+ principal_kind == "system" and principal_subject_ref != SYSTEM_PRINCIPAL_SUBJECT_REF+ )+ or (+ principal_kind in {"actor", "resolver"}+ and (+ not valid_uuid(principal_user_id)+ or not self._valid_nonnegative_i53(principal_authority_revision)+ )+ )+ or (+ principal_kind in {"worker", "system"}+ and (principal_user_id is not None or principal_authority_revision is not None)+ )+ or (+ expected_revision is not None and not self._valid_nonnegative_i53(expected_revision)+ )+ or (+ secondary_expected_revision is not None+ and not self._valid_nonnegative_i53(secondary_expected_revision)+ )+ or (owner_ref is not None and not valid_uuid(owner_ref))+ or (owner_ref is None) != (lease_generation is None)+ or (lease_generation is not None and not self._valid_nonnegative_i53(lease_generation))+ ):+ raise ValueError("Invalid operation receipt contract")+ standard: tuple[tuple[str, str | int | bool | None], ...] = (+ ("operation_id", operation_id),+ ("operation_code", operation_code),+ ("campaign_id_present", campaign_id is not None),+ ("campaign_id", campaign_id),+ ("primary_target_id", primary_target_id),+ ("secondary_target_id_present", secondary_target_id is not None),+ ("secondary_target_id", secondary_target_id),+ ("principal_kind", principal_kind),+ ("principal_subject_ref", principal_subject_ref),+ ("principal_user_id_present", principal_user_id is not None),+ ("principal_user_id", principal_user_id),+ (+ "principal_authority_revision_present",+ principal_authority_revision is not None,+ ),+ ("principal_authority_revision", principal_authority_revision),+ ("expected_revision_present", expected_revision is not None),+ ("expected_revision", expected_revision),+ (+ "secondary_expected_revision_present",+ secondary_expected_revision is not None,+ ),+ ("secondary_expected_revision", secondary_expected_revision),+ ("owner_ref_present", owner_ref is not None),+ ("owner_ref", owner_ref),+ ("lease_generation_present", lease_generation is not None),+ ("lease_generation", lease_generation),+ )+ return _ReceiptSpec(+ operation_id=operation_id,+ operation_code=operation_code,+ campaign_id=campaign_id,+ primary_target_id=primary_target_id,+ secondary_target_id=secondary_target_id,+ principal_kind=principal_kind,+ principal_subject_ref=principal_subject_ref,+ principal_user_id=principal_user_id,+ principal_authority_revision=principal_authority_revision,+ request_binding_digest=canonical_operation_binding_digest(+ operation_code + ".request", standard + fields+ ),+ expected_revision=expected_revision,+ secondary_expected_revision=secondary_expected_revision,+ owner_ref=owner_ref,+ lease_generation=lease_generation,+ )++ async def _acquire_transaction_key(self, connection: Any, identity: str) -> None:+ """Acquire the class-zero lock before any mutation-authorizing read."""+ if not valid_uuid(identity):+ raise _AbortOperationError(OperationResult(FixedResult.INVALID_CONTRACT, None))+ if self._dialect == "postgresql":+ row = await self._fetchrow(+ connection,+ "SELECT pg_advisory_xact_lock(hashtextextended(?,0)) AS locked",+ (identity,),+ )+ if row is None:+ raise _AbortOperationError(OperationResult(FixedResult.INVARIANT_FAILURE, None))++ async def _acquire_logical_attempt_transaction_keys(+ self,+ connection: Any,+ logical_execution_id: str,+ attempt_id: str,+ ) -> None:+ """Serialize all row-lock orders that can mutate one logical attempt graph."""+ await self._acquire_transaction_key(connection, logical_execution_id)+ if attempt_id != logical_execution_id:+ await self._acquire_transaction_key(connection, attempt_id)++ async def _lock_attempt_prefix(+ self, connection: Any, attempt_id: str+ ) -> tuple[str, str, str, str, int] | None:+ discovery = await self._fetchrow(+ connection,+ "SELECT logical_execution_id,campaign_id,actor_user_id,actor_subject_ref,"+ "actor_authority_revision "+ "FROM execution_attempts WHERE id=?",+ (attempt_id,),+ )+ if discovery is None:+ return None+ logical_id = str(self._value(discovery, "logical_execution_id", 0))+ campaign_id = str(self._value(discovery, "campaign_id", 1))+ actor_user_id = str(self._value(discovery, "actor_user_id", 2))+ actor_subject_ref = str(self._value(discovery, "actor_subject_ref", 3))+ actor_authority_revision = int(self._value(discovery, "actor_authority_revision", 4))+ await self._acquire_logical_attempt_transaction_keys(+ connection,+ logical_id,+ attempt_id,+ )+ suffix = " FOR UPDATE" if self._dialect == "postgresql" else ""+ locks = (+ ("SELECT singleton_id FROM execution_gateway_state WHERE singleton_id=1", None),+ ("SELECT id FROM users WHERE id=?", actor_user_id),+ ("SELECT id FROM campaigns WHERE id=?", campaign_id),+ (+ "SELECT user_id FROM execution_actor_authority_revisions WHERE user_id=?",+ actor_user_id,+ ),+ (+ "SELECT campaign_id FROM campaign_execution_authority_revisions WHERE campaign_id=?",+ campaign_id,+ ),+ ("SELECT id FROM logical_executions WHERE id=?", logical_id),+ )+ for sql, value in locks:+ params: tuple[Any, ...] = () if value is None else (value,)+ if await self._fetchrow(connection, sql + suffix, params) is None:+ return None+ return (+ logical_id,+ campaign_id,+ actor_user_id,+ actor_subject_ref,+ actor_authority_revision,+ )++ def _transition_receipt_spec(+ self,+ request: TransitionRequest,+ *,+ operation_code: str | None = None,+ ) -> _ReceiptSpec:+ if operation_code is None and request.resolver_subject_ref is not None:+ operation_code = {+ AttemptState.SUCCEEDED: "recovery_succeeded",+ AttemptState.PARTIAL: "recovery_partial",+ AttemptState.FAILED: "recovery_failed",+ AttemptState.CANCELLED: "recovery_cancelled",+ AttemptState.TIMED_OUT: "recovery_timed_out",+ AttemptState.INDETERMINATE: "recovery_indeterminate",+ }.get(request.target_state)+ if operation_code is None:+ operation_code = {+ AttemptState.QUEUED: "queue",+ AttemptState.DISPATCHING: "dispatch",+ AttemptState.RUNNING: "start",+ AttemptState.CANCELLING: "cancellation_request",+ AttemptState.SETTLEMENT_PENDING: "settlement_pending",+ AttemptState.TIMED_OUT: "timeout",+ AttemptState.SKIPPED: "terminal_skipped",+ AttemptState.INDETERMINATE: "recovery_indeterminate",+ }.get(request.target_state)+ if operation_code is None:+ if (+ request.cancellation_request_revision is not None+ or request.target_state is AttemptState.CANCELLED+ ):+ operation_code = "cancellation_acknowledgement"+ else:+ operation_code = "terminal_" + request.target_state.value+ principal = self._transition_principal(request)+ return self._receipt_spec(+ operation_id=request.operation_id,+ operation_code=operation_code,+ campaign_id=request.campaign_id,+ primary_target_id=request.attempt_id,+ principal_kind=principal[0],+ principal_subject_ref=principal[1],+ principal_user_id=principal[2],+ principal_authority_revision=principal[3],+ expected_revision=request.expected_revision,+ owner_ref=request.owner_ref,+ lease_generation=request.lease_generation,+ fields=(+ ("target_state", request.target_state.value),+ ("lease_duration_ms", request.lease_duration_ms),+ ("cancellation_request_revision", request.cancellation_request_revision),+ (+ "outcome_code",+ None if request.outcome_code is None else request.outcome_code.value,+ ),+ ("authoritative_proof", request.authoritative_proof),+ ("resolver_subject_ref", request.resolver_subject_ref),+ ("resolver_user_id", request.resolver_user_id),+ ("resolver_authority_revision", request.resolver_authority_revision),+ ("outbox_id", request.outbox_id),+ ("publication_key", request.publication_key),+ ),+ )++ @staticmethod+ def _transition_principal(+ request: TransitionRequest,+ ) -> tuple[str, str, str | None, int | None]:+ if request.resolver_subject_ref is not None:+ return (+ "resolver",+ request.resolver_subject_ref,+ request.resolver_user_id,+ request.resolver_authority_revision,+ )+ if request.owner_ref is not None:+ return ("worker", request.owner_ref, None, None)+ if request.actor_subject_ref is not None:+ return (+ "actor",+ request.actor_subject_ref,+ request.actor_user_id,+ request.actor_authority_revision,+ )+ return ("system", SYSTEM_PRINCIPAL_SUBJECT_REF, None, None)++ def _terminal_receipt_spec(+ self,+ request: TerminalCommitRequest,+ ) -> _ReceiptSpec:+ transition = request.transition+ operation_code = self._transition_receipt_spec(+ transition,+ ).operation_code+ principal = self._transition_principal(transition)+ fields: tuple[tuple[str, str | int | bool | None], ...] = (+ ("logical_execution_id", request.logical_execution_id),+ ("target_state", transition.target_state.value),+ (+ "outcome_code",+ None if transition.outcome_code is None else transition.outcome_code.value,+ ),+ ("authoritative_proof", transition.authoritative_proof),+ ("cancellation_request_revision", transition.cancellation_request_revision),+ ("resolver_subject_ref", transition.resolver_subject_ref),+ ("resolver_user_id", transition.resolver_user_id),+ ("resolver_authority_revision", transition.resolver_authority_revision),+ ("outbox_id", request.outbox_id),+ ("publication_key", request.publication_key),+ ("noise_budget_id", request.budgets.noise_budget_id),+ ("noise_units", request.budgets.noise_units),+ ("noise_actual", request.budgets.noise_actual),+ ("noise_expected_revision", request.budgets.noise_expected_revision),+ ("exfiltration_budget_id", request.budgets.exfiltration_budget_id),+ ("exfiltration_units", request.budgets.exfiltration_units),+ ("exfiltration_actual", request.budgets.exfiltration_actual),+ (+ "exfiltration_expected_revision",+ request.budgets.exfiltration_expected_revision,+ ),+ ("concurrency_budget_id", request.budgets.concurrency_budget_id),+ (+ "concurrency_expected_revision",+ request.budgets.concurrency_expected_revision,+ ),+ ) + tuple(+ item+ for index, output in enumerate(+ sorted(+ request.outputs,+ key=lambda value: (value.kind.value, value.target_id, value.link_id),+ )+ )+ for item in (+ (f"output_{index}_link_id", output.link_id),+ (f"output_{index}_kind", output.kind.value),+ (f"output_{index}_target_id", output.target_id),+ )+ )+ return self._receipt_spec(+ operation_id=transition.operation_id,+ operation_code=operation_code,+ campaign_id=request.campaign_id,+ primary_target_id=transition.attempt_id,+ secondary_target_id=request.logical_execution_id,+ principal_kind=principal[0],+ principal_subject_ref=principal[1],+ principal_user_id=principal[2],+ principal_authority_revision=principal[3],+ expected_revision=transition.expected_revision,+ owner_ref=transition.owner_ref,+ lease_generation=transition.lease_generation,+ fields=fields,+ )++ @staticmethod+ def _terminal_v3_outcome_contract(+ outcome_code: OutcomeCode,+ ) -> tuple[AttemptState, AttemptState, str, str] | None:+ """Return the sole known-settled predecessor/terminal binding for V3."""+ return {+ OutcomeCode.CONFIRMED_SUCCESS: (+ AttemptState.RUNNING,+ AttemptState.SUCCEEDED,+ "terminal_succeeded",+ "local_completion",+ ),+ OutcomeCode.CONFIRMED_FAILURE: (+ AttemptState.RUNNING,+ AttemptState.FAILED,+ "terminal_failed",+ "local_completion",+ ),+ OutcomeCode.CONFIRMED_CANCELLED_NO_RESULT: (+ AttemptState.CANCELLING,+ AttemptState.CANCELLED,+ "cancellation_acknowledgement",+ "cancellation_no_result_ack",+ ),+ OutcomeCode.CONFIRMED_TIMEOUT_TERMINATED: (+ AttemptState.RUNNING,+ AttemptState.TIMED_OUT,+ "timeout",+ "timeout_termination_ack",+ ),+ }.get(outcome_code)++ @classmethod+ def _canonical_terminal_v3_outputs(+ cls,+ intent: object,+ ) -> tuple[OutputObservation, ...] | None:+ if (+ type(intent) is not TerminalCommitIntentV3+ or not all(+ valid_uuid(value)+ for value in (+ intent.logical_execution_id,+ intent.campaign_id,+ intent.attempt_id,+ )+ )+ or type(intent.expected_attempt_revision) is not int+ or not 0 <= intent.expected_attempt_revision < MAX_I53+ or type(intent.outcome_code) is not OutcomeCode+ or cls._terminal_v3_outcome_contract(intent.outcome_code) is None+ or any(+ type(value) is not int or not 0 <= value <= MAX_I53+ for value in (+ intent.noise_actual,+ intent.exfiltration_actual,+ intent.concurrency_actual,+ )+ )+ or intent.concurrency_actual != 0+ or type(intent.outputs) is not tuple+ or len(intent.outputs) > MAX_TERMINAL_OUTPUTS_V3+ or not cls._valid_output_observations(intent.outputs)+ ):+ return None+ result_digest = intent.execution_result_digest+ if intent.outcome_code in {+ OutcomeCode.CONFIRMED_SUCCESS,+ OutcomeCode.CONFIRMED_FAILURE,+ }:+ if (+ type(result_digest) is not str+ or re.fullmatch(r"[0-9a-f]{64}", result_digest) is None+ ):+ return None+ elif result_digest is not None:+ return None+ if intent.outcome_code is not OutcomeCode.CONFIRMED_SUCCESS and intent.outputs:+ return None+ return tuple(+ sorted(+ intent.outputs,+ key=lambda output: (output.kind.value, output.target_id, output.link_id),+ )+ )++ @staticmethod+ def _terminal_v3_operation_id(attempt_id: str) -> str:+ """Derive one terminal receipt authority for the canonical attempt UUID."""+ digest = canonical_operation_binding_digest(+ _TERMINAL_COMMIT_OPERATION_ID_DOMAIN_V3,+ (+ ("attempt_id", attempt_id),+ ("action", _TERMINAL_COMMIT_ACTION_V3),+ ),+ )+ return (+ digest[:8]+ + "-"+ + digest[8:12]+ + "-4"+ + digest[13:16]+ + "-8"+ + digest[17:20]+ + "-"+ + digest[20:32]+ )++ @staticmethod+ def _terminal_v3_receipt_spec(+ intent: TerminalCommitIntentV3,+ operation_id: str,+ operation_code: str,+ outputs: tuple[OutputObservation, ...],+ ) -> _ReceiptSpec:+ fields: tuple[tuple[str, str | int | bool | None], ...] = (+ ("terminal_commit_contract_version", TERMINAL_COMMIT_CONTRACT_VERSION_V3),+ ("logical_execution_id", intent.logical_execution_id),+ ("campaign_id", intent.campaign_id),+ ("attempt_id", intent.attempt_id),+ ("operation_id", operation_id),+ ("expected_attempt_revision", intent.expected_attempt_revision),+ ("operation_code", operation_code),+ ("outcome_code", intent.outcome_code.value),+ ("noise_actual", intent.noise_actual),+ ("exfiltration_actual", intent.exfiltration_actual),+ ("concurrency_actual", intent.concurrency_actual),+ ("execution_result_digest_present", intent.execution_result_digest is not None),+ ("execution_result_digest", intent.execution_result_digest),+ ("output_count", len(outputs)),+ ) + tuple(+ item+ for index, output in enumerate(outputs)+ for item in (+ (f"output_{index}_link_id", output.link_id),+ (f"output_{index}_kind", output.kind.value),+ (f"output_{index}_target_id", output.target_id),+ )+ )+ return _ReceiptSpec(+ operation_id=operation_id,+ operation_code=operation_code,+ campaign_id=intent.campaign_id,+ primary_target_id=intent.attempt_id,+ secondary_target_id=intent.logical_execution_id,+ principal_kind="system",+ principal_subject_ref=SYSTEM_PRINCIPAL_SUBJECT_REF,+ principal_user_id=None,+ principal_authority_revision=None,+ request_binding_digest=canonical_operation_binding_digest(+ _TERMINAL_COMMIT_REQUEST_DOMAIN_V3,+ fields,+ ),+ expected_revision=intent.expected_attempt_revision,+ secondary_expected_revision=None,+ owner_ref=None,+ lease_generation=None,+ )++ async def ensure_actor_authority(self, user_id: str, operation_id: str) -> OperationResult:+ try:+ return await self._ensure_actor_authority(user_id, operation_id)+ except _AbortOperationError as aborted:+ return aborted.result++ async def _ensure_actor_authority(self, user_id: str, operation_id: str) -> OperationResult:+ if not valid_uuid(user_id) or not valid_uuid(operation_id):+ return OperationResult(FixedResult.INVALID_CONTRACT, None)+ spec = self._receipt_spec(+ operation_id=operation_id,+ operation_code="actor_authority_ensure",+ campaign_id=None,+ primary_target_id=user_id,+ )+ async with self._transaction() as connection:+ await self._acquire_transaction_key(connection, operation_id)+ replay = await self._classify_receipt(connection, spec, current_revision=None)+ if replay is not None:+ return replay+ suffix = " FOR UPDATE" if self._dialect == "postgresql" else ""+ gateway = await self._fetchrow(+ connection,+ "SELECT singleton_id FROM execution_gateway_state WHERE singleton_id=1" + suffix,+ (),+ )+ if gateway is None:+ return OperationResult(FixedResult.CONFLICT_STATE, None)+ user = await self._fetchrow(+ connection,+ "SELECT id,username,role,is_active,auth_epoch FROM users WHERE id=?" + suffix,+ (user_id,),+ )+ if user is None:+ return OperationResult(FixedResult.NOT_FOUND_OR_PURGED, None)+ row = await self._fetchrow(+ connection,+ "SELECT revision FROM execution_actor_authority_revisions WHERE user_id=?" + suffix,+ (user_id,),+ )+ if row is not None:+ return OperationResult(+ FixedResult.ALREADY_EXISTS, int(self._value(row, "revision", 0))+ )+ inserted = await self.cas_update_one(+ connection,+ "INSERT INTO execution_actor_authority_revisions("+ "user_id,revision,latest_operation_id,latest_operation_base_revision,"+ "latest_operation_code,authority_state,authority_revision,"+ "authority_binding_digest) VALUES(?,0,?,0,'ensure','active',0,?) "+ "ON CONFLICT(user_id) DO NOTHING RETURNING user_id,revision",+ (+ user_id,+ operation_id,+ self._actor_authority_binding(+ user_id,+ str(self._value(user, "username", 1)),+ str(self._value(user, "role", 2)),+ bool(self._value(user, "is_active", 3)),+ int(self._value(user, "auth_epoch", 4)),+ ),+ ),+ identity=user_id,+ post_revision=0,+ identity_column="user_id",+ zero_classifier=lambda: self._classify_zero_row(+ connection,+ table="execution_actor_authority_revisions",+ identity_column="user_id",+ identity=user_id,+ revision_column="revision",+ missing_result=FixedResult.INVARIANT_FAILURE,+ matched_result=FixedResult.CONFLICT_OPERATION,+ receipt_spec=spec,+ ),+ )+ if inserted is None:+ raise _AbortOperationError(OperationResult(FixedResult.CONFLICT_OPERATION, None))+ await self._insert_receipt(+ connection,+ spec,+ result=FixedResult.APPLIED,+ result_identity=user_id,+ result_revision=0,+ )+ return OperationResult(FixedResult.APPLIED, 0)++ async def _mutate_existing_authority_v11(+ self,+ principal: TrustedPrincipal,+ mutation: ActorAuthorityMutation | CampaignAuthorityMutation,+ *,+ kind: str,+ action: str,+ ) -> OperationResult:+ if not self._valid_trusted_principal(principal):+ return OperationResult(FixedResult.INVALID_CONTRACT, None)+ if kind not in {"actor", "campaign"} or action not in {+ "activate",+ "update",+ "revoke",+ }:+ return OperationResult(FixedResult.INVALID_CONTRACT, None)+ expected_type = ActorAuthorityMutation if kind == "actor" else CampaignAuthorityMutation+ target = (+ mutation.actor_user_id+ if type(mutation) is ActorAuthorityMutation+ else mutation.campaign_id+ if type(mutation) is CampaignAuthorityMutation+ else None+ )+ if (+ type(mutation) is not expected_type+ or target is None+ or not valid_uuid(target)+ or not valid_uuid(mutation.operation_id)+ or not self._valid_expected_revision(mutation.expected_revision)+ ):+ return OperationResult(FixedResult.INVALID_CONTRACT, None)+ code = f"{kind}_authority_{action}"+ campaign_id = target if kind == "campaign" else None+ table = (+ "execution_actor_authority_revisions"+ if kind == "actor"+ else "campaign_execution_authority_revisions"+ )+ key = "user_id" if kind == "actor" else "campaign_id"+ suffix = " FOR UPDATE" if self._dialect == "postgresql" else ""+ try:+ async with self._transaction() as connection:+ await self._acquire_transaction_key(connection, mutation.operation_id)+ authority_spec = await self._v11_actor_receipt_spec(+ connection,+ principal,+ suffix=suffix,+ operation_id=mutation.operation_id,+ operation_code=code,+ campaign_id=campaign_id,+ primary_target_id=target,+ expected_revision=mutation.expected_revision,+ )+ if authority_spec is None:+ return OperationResult(FixedResult.AUTHORITY_STALE, None)+ spec, resolved = authority_spec+ replay = await self._classify_receipt(+ connection, spec, current_revision=mutation.expected_revision+ )+ if replay is not None:+ return replay+ if resolved is None:+ resolved = await self._resolve_principal(connection, principal, suffix=suffix)+ if resolved is None:+ return OperationResult(FixedResult.AUTHORITY_STALE, None)+ if kind == "actor" and resolved.role != "admin":+ return OperationResult(FixedResult.AUTHORITY_STALE, None)+ if kind == "campaign" and not await self._principal_can_mutate_campaign(+ connection,+ resolved,+ target,+ suffix=suffix,+ ):+ return OperationResult(FixedResult.AUTHORITY_STALE, None)+ row = await self._fetchrow(+ connection,+ f"SELECT authority_state,authority_revision,authority_binding_digest "+ f"FROM {table} WHERE {key}=?" + suffix,+ (target,),+ )+ persisted = await self._fetchrow(+ connection,+ (+ "SELECT id,username,role,is_active,auth_epoch FROM users WHERE id=?"+ if kind == "actor"+ else "SELECT id,operator,status,noise_profile FROM campaigns WHERE id=?"+ )+ + suffix,+ (target,),+ )+ if row is None or persisted is None:+ return OperationResult(FixedResult.NOT_FOUND_OR_PURGED, None)+ revision = int(self._value(row, "authority_revision", 1))+ if revision != mutation.expected_revision:+ return OperationResult(FixedResult.CONFLICT_REVISION, revision)+ state = str(self._value(row, "authority_state", 0))+ if action == "activate" and state != "revoked":+ return OperationResult(FixedResult.CONFLICT_STATE, revision)+ if action in {"update", "revoke"} and state != "active":+ return OperationResult(FixedResult.CONFLICT_STATE, revision)+ if kind == "actor":+ binding = self._actor_authority_binding(+ str(self._value(persisted, "id", 0)),+ str(self._value(persisted, "username", 1)),+ str(self._value(persisted, "role", 2)),+ bool(self._value(persisted, "is_active", 3)),+ int(self._value(persisted, "auth_epoch", 4)),+ )+ else:+ destination = await self._fetchrow(+ connection,+ "SELECT binding_digest FROM campaign_execution_destination_authorities "+ "WHERE campaign_id=?" + suffix,+ (target,),+ )+ if destination is None:+ return OperationResult(FixedResult.AUTHORITY_STALE, revision)+ binding = canonical_operation_binding_digest(+ "campaign-authority",+ (+ ("campaign_id", str(self._value(persisted, "id", 0))),+ ("operator", str(self._value(persisted, "operator", 1))),+ ("status", str(self._value(persisted, "status", 2))),+ ("noise_profile", str(self._value(persisted, "noise_profile", 3))),+ (+ "destination_binding_digest",+ str(self._value(destination, "binding_digest", 0)),+ ),+ ),+ )+ next_state = "revoked" if action == "revoke" else "active"+ updated = await self.cas_update_one(+ connection,+ f"UPDATE {table} SET authority_state=?,authority_revision=authority_revision+1,"+ "authority_binding_digest=?,authority_latest_operation_id=?,"+ "authority_latest_operation_base_revision=?,authority_latest_operation_code=?,"+ f"updated_at={self._now_sql} WHERE {key}=? AND authority_revision=? "+ f"AND authority_state=? RETURNING {key},authority_revision",+ (+ next_state,+ binding,+ mutation.operation_id,+ mutation.expected_revision,+ action,+ target,+ mutation.expected_revision,+ state,+ ),+ identity=target,+ post_revision=revision + 1,+ identity_column=key,+ revision_column="authority_revision",+ zero_classifier=lambda: self._classify_zero_row(+ connection,+ table=table,+ identity_column=key,+ identity=target,+ revision_column="authority_revision",+ checks=(+ (+ "authority_revision",+ (mutation.expected_revision,),+ FixedResult.CONFLICT_REVISION,+ ),+ ("authority_state", (state,), FixedResult.CONFLICT_STATE),+ ),+ ),+ )+ if updated is None:+ return OperationResult(FixedResult.CONFLICT_STATE, revision)+ await self._insert_receipt(+ connection,+ spec,+ result=FixedResult.APPLIED,+ result_identity=target,+ result_revision=revision + 1,+ result_fields=(+ ("authority_state", next_state),+ ("authority_binding_digest", binding),+ ),+ )+ return OperationResult(FixedResult.APPLIED, revision + 1)+ except _AbortOperationError as aborted:+ return aborted.result++ async def activate_actor_authority(+ self, principal: TrustedPrincipal, mutation: ActorAuthorityMutation+ ) -> OperationResult:+ return await self._mutate_existing_authority_v11(+ principal, mutation, kind="actor", action="activate"+ )++ async def update_actor_authority(+ self, principal: TrustedPrincipal, mutation: ActorAuthorityMutation+ ) -> OperationResult:+ return await self._mutate_existing_authority_v11(+ principal, mutation, kind="actor", action="update"+ )++ async def revoke_actor_authority(+ self, principal: TrustedPrincipal, mutation: ActorAuthorityMutation+ ) -> OperationResult:+ return await self._mutate_existing_authority_v11(+ principal, mutation, kind="actor", action="revoke"+ )++ async def activate_campaign_authority(+ self, principal: TrustedPrincipal, mutation: CampaignAuthorityMutation+ ) -> OperationResult:+ return await self._mutate_existing_authority_v11(+ principal, mutation, kind="campaign", action="activate"+ )++ async def update_campaign_authority(+ self, principal: TrustedPrincipal, mutation: CampaignAuthorityMutation+ ) -> OperationResult:+ return await self._mutate_existing_authority_v11(+ principal, mutation, kind="campaign", action="update"+ )++ async def revoke_campaign_authority(+ self, principal: TrustedPrincipal, mutation: CampaignAuthorityMutation+ ) -> OperationResult:+ return await self._mutate_existing_authority_v11(+ principal, mutation, kind="campaign", action="revoke"+ )++ async def update_gateway_authority(+ self, principal: TrustedPrincipal, mutation: GatewayAuthorityMutation+ ) -> OperationResult:+ if (+ not self._valid_trusted_principal(principal)+ or type(mutation) is not GatewayAuthorityMutation+ or not valid_uuid(mutation.operation_id)+ or not self._valid_expected_revision(mutation.expected_revision)+ or mutation.mode+ not in {"disabled", "shadow_candidate", "enforced", "emergency_disabled"}+ ):+ return OperationResult(FixedResult.INVALID_CONTRACT, None)+ # Once activated the v10 shape has no representable transition back to+ # disabled (disabled is the unique revision-zero bootstrap state).+ if mutation.mode == "disabled" and mutation.expected_revision != 0:+ return OperationResult(FixedResult.INVALID_CONTRACT, None)+ suffix = " FOR UPDATE" if self._dialect == "postgresql" else ""+ try:+ async with self._transaction() as connection:+ await self._acquire_transaction_key(connection, mutation.operation_id)+ authority_spec = await self._v11_actor_receipt_spec(+ connection,+ principal,+ suffix=suffix,+ operation_id=mutation.operation_id,+ operation_code="gateway_authority_update",+ campaign_id=None,+ primary_target_id=GATEWAY_AUTHORITY_TARGET_ID,+ expected_revision=mutation.expected_revision,+ fields=(("mode", mutation.mode),),+ )+ if authority_spec is None:+ return OperationResult(FixedResult.AUTHORITY_STALE, None)+ spec, resolved = authority_spec+ replay = await self._classify_receipt(+ connection, spec, current_revision=mutation.expected_revision+ )+ if replay is not None:+ return replay+ if resolved is None:+ resolved = await self._resolve_principal(connection, principal, suffix=suffix)+ if resolved is None:+ return OperationResult(FixedResult.AUTHORITY_STALE, None)+ if resolved.role != "admin":+ return OperationResult(FixedResult.AUTHORITY_STALE, None)+ row = await self._fetchrow(+ connection,+ "SELECT mode,revision FROM execution_gateway_state WHERE singleton_id=1"+ + suffix,+ (),+ )+ if row is None:+ return OperationResult(FixedResult.CONFLICT_STATE, None)+ revision = int(self._value(row, "revision", 1))+ if revision != mutation.expected_revision:+ return OperationResult(FixedResult.CONFLICT_REVISION, revision)+ if mutation.mode == "disabled":+ return OperationResult(FixedResult.CONFLICT_STATE, revision)+ catalog_digest = self._descriptor_catalog_digest()+ activation = mutation.mode != "disabled"+ updated = await self.cas_update_one(+ connection,+ "UPDATE execution_gateway_state SET mode=?,catalog_digest=?,"+ "activation_revision=?,activation_at="+ + (self._now_sql if activation else "NULL")+ + ",revision=revision+1,updated_at="+ + self._now_sql+ + " WHERE singleton_id=1 AND revision=? RETURNING singleton_id,revision",+ (+ mutation.mode,+ catalog_digest if activation else None,+ revision + 1 if activation else None,+ revision,+ ),+ identity=1,+ post_revision=revision + 1,+ identity_column="singleton_id",+ revision_column="revision",+ zero_classifier=lambda: self._classify_zero_row(+ connection,+ table="execution_gateway_state",+ identity_column="singleton_id",+ identity=1,+ revision_column="revision",+ checks=(+ (+ "revision",+ (mutation.expected_revision,),+ FixedResult.CONFLICT_REVISION,+ ),+ ),+ ),+ )+ if updated is None:+ return OperationResult(FixedResult.CONFLICT_REVISION, revision)+ await self._insert_receipt(+ connection,+ spec,+ result=FixedResult.APPLIED,+ result_identity=GATEWAY_AUTHORITY_TARGET_ID,+ result_revision=revision + 1,+ result_fields=(("mode", mutation.mode), ("catalog_digest", catalog_digest)),+ )+ return OperationResult(FixedResult.APPLIED, revision + 1)+ except _AbortOperationError as aborted:+ return aborted.result++ @staticmethod+ def _descriptor_catalog_digest() -> str:+ from ares.modules.descriptors import FIRST_PARTY_DESCRIPTORS++ encoded = bytearray(b"ares.descriptor-catalog.v1\x00")+ for module_id, descriptor in sorted(FIRST_PARTY_DESCRIPTORS.items()):+ for value in (module_id, descriptor.semantic_digest):+ item = value.encode("utf-8")+ encoded.extend(len(item).to_bytes(4, "big"))+ encoded.extend(item)+ return hashlib.sha256(encoded).hexdigest()++ async def _mutate_campaign_actor_grant(+ self,+ principal: TrustedPrincipal,+ mutation: CampaignActorGrantMutation,+ *,+ action: str,+ ) -> OperationResult:+ if (+ not self._valid_trusted_principal(principal)+ or type(mutation) is not CampaignActorGrantMutation+ or action not in {"put", "revoke"}+ or not all(+ valid_uuid(value)+ for value in (+ mutation.operation_id,+ mutation.campaign_id,+ mutation.actor_user_id,+ )+ )+ or not self._valid_expected_revision(+ mutation.expected_revision, optional=action == "put"+ )+ or (action == "revoke" and mutation.expected_revision is None)+ ):+ return OperationResult(FixedResult.INVALID_CONTRACT, None)+ suffix = " FOR UPDATE" if self._dialect == "postgresql" else ""+ try:+ async with self._transaction() as connection:+ await self._acquire_transaction_key(connection, mutation.operation_id)+ authority_spec = await self._v11_actor_receipt_spec(+ connection,+ principal,+ suffix=suffix,+ operation_id=mutation.operation_id,+ operation_code=f"campaign_actor_grant_{action}",+ campaign_id=mutation.campaign_id,+ primary_target_id=mutation.campaign_id,+ secondary_target_id=mutation.actor_user_id,+ expected_revision=mutation.expected_revision,+ fields=(("actor_user_id", mutation.actor_user_id),),+ )+ if authority_spec is None:+ return OperationResult(FixedResult.AUTHORITY_STALE, None)+ spec, resolved = authority_spec+ replay = await self._classify_receipt(+ connection, spec, current_revision=mutation.expected_revision+ )+ if replay is not None:+ return replay+ if resolved is None:+ resolved = await self._resolve_principal(connection, principal, suffix=suffix)+ if resolved is None:+ return OperationResult(FixedResult.AUTHORITY_STALE, None)+ if not await self._principal_can_mutate_campaign(+ connection,+ resolved,+ mutation.campaign_id,+ suffix=suffix,+ ):+ return OperationResult(FixedResult.AUTHORITY_STALE, None)+ campaign = await self._fetchrow(+ connection,+ "SELECT id FROM campaigns WHERE id=?" + suffix,+ (mutation.campaign_id,),+ )+ actor = await self._fetchrow(+ connection,+ "SELECT id FROM users WHERE id=?" + suffix,+ (mutation.actor_user_id,),+ )+ if campaign is None or actor is None:+ return OperationResult(FixedResult.NOT_FOUND_OR_PURGED, None)+ row = await self._fetchrow(+ connection,+ "SELECT authority_state,revision FROM campaign_execution_actor_grants "+ "WHERE campaign_id=? AND actor_user_id=?" + suffix,+ (mutation.campaign_id, mutation.actor_user_id),+ )+ binding = canonical_operation_binding_digest(+ "campaign-actor-grant",+ (+ ("campaign_id", mutation.campaign_id),+ ("actor_user_id", mutation.actor_user_id),+ ("authority_state", "active" if action == "put" else "revoked"),+ ),+ )+ if row is None:+ if action != "put" or mutation.expected_revision is not None:+ return OperationResult(FixedResult.CONFLICT_STATE, None)+ inserted = await self.cas_update_one(+ connection,+ "INSERT INTO campaign_execution_actor_grants("+ "campaign_id,actor_user_id,authority_state,revision,binding_digest,"+ "latest_operation_id,latest_operation_base_revision,latest_operation_code) "+ "VALUES(?,?,'active',0,?,?,0,'put') ON CONFLICT(campaign_id,actor_user_id) "+ "DO NOTHING RETURNING campaign_id,revision",+ (+ mutation.campaign_id,+ mutation.actor_user_id,+ binding,+ mutation.operation_id,+ ),+ identity=mutation.campaign_id,+ post_revision=0,+ identity_column="campaign_id",+ revision_column="revision",+ zero_classifier=lambda: self._classify_zero_row(+ connection,+ table="campaign_execution_actor_grants",+ identity_column="campaign_id",+ identity=mutation.campaign_id,+ revision_column="revision",+ matched_result=FixedResult.CONFLICT_OPERATION,+ ),+ )+ if inserted is None:+ return OperationResult(FixedResult.CONFLICT_OPERATION, None)+ next_revision = 0+ else:+ revision = int(self._value(row, "revision", 1))+ state = str(self._value(row, "authority_state", 0))+ if mutation.expected_revision != revision:+ return OperationResult(FixedResult.CONFLICT_REVISION, revision)+ if action == "put" and state != "revoked":+ return OperationResult(FixedResult.CONFLICT_STATE, revision)+ if action == "revoke" and state != "active":+ return OperationResult(FixedResult.CONFLICT_STATE, revision)+ next_state = "active" if action == "put" else "revoked"+ next_revision = revision + 1+ updated = await self.cas_update_one(+ connection,+ "UPDATE campaign_execution_actor_grants SET authority_state=?,"+ "revision=revision+1,binding_digest=?,latest_operation_id=?,"+ "latest_operation_base_revision=?,latest_operation_code=?,updated_at="+ + self._now_sql+ + " WHERE campaign_id=? AND actor_user_id=? AND revision=? "+ "AND authority_state=? RETURNING campaign_id,revision",+ (+ next_state,+ binding,+ mutation.operation_id,+ revision,+ action,+ mutation.campaign_id,+ mutation.actor_user_id,+ revision,+ state,+ ),+ identity=mutation.campaign_id,+ post_revision=next_revision,+ identity_column="campaign_id",+ revision_column="revision",+ zero_classifier=lambda: self._classify_zero_row(+ connection,+ table="campaign_execution_actor_grants",+ identity_column="campaign_id",+ identity=mutation.campaign_id,+ revision_column="revision",+ checks=(("revision", (revision,), FixedResult.CONFLICT_REVISION),),+ ),+ )+ if updated is None:+ return OperationResult(FixedResult.CONFLICT_STATE, revision)+ await self._insert_receipt(+ connection,+ spec,+ result=FixedResult.APPLIED,+ result_identity=mutation.actor_user_id,+ result_revision=next_revision,+ result_fields=(+ ("authority_state", "active" if action == "put" else "revoked"),+ ),+ )+ return OperationResult(FixedResult.APPLIED, next_revision)+ except _AbortOperationError as aborted:+ return aborted.result++ async def put_campaign_actor_grant(+ self, principal: TrustedPrincipal, mutation: CampaignActorGrantMutation+ ) -> OperationResult:+ return await self._mutate_campaign_actor_grant(principal, mutation, action="put")++ async def revoke_campaign_actor_grant(+ self, principal: TrustedPrincipal, mutation: CampaignActorGrantMutation+ ) -> OperationResult:+ return await self._mutate_campaign_actor_grant(principal, mutation, action="revoke")++ async def _mutate_destination_authority(+ self,+ principal: TrustedPrincipal,+ mutation: DestinationAuthorityMutation,+ *,+ action: str,+ ) -> OperationResult:+ if (+ not self._valid_trusted_principal(principal)+ or type(mutation) is not DestinationAuthorityMutation+ or action not in {"update", "revoke"}+ or not valid_uuid(mutation.operation_id)+ or not valid_uuid(mutation.campaign_id)+ or not self._valid_expected_revision(mutation.expected_revision)+ ):+ return OperationResult(FixedResult.INVALID_CONTRACT, None)+ suffix = " FOR UPDATE" if self._dialect == "postgresql" else ""+ try:+ async with self._transaction() as connection:+ await self._acquire_transaction_key(connection, mutation.operation_id)+ authority_spec = await self._v11_actor_receipt_spec(+ connection,+ principal,+ suffix=suffix,+ operation_id=mutation.operation_id,+ operation_code=f"destination_authority_{action}",+ campaign_id=mutation.campaign_id,+ primary_target_id=mutation.campaign_id,+ expected_revision=mutation.expected_revision,+ )+ if authority_spec is None:+ return OperationResult(FixedResult.AUTHORITY_STALE, None)+ spec, resolved = authority_spec+ replay = await self._classify_receipt(+ connection, spec, current_revision=mutation.expected_revision+ )+ if replay is not None:+ return replay+ if resolved is None:+ resolved = await self._resolve_principal(connection, principal, suffix=suffix)+ if resolved is None:+ return OperationResult(FixedResult.AUTHORITY_STALE, None)+ if not await self._principal_can_mutate_campaign(+ connection,+ resolved,+ mutation.campaign_id,+ suffix=suffix,+ ):+ return OperationResult(FixedResult.AUTHORITY_STALE, None)+ campaign = await self._fetchrow(+ connection,+ "SELECT scope_json,targets_json FROM campaigns WHERE id=?" + suffix,+ (mutation.campaign_id,),+ )+ row = await self._fetchrow(+ connection,+ "SELECT authority_state,revision FROM "+ "campaign_execution_destination_authorities WHERE campaign_id=?" + suffix,+ (mutation.campaign_id,),+ )+ if campaign is None or row is None:+ return OperationResult(FixedResult.NOT_FOUND_OR_PURGED, None)+ revision = int(self._value(row, "revision", 1))+ state = str(self._value(row, "authority_state", 0))+ if revision != mutation.expected_revision:+ return OperationResult(FixedResult.CONFLICT_REVISION, revision)+ if state != "active":+ return OperationResult(FixedResult.CONFLICT_STATE, revision)+ try:+ values = self._canonical_destination_values(+ self._value(campaign, "scope_json", 0),+ self._value(campaign, "targets_json", 1),+ )+ count, digest, binding = self._destination_authority_facts(values)+ except ValueError:+ return OperationResult(FixedResult.INVALID_CONTRACT, revision)+ next_state = "revoked" if action == "revoke" else "active"+ updated = await self.cas_update_one(+ connection,+ "UPDATE campaign_execution_destination_authorities SET authority_state=?,"+ "revision=revision+1,normalization_version=?,destination_count=?,"+ "destination_set_digest=?,binding_digest=?,latest_operation_id=?,"+ "latest_operation_base_revision=?,latest_operation_code=?,updated_at="+ + self._now_sql+ + " WHERE campaign_id=? AND revision=? AND authority_state='active' "+ "RETURNING campaign_id,revision",+ (+ next_state,+ DESTINATION_NORMALIZATION_VERSION,+ count,+ digest,+ binding,+ mutation.operation_id,+ revision,+ action,+ mutation.campaign_id,+ revision,+ ),+ identity=mutation.campaign_id,+ post_revision=revision + 1,+ identity_column="campaign_id",+ revision_column="revision",+ zero_classifier=lambda: self._classify_zero_row(+ connection,+ table="campaign_execution_destination_authorities",+ identity_column="campaign_id",+ identity=mutation.campaign_id,+ revision_column="revision",+ checks=(+ ("revision", (revision,), FixedResult.CONFLICT_REVISION),+ ("authority_state", ("active",), FixedResult.CONFLICT_STATE),+ ),+ ),+ )+ if updated is None:+ return OperationResult(FixedResult.CONFLICT_STATE, revision)+ await self._insert_receipt(+ connection,+ spec,+ result=FixedResult.APPLIED,+ result_identity=mutation.campaign_id,+ result_revision=revision + 1,+ result_fields=(+ ("authority_state", next_state),+ ("binding_digest", binding),+ ),+ )+ return OperationResult(FixedResult.APPLIED, revision + 1)+ except _AbortOperationError as aborted:+ return aborted.result++ async def update_destination_authority(+ self, principal: TrustedPrincipal, mutation: DestinationAuthorityMutation+ ) -> OperationResult:+ return await self._mutate_destination_authority(principal, mutation, action="update")++ async def revoke_destination_authority(+ self, principal: TrustedPrincipal, mutation: DestinationAuthorityMutation+ ) -> OperationResult:+ return await self._mutate_destination_authority(principal, mutation, action="revoke")++ async def _mutate_credential_authority(+ self,+ principal: TrustedPrincipal,+ mutation: CredentialAuthorityMutation,+ *,+ action: str,+ ) -> OperationResult:+ if (+ not self._valid_trusted_principal(principal)+ or type(mutation) is not CredentialAuthorityMutation+ or action not in {"update", "revoke"}+ or not valid_uuid(mutation.operation_id)+ or not valid_uuid(mutation.credential_id)+ or not self._valid_expected_revision(mutation.expected_revision)+ ):+ return OperationResult(FixedResult.INVALID_CONTRACT, None)+ suffix = " FOR UPDATE" if self._dialect == "postgresql" else ""+ try:+ async with self._transaction() as connection:+ await self._acquire_transaction_key(connection, mutation.operation_id)+ prior = await self._receipt_row(connection, mutation.operation_id)+ if prior is not None:+ authority_spec = await self._v11_actor_receipt_spec(+ connection,+ principal,+ suffix=suffix,+ operation_id=mutation.operation_id,+ operation_code=f"credential_authority_{action}",+ campaign_id=self._value(prior, "campaign_id", 1),+ primary_target_id=mutation.credential_id,+ expected_revision=mutation.expected_revision,+ )+ if authority_spec is None:+ return OperationResult(FixedResult.INVALID_CONTRACT, None)+ spec, _ = authority_spec+ replay = await self._classify_receipt(+ connection,+ spec,+ current_revision=mutation.expected_revision,+ )+ return replay or OperationResult(+ FixedResult.CONFLICT_OPERATION,+ mutation.expected_revision,+ )+ gateway = await self._fetchrow(+ connection,+ "SELECT singleton_id FROM execution_gateway_state "+ "WHERE singleton_id=1" + suffix,+ (),+ )+ if gateway is None:+ return OperationResult(FixedResult.AUTHORITY_STALE, None)+ resolved = await self._resolve_principal(connection, principal, suffix=suffix)+ if resolved is None:+ return OperationResult(FixedResult.AUTHORITY_STALE, None)+ credential = await self._fetchrow(+ connection,+ "SELECT id,campaign_id,host_id,username,cred_type,domain,source_module,"+ "execution_authority_state,execution_authority_revision "+ "FROM credentials WHERE id=?" + suffix,+ (mutation.credential_id,),+ )+ if credential is None:+ return OperationResult(FixedResult.NOT_FOUND_OR_PURGED, None)+ campaign_id = str(self._value(credential, "campaign_id", 1))+ authority_spec = await self._v11_actor_receipt_spec(+ connection,+ principal,+ suffix=suffix,+ operation_id=mutation.operation_id,+ operation_code=f"credential_authority_{action}",+ campaign_id=campaign_id,+ primary_target_id=mutation.credential_id,+ expected_revision=mutation.expected_revision,+ )+ if authority_spec is None:+ return OperationResult(FixedResult.AUTHORITY_STALE, None)+ spec, _ = authority_spec+ if not await self._principal_can_mutate_campaign(+ connection,+ resolved,+ campaign_id,+ suffix=suffix,+ ):+ return OperationResult(FixedResult.AUTHORITY_STALE, None)+ revision = int(self._value(credential, "execution_authority_revision", 8))+ state = str(self._value(credential, "execution_authority_state", 7))+ if revision != mutation.expected_revision:+ return OperationResult(FixedResult.CONFLICT_REVISION, revision)+ if state != "active":+ return OperationResult(FixedResult.CONFLICT_STATE, revision)+ binding = self._credential_authority_binding(credential)+ next_state = "revoked" if action == "revoke" else "active"+ updated = await self.cas_update_one(+ connection,+ "UPDATE credentials SET execution_authority_state=?,"+ "execution_authority_revision=execution_authority_revision+1,"+ "execution_authority_binding_digest=?,"+ "execution_authority_latest_operation_id=?,"+ "execution_authority_latest_operation_base_revision=?,"+ "execution_authority_latest_operation_code=? WHERE id=? "+ "AND execution_authority_revision=? AND execution_authority_state='active' "+ "RETURNING id,execution_authority_revision",+ (+ next_state,+ binding,+ mutation.operation_id,+ revision,+ action,+ mutation.credential_id,+ revision,+ ),+ identity=mutation.credential_id,+ post_revision=revision + 1,+ revision_column="execution_authority_revision",+ zero_classifier=lambda: self._classify_zero_row(+ connection,+ table="credentials",+ identity_column="id",+ identity=mutation.credential_id,+ revision_column="execution_authority_revision",+ checks=(+ (+ "execution_authority_revision",+ (revision,),+ FixedResult.CONFLICT_REVISION,+ ),+ (+ "execution_authority_state",+ ("active",),+ FixedResult.CONFLICT_STATE,+ ),+ ),+ ),+ )+ if updated is None:+ return OperationResult(FixedResult.CONFLICT_STATE, revision)+ await self._insert_receipt(+ connection,+ spec,+ result=FixedResult.APPLIED,+ result_identity=mutation.credential_id,+ result_revision=revision + 1,+ result_fields=(+ ("authority_state", next_state),+ ("binding_digest", binding),+ ),+ )+ return OperationResult(FixedResult.APPLIED, revision + 1)+ except _AbortOperationError as aborted:+ return aborted.result++ async def update_credential_authority(+ self, principal: TrustedPrincipal, mutation: CredentialAuthorityMutation+ ) -> OperationResult:+ return await self._mutate_credential_authority(principal, mutation, action="update")++ async def revoke_credential_authority(+ self, principal: TrustedPrincipal, mutation: CredentialAuthorityMutation+ ) -> OperationResult:+ return await self._mutate_credential_authority(principal, mutation, action="revoke")++ async def grant_approval_authority(+ self, principal: TrustedPrincipal, mutation: ApprovalAuthorityGrant+ ) -> OperationResult:+ if (+ not self._valid_trusted_principal(principal)+ or type(mutation) is not ApprovalAuthorityGrant+ or not all(+ valid_uuid(value)+ for value in (+ mutation.operation_id,+ mutation.approval_id,+ mutation.approval_ref,+ mutation.campaign_id,+ mutation.submission_id,+ mutation.attempt_id,+ mutation.actor_subject_ref,+ mutation.actor_user_id,+ )+ )+ or type(mutation.module_id) is not str+ or mutation.actor_subject_ref != mutation.actor_user_id+ or type(mutation.granted_capability_mask) is not int+ or not 0 <= mutation.granted_capability_mask <= 15+ ):+ return OperationResult(FixedResult.INVALID_CONTRACT, None)+ suffix = " FOR UPDATE" if self._dialect == "postgresql" else ""+ fields: tuple[tuple[str, str | int | bool | None], ...] = (+ ("approval_ref", mutation.approval_ref),+ ("submission_id", mutation.submission_id),+ ("attempt_id", mutation.attempt_id),+ ("actor_subject_ref", mutation.actor_subject_ref),+ ("actor_user_id", mutation.actor_user_id),+ ("module_id", mutation.module_id),+ ("granted_capability_mask", mutation.granted_capability_mask),+ )+ try:+ async with self._transaction() as connection:+ await self._acquire_transaction_key(connection, mutation.operation_id)+ authority_spec = await self._v11_actor_receipt_spec(+ connection,+ principal,+ suffix=suffix,+ operation_id=mutation.operation_id,+ operation_code="approval_authority_grant",+ campaign_id=mutation.campaign_id,+ primary_target_id=mutation.approval_id,+ expected_revision=None,+ fields=fields,+ )+ if authority_spec is None:+ return OperationResult(FixedResult.AUTHORITY_STALE, None)+ spec, resolved = authority_spec+ replay = await self._classify_receipt(connection, spec, current_revision=None)+ if replay is not None:+ return replay+ if resolved is None:+ resolved = await self._resolve_principal(connection, principal, suffix=suffix)+ if resolved is None:+ return OperationResult(FixedResult.AUTHORITY_STALE, None)+ if not await self._principal_can_mutate_campaign(+ connection,+ resolved,+ mutation.campaign_id,+ suffix=suffix,+ ):+ return OperationResult(FixedResult.AUTHORITY_STALE, None)+ from ares.modules.descriptors import get_descriptor++ descriptor = get_descriptor(mutation.module_id)+ if descriptor is None:+ return OperationResult(FixedResult.INVALID_CONTRACT, None)+ descriptor_digest = descriptor.semantic_digest+ campaign = await self._fetchrow(+ connection,+ "SELECT id FROM campaigns WHERE id=?" + suffix,+ (mutation.campaign_id,),+ )+ actor = await self._fetchrow(+ connection,+ "SELECT id FROM users WHERE id=?" + suffix,+ (mutation.actor_user_id,),+ )+ if campaign is None or actor is None:+ return OperationResult(FixedResult.NOT_FOUND_OR_PURGED, None)+ binding = canonical_operation_binding_digest(+ "approval-authority",+ fields+ + (+ ("descriptor_semantic_digest", descriptor_digest),+ ("approver_subject_ref", resolved.subject_ref),+ ("approver_user_id", resolved.user_id),+ ("authority_state", "active"),+ ),+ )+ inserted = await self.cas_update_one(+ connection,+ "INSERT INTO execution_approval_authorities("+ "id,approval_ref,campaign_id,submission_id,attempt_id,actor_subject_ref,"+ "actor_user_id,module_id,approver_subject_ref,approver_user_id,authority_state,"+ "revision,granted_capability_mask,descriptor_semantic_digest,binding_digest,"+ "latest_operation_id,latest_operation_base_revision,latest_operation_code) "+ "VALUES(?,?,?,?,?,?,?,?,?,?,'active',0,?,?,?,?,0,'grant') "+ "ON CONFLICT DO NOTHING RETURNING id,revision",+ (+ mutation.approval_id,+ mutation.approval_ref,+ mutation.campaign_id,+ mutation.submission_id,+ mutation.attempt_id,+ mutation.actor_subject_ref,+ mutation.actor_user_id,+ mutation.module_id,+ resolved.subject_ref,+ resolved.user_id,+ mutation.granted_capability_mask,+ descriptor_digest,+ binding,+ mutation.operation_id,+ ),+ identity=mutation.approval_id,+ post_revision=0,+ revision_column="revision",+ zero_classifier=None,+ )+ if inserted is None:+ return OperationResult(FixedResult.CONFLICT_OPERATION, None)+ await self._insert_receipt(+ connection,+ spec,+ result=FixedResult.APPLIED,+ result_identity=mutation.approval_id,+ result_revision=0,+ result_fields=(("binding_digest", binding),),+ )+ return OperationResult(FixedResult.APPLIED, 0)+ except _AbortOperationError as aborted:+ return aborted.result++ async def revoke_approval_authority(+ self, principal: TrustedPrincipal, mutation: ApprovalAuthorityMutation+ ) -> OperationResult:+ if (+ not self._valid_trusted_principal(principal)+ or type(mutation) is not ApprovalAuthorityMutation+ or not valid_uuid(mutation.operation_id)+ or not valid_uuid(mutation.approval_id)+ or not self._valid_expected_revision(mutation.expected_revision)+ ):+ return OperationResult(FixedResult.INVALID_CONTRACT, None)+ suffix = " FOR UPDATE" if self._dialect == "postgresql" else ""+ try:+ async with self._transaction() as connection:+ await self._acquire_transaction_key(connection, mutation.operation_id)+ prior = await self._receipt_row(connection, mutation.operation_id)+ if prior is not None:+ authority_spec = await self._v11_actor_receipt_spec(+ connection,+ principal,+ suffix=suffix,+ operation_id=mutation.operation_id,+ operation_code="approval_authority_revoke",+ campaign_id=self._value(prior, "campaign_id", 1),+ primary_target_id=mutation.approval_id,+ expected_revision=mutation.expected_revision,+ )+ if authority_spec is None:+ return OperationResult(FixedResult.INVALID_CONTRACT, None)+ spec, _ = authority_spec+ replay = await self._classify_receipt(+ connection,+ spec,+ current_revision=mutation.expected_revision,+ )+ return replay or OperationResult(+ FixedResult.CONFLICT_OPERATION,+ mutation.expected_revision,+ )+ gateway = await self._fetchrow(+ connection,+ "SELECT singleton_id FROM execution_gateway_state "+ "WHERE singleton_id=1" + suffix,+ (),+ )+ if gateway is None:+ return OperationResult(FixedResult.AUTHORITY_STALE, None)+ resolved = await self._resolve_principal(connection, principal, suffix=suffix)+ if resolved is None:+ return OperationResult(FixedResult.AUTHORITY_STALE, None)+ row = await self._fetchrow(+ connection,+ "SELECT id,approval_ref,approver_subject_ref,approver_user_id,revision,"+ "binding_digest,authority_state,campaign_id,submission_id,attempt_id,"+ "actor_subject_ref,actor_user_id,module_id,granted_capability_mask,"+ "descriptor_semantic_digest FROM "+ "execution_approval_authorities WHERE id=?" + suffix,+ (mutation.approval_id,),+ )+ campaign_id = None if row is None else str(self._value(row, "campaign_id", 7))+ authority_spec = await self._v11_actor_receipt_spec(+ connection,+ principal,+ suffix=suffix,+ operation_id=mutation.operation_id,+ operation_code="approval_authority_revoke",+ campaign_id=campaign_id,+ primary_target_id=mutation.approval_id,+ expected_revision=mutation.expected_revision,+ )+ if authority_spec is None:+ return OperationResult(FixedResult.AUTHORITY_STALE, None)+ spec, _ = authority_spec+ if row is None:+ return OperationResult(FixedResult.NOT_FOUND_OR_PURGED, None)+ if not await self._principal_can_mutate_campaign(+ connection,+ resolved,+ str(campaign_id),+ suffix=suffix,+ ):+ return OperationResult(FixedResult.AUTHORITY_STALE, None)+ revision = int(self._value(row, "revision", 4))+ if revision != mutation.expected_revision:+ return OperationResult(FixedResult.CONFLICT_REVISION, revision)+ if self._value(row, "authority_state", 6) != "active":+ return OperationResult(FixedResult.CONFLICT_STATE, revision)+ binding = self._approval_authority_binding(+ row,+ authority_state="revoked",+ )+ updated = await self.cas_update_one(+ connection,+ "UPDATE execution_approval_authorities SET authority_state='revoked',"+ "revision=revision+1,binding_digest=?,latest_operation_id=?,"+ "latest_operation_base_revision=?,latest_operation_code='revoke',updated_at="+ + self._now_sql+ + " WHERE id=? AND revision=? AND authority_state='active' "+ "RETURNING id,revision",+ (+ binding,+ mutation.operation_id,+ revision,+ mutation.approval_id,+ revision,+ ),+ identity=mutation.approval_id,+ post_revision=revision + 1,+ revision_column="revision",+ zero_classifier=lambda: self._classify_zero_row(+ connection,+ table="execution_approval_authorities",+ identity_column="id",+ identity=mutation.approval_id,+ revision_column="revision",+ checks=(+ ("revision", (revision,), FixedResult.CONFLICT_REVISION),+ ("authority_state", ("active",), FixedResult.CONFLICT_STATE),+ ),+ ),+ )+ if updated is None:+ return OperationResult(FixedResult.CONFLICT_STATE, revision)+ await self._insert_receipt(+ connection,+ spec,+ result=FixedResult.APPLIED,+ result_identity=mutation.approval_id,+ result_revision=revision + 1,+ result_fields=(+ ("authority_state", "revoked"),+ ("binding_digest", binding),+ ),+ )+ return OperationResult(FixedResult.APPLIED, revision + 1)+ except _AbortOperationError as aborted:+ return aborted.result++ async def ensure_campaign_authority(+ self, campaign_id: str, operation_id: str+ ) -> OperationResult:+ try:+ return await self._ensure_campaign_authority(campaign_id, operation_id)+ except _AbortOperationError as aborted:+ return aborted.result++ async def _ensure_campaign_authority(+ self, campaign_id: str, operation_id: str+ ) -> OperationResult:+ if not valid_uuid(campaign_id) or not valid_uuid(operation_id):+ return OperationResult(FixedResult.INVALID_CONTRACT, None)+ spec = self._receipt_spec(+ operation_id=operation_id,+ operation_code="campaign_authority_ensure",+ campaign_id=campaign_id,+ primary_target_id=campaign_id,+ )+ async with self._transaction() as connection:+ await self._acquire_transaction_key(connection, operation_id)+ replay = await self._classify_receipt(connection, spec, current_revision=None)+ if replay is not None:+ return replay+ suffix = " FOR UPDATE" if self._dialect == "postgresql" else ""+ gateway = await self._fetchrow(+ connection,+ "SELECT singleton_id FROM execution_gateway_state WHERE singleton_id=1" + suffix,+ (),+ )+ if gateway is None:+ return OperationResult(FixedResult.CONFLICT_STATE, None)+ campaign = await self._fetchrow(+ connection,+ "SELECT id,operator,status,noise_profile,scope_json,targets_json "+ "FROM campaigns WHERE id=?" + suffix,+ (campaign_id,),+ )+ if campaign is None:+ return OperationResult(FixedResult.NOT_FOUND_OR_PURGED, None)+ row = await self._fetchrow(+ connection,+ "SELECT revision FROM campaign_execution_authority_revisions WHERE campaign_id=?"+ + suffix,+ (campaign_id,),+ )+ if row is not None:+ return OperationResult(+ FixedResult.ALREADY_EXISTS, int(self._value(row, "revision", 0))+ )+ try:+ destination_values = self._canonical_destination_values(+ self._value(campaign, "scope_json", 4),+ self._value(campaign, "targets_json", 5),+ )+ destination_count, destination_digest, destination_binding = (+ self._destination_authority_facts(destination_values)+ )+ except ValueError:+ return OperationResult(FixedResult.INVALID_CONTRACT, None)+ campaign_binding = self._campaign_authority_binding(+ campaign,+ destination_binding,+ )+ async with self._savepoint(connection):+ destination_insert = await self.cas_update_one(+ connection,+ "INSERT INTO campaign_execution_destination_authorities("+ "campaign_id,authority_state,revision,normalization_version,"+ "destination_count,destination_set_digest,binding_digest,"+ "latest_operation_id,latest_operation_base_revision,latest_operation_code) "+ "VALUES(?,'active',0,?,?,?,?,?,0,'update') ON CONFLICT(campaign_id) "+ "DO NOTHING RETURNING campaign_id,revision",+ (+ campaign_id,+ DESTINATION_NORMALIZATION_VERSION,+ destination_count,+ destination_digest,+ destination_binding,+ operation_id,+ ),+ identity=campaign_id,+ post_revision=0,+ identity_column="campaign_id",+ revision_column="revision",+ zero_classifier=None,+ )+ if destination_insert is None:+ raise _AbortOperationError(+ OperationResult(FixedResult.CONFLICT_OPERATION, None)+ )+ inserted = await self.cas_update_one(+ connection,+ "INSERT INTO campaign_execution_authority_revisions("+ "campaign_id,revision,latest_operation_id,latest_operation_base_revision,"+ "latest_operation_code,authority_state,authority_revision,"+ "authority_binding_digest) VALUES(?,0,?,0,'ensure','active',0,?) "+ "ON CONFLICT(campaign_id) DO NOTHING RETURNING campaign_id,revision",+ (campaign_id, operation_id, campaign_binding),+ identity=campaign_id,+ post_revision=0,+ identity_column="campaign_id",+ zero_classifier=lambda: self._classify_zero_row(+ connection,+ table="campaign_execution_authority_revisions",+ identity_column="campaign_id",+ identity=campaign_id,+ revision_column="revision",+ missing_result=FixedResult.INVARIANT_FAILURE,+ matched_result=FixedResult.CONFLICT_OPERATION,+ receipt_spec=spec,+ ),+ )+ if inserted is None:+ raise _AbortOperationError(+ OperationResult(FixedResult.CONFLICT_OPERATION, None)+ )+ await self._insert_receipt(+ connection,+ spec,+ result=FixedResult.APPLIED,+ result_identity=campaign_id,+ result_revision=0,+ )+ return OperationResult(FixedResult.APPLIED, 0)++ async def _invalidate_authority(+ self,+ *,+ table: str,+ key: str,+ value: str,+ expected_revision: int,+ operation_id: str,+ ) -> OperationResult:+ if (+ table+ not in {"execution_actor_authority_revisions", "campaign_execution_authority_revisions"}+ or key not in {"user_id", "campaign_id"}+ or type(value) is not str+ or type(expected_revision) is not int+ or not 0 <= expected_revision < MAX_I53+ or not valid_uuid(operation_id)+ ):+ return OperationResult(FixedResult.INVALID_CONTRACT, None)+ operation_code = (+ "actor_authority_invalidate"+ if table == "execution_actor_authority_revisions"+ else "campaign_authority_invalidate"+ )+ spec = self._receipt_spec(+ operation_id=operation_id,+ operation_code=operation_code,+ campaign_id=value if key == "campaign_id" else None,+ primary_target_id=value,+ expected_revision=expected_revision,+ )+ async with self._transaction() as connection:+ await self._acquire_transaction_key(connection, operation_id)+ replay = await self._classify_receipt(+ connection, spec, current_revision=expected_revision+ )+ if replay is not None:+ return replay+ suffix = " FOR UPDATE" if self._dialect == "postgresql" else ""+ gateway = await self._fetchrow(+ connection,+ "SELECT singleton_id FROM execution_gateway_state WHERE singleton_id=1" + suffix,+ (),+ )+ if gateway is None:+ return OperationResult(FixedResult.CONFLICT_STATE, None)+ owner_table = "users" if key == "user_id" else "campaigns"+ owner = await self._fetchrow(+ connection, f"SELECT id FROM {owner_table} WHERE id=?" + suffix, (value,)+ )+ if owner is None:+ return OperationResult(FixedResult.NOT_FOUND_OR_PURGED, None)+ row = await self._fetchrow(+ connection,+ f"SELECT revision FROM {table} WHERE {key}=?" + suffix,+ (value,),+ )+ if row is None:+ return OperationResult(FixedResult.CONFLICT_STATE, None)+ revision = int(self._value(row, "revision", 0))+ if revision != expected_revision:+ return OperationResult(FixedResult.CONFLICT_REVISION, revision)+ updated = await self.cas_update_one(+ connection,+ f"UPDATE {table} SET revision=revision+1,latest_operation_id=?,latest_operation_base_revision=?,latest_operation_code='invalidate',updated_at="+ + (+ "floor(extract(epoch FROM clock_timestamp())*1000)::bigint"+ if self._dialect == "postgresql"+ else "CAST((julianday('now')-2440587.5)*86400000 AS INTEGER)"+ )+ + f" WHERE {key}=? AND revision=? RETURNING {key},revision",+ (operation_id, expected_revision, value, expected_revision),+ identity=value,+ post_revision=expected_revision + 1,+ identity_column=key,+ zero_classifier=lambda: self._classify_zero_row(+ connection,+ table=table,+ identity_column=key,+ identity=value,+ revision_column="revision",+ checks=(("revision", (expected_revision,), FixedResult.CONFLICT_REVISION),),+ missing_result=FixedResult.CONFLICT_STATE,+ ),+ )+ if updated is None:+ return OperationResult(FixedResult.CONFLICT_REVISION, revision)+ await self._insert_receipt(+ connection,+ spec,+ result=FixedResult.APPLIED,+ result_identity=value,+ result_revision=expected_revision + 1,+ )+ return OperationResult(FixedResult.APPLIED, expected_revision + 1)++ async def invalidate_actor_authority(+ self, user_id: str, expected_revision: int, operation_id: str+ ) -> OperationResult:+ try:+ return await self._invalidate_authority(+ table="execution_actor_authority_revisions",+ key="user_id",+ value=user_id,+ expected_revision=expected_revision,+ operation_id=operation_id,+ )+ except _AbortOperationError as aborted:+ return aborted.result++ async def invalidate_campaign_authority(+ self, campaign_id: str, expected_revision: int, operation_id: str+ ) -> OperationResult:+ try:+ return await self._invalidate_authority(+ table="campaign_execution_authority_revisions",+ key="campaign_id",+ value=campaign_id,+ expected_revision=expected_revision,+ operation_id=operation_id,+ )+ except _AbortOperationError as aborted:+ return aborted.result++ async def configure_campaign_budgets(self, request: BudgetConfiguration) -> OperationResult:+ try:+ return await self._configure_campaign_budgets(request)+ except _AbortOperationError as aborted:+ return aborted.result++ async def _configure_campaign_budgets(self, request: BudgetConfiguration) -> OperationResult:+ if (+ type(request) is not BudgetConfiguration+ or not all(+ valid_uuid(value)+ for value in (+ request.campaign_id,+ request.noise_budget_id,+ request.exfiltration_budget_id,+ request.concurrency_budget_id,+ request.operation_id,+ )+ )+ or not all(+ self._valid_nonnegative_i53(value)+ for value in (+ request.noise_capacity,+ request.exfiltration_capacity,+ request.concurrency_capacity,+ )+ )+ or request.concurrency_capacity < 1+ or not self._valid_principal_binding(request)+ ):+ return OperationResult(FixedResult.INVALID_CONTRACT, None)+ requested = (+ ("noise", request.noise_budget_id, request.noise_capacity),+ (+ "exfiltration",+ request.exfiltration_budget_id,+ request.exfiltration_capacity,+ ),+ (+ "concurrency",+ request.concurrency_budget_id,+ request.concurrency_capacity,+ ),+ )+ spec = self._receipt_spec(+ operation_id=request.operation_id,+ operation_code="budget_configure",+ campaign_id=request.campaign_id,+ primary_target_id=request.campaign_id,+ principal_kind=str(request.principal_kind),+ principal_subject_ref=str(request.principal_subject_ref),+ principal_user_id=request.principal_user_id,+ principal_authority_revision=request.principal_authority_revision,+ fields=(+ ("noise_budget_id", request.noise_budget_id),+ ("noise_capacity", request.noise_capacity),+ ("exfiltration_budget_id", request.exfiltration_budget_id),+ ("exfiltration_capacity", request.exfiltration_capacity),+ ("concurrency_budget_id", request.concurrency_budget_id),+ ("concurrency_capacity", request.concurrency_capacity),+ ),+ )+ async with self._transaction() as connection:+ await self._acquire_transaction_key(connection, request.operation_id)+ replay = await self._classify_receipt(connection, spec, current_revision=None)+ if replay is not None:+ return replay+ suffix = " FOR UPDATE" if self._dialect == "postgresql" else ""+ gateway = await self._fetchrow(+ connection,+ "SELECT singleton_id FROM execution_gateway_state WHERE singleton_id=1" + suffix,+ (),+ )+ if gateway is None:+ return OperationResult(FixedResult.CONFLICT_STATE, None)+ campaign = await self._fetchrow(+ connection, "SELECT id FROM campaigns WHERE id=?" + suffix, (request.campaign_id,)+ )+ if campaign is None:+ return OperationResult(FixedResult.NOT_FOUND_OR_PURGED, None)+ authority = await self._fetchrow(+ connection,+ "SELECT revision FROM campaign_execution_authority_revisions WHERE campaign_id=?"+ + suffix,+ (request.campaign_id,),+ )+ if authority is None:+ return OperationResult(FixedResult.AUTHORITY_STALE, None)+ rows = await self._fetchall(+ connection,+ "SELECT id,budget_kind,capacity_units,reserved_units,consumed_units,"+ "revision,latest_operation_id,latest_operation_code "+ "FROM campaign_execution_budgets WHERE campaign_id=? "+ "ORDER BY CASE budget_kind WHEN 'noise' THEN 1 "+ "WHEN 'exfiltration' THEN 2 ELSE 3 END" + suffix,+ (request.campaign_id,),+ )+ if rows:+ return OperationResult(FixedResult.ALREADY_EXISTS, None)+ async with self._savepoint(connection):+ for kind, budget_id, capacity in requested:+ inserted = await self.insert_or_validate_binding(+ connection,+ "INSERT INTO campaign_execution_budgets("+ "id,campaign_id,budget_kind,capacity_units,reserved_units,"+ "consumed_units,revision,latest_operation_id,"+ "latest_operation_base_revision,latest_operation_code) "+ "VALUES(?,?,?,?,0,0,0,?,0,'configure') "+ "ON CONFLICT(id) DO NOTHING RETURNING id,revision",+ (+ budget_id,+ request.campaign_id,+ kind,+ capacity,+ request.operation_id,+ ),+ identity=budget_id,+ revision=0,+ )+ if inserted is None:+ raise _AbortOperationError(+ OperationResult(FixedResult.CONFLICT_OPERATION, None)+ )+ await self._insert_receipt(+ connection,+ spec,+ result=FixedResult.APPLIED,+ result_identity=request.campaign_id,+ result_revision=0,+ result_fields=(("budget_count", 3),),+ )+ return OperationResult(FixedResult.APPLIED, 0)++ async def reserve_budgets(self, request: BudgetReservation) -> OperationResult:+ try:+ return await self._reserve_budgets(request)+ except _AbortOperationError as aborted:+ return aborted.result++ async def _reserve_budgets(self, request: BudgetReservation) -> OperationResult:+ if not self._valid_budget_reservation(request):+ return OperationResult(FixedResult.INVALID_CONTRACT, None)+ entries = (+ (+ "noise",+ request.noise_budget_id,+ request.noise_ledger_id,+ request.noise_units,+ request.noise_expected_revision,+ ),+ (+ "exfiltration",+ request.exfiltration_budget_id,+ request.exfiltration_ledger_id,+ request.exfiltration_units,+ request.exfiltration_expected_revision,+ ),+ (+ "concurrency",+ request.concurrency_budget_id,+ request.concurrency_ledger_id,+ 1,+ request.concurrency_expected_revision,+ ),+ )+ spec = self._budget_reservation_receipt_spec(request)+ async with self._transaction() as connection:+ await self._acquire_transaction_key(connection, request.operation_id)+ replay = await self._classify_receipt(+ connection,+ spec,+ current_revision=max(+ request.noise_expected_revision,+ request.exfiltration_expected_revision,+ request.concurrency_expected_revision,+ ),+ )+ if replay is not None:+ return replay+ suffix = " FOR UPDATE" if self._dialect == "postgresql" else ""+ discovery = await self._fetchrow(+ connection,+ "SELECT logical_execution_id,actor_user_id FROM execution_attempts WHERE id=?",+ (request.attempt_id,),+ )+ if discovery is None:+ return OperationResult(FixedResult.NOT_FOUND_OR_PURGED, None)+ actor_user_id = str(self._value(discovery, "actor_user_id", 1))+ logical_execution_id = str(self._value(discovery, "logical_execution_id", 0))+ await self._acquire_logical_attempt_transaction_keys(+ connection,+ logical_execution_id,+ request.attempt_id,+ )+ await self._fetchrow(+ connection,+ "SELECT singleton_id FROM execution_gateway_state WHERE singleton_id=1" + suffix,+ (),+ )+ for sql, value in (+ ("SELECT id FROM users WHERE id=?", actor_user_id),+ ("SELECT id FROM campaigns WHERE id=?", request.campaign_id),+ (+ "SELECT user_id FROM execution_actor_authority_revisions WHERE user_id=?",+ actor_user_id,+ ),+ (+ "SELECT campaign_id FROM campaign_execution_authority_revisions WHERE campaign_id=?",+ request.campaign_id,+ ),+ ("SELECT id FROM logical_executions WHERE id=?", logical_execution_id),+ ("SELECT id FROM execution_attempts WHERE id=?", request.attempt_id),+ ):+ locked = await self._fetchrow(connection, sql + suffix, (value,))+ if locked is None:+ return OperationResult(FixedResult.AUTHORITY_STALE, None)+ validated: list[tuple[str, str, str, int, int]] = []+ budget_rows: list[Any] = []+ for kind, budget_id, ledger_id, units, expected_revision in entries:+ row = await self._fetchrow(+ connection,+ "SELECT id,campaign_id,budget_kind,capacity_units,reserved_units,"+ "consumed_units,revision FROM campaign_execution_budgets "+ "WHERE id=?" + suffix,+ (budget_id,),+ )+ if row is None or (+ self._value(row, "campaign_id", 1) != request.campaign_id+ or self._value(row, "budget_kind", 2) != kind+ ):+ return OperationResult(FixedResult.INCONSISTENT_BUDGET_SET, None)+ budget_rows.append(row)+ validated.append((kind, budget_id, ledger_id, units, expected_revision))+ existing = await self._fetchall(+ connection,+ "SELECT id,budget_kind,budget_id,reservation_units,"+ "budget_revision_reserved FROM campaign_execution_budget_ledger "+ "WHERE attempt_id=? ORDER BY CASE budget_kind WHEN 'noise' THEN 1 "+ "WHEN 'exfiltration' THEN 2 ELSE 3 END" + suffix,+ (request.attempt_id,),+ )+ if existing:+ return OperationResult(FixedResult.CONFLICT_OPERATION, None)+ for row, (_kind, _budget_id, _ledger_id, units, expected_revision) in zip(+ budget_rows, validated, strict=True+ ):+ revision = int(self._value(row, "revision", 6))+ if revision != expected_revision:+ return OperationResult(FixedResult.CONFLICT_REVISION, revision)+ capacity = int(self._value(row, "capacity_units", 3))+ reserved = int(self._value(row, "reserved_units", 4))+ consumed = int(self._value(row, "consumed_units", 5))+ if reserved + consumed + units > capacity:+ return OperationResult(FixedResult.CAPACITY_UNAVAILABLE, revision)+ async with self._savepoint(connection):+ for kind, budget_id, ledger_id, units, expected_revision in validated:+ updated = await self.cas_update_one(+ connection,+ "UPDATE campaign_execution_budgets SET "+ "reserved_units=reserved_units+?,revision=revision+1,"+ "latest_operation_id=?,latest_operation_base_revision=?,"+ "latest_operation_code='reserve',updated_at="+ + self._now_sql+ + " WHERE id=? AND revision=? AND reserved_units+consumed_units+?<=capacity_units RETURNING id,revision",+ (+ units,+ request.operation_id,+ expected_revision,+ budget_id,+ expected_revision,+ units,+ ),+ identity=budget_id,+ post_revision=expected_revision + 1,+ zero_classifier=lambda budget_id=budget_id, kind=kind, expected_revision=expected_revision, units=units: (+ self._classify_zero_budget(+ connection,+ budget_id=budget_id,+ campaign_id=request.campaign_id,+ budget_kind=kind,+ expected_revision=expected_revision,+ required_units=units,+ operation="reserve",+ )+ ),+ )+ if updated is None:+ raise _AbortOperationError(+ OperationResult(FixedResult.CONFLICT_REVISION, expected_revision)+ )+ inserted = await self.insert_or_validate_binding(+ connection,+ "INSERT INTO campaign_execution_budget_ledger("+ "id,attempt_id,campaign_id,budget_id,budget_kind,"+ "reservation_units,consumed_units,disposition,"+ "budget_revision_reserved) VALUES(?,?,?,?,?,?,0,'held',?) "+ "ON CONFLICT(id) DO NOTHING RETURNING id,budget_revision_reserved",+ (+ ledger_id,+ request.attempt_id,+ request.campaign_id,+ budget_id,+ kind,+ units,+ expected_revision + 1,+ ),+ identity=ledger_id,+ revision=expected_revision + 1,+ revision_column="budget_revision_reserved",+ )+ if inserted is None:+ raise _AbortOperationError(+ OperationResult(FixedResult.CONFLICT_OPERATION, None)+ )+ result_fields = (+ ("noise_ledger_id", request.noise_ledger_id),+ ("noise_post_revision", request.noise_expected_revision + 1),+ ("exfiltration_ledger_id", request.exfiltration_ledger_id),+ ("exfiltration_post_revision", request.exfiltration_expected_revision + 1),+ ("concurrency_ledger_id", request.concurrency_ledger_id),+ ("concurrency_post_revision", request.concurrency_expected_revision + 1),+ )+ await self._insert_receipt(+ connection,+ spec,+ result=FixedResult.APPLIED,+ result_identity=request.attempt_id,+ result_revision=max(+ request.noise_expected_revision,+ request.exfiltration_expected_revision,+ request.concurrency_expected_revision,+ )+ + 1,+ secondary_result_identity=request.noise_budget_id,+ secondary_result_revision=request.noise_expected_revision + 1,+ result_fields=result_fields,+ )+ return OperationResult(FixedResult.APPLIED, None)++ def _valid_budget_reservation(self, request: object) -> bool:+ if type(request) is not BudgetReservation:+ return False+ identifiers = (+ request.campaign_id,+ request.attempt_id,+ request.noise_budget_id,+ request.noise_ledger_id,+ request.exfiltration_budget_id,+ request.exfiltration_ledger_id,+ request.concurrency_budget_id,+ request.concurrency_ledger_id,+ request.operation_id,+ )+ numbers = (+ request.noise_units,+ request.noise_expected_revision,+ request.exfiltration_units,+ request.exfiltration_expected_revision,+ request.concurrency_expected_revision,+ )+ return (+ all(valid_uuid(value) for value in identifiers)+ and all(self._valid_nonnegative_i53(value) for value in numbers)+ and self._valid_principal_binding(request)+ )++ def _budget_reservation_receipt_spec(self, request: BudgetReservation) -> _ReceiptSpec:+ return self._receipt_spec(+ operation_id=request.operation_id,+ operation_code="budget_reserve",+ campaign_id=request.campaign_id,+ primary_target_id=request.attempt_id,+ secondary_target_id=request.noise_budget_id,+ principal_kind=str(request.principal_kind),+ principal_subject_ref=str(request.principal_subject_ref),+ principal_user_id=request.principal_user_id,+ principal_authority_revision=request.principal_authority_revision,+ expected_revision=request.noise_expected_revision,+ secondary_expected_revision=request.exfiltration_expected_revision,+ fields=(+ ("noise_budget_id", request.noise_budget_id),+ ("noise_ledger_id", request.noise_ledger_id),+ ("noise_units", request.noise_units),+ ("exfiltration_budget_id", request.exfiltration_budget_id),+ ("exfiltration_ledger_id", request.exfiltration_ledger_id),+ ("exfiltration_units", request.exfiltration_units),+ ("concurrency_budget_id", request.concurrency_budget_id),+ ("concurrency_ledger_id", request.concurrency_ledger_id),+ ("concurrency_expected_revision", request.concurrency_expected_revision),+ ),+ )++ async def settle_budgets(self, request: BudgetSettlement) -> OperationResult:+ if not self._valid_budget_settlement(request):+ return OperationResult(FixedResult.INVALID_CONTRACT, None)+ spec = self._budget_settlement_receipt_spec(request)+ try:+ async with self._transaction() as connection:+ await self._acquire_transaction_key(connection, request.operation_id)+ replay = await self._classify_receipt(+ connection,+ spec,+ current_revision=max(+ request.noise_expected_revision,+ request.exfiltration_expected_revision,+ request.concurrency_expected_revision,+ ),+ )+ if replay is not None:+ return replay+ suffix = " FOR UPDATE" if self._dialect == "postgresql" else ""+ discovery = await self._fetchrow(+ connection,+ "SELECT logical_execution_id,actor_user_id FROM execution_attempts WHERE id=?",+ (request.attempt_id,),+ )+ if discovery is None:+ return OperationResult(FixedResult.NOT_FOUND_OR_PURGED, None)+ actor_user_id = str(self._value(discovery, "actor_user_id", 1))+ logical_execution_id = str(self._value(discovery, "logical_execution_id", 0))+ await self._acquire_logical_attempt_transaction_keys(+ connection,+ logical_execution_id,+ request.attempt_id,+ )+ await self._fetchrow(+ connection,+ "SELECT singleton_id FROM execution_gateway_state WHERE singleton_id=1"+ + suffix,+ (),+ )+ for sql, value in (+ ("SELECT id FROM users WHERE id=?", actor_user_id),+ ("SELECT id FROM campaigns WHERE id=?", request.campaign_id),+ (+ "SELECT user_id FROM execution_actor_authority_revisions WHERE user_id=?",+ actor_user_id,+ ),+ (+ "SELECT campaign_id FROM campaign_execution_authority_revisions WHERE campaign_id=?",+ request.campaign_id,+ ),+ ("SELECT id FROM logical_executions WHERE id=?", logical_execution_id),+ ("SELECT id FROM execution_attempts WHERE id=?", request.attempt_id),+ ):+ if await self._fetchrow(connection, sql + suffix, (value,)) is None:+ return OperationResult(FixedResult.AUTHORITY_STALE, None)+ async with self._savepoint(connection):+ result = await self._settle_budgets_locked(connection, request)+ if result.result not in {+ FixedResult.APPLIED,+ FixedResult.REPLAYED,+ FixedResult.SUPERSEDED,+ }:+ raise _AbortOperationError(result)+ return result+ except _AbortOperationError as aborted:+ return aborted.result++ def _valid_budget_settlement(self, request: object) -> bool:+ if type(request) is not BudgetSettlement:+ return False+ identifiers = (+ request.campaign_id,+ request.attempt_id,+ request.noise_budget_id,+ request.exfiltration_budget_id,+ request.concurrency_budget_id,+ request.operation_id,+ )+ numbers = (+ request.noise_units,+ request.noise_actual,+ request.noise_expected_revision,+ request.exfiltration_units,+ request.exfiltration_actual,+ request.exfiltration_expected_revision,+ request.concurrency_expected_revision,+ )+ return (+ all(valid_uuid(value) for value in identifiers)+ and all(self._valid_nonnegative_i53(value) for value in numbers)+ and request.noise_actual <= request.noise_units+ and request.exfiltration_actual <= request.exfiltration_units+ and self._valid_principal_binding(request)+ )++ @staticmethod+ def _valid_snapshot(snapshot: object) -> bool:+ if type(snapshot) is not AttemptPolicySnapshot:+ return False+ boolean_fields = (+ "request_structure_valid",+ "canonicalization_complete",+ "unknown_fields_absent",+ "alternate_transport_absent",+ "bounded_shape_valid",+ "trusted_first_party_binding",+ "descriptor_binding_current",+ "descriptor_complete",+ "static_policy_evaluable",+ "preview_ready",+ "lifecycle_ready",+ "result_authority_ready",+ "transport_ready",+ "future_gateway_eligible",+ "authority_snapshots_complete",+ "authority_revisions_current",+ "actor_authenticated",+ "actor_active",+ "campaign_active",+ "actor_campaign_authorized",+ "approval_present",+ "approval_current",+ "approval_exactly_bound",+ "destination_extraction_complete",+ "destinations_in_scope",+ "credential_authority_resolved",+ "credential_authority_current",+ "opaque_handles_only",+ "permitted_handle_kinds_only",+ "raw_credentials_absent",+ "ambient_credentials_absent",+ "budget_authority_resolved",+ "budget_authority_current",+ "budget_capacity_available",+ )+ integer_fields = (+ "actor_authority_revision",+ "campaign_authority_revision",+ "destination_authority_revision",+ "credential_authority_revision",+ )+ if not all(type(getattr(snapshot, name)) is bool for name in boolean_fields):+ return False+ if not all(+ type(getattr(snapshot, name)) is int and 0 <= getattr(snapshot, name) <= MAX_I53+ for name in integer_fields+ ):+ return False+ if (+ type(snapshot.request_shape_units) is not int+ or not 0 <= snapshot.request_shape_units <= 4096+ or type(snapshot.required_capability_mask) is not int+ or not 0 <= snapshot.required_capability_mask <= 15+ or type(snapshot.granted_capability_mask) is not int+ or not 0 <= snapshot.granted_capability_mask <= 15+ or type(snapshot.descriptor_blocker_mask) is not int+ or not 0 <= snapshot.descriptor_blocker_mask <= 511+ or (+ snapshot.policy_reason_mask is not None+ and (+ type(snapshot.policy_reason_mask) is not int+ or not 0 <= snapshot.policy_reason_mask <= 34_359_738_367+ )+ )+ or type(snapshot.timeout_limit_ms) is not int+ or not MIN_TIMEOUT_MS <= snapshot.timeout_limit_ms <= MAX_TIMEOUT_MS+ ):+ return False+ domains = (+ (snapshot.evaluation_mode, ("preview", "live")),+ (snapshot.minimum_role, MINIMUM_ROLES),+ (snapshot.actor_role, ACTOR_ROLES),+ (snapshot.noise_class, NOISE_CLASSES),+ (snapshot.approval_policy, APPROVAL_POLICIES),+ (+ snapshot.gateway_mode_snapshot,+ ("disabled", "shadow_candidate", "enforced", "emergency_disabled"),+ ),+ (snapshot.gateway_decision_code, ("none", "emergency_disabled")),+ (snapshot.policy_evaluation_state, ("evaluated", "not_evaluated")),+ (snapshot.external_effect_class, EXTERNAL_EFFECT_CLASSES),+ (snapshot.idempotency_class, IDEMPOTENCY_CLASSES),+ (snapshot.retry_policy, RETRY_POLICIES),+ (snapshot.retry_disposition, RETRY_DISPOSITIONS),+ (snapshot.cancellation_ownership, CANCELLATION_OWNERSHIP),+ (snapshot.compensation_class, COMPENSATION_CLASSES),+ (snapshot.timeout_origin, TIMEOUT_ORIGINS),+ (snapshot.timeout_settlement, TIMEOUT_SETTLEMENTS),+ )+ if any(type(value) is not str or value not in domain for value, domain in domains):+ return False+ if snapshot.policy_verdict is not None and (+ type(snapshot.policy_verdict) is not str+ or snapshot.policy_verdict not in POLICY_VERDICTS+ ):+ return False+ if not (+ type(snapshot.descriptor_semantic_digest) is str+ and re.fullmatch(r"[0-9a-f]{64}", snapshot.descriptor_semantic_digest)+ and type(snapshot.catalog_digest) is str+ and re.fullmatch(r"[0-9a-f]{64}", snapshot.catalog_digest)+ ):+ return False+ return True++ @staticmethod+ def _snapshot_columns_values(+ snapshot: AttemptPolicySnapshot,+ ) -> tuple[tuple[str, ...], tuple[Any, ...]]:+ names = tuple(AttemptPolicySnapshot.__dataclass_fields__)+ columns = tuple(+ {+ "policy_reason_mask": "policy_reason_mask",+ }.get(name, name)+ for name in names+ )+ values = tuple(getattr(snapshot, name) for name in names)+ return columns, values++ @staticmethod+ def _role_satisfies(actor_role: str, minimum_role: str) -> bool:+ ranks = {"reporter": 0, "operator": 1, "team_lead": 2, "admin": 3}+ return ranks[actor_role] >= ranks[minimum_role]++ def _valid_admission(self, request: object) -> bool:+ if type(request) is not AdmissionRequest or not self._valid_snapshot(request.snapshot):+ return False+ identifiers = (+ request.logical_execution_id,+ request.submission_id,+ request.attempt_id,+ request.campaign_id,+ request.actor_subject_ref,+ request.actor_user_id,+ request.operation_id,+ )+ if not all(valid_uuid(value) for value in identifiers):+ return False+ if request.outbox_id is not None and not valid_uuid(request.outbox_id):+ return False+ if request.publication_key is not None and not valid_uuid(request.publication_key):+ return False+ if (+ type(request.module_id) is not str+ or re.fullmatch(r"[a-z][a-z0-9_.:-]{0,127}", request.module_id) is None+ or type(request.ingress_code) is not str+ or request.ingress_code not in INGRESS_CODES+ or type(request.initial_state) is not AttemptState+ or request.initial_state+ not in {AttemptState.REJECTED, AttemptState.BLOCKED, AttemptState.ACCEPTED}+ ):+ return False+ terminal = request.initial_state in {AttemptState.REJECTED, AttemptState.BLOCKED}+ if terminal != (request.outbox_id is not None and request.publication_key is not None):+ return False+ if terminal and (request.approval is not None or request.budgets is not None):+ return False+ snapshot = request.snapshot+ emergency = snapshot.gateway_mode_snapshot == "emergency_disabled"+ ordinary_policy_shape = (+ not emergency+ and snapshot.gateway_decision_code == "none"+ and snapshot.policy_evaluation_state == "evaluated"+ and snapshot.policy_verdict is not None+ and snapshot.policy_reason_mask is not None+ )+ emergency_policy_shape = (+ emergency+ and snapshot.gateway_decision_code == "emergency_disabled"+ and snapshot.policy_evaluation_state == "not_evaluated"+ and snapshot.policy_verdict is None+ and snapshot.policy_reason_mask is None+ )+ if not (ordinary_policy_shape or emergency_policy_shape):+ return False+ if request.initial_state is AttemptState.ACCEPTED:+ if (+ request.budgets is None+ or request.budgets.campaign_id != request.campaign_id+ or request.budgets.attempt_id != request.attempt_id+ or (+ self._principal_binding(request.budgets)+ not in {+ (+ "system",+ SYSTEM_PRINCIPAL_SUBJECT_REF,+ None,+ None,+ ),+ (+ "actor",+ request.actor_subject_ref,+ request.actor_user_id,+ request.snapshot.actor_authority_revision,+ ),+ }+ )+ ):+ return False+ if snapshot.approval_policy == "none" and request.approval is not None:+ return False+ if snapshot.approval_policy == "attempt_bound" and request.approval is None:+ return False+ if request.initial_state is AttemptState.REJECTED:+ return ordinary_policy_shape and snapshot.policy_verdict == "rejected"+ if request.initial_state is AttemptState.BLOCKED:+ return (+ ordinary_policy_shape+ and snapshot.policy_verdict == "blocked"+ or (ordinary_policy_shape and snapshot.policy_verdict == "preview_ready")+ or (emergency_policy_shape)+ )+ return (+ ordinary_policy_shape+ and snapshot.evaluation_mode == "live"+ and snapshot.policy_verdict == "live_candidate"+ and snapshot.gateway_mode_snapshot == "enforced"+ and snapshot.gateway_decision_code == "none"+ and snapshot.policy_reason_mask == 0+ and snapshot.request_structure_valid+ and snapshot.canonicalization_complete+ and snapshot.unknown_fields_absent+ and snapshot.alternate_transport_absent+ and snapshot.bounded_shape_valid+ and snapshot.trusted_first_party_binding+ and snapshot.descriptor_binding_current+ and snapshot.descriptor_complete+ and snapshot.static_policy_evaluable+ and snapshot.descriptor_blocker_mask == 0+ and snapshot.preview_ready+ and snapshot.future_gateway_eligible+ and snapshot.lifecycle_ready+ and snapshot.result_authority_ready+ and snapshot.transport_ready+ and snapshot.authority_snapshots_complete+ and snapshot.authority_revisions_current+ and snapshot.actor_authenticated+ and snapshot.actor_active+ and snapshot.campaign_active+ and snapshot.actor_campaign_authorized+ and self._role_satisfies(snapshot.actor_role, snapshot.minimum_role)+ and (+ snapshot.noise_class != "high_noise"+ or snapshot.actor_role in {"team_lead", "admin"}+ )+ and (snapshot.granted_capability_mask & snapshot.required_capability_mask)+ == snapshot.required_capability_mask+ and snapshot.destination_extraction_complete+ and snapshot.destinations_in_scope+ and snapshot.credential_authority_resolved+ and snapshot.credential_authority_current+ and snapshot.opaque_handles_only+ and snapshot.permitted_handle_kinds_only+ and snapshot.raw_credentials_absent+ and snapshot.ambient_credentials_absent+ and snapshot.budget_authority_resolved+ and snapshot.budget_authority_current+ and snapshot.budget_capacity_available+ and (+ (+ snapshot.approval_policy == "none"+ and not snapshot.approval_present+ and not snapshot.approval_current+ and not snapshot.approval_exactly_bound+ )+ or (+ snapshot.approval_policy == "attempt_bound"+ and snapshot.approval_present+ and snapshot.approval_current+ and snapshot.approval_exactly_bound+ and request.approval is not None+ )+ )+ )++ def _admission_receipt_spec(+ self, request: AdmissionRequest, *, operation_code: str = "admission"+ ) -> _ReceiptSpec:+ approval = request.approval+ budgets = request.budgets+ fields: tuple[tuple[str, str | int | bool | None], ...] = (+ ("submission_id", request.submission_id),+ ("attempt_id", request.attempt_id),+ ("actor_subject_ref", request.actor_subject_ref),+ ("actor_user_id", request.actor_user_id),+ ("module_id", request.module_id),+ ("ingress_code", request.ingress_code),+ ("initial_state", request.initial_state.value),+ ("outbox_id", request.outbox_id),+ ("publication_key", request.publication_key),+ ("approval_id", None if approval is None else approval.approval_id),+ ("approval_ref", None if approval is None else approval.approval_ref),+ (+ "approver_subject_ref",+ None if approval is None else approval.approver_subject_ref,+ ),+ ("approver_user_id", None if approval is None else approval.approver_user_id),+ (+ "approval_authority_revision",+ None if approval is None else approval.authority_revision,+ ),+ ("approval_binding_digest", None if approval is None else approval.binding_digest),+ ("noise_budget_id", None if budgets is None else budgets.noise_budget_id),+ ("noise_ledger_id", None if budgets is None else budgets.noise_ledger_id),+ ("noise_units", None if budgets is None else budgets.noise_units),+ (+ "noise_expected_revision",+ None if budgets is None else budgets.noise_expected_revision,+ ),+ (+ "exfiltration_budget_id",+ None if budgets is None else budgets.exfiltration_budget_id,+ ),+ (+ "exfiltration_ledger_id",+ None if budgets is None else budgets.exfiltration_ledger_id,+ ),+ ("exfiltration_units", None if budgets is None else budgets.exfiltration_units),+ (+ "exfiltration_expected_revision",+ None if budgets is None else budgets.exfiltration_expected_revision,+ ),+ (+ "concurrency_budget_id",+ None if budgets is None else budgets.concurrency_budget_id,+ ),+ (+ "concurrency_ledger_id",+ None if budgets is None else budgets.concurrency_ledger_id,+ ),+ (+ "concurrency_expected_revision",+ None if budgets is None else budgets.concurrency_expected_revision,+ ),+ ) + _snapshot_binding_values(request.snapshot)+ return self._receipt_spec(+ operation_id=request.operation_id,+ operation_code=operation_code,+ campaign_id=request.campaign_id,+ primary_target_id=request.logical_execution_id,+ secondary_target_id=request.attempt_id,+ principal_kind="actor",+ principal_subject_ref=request.actor_subject_ref,+ principal_user_id=request.actor_user_id,+ principal_authority_revision=request.snapshot.actor_authority_revision,+ fields=fields,+ )++ @staticmethod+ def _submission_result_binding_digest(request: AdmissionRequest) -> str:+ return canonical_operation_binding_digest(+ "admission.submission-result",+ (+ ("result_code", FixedResult.APPLIED.value),+ ("exact_replay_code", FixedResult.REPLAYED.value),+ ("logical_execution_id", request.logical_execution_id),+ ("logical_revision", 0),+ ("attempt_id", request.attempt_id),+ ("attempt_revision", 0),+ ("state", request.initial_state.value),+ ),+ )++ def _classify_submission_authority(+ self,+ row: Any,+ request: AdmissionRequest,+ spec: _ReceiptSpec,+ ) -> OperationResult:+ matches = (+ self._value(row, "id", 0) == request.logical_execution_id+ and self._value(row, "admission_operation_id", 1) == request.operation_id+ and int(self._value(row, "submission_binding_contract_version", 2)) == 2+ and self._value(row, "submission_request_binding_digest", 3)+ == spec.request_binding_digest+ and self._value(row, "submission_result_code", 4) == FixedResult.APPLIED.value+ and self._value(row, "submission_exact_replay_code", 5) == FixedResult.REPLAYED.value+ and self._value(row, "submission_result_binding_digest", 6)+ == self._submission_result_binding_digest(request)+ )+ return OperationResult(+ FixedResult.REPLAYED if matches else FixedResult.CONFLICT_OPERATION,+ 0 if matches else None,+ )++ async def create_initial_execution(self, request: AdmissionRequest) -> OperationResult:+ """Reject fresh v2 admission; historical rows use ``replay_initial_execution_v2``."""+ del request+ return OperationResult(FixedResult.INVALID_CONTRACT, None)++ async def _create_initial_execution_v2_for_migration_fixture(+ self, request: AdmissionRequest+ ) -> OperationResult:+ """Create a v2 row only for migration/compatibility fixture construction."""+ if not self._valid_admission(request):+ return OperationResult(FixedResult.INVALID_CONTRACT, None)+ spec = self._admission_receipt_spec(request)+ try:+ async with self._transaction() as connection:+ await self._acquire_transaction_key(connection, request.submission_id)+ suffix = " FOR UPDATE" if self._dialect == "postgresql" else ""+ existing = await self._fetchrow(+ connection,+ "SELECT id,admission_operation_id,submission_binding_contract_version,"+ "submission_request_binding_digest,submission_result_code,"+ "submission_exact_replay_code,submission_result_binding_digest "+ "FROM logical_executions WHERE campaign_id=? AND submission_id=?" + suffix,+ (request.campaign_id, request.submission_id),+ )+ if existing is not None:+ return self._classify_submission_authority(existing, request, spec)+ if request.budgets is not None:+ budget_spec = self._budget_reservation_receipt_spec(request.budgets)+ await self._acquire_transaction_key(connection, request.budgets.operation_id)+ if (+ await self._classify_receipt(+ connection,+ budget_spec,+ current_revision=max(+ request.budgets.noise_expected_revision,+ request.budgets.exfiltration_expected_revision,+ request.budgets.concurrency_expected_revision,+ ),+ )+ is not None+ ):+ return OperationResult(FixedResult.CONFLICT_OPERATION, None)+ gateway = await self._fetchrow(+ connection,+ "SELECT mode FROM execution_gateway_state WHERE singleton_id=1" + suffix,+ (),+ )+ if (+ gateway is None+ or self._value(gateway, "mode", 0) != request.snapshot.gateway_mode_snapshot+ ):+ raise _AbortOperationError(OperationResult(FixedResult.CONFLICT_STATE, None))+ user = await self._fetchrow(+ connection,+ "SELECT id,is_active,role FROM users WHERE id=?" + suffix,+ (request.actor_user_id,),+ )+ campaign = await self._fetchrow(+ connection,+ "SELECT id,status FROM campaigns WHERE id=?" + suffix,+ (request.campaign_id,),+ )+ actor_authority = await self._fetchrow(+ connection,+ "SELECT revision FROM execution_actor_authority_revisions WHERE user_id=?"+ + suffix,+ (request.actor_user_id,),+ )+ campaign_authority = await self._fetchrow(+ connection,+ "SELECT revision FROM campaign_execution_authority_revisions WHERE campaign_id=?"+ + suffix,+ (request.campaign_id,),+ )+ if (+ user is None+ or campaign is None+ or actor_authority is None+ or campaign_authority is None+ or self._value(user, "id", 0) != request.actor_subject_ref+ or not bool(self._value(user, "is_active", 1))+ or self._value(user, "role", 2) != request.snapshot.actor_role+ or self._value(campaign, "status", 1) not in {"created", "running"}+ or int(self._value(actor_authority, "revision", 0))+ != request.snapshot.actor_authority_revision+ or int(self._value(campaign_authority, "revision", 0))+ != request.snapshot.campaign_authority_revision+ ):+ raise _AbortOperationError(OperationResult(FixedResult.AUTHORITY_STALE, None))+ terminal = request.initial_state in {+ AttemptState.REJECTED,+ AttemptState.BLOCKED,+ }+ now = self._now_sql+ logical_columns = (+ "id,submission_id,campaign_id,actor_subject_ref,actor_user_id,"+ "module_id,ingress_code,admission_operation_id,"+ "submission_binding_contract_version,submission_request_binding_digest,"+ "submission_result_code,submission_exact_replay_code,"+ "submission_result_binding_digest,highest_attempt_ordinal,revision,created_at"+ )+ logical_values: tuple[Any, ...] = (+ request.logical_execution_id,+ request.submission_id,+ request.campaign_id,+ request.actor_subject_ref,+ request.actor_user_id,+ request.module_id,+ request.ingress_code,+ request.operation_id,+ 2,+ spec.request_binding_digest,+ FixedResult.APPLIED.value,+ FixedResult.REPLAYED.value,+ self._submission_result_binding_digest(request),+ )+ async with self._savepoint(connection):+ if terminal:+ logical_columns += (+ ",closure_operation_id,closure_authority_subject_ref,"+ "closure_authority_user_id,closure_authority_revision,"+ "closing_attempt_id,closed_at"+ )+ logical_values += (+ request.operation_id,+ request.actor_subject_ref,+ request.actor_user_id,+ request.snapshot.actor_authority_revision,+ request.attempt_id,+ )+ logical_sql = (+ "INSERT INTO logical_executions(" + logical_columns + ") "+ "SELECT ?,?,?,?,?,?,?,?,?,?,?,?,?,0,0,db_now,?,?,?,?,?,db_now FROM "+ "(SELECT " + now + " AS db_now) AS clock WHERE 1=1 "+ "ON CONFLICT(id) DO NOTHING RETURNING id,revision"+ )+ else:+ logical_sql = (+ "INSERT INTO logical_executions(" + logical_columns + ") "+ "SELECT ?,?,?,?,?,?,?,?,?,?,?,?,?,0,0,db_now FROM (SELECT "+ + now+ + " AS db_now) AS clock WHERE 1=1 ON CONFLICT(id) DO NOTHING RETURNING id,revision"+ )+ inserted_logical = await self.insert_or_validate_binding(+ connection,+ logical_sql,+ logical_values,+ identity=request.logical_execution_id,+ revision=0,+ )+ if inserted_logical is None:+ raise _AbortOperationError(+ OperationResult(FixedResult.CONFLICT_OPERATION, None)+ )+ await self._insert_attempt(connection, request, ordinal=0, parent=None)+ if terminal:+ await self._insert_initial_terminal_outbox(connection, request)+ else:+ if request.approval is not None:+ await self._insert_approval(connection, request)+ budget_result = await self._reserve_budgets_locked(+ connection, request.budgets+ )+ if budget_result.result is not FixedResult.APPLIED:+ raise _AbortOperationError(budget_result)+ return OperationResult(FixedResult.APPLIED, 0)+ except _AbortOperationError as aborted:+ return aborted.result++ async def replay_initial_execution_v2(+ self,+ principal: TrustedPrincipal,+ request: AdmissionRequest,+ ) -> OperationResult:+ """Replay one existing historical v2 submission without live-authority reads."""+ if (+ not self._valid_trusted_principal(principal)+ or not self._valid_admission(request)+ or request.actor_subject_ref != principal.subject_ref+ or request.actor_user_id != principal.user_id+ ):+ return OperationResult(FixedResult.INVALID_CONTRACT, None)+ spec = self._admission_receipt_spec(request)+ suffix = " FOR UPDATE" if self._dialect == "postgresql" else ""+ async with self._transaction() as connection:+ await self._acquire_transaction_key(connection, request.submission_id)+ row = await self._fetchrow(+ connection,+ "SELECT id,admission_operation_id,submission_binding_contract_version,"+ "submission_request_binding_digest,submission_result_code,"+ "submission_exact_replay_code,submission_result_binding_digest,"+ "admission_authority_contract_version,actor_subject_ref,actor_user_id "+ "FROM logical_executions WHERE campaign_id=? AND submission_id=?" + suffix,+ (request.campaign_id, request.submission_id),+ )+ if row is None:+ return OperationResult(FixedResult.INVALID_CONTRACT, None)+ if (+ int(self._value(row, "admission_authority_contract_version", 7))+ != ADMISSION_AUTHORITY_CONTRACT_V2+ or self._value(row, "actor_subject_ref", 8) != principal.subject_ref+ or self._value(row, "actor_user_id", 9) != principal.user_id+ ):+ return OperationResult(FixedResult.CONFLICT_OPERATION, None)+ return self._classify_submission_authority(row, request, spec)++ @staticmethod+ def _v3_initial_state(snapshot: AttemptPolicySnapshot) -> AttemptState:+ if snapshot.policy_verdict == "live_candidate":+ return AttemptState.ACCEPTED+ if snapshot.policy_verdict == "rejected":+ return AttemptState.REJECTED+ return AttemptState.BLOCKED++ async def _insert_v3_observations(+ self,+ connection: Any,+ request: AdmissionRequest,+ resolved: _ResolvedAdmissionV3,+ ) -> None:+ for ordinal, (destination_ref_digest, authority_revision) in enumerate(+ resolved.destination_observations+ ):+ row = await self.insert_or_validate_binding(+ connection,+ "INSERT INTO execution_attempt_destination_observations("+ "attempt_id,campaign_id,ordinal,destination_ref_digest,authority_revision,"+ "normalization_version) VALUES(?,?,?,?,?,?) ON CONFLICT(attempt_id,ordinal) "+ "DO NOTHING RETURNING attempt_id,ordinal",+ (+ request.attempt_id,+ request.campaign_id,+ ordinal,+ destination_ref_digest,+ authority_revision,+ DESTINATION_NORMALIZATION_VERSION,+ ),+ identity=request.attempt_id,+ revision=ordinal,+ identity_column="attempt_id",+ revision_column="ordinal",+ )+ if row is None:+ raise _AbortOperationError(OperationResult(FixedResult.CONFLICT_OPERATION, None))+ for ordinal, (credential_id, authority_revision, binding_digest) in enumerate(+ resolved.credential_observations+ ):+ row = await self.insert_or_validate_binding(+ connection,+ "INSERT INTO execution_attempt_credential_observations("+ "attempt_id,campaign_id,ordinal,credential_id,authority_revision,binding_digest) "+ "VALUES(?,?,?,?,?,?) ON CONFLICT(attempt_id,ordinal) DO NOTHING "+ "RETURNING attempt_id,ordinal",+ (+ request.attempt_id,+ request.campaign_id,+ ordinal,+ credential_id,+ authority_revision,+ binding_digest,+ ),+ identity=request.attempt_id,+ revision=ordinal,+ identity_column="attempt_id",+ revision_column="ordinal",+ )+ if row is None:+ raise _AbortOperationError(OperationResult(FixedResult.CONFLICT_OPERATION, None))++ async def _insert_attempt_v3(+ self,+ connection: Any,+ request: AdmissionRequest,+ resolved: _ResolvedAdmissionV3,+ prepared: _PreparedAdmissionV3,+ *,+ ordinal: int,+ parent: str | None,+ ) -> None:+ await self._insert_attempt(connection, request, ordinal=ordinal, parent=parent)+ await self.update_exact_set(+ connection,+ "UPDATE execution_attempts SET authority_contract_version=3,"+ "trusted_principal_subject_ref=?,trusted_principal_user_id=?,"+ "immutable_intent_digest=?,immutable_work_digest=?,gateway_revision=?,"+ "gateway_activation_revision=?,"+ "campaign_actor_grant_revision=?,destination_authority_binding_digest=?,"+ "credential_authority_binding_digest=?,approval_authority_binding_digest=? "+ "WHERE id=? AND authority_contract_version=2 RETURNING id,authority_contract_version",+ (+ resolved.principal.subject_ref,+ resolved.principal.user_id,+ prepared.immutable_intent_digest,+ prepared.immutable_work_digest,+ resolved.gateway_revision,+ resolved.gateway_activation_revision,+ resolved.grant_revision,+ resolved.destination_binding_digest,+ resolved.credential_binding_digest,+ resolved.approval_binding_digest,+ request.attempt_id,+ ),+ expected=(("id", request.attempt_id), ("authority_contract_version", 3)),+ zero_classifier=lambda: self._classify_zero_row(+ connection,+ table="execution_attempts",+ identity_column="id",+ identity=request.attempt_id,+ revision_column="revision",+ matched_result=FixedResult.CONFLICT_OPERATION,+ ),+ )+ await self._insert_v3_observations(connection, request, resolved)++ async def create_initial_execution_v3(+ self,+ principal: TrustedPrincipal,+ intent: AdmissionIntentV3,+ ) -> OperationResult:+ principal_shape_valid = (+ type(principal) is TrustedPrincipal+ and valid_uuid(principal.subject_ref)+ and valid_uuid(principal.user_id)+ and principal.subject_ref == principal.user_id+ )+ if not principal_shape_valid:+ return OperationResult(FixedResult.INVALID_CONTRACT, None)+ if (+ not self._valid_initial_v3_intent_shape(intent)+ or intent.outbox_id is not None+ or intent.publication_key is not None+ ):+ return OperationResult(FixedResult.INVALID_CONTRACT, None)+ replay_digest = self._initial_v3_replay_digest(intent)+ if replay_digest is None:+ return OperationResult(FixedResult.INVALID_CONTRACT, None)+ suffix = " FOR UPDATE" if self._dialect == "postgresql" else ""+ try:+ async with self._transaction() as connection:+ await self._acquire_transaction_key(connection, intent.submission_id)+ existing = await self._fetchrow(+ connection,+ "SELECT id,admission_operation_id,submission_binding_contract_version,"+ "submission_request_binding_digest,submission_result_code,"+ "submission_exact_replay_code,submission_result_binding_digest,"+ "admission_authority_contract_version,canonical_principal_user_id,"+ "immutable_intent_digest,actor_subject_ref,actor_user_id "+ "FROM logical_executions "+ "WHERE campaign_id=? AND submission_id=?" + suffix,+ (intent.campaign_id, intent.submission_id),+ )+ if existing is not None:+ matches = (+ self._value(existing, "id", 0) == intent.logical_execution_id+ and self._value(existing, "admission_operation_id", 1)+ == intent.operation_id+ and int(+ self._value(+ existing,+ "submission_binding_contract_version",+ 2,+ )+ )+ == 2+ and self._value(existing, "submission_result_code", 4)+ == FixedResult.APPLIED.value+ and self._value(existing, "submission_exact_replay_code", 5)+ == FixedResult.REPLAYED.value+ and int(+ self._value(+ existing,+ "admission_authority_contract_version",+ 7,+ )+ )+ == ADMISSION_AUTHORITY_CONTRACT_V3+ and self._value(existing, "canonical_principal_user_id", 8)+ == principal.user_id+ and self._value(existing, "immutable_intent_digest", 9) == replay_digest+ and self._value(existing, "actor_subject_ref", 10) == principal.subject_ref+ and self._value(existing, "actor_user_id", 11) == principal.user_id+ )+ return OperationResult(+ FixedResult.REPLAYED if matches else FixedResult.CONFLICT_OPERATION,+ 0 if matches else None,+ )+ prepared = self._prepared_admission(intent)+ if prepared is None:+ return OperationResult(FixedResult.INVALID_CONTRACT, None)+ resolved = await self._resolve_admission_v3(+ connection, principal, intent, prepared, suffix=suffix+ )+ state = self._v3_initial_state(resolved.snapshot)+ terminal = state in {AttemptState.REJECTED, AttemptState.BLOCKED}+ outbox_id = (+ self._derived_v3_uuid(intent.operation_id, "terminal-outbox")+ if terminal+ else None+ )+ publication_key = (+ self._derived_v3_uuid(intent.operation_id, "terminal-publication")+ if terminal+ else None+ )+ request = AdmissionRequest(+ intent.logical_execution_id,+ intent.submission_id,+ intent.attempt_id,+ outbox_id,+ publication_key,+ intent.campaign_id,+ resolved.principal.subject_ref,+ resolved.principal.user_id,+ intent.module_id,+ intent.ingress_code,+ state,+ intent.operation_id,+ resolved.snapshot,+ resolved.approval,+ resolved.budgets,+ )+ if not self._valid_admission(request):+ return OperationResult(FixedResult.INVALID_CONTRACT, None)+ spec = self._admission_receipt_spec(request)+ if request.budgets is not None:+ await self._acquire_transaction_key(connection, request.budgets.operation_id)+ logical_columns = (+ "id,submission_id,campaign_id,actor_subject_ref,actor_user_id,module_id,"+ "ingress_code,admission_operation_id,submission_binding_contract_version,"+ "submission_request_binding_digest,submission_result_code,"+ "submission_exact_replay_code,submission_result_binding_digest,"+ "highest_attempt_ordinal,revision,admission_authority_contract_version,"+ "canonical_principal_user_id,immutable_intent_digest,"+ "immutable_work_digest"+ )+ values: tuple[Any, ...] = (+ intent.logical_execution_id,+ intent.submission_id,+ intent.campaign_id,+ resolved.principal.subject_ref,+ resolved.principal.user_id,+ intent.module_id,+ intent.ingress_code,+ intent.operation_id,+ 2,+ spec.request_binding_digest,+ FixedResult.APPLIED.value,+ FixedResult.REPLAYED.value,+ self._submission_result_binding_digest(request),+ 0,+ 0,+ ADMISSION_AUTHORITY_CONTRACT_V3,+ resolved.principal.user_id,+ prepared.immutable_intent_digest,+ prepared.immutable_work_digest,+ )+ if terminal:+ logical_columns += (+ ",closure_operation_id,closure_authority_subject_ref,"+ "closure_authority_user_id,closure_authority_revision,"+ "closing_attempt_id,created_at,closed_at"+ )+ values += (+ intent.operation_id,+ resolved.principal.subject_ref,+ resolved.principal.user_id,+ resolved.principal.authority_revision,+ intent.attempt_id,+ )+ clock_values = ",db_now,db_now"+ else:+ logical_columns += ",created_at"+ clock_values = ",db_now"+ placeholders = ",".join("?" for _ in values)+ sql = (+ "INSERT INTO logical_executions("+ + logical_columns+ + ") SELECT "+ + placeholders+ + clock_values+ + " FROM (SELECT "+ + self._now_sql+ + " AS db_now) AS clock WHERE 1=1 ON CONFLICT(id) DO NOTHING "+ "RETURNING id,revision"+ )+ async with self._savepoint(connection):+ inserted = await self.insert_or_validate_binding(+ connection,+ sql,+ values,+ identity=intent.logical_execution_id,+ revision=0,+ )+ if inserted is None:+ raise _AbortOperationError(+ OperationResult(FixedResult.CONFLICT_OPERATION, None)+ )+ await self._insert_attempt_v3(+ connection,+ request,+ resolved,+ prepared,+ ordinal=0,+ parent=None,+ )+ if terminal:+ await self._insert_initial_terminal_outbox(connection, request)+ else:+ if resolved.approval is not None:+ await self._consume_approval_authority_v3(connection, request, resolved)+ await self._insert_approval(connection, request)+ budget_result = await self._reserve_budgets_locked(+ connection, resolved.budgets+ )+ if budget_result.result is not FixedResult.APPLIED:+ raise _AbortOperationError(budget_result)+ return OperationResult(FixedResult.APPLIED, 0)+ except _AbortOperationError as aborted:+ return aborted.result++ async def _consume_approval_authority_v3(+ self,+ connection: Any,+ request: AdmissionRequest,+ resolved: _ResolvedAdmissionV3,+ ) -> None:+ approval = request.approval+ if approval is None:+ return+ suffix = " FOR UPDATE" if self._dialect == "postgresql" else ""+ row = await self._fetchrow(+ connection,+ "SELECT id,approval_ref,approver_subject_ref,approver_user_id,revision,"+ "binding_digest,authority_state,campaign_id,submission_id,attempt_id,"+ "actor_subject_ref,actor_user_id,module_id,granted_capability_mask,"+ "descriptor_semantic_digest FROM execution_approval_authorities WHERE id=?" + suffix,+ (approval.approval_id,),+ )+ if (+ row is None+ or self._value(row, "binding_digest", 5) != approval.binding_digest+ or self._value(row, "authority_state", 6) != "active"+ ):+ raise _AbortOperationError(OperationResult(FixedResult.AUTHORITY_STALE, None))+ consumed_binding = self._approval_authority_binding(+ row,+ authority_state="consumed",+ )+ updated = await self.cas_update_one(+ connection,+ "UPDATE execution_approval_authorities SET authority_state='consumed',"+ "revision=revision+1,binding_digest=?,latest_operation_id=?,"+ "latest_operation_base_revision=?,"+ "latest_operation_code='consume',updated_at="+ + self._now_sql+ + ",consumed_at="+ + self._now_sql+ + " WHERE id=? AND revision=? AND authority_state='active' "+ "RETURNING id,revision",+ (+ consumed_binding,+ request.operation_id,+ approval.authority_revision,+ approval.approval_id,+ approval.authority_revision,+ ),+ identity=approval.approval_id,+ post_revision=approval.authority_revision + 1,+ revision_column="revision",+ zero_classifier=lambda: self._classify_zero_row(+ connection,+ table="execution_approval_authorities",+ identity_column="id",+ identity=approval.approval_id,+ revision_column="revision",+ checks=(+ (+ "revision",+ (approval.authority_revision,),+ FixedResult.CONFLICT_REVISION,+ ),+ ("authority_state", ("active",), FixedResult.CONFLICT_STATE),+ ),+ ),+ )+ if updated is None:+ raise _AbortOperationError(OperationResult(FixedResult.AUTHORITY_STALE, None))++ async def _insert_attempt(+ self,+ connection: Any,+ request: AdmissionRequest,+ *,+ ordinal: int,+ parent: str | None,+ ) -> None:+ snapshot_columns, snapshot_values = self._snapshot_columns_values(request.snapshot)+ state = request.initial_state+ terminal = state in {AttemptState.REJECTED, AttemptState.BLOCKED}+ columns = (+ "id",+ "logical_execution_id",+ "campaign_id",+ "ordinal",+ "parent_attempt_id",+ "state",+ "closes_logical",+ "actor_subject_ref",+ "actor_user_id",+ "request_contract_version",+ "descriptor_contract_version",+ "capability_mask_version",+ "descriptor_blocker_mask_version",+ "policy_contract_version",+ "policy_reason_mask_version",+ ) + snapshot_columns+ values: tuple[Any, ...] = (+ request.attempt_id,+ request.logical_execution_id,+ request.campaign_id,+ ordinal,+ parent,+ state.value,+ terminal,+ request.actor_subject_ref,+ request.actor_user_id,+ REQUEST_CONTRACT_VERSION,+ DESCRIPTOR_CONTRACT_VERSION,+ MASK_VERSION,+ MASK_VERSION,+ POLICY_CONTRACT_VERSION,+ None if request.snapshot.policy_reason_mask is None else MASK_VERSION,+ ) + snapshot_values+ now = self._now_sql+ extra_columns: tuple[str, ...]+ extra_values: tuple[Any, ...]+ if terminal:+ extra_columns = (+ "outcome_code",+ "error_action_code",+ "settlement_state",+ "settlement_proof_code",+ "termination_confirmed",+ "lease_generation",+ "terminal_operation_id",+ "created_at",+ "finished_at",+ "settled_at",+ )+ extra_values = (+ "policy_rejected" if state is AttemptState.REJECTED else "policy_blocked",+ "abort",+ "not_applicable",+ "no_dispatch",+ False,+ 0,+ request.operation_id,+ )+ sql = (+ "INSERT INTO execution_attempts("+ + ",".join(columns + extra_columns)+ + ") SELECT "+ + ",".join("?" for _ in values + extra_values)+ + ",db_now,db_now,db_now FROM (SELECT "+ + now+ + " AS db_now) AS clock WHERE 1=1 ON CONFLICT(id) DO NOTHING RETURNING id,revision"+ )+ else:+ extra_columns = (+ "outcome_code",+ "error_action_code",+ "settlement_state",+ "settlement_proof_code",+ "termination_confirmed",+ "lease_generation",+ "created_at",+ "accepted_at",+ )+ extra_values = (None, "none", "reserved", "none", False, 0)+ sql = (+ "INSERT INTO execution_attempts("+ + ",".join(columns + extra_columns)+ + ") SELECT "+ + ",".join("?" for _ in values + extra_values)+ + ",db_now,db_now FROM (SELECT "+ + now+ + " AS db_now) AS clock WHERE 1=1 ON CONFLICT(id) DO NOTHING RETURNING id,revision"+ )+ inserted = await self.insert_or_validate_binding(+ connection,+ sql,+ values + extra_values,+ identity=request.attempt_id,+ revision=0,+ )+ if inserted is None:+ raise _AbortOperationError(OperationResult(FixedResult.CONFLICT_OPERATION, None))++ async def create_retry_attempt(self, request: RetryRequest) -> OperationResult:+ """Reject fresh v2 retry; historical receipts use ``replay_retry_attempt_v2``."""+ del request+ return OperationResult(FixedResult.INVALID_CONTRACT, None)++ async def _create_retry_attempt_v2_for_migration_fixture(+ self, request: RetryRequest+ ) -> OperationResult:+ """Create a v2 retry only for migration/compatibility fixture construction."""+ if (+ type(request) is not RetryRequest+ or not valid_uuid(request.logical_execution_id)+ or not valid_uuid(request.parent_attempt_id)+ or type(request.expected_parent_revision) is not int+ or not 0 <= request.expected_parent_revision < MAX_I53+ or not self._valid_admission(request.child)+ or request.child.logical_execution_id != request.logical_execution_id+ ):+ return OperationResult(FixedResult.INVALID_CONTRACT, None)+ child = request.child+ suffix = " FOR UPDATE" if self._dialect == "postgresql" else ""+ approval = child.approval+ budgets = child.budgets+ fields: tuple[tuple[str, str | int | bool | None], ...] = (+ ("logical_execution_id", request.logical_execution_id),+ ("parent_attempt_id", request.parent_attempt_id),+ ("child_attempt_id", child.attempt_id),+ ("child_submission_id", child.submission_id),+ ("child_operation_id", child.operation_id),+ ("child_outbox_id", child.outbox_id),+ ("child_publication_key", child.publication_key),+ ("child_campaign_id", child.campaign_id),+ ("actor_subject_ref", child.actor_subject_ref),+ ("actor_user_id", child.actor_user_id),+ ("module_id", child.module_id),+ ("ingress_code", child.ingress_code),+ ("initial_state", child.initial_state.value),+ ) + _snapshot_binding_values(child.snapshot)+ fields += (+ ("approval_id", None if approval is None else approval.approval_id),+ ("approval_ref", None if approval is None else approval.approval_ref),+ (+ "approval_authority_revision",+ None if approval is None else approval.authority_revision,+ ),+ (+ "approval_binding_digest",+ None if approval is None else approval.binding_digest,+ ),+ ("budget_operation_id", None if budgets is None else budgets.operation_id),+ ("noise_budget_id", None if budgets is None else budgets.noise_budget_id),+ ("noise_ledger_id", None if budgets is None else budgets.noise_ledger_id),+ ("noise_units", None if budgets is None else budgets.noise_units),+ (+ "noise_expected_revision",+ None if budgets is None else budgets.noise_expected_revision,+ ),+ (+ "exfiltration_budget_id",+ None if budgets is None else budgets.exfiltration_budget_id,+ ),+ (+ "exfiltration_ledger_id",+ None if budgets is None else budgets.exfiltration_ledger_id,+ ),+ ("exfiltration_units", None if budgets is None else budgets.exfiltration_units),+ (+ "exfiltration_expected_revision",+ None if budgets is None else budgets.exfiltration_expected_revision,+ ),+ (+ "concurrency_budget_id",+ None if budgets is None else budgets.concurrency_budget_id,+ ),+ (+ "concurrency_ledger_id",+ None if budgets is None else budgets.concurrency_ledger_id,+ ),+ (+ "concurrency_expected_revision",+ None if budgets is None else budgets.concurrency_expected_revision,+ ),+ )+ spec = self._receipt_spec(+ operation_id=child.operation_id,+ operation_code="retry",+ campaign_id=child.campaign_id,+ primary_target_id=request.parent_attempt_id,+ secondary_target_id=child.attempt_id,+ principal_kind="actor",+ principal_subject_ref=child.actor_subject_ref,+ principal_user_id=child.actor_user_id,+ principal_authority_revision=child.snapshot.actor_authority_revision,+ expected_revision=request.expected_parent_revision,+ fields=fields,+ )+ try:+ async with self._transaction() as connection:+ await self._acquire_transaction_key(connection, child.operation_id)+ replay = await self._classify_receipt(+ connection,+ spec,+ current_revision=request.expected_parent_revision,+ )+ if replay is not None:+ return replay+ if budgets is not None:+ budget_spec = self._budget_reservation_receipt_spec(budgets)+ await self._acquire_transaction_key(connection, budgets.operation_id)+ if (+ await self._classify_receipt(+ connection,+ budget_spec,+ current_revision=max(+ budgets.noise_expected_revision,+ budgets.exfiltration_expected_revision,+ budgets.concurrency_expected_revision,+ ),+ )+ is not None+ ):+ return OperationResult(FixedResult.CONFLICT_OPERATION, None)+ await self._acquire_logical_attempt_transaction_keys(+ connection,+ request.logical_execution_id,+ request.parent_attempt_id,+ )+ gateway = await self._fetchrow(+ connection,+ "SELECT mode FROM execution_gateway_state WHERE singleton_id=1" + suffix,+ (),+ )+ for sql, params in (+ ("SELECT id FROM users WHERE id=?", (child.actor_user_id,)),+ ("SELECT id FROM campaigns WHERE id=?", (child.campaign_id,)),+ (+ "SELECT user_id FROM execution_actor_authority_revisions WHERE user_id=?",+ (child.actor_user_id,),+ ),+ (+ "SELECT campaign_id FROM campaign_execution_authority_revisions "+ "WHERE campaign_id=?",+ (child.campaign_id,),+ ),+ ):+ await self._fetchrow(connection, sql + suffix, params)+ logical = await self._fetchrow(+ connection,+ "SELECT campaign_id,actor_subject_ref,highest_attempt_ordinal,"+ "closure_operation_id,revision FROM logical_executions WHERE id=?" + suffix,+ (request.logical_execution_id,),+ )+ if logical is None:+ return OperationResult(FixedResult.RETRY_AUTHORITY_UNRESOLVED, None)+ parent_row = await self._fetchrow(+ connection,+ "SELECT campaign_id,ordinal,revision,state,closes_logical,"+ "retry_disposition FROM execution_attempts "+ "WHERE logical_execution_id=? AND id=?" + suffix,+ (request.logical_execution_id, request.parent_attempt_id),+ )+ if parent_row is None:+ return OperationResult(FixedResult.CONFLICT_STATE, None)+ parent_revision = int(self._value(parent_row, "revision", 2))+ existing_child = await self._fetchrow(+ connection,+ "SELECT logical_execution_id,parent_attempt_id,revision "+ "FROM execution_attempts WHERE id=?" + suffix,+ (child.attempt_id,),+ )+ if existing_child is not None:+ return OperationResult(FixedResult.CONFLICT_OPERATION, parent_revision)+ if self._value(logical, "closure_operation_id", 3) is not None:+ return OperationResult(FixedResult.ALREADY_CLOSED, parent_revision)+ if parent_revision != request.expected_parent_revision:+ return OperationResult(FixedResult.CONFLICT_REVISION, parent_revision)+ sibling = await self._fetchrow(+ connection,+ "SELECT id FROM execution_attempts WHERE logical_execution_id=? "+ "AND parent_attempt_id=?",+ (request.logical_execution_id, request.parent_attempt_id),+ )+ parent_ordinal = int(self._value(parent_row, "ordinal", 1))+ if (+ self._value(parent_row, "campaign_id", 0) != child.campaign_id+ or self._value(logical, "campaign_id", 0) != child.campaign_id+ or self._value(logical, "actor_subject_ref", 1) != child.actor_subject_ref+ or parent_ordinal != int(self._value(logical, "highest_attempt_ordinal", 2))+ or self._value(parent_row, "state", 3) not in {"failed", "timed_out"}+ or bool(self._value(parent_row, "closes_logical", 4))+ or self._value(parent_row, "retry_disposition", 5) != "eligible"+ or sibling is not None+ ):+ return OperationResult(FixedResult.CONFLICT_STATE, parent_revision)+ output = await self._fetchrow(+ connection,+ "SELECT id FROM execution_output_links WHERE attempt_id=?",+ (request.parent_attempt_id,),+ )+ if output is not None:+ return OperationResult(FixedResult.CONFLICT_STATE, parent_revision)+ if (+ gateway is None+ or self._value(gateway, "mode", 0) != child.snapshot.gateway_mode_snapshot+ ):+ return OperationResult(FixedResult.CONFLICT_STATE, parent_revision)+ authority = await self._fetchrow(+ connection,+ "SELECT u.id AS actor_id,u.is_active,u.role,"+ "a.revision AS actor_revision,c.id AS campaign_id,c.status,"+ "ca.revision AS campaign_revision "+ "FROM users u JOIN execution_actor_authority_revisions a ON a.user_id=u.id "+ "JOIN campaigns c ON c.id=? JOIN campaign_execution_authority_revisions ca ON ca.campaign_id=c.id "+ "WHERE u.id=?" + suffix,+ (child.campaign_id, child.actor_user_id),+ )+ if authority is None or not (+ self._value(authority, "actor_id", 0) == child.actor_subject_ref+ and bool(self._value(authority, "is_active", 1))+ and self._value(authority, "role", 2) == child.snapshot.actor_role+ and int(self._value(authority, "actor_revision", 3))+ == child.snapshot.actor_authority_revision+ and self._value(authority, "campaign_id", 4) == child.campaign_id+ and self._value(authority, "status", 5) in {"created", "running"}+ and int(self._value(authority, "campaign_revision", 6))+ == child.snapshot.campaign_authority_revision+ ):+ return OperationResult(FixedResult.RETRY_AUTHORITY_UNRESOLVED, parent_revision)+ child_ordinal = parent_ordinal + 1+ logical_revision = int(self._value(logical, "revision", 4))+ terminal = child.initial_state in {AttemptState.REJECTED, AttemptState.BLOCKED}+ async with self._savepoint(connection):+ parent_update = await self.cas_update_one(+ connection,+ "UPDATE execution_attempts SET retry_disposition='child_bound',"+ "retry_child_bound_at="+ + self._now_sql+ + ",revision=revision+1 WHERE id=? AND logical_execution_id=? "+ "AND revision=? AND retry_disposition='eligible' AND closes_logical="+ + ("FALSE" if self._dialect == "postgresql" else "0")+ + " RETURNING id,revision,retry_disposition",+ (+ request.parent_attempt_id,+ request.logical_execution_id,+ request.expected_parent_revision,+ ),+ identity=request.parent_attempt_id,+ post_revision=request.expected_parent_revision + 1,+ zero_classifier=lambda: self._classify_zero_row(+ connection,+ table="execution_attempts",+ identity_column="id",+ identity=request.parent_attempt_id,+ revision_column="revision",+ checks=(+ (+ "revision",+ (request.expected_parent_revision,),+ FixedResult.CONFLICT_REVISION,+ ),+ (+ "logical_execution_id",+ (request.logical_execution_id,),+ FixedResult.CONFLICT_STATE,+ ),+ (+ "retry_disposition",+ ("eligible",),+ FixedResult.CONFLICT_STATE,+ ),+ ("closes_logical", (False,), FixedResult.CONFLICT_STATE),+ ),+ missing_result=FixedResult.CONFLICT_STATE,+ ),+ )+ if parent_update is None:+ raise _AbortOperationError(+ OperationResult(FixedResult.CONFLICT_STATE, parent_revision)+ )+ await self._insert_attempt(+ connection,+ child,+ ordinal=child_ordinal,+ parent=request.parent_attempt_id,+ )+ logical_sql = (+ "UPDATE logical_executions SET highest_attempt_ordinal=?,"+ + (+ "closure_operation_id=?,closure_authority_subject_ref=?,"+ "closure_authority_user_id=?,closure_authority_revision=?,"+ "closing_attempt_id=?,closed_at=" + self._now_sql + ","+ if terminal+ else ""+ )+ + "revision=revision+1 WHERE id=? AND campaign_id=? AND revision=? "+ "AND closure_operation_id IS NULL RETURNING id,revision"+ )+ logical_params: tuple[Any, ...] = (child_ordinal,)+ if terminal:+ logical_params += (+ child.operation_id,+ child.actor_subject_ref,+ child.actor_user_id,+ child.snapshot.actor_authority_revision,+ child.attempt_id,+ )+ logical_params += (+ request.logical_execution_id,+ child.campaign_id,+ logical_revision,+ )+ logical_update = await self.cas_update_one(+ connection,+ logical_sql,+ logical_params,+ identity=request.logical_execution_id,+ post_revision=logical_revision + 1,+ zero_classifier=lambda: self._classify_zero_row(+ connection,+ table="logical_executions",+ identity_column="id",+ identity=request.logical_execution_id,+ revision_column="revision",+ checks=(+ (+ "campaign_id",+ (child.campaign_id,),+ FixedResult.CONFLICT_STATE,+ ),+ (+ "closure_operation_id",+ (None,),+ FixedResult.ALREADY_CLOSED,+ ),+ (+ "revision",+ (logical_revision,),+ FixedResult.CONFLICT_REVISION,+ ),+ ),+ missing_result=FixedResult.RETRY_AUTHORITY_UNRESOLVED,+ ),+ )+ if logical_update is None:+ raise _AbortOperationError(+ OperationResult(FixedResult.CONFLICT_STATE, parent_revision)+ )+ if terminal:+ await self._insert_initial_terminal_outbox(connection, child)+ else:+ if child.approval is not None:+ await self._insert_approval(connection, child)+ budget_result = await self._reserve_budgets_locked(+ connection, child.budgets+ )+ if budget_result.result is not FixedResult.APPLIED:+ raise _AbortOperationError(budget_result)+ await self._insert_receipt(+ connection,+ spec,+ result=FixedResult.APPLIED,+ exact_replay_code=FixedResult.REPLAYED_BOUND_CHILD,+ result_identity=child.attempt_id,+ result_revision=0,+ secondary_result_identity=request.parent_attempt_id,+ secondary_result_revision=request.expected_parent_revision + 1,+ result_fields=(+ ("child_attempt_id", child.attempt_id),+ ("child_revision", 0),+ (+ "parent_revision",+ request.expected_parent_revision + 1,+ ),+ ("logical_revision", logical_revision + 1),+ ("child_ordinal", child_ordinal),+ ),+ )+ return OperationResult(FixedResult.APPLIED, 0)+ except _AbortOperationError as aborted:+ return aborted.result++ async def create_retry_attempt_v3(+ self,+ principal: TrustedPrincipal,+ intent: RetryIntentV3,+ ) -> OperationResult:+ if (+ not self._valid_trusted_principal(principal)+ or type(intent) is not RetryIntentV3+ or not valid_uuid(intent.logical_execution_id)+ or not valid_uuid(intent.parent_attempt_id)+ or not valid_uuid(intent.child_attempt_id)+ or not valid_uuid(intent.operation_id)+ or not self._valid_expected_revision(intent.expected_parent_revision)+ or (intent.outbox_id is not None and not valid_uuid(intent.outbox_id))+ or (intent.publication_key is not None and not valid_uuid(intent.publication_key))+ or (intent.outbox_id is None) != (intent.publication_key is None)+ or intent.outbox_id is not None+ or intent.publication_key is not None+ or intent.evaluation_mode not in {"preview", "live"}+ or type(intent.credential_ids) is not tuple+ or len(intent.credential_ids) > 256+ or len(set(intent.credential_ids)) != len(intent.credential_ids)+ or not all(valid_uuid(value) for value in intent.credential_ids)+ or (intent.approval_ref is not None and not valid_uuid(intent.approval_ref))+ or type(intent.noise_units) is not int+ or not 0 <= intent.noise_units <= MAX_I53+ or type(intent.exfiltration_units) is not int+ or not 0 <= intent.exfiltration_units <= MAX_I53+ ):+ return OperationResult(FixedResult.INVALID_CONTRACT, None)+ suffix = " FOR UPDATE" if self._dialect == "postgresql" else ""+ try:+ async with self._transaction() as connection:+ await self._acquire_transaction_key(connection, intent.operation_id)+ prior = await self._receipt_row(connection, intent.operation_id)+ if prior is not None:+ if (+ self._value(prior, "principal_kind", 4) != "actor"+ or self._value(prior, "principal_subject_ref", 5) != principal.subject_ref+ or self._value(prior, "principal_user_id", 6) != principal.user_id+ or not bool(+ self._value(+ prior,+ "principal_authority_revision_present",+ 7,+ )+ )+ ):+ return OperationResult(FixedResult.CONFLICT_OPERATION, None)+ receipt_spec = self._retry_v3_receipt_spec(+ principal,+ intent,+ campaign_id=self._value(prior, "campaign_id", 1),+ authority_revision=int(+ self._value(prior, "principal_authority_revision", 8)+ ),+ )+ if receipt_spec is None:+ return OperationResult(FixedResult.INVALID_CONTRACT, None)+ replay = await self._classify_receipt(+ connection,+ receipt_spec,+ current_revision=intent.expected_parent_revision,+ )+ return replay or OperationResult(+ FixedResult.CONFLICT_OPERATION,+ intent.expected_parent_revision,+ )+ await self._acquire_logical_attempt_transaction_keys(+ connection,+ intent.logical_execution_id,+ intent.parent_attempt_id,+ )+ # Discover immutable logical identity without taking a row lock.+ # The complete authority graph is then locked in generation-11+ # order before the logical/parent rows are locked and revalidated.+ logical = await self._fetchrow(+ connection,+ "SELECT campaign_id,module_id,ingress_code,immutable_work_digest,"+ "admission_authority_contract_version,highest_attempt_ordinal,revision,"+ "closure_operation_id,actor_subject_ref,actor_user_id,submission_id "+ "FROM logical_executions "+ "WHERE id=?",+ (intent.logical_execution_id,),+ )+ if logical is None:+ return OperationResult(FixedResult.RETRY_AUTHORITY_UNRESOLVED, None)+ if int(self._value(logical, "admission_authority_contract_version", 4)) != 3:+ return OperationResult(FixedResult.INVALID_CONTRACT, None)+ campaign_id = str(self._value(logical, "campaign_id", 0))+ module_id = str(self._value(logical, "module_id", 1))+ ingress_code = str(self._value(logical, "ingress_code", 2))+ submission_id = str(self._value(logical, "submission_id", 10))+ child_intent = AdmissionIntentV3(+ intent.logical_execution_id,+ submission_id,+ intent.child_attempt_id,+ intent.outbox_id,+ intent.publication_key,+ campaign_id,+ module_id,+ ingress_code,+ intent.operation_id,+ intent.evaluation_mode,+ intent.raw_parameters,+ intent.credential_ids,+ intent.approval_ref,+ intent.noise_units,+ intent.exfiltration_units,+ )+ prepared = self._prepared_admission(child_intent)+ if prepared is None:+ return OperationResult(FixedResult.INVALID_CONTRACT, None)+ if (+ self._value(logical, "immutable_work_digest", 3)+ != prepared.immutable_work_digest+ ):+ return OperationResult(FixedResult.CONFLICT_OPERATION, None)+ resolved = await self._resolve_admission_v3(+ connection, principal, child_intent, prepared, suffix=suffix+ )+ state = self._v3_initial_state(resolved.snapshot)+ terminal = state in {AttemptState.REJECTED, AttemptState.BLOCKED}+ outbox_id = (+ self._derived_v3_uuid(intent.operation_id, "terminal-outbox")+ if terminal+ else None+ )+ publication_key = (+ self._derived_v3_uuid(intent.operation_id, "terminal-publication")+ if terminal+ else None+ )+ request = AdmissionRequest(+ intent.logical_execution_id,+ submission_id,+ intent.child_attempt_id,+ outbox_id,+ publication_key,+ campaign_id,+ resolved.principal.subject_ref,+ resolved.principal.user_id,+ module_id,+ ingress_code,+ state,+ intent.operation_id,+ resolved.snapshot,+ resolved.approval,+ resolved.budgets,+ )+ if not self._valid_admission(request):+ return OperationResult(FixedResult.INVALID_CONTRACT, None)+ receipt_spec = self._retry_v3_receipt_spec(+ principal,+ intent,+ campaign_id=campaign_id,+ authority_revision=resolved.principal.authority_revision,+ )+ if receipt_spec is None:+ return OperationResult(FixedResult.INVALID_CONTRACT, None)+ logical = await self._fetchrow(+ connection,+ "SELECT campaign_id,module_id,ingress_code,immutable_work_digest,"+ "admission_authority_contract_version,highest_attempt_ordinal,revision,"+ "closure_operation_id,actor_subject_ref,actor_user_id,submission_id "+ "FROM logical_executions WHERE id=?" + suffix,+ (intent.logical_execution_id,),+ )+ parent = await self._fetchrow(+ connection,+ "SELECT campaign_id,ordinal,revision,state,closes_logical,retry_disposition "+ "FROM execution_attempts WHERE logical_execution_id=? AND id=?" + suffix,+ (intent.logical_execution_id, intent.parent_attempt_id),+ )+ if logical is None or parent is None:+ return OperationResult(FixedResult.RETRY_AUTHORITY_UNRESOLVED, None)+ if (+ int(self._value(logical, "admission_authority_contract_version", 4)) != 3+ or self._value(logical, "campaign_id", 0) != campaign_id+ or self._value(logical, "module_id", 1) != module_id+ or self._value(logical, "ingress_code", 2) != ingress_code+ or self._value(logical, "submission_id", 10) != submission_id+ or self._value(logical, "immutable_work_digest", 3)+ != prepared.immutable_work_digest+ ):+ return OperationResult(FixedResult.CONFLICT_OPERATION, None)+ parent_revision = int(self._value(parent, "revision", 2))+ parent_ordinal = int(self._value(parent, "ordinal", 1))+ if parent_revision != intent.expected_parent_revision:+ return OperationResult(FixedResult.CONFLICT_REVISION, parent_revision)+ if (+ self._value(parent, "campaign_id", 0) != campaign_id+ or self._value(parent, "state", 3) not in {"failed", "timed_out"}+ or bool(self._value(parent, "closes_logical", 4))+ or self._value(parent, "retry_disposition", 5) != "eligible"+ or self._value(logical, "closure_operation_id", 7) is not None+ or self._value(logical, "actor_subject_ref", 8)+ != resolved.principal.subject_ref+ or self._value(logical, "actor_user_id", 9) != resolved.principal.user_id+ or parent_ordinal != int(self._value(logical, "highest_attempt_ordinal", 5))+ ):+ return OperationResult(FixedResult.CONFLICT_STATE, parent_revision)+ sibling = await self._fetchrow(+ connection,+ "SELECT id FROM execution_attempts WHERE logical_execution_id=? "+ "AND parent_attempt_id=?",+ (intent.logical_execution_id, intent.parent_attempt_id),+ )+ if sibling is not None:+ return OperationResult(FixedResult.CONFLICT_OPERATION, parent_revision)+ if resolved.budgets is not None:+ await self._acquire_transaction_key(connection, resolved.budgets.operation_id)+ logical_revision = int(self._value(logical, "revision", 6))+ child_ordinal = parent_ordinal + 1+ async with self._savepoint(connection):+ parent_update = await self.cas_update_one(+ connection,+ "UPDATE execution_attempts SET retry_disposition='child_bound',"+ "retry_child_bound_at="+ + self._now_sql+ + ",revision=revision+1 WHERE id=? AND logical_execution_id=? "+ "AND revision=? AND retry_disposition='eligible' AND closes_logical="+ + ("FALSE" if self._dialect == "postgresql" else "0")+ + " RETURNING id,revision",+ (+ intent.parent_attempt_id,+ intent.logical_execution_id,+ parent_revision,+ ),+ identity=intent.parent_attempt_id,+ post_revision=parent_revision + 1,+ revision_column="revision",+ zero_classifier=lambda: self._classify_zero_row(+ connection,+ table="execution_attempts",+ identity_column="id",+ identity=intent.parent_attempt_id,+ revision_column="revision",+ checks=(+ ("revision", (parent_revision,), FixedResult.CONFLICT_REVISION),+ ),+ ),+ )+ if parent_update is None:+ raise _AbortOperationError(+ OperationResult(FixedResult.CONFLICT_STATE, parent_revision)+ )+ await self._insert_attempt_v3(+ connection,+ request,+ resolved,+ prepared,+ ordinal=child_ordinal,+ parent=intent.parent_attempt_id,+ )+ logical_sql = (+ "UPDATE logical_executions SET highest_attempt_ordinal=?,"+ + (+ "closure_operation_id=?,closure_authority_subject_ref=?,"+ "closure_authority_user_id=?,closure_authority_revision=?,"+ "closing_attempt_id=?,closed_at=" + self._now_sql + ","+ if terminal+ else ""+ )+ + "revision=revision+1 WHERE id=? AND revision=? "+ "AND closure_operation_id IS NULL RETURNING id,revision"+ )+ logical_params: tuple[Any, ...] = (child_ordinal,)+ if terminal:+ logical_params += (+ intent.operation_id,+ resolved.principal.subject_ref,+ resolved.principal.user_id,+ resolved.principal.authority_revision,+ intent.child_attempt_id,+ )+ logical_params += (+ intent.logical_execution_id,+ logical_revision,+ )+ logical_update = await self.cas_update_one(+ connection,+ logical_sql,+ logical_params,+ identity=intent.logical_execution_id,+ post_revision=logical_revision + 1,+ revision_column="revision",+ zero_classifier=lambda: self._classify_zero_row(+ connection,+ table="logical_executions",+ identity_column="id",+ identity=intent.logical_execution_id,+ revision_column="revision",+ checks=(+ ("revision", (logical_revision,), FixedResult.CONFLICT_REVISION),+ ("closure_operation_id", (None,), FixedResult.ALREADY_CLOSED),+ ),+ ),+ )+ if logical_update is None:+ raise _AbortOperationError(+ OperationResult(FixedResult.CONFLICT_STATE, parent_revision)+ )+ if terminal:+ await self._insert_initial_terminal_outbox(connection, request)+ else:+ if resolved.approval is not None:+ await self._consume_approval_authority_v3(connection, request, resolved)+ await self._insert_approval(connection, request)+ budget_result = await self._reserve_budgets_locked(+ connection, resolved.budgets+ )+ if budget_result.result is not FixedResult.APPLIED:+ raise _AbortOperationError(budget_result)+ await self._insert_receipt(+ connection,+ receipt_spec,+ result=FixedResult.APPLIED,+ exact_replay_code=FixedResult.REPLAYED_BOUND_CHILD,+ result_identity=intent.parent_attempt_id,+ result_revision=parent_revision + 1,+ secondary_result_identity=intent.child_attempt_id,+ secondary_result_revision=0,+ result_fields=(+ ("logical_execution_id", intent.logical_execution_id),+ ("child_ordinal", child_ordinal),+ ("immutable_intent_digest", prepared.immutable_intent_digest),+ ),+ )+ return OperationResult(FixedResult.APPLIED, parent_revision + 1)+ except (ValueError, _AbortOperationError) as error:+ if isinstance(error, _AbortOperationError):+ return error.result+ return OperationResult(FixedResult.INVALID_CONTRACT, None)++ async def replay_retry_attempt_v2(+ self,+ principal: TrustedPrincipal,+ request: RetryRequest,+ ) -> OperationResult:+ """Replay one existing historical v2 retry receipt without live authority."""+ if (+ not self._valid_trusted_principal(principal)+ or type(request) is not RetryRequest+ or not valid_uuid(request.logical_execution_id)+ or not valid_uuid(request.parent_attempt_id)+ or not self._valid_expected_revision(request.expected_parent_revision)+ or not self._valid_admission(request.child)+ or request.child.logical_execution_id != request.logical_execution_id+ or request.child.actor_subject_ref != principal.subject_ref+ or request.child.actor_user_id != principal.user_id+ ):+ return OperationResult(FixedResult.INVALID_CONTRACT, None)+ child = request.child+ approval = child.approval+ budgets = child.budgets+ fields: tuple[tuple[str, str | int | bool | None], ...] = (+ ("logical_execution_id", request.logical_execution_id),+ ("parent_attempt_id", request.parent_attempt_id),+ ("child_attempt_id", child.attempt_id),+ ("child_submission_id", child.submission_id),+ ("child_operation_id", child.operation_id),+ ("child_outbox_id", child.outbox_id),+ ("child_publication_key", child.publication_key),+ ("child_campaign_id", child.campaign_id),+ ("actor_subject_ref", child.actor_subject_ref),+ ("actor_user_id", child.actor_user_id),+ ("module_id", child.module_id),+ ("ingress_code", child.ingress_code),+ ("initial_state", child.initial_state.value),+ ) + _snapshot_binding_values(child.snapshot)+ fields += (+ ("approval_id", None if approval is None else approval.approval_id),+ ("approval_ref", None if approval is None else approval.approval_ref),+ (+ "approval_authority_revision",+ None if approval is None else approval.authority_revision,+ ),+ (+ "approval_binding_digest",+ None if approval is None else approval.binding_digest,+ ),+ ("budget_operation_id", None if budgets is None else budgets.operation_id),+ ("noise_budget_id", None if budgets is None else budgets.noise_budget_id),+ ("noise_ledger_id", None if budgets is None else budgets.noise_ledger_id),+ ("noise_units", None if budgets is None else budgets.noise_units),+ (+ "noise_expected_revision",+ None if budgets is None else budgets.noise_expected_revision,+ ),+ (+ "exfiltration_budget_id",+ None if budgets is None else budgets.exfiltration_budget_id,+ ),+ (+ "exfiltration_ledger_id",+ None if budgets is None else budgets.exfiltration_ledger_id,+ ),+ (+ "exfiltration_units",+ None if budgets is None else budgets.exfiltration_units,+ ),+ (+ "exfiltration_expected_revision",+ None if budgets is None else budgets.exfiltration_expected_revision,+ ),+ (+ "concurrency_budget_id",+ None if budgets is None else budgets.concurrency_budget_id,+ ),+ (+ "concurrency_ledger_id",+ None if budgets is None else budgets.concurrency_ledger_id,+ ),+ (+ "concurrency_expected_revision",+ None if budgets is None else budgets.concurrency_expected_revision,+ ),+ )+ spec = self._receipt_spec(+ operation_id=child.operation_id,+ operation_code="retry",+ campaign_id=child.campaign_id,+ primary_target_id=request.parent_attempt_id,+ secondary_target_id=child.attempt_id,+ principal_kind="actor",+ principal_subject_ref=principal.subject_ref,+ principal_user_id=principal.user_id,+ principal_authority_revision=child.snapshot.actor_authority_revision,+ expected_revision=request.expected_parent_revision,+ fields=fields,+ )+ async with self._transaction() as connection:+ await self._acquire_transaction_key(connection, child.operation_id)+ replay = await self._classify_receipt(+ connection,+ spec,+ current_revision=request.expected_parent_revision,+ )+ if replay is not None:+ return replay+ logical = await self._fetchrow(+ connection,+ "SELECT admission_authority_contract_version FROM logical_executions WHERE id=?",+ (request.logical_execution_id,),+ )+ if logical is None:+ return OperationResult(FixedResult.INVALID_CONTRACT, None)+ if int(self._value(logical, "admission_authority_contract_version", 0)) != 2:+ return OperationResult(FixedResult.CONFLICT_OPERATION, None)+ return OperationResult(FixedResult.INVALID_CONTRACT, None)++ async def _insert_initial_terminal_outbox(+ self, connection: Any, request: AdmissionRequest+ ) -> None:+ event = (+ "execution_rejected"+ if request.initial_state is AttemptState.REJECTED+ else "execution_blocked"+ )+ now = self._now_sql+ inserted = await self.insert_or_validate_binding(+ connection,+ "INSERT INTO execution_publication_outbox("+ "id,publication_key,attempt_id,campaign_id,event_code,"+ "is_attempt_terminal,available_at,latest_operation_id,"+ "latest_operation_code,latest_operation_base_revision,created_at) "+ "SELECT ?,?,?,?,?,"+ + ("TRUE" if self._dialect == "postgresql" else "1")+ + ",db_now,?,'insert',0,db_now FROM (SELECT "+ + now+ + " AS db_now) AS clock WHERE 1=1 ON CONFLICT(id) DO NOTHING RETURNING id,claim_revision",+ (+ request.outbox_id,+ request.publication_key,+ request.attempt_id,+ request.campaign_id,+ event,+ request.publication_key,+ ),+ identity=request.outbox_id,+ revision=0,+ revision_column="claim_revision",+ )+ if inserted is None:+ raise _AbortOperationError(OperationResult(FixedResult.CONFLICT_OPERATION, None))+ spec = self._receipt_spec(+ operation_id=request.outbox_id,+ operation_code="outbox_insert",+ campaign_id=request.campaign_id,+ primary_target_id=request.outbox_id,+ secondary_target_id=request.attempt_id,+ fields=(+ ("publication_key", request.publication_key),+ ("event_code", event),+ ("terminal", True),+ ("finding_count", 0),+ ("credential_count", 0),+ ("host_count", 0),+ ("artifact_count", 0),+ ),+ )+ await self._insert_receipt(+ connection,+ spec,+ result=FixedResult.APPLIED,+ result_identity=request.outbox_id,+ result_revision=0,+ result_fields=(("publication_state", "pending"), ("claim_revision", 0)),+ )++ async def _insert_approval(self, connection: Any, request: AdmissionRequest) -> None:+ approval = request.approval+ if approval is None or not (+ type(approval) is ApprovalBinding+ and all(+ valid_uuid(value)+ for value in (+ approval.approval_id,+ approval.approval_ref,+ approval.approver_subject_ref,+ )+ )+ and (approval.approver_user_id is None or valid_uuid(approval.approver_user_id))+ and type(approval.authority_revision) is int+ and 0 <= approval.authority_revision <= MAX_I53+ and type(approval.binding_digest) is str+ and re.fullmatch(r"[0-9a-f]{64}", approval.binding_digest)+ ):+ raise _AbortOperationError(OperationResult(FixedResult.INVALID_CONTRACT, None))+ inserted = await self.insert_or_validate_binding(+ connection,+ "INSERT INTO execution_attempt_approvals("+ "id,attempt_id,campaign_id,approval_ref,approver_subject_ref,"+ "approver_user_id,authority_revision,binding_digest) "+ "VALUES(?,?,?,?,?,?,?,?) ON CONFLICT(id) DO NOTHING RETURNING id,authority_revision",+ (+ approval.approval_id,+ request.attempt_id,+ request.campaign_id,+ approval.approval_ref,+ approval.approver_subject_ref,+ approval.approver_user_id,+ approval.authority_revision,+ approval.binding_digest,+ ),+ identity=approval.approval_id,+ revision=approval.authority_revision,+ revision_column="authority_revision",+ )+ if inserted is None:+ raise _AbortOperationError(OperationResult(FixedResult.CONFLICT_OPERATION, None))++ async def _reserve_budgets_locked(+ self, connection: Any, request: BudgetReservation | None+ ) -> OperationResult:+ if request is None or not self._valid_budget_reservation(request):+ return OperationResult(FixedResult.INVALID_CONTRACT, None)+ entries = (+ (+ "noise",+ request.noise_budget_id,+ request.noise_ledger_id,+ request.noise_units,+ request.noise_expected_revision,+ ),+ (+ "exfiltration",+ request.exfiltration_budget_id,+ request.exfiltration_ledger_id,+ request.exfiltration_units,+ request.exfiltration_expected_revision,+ ),+ (+ "concurrency",+ request.concurrency_budget_id,+ request.concurrency_ledger_id,+ 1,+ request.concurrency_expected_revision,+ ),+ )+ if request.attempt_id is None:+ return OperationResult(FixedResult.INVALID_CONTRACT, None)+ spec = self._budget_reservation_receipt_spec(request)+ await self._acquire_transaction_key(connection, request.operation_id)+ replay = await self._classify_receipt(+ connection,+ spec,+ current_revision=max(+ request.noise_expected_revision,+ request.exfiltration_expected_revision,+ request.concurrency_expected_revision,+ ),+ )+ if replay is not None:+ return replay+ suffix = " FOR UPDATE" if self._dialect == "postgresql" else ""+ validated: list[tuple[str, str, str, int, int]] = []+ for kind, budget_id, ledger_id, units, expected_revision in entries:+ row = await self._fetchrow(+ connection,+ "SELECT campaign_id,budget_kind,capacity_units,reserved_units,"+ "consumed_units,revision FROM campaign_execution_budgets "+ "WHERE id=?" + suffix,+ (budget_id,),+ )+ if row is None or (+ self._value(row, "campaign_id", 0) != request.campaign_id+ or self._value(row, "budget_kind", 1) != kind+ ):+ return OperationResult(FixedResult.INCONSISTENT_BUDGET_SET, None)+ revision = int(self._value(row, "revision", 5))+ if revision != expected_revision:+ return OperationResult(FixedResult.CONFLICT_REVISION, revision)+ capacity = int(self._value(row, "capacity_units", 2))+ reserved = int(self._value(row, "reserved_units", 3))+ consumed = int(self._value(row, "consumed_units", 4))+ if reserved + consumed + units > capacity:+ return OperationResult(FixedResult.CAPACITY_UNAVAILABLE, revision)+ validated.append((kind, budget_id, ledger_id, units, expected_revision))+ for kind, budget_id, ledger_id, units, expected_revision in validated:+ updated = await self.cas_update_one(+ connection,+ "UPDATE campaign_execution_budgets SET reserved_units=reserved_units+?,"+ "revision=revision+1,latest_operation_id=?,"+ "latest_operation_base_revision=?,latest_operation_code='reserve',"+ "updated_at=" + self._now_sql + " WHERE id=? AND revision=? "+ "AND reserved_units+consumed_units+?<=capacity_units RETURNING id,revision",+ (+ units,+ request.operation_id,+ expected_revision,+ budget_id,+ expected_revision,+ units,+ ),+ identity=budget_id,+ post_revision=expected_revision + 1,+ zero_classifier=lambda budget_id=budget_id, kind=kind, expected_revision=expected_revision, units=units: (+ self._classify_zero_budget(+ connection,+ budget_id=budget_id,+ campaign_id=request.campaign_id,+ budget_kind=kind,+ expected_revision=expected_revision,+ required_units=units,+ operation="reserve",+ )+ ),+ )+ if updated is None:+ return OperationResult(FixedResult.CONFLICT_REVISION, expected_revision)+ inserted = await self.insert_or_validate_binding(+ connection,+ "INSERT INTO campaign_execution_budget_ledger("+ "id,attempt_id,campaign_id,budget_id,budget_kind,"+ "reservation_units,consumed_units,disposition,"+ "budget_revision_reserved) VALUES(?,?,?,?,?,?,0,'held',?) "+ "ON CONFLICT(id) DO NOTHING RETURNING id,budget_revision_reserved",+ (+ ledger_id,+ request.attempt_id,+ request.campaign_id,+ budget_id,+ kind,+ units,+ expected_revision + 1,+ ),+ identity=ledger_id,+ revision=expected_revision + 1,+ revision_column="budget_revision_reserved",+ )+ if inserted is None:+ return OperationResult(FixedResult.CONFLICT_OPERATION, None)+ await self._insert_receipt(+ connection,+ spec,+ result=FixedResult.APPLIED,+ result_identity=request.attempt_id,+ result_revision=max(+ request.noise_expected_revision,+ request.exfiltration_expected_revision,+ request.concurrency_expected_revision,+ )+ + 1,+ secondary_result_identity=request.noise_budget_id,+ secondary_result_revision=request.noise_expected_revision + 1,+ result_fields=(+ ("noise_ledger_id", request.noise_ledger_id),+ ("noise_post_revision", request.noise_expected_revision + 1),+ ("exfiltration_ledger_id", request.exfiltration_ledger_id),+ ("exfiltration_post_revision", request.exfiltration_expected_revision + 1),+ ("concurrency_ledger_id", request.concurrency_ledger_id),+ ("concurrency_post_revision", request.concurrency_expected_revision + 1),+ ),+ )+ return OperationResult(FixedResult.APPLIED, None)++ def _budget_settlement_receipt_spec(self, request: BudgetSettlement) -> _ReceiptSpec:+ return self._receipt_spec(+ operation_id=request.operation_id,+ operation_code="budget_settle",+ campaign_id=request.campaign_id,+ primary_target_id=request.attempt_id,+ secondary_target_id=request.noise_budget_id,+ principal_kind=str(request.principal_kind),+ principal_subject_ref=str(request.principal_subject_ref),+ principal_user_id=request.principal_user_id,+ principal_authority_revision=request.principal_authority_revision,+ expected_revision=request.noise_expected_revision,+ secondary_expected_revision=request.exfiltration_expected_revision,+ fields=(+ ("noise_budget_id", request.noise_budget_id),+ ("noise_units", request.noise_units),+ ("noise_actual", request.noise_actual),+ ("exfiltration_budget_id", request.exfiltration_budget_id),+ ("exfiltration_units", request.exfiltration_units),+ ("exfiltration_actual", request.exfiltration_actual),+ ("concurrency_budget_id", request.concurrency_budget_id),+ ("concurrency_expected_revision", request.concurrency_expected_revision),+ ),+ )++ @staticmethod+ def _budget_settlement_result_fields(+ request: BudgetSettlement,+ ) -> tuple[tuple[str, str | int | bool | None], ...]:+ return (+ ("noise_post_revision", request.noise_expected_revision + 1),+ ("noise_disposition", "released" if request.noise_actual == 0 else "consumed"),+ ("noise_consumed", request.noise_actual),+ ("exfiltration_post_revision", request.exfiltration_expected_revision + 1),+ (+ "exfiltration_disposition",+ "released" if request.exfiltration_actual == 0 else "consumed",+ ),+ ("exfiltration_consumed", request.exfiltration_actual),+ ("concurrency_post_revision", request.concurrency_expected_revision + 1),+ ("concurrency_disposition", "released"),+ ("concurrency_consumed", 0),+ )++ async def _insert_budget_settlement_receipt(+ self, connection: Any, request: BudgetSettlement+ ) -> None:+ await self._insert_receipt(+ connection,+ self._budget_settlement_receipt_spec(request),+ result=FixedResult.APPLIED,+ result_identity=request.attempt_id,+ result_revision=max(+ request.noise_expected_revision,+ request.exfiltration_expected_revision,+ request.concurrency_expected_revision,+ )+ + 1,+ secondary_result_identity=request.noise_budget_id,+ secondary_result_revision=request.noise_expected_revision + 1,+ result_fields=self._budget_settlement_result_fields(request),+ )++ async def _settle_budgets_locked(+ self,+ connection: Any,+ request: BudgetSettlement,+ *,+ write_receipt: bool = True,+ prepared_terminal_v3: _PreparedTerminalV3BudgetSettlement | None = None,+ ) -> OperationResult:+ if not self._valid_budget_settlement(request):+ return OperationResult(FixedResult.INVALID_CONTRACT, None)+ entries = (+ (+ "noise",+ request.noise_budget_id,+ request.noise_units,+ request.noise_actual,+ request.noise_expected_revision,+ ),+ (+ "exfiltration",+ request.exfiltration_budget_id,+ request.exfiltration_units,+ request.exfiltration_actual,+ request.exfiltration_expected_revision,+ ),+ (+ "concurrency",+ request.concurrency_budget_id,+ 1,+ 0,+ request.concurrency_expected_revision,+ ),+ )+ validated: list[tuple[str, str, str, int, int, int, str]] = []+ if prepared_terminal_v3 is not None:+ if type(prepared_terminal_v3) is not _PreparedTerminalV3BudgetSettlement:+ return OperationResult(FixedResult.INVARIANT_FAILURE, None)+ prepared_entries = prepared_terminal_v3.entries+ if (+ prepared_terminal_v3.request is not request+ or type(prepared_entries) is not tuple+ or len(prepared_entries) != len(entries)+ or any(type(item) is not tuple or len(item) != 7 for item in prepared_entries)+ ):+ return OperationResult(FixedResult.INVARIANT_FAILURE, None)+ for expected, prepared in zip(entries, prepared_entries, strict=True):+ kind, budget_id, reservation, actual, expected_revision = expected+ (+ prepared_kind,+ prepared_budget_id,+ ledger_id,+ prepared_reservation,+ prepared_actual,+ prepared_revision,+ prepared_disposition,+ ) = prepared+ if (+ prepared_kind != kind+ or prepared_budget_id != budget_id+ or not valid_uuid(ledger_id)+ or prepared_reservation != reservation+ or prepared_actual != actual+ or prepared_revision != expected_revision+ or prepared_disposition != ("released" if actual == 0 else "consumed")+ ):+ return OperationResult(FixedResult.INVARIANT_FAILURE, None)+ validated.append(prepared)+ else:+ suffix = " FOR UPDATE" if self._dialect == "postgresql" else ""+ budgets: list[Any] = []+ for kind, budget_id, _reservation, _actual, _expected_revision in entries:+ budget = await self._fetchrow(+ connection,+ "SELECT id,campaign_id,budget_kind,reserved_units,revision "+ "FROM campaign_execution_budgets WHERE id=?" + suffix,+ (budget_id,),+ )+ if budget is None or (+ self._value(budget, "campaign_id", 1) != request.campaign_id+ or self._value(budget, "budget_kind", 2) != kind+ ):+ return OperationResult(FixedResult.INCONSISTENT_BUDGET_SET, None)+ budgets.append(budget)+ ledgers: list[Any] = []+ for kind, _budget_id, _reservation, _actual, _expected_revision in entries:+ ledger = await self._fetchrow(+ connection,+ "SELECT id,disposition,reservation_units,consumed_units,"+ "budget_revision_settled FROM campaign_execution_budget_ledger "+ "WHERE attempt_id=? AND budget_kind=?" + suffix,+ (request.attempt_id, kind),+ )+ if ledger is None:+ return OperationResult(FixedResult.INCONSISTENT_BUDGET_SET, None)+ ledgers.append(ledger)+ for index, (kind, budget_id, reservation, actual, expected_revision) in enumerate(+ entries+ ):+ budget = budgets[index]+ ledger = ledgers[index]+ disposition = str(self._value(ledger, "disposition", 1))+ reserved_units = int(self._value(ledger, "reservation_units", 2))+ expected_disposition = "released" if actual == 0 else "consumed"+ revision = int(self._value(budget, "revision", 4))+ if disposition != "held":+ return OperationResult(FixedResult.CONFLICT_OPERATION, revision)+ if (+ reserved_units != reservation+ or revision != expected_revision+ or int(self._value(budget, "reserved_units", 3)) < reservation+ ):+ return OperationResult(+ FixedResult.CONFLICT_REVISION+ if revision != expected_revision+ else FixedResult.INCONSISTENT_BUDGET_SET,+ revision,+ )+ validated.append(+ (+ kind,+ budget_id,+ str(self._value(ledger, "id", 0)),+ reservation,+ actual,+ expected_revision,+ expected_disposition,+ )+ )+ for (+ kind,+ budget_id,+ ledger_id,+ reservation,+ actual,+ expected_revision,+ disposition,+ ) in validated:+ updated = await self.cas_update_one(+ connection,+ "UPDATE campaign_execution_budgets SET reserved_units=reserved_units-?,"+ "consumed_units=consumed_units+?,revision=revision+1,"+ "latest_operation_id=?,latest_operation_base_revision=?,"+ "latest_operation_code='settle',updated_at="+ + self._now_sql+ + " WHERE id=? AND revision=? AND reserved_units>=? RETURNING id,revision",+ (+ reservation,+ actual,+ request.operation_id,+ expected_revision,+ budget_id,+ expected_revision,+ reservation,+ ),+ identity=budget_id,+ post_revision=expected_revision + 1,+ zero_classifier=lambda budget_id=budget_id, kind=kind, expected_revision=expected_revision, reservation=reservation: (+ self._classify_zero_budget(+ connection,+ budget_id=budget_id,+ campaign_id=request.campaign_id,+ budget_kind=kind,+ expected_revision=expected_revision,+ required_units=reservation,+ operation="settle",+ )+ ),+ )+ if updated is None:+ return OperationResult(FixedResult.CONFLICT_REVISION, expected_revision)+ updated_ledger = await self.update_exact_set(+ connection,+ "UPDATE campaign_execution_budget_ledger SET consumed_units=?,"+ "disposition=?,budget_revision_settled=?,settled_at="+ + self._now_sql+ + " WHERE id=? AND attempt_id=? AND budget_kind=? AND disposition='held' "+ "RETURNING id,budget_revision_settled,disposition,consumed_units",+ (+ actual,+ disposition,+ expected_revision + 1,+ ledger_id,+ request.attempt_id,+ kind,+ ),+ expected=(+ ("id", ledger_id),+ ("budget_revision_settled", expected_revision + 1),+ ("disposition", disposition),+ ("consumed_units", actual),+ ),+ zero_classifier=lambda ledger_id=ledger_id, kind=kind: self._classify_zero_ledger(+ connection,+ ledger_id=ledger_id,+ attempt_id=request.attempt_id,+ budget_kind=kind,+ ),+ )+ if updated_ledger is None:+ return OperationResult(FixedResult.CONFLICT_STATE, None)+ if write_receipt:+ await self._insert_budget_settlement_receipt(connection, request)+ return OperationResult(FixedResult.APPLIED, None)++ @staticmethod+ def _valid_output_observations(outputs: object) -> bool:+ if type(outputs) is not tuple:+ return False+ identities: set[str] = set()+ targets: set[tuple[OutputKind, str]] = set()+ for output in outputs:+ if (+ type(output) is not OutputObservation+ or not valid_uuid(output.link_id)+ or type(output.kind) is not OutputKind+ or not valid_uuid(output.target_id)+ or output.link_id in identities+ or (output.kind, output.target_id) in targets+ ):+ return False+ identities.add(output.link_id)+ targets.add((output.kind, output.target_id))+ return True++ async def _commit_terminal_attempt_same_transaction(+ self,+ connection: Any,+ request: TerminalCommitRequest,+ *,+ receipt_spec: _ReceiptSpec,+ logical: Any,+ attempt: Any,+ current: AttemptState,+ retry_eligible: bool,+ result_binding_domain: str | None = None,+ additional_result_fields: tuple[tuple[str, str | int | bool | None], ...] = (),+ prepared_budget_settlement: _PreparedTerminalV3BudgetSettlement | None = None,+ ) -> OperationResult:+ """Apply a prepared terminal commit without opening a transaction or connection."""+ target = request.transition.target_state+ revision = int(self._value(attempt, "revision", 1))+ async with self._savepoint(connection):+ budget_result = await self._settle_budgets_locked(+ connection,+ request.budgets,+ write_receipt=False,+ prepared_terminal_v3=prepared_budget_settlement,+ )+ if budget_result.result is not FixedResult.APPLIED:+ raise _AbortOperationError(budget_result)+ counts = await self._insert_output_links(+ connection,+ request.campaign_id,+ request.transition.attempt_id,+ request.outputs,+ )+ result = await self._apply_transition(+ connection,+ attempt,+ current,+ request.transition,+ zero_receipt_spec=receipt_spec,+ retry_eligible=retry_eligible,+ )+ if result.result is not FixedResult.APPLIED:+ raise _AbortOperationError(result)+ closes = not retry_eligible+ if closes:+ closed_attempt = await self.cas_update_one(+ connection,+ "UPDATE execution_attempts SET closes_logical="+ + ("TRUE" if self._dialect == "postgresql" else "1")+ + " WHERE id=? AND revision=? AND closes_logical="+ + ("FALSE" if self._dialect == "postgresql" else "0")+ + " RETURNING id,revision",+ (+ request.transition.attempt_id,+ request.transition.expected_revision + 1,+ ),+ identity=request.transition.attempt_id,+ post_revision=request.transition.expected_revision + 1,+ zero_classifier=lambda: self._classify_zero_row(+ connection,+ table="execution_attempts",+ identity_column="id",+ identity=request.transition.attempt_id,+ revision_column="revision",+ checks=(+ (+ "revision",+ (request.transition.expected_revision + 1,),+ FixedResult.CONFLICT_REVISION,+ ),+ ("closes_logical", (False,), FixedResult.CONFLICT_STATE),+ ),+ receipt_spec=receipt_spec,+ authority_columns=(+ "actor_user_id",+ "actor_authority_revision",+ "actor_role",+ ),+ expected_authority_user_id=self._value(attempt, "actor_user_id", 20),+ ),+ )+ if closed_attempt is None:+ raise _AbortOperationError(+ OperationResult(FixedResult.CONFLICT_STATE, revision)+ )+ logical_revision = int(self._value(logical, "revision", 2))+ closed_logical = await self.cas_update_one(+ connection,+ "UPDATE logical_executions SET closure_operation_id=?,"+ "closure_authority_subject_ref=?,closure_authority_user_id=?,"+ "closure_authority_revision=?,closing_attempt_id=?,closed_at="+ + self._now_sql+ + ",revision=revision+1 WHERE id=? AND revision=? "+ "AND closure_operation_id IS NULL RETURNING id,revision",+ (+ request.transition.operation_id,+ self._value(attempt, "actor_subject_ref", 19),+ self._value(attempt, "actor_user_id", 20),+ self._value(attempt, "actor_authority_revision", 21),+ request.transition.attempt_id,+ request.logical_execution_id,+ logical_revision,+ ),+ identity=request.logical_execution_id,+ post_revision=logical_revision + 1,+ zero_classifier=lambda: self._classify_zero_row(+ connection,+ table="logical_executions",+ identity_column="id",+ identity=request.logical_execution_id,+ revision_column="revision",+ checks=(+ (+ "campaign_id",+ (request.campaign_id,),+ FixedResult.CONFLICT_STATE,+ ),+ (+ "closure_operation_id",+ (None,),+ FixedResult.ALREADY_CLOSED,+ ),+ (+ "revision",+ (logical_revision,),+ FixedResult.CONFLICT_REVISION,+ ),+ ),+ missing_result=FixedResult.CONFLICT_STATE,+ ),+ )+ if closed_logical is None:+ raise _AbortOperationError(+ OperationResult(FixedResult.ALREADY_CLOSED, revision)+ )+ await self._insert_terminal_outbox(connection, request, counts)+ await self._insert_budget_settlement_receipt(connection, request.budgets)+ secondary_result_revision = int(self._value(logical, "revision", 2)) + int(closes)+ result_fields = (+ ("state", target.value),+ ("revision", request.transition.expected_revision + 1),+ ("closes_logical", closes),+ ("finding_count", counts[0]),+ ("credential_count", counts[1]),+ ("host_count", counts[2]),+ ("artifact_count", counts[3]),+ ("outbox_id", request.outbox_id),+ ) + additional_result_fields+ if result_binding_domain is None:+ await self._insert_receipt(+ connection,+ receipt_spec,+ result=FixedResult.APPLIED,+ result_identity=request.transition.attempt_id,+ result_revision=request.transition.expected_revision + 1,+ secondary_result_identity=request.logical_execution_id,+ secondary_result_revision=secondary_result_revision,+ result_fields=result_fields,+ )+ elif result_binding_domain == _TERMINAL_COMMIT_RESULT_DOMAIN_V3:+ await self._insert_terminal_v3_receipt(+ connection,+ receipt_spec,+ result_identity=request.transition.attempt_id,+ result_revision=request.transition.expected_revision + 1,+ secondary_result_identity=request.logical_execution_id,+ secondary_result_revision=secondary_result_revision,+ result_fields=result_fields,+ )+ else:+ raise _AbortOperationError(OperationResult(FixedResult.INVARIANT_FAILURE, None))+ return result++ async def _derive_terminal_v3_budget_settlement(+ self,+ connection: Any,+ intent: TerminalCommitIntentV3,+ operation_id: str,+ *,+ attempt_revision: int,+ ) -> _PreparedTerminalV3BudgetSettlement:+ """Lock and derive the exact three-HELD-ledger settlement authority."""+ suffix = " FOR UPDATE" if self._dialect == "postgresql" else ""+ ledgers = tuple(+ await self._fetchall(+ connection,+ "SELECT id,attempt_id,campaign_id,budget_id,budget_kind,"+ "reservation_units,consumed_units,disposition,"+ "budget_revision_reserved,budget_revision_settled "+ "FROM campaign_execution_budget_ledger WHERE attempt_id=? "+ "ORDER BY CASE budget_kind WHEN 'noise' THEN 0 "+ "WHEN 'exfiltration' THEN 1 WHEN 'concurrency' THEN 2 ELSE 3 END,id" + suffix,+ (intent.attempt_id,),+ )+ )+ expected_kinds = ("noise", "exfiltration", "concurrency")+ if len(ledgers) != len(expected_kinds):+ raise _AbortOperationError(+ OperationResult(FixedResult.INCONSISTENT_BUDGET_SET, attempt_revision)+ )+ ledger_facts: dict[str, tuple[str, str, int]] = {}+ for expected_kind, ledger in zip(expected_kinds, ledgers, strict=True):+ ledger_id = self._value(ledger, "id", 0)+ ledger_attempt = self._value(ledger, "attempt_id", 1)+ ledger_campaign = self._value(ledger, "campaign_id", 2)+ budget_id = self._value(ledger, "budget_id", 3)+ kind = self._value(ledger, "budget_kind", 4)+ if (+ kind != expected_kind+ or kind in ledger_facts+ or not valid_uuid(ledger_id)+ or not valid_uuid(budget_id)+ or ledger_attempt != intent.attempt_id+ or ledger_campaign != intent.campaign_id+ ):+ raise _AbortOperationError(+ OperationResult(FixedResult.INCONSISTENT_BUDGET_SET, attempt_revision)+ )+ if self._value(ledger, "disposition", 7) != "held":+ raise _AbortOperationError(+ OperationResult(FixedResult.CONFLICT_OPERATION, attempt_revision)+ )+ reservation = self._value(ledger, "reservation_units", 5)+ consumed = self._value(ledger, "consumed_units", 6)+ reserved_revision = self._value(ledger, "budget_revision_reserved", 8)+ settled_revision = self._value(ledger, "budget_revision_settled", 9)+ if (+ type(reservation) is not int+ or not 0 <= reservation <= MAX_I53+ or type(consumed) is not int+ or consumed != 0+ or type(reserved_revision) is not int+ or not 0 <= reserved_revision <= MAX_I53+ or settled_revision is not None+ or (kind == "concurrency" and reservation != 1)+ ):+ raise _AbortOperationError(OperationResult(FixedResult.INVARIANT_FAILURE, None))+ ledger_facts[kind] = (str(ledger_id), str(budget_id), reservation)++ actual_by_kind = {+ "noise": intent.noise_actual,+ "exfiltration": intent.exfiltration_actual,+ "concurrency": intent.concurrency_actual,+ }+ for kind in expected_kinds:+ if actual_by_kind[kind] > ledger_facts[kind][2]:+ raise _AbortOperationError(+ OperationResult(FixedResult.INVALID_CONTRACT, attempt_revision)+ )++ budget_revisions: dict[str, int] = {}+ for kind in expected_kinds:+ _ledger_id, budget_id, reservation = ledger_facts[kind]+ budget = await self._fetchrow(+ connection,+ "SELECT id,campaign_id,budget_kind,capacity_units,reserved_units,"+ "consumed_units,revision FROM campaign_execution_budgets WHERE id=?" + suffix,+ (budget_id,),+ )+ if budget is None or (+ self._value(budget, "id", 0) != budget_id+ or self._value(budget, "campaign_id", 1) != intent.campaign_id+ or self._value(budget, "budget_kind", 2) != kind+ ):+ raise _AbortOperationError(+ OperationResult(FixedResult.INCONSISTENT_BUDGET_SET, attempt_revision)+ )+ capacity = self._value(budget, "capacity_units", 3)+ reserved = self._value(budget, "reserved_units", 4)+ consumed = self._value(budget, "consumed_units", 5)+ revision = self._value(budget, "revision", 6)+ if (+ any(+ type(value) is not int or not 0 <= value <= MAX_I53+ for value in (capacity, reserved, consumed, revision)+ )+ or reserved + consumed > capacity+ ):+ raise _AbortOperationError(OperationResult(FixedResult.INVARIANT_FAILURE, None))+ if reserved < reservation:+ raise _AbortOperationError(+ OperationResult(FixedResult.INCONSISTENT_BUDGET_SET, attempt_revision)+ )+ if revision == MAX_I53 or consumed > MAX_I53 - actual_by_kind[kind]:+ raise _AbortOperationError(OperationResult(FixedResult.INVARIANT_FAILURE, None))+ budget_revisions[kind] = revision++ request = BudgetSettlement(+ campaign_id=intent.campaign_id,+ attempt_id=intent.attempt_id,+ noise_budget_id=ledger_facts["noise"][1],+ noise_units=ledger_facts["noise"][2],+ noise_actual=intent.noise_actual,+ noise_expected_revision=budget_revisions["noise"],+ exfiltration_budget_id=ledger_facts["exfiltration"][1],+ exfiltration_units=ledger_facts["exfiltration"][2],+ exfiltration_actual=intent.exfiltration_actual,+ exfiltration_expected_revision=budget_revisions["exfiltration"],+ concurrency_budget_id=ledger_facts["concurrency"][1],+ concurrency_expected_revision=budget_revisions["concurrency"],+ operation_id=self._derived_v3_uuid(+ operation_id,+ "terminal-budget-settlement",+ ),+ principal_kind="system",+ principal_subject_ref=SYSTEM_PRINCIPAL_SUBJECT_REF,+ principal_user_id=None,+ principal_authority_revision=None,+ )+ entries = tuple(+ (+ kind,+ ledger_facts[kind][1],+ ledger_facts[kind][0],+ ledger_facts[kind][2],+ actual_by_kind[kind],+ budget_revisions[kind],+ "released" if actual_by_kind[kind] == 0 else "consumed",+ )+ for kind in expected_kinds+ )+ return _PreparedTerminalV3BudgetSettlement(request, entries)++ async def commit_terminal_attempt_v3(+ self,+ intent: TerminalCommitIntentV3,+ ) -> OperationResult:+ """Commit one coordinator-confirmed, quiescent module outcome at most once."""+ outputs = self._canonical_terminal_v3_outputs(intent)+ if outputs is None:+ return OperationResult(FixedResult.INVALID_CONTRACT, None)+ contract = self._terminal_v3_outcome_contract(intent.outcome_code)+ if contract is None: # Kept explicit so no future enum value widens this seam.+ return OperationResult(FixedResult.INVALID_CONTRACT, None)+ predecessor, target, operation_code, authoritative_proof = contract+ operation_id = self._terminal_v3_operation_id(intent.attempt_id)+ spec = self._terminal_v3_receipt_spec(+ intent,+ operation_id,+ operation_code,+ outputs,+ )+ suffix = " FOR UPDATE" if self._dialect == "postgresql" else ""+ try:+ async with self._transaction() as connection:+ await self._acquire_transaction_key(connection, operation_id)+ replay = await self._classify_receipt(+ connection,+ spec,+ current_revision=None,+ )+ if replay is not None:+ return replay+ await self._acquire_logical_attempt_transaction_keys(+ connection,+ intent.logical_execution_id,+ intent.attempt_id,+ )+ attempt = await self._fetchrow(+ connection,+ "SELECT state,revision,dispatch_owner_ref,lease_generation,"+ "start_operation_id,dispatch_operation_id,"+ "cancellation_request_revision,recovery_deadline_at,timeout_limit_ms,"+ "lease_expires_at,queue_operation_id,cancellation_request_operation_id,"+ "cancellation_ack_operation_id,timeout_operation_id,"+ "settlement_pending_operation_id,terminal_operation_id,"+ "logical_execution_id,campaign_id,retry_disposition,"+ "actor_subject_ref,actor_user_id,actor_authority_revision,closes_logical,"+ "external_effect_class,idempotency_class,retry_policy "+ "FROM execution_attempts WHERE id=?" + suffix,+ (intent.attempt_id,),+ )+ if attempt is None:+ return OperationResult(FixedResult.NOT_FOUND_OR_PURGED, None)+ revision_value = self._value(attempt, "revision", 1)+ if type(revision_value) is not int or not 0 <= revision_value <= MAX_I53:+ return OperationResult(FixedResult.INVARIANT_FAILURE, None)+ revision = revision_value+ if (+ self._value(attempt, "logical_execution_id", 16) != intent.logical_execution_id+ or self._value(attempt, "campaign_id", 17) != intent.campaign_id+ ):+ return OperationResult(FixedResult.CONFLICT_STATE, revision)+ try:+ current = AttemptState(str(self._value(attempt, "state", 0)))+ except ValueError:+ return OperationResult(FixedResult.INVARIANT_FAILURE, None)+ if current is not predecessor:+ return OperationResult(FixedResult.CONFLICT_STATE, revision)+ if revision != intent.expected_attempt_revision:+ return OperationResult(FixedResult.CONFLICT_REVISION, revision)+ started = self._value(attempt, "start_operation_id", 4) is not None+ dispatched = self._value(attempt, "dispatch_operation_id", 5) is not None+ if predecessor is AttemptState.RUNNING and (not started or not dispatched):+ return OperationResult(FixedResult.INVARIANT_FAILURE, None)+ owner_ref = self._value(attempt, "dispatch_owner_ref", 2)+ lease_generation = self._value(attempt, "lease_generation", 3)+ if dispatched:+ if (+ not valid_uuid(owner_ref)+ or type(lease_generation) is not int+ or not 1 <= lease_generation <= MAX_I53+ ):+ return OperationResult(FixedResult.INVARIANT_FAILURE, None)+ elif owner_ref is not None or lease_generation != 0:+ return OperationResult(FixedResult.INVARIANT_FAILURE, None)+ cancellation_revision = None+ if current is AttemptState.CANCELLING:+ cancellation_revision = self._value(+ attempt,+ "cancellation_request_revision",+ 6,+ )+ if (+ type(cancellation_revision) is not int+ or not 1 <= cancellation_revision <= MAX_I53+ ):+ return OperationResult(FixedResult.INVARIANT_FAILURE, None)++ prepared_budget_settlement = await self._derive_terminal_v3_budget_settlement(+ connection,+ intent,+ operation_id,+ attempt_revision=revision,+ )+ logical = await self._fetchrow(+ connection,+ "SELECT campaign_id,closure_operation_id,revision FROM logical_executions "+ "WHERE id=?" + suffix,+ (intent.logical_execution_id,),+ )+ if logical is None or self._value(logical, "campaign_id", 0) != intent.campaign_id:+ return OperationResult(FixedResult.CONFLICT_STATE, revision)+ if self._value(logical, "closure_operation_id", 1) is not None:+ return OperationResult(FixedResult.ALREADY_CLOSED, revision)+ logical_revision_value = self._value(logical, "revision", 2)+ if (+ type(logical_revision_value) is not int+ or not 0 <= logical_revision_value <= MAX_I53+ ):+ return OperationResult(FixedResult.INVARIANT_FAILURE, None)+ retry_eligible = bool(+ target in {AttemptState.FAILED, AttemptState.TIMED_OUT}+ and self._value(attempt, "external_effect_class", 23) == "read_only"+ and self._value(attempt, "idempotency_class", 24) == "proven_idempotent"+ and self._value(attempt, "retry_policy", 25) == "after_revalidation"+ )+ if not retry_eligible and logical_revision_value == MAX_I53:+ return OperationResult(FixedResult.INVARIANT_FAILURE, None)+ actor_subject_ref = self._value(attempt, "actor_subject_ref", 19)+ actor_user_id = self._value(attempt, "actor_user_id", 20)+ actor_authority_revision = self._value(+ attempt,+ "actor_authority_revision",+ 21,+ )+ if (+ not valid_uuid(actor_subject_ref)+ or not valid_uuid(actor_user_id)+ or type(actor_authority_revision) is not int+ or not 0 <= actor_authority_revision <= MAX_I53+ ):+ return OperationResult(FixedResult.INVARIANT_FAILURE, None)++ outbox_id = self._derived_v3_uuid(operation_id, "terminal-outbox")+ publication_key = self._derived_v3_uuid(+ operation_id,+ "terminal-publication",+ )+ transition = TransitionRequest(+ attempt_id=intent.attempt_id,+ expected_revision=intent.expected_attempt_revision,+ target_state=target,+ operation_id=operation_id,+ owner_ref=str(owner_ref) if dispatched else None,+ lease_generation=int(lease_generation) if dispatched else None,+ cancellation_request_revision=cancellation_revision,+ outcome_code=intent.outcome_code,+ authoritative_proof=authoritative_proof,+ campaign_id=intent.campaign_id,+ )+ request = TerminalCommitRequest(+ logical_execution_id=intent.logical_execution_id,+ campaign_id=intent.campaign_id,+ outbox_id=outbox_id,+ publication_key=publication_key,+ transition=transition,+ budgets=prepared_budget_settlement.request,+ outputs=outputs,+ )+ return await self._commit_terminal_attempt_same_transaction(+ connection,+ request,+ receipt_spec=spec,+ logical=logical,+ attempt=attempt,+ current=current,+ retry_eligible=retry_eligible,+ result_binding_domain=_TERMINAL_COMMIT_RESULT_DOMAIN_V3,+ prepared_budget_settlement=prepared_budget_settlement,+ additional_result_fields=(+ (+ "terminal_commit_contract_version",+ TERMINAL_COMMIT_CONTRACT_VERSION_V3,+ ),+ ("operation_id", operation_id),+ ("operation_code", operation_code),+ ("campaign_id", intent.campaign_id),+ ("logical_execution_id", intent.logical_execution_id),+ ("attempt_id", intent.attempt_id),+ ("outcome_code", intent.outcome_code.value),+ ("authoritative_proof", authoritative_proof),+ ("retry_eligible", retry_eligible),+ (+ "execution_result_digest_present",+ intent.execution_result_digest is not None,+ ),+ ("execution_result_digest", intent.execution_result_digest),+ ("publication_key", publication_key),+ ),+ )+ except _AbortOperationError as aborted:+ return aborted.result++ async def commit_terminal_attempt(self, request: TerminalCommitRequest) -> OperationResult:+ """Atomically settle budgets, bind outputs, close state, and enqueue publication."""+ terminal_states = {+ AttemptState.SUCCEEDED,+ AttemptState.PARTIAL,+ AttemptState.FAILED,+ AttemptState.SKIPPED,+ AttemptState.CANCELLED,+ AttemptState.TIMED_OUT,+ AttemptState.INDETERMINATE,+ }+ if (+ type(request) is not TerminalCommitRequest+ or not all(+ valid_uuid(value)+ for value in (+ request.logical_execution_id,+ request.campaign_id,+ request.outbox_id,+ request.publication_key,+ )+ )+ or validate_transition_request(request.transition) is not None+ or request.transition.target_state not in terminal_states+ or request.transition.outbox_id is not None+ or request.transition.publication_key is not None+ or request.transition.campaign_id != request.campaign_id+ or not self._valid_budget_settlement(request.budgets)+ or request.budgets.attempt_id != request.transition.attempt_id+ or request.budgets.campaign_id != request.campaign_id+ or not self._valid_output_observations(request.outputs)+ ):+ return OperationResult(FixedResult.INVALID_CONTRACT, None)+ target = request.transition.target_state+ if target is AttemptState.PARTIAL and not request.outputs:+ return OperationResult(FixedResult.INVALID_CONTRACT, None)+ if target not in {AttemptState.SUCCEEDED, AttemptState.PARTIAL} and request.outputs:+ return OperationResult(FixedResult.INVALID_CONTRACT, None)+ spec = self._terminal_receipt_spec(request)+ suffix = " FOR UPDATE" if self._dialect == "postgresql" else ""+ try:+ async with self._transaction() as connection:+ await self._acquire_transaction_key(connection, request.transition.operation_id)+ replay = await self._classify_receipt(+ connection,+ spec,+ current_revision=request.transition.expected_revision,+ )+ if replay is not None:+ return replay+ context = await self._lock_attempt_prefix(connection, request.transition.attempt_id)+ if context is None:+ return OperationResult(FixedResult.NOT_FOUND_OR_PURGED, None)+ (+ context_logical,+ context_campaign,+ context_actor_user_id,+ context_actor_subject_ref,+ context_actor_authority_revision,+ ) = context+ if (+ context_logical != request.logical_execution_id+ or context_campaign != request.campaign_id+ or (+ request.transition.actor_subject_ref is not None+ and (+ context_actor_subject_ref != request.transition.actor_subject_ref+ or context_actor_user_id != request.transition.actor_user_id+ or context_actor_authority_revision+ != request.transition.actor_authority_revision+ )+ )+ ):+ return OperationResult(FixedResult.CONFLICT_STATE, None)+ logical = await self._fetchrow(+ connection,+ "SELECT campaign_id,closure_operation_id,revision FROM logical_executions "+ "WHERE id=?" + suffix,+ (request.logical_execution_id,),+ )+ if logical is None or self._value(logical, "campaign_id", 0) != request.campaign_id:+ return OperationResult(FixedResult.CONFLICT_STATE, None)+ row = await self._fetchrow(+ connection,+ "SELECT state,revision,dispatch_owner_ref,lease_generation,"+ "start_operation_id,dispatch_operation_id,"+ "cancellation_request_revision,recovery_deadline_at,timeout_limit_ms,"+ "lease_expires_at,queue_operation_id,cancellation_request_operation_id,"+ "cancellation_ack_operation_id,timeout_operation_id,"+ "settlement_pending_operation_id,terminal_operation_id,"+ "logical_execution_id,campaign_id,retry_disposition,"+ "actor_subject_ref,actor_user_id,actor_authority_revision,closes_logical,"+ "external_effect_class,idempotency_class,retry_policy "+ "FROM execution_attempts WHERE id=?" + suffix,+ (request.transition.attempt_id,),+ )+ if row is None or (+ self._value(row, "logical_execution_id", 16) != request.logical_execution_id+ or self._value(row, "campaign_id", 17) != request.campaign_id+ ):+ return OperationResult(FixedResult.CONFLICT_STATE, None)+ current = AttemptState(str(self._value(row, "state", 0)))+ revision = int(self._value(row, "revision", 1))+ if current is target:+ return OperationResult(FixedResult.CONFLICT_OPERATION, revision)+ if self._value(logical, "closure_operation_id", 1) is not None:+ return OperationResult(FixedResult.ALREADY_CLOSED, revision)+ if revision != request.transition.expected_revision:+ return OperationResult(FixedResult.CONFLICT_REVISION, revision)+ if (current, target) not in LEGAL_TRANSITIONS:+ return OperationResult(FixedResult.CONFLICT_STATE, revision)+ started = self._value(row, "start_operation_id", 4) is not None+ dispatched = self._value(row, "dispatch_operation_id", 5) is not None+ if (+ target in {AttemptState.SUCCEEDED, AttemptState.PARTIAL, AttemptState.TIMED_OUT}+ and not started+ ):+ return OperationResult(FixedResult.CONFLICT_STATE, revision)+ outcome_by_target = {+ AttemptState.SUCCEEDED: OutcomeCode.CONFIRMED_SUCCESS,+ AttemptState.PARTIAL: OutcomeCode.CONFIRMED_PARTIAL,+ AttemptState.SKIPPED: OutcomeCode.ORCHESTRATION_SKIPPED,+ AttemptState.CANCELLED: OutcomeCode.CONFIRMED_CANCELLED_NO_RESULT,+ AttemptState.TIMED_OUT: OutcomeCode.CONFIRMED_TIMEOUT_TERMINATED,+ AttemptState.INDETERMINATE: OutcomeCode.UNKNOWN_AFTER_RECOVERY,+ }+ required_outcome = outcome_by_target.get(target)+ if target is AttemptState.FAILED:+ required_outcome = (+ OutcomeCode.CONFIRMED_FAILURE+ if started+ else OutcomeCode.CONFIRMED_FAILURE_NO_DISPATCH+ )+ if request.transition.outcome_code is not required_outcome:+ return OperationResult(FixedResult.INVALID_CONTRACT, revision)+ proof = request.transition.authoritative_proof+ result_proofs = {+ "local_completion",+ "process_group_exit",+ "worker_terminal_ack",+ "external_settlement_ack",+ }+ if target in {AttemptState.SUCCEEDED, AttemptState.PARTIAL} and (+ proof not in result_proofs+ ):+ return OperationResult(FixedResult.INVALID_CONTRACT, revision)+ if target is AttemptState.FAILED and (+ (started and proof not in result_proofs)+ or (not started and proof != "no_dispatch")+ ):+ return OperationResult(FixedResult.INVALID_CONTRACT, revision)+ if target is AttemptState.SKIPPED and proof != "no_dispatch":+ return OperationResult(FixedResult.INVALID_CONTRACT, revision)+ if target is AttemptState.CANCELLED and proof != "cancellation_no_result_ack":+ return OperationResult(FixedResult.INVALID_CONTRACT, revision)+ if target is AttemptState.TIMED_OUT and proof != "timeout_termination_ack":+ return OperationResult(FixedResult.INVALID_CONTRACT, revision)+ if target is AttemptState.INDETERMINATE and proof != "bounded_recovery_exhausted":+ return OperationResult(FixedResult.INVALID_CONTRACT, revision)+ owner_required = dispatched and target is not AttemptState.INDETERMINATE+ if owner_required:+ if request.transition.owner_ref != self._value(row, "dispatch_owner_ref", 2):+ return OperationResult(FixedResult.CONFLICT_OWNER, revision)+ if request.transition.lease_generation != int(+ self._value(row, "lease_generation", 3)+ ):+ return OperationResult(FixedResult.CONFLICT_GENERATION, revision)+ if current is AttemptState.CANCELLING and (+ request.transition.cancellation_request_revision+ != int(self._value(row, "cancellation_request_revision", 6))+ ):+ return OperationResult(FixedResult.CONFLICT_REVISION, revision)+ if target is AttemptState.INDETERMINATE:+ if not await self._resolver_is_current_admin(connection, request.transition):+ return OperationResult(FixedResult.AUTHORITY_STALE, revision)+ current_time = await self._fetchrow(+ connection, f"SELECT {self._now_sql} AS value", ()+ )+ if int(self._value(current_time, "value", 0)) < int(+ self._value(row, "recovery_deadline_at", 7)+ ):+ return OperationResult(FixedResult.CONFLICT_STATE, revision)+ if (+ request.budgets.noise_actual != request.budgets.noise_units+ or request.budgets.exfiltration_actual != request.budgets.exfiltration_units+ ):+ return OperationResult(FixedResult.INVALID_CONTRACT, revision)+ retry_eligible = bool(+ target in {AttemptState.FAILED, AttemptState.TIMED_OUT}+ and self._value(row, "external_effect_class", 23) == "read_only"+ and self._value(row, "idempotency_class", 24) == "proven_idempotent"+ and self._value(row, "retry_policy", 25) == "after_revalidation"+ )+ return await self._commit_terminal_attempt_same_transaction(+ connection,+ request,+ receipt_spec=spec,+ logical=logical,+ attempt=row,+ current=current,+ retry_eligible=retry_eligible,+ )+ except _AbortOperationError as aborted:+ return aborted.result++ async def _insert_output_links(+ self,+ connection: Any,+ campaign_id: str,+ attempt_id: str,+ outputs: tuple[OutputObservation, ...],+ ) -> tuple[int, int, int, int]:+ table_columns = {+ OutputKind.FINDING: ("findings", "finding_id", 0),+ OutputKind.CREDENTIAL: ("credentials", "credential_id", 1),+ OutputKind.HOST: ("hosts", "host_id", 2),+ OutputKind.ARTIFACT: ("loot", "loot_id", 3),+ }+ counts = [0, 0, 0, 0]+ suffix = " FOR UPDATE" if self._dialect == "postgresql" else ""+ host_ids = tuple(+ sorted(output.target_id for output in outputs if output.kind is OutputKind.HOST)+ )+ if host_ids:+ host_rows = await self._fetchall(+ connection,+ "SELECT id FROM hosts WHERE campaign_id=? AND id IN ("+ + ",".join("?" for _ in host_ids)+ + ") ORDER BY ip_address,id"+ + suffix,+ (campaign_id, *host_ids),+ )+ if tuple(sorted(str(self._value(row, "id", 0)) for row in host_rows)) != host_ids:+ raise _AbortOperationError(OperationResult(FixedResult.CONFLICT_STATE, None))+ non_hosts = tuple(+ sorted(+ (output for output in outputs if output.kind is not OutputKind.HOST),+ key=lambda item: (item.kind.value, item.target_id),+ )+ )+ for output in non_hosts:+ table, _column, _count_index = table_columns[output.kind]+ target = await self._fetchrow(+ connection,+ f"SELECT id FROM {table} WHERE campaign_id=? AND id=?" + suffix,+ (campaign_id, output.target_id),+ )+ if target is None:+ raise _AbortOperationError(OperationResult(FixedResult.CONFLICT_STATE, None))+ for output in sorted(outputs, key=lambda item: (item.kind.value, item.target_id)):+ _table, column, count_index = table_columns[output.kind]+ values: dict[str, Any] = {+ "finding_id": None,+ "credential_id": None,+ "host_id": None,+ "loot_id": None,+ }+ values[column] = output.target_id+ inserted = await self.update_exact_set(+ connection,+ "INSERT INTO execution_output_links("+ "id,attempt_id,campaign_id,finding_id,credential_id,host_id,loot_id) "+ "VALUES(?,?,?,?,?,?,?) ON CONFLICT(id) DO NOTHING RETURNING id,attempt_id",+ (+ output.link_id,+ attempt_id,+ campaign_id,+ values["finding_id"],+ values["credential_id"],+ values["host_id"],+ values["loot_id"],+ ),+ expected=(("id", output.link_id), ("attempt_id", attempt_id)),+ zero_classifier=None,+ )+ if inserted is None:+ raise _AbortOperationError(OperationResult(FixedResult.CONFLICT_OPERATION, None))+ counts[count_index] += 1+ return tuple(counts) # type: ignore[return-value]++ async def _insert_terminal_outbox(+ self,+ connection: Any,+ request: TerminalCommitRequest,+ counts: tuple[int, int, int, int],+ ) -> None:+ events = {+ AttemptState.SUCCEEDED: "execution_succeeded",+ AttemptState.PARTIAL: "execution_partial",+ AttemptState.FAILED: "execution_failed",+ AttemptState.SKIPPED: "execution_skipped",+ AttemptState.CANCELLED: "execution_cancelled",+ AttemptState.TIMED_OUT: "execution_timed_out",+ AttemptState.INDETERMINATE: "execution_indeterminate",+ }+ now = self._now_sql+ inserted = await self.insert_or_validate_binding(+ connection,+ "INSERT INTO execution_publication_outbox("+ "id,publication_key,attempt_id,campaign_id,event_code,is_attempt_terminal,"+ "finding_count,credential_count,host_count,artifact_count,available_at,"+ "latest_operation_id,latest_operation_code,latest_operation_base_revision,"+ "created_at) SELECT ?,?,?,?,?,"+ + ("TRUE" if self._dialect == "postgresql" else "1")+ + ",?,?,?,?,db_now,?,'insert',0,db_now FROM (SELECT "+ + now+ + " AS db_now) AS clock WHERE 1=1 ON CONFLICT(id) DO NOTHING RETURNING id,claim_revision",+ (+ request.outbox_id,+ request.publication_key,+ request.transition.attempt_id,+ request.campaign_id,+ events[request.transition.target_state],+ *counts,+ request.publication_key,+ ),+ identity=request.outbox_id,+ revision=0,+ revision_column="claim_revision",+ )+ if inserted is None:+ raise _AbortOperationError(OperationResult(FixedResult.CONFLICT_OPERATION, None))+ spec = self._receipt_spec(+ operation_id=request.outbox_id,+ operation_code="outbox_insert",+ campaign_id=request.campaign_id,+ primary_target_id=request.outbox_id,+ secondary_target_id=request.transition.attempt_id,+ fields=(+ ("publication_key", request.publication_key),+ ("event_code", events[request.transition.target_state]),+ ("terminal", True),+ ("finding_count", counts[0]),+ ("credential_count", counts[1]),+ ("host_count", counts[2]),+ ("artifact_count", counts[3]),+ ),+ )+ await self._insert_receipt(+ connection,+ spec,+ result=FixedResult.APPLIED,+ result_identity=request.outbox_id,+ result_revision=0,+ result_fields=(("publication_state", "pending"), ("claim_revision", 0)),+ )++ async def close_without_retry(self, request: ClosureRequest) -> OperationResult:+ """Permanently close a retryable terminal attempt in one locking CAS."""+ if (+ type(request) is not ClosureRequest+ or not all(+ valid_uuid(value)+ for value in (+ request.logical_execution_id,+ request.attempt_id,+ request.outbox_id,+ request.operation_id,+ request.authority_subject_ref,+ request.authority_user_id,+ request.campaign_id,+ )+ )+ or type(request.expected_attempt_revision) is not int+ or not 0 <= request.expected_attempt_revision < MAX_I53+ or type(request.authority_revision) is not int+ or not 0 <= request.authority_revision <= MAX_I53+ ):+ return OperationResult(FixedResult.INVALID_CONTRACT, None)+ spec = self._receipt_spec(+ operation_id=request.operation_id,+ operation_code="close_without_retry",+ campaign_id=request.campaign_id,+ primary_target_id=request.attempt_id,+ secondary_target_id=request.logical_execution_id,+ principal_kind="resolver",+ principal_subject_ref=request.authority_subject_ref,+ principal_user_id=request.authority_user_id,+ principal_authority_revision=request.authority_revision,+ expected_revision=request.expected_attempt_revision,+ fields=(+ ("outbox_id", request.outbox_id),+ ("authority_subject_ref", request.authority_subject_ref),+ ("authority_user_id", request.authority_user_id),+ ("authority_revision", request.authority_revision),+ ),+ )+ suffix = " FOR UPDATE" if self._dialect == "postgresql" else ""+ try:+ async with self._transaction() as connection:+ await self._acquire_transaction_key(connection, request.operation_id)+ replay = await self._classify_receipt(+ connection,+ spec,+ current_revision=request.expected_attempt_revision,+ )+ if replay is not None:+ return replay+ await self._acquire_logical_attempt_transaction_keys(+ connection,+ request.logical_execution_id,+ request.attempt_id,+ )+ discovery = await self._fetchrow(+ connection,+ "SELECT campaign_id,actor_user_id FROM execution_attempts "+ "WHERE logical_execution_id=? AND id=?",+ (request.logical_execution_id, request.attempt_id),+ )+ if discovery is None:+ return OperationResult(FixedResult.NOT_FOUND_OR_PURGED, None)+ campaign_id = str(self._value(discovery, "campaign_id", 0))+ actor_user_id = str(self._value(discovery, "actor_user_id", 1))+ if campaign_id != request.campaign_id:+ return OperationResult(FixedResult.CONFLICT_STATE, None)+ for sql, params in (+ ("SELECT singleton_id FROM execution_gateway_state WHERE singleton_id=1", ()),+ (+ "SELECT id FROM users WHERE id IN (?,?) ORDER BY id",+ tuple(sorted((actor_user_id, request.authority_user_id))),+ ),+ ("SELECT id FROM campaigns WHERE id=?", (campaign_id,)),+ (+ "SELECT user_id FROM execution_actor_authority_revisions "+ "WHERE user_id IN (?,?) ORDER BY user_id",+ tuple(sorted((actor_user_id, request.authority_user_id))),+ ),+ (+ "SELECT campaign_id FROM campaign_execution_authority_revisions "+ "WHERE campaign_id=?",+ (campaign_id,),+ ),+ ):+ await self._fetchall(connection, sql + suffix, params)+ logical = await self._fetchrow(+ connection,+ "SELECT campaign_id,highest_attempt_ordinal,revision,"+ "closure_operation_id,closing_attempt_id "+ "FROM logical_executions WHERE id=?" + suffix,+ (request.logical_execution_id,),+ )+ attempt = await self._fetchrow(+ connection,+ "SELECT campaign_id,ordinal,revision,state,closes_logical,"+ "retry_disposition FROM execution_attempts "+ "WHERE logical_execution_id=? AND id=?" + suffix,+ (request.logical_execution_id, request.attempt_id),+ )+ if logical is None or attempt is None:+ return OperationResult(FixedResult.NOT_FOUND_OR_PURGED, None)+ revision = int(self._value(attempt, "revision", 2))+ logical_revision = int(self._value(logical, "revision", 2))+ closure_operation = self._value(logical, "closure_operation_id", 3)+ if closure_operation is not None:+ return OperationResult(FixedResult.ALREADY_CLOSED, revision)+ if revision != request.expected_attempt_revision:+ return OperationResult(FixedResult.CONFLICT_REVISION, revision)+ child = await self._fetchrow(+ connection,+ "SELECT id FROM execution_attempts WHERE logical_execution_id=? "+ "AND parent_attempt_id=?" + suffix,+ (request.logical_execution_id, request.attempt_id),+ )+ if (+ self._value(logical, "campaign_id", 0) != campaign_id+ or self._value(attempt, "campaign_id", 0) != campaign_id+ or int(self._value(attempt, "ordinal", 1))+ != int(self._value(logical, "highest_attempt_ordinal", 1))+ or bool(self._value(attempt, "closes_logical", 4))+ or self._value(attempt, "retry_disposition", 5) != "eligible"+ or self._value(attempt, "state", 3) not in {"failed", "timed_out"}+ or child is not None+ ):+ return OperationResult(FixedResult.CONFLICT_STATE, revision)+ authority = await self._fetchrow(+ connection,+ "SELECT u.id,u.role,u.is_active,a.revision "+ "FROM users u JOIN execution_actor_authority_revisions a "+ "ON a.user_id=u.id WHERE u.id=?" + suffix,+ (request.authority_user_id,),+ )+ if not (+ authority is not None+ and self._value(authority, "id", 0) == request.authority_subject_ref+ and self._value(authority, "role", 1) == "admin"+ and bool(self._value(authority, "is_active", 2))+ and int(self._value(authority, "revision", 3)) == request.authority_revision+ ):+ return OperationResult(FixedResult.AUTHORITY_STALE, revision)+ now = self._now_sql+ async with self._savepoint(connection):+ updated_attempt = await self.cas_update_one(+ connection,+ "UPDATE execution_attempts SET closes_logical="+ + ("TRUE" if self._dialect == "postgresql" else "1")+ + ",retry_disposition='closed_without_retry',revision=revision+1 "+ "WHERE id=? AND logical_execution_id=? AND revision=? "+ "AND closes_logical="+ + ("FALSE" if self._dialect == "postgresql" else "0")+ + " AND retry_disposition='eligible' "+ "RETURNING id,revision,retry_disposition",+ (+ request.attempt_id,+ request.logical_execution_id,+ request.expected_attempt_revision,+ ),+ identity=request.attempt_id,+ post_revision=request.expected_attempt_revision + 1,+ zero_classifier=lambda: self._classify_zero_row(+ connection,+ table="execution_attempts",+ identity_column="id",+ identity=request.attempt_id,+ revision_column="revision",+ checks=(+ (+ "revision",+ (request.expected_attempt_revision,),+ FixedResult.CONFLICT_REVISION,+ ),+ (+ "logical_execution_id",+ (request.logical_execution_id,),+ FixedResult.CONFLICT_STATE,+ ),+ (+ "state",+ ("failed", "timed_out"),+ FixedResult.CONFLICT_STATE,+ ),+ (+ "retry_disposition",+ ("eligible",),+ FixedResult.CONFLICT_STATE,+ ),+ ("closes_logical", (False,), FixedResult.CONFLICT_STATE),+ ),+ receipt_spec=spec,+ authority_columns=(+ "actor_user_id",+ "actor_authority_revision",+ "actor_role",+ ),+ authority_before_checks=True,+ expected_authority_user_id=request.authority_user_id,+ expected_authority_revision=request.authority_revision,+ expected_authority_role="admin",+ ),+ )+ if updated_attempt is None:+ raise _AbortOperationError(+ OperationResult(FixedResult.CONFLICT_STATE, revision)+ )+ updated_logical = await self.cas_update_one(+ connection,+ "UPDATE logical_executions SET closure_operation_id=?,"+ "closure_authority_subject_ref=?,closure_authority_user_id=?,"+ "closure_authority_revision=?,closing_attempt_id=?,closed_at="+ + now+ + ",revision=revision+1 WHERE id=? AND campaign_id=? "+ "AND revision=? AND closure_operation_id IS NULL "+ "RETURNING id,revision,closing_attempt_id",+ (+ request.operation_id,+ request.authority_subject_ref,+ request.authority_user_id,+ request.authority_revision,+ request.attempt_id,+ request.logical_execution_id,+ campaign_id,+ logical_revision,+ ),+ identity=request.logical_execution_id,+ post_revision=logical_revision + 1,+ zero_classifier=lambda: self._classify_zero_row(+ connection,+ table="logical_executions",+ identity_column="id",+ identity=request.logical_execution_id,+ revision_column="revision",+ checks=(+ (+ "campaign_id",+ (campaign_id,),+ FixedResult.CONFLICT_STATE,+ ),+ (+ "closure_operation_id",+ (None,),+ FixedResult.ALREADY_CLOSED,+ ),+ (+ "revision",+ (logical_revision,),+ FixedResult.CONFLICT_REVISION,+ ),+ ),+ ),+ )+ if updated_logical is None:+ raise _AbortOperationError(+ OperationResult(FixedResult.ALREADY_CLOSED, revision)+ )+ inserted_outbox = await self.insert_or_validate_binding(+ connection,+ "INSERT INTO execution_publication_outbox("+ "id,publication_key,attempt_id,campaign_id,event_code,"+ "is_attempt_terminal,available_at,latest_operation_id,"+ "latest_operation_code,latest_operation_base_revision,created_at) "+ "SELECT ?,?,?,?,'logical_execution_closed',"+ + ("FALSE" if self._dialect == "postgresql" else "0")+ + ",db_now,?,'insert',0,db_now FROM (SELECT "+ + now+ + " AS db_now) AS clock WHERE 1=1 "+ "ON CONFLICT(id) DO NOTHING RETURNING id,claim_revision",+ (+ request.outbox_id,+ request.operation_id,+ request.attempt_id,+ campaign_id,+ request.operation_id,+ ),+ identity=request.outbox_id,+ revision=0,+ revision_column="claim_revision",+ )+ if inserted_outbox is None:+ raise _AbortOperationError(+ OperationResult(FixedResult.CONFLICT_OPERATION, revision)+ )+ outbox_spec = self._receipt_spec(+ operation_id=request.outbox_id,+ operation_code="outbox_insert",+ campaign_id=campaign_id,+ primary_target_id=request.outbox_id,+ secondary_target_id=request.attempt_id,+ fields=(+ ("publication_key", request.operation_id),+ ("event_code", "logical_execution_closed"),+ ("terminal", False),+ ("finding_count", 0),+ ("credential_count", 0),+ ("host_count", 0),+ ("artifact_count", 0),+ ),+ )+ await self._insert_receipt(+ connection,+ outbox_spec,+ result=FixedResult.APPLIED,+ result_identity=request.outbox_id,+ result_revision=0,+ result_fields=(+ ("publication_state", "pending"),+ ("claim_revision", 0),+ ),+ )+ await self._insert_receipt(+ connection,+ spec,+ result=FixedResult.APPLIED,+ exact_replay_code=FixedResult.REPLAYED_CLOSED,+ result_identity=request.attempt_id,+ result_revision=request.expected_attempt_revision + 1,+ secondary_result_identity=request.logical_execution_id,+ secondary_result_revision=logical_revision + 1,+ result_fields=(+ ("attempt_revision", request.expected_attempt_revision + 1),+ ("logical_revision", logical_revision + 1),+ ("closing_attempt_id", request.attempt_id),+ ),+ )+ return OperationResult(FixedResult.APPLIED, request.expected_attempt_revision + 1)+ except _AbortOperationError as aborted:+ return aborted.result++ async def transition_attempt(self, request: TransitionRequest) -> OperationResult:+ invalid = validate_transition_request(request)+ if invalid is not None:+ return OperationResult(invalid, None)+ if request.target_state not in {+ AttemptState.QUEUED,+ AttemptState.DISPATCHING,+ AttemptState.RUNNING,+ AttemptState.CANCELLING,+ }:+ return OperationResult(FixedResult.INVALID_CONTRACT, None)+ spec = self._transition_receipt_spec(request)+ try:+ async with self._transaction() as connection:+ await self._acquire_transaction_key(connection, request.operation_id)+ replay = await self._classify_receipt(+ connection, spec, current_revision=request.expected_revision+ )+ if replay is not None:+ return replay+ context = await self._lock_attempt_prefix(connection, request.attempt_id)+ if context is None:+ return OperationResult(FixedResult.NOT_FOUND_OR_PURGED, None)+ (+ _logical_id,+ campaign_id,+ actor_user_id,+ actor_subject_ref,+ actor_authority_revision,+ ) = context+ if campaign_id != request.campaign_id or (+ request.actor_subject_ref is not None+ and (+ actor_subject_ref != request.actor_subject_ref+ or actor_user_id != request.actor_user_id+ or actor_authority_revision != request.actor_authority_revision+ )+ ):+ return OperationResult(FixedResult.CONFLICT_STATE, None)+ suffix = " FOR UPDATE" if self._dialect == "postgresql" else ""+ row = await self._fetchrow(+ connection,+ "SELECT state,revision,dispatch_owner_ref,lease_generation,"+ "start_operation_id,dispatch_operation_id,"+ "cancellation_request_revision,recovery_deadline_at,timeout_limit_ms "+ ",lease_expires_at,queue_operation_id,cancellation_request_operation_id,"+ "cancellation_ack_operation_id,timeout_operation_id,"+ "settlement_pending_operation_id,terminal_operation_id "+ "FROM execution_attempts WHERE id=?" + suffix,+ (request.attempt_id,),+ )+ if row is None:+ return OperationResult(FixedResult.NOT_FOUND_OR_PURGED, None)+ current = AttemptState(str(self._value(row, "state", 0)))+ revision = int(self._value(row, "revision", 1))+ if revision != request.expected_revision:+ return OperationResult(FixedResult.CONFLICT_REVISION, revision)+ if (current, request.target_state) not in LEGAL_TRANSITIONS:+ return OperationResult(FixedResult.CONFLICT_STATE, revision)+ owner = self._value(row, "dispatch_owner_ref", 2)+ generation = int(self._value(row, "lease_generation", 3))+ started = self._value(row, "start_operation_id", 4) is not None+ dispatched = self._value(row, "dispatch_operation_id", 5) is not None+ if request.target_state is AttemptState.DISPATCHING and (+ not valid_uuid(request.owner_ref)+ or request.lease_generation is None+ or request.lease_duration_ms is None+ or request.lease_generation != generation + 1+ or request.lease_duration_ms > int(self._value(row, "timeout_limit_ms", 8))+ ):+ return OperationResult(FixedResult.INVALID_CONTRACT, revision)+ if dispatched and request.target_state not in {AttemptState.QUEUED}:+ if request.owner_ref != owner:+ return OperationResult(FixedResult.CONFLICT_OWNER, revision)+ if request.lease_generation != generation:+ return OperationResult(FixedResult.CONFLICT_GENERATION, revision)+ if current is AttemptState.CANCELLING:+ requested_revision = int(self._value(row, "cancellation_request_revision", 6))+ if request.cancellation_request_revision != requested_revision:+ return OperationResult(FixedResult.CONFLICT_REVISION, revision)+ if not dispatched and request.target_state not in {+ AttemptState.CANCELLED,+ AttemptState.FAILED,+ }:+ return OperationResult(FixedResult.CONFLICT_STATE, revision)+ if (+ dispatched+ and not started+ and request.target_state+ not in {+ AttemptState.CANCELLED,+ AttemptState.FAILED,+ AttemptState.SETTLEMENT_PENDING,+ }+ ):+ return OperationResult(FixedResult.CONFLICT_STATE, revision)+ async with self._savepoint(connection):+ return await self._apply_transition(+ connection,+ row,+ current,+ request,+ receipt_spec=spec,+ require_unexpired_lease=(+ dispatched and request.target_state is not AttemptState.QUEUED+ ),+ )+ except _AbortOperationError as aborted:+ return aborted.result++ def _transition_operation_id(self, row: Any, target: AttemptState) -> Any:+ if (+ target+ in {+ AttemptState.SUCCEEDED,+ AttemptState.PARTIAL,+ AttemptState.FAILED,+ }+ and self._value(row, "cancellation_ack_operation_id", 12) is not None+ ):+ return self._value(row, "cancellation_ack_operation_id", 12)+ index_by_target = {+ AttemptState.QUEUED: 10,+ AttemptState.DISPATCHING: 5,+ AttemptState.RUNNING: 4,+ AttemptState.CANCELLING: 11,+ AttemptState.SETTLEMENT_PENDING: 14,+ AttemptState.CANCELLED: 12,+ AttemptState.TIMED_OUT: 13,+ AttemptState.REJECTED: 15,+ AttemptState.BLOCKED: 15,+ AttemptState.SUCCEEDED: 15,+ AttemptState.PARTIAL: 15,+ AttemptState.FAILED: 15,+ AttemptState.SKIPPED: 15,+ AttemptState.INDETERMINATE: 15,+ }+ index = index_by_target.get(target)+ if index is None:+ return None+ names = {+ 4: "start_operation_id",+ 5: "dispatch_operation_id",+ 10: "queue_operation_id",+ 11: "cancellation_request_operation_id",+ 12: "cancellation_ack_operation_id",+ 13: "timeout_operation_id",+ 14: "settlement_pending_operation_id",+ 15: "terminal_operation_id",+ }+ return self._value(row, names[index], index)++ async def mark_expired_lease_settlement_pending(+ self, request: TransitionRequest+ ) -> OperationResult:+ return await self._enter_settlement_pending(request, require_expired=True)++ async def enter_settlement_pending(self, request: TransitionRequest) -> OperationResult:+ return await self._enter_settlement_pending(request, require_expired=False)++ async def _enter_settlement_pending(+ self, request: TransitionRequest, *, require_expired: bool+ ) -> OperationResult:+ invalid = validate_transition_request(request)+ if (+ invalid is not None+ or request.target_state is not AttemptState.SETTLEMENT_PENDING+ or not valid_uuid(request.outbox_id)+ or not valid_uuid(request.publication_key)+ ):+ return OperationResult(FixedResult.INVALID_CONTRACT, None)+ operation_code = "lease_loss" if require_expired else "settlement_pending"+ spec = self._transition_receipt_spec(request, operation_code=operation_code)+ try:+ async with self._transaction() as connection:+ await self._acquire_transaction_key(connection, request.operation_id)+ replay = await self._classify_receipt(+ connection, spec, current_revision=request.expected_revision+ )+ if replay is not None:+ return replay+ context = await self._lock_attempt_prefix(connection, request.attempt_id)+ if context is None:+ return OperationResult(FixedResult.NOT_FOUND_OR_PURGED, None)+ (+ _logical_id,+ campaign_id,+ actor_user_id,+ actor_subject_ref,+ actor_authority_revision,+ ) = context+ if campaign_id != request.campaign_id or (+ request.actor_subject_ref is not None+ and (+ actor_subject_ref != request.actor_subject_ref+ or actor_user_id != request.actor_user_id+ or actor_authority_revision != request.actor_authority_revision+ )+ ):+ return OperationResult(FixedResult.CONFLICT_STATE, None)+ suffix = " FOR UPDATE" if self._dialect == "postgresql" else ""+ row = await self._fetchrow(+ connection,+ "SELECT state,revision,dispatch_owner_ref,lease_generation,"+ "start_operation_id,dispatch_operation_id,"+ "cancellation_request_revision,recovery_deadline_at,"+ "timeout_limit_ms,lease_expires_at,settlement_pending_operation_id "+ "FROM execution_attempts WHERE id=?" + suffix,+ (request.attempt_id,),+ )+ if row is None:+ return OperationResult(FixedResult.NOT_FOUND_OR_PURGED, None)+ current = AttemptState(str(self._value(row, "state", 0)))+ revision = int(self._value(row, "revision", 1))+ if revision != request.expected_revision:+ return OperationResult(FixedResult.CONFLICT_REVISION, revision)+ if current not in {+ AttemptState.DISPATCHING,+ AttemptState.RUNNING,+ AttemptState.CANCELLING,+ }:+ return OperationResult(FixedResult.CONFLICT_STATE, revision)+ if self._value(row, "dispatch_owner_ref", 2) != request.owner_ref:+ return OperationResult(FixedResult.CONFLICT_OWNER, revision)+ if int(self._value(row, "lease_generation", 3)) != request.lease_generation:+ return OperationResult(FixedResult.CONFLICT_GENERATION, revision)+ if require_expired:+ current_time = await self._fetchrow(+ connection, f"SELECT {self._now_sql} AS value", ()+ )+ if int(self._value(current_time, "value", 0)) < int(+ self._value(row, "lease_expires_at", 9)+ ):+ return OperationResult(FixedResult.CONFLICT_STATE, revision)+ async with self._savepoint(connection):+ result = await self._apply_transition(+ connection, row, current, request, zero_receipt_spec=spec+ )+ if result.result is not FixedResult.APPLIED:+ raise _AbortOperationError(result)+ if require_expired:+ exact = await self.update_exact_set(+ connection,+ "UPDATE execution_attempts SET error_action_code='worker_loss' "+ "WHERE id=? AND revision=? AND state='settlement_pending' "+ "RETURNING id,revision,error_action_code",+ (request.attempt_id, request.expected_revision + 1),+ expected=(+ ("id", request.attempt_id),+ ("revision", request.expected_revision + 1),+ ("error_action_code", "worker_loss"),+ ),+ zero_classifier=lambda: self._classify_zero_row(+ connection,+ table="execution_attempts",+ identity_column="id",+ identity=request.attempt_id,+ revision_column="revision",+ checks=(+ (+ "revision",+ (request.expected_revision + 1,),+ FixedResult.CONFLICT_REVISION,+ ),+ (+ "state",+ ("settlement_pending",),+ FixedResult.CONFLICT_STATE,+ ),+ ),+ ),+ )+ if exact is None:+ raise _AbortOperationError(+ OperationResult(FixedResult.CONFLICT_STATE, revision)+ )+ await self._insert_recovery_outbox(connection, request, campaign_id)+ await self._insert_receipt(+ connection,+ spec,+ result=FixedResult.APPLIED,+ result_identity=request.attempt_id,+ result_revision=request.expected_revision + 1,+ secondary_result_identity=request.outbox_id,+ secondary_result_revision=0,+ result_fields=(+ ("state", AttemptState.SETTLEMENT_PENDING.value),+ ("revision", request.expected_revision + 1),+ ("outbox_id", request.outbox_id),+ ),+ )+ return result+ except _AbortOperationError as aborted:+ return aborted.result++ async def _insert_recovery_outbox(+ self, connection: Any, request: TransitionRequest, campaign_id: str+ ) -> None:+ now = self._now_sql+ inserted = await self.insert_or_validate_binding(+ connection,+ "INSERT INTO execution_publication_outbox("+ "id,publication_key,attempt_id,campaign_id,event_code,"+ "is_attempt_terminal,available_at,latest_operation_id,"+ "latest_operation_code,latest_operation_base_revision,created_at) "+ "SELECT ?,?,?,a.campaign_id,'recovery_required',"+ + ("FALSE" if self._dialect == "postgresql" else "0")+ + ",db_now,?,'insert',0,db_now FROM execution_attempts a,"+ "(SELECT " + now + " AS db_now) AS clock WHERE a.id=? "+ "ON CONFLICT(id) DO NOTHING RETURNING id,claim_revision",+ (+ request.outbox_id,+ request.publication_key,+ request.attempt_id,+ request.publication_key,+ request.attempt_id,+ ),+ identity=request.outbox_id,+ revision=0,+ revision_column="claim_revision",+ )+ if inserted is None:+ raise _AbortOperationError(OperationResult(FixedResult.CONFLICT_OPERATION, None))+ spec = self._receipt_spec(+ operation_id=request.outbox_id,+ operation_code="outbox_insert",+ campaign_id=campaign_id,+ primary_target_id=request.outbox_id,+ secondary_target_id=request.attempt_id,+ fields=(+ ("publication_key", request.publication_key),+ ("event_code", "recovery_required"),+ ("terminal", False),+ ("finding_count", 0),+ ("credential_count", 0),+ ("host_count", 0),+ ("artifact_count", 0),+ ),+ )+ await self._insert_receipt(+ connection,+ spec,+ result=FixedResult.APPLIED,+ result_identity=request.outbox_id,+ result_revision=0,+ result_fields=(("publication_state", "pending"), ("claim_revision", 0)),+ )++ async def _resolver_is_current_admin(self, connection: Any, request: TransitionRequest) -> bool:+ if (+ not valid_uuid(request.resolver_subject_ref)+ or not valid_uuid(request.resolver_user_id)+ or request.resolver_authority_revision is None+ ):+ return False+ row = await self._fetchrow(+ connection,+ "SELECT u.id,u.role,u.is_active,a.revision "+ "FROM users u JOIN execution_actor_authority_revisions a "+ "ON a.user_id=u.id WHERE u.id=?",+ (request.resolver_user_id,),+ )+ return bool(+ row is not None+ and self._value(row, "id", 0) == request.resolver_subject_ref+ and self._value(row, "role", 1) == "admin"+ and bool(self._value(row, "is_active", 2))+ and int(self._value(row, "revision", 3)) == request.resolver_authority_revision+ )++ async def _apply_transition(+ self,+ connection: Any,+ row: Any,+ current: AttemptState,+ request: TransitionRequest,+ *,+ receipt_spec: _ReceiptSpec | None = None,+ zero_receipt_spec: _ReceiptSpec | None = None,+ require_unexpired_lease: bool = False,+ retry_eligible: bool = False,+ ) -> OperationResult:+ now = (+ "floor(extract(epoch FROM clock_timestamp())*1000)::bigint"+ if self._dialect == "postgresql"+ else "CAST((julianday('now')-2440587.5)*86400000 AS INTEGER)"+ )+ target = request.target_state+ fields: list[str] = ["state=?", "revision=revision+1"]+ params: list[Any] = [target.value]+ terminal = target in {+ AttemptState.SUCCEEDED,+ AttemptState.PARTIAL,+ AttemptState.FAILED,+ AttemptState.SKIPPED,+ AttemptState.CANCELLED,+ AttemptState.TIMED_OUT,+ AttemptState.INDETERMINATE,+ }+ if target is AttemptState.QUEUED:+ fields += ["queue_operation_id=?", f"queued_at={now}"]+ params.append(request.operation_id)+ elif target is AttemptState.DISPATCHING:+ fields += [+ "dispatch_operation_id=?",+ "dispatch_owner_ref=?",+ "lease_generation=?",+ "dispatch_lease_duration_ms=?",+ f"dispatching_at={now}",+ f"lease_expires_at={now}+?",+ ]+ params.extend(+ (+ request.operation_id,+ request.owner_ref,+ request.lease_generation,+ request.lease_duration_ms,+ request.lease_duration_ms,+ )+ )+ elif target is AttemptState.RUNNING:+ fields += ["start_operation_id=?", f"started_at={now}", "settlement_state='active'"]+ params.append(request.operation_id)+ elif target is AttemptState.CANCELLING:+ fields += [+ "cancellation_request_operation_id=?",+ "cancellation_request_revision=revision+1",+ f"cancellation_requested_at={now}",+ "error_action_code='operator_cancel'",+ ]+ params.append(request.operation_id)+ elif target is AttemptState.SETTLEMENT_PENDING:+ fields += [+ "settlement_pending_operation_id=?",+ f"settlement_pending_at={now}",+ f"recovery_deadline_at={now}+{RECOVERY_WINDOW_MS}",+ f"lease_invalidated_at={now}",+ "settlement_state='recovery_pending'",+ "settlement_proof_code='unresolved'",+ "termination_confirmed=" + ("FALSE" if self._dialect == "postgresql" else "0"),+ "error_action_code='recovery_required'",+ ]+ params.append(request.operation_id)+ elif terminal:+ if target is AttemptState.TIMED_OUT:+ fields += ["timeout_operation_id=?", f"timeout_observed_at={now}"]+ elif current is AttemptState.CANCELLING or target is AttemptState.CANCELLED:+ fields += [+ "cancellation_ack_operation_id=?",+ f"cancellation_acknowledged_at={now}",+ ]+ else:+ fields.append("terminal_operation_id=?")+ params.append(request.operation_id)+ fields += [f"finished_at={now}", f"settled_at={now}"]+ fields.append(+ "retry_disposition='eligible'"+ if retry_eligible+ else "retry_disposition='closed_without_retry'"+ )+ if self._value(row, "dispatch_operation_id", 5) is not None:+ fields.append(f"lease_invalidated_at=COALESCE(lease_invalidated_at,{now})")+ if request.outcome_code is not None:+ fields.append("outcome_code=?")+ params.append(request.outcome_code.value)+ if target is AttemptState.INDETERMINATE:+ fields += [+ "settlement_proof_code=?",+ "settlement_state='operator_resolved'",+ "termination_confirmed=" + ("FALSE" if self._dialect == "postgresql" else "0"),+ "resolver_subject_ref=?",+ "resolver_user_id=?",+ "resolver_authority_revision=?",+ "bounded_recovery_proof_code='recovery_sources_exhausted'",+ ]+ params.extend(+ (+ request.authoritative_proof,+ request.resolver_subject_ref,+ request.resolver_user_id,+ request.resolver_authority_revision,+ )+ )+ elif self._value(row, "start_operation_id", 4) is None:+ fields += [+ "settlement_state='not_applicable'",+ "settlement_proof_code='no_dispatch'",+ (+ "termination_confirmed=FALSE"+ if self._dialect == "postgresql"+ else "termination_confirmed=0"+ ),+ ]+ else:+ fields += [+ "settlement_proof_code=?",+ "settlement_state='settled'",+ "termination_confirmed=" + ("TRUE" if self._dialect == "postgresql" else "1"),+ ]+ params.append(request.authoritative_proof)+ where = " WHERE id=? AND revision=? AND state=?"+ params.extend([request.attempt_id, request.expected_revision, current.value])+ guarded_dispatch = (+ self._value(row, "dispatch_operation_id", 5) is not None+ and request.owner_ref is not None+ )+ if guarded_dispatch:+ where += " AND dispatch_owner_ref=? AND lease_generation=?"+ params.extend([request.owner_ref, request.lease_generation])+ if current is AttemptState.CANCELLING:+ where += " AND cancellation_request_revision=?"+ params.append(request.cancellation_request_revision)+ if require_unexpired_lease:+ where += f" AND lease_expires_at=? AND lease_expires_at>{now}"+ params.append(self._value(row, "lease_expires_at", 9))+ updated = await self.cas_update_one(+ connection,+ "UPDATE execution_attempts SET "+ + ",".join(fields)+ + where+ + " RETURNING id,revision,state,dispatch_owner_ref,lease_generation",+ tuple(params),+ identity=request.attempt_id,+ post_revision=request.expected_revision + 1,+ zero_classifier=lambda: self._classify_zero_transition(+ connection,+ row=row,+ current=current,+ request=request,+ receipt_spec=receipt_spec or zero_receipt_spec,+ guarded_dispatch=guarded_dispatch,+ require_unexpired_lease=require_unexpired_lease,+ ),+ )+ if updated is None:+ return OperationResult(FixedResult.CONFLICT_STATE, request.expected_revision)+ if receipt_spec is not None:+ await self._insert_receipt(+ connection,+ receipt_spec,+ result=FixedResult.APPLIED,+ result_identity=request.attempt_id,+ result_revision=request.expected_revision + 1,+ result_fields=(+ ("state", target.value),+ ("revision", request.expected_revision + 1),+ ("owner_ref", self._value(updated, "dispatch_owner_ref", 3)),+ ("lease_generation", int(self._value(updated, "lease_generation", 4))),+ ),+ )+ return OperationResult(FixedResult.APPLIED, request.expected_revision + 1)++ def _outbox_receipt_spec(+ self,+ request: OutboxMutation,+ operation: str,+ ) -> _ReceiptSpec:+ principal_kind = "worker" if request.owner_ref is not None else "system"+ principal_subject_ref = request.owner_ref or SYSTEM_PRINCIPAL_SUBJECT_REF+ return self._receipt_spec(+ operation_id=request.operation_id,+ operation_code="outbox_" + operation,+ campaign_id=request.campaign_id,+ primary_target_id=request.outbox_id,+ secondary_target_id=request.attempt_id,+ principal_kind=principal_kind,+ principal_subject_ref=principal_subject_ref,+ expected_revision=request.expected_revision,+ owner_ref=request.owner_ref,+ lease_generation=request.lease_generation,+ fields=(+ ("publication_key", request.publication_key),+ ("event_code", request.event_code),+ ("operation", operation),+ ("purge_poisoned", request.purge_poisoned),+ ),+ )++ def _outbox_row_matches_binding(self, row: Any, request: OutboxMutation) -> bool:+ return (+ self._value(row, "campaign_id", 10) == request.campaign_id+ and self._value(row, "attempt_id", 11) == request.attempt_id+ and self._value(row, "publication_key", 12) == request.publication_key+ and self._value(row, "event_code", 13) == request.event_code+ )++ def _outbox_result_fields(self, row: Any) -> tuple[tuple[str, str | int | bool | None], ...]:+ return (+ ("publication_state", str(self._value(row, "publication_state", 0))),+ ("claim_revision", int(self._value(row, "claim_revision", 1))),+ ("claim_owner_ref", self._value(row, "claim_owner_ref", 2)),+ ("lease_generation", int(self._value(row, "lease_generation", 3))),+ (+ "delivery_attempt_count",+ int(self._value(row, "delivery_attempt_count", 5)),+ ),+ ("failure_code", self._value(row, "failure_code", 14)),+ )++ async def _locked_outbox_row(self, connection: Any, outbox_id: str) -> Any:+ suffix = " FOR UPDATE" if self._dialect == "postgresql" else ""+ return await self._fetchrow(+ connection,+ "SELECT publication_state,claim_revision,claim_owner_ref,lease_generation,"+ "lease_expires_at,delivery_attempt_count,latest_operation_id,"+ "latest_operation_code,latest_operation_base_revision,available_at,"+ "campaign_id,attempt_id,publication_key,event_code,failure_code "+ "FROM execution_publication_outbox WHERE id=?" + suffix,+ (outbox_id,),+ )++ async def claim_outbox(+ self, request: OutboxMutation, *, reclaim: bool = False+ ) -> OperationResult:+ if not self._valid_outbox_mutation(request, require_owner=True):+ return OperationResult(FixedResult.INVALID_CONTRACT, None)+ code = "reclaim" if reclaim else "claim"+ spec = self._outbox_receipt_spec(request, code)+ now = (+ "floor(extract(epoch FROM clock_timestamp())*1000)::bigint"+ if self._dialect == "postgresql"+ else "CAST((julianday('now')-2440587.5)*86400000 AS INTEGER)"+ )+ try:+ async with self._transaction() as connection:+ await self._acquire_transaction_key(connection, request.operation_id)+ replay = await self._classify_receipt(+ connection, spec, current_revision=request.expected_revision+ )+ if replay is not None:+ return replay+ row = await self._locked_outbox_row(connection, request.outbox_id)+ if row is None:+ return OperationResult(FixedResult.NOT_FOUND_OR_PURGED, None)+ if not self._outbox_row_matches_binding(row, request):+ return OperationResult(FixedResult.CONFLICT_STATE, None)+ revision = int(self._value(row, "claim_revision", 1))+ if revision != request.expected_revision:+ return OperationResult(FixedResult.CONFLICT_REVISION, revision)+ state = str(self._value(row, "publication_state", 0))+ count = int(self._value(row, "delivery_attempt_count", 5))+ if (+ (not reclaim and state != "pending")+ or (reclaim and state != "claimed")+ or count >= 20+ ):+ return OperationResult(FixedResult.CONFLICT_STATE, revision)+ stored_generation = int(self._value(row, "lease_generation", 3))+ if stored_generation != request.lease_generation:+ return OperationResult(FixedResult.CONFLICT_GENERATION, revision)+ time_row = await self._fetchrow(connection, f"SELECT {now} AS value", ())+ db_now = int(self._value(time_row, "value", 0))+ if reclaim:+ if db_now < int(self._value(row, "lease_expires_at", 4)):+ return OperationResult(FixedResult.CONFLICT_STATE, revision)+ elif db_now < int(self._value(row, "available_at", 9)):+ return OperationResult(FixedResult.CONFLICT_STATE, revision)+ state_predicate = "claimed" if reclaim else "pending"+ time_predicate = (+ "lease_expires_at IS NOT NULL AND " + now + ">=lease_expires_at"+ if reclaim+ else "available_at IS NOT NULL AND " + now + ">=available_at"+ )+ async with self._savepoint(connection):+ updated = await self.cas_update_one(+ connection,+ "UPDATE execution_publication_outbox SET "+ "publication_state='claimed',"+ "delivery_attempt_count=delivery_attempt_count+1,"+ "available_at=NULL,failure_code=NULL,claim_owner_ref=?,"+ "lease_generation=lease_generation+1,claimed_at="+ + now+ + ",lease_expires_at="+ + now+ + f"+{OUTBOX_LEASE_MS},latest_operation_id=?,"+ "latest_operation_code=?,latest_operation_base_revision=?,"+ "claim_revision=claim_revision+1 WHERE id=? AND claim_revision=? "+ "AND publication_state=? AND lease_generation=? AND "+ + time_predicate+ + " RETURNING id,claim_revision,publication_state,claim_owner_ref,"+ "lease_generation,delivery_attempt_count,failure_code",+ (+ request.owner_ref,+ request.operation_id,+ code,+ request.expected_revision,+ request.outbox_id,+ request.expected_revision,+ state_predicate,+ request.lease_generation,+ ),+ identity=request.outbox_id,+ post_revision=request.expected_revision + 1,+ revision_column="claim_revision",+ zero_classifier=lambda: self._classify_zero_outbox(+ connection,+ outbox_id=request.outbox_id,+ expected_revision=request.expected_revision,+ expected_state=state_predicate,+ expected_generation=request.lease_generation,+ time_requirement="expired" if reclaim else "available",+ maximum_delivery_count=20,+ ),+ )+ if updated is None:+ raise _AbortOperationError(+ OperationResult(FixedResult.CONFLICT_STATE, revision)+ )+ result_fields = (+ ("publication_state", str(self._value(updated, "publication_state", 2))),+ ("claim_revision", request.expected_revision + 1),+ ("claim_owner_ref", self._value(updated, "claim_owner_ref", 3)),+ ("lease_generation", int(self._value(updated, "lease_generation", 4))),+ (+ "delivery_attempt_count",+ int(self._value(updated, "delivery_attempt_count", 5)),+ ),+ ("failure_code", self._value(updated, "failure_code", 6)),+ )+ await self._insert_receipt(+ connection,+ spec,+ result=FixedResult.APPLIED,+ result_identity=request.outbox_id,+ result_revision=request.expected_revision + 1,+ result_fields=result_fields,+ )+ return OperationResult(FixedResult.APPLIED, revision + 1)+ except _AbortOperationError as aborted:+ return aborted.result++ @staticmethod+ def _valid_outbox_mutation(request: object, *, require_owner: bool) -> bool:+ return (+ type(request) is OutboxMutation+ and valid_uuid(request.outbox_id)+ and valid_uuid(request.operation_id)+ and type(request.expected_revision) is int+ and 0 <= request.expected_revision < MAX_I53+ and valid_uuid(request.campaign_id)+ and valid_uuid(request.attempt_id)+ and valid_uuid(request.publication_key)+ and request.event_code+ in {+ "recovery_required",+ "execution_rejected",+ "execution_blocked",+ "execution_succeeded",+ "execution_partial",+ "execution_failed",+ "execution_skipped",+ "execution_cancelled",+ "execution_timed_out",+ "execution_indeterminate",+ "logical_execution_closed",+ }+ and (request.purge_poisoned is None or type(request.purge_poisoned) is bool)+ and (request.owner_ref is None) == (request.lease_generation is None)+ and (+ request.owner_ref is None+ or (+ valid_uuid(request.owner_ref)+ and type(request.lease_generation) is int+ and 0 <= request.lease_generation <= MAX_I53+ )+ )+ and (+ not require_owner+ or (+ valid_uuid(request.owner_ref)+ and type(request.lease_generation) is int+ and 0 <= request.lease_generation <= MAX_I53+ )+ )+ )++ async def poison_expired_attempt_twenty(self, request: OutboxMutation) -> OperationResult:+ if (+ not self._valid_outbox_mutation(request, require_owner=False)+ or request.owner_ref is not None+ or request.lease_generation is not None+ ):+ return OperationResult(FixedResult.INVALID_CONTRACT, None)+ spec = self._outbox_receipt_spec(request, "poison")+ now = (+ "floor(extract(epoch FROM clock_timestamp())*1000)::bigint"+ if self._dialect == "postgresql"+ else "CAST((julianday('now')-2440587.5)*86400000 AS INTEGER)"+ )+ try:+ async with self._transaction() as connection:+ await self._acquire_transaction_key(connection, request.operation_id)+ replay = await self._classify_receipt(+ connection, spec, current_revision=request.expected_revision+ )+ if replay is not None:+ return replay+ row = await self._locked_outbox_row(connection, request.outbox_id)+ if row is None:+ return OperationResult(FixedResult.NOT_FOUND_OR_PURGED, None)+ if not self._outbox_row_matches_binding(row, request):+ return OperationResult(FixedResult.CONFLICT_STATE, None)+ revision = int(self._value(row, "claim_revision", 1))+ if revision != request.expected_revision:+ return OperationResult(FixedResult.CONFLICT_REVISION, revision)+ if (+ str(self._value(row, "publication_state", 0)) != "claimed"+ or int(self._value(row, "delivery_attempt_count", 5)) != 20+ ):+ return OperationResult(FixedResult.CONFLICT_STATE, revision)+ expiry = int(self._value(row, "lease_expires_at", 4))+ time_row = await self._fetchrow(connection, f"SELECT {now} AS value", ())+ if int(self._value(time_row, "value", 0)) < expiry:+ return OperationResult(FixedResult.CONFLICT_STATE, revision)+ async with self._savepoint(connection):+ updated = await self.cas_update_one(+ connection,+ "UPDATE execution_publication_outbox SET publication_state='poisoned',"+ "claim_owner_ref=NULL,lease_expires_at=NULL,available_at=NULL,"+ "poisoned_at="+ + now+ + ",failure_code='delivery_attempt_limit',latest_operation_id=?,"+ "latest_operation_code='poison',latest_operation_base_revision=?,"+ "claim_revision=claim_revision+1 WHERE id=? AND claim_revision=? "+ "AND publication_state='claimed' AND delivery_attempt_count=20 "+ "AND lease_expires_at IS NOT NULL AND "+ + now+ + ">=lease_expires_at RETURNING id,claim_revision,publication_state,"+ "claim_owner_ref,lease_generation,delivery_attempt_count,failure_code",+ (+ request.operation_id,+ request.expected_revision,+ request.outbox_id,+ request.expected_revision,+ ),+ identity=request.outbox_id,+ post_revision=request.expected_revision + 1,+ revision_column="claim_revision",+ zero_classifier=lambda: self._classify_zero_outbox(+ connection,+ outbox_id=request.outbox_id,+ expected_revision=request.expected_revision,+ expected_state="claimed",+ time_requirement="expired",+ expected_delivery_count=20,+ ),+ )+ if updated is None:+ raise _AbortOperationError(+ OperationResult(FixedResult.CONFLICT_STATE, revision)+ )+ result_fields = (+ ("publication_state", "poisoned"),+ ("claim_revision", request.expected_revision + 1),+ ("claim_owner_ref", None),+ ("lease_generation", int(self._value(updated, "lease_generation", 4))),+ ("delivery_attempt_count", 20),+ ("failure_code", "delivery_attempt_limit"),+ )+ await self._insert_receipt(+ connection,+ spec,+ result=FixedResult.APPLIED,+ result_identity=request.outbox_id,+ result_revision=request.expected_revision + 1,+ result_fields=result_fields,+ )+ return OperationResult(FixedResult.APPLIED, revision + 1)+ except _AbortOperationError as aborted:+ return aborted.result++ async def renew_outbox(self, request: OutboxMutation) -> OperationResult:+ return await self._mutate_claimed_outbox(request, "renew")++ async def publish_outbox(self, request: OutboxMutation) -> OperationResult:+ return await self._mutate_claimed_outbox(request, "publish")++ async def fail_outbox(self, request: OutboxMutation, *, retryable: bool) -> OperationResult:+ return await self._mutate_claimed_outbox(+ request,+ "retryable_failure" if retryable else "nonretryable_failure",+ )++ async def _mutate_claimed_outbox(+ self, request: OutboxMutation, operation: str+ ) -> OperationResult:+ if operation not in {+ "renew",+ "publish",+ "retryable_failure",+ "nonretryable_failure",+ } or not self._valid_outbox_mutation(request, require_owner=True):+ return OperationResult(FixedResult.INVALID_CONTRACT, None)+ spec = self._outbox_receipt_spec(request, operation)+ now = (+ "floor(extract(epoch FROM clock_timestamp())*1000)::bigint"+ if self._dialect == "postgresql"+ else "CAST((julianday('now')-2440587.5)*86400000 AS INTEGER)"+ )+ try:+ async with self._transaction() as connection:+ await self._acquire_transaction_key(connection, request.operation_id)+ replay = await self._classify_receipt(+ connection, spec, current_revision=request.expected_revision+ )+ if replay is not None:+ return replay+ row = await self._locked_outbox_row(connection, request.outbox_id)+ if row is None:+ return OperationResult(FixedResult.NOT_FOUND_OR_PURGED, None)+ if not self._outbox_row_matches_binding(row, request):+ return OperationResult(FixedResult.CONFLICT_STATE, None)+ revision = int(self._value(row, "claim_revision", 1))+ if revision != request.expected_revision:+ return OperationResult(FixedResult.CONFLICT_REVISION, revision)+ if str(self._value(row, "publication_state", 0)) != "claimed":+ return OperationResult(FixedResult.CONFLICT_STATE, revision)+ if self._value(row, "claim_owner_ref", 2) != request.owner_ref:+ return OperationResult(FixedResult.CONFLICT_OWNER, revision)+ if int(self._value(row, "lease_generation", 3)) != request.lease_generation:+ return OperationResult(FixedResult.CONFLICT_GENERATION, revision)+ expiry = int(self._value(row, "lease_expires_at", 4))+ current_row = await self._fetchrow(connection, f"SELECT {now} AS value", ())+ if int(self._value(current_row, "value", 0)) >= expiry:+ return OperationResult(FixedResult.CONFLICT_STATE, revision)+ common_where = (+ " WHERE id=? AND claim_revision=? AND publication_state='claimed' "+ "AND claim_owner_ref=? AND lease_generation=? AND lease_expires_at=? "+ "AND " + now + "<lease_expires_at"+ )+ common_params: tuple[Any, ...] = (+ request.operation_id,+ operation,+ request.expected_revision,+ request.outbox_id,+ request.expected_revision,+ request.owner_ref,+ request.lease_generation,+ expiry,+ )+ if operation == "renew":+ update = (+ "UPDATE execution_publication_outbox SET "+ f"lease_expires_at=lease_expires_at+{OUTBOX_LEASE_MS},"+ "latest_operation_id=?,latest_operation_code=?,"+ "latest_operation_base_revision=?,claim_revision=claim_revision+1"+ + common_where+ )+ elif operation == "publish":+ update = (+ "UPDATE execution_publication_outbox SET publication_state='published',"+ "claim_owner_ref=NULL,lease_expires_at=NULL,published_at="+ + now+ + ",failure_code=NULL,latest_operation_id=?,latest_operation_code=?,"+ "latest_operation_base_revision=?,claim_revision=claim_revision+1"+ + common_where+ )+ elif operation == "retryable_failure":+ attempt_count = int(self._value(row, "delivery_attempt_count", 5))+ delay = retry_delay_ms(attempt_count)+ if delay is None or attempt_count >= 20:+ return OperationResult(FixedResult.CONFLICT_STATE, revision)+ update = (+ "UPDATE execution_publication_outbox SET publication_state='pending',"+ "claim_owner_ref=NULL,lease_expires_at=NULL,available_at="+ + now+ + f"+{delay},failure_code='delivery_retryable',latest_operation_id=?,"+ "latest_operation_code=?,latest_operation_base_revision=?,"+ "claim_revision=claim_revision+1" + common_where+ )+ else:+ update = (+ "UPDATE execution_publication_outbox SET publication_state='poisoned',"+ "claim_owner_ref=NULL,lease_expires_at=NULL,available_at=NULL,poisoned_at="+ + now+ + ",failure_code='delivery_nonretryable',latest_operation_id=?,"+ "latest_operation_code=?,latest_operation_base_revision=?,"+ "claim_revision=claim_revision+1" + common_where+ )+ update += (+ " RETURNING id,claim_revision,publication_state,claim_owner_ref,"+ "lease_generation,delivery_attempt_count,failure_code"+ )+ async with self._savepoint(connection):+ updated = await self.cas_update_one(+ connection,+ update,+ common_params,+ identity=request.outbox_id,+ post_revision=request.expected_revision + 1,+ revision_column="claim_revision",+ zero_classifier=lambda: self._classify_zero_outbox(+ connection,+ outbox_id=request.outbox_id,+ expected_revision=request.expected_revision,+ expected_state="claimed",+ expected_owner=request.owner_ref,+ expected_generation=request.lease_generation,+ expected_lease_expires_at=expiry,+ time_requirement="unexpired",+ ),+ )+ if updated is None:+ raise _AbortOperationError(+ OperationResult(FixedResult.CONFLICT_STATE, revision)+ )+ result_fields = (+ ("publication_state", str(self._value(updated, "publication_state", 2))),+ ("claim_revision", request.expected_revision + 1),+ ("claim_owner_ref", self._value(updated, "claim_owner_ref", 3)),+ ("lease_generation", int(self._value(updated, "lease_generation", 4))),+ (+ "delivery_attempt_count",+ int(self._value(updated, "delivery_attempt_count", 5)),+ ),+ ("failure_code", self._value(updated, "failure_code", 6)),+ )+ await self._insert_receipt(+ connection,+ spec,+ result=FixedResult.APPLIED,+ result_identity=request.outbox_id,+ result_revision=request.expected_revision + 1,+ result_fields=result_fields,+ )+ return OperationResult(FixedResult.APPLIED, revision + 1)+ except _AbortOperationError as aborted:+ return aborted.result++ async def purge_outbox(+ self,+ outbox_id: str,+ expected_revision: int,+ operation_id: str,+ *,+ poisoned: bool,+ campaign_id: str | None = None,+ attempt_id: str | None = None,+ publication_key: str | None = None,+ event_code: str | None = None,+ ) -> OperationResult:+ request = OutboxMutation(+ outbox_id,+ expected_revision,+ operation_id,+ campaign_id=campaign_id,+ attempt_id=attempt_id,+ publication_key=publication_key,+ event_code=event_code,+ purge_poisoned=poisoned,+ )+ if (+ not self._valid_outbox_mutation(request, require_owner=False)+ or type(poisoned) is not bool+ ):+ return OperationResult(FixedResult.INVALID_CONTRACT, None)+ required_state = "poisoned" if poisoned else "published"+ spec = self._outbox_receipt_spec(request, "purge")+ try:+ async with self._transaction() as connection:+ await self._acquire_transaction_key(connection, operation_id)+ replay = await self._classify_receipt(+ connection, spec, current_revision=expected_revision+ )+ if replay is not None:+ return replay+ row = await self._locked_outbox_row(connection, outbox_id)+ if row is None:+ return OperationResult(FixedResult.NOT_FOUND_OR_PURGED, None)+ if not self._outbox_row_matches_binding(row, request):+ return OperationResult(FixedResult.CONFLICT_STATE, None)+ revision = int(self._value(row, "claim_revision", 1))+ if revision != expected_revision:+ return OperationResult(FixedResult.CONFLICT_REVISION, revision)+ if self._value(row, "publication_state", 0) != required_state:+ return OperationResult(FixedResult.CONFLICT_STATE, revision)+ async with self._savepoint(connection):+ await self._insert_receipt(+ connection,+ spec,+ result=FixedResult.APPLIED,+ result_identity=outbox_id,+ result_revision=expected_revision,+ result_fields=(+ ("publication_state", required_state),+ ("purged", True),+ ),+ )+ deleted = await self.delete_exact_set(+ connection,+ "DELETE FROM execution_publication_outbox WHERE id=? "+ "AND claim_revision=? AND publication_state=? RETURNING id",+ (outbox_id, expected_revision, required_state),+ expected_identities=(outbox_id,),+ zero_classifier=lambda: self._classify_zero_outbox(+ connection,+ outbox_id=outbox_id,+ expected_revision=expected_revision,+ expected_state=required_state,+ ),+ )+ if not deleted:+ raise _AbortOperationError(+ OperationResult(FixedResult.CONFLICT_STATE, revision)+ )+ return OperationResult(FixedResult.APPLIED, None)+ except _AbortOperationError as aborted:+ return aborted.result+++def sqlite_catalog_names(connection: Any) -> tuple[str, ...]:+ rows = connection.execute(+ "SELECT name FROM sqlite_schema WHERE type='table' AND name IN ("+ + ",".join("?" for _ in LIFECYCLE_TABLES)+ + ") ORDER BY name",+ LIFECYCLE_TABLES,+ ).fetchall()+ return tuple(str(row[0]) for row in rows)+++def _normalized_sql(value: object) -> str:+ if type(value) is not str:+ return ""+ return " ".join(value.replace("IF NOT EXISTS ", "").replace(" OR IGNORE", "").split())+++def _expected_sqlite_catalog_sql() -> tuple[tuple[str, str, str], ...]:+ entries: list[tuple[str, str, str]] = []+ for statement in SQLITE_LIFECYCLE_DDL:+ normalized = _normalized_sql(statement)+ table_match = re.match(r"CREATE TABLE ([a-z0-9_]+) ", normalized)+ if table_match is not None and table_match.group(1) in LIFECYCLE_TABLES:+ entries.append(("table", table_match.group(1), normalized))+ continue+ index_match = re.match(+ r"CREATE (?:UNIQUE )?INDEX ([a-z0-9_]+) ON ([a-z0-9_]+)",+ normalized,+ )+ if index_match is not None:+ entries.append(("index", index_match.group(1), normalized))+ continue+ trigger_match = re.match(+ r"CREATE TRIGGER ([a-z0-9_]+) BEFORE (?:UPDATE|DELETE) ON ([a-z0-9_]+)",+ normalized,+ )+ if trigger_match is not None and trigger_match.group(2) in LIFECYCLE_TABLES:+ entries.append(("trigger", trigger_match.group(1), normalized))+ return tuple(sorted(entries))+++_EXPECTED_SQLITE_CATALOG_SQL: Final = _expected_sqlite_catalog_sql()+_V11_ALTERED_LIFECYCLE_TABLES: Final[frozenset[str]] = frozenset(+ {+ "logical_executions",+ "execution_attempts",+ "execution_actor_authority_revisions",+ "campaign_execution_authority_revisions",+ "execution_operation_receipts",+ }+)+++def _validate_sqlite_catalog_sql(rows: Sequence[Any]) -> None:+ observed = tuple(+ sorted(+ (+ str(row[0]),+ str(row[1]),+ _normalized_sql(row[2]),+ )+ for row in rows+ )+ )+ if observed != _EXPECTED_SQLITE_CATALOG_SQL:+ raise RuntimeError("Incompatible execution lifecycle schema")+++def _validate_sqlite_v11_base_catalog_sql(rows: Sequence[Any]) -> None:+ """Prove generation-10 objects untouched except the five v11-altered tables."""+ expected = tuple(+ entry+ for entry in _EXPECTED_SQLITE_CATALOG_SQL+ if not (entry[0] == "table" and entry[1] in _V11_ALTERED_LIFECYCLE_TABLES)+ )+ observed = tuple(+ sorted(+ (+ str(row[0]),+ str(row[1]),+ _normalized_sql(row[2]),+ )+ for row in rows+ if not (str(row[0]) == "table" and str(row[1]) in _V11_ALTERED_LIFECYCLE_TABLES)+ )+ )+ if observed != expected:+ raise RuntimeError("Incompatible execution lifecycle schema")+++def validate_sqlite_lifecycle_catalog_rows(rows: Sequence[Any]) -> None:+ """Validate pre-fetched SQLite catalog rows against the exact generation-10 DDL."""+ _validate_sqlite_catalog_sql(rows)+++def validate_sqlite_lifecycle_catalog(connection: Any) -> None:+ if sqlite_catalog_names(connection) != tuple(sorted(LIFECYCLE_TABLES)):+ raise RuntimeError("Incompatible execution lifecycle schema")+ row = connection.execute(+ "SELECT mode,revision,catalog_digest,activation_revision,activation_at FROM execution_gateway_state WHERE singleton_id=1"+ ).fetchone()+ if row != ("disabled", 0, None, None, None):+ raise RuntimeError("Incompatible execution lifecycle schema")+ triggers = connection.execute(+ "SELECT name FROM sqlite_schema WHERE type='trigger' AND tbl_name IN ("+ + ",".join("?" for _ in LIFECYCLE_TABLES)+ + ") ORDER BY name",+ LIFECYCLE_TABLES,+ ).fetchall()+ if tuple(str(item[0]) for item in triggers) != (+ "trg_eor_immutable_delete",+ "trg_eor_immutable_update",+ ):+ raise RuntimeError("Incompatible execution lifecycle schema")+ names = tuple(name for _, name, _ in _EXPECTED_SQLITE_CATALOG_SQL)+ rows = connection.execute(+ "SELECT type,name,sql FROM sqlite_schema WHERE sql IS NOT NULL AND ("+ "name IN ("+ + ",".join("?" for _ in names)+ + ") OR tbl_name IN ("+ + ",".join("?" for _ in LIFECYCLE_TABLES)+ + ")) ORDER BY type,name",+ names + LIFECYCLE_TABLES,+ ).fetchall()+ v11_tables = {+ str(item[0])+ for item in connection.execute(+ "SELECT name FROM sqlite_schema WHERE type='table' AND name IN ("+ + ",".join("?" for _ in V11_AUTHORITY_TABLES)+ + ")",+ V11_AUTHORITY_TABLES,+ ).fetchall()+ }+ if v11_tables:+ if v11_tables != set(V11_AUTHORITY_TABLES):+ raise RuntimeError("Incompatible execution lifecycle schema")+ _validate_sqlite_v11_base_catalog_sql(rows)+ else:+ _validate_sqlite_catalog_sql(rows)+++async def validate_sqlite_lifecycle_catalog_async(connection: Any) -> None:+ placeholders = ",".join("?" for _ in LIFECYCLE_TABLES)+ async with connection.execute(+ "SELECT name FROM sqlite_schema WHERE type='table' AND name IN ("+ + placeholders+ + ") ORDER BY name",+ LIFECYCLE_TABLES,+ ) as cursor:+ rows = await cursor.fetchall()+ if tuple(str(row[0]) for row in rows) != tuple(sorted(LIFECYCLE_TABLES)):+ raise RuntimeError("Incompatible execution lifecycle schema")+ async with connection.execute(+ "SELECT mode,revision,catalog_digest,activation_revision,activation_at "+ "FROM execution_gateway_state WHERE singleton_id=1"+ ) as cursor:+ row = await cursor.fetchone()+ if row is None or tuple(row) != ("disabled", 0, None, None, None):+ raise RuntimeError("Incompatible execution lifecycle schema")+ async with connection.execute(+ "SELECT name FROM sqlite_schema WHERE type='trigger' AND tbl_name IN ("+ + placeholders+ + ") ORDER BY name",+ LIFECYCLE_TABLES,+ ) as cursor:+ triggers = await cursor.fetchall()+ if tuple(str(item[0]) for item in triggers) != (+ "trg_eor_immutable_delete",+ "trg_eor_immutable_update",+ ):+ raise RuntimeError("Incompatible execution lifecycle schema")+ names = tuple(name for _, name, _ in _EXPECTED_SQLITE_CATALOG_SQL)+ async with connection.execute(+ "SELECT type,name,sql FROM sqlite_schema WHERE sql IS NOT NULL AND ("+ "name IN ("+ + ",".join("?" for _ in names)+ + ") OR tbl_name IN ("+ + ",".join("?" for _ in LIFECYCLE_TABLES)+ + ")) ORDER BY type,name",+ names + LIFECYCLE_TABLES,+ ) as cursor:+ catalog_rows = await cursor.fetchall()+ v11_placeholders = ",".join("?" for _ in V11_AUTHORITY_TABLES)+ async with connection.execute(+ "SELECT name FROM sqlite_schema WHERE type='table' AND name IN (" + v11_placeholders + ")",+ V11_AUTHORITY_TABLES,+ ) as cursor:+ v11_rows = await cursor.fetchall()+ v11_tables = {str(item[0]) for item in v11_rows}+ if v11_tables:+ if v11_tables != set(V11_AUTHORITY_TABLES):+ raise RuntimeError("Incompatible execution lifecycle schema")+ _validate_sqlite_v11_base_catalog_sql(catalog_rows)+ else:+ _validate_sqlite_catalog_sql(catalog_rows)+++async def validate_postgresql_lifecycle_catalog(connection: Any) -> None:+ if not _POSTGRES_CATALOG_FINGERPRINT_V1:+ raise RuntimeError("Incompatible execution lifecycle schema")+++_V11_EXISTING_COLUMNS: Final[dict[str, tuple[str, ...]]] = {+ "logical_executions": (+ "admission_authority_contract_version",+ "canonical_principal_user_id",+ "immutable_intent_digest",+ "immutable_work_digest",+ ),+ "execution_attempts": (+ "authority_contract_version",+ "trusted_principal_subject_ref",+ "trusted_principal_user_id",+ "immutable_intent_digest",+ "immutable_work_digest",+ "gateway_revision",+ "gateway_activation_revision",+ "campaign_actor_grant_revision",+ "destination_authority_binding_digest",+ "credential_authority_binding_digest",+ "approval_authority_binding_digest",+ ),+ "execution_actor_authority_revisions": (+ "authority_state",+ "authority_revision",+ "authority_binding_digest",+ "authority_latest_operation_id",+ "authority_latest_operation_base_revision",+ "authority_latest_operation_code",+ ),+ "campaign_execution_authority_revisions": (+ "authority_state",+ "authority_revision",+ "authority_binding_digest",+ "authority_latest_operation_id",+ "authority_latest_operation_base_revision",+ "authority_latest_operation_code",+ ),+ "credentials": (+ "execution_authority_state",+ "execution_authority_revision",+ "execution_authority_binding_digest",+ "execution_authority_latest_operation_id",+ "execution_authority_latest_operation_base_revision",+ "execution_authority_latest_operation_code",+ ),+}++_V11_NEW_COLUMNS: Final[dict[str, tuple[str, ...]]] = {+ "campaign_execution_actor_grants": (+ "campaign_id",+ "actor_user_id",+ "authority_state",+ "revision",+ "binding_digest",+ "latest_operation_id",+ "latest_operation_base_revision",+ "latest_operation_code",+ "created_at",+ "updated_at",+ ),+ "campaign_execution_destination_authorities": (+ "campaign_id",+ "authority_state",+ "revision",+ "normalization_version",+ "destination_count",+ "destination_set_digest",+ "binding_digest",+ "latest_operation_id",+ "latest_operation_base_revision",+ "latest_operation_code",+ "created_at",+ "updated_at",+ ),+ "execution_approval_authorities": (+ "id",+ "approval_ref",+ "campaign_id",+ "submission_id",+ "attempt_id",+ "actor_subject_ref",+ "actor_user_id",+ "module_id",+ "approver_subject_ref",+ "approver_user_id",+ "authority_state",+ "revision",+ "granted_capability_mask",+ "descriptor_semantic_digest",+ "binding_digest",+ "latest_operation_id",+ "latest_operation_base_revision",+ "latest_operation_code",+ "created_at",+ "updated_at",+ "consumed_at",+ ),+ "execution_attempt_destination_observations": (+ "attempt_id",+ "campaign_id",+ "ordinal",+ "destination_ref_digest",+ "authority_revision",+ "normalization_version",+ "observed_at",+ ),+ "execution_attempt_credential_observations": (+ "attempt_id",+ "campaign_id",+ "ordinal",+ "credential_id",+ "authority_revision",+ "binding_digest",+ "observed_at",+ ),+}++_V11_ADDED_COLUMN_PROPERTIES: Final[dict[str, dict[str, tuple[str, bool, str | None]]]] = {+ "logical_executions": {+ "admission_authority_contract_version": ("integer", False, "2"),+ "canonical_principal_user_id": ("text", True, None),+ "immutable_intent_digest": ("text", True, None),+ "immutable_work_digest": ("text", True, None),+ },+ "execution_attempts": {+ "authority_contract_version": ("integer", False, "2"),+ "trusted_principal_subject_ref": ("text", True, None),+ "trusted_principal_user_id": ("text", True, None),+ "immutable_intent_digest": ("text", True, None),+ "immutable_work_digest": ("text", True, None),+ "gateway_revision": ("integer", True, None),+ "gateway_activation_revision": ("integer", True, None),+ "campaign_actor_grant_revision": ("integer", True, None),+ "destination_authority_binding_digest": ("text", True, None),+ "credential_authority_binding_digest": ("text", True, None),+ "approval_authority_binding_digest": ("text", True, None),+ },+ "execution_actor_authority_revisions": {+ "authority_state": ("text", False, "active"),+ "authority_revision": ("integer", False, "0"),+ "authority_binding_digest": ("text", False, "0" * 64),+ "authority_latest_operation_id": ("text", True, None),+ "authority_latest_operation_base_revision": ("integer", True, None),+ "authority_latest_operation_code": ("text", True, None),+ },+ "campaign_execution_authority_revisions": {+ "authority_state": ("text", False, "active"),+ "authority_revision": ("integer", False, "0"),+ "authority_binding_digest": ("text", False, "0" * 64),+ "authority_latest_operation_id": ("text", True, None),+ "authority_latest_operation_base_revision": ("integer", True, None),+ "authority_latest_operation_code": ("text", True, None),+ },+ "credentials": {+ "execution_authority_state": ("text", False, "active"),+ "execution_authority_revision": ("integer", False, "0"),+ "execution_authority_binding_digest": ("text", False, "0" * 64),+ "execution_authority_latest_operation_id": ("text", True, None),+ "execution_authority_latest_operation_base_revision": ("integer", True, None),+ "execution_authority_latest_operation_code": ("text", True, None),+ },+}++_V11_NEW_COLUMN_PROPERTIES: Final[dict[str, dict[str, tuple[str, bool, str | None]]]] = {+ "campaign_execution_actor_grants": {+ "campaign_id": ("text", False, None),+ "actor_user_id": ("text", False, None),+ "authority_state": ("text", False, None),+ "revision": ("integer", False, "0"),+ "binding_digest": ("text", False, None),+ "latest_operation_id": ("text", False, None),+ "latest_operation_base_revision": ("integer", False, None),+ "latest_operation_code": ("text", False, None),+ "created_at": ("integer", False, "$epoch_ms"),+ "updated_at": ("integer", False, "$epoch_ms"),+ },+ "campaign_execution_destination_authorities": {+ "campaign_id": ("text", False, None),+ "authority_state": ("text", False, None),+ "revision": ("integer", False, "0"),+ "normalization_version": ("integer", False, None),+ "destination_count": ("integer", False, None),+ "destination_set_digest": ("text", False, None),+ "binding_digest": ("text", False, None),+ "latest_operation_id": ("text", False, None),+ "latest_operation_base_revision": ("integer", False, None),+ "latest_operation_code": ("text", False, None),+ "created_at": ("integer", False, "$epoch_ms"),+ "updated_at": ("integer", False, "$epoch_ms"),+ },+ "execution_approval_authorities": {+ "id": ("text", False, None),+ "approval_ref": ("text", False, None),+ "campaign_id": ("text", False, None),+ "submission_id": ("text", False, None),+ "attempt_id": ("text", False, None),+ "actor_subject_ref": ("text", False, None),+ "actor_user_id": ("text", False, None),+ "module_id": ("text", False, None),+ "approver_subject_ref": ("text", False, None),+ "approver_user_id": ("text", True, None),+ "authority_state": ("text", False, None),+ "revision": ("integer", False, "0"),+ "granted_capability_mask": ("integer", False, None),+ "descriptor_semantic_digest": ("text", False, None),+ "binding_digest": ("text", False, None),+ "latest_operation_id": ("text", False, None),+ "latest_operation_base_revision": ("integer", False, None),+ "latest_operation_code": ("text", False, None),+ "created_at": ("integer", False, "$epoch_ms"),+ "updated_at": ("integer", False, "$epoch_ms"),+ "consumed_at": ("integer", True, None),+ },+ "execution_attempt_destination_observations": {+ "attempt_id": ("text", False, None),+ "campaign_id": ("text", False, None),+ "ordinal": ("integer", False, None),+ "destination_ref_digest": ("text", False, None),+ "authority_revision": ("integer", False, None),+ "normalization_version": ("integer", False, None),+ "observed_at": ("integer", False, "$epoch_ms"),+ },+ "execution_attempt_credential_observations": {+ "attempt_id": ("text", False, None),+ "campaign_id": ("text", False, None),+ "ordinal": ("integer", False, None),+ "credential_id": ("text", False, None),+ "authority_revision": ("integer", False, None),+ "binding_digest": ("text", False, None),+ "observed_at": ("integer", False, "$epoch_ms"),+ },+}++# Independent semantic catalog authority. These facts are intentionally+# literal and do not reuse the migration DDL or its generators.+_V11_CONSTRAINT_FACTS: Final[dict[str, dict[str, object]]] = {+ "campaign_execution_actor_grants": {+ "primary": {"pk_ceag": ("campaign_id", "actor_user_id")},+ "unique": {},+ "checks": {+ "ck_ceag_ids": ("campaign_id", "actor_user_id", "latest_operation_id", "0-9a-f"),+ "ck_ceag_digest": ("binding_digest", "64", "0-9a-f"),+ "ck_ceag_shape": (+ "authority_state",+ "active",+ "revoked",+ "revision",+ "9007199254740991",+ "latest_operation_base_revision",+ "latest_operation_code",+ "put",+ "revoke",+ "created_at",+ "updated_at",+ ),+ },+ "foreign": {+ "fk_ceag_campaign": (+ ("campaign_id",),+ "campaigns",+ ("id",),+ "NO ACTION",+ "NO ACTION",+ True,+ True,+ ),+ "fk_ceag_actor": (+ ("actor_user_id",),+ "users",+ ("id",),+ "NO ACTION",+ "NO ACTION",+ True,+ True,+ ),+ },+ },+ "campaign_execution_destination_authorities": {+ "primary": {"pk_ceda": ("campaign_id",)},+ "unique": {},+ "checks": {+ "ck_ceda_ids": ("campaign_id", "latest_operation_id", "0-9a-f"),+ "ck_ceda_digests": (+ "destination_set_digest",+ "binding_digest",+ "64",+ "0-9a-f",+ ),+ "ck_ceda_shape": (+ "authority_state",+ "active",+ "revoked",+ "revision",+ "normalization_version",+ "destination_count",+ "4096",+ "latest_operation_base_revision",+ "latest_operation_code",+ "update",+ "revoke",+ "created_at",+ "updated_at",+ ),+ },+ "foreign": {+ "fk_ceda_campaign": (+ ("campaign_id",),+ "campaigns",+ ("id",),+ "NO ACTION",+ "NO ACTION",+ True,+ True,+ ),+ },+ },+ "execution_approval_authorities": {+ "primary": {"pk_eapa": ("id",)},+ "unique": {+ "uq_eapa_ref": ("approval_ref",),+ "uq_eapa_attempt": ("attempt_id",),+ },+ "checks": {+ "ck_eapa_ids": (+ "id",+ "approval_ref",+ "campaign_id",+ "submission_id",+ "attempt_id",+ "actor_subject_ref",+ "actor_user_id",+ "approver_subject_ref",+ "approver_user_id",+ "latest_operation_id",+ "0-9a-f",+ ),+ "ck_eapa_module": ("module_id", "128", "a-z"),+ "ck_eapa_digests": (+ "descriptor_semantic_digest",+ "binding_digest",+ "64",+ "0-9a-f",+ ),+ "ck_eapa_shape": (+ "authority_state",+ "active",+ "revoked",+ "consumed",+ "revision",+ "granted_capability_mask",+ "15",+ "latest_operation_base_revision",+ "latest_operation_code",+ "grant",+ "revoke",+ "consume",+ "consumed_at",+ "created_at",+ "updated_at",+ ),+ },+ "foreign": {+ "fk_eapa_campaign": (+ ("campaign_id",),+ "campaigns",+ ("id",),+ "NO ACTION",+ "NO ACTION",+ True,+ True,+ ),+ "fk_eapa_approver": (+ ("approver_user_id",),+ "users",+ ("id",),+ "NO ACTION",+ "SET NULL",+ True,+ True,+ ),+ },+ },+ "execution_attempt_destination_observations": {+ "primary": {"pk_eado": ("attempt_id", "ordinal")},+ "unique": {+ "uq_eado_attempt_destination": ("attempt_id", "destination_ref_digest"),+ },+ "checks": {+ "ck_eado_ids": ("attempt_id", "campaign_id", "0-9a-f"),+ "ck_eado_ref": ("destination_ref_digest", "64", "0-9a-f"),+ "ck_eado_shape": (+ "ordinal",+ "4095",+ "authority_revision",+ "9007199254740991",+ "normalization_version",+ "observed_at",+ ),+ },+ "foreign": {+ "fk_eado_attempt": (+ ("campaign_id", "attempt_id"),+ "execution_attempts",+ ("campaign_id", "id"),+ "NO ACTION",+ "NO ACTION",+ True,+ True,+ ),+ },+ },+ "execution_attempt_credential_observations": {+ "primary": {"pk_eaco": ("attempt_id", "ordinal")},+ "unique": {+ "uq_eaco_attempt_credential": ("attempt_id", "credential_id"),+ },+ "checks": {+ "ck_eaco_ids": ("attempt_id", "campaign_id", "credential_id", "0-9a-f"),+ "ck_eaco_digest": ("binding_digest", "64", "0-9a-f"),+ "ck_eaco_shape": (+ "ordinal",+ "4095",+ "authority_revision",+ "9007199254740991",+ "observed_at",+ ),+ },+ "foreign": {+ "fk_eaco_attempt": (+ ("campaign_id", "attempt_id"),+ "execution_attempts",+ ("campaign_id", "id"),+ "NO ACTION",+ "NO ACTION",+ True,+ True,+ ),+ },+ },+}++_V11_INDEX_FACTS: Final[dict[str, tuple[str, bool, tuple[str, ...], str | None]]] = {+ "uq_ceag_latest_operation": (+ "campaign_execution_actor_grants",+ True,+ ("latest_operation_id",),+ None,+ ),+ "ix_ceag_actor_state": (+ "campaign_execution_actor_grants",+ False,+ ("actor_user_id", "authority_state", "campaign_id"),+ None,+ ),+ "uq_ceda_latest_operation": (+ "campaign_execution_destination_authorities",+ True,+ ("latest_operation_id",),+ None,+ ),+ "uq_eapa_latest_operation": (+ "execution_approval_authorities",+ True,+ ("latest_operation_id",),+ None,+ ),+ "ix_eapa_campaign_state": (+ "execution_approval_authorities",+ False,+ ("campaign_id", "authority_state", "id"),+ None,+ ),+ "ix_eado_campaign_attempt": (+ "execution_attempt_destination_observations",+ False,+ ("campaign_id", "attempt_id", "ordinal"),+ None,+ ),+ "ix_eaco_campaign_attempt": (+ "execution_attempt_credential_observations",+ False,+ ("campaign_id", "attempt_id", "ordinal"),+ None,+ ),+ "ix_credentials_execution_authority": (+ "credentials",+ False,+ ("campaign_id", "execution_authority_state", "id"),+ None,+ ),+}++_V11_EXISTING_CHECK_REQUIREMENTS: Final[dict[str, dict[str, tuple[str, ...]]]] = {+ "logical_executions": {+ "admission_authority_contract_version": ("admission_authority_contract_version", "2", "3"),+ "canonical_principal_user_id": ("canonical_principal_user_id", "isnull", "0-9a-f"),+ "immutable_intent_digest": ("immutable_intent_digest", "isnull", "64", "0-9a-f"),+ "immutable_work_digest": ("immutable_work_digest", "isnull", "64", "0-9a-f"),+ },+ "execution_attempts": {+ "authority_contract_version": ("authority_contract_version", "2", "3"),+ "trusted_principal_subject_ref": ("trusted_principal_subject_ref", "isnull", "0-9a-f"),+ "trusted_principal_user_id": ("trusted_principal_user_id", "isnull", "0-9a-f"),+ "immutable_intent_digest": ("immutable_intent_digest", "isnull", "64", "0-9a-f"),+ "immutable_work_digest": ("immutable_work_digest", "isnull", "64", "0-9a-f"),+ "gateway_revision": ("gateway_revision", "isnull", "9007199254740991"),+ "gateway_activation_revision": (+ "gateway_activation_revision",+ "isnull",+ "9007199254740991",+ ),+ "campaign_actor_grant_revision": (+ "campaign_actor_grant_revision",+ "isnull",+ "9007199254740991",+ ),+ "destination_authority_binding_digest": (+ "destination_authority_binding_digest",+ "isnull",+ "64",+ "0-9a-f",+ ),+ "credential_authority_binding_digest": (+ "credential_authority_binding_digest",+ "isnull",+ "64",+ "0-9a-f",+ ),+ "approval_authority_binding_digest": (+ "approval_authority_binding_digest",+ "isnull",+ "64",+ "0-9a-f",+ ),+ },+ "execution_actor_authority_revisions": {+ "authority_state": ("authority_state", "active", "revoked"),+ "authority_revision": ("authority_revision", "9007199254740991"),+ "authority_binding_digest": ("authority_binding_digest", "64", "0-9a-f"),+ "authority_latest_operation_id": ("authority_latest_operation_id", "isnull", "0-9a-f"),+ "authority_latest_operation_base_revision": (+ "authority_latest_operation_base_revision",+ "isnull",+ "9007199254740991",+ ),+ "authority_latest_operation_code": (+ "authority_latest_operation_code",+ "isnull",+ "activate",+ "update",+ "revoke",+ ),+ },+ "campaign_execution_authority_revisions": {+ "authority_state": ("authority_state", "active", "revoked"),+ "authority_revision": ("authority_revision", "9007199254740991"),+ "authority_binding_digest": ("authority_binding_digest", "64", "0-9a-f"),+ "authority_latest_operation_id": ("authority_latest_operation_id", "isnull", "0-9a-f"),+ "authority_latest_operation_base_revision": (+ "authority_latest_operation_base_revision",+ "isnull",+ "9007199254740991",+ ),+ "authority_latest_operation_code": (+ "authority_latest_operation_code",+ "isnull",+ "activate",+ "update",+ "revoke",+ ),+ },+ "credentials": {+ "execution_authority_state": ("execution_authority_state", "active", "revoked"),+ "execution_authority_revision": (+ "execution_authority_revision",+ "9007199254740991",+ ),+ "execution_authority_binding_digest": (+ "execution_authority_binding_digest",+ "64",+ "0-9a-f",+ ),+ "execution_authority_latest_operation_id": (+ "execution_authority_latest_operation_id",+ "isnull",+ "0-9a-f",+ ),+ "execution_authority_latest_operation_base_revision": (+ "execution_authority_latest_operation_base_revision",+ "isnull",+ "9007199254740991",+ ),+ "execution_authority_latest_operation_code": (+ "execution_authority_latest_operation_code",+ "isnull",+ "update",+ "revoke",+ ),+ },+}+++def _validate_v11_columns(rows: Sequence[Any]) -> None:+ observed: dict[str, list[str]] = {}+ for row in rows:+ table = str(row[0])+ observed.setdefault(table, []).append(str(row[1]))+ for table, expected in _V11_EXISTING_COLUMNS.items():+ columns = tuple(observed.get(table, ()))+ if not columns or columns[-len(expected) :] != expected:+ raise RuntimeError("Incompatible admission authority schema")+ for table, expected in _V11_NEW_COLUMNS.items():+ if tuple(observed.get(table, ())) != expected:+ raise RuntimeError("Incompatible admission authority schema")+++def _validate_v11_column_properties(rows: Sequence[Any], dialect: str) -> None:+ observed = {+ (str(row[0]), str(row[1])): (+ str(row[2]).lower(),+ (not bool(row[3])) if dialect == "sqlite" else str(row[3]) == "YES",+ None if row[4] is None else str(row[4]),+ )+ for row in rows+ }+ expected_tables = _V11_ADDED_COLUMN_PROPERTIES | _V11_NEW_COLUMN_PROPERTIES+ for table, columns in expected_tables.items():+ for column, (kind, nullable, default) in columns.items():+ actual = observed.get((table, column))+ expected_kind = "bigint" if dialect == "postgresql" and kind == "integer" else kind+ if actual is None or actual[:2] != (expected_kind, nullable):+ raise RuntimeError("Incompatible admission authority schema")+ actual_default = actual[2]+ if default is None:+ if actual_default is not None:+ raise RuntimeError("Incompatible admission authority schema")+ elif default == "$epoch_ms":+ normalized_default = (+ "" if actual_default is None else "".join(actual_default.lower().split())+ )+ required = (+ ("julianday('now')", "2440587.5", "86400000")+ if dialect == "sqlite"+ else ("extract(epochfromclock_timestamp())", "1000")+ )+ if not all(token in normalized_default for token in required):+ raise RuntimeError("Incompatible admission authority schema")+ elif kind == "text":+ expected_default = (+ f"'{default}'::text" if dialect == "postgresql" else f"'{default}'"+ )+ if actual_default != expected_default:+ raise RuntimeError("Incompatible admission authority schema")+ elif actual_default != default:+ raise RuntimeError("Incompatible admission authority schema")+++def _balanced_check_expressions(create_sql: object) -> tuple[str, ...]:+ if type(create_sql) is not str:+ return ()+ source = create_sql+ lowered = source.lower()+ expressions: list[str] = []+ offset = 0+ while True:+ index = lowered.find("check", offset)+ if index < 0:+ break+ cursor = index + 5+ while cursor < len(source) and source[cursor].isspace():+ cursor += 1+ if cursor >= len(source) or source[cursor] != "(":+ offset = cursor+ continue+ depth = 0+ quote: str | None = None+ while cursor < len(source):+ character = source[cursor]+ if quote is not None:+ if character == quote:+ if cursor + 1 < len(source) and source[cursor + 1] == quote:+ cursor += 2+ continue+ quote = None+ elif character in {"'", '"'}:+ quote = character+ elif character == "(":+ depth += 1+ elif character == ")":+ depth -= 1+ if depth == 0:+ expressions.append(source[index : cursor + 1])+ cursor += 1+ break+ cursor += 1+ if depth != 0 or quote is not None:+ return ()+ offset = cursor+ return tuple(expressions)+++def _normalized_catalog_expression(value: object) -> str:+ return (+ "".join(str(value).lower().replace('"', "").split())+ .replace("::text", "")+ .replace("::bigint", "")+ )+++def _validate_check_requirements(+ definitions: Sequence[object],+ requirements: dict[str, tuple[str, ...]],+) -> None:+ normalized = tuple(_normalized_catalog_expression(value) for value in definitions)+ if len(normalized) != len(requirements):+ raise RuntimeError("Incompatible admission authority schema")+ for requirement in requirements.values():+ matches = [value for value in normalized if all(token in value for token in requirement)]+ if len(matches) != 1 or "ortrue" in matches[0]:+ raise RuntimeError("Incompatible admission authority schema")+++def _named_sqlite_constraints(create_sql: object) -> dict[str, tuple[str, str]]:+ if type(create_sql) is not str:+ return {}+ source = create_sql+ matches = tuple(+ re.finditer(+ r"\bCONSTRAINT\s+([a-z0-9_]+)\s+"+ r"(PRIMARY\s+KEY|UNIQUE|CHECK|FOREIGN\s+KEY)\b",+ source,+ re.I,+ )+ )+ result: dict[str, tuple[str, str]] = {}+ for index, match in enumerate(matches):+ name = match.group(1).lower()+ kind = " ".join(match.group(2).lower().split())+ end = matches[index + 1].start() if index + 1 < len(matches) else len(source)+ if name in result:+ return {}+ result[name] = (kind, source[match.start() : end])+ return result+++def _parenthesized_columns(fragment: str, marker: str) -> tuple[str, ...]:+ normalized = " ".join(fragment.lower().replace('"', "").split())+ match = re.search(re.escape(marker) + r"\s*\(([^()]*)\)", normalized)+ if match is None:+ return ()+ return tuple(item.strip() for item in match.group(1).split(","))+++def _validate_sqlite_v11_semantics(+ schema_rows: Sequence[Any],+ index_rows: Sequence[Any],+ foreign_key_rows: Sequence[Any],+) -> None:+ table_sql = {+ str(row[1]): row[3]+ for row in schema_rows+ if str(row[0]) == "table" and str(row[1]) in _V11_NEW_COLUMNS+ }+ if set(table_sql) != set(_V11_NEW_COLUMNS):+ raise RuntimeError("Incompatible admission authority schema")++ explicit_expected = {+ name: fact for name, fact in _V11_INDEX_FACTS.items() if fact[0] in _V11_NEW_COLUMNS+ }+ explicit_observed = {+ str(row[1])+ for row in schema_rows+ if str(row[0]) == "index" and str(row[2]) in _V11_NEW_COLUMNS and row[3] is not None+ }+ if explicit_observed != set(explicit_expected):+ raise RuntimeError("Incompatible admission authority schema")+ if any(str(row[0]) == "trigger" and str(row[2]) in _V11_NEW_COLUMNS for row in schema_rows):+ raise RuntimeError("Incompatible admission authority schema")++ for table, facts in _V11_CONSTRAINT_FACTS.items():+ constraints = _named_sqlite_constraints(table_sql[table])+ expected_kinds = {+ **dict.fromkeys(facts["primary"], "primary key"),+ **dict.fromkeys(facts["unique"], "unique"),+ **dict.fromkeys(facts["checks"], "check"),+ **dict.fromkeys(facts["foreign"], "foreign key"),+ }+ if {name: value[0] for name, value in constraints.items()} != expected_kinds:+ raise RuntimeError("Incompatible admission authority schema")+ for name, columns in facts["primary"].items():+ observed_columns = _parenthesized_columns(constraints[name][1], "primary key")+ inline_singleton = (+ len(columns) == 1+ and not observed_columns+ and "primarykey" in _normalized_catalog_expression(constraints[name][1])+ )+ if not inline_singleton and observed_columns != columns:+ raise RuntimeError("Incompatible admission authority schema")+ for name, columns in facts["unique"].items():+ if _parenthesized_columns(constraints[name][1], "unique") != columns:+ raise RuntimeError("Incompatible admission authority schema")+ _validate_check_requirements(+ tuple(constraints[name][1] for name in facts["checks"]),+ facts["checks"],+ )+ for name, expected in facts["foreign"].items():+ local, referenced_table, referenced, on_update, on_delete, deferred, initially = (+ expected+ )+ fragment = _normalized_catalog_expression(constraints[name][1])+ required = (+ "foreignkey(" + ",".join(local) + ")",+ "references" + referenced_table + "(" + ",".join(referenced) + ")",+ "onupdate" + on_update.lower().replace(" ", ""),+ "ondelete" + on_delete.lower().replace(" ", ""),+ )+ if not all(token in fragment for token in required):+ raise RuntimeError("Incompatible admission authority schema")+ if deferred != ("deferrable" in fragment) or initially != (+ "initiallydeferred" in fragment+ ):+ raise RuntimeError("Incompatible admission authority schema")++ grouped_indexes: dict[str, list[Any]] = {}+ for row in index_rows:+ grouped_indexes.setdefault(str(row[1]), []).append(row)+ for name, (table, unique, columns, predicate) in _V11_INDEX_FACTS.items():+ rows = grouped_indexes.get(name, [])+ if (+ len(rows) != len(columns)+ or any(str(row[0]) != table for row in rows)+ or bool(rows[0][2]) is not unique+ or any(str(row[3]) != "c" or bool(row[4]) for row in rows)+ or tuple(str(row[6]) for row in sorted(rows, key=lambda value: int(value[5])))+ != columns+ or predicate is not None+ ):+ raise RuntimeError("Incompatible admission authority schema")++ expected_backing = {+ table: sorted(+ tuple(columns)+ for columns in tuple(facts["primary"].values()) + tuple(facts["unique"].values())+ )+ for table, facts in _V11_CONSTRAINT_FACTS.items()+ }+ observed_backing: dict[str, list[tuple[str, ...]]] = {+ table: [] for table in _V11_CONSTRAINT_FACTS+ }+ backing_groups: dict[tuple[str, str], list[Any]] = {}+ for row in index_rows:+ if str(row[0]) in _V11_CONSTRAINT_FACTS and str(row[3]) in {"pk", "u"}:+ backing_groups.setdefault((str(row[0]), str(row[1])), []).append(row)+ for (table, _), rows in backing_groups.items():+ observed_backing[table].append(+ tuple(str(row[6]) for row in sorted(rows, key=lambda value: int(value[5])))+ )+ if any(+ sorted(observed_backing[table]) != expected for table, expected in expected_backing.items()+ ):+ raise RuntimeError("Incompatible admission authority schema")++ fk_groups: dict[tuple[str, int], list[Any]] = {}+ for row in foreign_key_rows:+ fk_groups.setdefault((str(row[0]), int(row[1])), []).append(row)+ observed_foreign: dict[str, list[tuple[object, ...]]] = {+ table: [] for table in _V11_CONSTRAINT_FACTS+ }+ for (table, _), rows in fk_groups.items():+ ordered = sorted(rows, key=lambda value: int(value[2]))+ observed_foreign[table].append(+ (+ tuple(str(row[4]) for row in ordered),+ str(ordered[0][3]),+ tuple(str(row[5]) for row in ordered),+ str(ordered[0][6]).upper(),+ str(ordered[0][7]).upper(),+ )+ )+ for table, facts in _V11_CONSTRAINT_FACTS.items():+ expected = sorted(tuple(value[:5]) for value in facts["foreign"].values())+ if sorted(observed_foreign[table]) != expected:+ raise RuntimeError("Incompatible admission authority schema")+++def _validate_v11_existing_checks(table_sql: dict[str, object]) -> None:+ for table, requirements in _V11_EXISTING_CHECK_REQUIREMENTS.items():+ expressions = _balanced_check_expressions(table_sql.get(table))+ selected = tuple(+ expression+ for expression in expressions+ if any(column in expression.lower() for column in requirements)+ )+ _validate_check_requirements(selected, requirements)+++def _row_value(row: Any, key: str) -> Any:+ try:+ return row[key]+ except (KeyError, TypeError):+ return getattr(row, key)+++def _postgres_action(code: object) -> str:+ actions = {+ "a": "NO ACTION",+ "r": "RESTRICT",+ "c": "CASCADE",+ "n": "SET NULL",+ "d": "SET DEFAULT",+ }+ try:+ return actions[str(code)]+ except KeyError as error:+ raise RuntimeError("Incompatible admission authority schema") from error+++def _validate_postgresql_v11_semantics(+ relation_rows: Sequence[Any],+ collation_rows: Sequence[Any],+ constraint_rows: Sequence[Any],+ index_rows: Sequence[Any],+ existing_check_rows: Sequence[Any],+) -> None:+ campaign_relations = {+ str(_row_value(row, "table_name")): str(_row_value(row, "relkind"))+ for row in relation_rows+ if str(_row_value(row, "table_name")).startswith("campaign_execution_")+ }+ if campaign_relations != dict.fromkeys(+ _V11_RESERVED_CAMPAIGN_EXECUTION_RELATIONS,+ "r",+ ):+ raise RuntimeError("Incompatible admission authority schema")+ relations = {+ str(_row_value(row, "table_name")): (+ str(_row_value(row, "relkind")),+ str(_row_value(row, "relpersistence")),+ bool(_row_value(row, "relispartition")),+ bool(_row_value(row, "relrowsecurity")),+ bool(_row_value(row, "relforcerowsecurity")),+ int(_row_value(row, "user_trigger_count")),+ int(_row_value(row, "policy_count")),+ int(_row_value(row, "user_rule_count")),+ )+ for row in relation_rows+ if str(_row_value(row, "table_name")) in V11_AUTHORITY_TABLES+ }+ if relations != dict.fromkeys(+ _V11_NEW_COLUMNS,+ ("r", "p", False, False, False, 0, 0, 0),+ ):+ raise RuntimeError("Incompatible admission authority schema")++ observed_collations = {+ (+ str(_row_value(row, "table_name")),+ str(_row_value(row, "column_name")),+ ): bool(_row_value(row, "collation_is_default"))+ for row in collation_rows+ }+ expected_collations = {+ (table, column)+ for table, columns in (_V11_EXISTING_COLUMNS | _V11_NEW_COLUMNS).items()+ for column in columns+ }+ if any(not observed_collations.get(key, False) for key in expected_collations):+ raise RuntimeError("Incompatible admission authority schema")++ observed_constraints: dict[str, dict[str, Any]] = {table: {} for table in _V11_CONSTRAINT_FACTS}+ for row in constraint_rows:+ table = str(_row_value(row, "table_name"))+ name = str(_row_value(row, "constraint_name"))+ if name in observed_constraints[table]:+ raise RuntimeError("Incompatible admission authority schema")+ observed_constraints[table][name] = row+ for table, facts in _V11_CONSTRAINT_FACTS.items():+ expected_types = {+ **dict.fromkeys(facts["primary"], "p"),+ **dict.fromkeys(facts["unique"], "u"),+ **dict.fromkeys(facts["checks"], "c"),+ **dict.fromkeys(facts["foreign"], "f"),+ }+ rows = observed_constraints[table]+ if set(rows) != set(expected_types) or any(+ str(_row_value(rows[name], "constraint_type")) != kind+ for name, kind in expected_types.items()+ ):+ raise RuntimeError("Incompatible admission authority schema")+ for name, columns in {**facts["primary"], **facts["unique"]}.items():+ row = rows[name]+ if tuple(_row_value(row, "local_columns") or ()) != columns:+ raise RuntimeError("Incompatible admission authority schema")+ _validate_check_requirements(+ tuple(_row_value(rows[name], "definition") for name in facts["checks"]),+ facts["checks"],+ )+ for name, expected in facts["foreign"].items():+ row = rows[name]+ local, referenced_table, referenced, on_update, on_delete, deferred, initially = (+ expected+ )+ actual = (+ tuple(_row_value(row, "local_columns") or ()),+ str(_row_value(row, "referenced_table")),+ tuple(_row_value(row, "referenced_columns") or ()),+ _postgres_action(_row_value(row, "update_action")),+ _postgres_action(_row_value(row, "delete_action")),+ bool(_row_value(row, "is_deferrable")),+ bool(_row_value(row, "is_deferred")),+ )+ if actual != expected or not bool(_row_value(row, "is_validated")):+ raise RuntimeError("Incompatible admission authority schema")++ expected_indexes: dict[str, tuple[str, bool, bool, tuple[str, ...]]] = {}+ for table, facts in _V11_CONSTRAINT_FACTS.items():+ expected_indexes.update(+ {name: (table, True, True, columns) for name, columns in facts["primary"].items()}+ )+ expected_indexes.update(+ {name: (table, True, False, columns) for name, columns in facts["unique"].items()}+ )+ expected_indexes.update(+ {+ name: (table, unique, False, columns)+ for name, (table, unique, columns, _) in _V11_INDEX_FACTS.items()+ }+ )+ observed_indexes = {str(_row_value(row, "index_name")): row for row in index_rows}+ if set(observed_indexes) != set(expected_indexes):+ raise RuntimeError("Incompatible admission authority schema")+ for name, expected in expected_indexes.items():+ row = observed_indexes[name]+ actual = (+ str(_row_value(row, "table_name")),+ bool(_row_value(row, "is_unique")),+ bool(_row_value(row, "is_primary")),+ tuple(_row_value(row, "key_columns") or ()),+ )+ if (+ actual != expected+ or str(_row_value(row, "method")) != "btree"+ or _row_value(row, "predicate") is not None+ or bool(_row_value(row, "has_expressions"))+ or not bool(_row_value(row, "is_valid"))+ or not bool(_row_value(row, "is_ready"))+ ):+ raise RuntimeError("Incompatible admission authority schema")++ observed_existing: dict[str, list[object]] = {+ table: [] for table in _V11_EXISTING_CHECK_REQUIREMENTS+ }+ observed_columns: dict[str, list[tuple[str, ...]]] = {+ table: [] for table in _V11_EXISTING_CHECK_REQUIREMENTS+ }+ for row in existing_check_rows:+ table = str(_row_value(row, "table_name"))+ observed_existing[table].append(_row_value(row, "definition"))+ observed_columns[table].append(tuple(_row_value(row, "local_columns") or ()))+ for table, requirements in _V11_EXISTING_CHECK_REQUIREMENTS.items():+ if sorted(observed_columns[table]) != sorted((column,) for column in requirements):+ raise RuntimeError("Incompatible admission authority schema")+ _validate_check_requirements(observed_existing[table], requirements)+++def _validate_v11_credential_checks(definitions: Sequence[object]) -> None:+ normalized = tuple("".join(str(value).lower().split()) for value in definitions)+ requirements = (+ ("execution_authority_state", "active", "revoked"),+ ("execution_authority_revision", "between0and9007199254740991"),+ ("execution_authority_binding_digest", "64", "0-9a-f"),+ ("execution_authority_latest_operation_id", "isnull", "36", "0-9a-f"),+ (+ "execution_authority_latest_operation_base_revision",+ "isnull",+ "between0and9007199254740991",+ ),+ ("execution_authority_latest_operation_code", "isnull", "update", "revoke"),+ )+ if len(normalized) != len(requirements):+ raise RuntimeError("Incompatible admission authority schema")+ for requirement in requirements:+ matches = [value for value in normalized if all(token in value for token in requirement)]+ if len(matches) != 1 or "ortrue" in matches[0]:+ raise RuntimeError("Incompatible admission authority schema")+++def validate_sqlite_admission_authority_catalog(connection: Any) -> None:+ campaign_relations = connection.execute(+ "SELECT type,name FROM sqlite_schema WHERE type IN ('table','view') "+ "AND name GLOB 'campaign_execution_*' ORDER BY type,name"+ ).fetchall()+ if {(str(row[0]), str(row[1])) for row in campaign_relations} != {+ ("table", name) for name in _V11_RESERVED_CAMPAIGN_EXECUTION_RELATIONS+ }:+ raise RuntimeError("Incompatible admission authority schema")+ rows = connection.execute(+ 'SELECT m.name,p.name,p.type,p."notnull",p.dflt_value '+ "FROM sqlite_schema AS m JOIN pragma_table_info(m.name) AS p "+ "WHERE m.type='table' AND m.name IN ("+ + ",".join("?" for _ in tuple(_V11_EXISTING_COLUMNS) + V11_AUTHORITY_TABLES)+ + ") ORDER BY m.name,p.cid",+ tuple(_V11_EXISTING_COLUMNS) + V11_AUTHORITY_TABLES,+ ).fetchall()+ _validate_v11_columns(rows)+ _validate_v11_column_properties(rows, "sqlite")+ catalog_rows = connection.execute(+ "SELECT type,name,tbl_name,sql FROM sqlite_schema WHERE "+ "(tbl_name IN ("+ + ",".join("?" for _ in V11_AUTHORITY_TABLES)+ + ") OR name IN ("+ + ",".join("?" for _ in _V11_EXISTING_CHECK_REQUIREMENTS)+ + ")) ORDER BY type,name",+ V11_AUTHORITY_TABLES + tuple(_V11_EXISTING_CHECK_REQUIREMENTS),+ ).fetchall()+ index_rows = connection.execute(+ 'SELECT m.name,il.name,il."unique",il.origin,il.partial,xi.seqno,xi.name '+ "FROM sqlite_schema AS m JOIN pragma_index_list(m.name) AS il "+ "JOIN pragma_index_xinfo(il.name) AS xi WHERE m.type='table' "+ "AND m.name IN ("+ + ",".join("?" for _ in V11_AUTHORITY_TABLES + ("credentials",))+ + ") AND xi.key=1 ORDER BY m.name,il.name,xi.seqno",+ V11_AUTHORITY_TABLES + ("credentials",),+ ).fetchall()+ foreign_rows = connection.execute(+ 'SELECT m.name,f.id,f.seq,f."table",f."from",f."to",f.on_update,f.on_delete '+ "FROM sqlite_schema AS m JOIN pragma_foreign_key_list(m.name) AS f "+ "WHERE m.type='table' AND m.name IN ("+ + ",".join("?" for _ in V11_AUTHORITY_TABLES)+ + ") ORDER BY m.name,f.id,f.seq",+ V11_AUTHORITY_TABLES,+ ).fetchall()+ _validate_sqlite_v11_semantics(catalog_rows, index_rows, foreign_rows)+ _validate_v11_existing_checks(+ {str(row[1]): row[3] for row in catalog_rows if str(row[0]) == "table"}+ )+ receipt = connection.execute(+ "SELECT sql FROM sqlite_schema WHERE type='table' AND name='execution_operation_receipts'"+ ).fetchone()+ if receipt is None or not all(code in str(receipt[0]) for code in V11_OPERATION_CODES):+ raise RuntimeError("Incompatible admission authority schema")+ triggers = connection.execute(+ "SELECT name FROM sqlite_schema WHERE type='trigger' "+ "AND tbl_name='execution_operation_receipts' ORDER BY name"+ ).fetchall()+ if tuple(str(row[0]) for row in triggers) != (+ "trg_eor_immutable_delete",+ "trg_eor_immutable_update",+ ):+ raise RuntimeError("Incompatible admission authority schema")+ credential_sql = connection.execute(+ "SELECT sql FROM sqlite_schema WHERE type='table' AND name='credentials'"+ ).fetchone()+ if credential_sql is None:+ raise RuntimeError("Incompatible admission authority schema")+ checks = tuple(+ expression+ for expression in _balanced_check_expressions(credential_sql[0])+ if "execution_authority_" in expression.lower()+ )+ _validate_v11_credential_checks(checks)+++async def validate_sqlite_admission_authority_catalog_async(connection: Any) -> None:+ async with connection.execute(+ "SELECT type,name FROM sqlite_schema WHERE type IN ('table','view') "+ "AND name GLOB 'campaign_execution_*' ORDER BY type,name"+ ) as cursor:+ campaign_relations = await cursor.fetchall()+ if {(str(row[0]), str(row[1])) for row in campaign_relations} != {+ ("table", name) for name in _V11_RESERVED_CAMPAIGN_EXECUTION_RELATIONS+ }:+ raise RuntimeError("Incompatible admission authority schema")+ placeholders = ",".join("?" for _ in tuple(_V11_EXISTING_COLUMNS) + V11_AUTHORITY_TABLES)+ async with connection.execute(+ 'SELECT m.name,p.name,p.type,p."notnull",p.dflt_value '+ "FROM sqlite_schema AS m JOIN pragma_table_info(m.name) AS p "+ "WHERE m.type='table' AND m.name IN (" + placeholders + ") ORDER BY m.name,p.cid",+ tuple(_V11_EXISTING_COLUMNS) + V11_AUTHORITY_TABLES,+ ) as cursor:+ rows = await cursor.fetchall()+ _validate_v11_columns(rows)+ _validate_v11_column_properties(rows, "sqlite")+ async with connection.execute(+ "SELECT type,name,tbl_name,sql FROM sqlite_schema WHERE "+ "(tbl_name IN ("+ + ",".join("?" for _ in V11_AUTHORITY_TABLES)+ + ") OR name IN ("+ + ",".join("?" for _ in _V11_EXISTING_CHECK_REQUIREMENTS)+ + ")) ORDER BY type,name",+ V11_AUTHORITY_TABLES + tuple(_V11_EXISTING_CHECK_REQUIREMENTS),+ ) as cursor:+ catalog_rows = await cursor.fetchall()+ async with connection.execute(+ 'SELECT m.name,il.name,il."unique",il.origin,il.partial,xi.seqno,xi.name '+ "FROM sqlite_schema AS m JOIN pragma_index_list(m.name) AS il "+ "JOIN pragma_index_xinfo(il.name) AS xi WHERE m.type='table' "+ "AND m.name IN ("+ + ",".join("?" for _ in V11_AUTHORITY_TABLES + ("credentials",))+ + ") AND xi.key=1 ORDER BY m.name,il.name,xi.seqno",+ V11_AUTHORITY_TABLES + ("credentials",),+ ) as cursor:+ index_rows = await cursor.fetchall()+ async with connection.execute(+ 'SELECT m.name,f.id,f.seq,f."table",f."from",f."to",f.on_update,f.on_delete '+ "FROM sqlite_schema AS m JOIN pragma_foreign_key_list(m.name) AS f "+ "WHERE m.type='table' AND m.name IN ("+ + ",".join("?" for _ in V11_AUTHORITY_TABLES)+ + ") ORDER BY m.name,f.id,f.seq",+ V11_AUTHORITY_TABLES,+ ) as cursor:+ foreign_rows = await cursor.fetchall()+ _validate_sqlite_v11_semantics(catalog_rows, index_rows, foreign_rows)+ _validate_v11_existing_checks(+ {str(row[1]): row[3] for row in catalog_rows if str(row[0]) == "table"}+ )+ async with connection.execute(+ "SELECT sql FROM sqlite_schema WHERE type='table' AND name='execution_operation_receipts'"+ ) as cursor:+ receipt = await cursor.fetchone()+ if receipt is None or not all(code in str(receipt[0]) for code in V11_OPERATION_CODES):+ raise RuntimeError("Incompatible admission authority schema")+ async with connection.execute(+ "SELECT name FROM sqlite_schema WHERE type='trigger' "+ "AND tbl_name='execution_operation_receipts' ORDER BY name"+ ) as cursor:+ triggers = await cursor.fetchall()+ if tuple(str(row[0]) for row in triggers) != (+ "trg_eor_immutable_delete",+ "trg_eor_immutable_update",+ ):+ raise RuntimeError("Incompatible admission authority schema")+ async with connection.execute(+ "SELECT sql FROM sqlite_schema WHERE type='table' AND name='credentials'"+ ) as cursor:+ credential_sql = await cursor.fetchone()+ if credential_sql is None:+ raise RuntimeError("Incompatible admission authority schema")+ checks = tuple(+ expression+ for expression in _balanced_check_expressions(credential_sql[0])+ if "execution_authority_" in expression.lower()+ )+ _validate_v11_credential_checks(checks)+++async def validate_postgresql_admission_authority_catalog(connection: Any) -> None:+ tables = list(tuple(_V11_EXISTING_COLUMNS) + V11_AUTHORITY_TABLES)+ rows = await connection.fetch(+ "SELECT table_name,column_name,data_type,is_nullable,column_default "+ "FROM information_schema.columns WHERE table_schema=current_schema() "+ "AND table_name=ANY($1::text[]) ORDER BY table_name,ordinal_position",+ tables,+ )+ properties = tuple(+ (+ row["table_name"],+ row["column_name"],+ row["data_type"],+ row["is_nullable"],+ row["column_default"],+ )+ for row in rows+ )+ _validate_v11_columns(properties)+ _validate_v11_column_properties(properties, "postgresql")+ relation_rows = await connection.fetch(+ "SELECT c.relname AS table_name,c.relkind::text AS relkind,"+ "c.relpersistence::text AS relpersistence,c.relispartition,"+ "c.relrowsecurity,c.relforcerowsecurity,"+ "(SELECT count(*) FROM pg_trigger t WHERE t.tgrelid=c.oid "+ "AND NOT t.tgisinternal) AS user_trigger_count,"+ "(SELECT count(*) FROM pg_policy p WHERE p.polrelid=c.oid) AS policy_count,"+ "(SELECT count(*) FROM pg_rewrite r WHERE r.ev_class=c.oid "+ "AND r.rulename<>'_RETURN') AS user_rule_count FROM pg_class c "+ "JOIN pg_namespace n ON n.oid=c.relnamespace WHERE n.nspname=current_schema() "+ "AND c.relkind IN ('r','p','v','m','f') AND ("+ "c.relname=ANY($1::text[]) OR "+ "c.relname LIKE 'campaign$_execution$_%' ESCAPE '$') ORDER BY c.relname",+ list(V11_AUTHORITY_TABLES),+ )+ collation_rows = await connection.fetch(+ "SELECT c.relname AS table_name,a.attname AS column_name,"+ "a.attcollation=t.typcollation AS collation_is_default FROM pg_class c "+ "JOIN pg_namespace n ON n.oid=c.relnamespace "+ "JOIN pg_attribute a ON a.attrelid=c.oid "+ "JOIN pg_type t ON t.oid=a.atttypid WHERE n.nspname=current_schema() "+ "AND c.relname=ANY($1::text[]) AND a.attnum>0 AND NOT a.attisdropped "+ "ORDER BY c.relname,a.attnum",+ tables,+ )+ constraint_rows = await connection.fetch(+ "SELECT c.relname AS table_name,con.conname AS constraint_name,"+ "con.contype::text AS constraint_type,"+ "ARRAY(SELECT a.attname FROM unnest(con.conkey) WITH ORDINALITY AS k(attnum,ord) "+ "JOIN pg_attribute a ON a.attrelid=con.conrelid AND a.attnum=k.attnum "+ "ORDER BY k.ord) AS local_columns,rc.relname AS referenced_table,"+ "ARRAY(SELECT a.attname FROM unnest(con.confkey) WITH ORDINALITY AS k(attnum,ord) "+ "JOIN pg_attribute a ON a.attrelid=con.confrelid AND a.attnum=k.attnum "+ "ORDER BY k.ord) AS referenced_columns,"+ "con.confupdtype::text AS update_action,"+ "con.confdeltype::text AS delete_action,"+ "con.condeferrable AS is_deferrable,"+ "con.condeferred AS is_deferred,con.convalidated AS is_validated,"+ "pg_get_expr(con.conbin,con.conrelid,false) AS definition "+ "FROM pg_constraint con JOIN pg_class c ON c.oid=con.conrelid "+ "JOIN pg_namespace n ON n.oid=c.relnamespace "+ "LEFT JOIN pg_class rc ON rc.oid=con.confrelid "+ "WHERE n.nspname=current_schema() AND c.relname=ANY($1::text[]) "+ "ORDER BY c.relname,con.conname",+ list(V11_AUTHORITY_TABLES),+ )+ index_rows = await connection.fetch(+ "SELECT c.relname AS table_name,ic.relname AS index_name,i.indisunique AS is_unique,"+ "i.indisprimary AS is_primary,i.indisvalid AS is_valid,i.indisready AS is_ready,"+ "am.amname AS method,pg_get_expr(i.indpred,i.indrelid,false) AS predicate,"+ "i.indexprs IS NOT NULL AS has_expressions,"+ "ARRAY(SELECT a.attname FROM unnest(i.indkey) WITH ORDINALITY AS k(attnum,ord) "+ "JOIN pg_attribute a ON a.attrelid=i.indrelid AND a.attnum=k.attnum "+ "WHERE k.ord<=i.indnkeyatts ORDER BY k.ord) AS key_columns "+ "FROM pg_index i JOIN pg_class c ON c.oid=i.indrelid "+ "JOIN pg_namespace n ON n.oid=c.relnamespace JOIN pg_class ic ON ic.oid=i.indexrelid "+ "JOIN pg_am am ON am.oid=ic.relam WHERE n.nspname=current_schema() "+ "AND (c.relname=ANY($1::text[]) OR ic.relname='ix_credentials_execution_authority') "+ "ORDER BY ic.relname",+ list(V11_AUTHORITY_TABLES),+ )+ existing_check_rows = await connection.fetch(+ "SELECT c.relname AS table_name,"+ "ARRAY(SELECT a.attname FROM unnest(con.conkey) WITH ORDINALITY AS k(attnum,ord) "+ "JOIN pg_attribute a ON a.attrelid=con.conrelid AND a.attnum=k.attnum "+ "ORDER BY k.ord) AS local_columns,pg_get_expr(con.conbin,con.conrelid,false) AS definition "+ "FROM pg_constraint con JOIN pg_class c ON c.oid=con.conrelid "+ "JOIN pg_namespace n ON n.oid=c.relnamespace WHERE n.nspname=current_schema() "+ "AND con.contype='c' AND c.relname=ANY($1::text[]) "+ "AND con.conkey <@ ARRAY(SELECT a.attnum FROM pg_attribute a "+ "WHERE a.attrelid=c.oid AND a.attname=ANY($2::text[])) "+ "ORDER BY c.relname,con.conname",+ list(_V11_EXISTING_CHECK_REQUIREMENTS),+ sorted(+ {column for columns in _V11_EXISTING_CHECK_REQUIREMENTS.values() for column in columns}+ ),+ )+ _validate_postgresql_v11_semantics(+ relation_rows,+ collation_rows,+ constraint_rows,+ index_rows,+ existing_check_rows,+ )+ definitions = await connection.fetch(+ "SELECT con.conname,pg_get_constraintdef(con.oid,true) AS definition "+ "FROM pg_constraint con JOIN pg_class c ON c.oid=con.conrelid "+ "JOIN pg_namespace n ON n.oid=c.relnamespace WHERE n.nspname=current_schema() "+ "AND c.relname='execution_operation_receipts' "+ "AND con.conname IN ('ck_eor_operation_code','ck_eor_operation_shape')",+ )+ if len(definitions) != 2 or not all(+ all(code in str(row["definition"]) for code in V11_ADDITIVE_OPERATION_CODES)+ for row in definitions+ if row["conname"] == "ck_eor_operation_code"+ ):+ raise RuntimeError("Incompatible admission authority schema")+++__all__ = [+ "ADMISSION_AUTHORITY_CONTRACT_V2",+ "ADMISSION_AUTHORITY_CONTRACT_V3",+ "ACTOR_ROLES",+ "AdmissionRequest",+ "AdmissionIntentV3",+ "ActorAuthorityMutation",+ "ApprovalBinding",+ "ApprovalAuthorityGrant",+ "ApprovalAuthorityMutation",+ "AttemptState",+ "AttemptPolicySnapshot",+ "BudgetConfiguration",+ "BudgetReservation",+ "BudgetSettlement",+ "CampaignActorGrantMutation",+ "CampaignAuthorityMutation",+ "ClosureRequest",+ "CAPABILITY_BITS_V1",+ "DESCRIPTOR_BLOCKER_BITS_V1",+ "DESCRIPTOR_CONTRACT_VERSION",+ "DESTINATION_NORMALIZATION_VERSION",+ "DestinationAuthorityMutation",+ "CredentialAuthorityMutation",+ "ExecutionLifecycleStore",+ "FixedResult",+ "GATEWAY_AUTHORITY_TARGET_ID",+ "GatewayAuthorityMutation",+ "LEGAL_TRANSITIONS",+ "LEGACY_SCHEMA_VERSION",+ "LIFECYCLE_TABLES",+ "MAX_I53",+ "MAX_TERMINAL_OUTPUTS_V3",+ "OperationResult",+ "OutcomeCode",+ "OutputKind",+ "OutputObservation",+ "OutboxMutation",+ "POSTGRES_LIFECYCLE_DDL",+ "POSTGRES_ADMISSION_AUTHORITY_V11_DDL",+ "POLICY_CONTRACT_VERSION",+ "PolicyReasonBit",+ "REQUEST_CONTRACT_VERSION",+ "RetryRequest",+ "RetryIntentV3",+ "RUNTIME_GENERATION",+ "RUNTIME_GENERATION_V11",+ "SYSTEM_PRINCIPAL_SUBJECT_REF",+ "SQLITE_LIFECYCLE_DDL",+ "SQLITE_ADMISSION_AUTHORITY_V11_DDL",+ "TransitionRequest",+ "TrustedPrincipal",+ "TerminalCommitRequest",+ "TerminalCommitIntentV3",+ "TERMINAL_COMMIT_CONTRACT_VERSION_V3",+ "canonical_operation_binding_digest",+ "admission_authority_v11_ddl",+ "lifecycle_ddl",+ "postgresql_catalog_fingerprint",+ "retry_delay_ms",+ "sqlite_lifecycle_script",+ "sqlite_lifecycle_runtime_script",+ "sqlite_admission_authority_runtime_script",+ "valid_uuid",+ "validate_sqlite_lifecycle_catalog",+ "validate_sqlite_lifecycle_catalog_async",+ "validate_sqlite_lifecycle_catalog_rows",+ "validate_postgresql_lifecycle_catalog",+ "validate_postgresql_admission_authority_catalog",+ "validate_sqlite_admission_authority_catalog",+ "validate_sqlite_admission_authority_catalog_async",+ "V11_ADDITIVE_OPERATION_CODES",+ "V11_AUTHORITY_TABLES",+ "V11_OPERATION_CODES",+ "validate_transition_request",+]diff --git a/ares/db/migrations/adoption.py b/ares/db/migrations/adoption.pyindex c143571..ffe2ad3 100644--- a/ares/db/migrations/adoption.py+++ b/ares/db/migrations/adoption.py@@ -63,10 +63,12 @@ SUPPORTED_GENERATIONS: Final[tuple[RuntimeGeneration, ...]] = (RuntimeGeneration("sqlite", 7, "0007", True),RuntimeGeneration("postgresql", 6, "0006", False),RuntimeGeneration("postgresql", 7, "0007", True),+ RuntimeGeneration("sqlite", 10, "runtime-0010", True),+ RuntimeGeneration("sqlite", 11, "runtime-0011", True),)_KNOWN_REVISIONS: Final[frozenset[str]] = frozenset(- f"{value:04d}" for value in range(1, 10)+ f"{value:04d}" for value in range(1, 12))_REVISION_FILES: Final[tuple[str, ...]] = ("0001_initial_schema.py",@@ -78,6 +80,8 @@ _REVISION_FILES: Final[tuple[str, ...]] = ("0007_add_websocket_tickets.py","0008_reconcile_schema_parity.py","0009_refresh_token_families.py",+ "0010_execution_lifecycle.py",+ "0011_execution_admission_authority.py",)_LOCK_KEY: Final[int] = int.from_bytes(hashlib.sha256(b"ARES-M2B-ADOPTION-LOCK-V1").digest()[:8],@@ -87,10 +91,10 @@ _LOCK_KEY: Final[int] = int.from_bytes(_FIXED_DIAGNOSTICS: Final[frozenset[str]] = frozenset({"ARES-M2B-EMPTY-DATABASE",- "ARES-M2B-ALREADY-MANAGED:0009",+ "ARES-M2B-ALREADY-MANAGED:0011","ARES-M2B-MIGRATION-REQUIRED",- "ARES-M2B-ADOPTED:SQLITE:0009",- "ARES-M2B-ADOPTED:POSTGRESQL:0009",+ "ARES-M2B-ADOPTED:SQLITE:0011",+ "ARES-M2B-ADOPTED:POSTGRESQL:0011","ARES-M2B-RESTORED:SQLITE","ARES-M2B-E02:USAGE","ARES-M2B-E03:CONFIGURATION",@@ -124,7 +128,7 @@ def _failure(exit_code: AdoptionExit, diagnostic: str) -> AdoptionFailure:def _revision_module() -> Any:- return import_module("migrations.versions.0009_refresh_token_families")+ return import_module("migrations.versions.0011_execution_admission_authority")@contextlib.contextmanager@@ -156,14 +160,14 @@ def migration_config(connection: Connection | None = None) -> Iterator[Config]:if connection is not None:cfg.attributes["connection"] = connectionscript = ScriptDirectory.from_config(cfg)- if script.get_heads() != ["0009"]:+ if script.get_heads() != ["0011"]:raise _failure(AdoptionExit.CONFIGURATION,"ARES-M2B-E03:CONFIGURATION",)revisions = tuple(script.walk_revisions(base="base", head="heads"))if tuple(item.revision for item in reversed(revisions)) != tuple(- f"{value:04d}" for value in range(1, 10)+ f"{value:04d}" for value in range(1, 12)):raise _failure(AdoptionExit.CONFIGURATION,@@ -254,10 +258,62 @@ def _is_empty(connection: Connection) -> bool:).first() is None+def _sqlite_catalog_signature(connection: Connection) -> tuple[tuple[str, ...], ...]:+ rows = connection.exec_driver_sql(+ "SELECT type,name,tbl_name,coalesce(sql,'') FROM sqlite_schema "+ "WHERE name NOT LIKE 'sqlite_%' ORDER BY type,name,tbl_name"+ ).fetchall()+ return tuple(tuple(str(value) for value in row) for row in rows)+++def _sqlite_reference_catalog_signature(script: str) -> tuple[tuple[str, ...], ...]:+ reference = sqlite3.connect(":memory:")+ try:+ reference.execute("PRAGMA foreign_keys=ON")+ reference.executescript(script)+ expected_rows = reference.execute(+ "SELECT type,name,tbl_name,coalesce(sql,'') FROM sqlite_schema "+ "WHERE name NOT LIKE 'sqlite_%' ORDER BY type,name,tbl_name"+ ).fetchall()+ expected = tuple(+ tuple(str(value) for value in row) for row in expected_rows+ )+ finally:+ reference.close()+ return expected+++def _is_sqlite_runtime_generation_10(connection: Connection) -> bool:+ """Recognize the exact unstamped predecessor runtime catalog."""+ if connection.dialect.name != "sqlite":+ return False+ from ares.db.execution_lifecycle import sqlite_admission_authority_runtime_script+ from ares.db.schema import CREATE_TABLES++ generation_11_script = sqlite_admission_authority_runtime_script()+ if not generation_11_script or not CREATE_TABLES.endswith(generation_11_script):+ return False+ generation_10_script = CREATE_TABLES[: -len(generation_11_script)]+ return _sqlite_catalog_signature(connection) == _sqlite_reference_catalog_signature(+ generation_10_script+ )+++def _is_sqlite_runtime_generation_11(connection: Connection) -> bool:+ """Recognize the exact unstamped current runtime catalog."""+ if connection.dialect.name != "sqlite":+ return False+ from ares.db.schema import CREATE_TABLES++ return _sqlite_catalog_signature(connection) == _sqlite_reference_catalog_signature(+ CREATE_TABLES+ )++def inspect_connection(connection: Connection) -> AdoptionResult:"""Classify one catalog without mutation or external dynamic diagnostics."""revision = _version_revision(connection)- if revision == "0009":+ if revision == "0011":try:_revision_module().verify_managed_catalog(connection)except (RuntimeError, sa.exc.SQLAlchemyError):@@ -267,7 +323,7 @@ def inspect_connection(connection: Connection) -> AdoptionResult:) from Nonereturn AdoptionResult(AdoptionExit.OK,- "ARES-M2B-ALREADY-MANAGED:0009",+ "ARES-M2B-ALREADY-MANAGED:0011",)if revision is not None:return AdoptionResult(@@ -277,6 +333,18 @@ def inspect_connection(connection: Connection) -> AdoptionResult:)if _is_empty(connection):return AdoptionResult(AdoptionExit.OK, "ARES-M2B-EMPTY-DATABASE")+ if _is_sqlite_runtime_generation_11(connection):+ return AdoptionResult(+ AdoptionExit.OK,+ "ARES-M2B-ADOPTION-READY:SQLITE:runtime-0011",+ "runtime-0011",+ )+ if _is_sqlite_runtime_generation_10(connection):+ return AdoptionResult(+ AdoptionExit.OK,+ "ARES-M2B-ADOPTION-READY:SQLITE:runtime-0010",+ "runtime-0010",+ )try:predecessor = _revision_module().classify_unversioned_catalog(connection)except (RuntimeError, sa.exc.SQLAlchemyError):@@ -294,7 +362,7 @@ def inspect_connection(connection: Connection) -> AdoptionResult:def verify_managed_connection(connection: Connection) -> AdoptionResult:result = inspect_connection(connection)- if result.diagnostic == "ARES-M2B-ALREADY-MANAGED:0009":+ if result.diagnostic == "ARES-M2B-ALREADY-MANAGED:0011":return resultif result.exit_code == AdoptionExit.MIGRATION_REQUIRED:raise _failure(@@ -313,7 +381,7 @@ def _adoption_predecessor(result: AdoptionResult) -> str:AdoptionExit.MIGRATION_REQUIRED,"ARES-M2B-E04:MIGRATION-REQUIRED",)- if result.predecessor not in {"0006", "0007"}:+ if result.predecessor not in {"0006", "0007", "runtime-0010", "runtime-0011"}:raise _failure(AdoptionExit.UNRECOGNIZED,"ARES-M2B-E06:UNRECOGNIZED-CATALOG",@@ -325,7 +393,7 @@ def _run_canonical_adoption(connection: Connection,predecessor: str,) -> None:- if predecessor not in {"0006", "0007"}:+ if predecessor not in {"0006", "0007", "runtime-0010", "runtime-0011"}:raise _failure(AdoptionExit.UNRECOGNIZED,"ARES-M2B-E06:UNRECOGNIZED-CATALOG",@@ -336,8 +404,16 @@ def _run_canonical_adoption(connection.info[adoption_marker] = Truetry:with migration_config(connection) as cfg:- command.stamp(cfg, predecessor)- command.upgrade(cfg, "0009")+ if predecessor == "runtime-0011":+ connection.exec_driver_sql("DROP TABLE schema_version")+ command.stamp(cfg, "0011")+ elif predecessor == "runtime-0010":+ connection.exec_driver_sql("DROP TABLE schema_version")+ command.stamp(cfg, "0010")+ command.upgrade(cfg, "0011")+ else:+ command.stamp(cfg, predecessor)+ command.upgrade(cfg, "0011")finally:if marked_sqlite:connection.info.pop(adoption_marker, None)@@ -623,7 +699,7 @@ def inspect_sqlite_database(path: str | Path) -> AdoptionResult:def adopt_sqlite(path: Path, backup: Path) -> AdoptionResult:initial = inspect_sqlite_database(path)- if initial.diagnostic == "ARES-M2B-ALREADY-MANAGED:0009":+ if initial.diagnostic == "ARES-M2B-ALREADY-MANAGED:0011":return initial_adoption_predecessor(initial)backup_digest = _create_sqlite_backup(path, backup)@@ -666,7 +742,7 @@ def adopt_sqlite(path: Path, backup: Path) -> AdoptionResult:rollback_proven = Falseraise_durable(path)- return AdoptionResult(AdoptionExit.OK, "ARES-M2B-ADOPTED:SQLITE:0009")+ return AdoptionResult(AdoptionExit.OK, "ARES-M2B-ADOPTED:SQLITE:0011")except (asyncio.CancelledError, KeyboardInterrupt, SystemExit, GeneratorExit):raiseexcept AdoptionFailure:@@ -774,7 +850,7 @@ async def _postgres_operation(url: URL, operation: str) -> AdoptionResult:"ARES-M2B-E07:OWNERSHIP-BUSY",)classified = await connection.run_sync(_sync_inspect)- if classified.diagnostic == "ARES-M2B-ALREADY-MANAGED:0009":+ if classified.diagnostic == "ARES-M2B-ALREADY-MANAGED:0011":already_managed = Trueelse:predecessor = _adoption_predecessor(classified)@@ -792,9 +868,9 @@ async def _postgres_operation(url: URL, operation: str) -> AdoptionResult:if already_managed:return AdoptionResult(AdoptionExit.OK,- "ARES-M2B-ALREADY-MANAGED:0009",+ "ARES-M2B-ALREADY-MANAGED:0011",)- return AdoptionResult(AdoptionExit.OK, "ARES-M2B-ADOPTED:POSTGRESQL:0009")+ return AdoptionResult(AdoptionExit.OK, "ARES-M2B-ADOPTED:POSTGRESQL:0011")finally:await engine.dispose()diff --git a/ares/db/postgres.py b/ares/db/postgres.pyindex d8b09c4..4dfdf22 100644--- a/ares/db/postgres.py+++ b/ares/db/postgres.py@@ -25,6 +25,7 @@ Production checklist:□ Run alembic upgrade head before first start□ Set max_connections in postgresql.conf to > (max_workers × pool_max + 5)"""+from __future__ import annotationsimport asyncio@@ -33,7 +34,7 @@ import jsonimport reimport secretsimport uuid-from datetime import datetime, timezone, timedelta+from datetime import datetime, timedelta, timezonefrom typing import Anyfrom ares.core.logger import get_logger@@ -53,13 +54,21 @@ from ares.core.token_sessions import (generate_refresh_token,hash_refresh_token,)+from ares.db.execution_lifecycle import (+ SYSTEM_PRINCIPAL_SUBJECT_REF,+ ExecutionLifecycleStore,+ FixedResult,+ OperationResult,+ valid_uuid,+ validate_postgresql_admission_authority_catalog,+)from ares.db.websocket_tickets import (+ WEBSOCKET_TICKET_TTL_SECONDS,ApiKeyTicketSource,BearerTicketSource,ConsumedWebSocketTicket,WebSocketTicketCredentialKind,WebSocketTicketPrincipal,- WEBSOCKET_TICKET_TTL_SECONDS,generate_websocket_ticket,hash_websocket_ticket,is_canonical_websocket_ticket,@@ -70,13 +79,24 @@ from ares.db.websocket_tickets import (logger = get_logger("ares.db.postgres")_REFRESH_TOKEN_LOCK_NAMESPACE = b"ares:refresh-token-user:v1\x00"+_CAMPAIGN_DELETE_OPERATION_DOMAIN = b"ares.campaign-delete.compat-operation.v1\x00"+++def _campaign_delete_operation_id(campaign_id: str) -> str:+ """Derive the stable UUIDv4-shaped identity for an implicit delete operation."""+ digest = bytearray(+ hashlib.sha256(_CAMPAIGN_DELETE_OPERATION_DOMAIN + campaign_id.encode("utf-8")).digest()[+ :16+ ]+ )+ digest[6] = (digest[6] & 0x0F) | 0x40+ digest[8] = (digest[8] & 0x3F) | 0x80+ return str(uuid.UUID(bytes=bytes(digest)))def _refresh_token_user_lock_key(user_id: str) -> int:"""Return a stable signed BIGINT key for a user's refresh-token writes."""- digest = hashlib.sha256(- _REFRESH_TOKEN_LOCK_NAMESPACE + user_id.encode("utf-8")- ).digest()+ digest = hashlib.sha256(_REFRESH_TOKEN_LOCK_NAMESPACE + user_id.encode("utf-8")).digest()return int.from_bytes(digest[:8], byteorder="big", signed=True)@@ -91,9 +111,7 @@ def _parse_postgres_timestamptz(value: str) -> datetime:"""Convert the public access-token expiry string to an aware datetime."""parsed = datetime.fromisoformat(value)if parsed.tzinfo is None:- parsed = datetime.strptime(value, "%Y-%m-%d %H:%M:%S").replace(- tzinfo=timezone.utc- )+ parsed = datetime.strptime(value, "%Y-%m-%d %H:%M:%S").replace(tzinfo=timezone.utc)return parsed.astimezone(timezone.utc)@@ -372,9 +390,7 @@ _POSTGRES_FALLBACK_DDL_CODES = ()-def _postgres_fallback_statement_spans() -> tuple[- tuple[str, int, int], ...-]:+def _postgres_fallback_statement_spans() -> tuple[tuple[str, int, int], ...]:spans: list[tuple[str, int, int]] = []start = 0for code in _POSTGRES_FALLBACK_DDL_CODES:@@ -414,12 +430,8 @@ _POSTGRES_TICKET_RELATION_PROPERTY_BITS = {"user_rule_count": 0x200,}_POSTGRES_TICKET_RELATION_PROPERTY_MASK = 0x3FF-_POSTGRES_TICKET_RELATION_AGGREGATE_ONLY = (- "ticket-relation-metadata:aggregate-comparison-only"-)-_POSTGRES_TICKET_RELATION_METADATA_PREFIX = (- "ticket-relation-metadata:"-)+_POSTGRES_TICKET_RELATION_AGGREGATE_ONLY = "ticket-relation-metadata:aggregate-comparison-only"+_POSTGRES_TICKET_RELATION_METADATA_PREFIX = "ticket-relation-metadata:"_POSTGRES_TICKET_RELATION_MISSING = object()_POSTGRES_TICKET_RELATION_UNREADABLE = object()@@ -541,11 +553,7 @@ def _postgres_ticket_relation_diagnostic_invariant():return "ticket-validation-unclassified"mismatched, alternate, unexpected, missing = masks- if any(- value < 0- or value & ~_POSTGRES_TICKET_RELATION_PROPERTY_MASK- for value in masks- ):+ if any(value < 0 or value & ~_POSTGRES_TICKET_RELATION_PROPERTY_MASK for value in masks):return "ticket-validation-unclassified"if (alternate & ~mismatched@@ -568,7 +576,7 @@ def _is_postgres_ticket_relation_diagnostic(invariant: str) -> bool:prefix = _POSTGRES_TICKET_RELATION_METADATA_PREFIXif not invariant.startswith(prefix):return False- parts = invariant[len(prefix):].split(";")+ parts = invariant[len(prefix) :].split(";")if len(parts) != 4:return Falseexpected_keys = ("m", "a", "x", "n")@@ -583,42 +591,110 @@ def _is_postgres_ticket_relation_diagnostic(invariant: str) -> bool:):return Falsevalues.append(int(encoded, 16))- return (- _postgres_ticket_relation_diagnostic_invariant(tuple(values))- == invariant- )+ return _postgres_ticket_relation_diagnostic_invariant(tuple(values)) == invariant_POSTGRES_TICKET_CENSUS_FIELDS = (- ("r", (("m", 0x3FF, 3), ("a", 0x3FF, 3), ("x", 0x3FF, 3),- ("n", 0x3FF, 3), ("g", 0x1, 1))),- ("c", (("m", 0x3FFF, 4), ("e", 0x1, 1), ("o", 0x3FFF, 4),- ("t", 0x3FFF, 4), ("u", 0x3FFF, 4), ("d", 0x3FFF, 4),- ("l", 0x3FFF, 4), ("i", 0x3FFF, 4), ("a", 0x3FFF, 4),- ("x", 0x3FFF, 4), ("g", 0x1, 1))),- ("q", (("m", 0xFFFF, 4), ("e", 0x1, 1), ("t", 0xFFFF, 4),- ("v", 0xFFFF, 4), ("f", 0xFFFF, 4), ("d", 0xFFFF, 4),- ("s", 0xFFFF, 4), ("b", 0xFFFF, 4), ("a", 0xFFFF, 4),- ("x", 0xFFFF, 4), ("g", 0x1, 1))),- ("p", (("l", 0x1, 1), ("r", 0x1, 1), ("n", 0x1, 1),- ("i", 0x1, 1), ("a", 0x1, 1), ("x", 0x1, 1),- ("g", 0x1, 1))),- ("h", (("t", 0x7FF, 3), ("v", 0x7FF, 3), ("f", 0x7FF, 3),- ("d", 0x7FF, 3), ("s", 0x7FF, 3), ("a", 0x7FF, 3),- ("x", 0x7FF, 3), ("g", 0x1, 1))),- ("f", (("l", 0xF, 1), ("s", 0xF, 1), ("t", 0xF, 1),- ("r", 0xF, 1), ("u", 0xF, 1), ("d", 0xF, 1),- ("i", 0xF, 1), ("a", 0xF, 1), ("x", 0xF, 1),- ("g", 0x1, 1))),- ("i", (("m", 0x3F, 2), ("e", 0x1, 1), ("o", 0x3F, 2),- ("b", 0x3F, 2), ("u", 0x3F, 2), ("p", 0x3F, 2),- ("v", 0x3F, 2), ("r", 0x3F, 2), ("l", 0x3F, 2),- ("k", 0x3F, 2), ("n", 0x3F, 2), ("c", 0x3F, 2),- ("d", 0x3F, 2), ("a", 0x3F, 2), ("j", 0x3F, 2),- ("s", 0x3F, 2), ("t", 0x3F, 2), ("y", 0x3F, 2),- ("h", 0x3F, 2), ("x", 0x3F, 2), ("g", 0x1, 1))),- ("o", (("m", 0x3, 1), ("e", 0x1, 1), ("x", 0x3, 1),- ("g", 0x1, 1))),+ ("r", (("m", 0x3FF, 3), ("a", 0x3FF, 3), ("x", 0x3FF, 3), ("n", 0x3FF, 3), ("g", 0x1, 1))),+ (+ "c",+ (+ ("m", 0x3FFF, 4),+ ("e", 0x1, 1),+ ("o", 0x3FFF, 4),+ ("t", 0x3FFF, 4),+ ("u", 0x3FFF, 4),+ ("d", 0x3FFF, 4),+ ("l", 0x3FFF, 4),+ ("i", 0x3FFF, 4),+ ("a", 0x3FFF, 4),+ ("x", 0x3FFF, 4),+ ("g", 0x1, 1),+ ),+ ),+ (+ "q",+ (+ ("m", 0xFFFF, 4),+ ("e", 0x1, 1),+ ("t", 0xFFFF, 4),+ ("v", 0xFFFF, 4),+ ("f", 0xFFFF, 4),+ ("d", 0xFFFF, 4),+ ("s", 0xFFFF, 4),+ ("b", 0xFFFF, 4),+ ("a", 0xFFFF, 4),+ ("x", 0xFFFF, 4),+ ("g", 0x1, 1),+ ),+ ),+ (+ "p",+ (+ ("l", 0x1, 1),+ ("r", 0x1, 1),+ ("n", 0x1, 1),+ ("i", 0x1, 1),+ ("a", 0x1, 1),+ ("x", 0x1, 1),+ ("g", 0x1, 1),+ ),+ ),+ (+ "h",+ (+ ("t", 0x7FF, 3),+ ("v", 0x7FF, 3),+ ("f", 0x7FF, 3),+ ("d", 0x7FF, 3),+ ("s", 0x7FF, 3),+ ("a", 0x7FF, 3),+ ("x", 0x7FF, 3),+ ("g", 0x1, 1),+ ),+ ),+ (+ "f",+ (+ ("l", 0xF, 1),+ ("s", 0xF, 1),+ ("t", 0xF, 1),+ ("r", 0xF, 1),+ ("u", 0xF, 1),+ ("d", 0xF, 1),+ ("i", 0xF, 1),+ ("a", 0xF, 1),+ ("x", 0xF, 1),+ ("g", 0x1, 1),+ ),+ ),+ (+ "i",+ (+ ("m", 0x3F, 2),+ ("e", 0x1, 1),+ ("o", 0x3F, 2),+ ("b", 0x3F, 2),+ ("u", 0x3F, 2),+ ("p", 0x3F, 2),+ ("v", 0x3F, 2),+ ("r", 0x3F, 2),+ ("l", 0x3F, 2),+ ("k", 0x3F, 2),+ ("n", 0x3F, 2),+ ("c", 0x3F, 2),+ ("d", 0x3F, 2),+ ("a", 0x3F, 2),+ ("j", 0x3F, 2),+ ("s", 0x3F, 2),+ ("t", 0x3F, 2),+ ("y", 0x3F, 2),+ ("h", 0x3F, 2),+ ("x", 0x3F, 2),+ ("g", 0x1, 1),+ ),+ ),+ ("o", (("m", 0x3, 1), ("e", 0x1, 1), ("x", 0x3, 1), ("g", 0x1, 1))),("z", (("q", 0x7F, 2), ("x", 0x7F, 2))),)@@ -841,13 +917,27 @@ def _is_postgres_q78_failure(value: str) -> bool:_POSTGRES_Q78_SPLIT_INDEX_FIELDS = (- ("m", 0x3F, 2), ("e", 0x1, 1), ("o", 0x3F, 2),- ("b", 0x3F, 2), ("u", 0x3F, 2), ("p", 0x3F, 2),- ("v", 0x3F, 2), ("r", 0x3F, 2), ("l", 0x3F, 2),- ("k", 0x3F, 2), ("n", 0x3F, 2), ("c", 0x3F, 2),- ("d", 0x3F, 2), ("a", 0x3F, 2), ("j", 0x3F, 2),- ("s", 0x3F, 2), ("t", 0x3F, 2), ("y", 0x3F, 2),- ("h", 0x3F, 2), ("x", 0x3F, 2), ("g", 0x1, 1),+ ("m", 0x3F, 2),+ ("e", 0x1, 1),+ ("o", 0x3F, 2),+ ("b", 0x3F, 2),+ ("u", 0x3F, 2),+ ("p", 0x3F, 2),+ ("v", 0x3F, 2),+ ("r", 0x3F, 2),+ ("l", 0x3F, 2),+ ("k", 0x3F, 2),+ ("n", 0x3F, 2),+ ("c", 0x3F, 2),+ ("d", 0x3F, 2),+ ("a", 0x3F, 2),+ ("j", 0x3F, 2),+ ("s", 0x3F, 2),+ ("t", 0x3F, 2),+ ("y", 0x3F, 2),+ ("h", 0x3F, 2),+ ("x", 0x3F, 2),+ ("g", 0x1, 1),)@@ -888,16 +978,14 @@ def _postgres_q78_split_invariant(query_failure,)if (- any(- type(value) is not int or not 0 <= value <= 0xF- for value in scalar_values[:-1]- )+ any(type(value) is not int or not 0 <= value <= 0xF for value in scalar_values[:-1])or type(query_failure) is not intor not 0 <= query_failure <= 0xF):return "q78-split-unclassified"return (- "q78-split:i=" + ",".join(encoded_index)+ "q78-split:i="+ + ",".join(encoded_index)+ f";p=i{primary_binding:x}"+ f";o=m{opclass_missing:x},e{opclass_extra:x},x{opclass_shape:x}"+ f";s=m{schema_mismatch:x},x{schema_shape:x}"@@ -991,34 +1079,104 @@ def _postgres_q78_index_split_census(section = {field: 0 for field, _maximum, _width in _POSTGRES_Q78_SPLIT_INDEX_FIELDS}expected = {"idx_ws_tickets_api_key": (- "btree", False, False, True, True, True,- 1, 1, ("api_key_id",), (0,), ("text_ops",), (True,), None, None,+ "btree",+ False,+ False,+ True,+ True,+ True,+ 1,+ 1,+ ("api_key_id",),+ (0,),+ ("text_ops",),+ (True,),+ None,+ None,),"idx_ws_tickets_bearer_family": (- "btree", False, False, True, True, True,- 1, 1, ("bearer_family_id",), (0,), ("text_ops",), (True,), None, None,+ "btree",+ False,+ False,+ True,+ True,+ True,+ 1,+ 1,+ ("bearer_family_id",),+ (0,),+ ("text_ops",),+ (True,),+ None,+ None,),"idx_ws_tickets_campaign": (- "btree", False, False, True, True, True,- 1, 1, ("campaign_id",), (0,), ("text_ops",), (True,), None, None,+ "btree",+ False,+ False,+ True,+ True,+ True,+ 1,+ 1,+ ("campaign_id",),+ (0,),+ ("text_ops",),+ (True,),+ None,+ None,),"idx_ws_tickets_expires": (- "btree", False, False, True, True, True,- 1, 1, ("expires_at",), (0,), ("timestamptz_ops",), (True,), None, None,+ "btree",+ False,+ False,+ True,+ True,+ True,+ 1,+ 1,+ ("expires_at",),+ (0,),+ ("timestamptz_ops",),+ (True,),+ None,+ None,),"idx_ws_tickets_user": (- "btree", False, False, True, True, True,- 1, 1, ("user_id",), (0,), ("text_ops",), (True,), None, None,+ "btree",+ False,+ False,+ True,+ True,+ True,+ 1,+ 1,+ ("user_id",),+ (0,),+ ("text_ops",),+ (True,),+ None,+ None,),"websocket_tickets_pkey": (- "btree", True, True, True, True, True,- 1, 1, ("ticket_hash",), (0,), ("text_ops",), (True,), None, None,+ "btree",+ True,+ True,+ True,+ True,+ True,+ 1,+ 1,+ ("ticket_hash",),+ (0,),+ ("text_ops",),+ (True,),+ None,+ None,),}expected_names = tuple(expected)- expected_ordinals = {- name: ordinal for ordinal, name in enumerate(expected_names)- }+ expected_ordinals = {name: ordinal for ordinal, name in enumerate(expected_names)}if type(rows) not in {list, tuple}:section["x"] = 0x3Freturn section, 1@@ -1034,30 +1192,21 @@ def _postgres_q78_index_split_census(ordinal = expected_ordinals.get(name)bit = 0 if ordinal is None else 1 << ordinalindex_oid = int(raw_row["index_oid"])- relkind, relkind_alternate, relkind_unexpected = (- _postgres_internal_character(raw_row["index_relkind"])+ relkind, relkind_alternate, relkind_unexpected = _postgres_internal_character(+ raw_row["index_relkind"])persistence, persistence_alternate, persistence_unexpected = (_postgres_internal_character(raw_row["index_relpersistence"]))- operator_classes = tuple(- str(value) for value in raw_row["operator_classes"]- )- operator_class_oids = tuple(- int(value) for value in raw_row["operator_class_oids"]- )- canonical_oids = tuple(- canonical_opclasses.get(value, -1) for value in operator_classes- )+ operator_classes = tuple(str(value) for value in raw_row["operator_classes"])+ operator_class_oids = tuple(int(value) for value in raw_row["operator_class_oids"])+ canonical_oids = tuple(canonical_opclasses.get(value, -1) for value in operator_classes)identity_noncodec_is_exact = (int(raw_row["table_oid"]) == table_oidand int(raw_row["index_schema_oid"]) == schema_oidand str(raw_row["index_schema"]) == schema_nameand not bool(raw_row["index_is_partition"])- and tuple(- str(value)- for value in raw_row["operator_class_namespaces"]- )+ and tuple(str(value) for value in raw_row["operator_class_namespaces"])== ("pg_catalog",)and operator_class_oids == canonical_oidsand index_oid not in index_oids@@ -1092,10 +1241,7 @@ def _postgres_q78_index_split_census(bool(raw_row["indislive"]),int(raw_row["indnkeyatts"]),int(raw_row["indnatts"]),- tuple(- None if value is None else str(value)- for value in raw_row["columns"]- ),+ tuple(None if value is None else str(value) for value in raw_row["columns"]),tuple(int(value) for value in raw_row["column_options"]),operator_classes,tuple(bool(value) for value in raw_row["column_collations_match"]),@@ -1111,8 +1257,7 @@ def _postgres_q78_index_split_census(for name in set(expected_names) - actual_name_set:section["m"] |= 1 << expected_ordinals[name]section["e"] = int(- bool(actual_name_set - set(expected_names))- or len(actual) != len(actual_names)+ bool(actual_name_set - set(expected_names)) or len(actual) != len(actual_names))for ordinal, name in enumerate(expected_names):bit = 1 << ordinal@@ -1123,10 +1268,20 @@ def _postgres_q78_index_split_census(continueexpected_item = expected[name]for field, position in (- ("b", 0), ("u", 1), ("p", 2), ("v", 3),- ("r", 4), ("l", 5), ("k", 6), ("n", 7),- ("c", 8), ("d", 9), ("a", 10), ("j", 11),- ("s", 12), ("t", 13),+ ("b", 0),+ ("u", 1),+ ("p", 2),+ ("v", 3),+ ("r", 4),+ ("l", 5),+ ("k", 6),+ ("n", 7),+ ("c", 8),+ ("d", 9),+ ("a", 10),+ ("j", 11),+ ("s", 12),+ ("t", 13),):if actual_item[position] != expected_item[position]:section[field] |= bit@@ -1137,10 +1292,7 @@ def _postgres_q78_index_split_census(for raw_row in constraint_rows:try:if raw_row["conname"] == "websocket_tickets_pkey":- primary_binding = int(- int(raw_row["constraint_index_oid"])- != primary_index_oid- )+ primary_binding = int(int(raw_row["constraint_index_oid"]) != primary_index_oid)breakexcept (KeyError, IndexError, TypeError, ValueError):continue@@ -1316,16 +1468,12 @@ async def _postgres_q78_split_observation(if type(opclass_rows) in {list, tuple}:try:canonical_opclasses = {- str(row["opcname"]): int(row["opclass_oid"])- for row in opclass_rows+ str(row["opcname"]): int(row["opclass_oid"]) for row in opclass_rows}- opclass_missing = (- int("text_ops" not in canonical_opclasses)- | (int("timestamptz_ops" not in canonical_opclasses) << 1)- )- opclass_extra = int(- bool(set(canonical_opclasses) - {"text_ops", "timestamptz_ops"})+ opclass_missing = int("text_ops" not in canonical_opclasses) | (+ int("timestamptz_ops" not in canonical_opclasses) << 1)+ opclass_extra = int(bool(set(canonical_opclasses) - {"text_ops", "timestamptz_ops"}))except (KeyError, IndexError, TypeError, ValueError):opclass_shape = 1else:@@ -1359,8 +1507,7 @@ async def _postgres_q78_split_observation(try:reference_names = [str(row["relname"]) for row in referenced_rows]reference_oids = {- str(row["relname"]): int(row["relation_oid"])- for row in referenced_rows+ str(row["relname"]): int(row["relation_oid"]) for row in referenced_rows}reference_missing = 0for ordinal, name in enumerate(expected_reference_names):@@ -1382,17 +1529,13 @@ async def _postgres_q78_split_observation(if type(constraint_rows) not in {list, tuple}:reference_binding = 0xFelse:- constraints = {- str(row["conname"]): row for row in constraint_rows- }+ constraints = {str(row["conname"]): row for row in constraint_rows}for ordinal, (constraint_name, relation_name) in enumerate(zip(expected_constraint_names, expected_reference_names, strict=True)):row = constraints.get(constraint_name)- if (- row is None- or int(row["referenced_oid"])- != reference_oids.get(relation_name)+ if row is None or int(row["referenced_oid"]) != reference_oids.get(+ relation_name):reference_binding |= 1 << ordinalexcept (KeyError, IndexError, TypeError, ValueError):@@ -1515,9 +1658,7 @@ def _postgres_ticket_column_census((raw_identity, expected_item[3]),(raw_generated, expected_item[4]),):- semantic, alternate, unexpected = _postgres_internal_character(- raw_internal- )+ semantic, alternate, unexpected = _postgres_internal_character(raw_internal)if unexpected:section["x"] |= bitelif semantic != expected_internal:@@ -1602,10 +1743,7 @@ def _postgres_operational_category(error: BaseException) -> str:return "timeout"if isinstance(error, ConnectionError):return "connection"- error_type_names = {- base.__name__- for base in type(error).__mro__- }+ error_type_names = {base.__name__ for base in type(error).__mro__}if error_type_names & {"PostgresError","InterfaceError",@@ -1631,24 +1769,16 @@ class _PostgresStartupDiagnosticError(RuntimeError):) -> None:super().__init__(public_message)self.diagnostic_stage = (- diagnostic_stage- if diagnostic_stage in _POSTGRES_STARTUP_STAGES- else "unclassified"+ diagnostic_stage if diagnostic_stage in _POSTGRES_STARTUP_STAGES else "unclassified")self.diagnostic_invariant = (diagnostic_invariantif (diagnostic_invariant in _POSTGRES_STARTUP_INVARIANTS- or _is_postgres_ticket_relation_diagnostic(- diagnostic_invariant- )- or _is_postgres_ticket_schema_census(- diagnostic_invariant- )+ or _is_postgres_ticket_relation_diagnostic(diagnostic_invariant)+ or _is_postgres_ticket_schema_census(diagnostic_invariant)or (- diagnostic_invariant.startswith(- ("managed-check-", "managed-foreign-")- )+ diagnostic_invariant.startswith(("managed-check-", "managed-foreign-"))and len(diagnostic_invariant)in {len("managed-check-00"), len("managed-foreign-00")}and diagnostic_invariant[-2:].isdigit()@@ -1658,16 +1788,11 @@ class _PostgresStartupDiagnosticError(RuntimeError):)self.operational_category = (operational_category- if operational_category- in _POSTGRES_STARTUP_OPERATIONAL_CATEGORIES+ if operational_category in _POSTGRES_STARTUP_OPERATIONAL_CATEGORIESelse "other")- self.q78_failure = (- q78_failure if _is_postgres_q78_failure(q78_failure) else ""- )- self.q78_split = (- q78_split if _is_postgres_q78_split(q78_split) else ""- )+ self.q78_failure = q78_failure if _is_postgres_q78_failure(q78_failure) else ""+ self.q78_split = q78_split if _is_postgres_q78_split(q78_split) else ""def _postgres_startup_diagnostic_label(error: BaseException) -> str:@@ -1683,24 +1808,14 @@ def _postgres_startup_diagnostic_label(error: BaseException) -> str:if (error.diagnostic_stage not in _POSTGRES_STARTUP_STAGESor (- error.diagnostic_invariant- not in _POSTGRES_STARTUP_INVARIANTS- and not _is_postgres_ticket_relation_diagnostic(- error.diagnostic_invariant- )- and not _is_postgres_ticket_schema_census(- error.diagnostic_invariant- )+ error.diagnostic_invariant not in _POSTGRES_STARTUP_INVARIANTS+ and not _is_postgres_ticket_relation_diagnostic(error.diagnostic_invariant)+ and not _is_postgres_ticket_schema_census(error.diagnostic_invariant))- or error.operational_category- not in _POSTGRES_STARTUP_OPERATIONAL_CATEGORIES+ or error.operational_category not in _POSTGRES_STARTUP_OPERATIONAL_CATEGORIES):return "unclassified"- label = (- f"{error.diagnostic_stage}:"- f"{error.diagnostic_invariant}:"- f"{error.operational_category}"- )+ label = f"{error.diagnostic_stage}:{error.diagnostic_invariant}:{error.operational_category}"if error.q78_failure or error.q78_split:if not error.q78_failure or not error.q78_split:return "unclassified"@@ -1715,11 +1830,7 @@ def _postgres_startup_error(invariant: str,cause: BaseException | None = None,) -> _PostgresStartupDiagnosticError:- category = (- "none"- if cause is None- else _postgres_operational_category(cause)- )+ category = "none" if cause is None else _postgres_operational_category(cause)return _PostgresStartupDiagnosticError(public_message,diagnostic_stage=stage,@@ -1769,16 +1880,25 @@ def _postgres_ticket_schema_error(invariant=invariant,cause=cause,)- error.q78_failure = (- q78_failure if _is_postgres_q78_failure(q78_failure) else ""- )+ error.q78_failure = q78_failure if _is_postgres_q78_failure(q78_failure) else ""error.q78_split = q78_split if _is_postgres_q78_split(q78_split) else ""return error-_POSTGRES_MANAGED_REVISION = "0009"+_POSTGRES_MANAGED_REVISION = "0011"_POSTGRES_OLDER_REVISIONS = frozenset(- {"0001", "0002", "0003", "0004", "0005", "0006", "0007", "0008"}+ {+ "0001",+ "0002",+ "0003",+ "0004",+ "0005",+ "0006",+ "0007",+ "0008",+ "0009",+ "0010",+ })_POSTGRES_MIGRATION_REQUIRED_ERROR = "PostgreSQL schema migration required"_POSTGRES_MANAGED_SCHEMA_ERROR = "Incompatible managed PostgreSQL schema"@@ -1826,6 +1946,11 @@ _POSTGRES_MANAGED_INDEXES = (("credentials", "idx_creds_campaign", ("campaign_id",)),("credentials", "idx_creds_username", ("username",)),("credentials", "idx_creds_type", ("cred_type",)),+ (+ "credentials",+ "ix_credentials_execution_authority",+ ("campaign_id", "execution_authority_state", "id"),+ ),("loot", "idx_loot_campaign", ("campaign_id",)),("loot", "idx_loot_type", ("loot_type",)),("audit_log", "idx_audit_campaign", ("campaign_id",)),@@ -2008,6 +2133,10 @@ _POSTGRES_MANAGED_FOREIGN_KEYS = ()_POSTGRES_MANAGED_UNIQUES = (+ ("findings", "uq_findings_campaign_id_id", ("campaign_id", "id")),+ ("credentials", "uq_credentials_campaign_id_id", ("campaign_id", "id")),+ ("hosts", "uq_hosts_campaign_id_id", ("campaign_id", "id")),+ ("loot", "uq_loot_campaign_id_id", ("campaign_id", "id")),("hosts", "uq_hosts_campaign_ip", ("campaign_id", "ip_address")),("users", "uq_users_username", ("username",)),(@@ -2056,6 +2185,17 @@ _POSTGRES_MANAGED_FINITE_CHECKS = (("revoked_access_tokens", "expires_at", False),)+_POSTGRES_V11_CREDENTIAL_AUTHORITY_COLUMNS = frozenset(+ {+ "execution_authority_state",+ "execution_authority_revision",+ "execution_authority_binding_digest",+ "execution_authority_latest_operation_id",+ "execution_authority_latest_operation_base_revision",+ "execution_authority_latest_operation_code",+ }+)+def _postgres_finite_check_name(table: str, column: str) -> str:if table == "module_runs":@@ -2147,21 +2287,19 @@ class PostgresDatabase:def __init__(self,- dsn: str,+ dsn: str,encryption_key: str | None = None,- pool_min: int = 2,- pool_max: int = 10,+ pool_min: int = 2,+ pool_max: int = 10,) -> None:# Strip SQLAlchemy dialect prefix — asyncpg uses plain postgres:// DSN- self._dsn = (- dsn- .replace("postgresql+asyncpg://", "postgresql://")- .replace("postgres+asyncpg://", "postgres://")+ self._dsn = dsn.replace("postgresql+asyncpg://", "postgresql://").replace(+ "postgres+asyncpg://", "postgres://")self._enc: DataEncryptor | None = DataEncryptor(encryption_key) if encryption_key else Noneself._pool_min = pool_minself._pool_max = pool_max- self._pool: Any = None # asyncpg.Pool+ self._pool: Any = None # asyncpg.Poolself._startup_trace: list[str] = []# ── Lifecycle ──────────────────────────────────────────────────────────────@@ -2202,10 +2340,7 @@ class PostgresDatabase:await pool.close()except Exception as cleanup_error:cleanup_category = _postgres_operational_category(cleanup_error)- primary.add_note(- "PostgreSQL startup cleanup failure "- f"[pool-close: {cleanup_category}]"- )+ primary.add_note(f"PostgreSQL startup cleanup failure [pool-close: {cleanup_category}]")finally:if self._pool is pool:self._pool = None@@ -2224,7 +2359,7 @@ class PostgresDatabase:@classmethodasync def create(cls,- dsn: str,+ dsn: str,encryption_key: str | None = None,) -> "PostgresDatabase":db = cls(dsn, encryption_key)@@ -2318,15 +2453,15 @@ class PostgresDatabase:relation_contract = (str(relation["relkind"]),str(relation["relpersistence"]),- bool(relation["relispartition"]),- bool(relation["relrowsecurity"]),- bool(relation["relforcerowsecurity"]),- int(relation["parent_count"]),- int(relation["child_count"]),- int(relation["policy_count"]),- int(relation["user_trigger_count"]),- int(relation["user_rule_count"]),- )+ bool(relation["relispartition"]),+ bool(relation["relrowsecurity"]),+ bool(relation["relforcerowsecurity"]),+ int(relation["parent_count"]),+ int(relation["child_count"]),+ int(relation["policy_count"]),+ int(relation["user_trigger_count"]),+ int(relation["user_rule_count"]),+ )except (KeyError, TypeError, ValueError):raise _PostgresManagedSchemaError(_POSTGRES_MANAGED_SCHEMA_ERROR,@@ -2337,10 +2472,8 @@ class PostgresDatabase:not isinstance(schema_name, str)or not schema_nameor type_oid <= 0- or type_contract- != (schema_name, "alembic_version", "c", table_oid)- or relation_contract- != ("r", "p", False, False, False, 0, 0, 0, 0, 0)+ or type_contract != (schema_name, "alembic_version", "c", table_oid)+ or relation_contract != ("r", "p", False, False, False, 0, 0, 0, 0, 0)):raise _PostgresManagedSchemaError(_POSTGRES_MANAGED_SCHEMA_ERROR,@@ -2571,17 +2704,9 @@ class PostgresDatabase:row["constraint_name"],tuple(str(column) for column in row["columns"]),tuple(int(option) for option in row["column_options"]),- tuple(- str(opclass) for opclass in row["operator_classes"]- ),- tuple(- str(namespace)- for namespace in row["operator_class_namespaces"]- ),- tuple(- bool(value)- for value in row["column_collations_match"]- ),+ tuple(str(opclass) for opclass in row["operator_classes"]),+ tuple(str(namespace) for namespace in row["operator_class_namespaces"]),+ tuple(bool(value) for value in row["column_collations_match"]),row["expressions"],row["predicate"],)@@ -2745,11 +2870,7 @@ class PostgresDatabase:0,))- actual = (- metadata[1:4]- if table == "websocket_tickets"- else metadata[1:11]- )+ actual = metadata[1:4] if table == "websocket_tickets" else metadata[1:11](table_schema,type_oid,@@ -2769,9 +2890,7 @@ class PostgresDatabase:):raise RuntimeError(_POSTGRES_MANAGED_SCHEMA_ERROR)- non_ticket_tables = sorted(- _POSTGRES_MANAGED_TABLES - {"websocket_tickets"}- )+ non_ticket_tables = sorted(_POSTGRES_MANAGED_TABLES - {"websocket_tickets"})legacy_index_rows = await connection.fetch("""SELECT table_rel.relname AS table_name,@@ -2898,17 +3017,9 @@ class PostgresDatabase:int(row["indnkeyatts"]),int(row["indnatts"]),tuple(int(option) for option in row["column_options"]),- tuple(- str(opclass) for opclass in row["operator_classes"]- ),- tuple(- str(namespace)- for namespace in row["operator_class_namespaces"]- ),- tuple(- bool(value)- for value in row["column_collations_match"]- ),+ tuple(str(opclass) for opclass in row["operator_classes"]),+ tuple(str(namespace) for namespace in row["operator_class_namespaces"]),+ tuple(bool(value) for value in row["column_collations_match"]),row["expressions"],)for row in index_rows@@ -2916,8 +3027,7 @@ class PostgresDatabase:except (KeyError, TypeError, ValueError):raise RuntimeError(_POSTGRES_MANAGED_SCHEMA_ERROR) from Noneexpected_indexes = {- (table, name): columns- for table, name, columns in _POSTGRES_MANAGED_INDEXES+ (table, name): columns for table, name, columns in _POSTGRES_MANAGED_INDEXES}if set(index_contract) != set(expected_indexes):raise RuntimeError(_POSTGRES_MANAGED_SCHEMA_ERROR)@@ -2943,10 +3053,7 @@ class PostgresDatabase:len(columns),len(columns),(0,) * len(columns),- tuple(- _postgres_index_opclass(key[0], column)- for column in columns- ),+ tuple(_postgres_index_opclass(key[0], column) for column in columns),("pg_catalog",) * len(columns),(True,) * len(columns),None,@@ -3015,29 +3122,32 @@ class PostgresDatabase:except (KeyError, TypeError, ValueError):raise RuntimeError(_POSTGRES_MANAGED_SCHEMA_ERROR) from Noneexpected_primary_keys = {- (table, name): columns- for table, name, columns in _POSTGRES_MANAGED_PRIMARY_KEYS+ (table, name): columns for table, name, columns in _POSTGRES_MANAGED_PRIMARY_KEYS}if set(primary_contract) != set(expected_primary_keys):raise RuntimeError(_POSTGRES_MANAGED_SCHEMA_ERROR)for key, columns in expected_primary_keys.items():actual = primary_contract[key]- if actual != (- "p",- True,- False,- False,- columns,- actual[5],- "i",- "p",- False,- True,- True,- True,- True,- True,- ) or actual[5] <= 0:+ if (+ actual+ != (+ "p",+ True,+ False,+ False,+ columns,+ actual[5],+ "i",+ "p",+ False,+ True,+ True,+ True,+ True,+ True,+ )+ or actual[5] <= 0+ ):raise RuntimeError(_POSTGRES_MANAGED_SCHEMA_ERROR)await PostgresDatabase._validate_managed_constraints(@@ -3166,9 +3276,36 @@ class PostgresDatabase:non_ticket_tables,)try:+ delegated_v11_checks = tuple(+ row+ for row in rows+ if str(row["table_name"]) == "credentials"+ and str(row["contype"]) == "c"+ and tuple(str(column) for column in row["local_columns"])+ in {+ (column,)+ for column in _POSTGRES_V11_CREDENTIAL_AUTHORITY_COLUMNS+ }+ )+ if (+ len(delegated_v11_checks)+ != len(_POSTGRES_V11_CREDENTIAL_AUTHORITY_COLUMNS)+ or {+ str(row["local_columns"][0])+ for row in delegated_v11_checks+ }+ != _POSTGRES_V11_CREDENTIAL_AUTHORITY_COLUMNS+ ):+ raise ValueError+ delegated_v11_keys = {+ (str(row["table_name"]), str(row["conname"]))+ for row in delegated_v11_checks+ }actual = {(str(row["table_name"]), str(row["conname"])): rowfor row in rows+ if (str(row["table_name"]), str(row["conname"]))+ not in delegated_v11_keys}except (KeyError, TypeError, ValueError):raise RuntimeError(_POSTGRES_MANAGED_SCHEMA_ERROR) from None@@ -3192,8 +3329,7 @@ class PostgresDatabase:) in _POSTGRES_MANAGED_FOREIGN_KEYS}expected_unique = {- (table, name): columns- for table, name, columns in _POSTGRES_MANAGED_UNIQUES+ (table, name): columns for table, name, columns in _POSTGRES_MANAGED_UNIQUES}expected_checks = {(@@ -3204,9 +3340,7 @@ class PostgresDatabase:if nullableelse f"CHECK (isfinite({column}))")- for table, column, nullable in (- _POSTGRES_MANAGED_FINITE_CHECKS- )+ for table, column, nullable in (_POSTGRES_MANAGED_FINITE_CHECKS)}expected_checks[(@@ -3216,15 +3350,11 @@ class PostgresDatabase:] = "CHECK (blocked = ANY (ARRAY[0, 1]))"expected_checks.update({- ("users", "ck_users_auth_epoch"): (- "CHECK (auth_epoch >= 1)"- ),+ ("users", "ck_users_auth_epoch"): ("CHECK (auth_epoch >= 1)"),("refresh_token_families", "ck_refresh_family_id"): ("CHECK (id ~ '^[A-Za-z0-9_-]{43}$'::text)"),- ("refresh_token_families", "ck_refresh_family_epoch"): (- "CHECK (auth_epoch >= 1)"- ),+ ("refresh_token_families", "ck_refresh_family_epoch"): ("CHECK (auth_epoch >= 1)"),("refresh_token_families", "ck_refresh_family_state"): ("CHECK (state = ANY (ARRAY['active'::text, 'revoked'::text]))"),@@ -3258,16 +3388,13 @@ class PostgresDatabase:("refresh_tokens", "ck_refresh_token_hash"): ("CHECK (id ~ '^[0-9a-f]{64}$'::text)"),- ("refresh_tokens", "ck_refresh_token_generation"): (- "CHECK (generation >= 0)"- ),+ ("refresh_tokens", "ck_refresh_token_generation"): ("CHECK (generation >= 0)"),("refresh_tokens", "ck_refresh_token_parent_shape"): ("CHECK (generation = 0 AND parent_id IS NULL ""OR generation > 0 AND parent_id IS NOT NULL)"),("refresh_tokens", "ck_refresh_token_state"): (- "CHECK (state = ANY (ARRAY['active'::text, "- "'consumed'::text, 'retired'::text]))"+ "CHECK (state = ANY (ARRAY['active'::text, 'consumed'::text, 'retired'::text]))"),("refresh_tokens", "ck_refresh_token_state_shape"): ("CHECK (state = 'active'::text AND is_revoked = 0 "@@ -3282,12 +3409,11 @@ class PostgresDatabase:),})- expected_keys = (- set(expected_foreign)- | set(expected_unique)- | set(expected_checks)- )- if len(rows) != len(actual) or set(actual) != expected_keys:+ expected_keys = set(expected_foreign) | set(expected_unique) | set(expected_checks)+ if (+ len(rows) - len(delegated_v11_checks) != len(actual)+ or set(actual) != expected_keys+ ):raise RuntimeError(_POSTGRES_MANAGED_SCHEMA_ERROR)for key, contract in actual.items():@@ -3298,19 +3424,11 @@ class PostgresDatabase:bool(contract["condeferrable"]),bool(contract["condeferred"]),)- definition = _postgres_constraint_definition(- contract["definition"]- )- local_columns = tuple(- str(column) for column in contract["local_columns"]- )- remote_columns = tuple(- str(column) for column in contract["remote_columns"]- )+ definition = _postgres_constraint_definition(contract["definition"])+ local_columns = tuple(str(column) for column in contract["local_columns"])+ remote_columns = tuple(str(column) for column in contract["remote_columns"])except (KeyError, TypeError, ValueError):- raise RuntimeError(- _POSTGRES_MANAGED_SCHEMA_ERROR- ) from None+ raise RuntimeError(_POSTGRES_MANAGED_SCHEMA_ERROR) from Noneexpected_common = ((True, True, True)if key == ("refresh_tokens", "fk_refresh_token_parent")@@ -3355,8 +3473,7 @@ class PostgresDatabase:or definition != expected_definitionor local_columns != expected_localor remote_columns != expected_remote- or str(contract["referenced_schema"])- != source_schema+ or str(contract["referenced_schema"]) != source_schemaor str(contract["referenced_table"]) != parentor str(contract["confupdtype"]) != "a"or str(contract["confdeltype"]) != delete_code@@ -3378,37 +3495,18 @@ class PostgresDatabase:bool(contract["indislive"]),int(contract["indnkeyatts"]),int(contract["indnatts"]),+ tuple(str(column) for column in contract["index_columns"]),+ tuple(int(option) for option in contract["column_options"]),+ tuple(str(opclass) for opclass in contract["operator_classes"]),tuple(- str(column)- for column in contract["index_columns"]- ),- tuple(- int(option)- for option in contract["column_options"]- ),- tuple(- str(opclass)- for opclass in contract["operator_classes"]- ),- tuple(- str(namespace)- for namespace in contract[- "operator_class_namespaces"- ]- ),- tuple(- bool(value)- for value in contract[- "column_collations_match"- ]+ str(namespace) for namespace in contract["operator_class_namespaces"]),+ tuple(bool(value) for value in contract["column_collations_match"]),contract["expressions"],contract["predicate"],)except (KeyError, TypeError, ValueError):- raise RuntimeError(- _POSTGRES_MANAGED_SCHEMA_ERROR- ) from None+ raise RuntimeError(_POSTGRES_MANAGED_SCHEMA_ERROR) from Nonereference_index_name = {("refresh_tokens",@@ -3420,29 +3518,33 @@ class PostgresDatabase:): "uq_refresh_token_family_hash",}.get(key, f"{parent}_pkey")reference_is_primary = reference_index_name.endswith("_pkey")- if foreign_index_contract != (- foreign_index_contract[0],- source_schema,- reference_index_name,- "i",- "p",- False,- "btree",- True,- reference_is_primary,- True,- True,- True,- len(expected_remote),- len(expected_remote),- expected_remote,- (0,) * len(expected_remote),- ("text_ops",) * len(expected_remote),- ("pg_catalog",) * len(expected_remote),- (True,) * len(expected_remote),- None,- None,- ) or foreign_index_contract[0] <= 0:+ if (+ foreign_index_contract+ != (+ foreign_index_contract[0],+ source_schema,+ reference_index_name,+ "i",+ "p",+ False,+ "btree",+ True,+ reference_is_primary,+ True,+ True,+ True,+ len(expected_remote),+ len(expected_remote),+ expected_remote,+ (0,) * len(expected_remote),+ ("text_ops",) * len(expected_remote),+ ("pg_catalog",) * len(expected_remote),+ (True,) * len(expected_remote),+ None,+ None,+ )+ or foreign_index_contract[0] <= 0+ ):ordinal = sorted(expected_foreign).index(key)raise _PostgresManagedSchemaError(_POSTGRES_MANAGED_SCHEMA_ERROR,@@ -3474,68 +3576,48 @@ class PostgresDatabase:bool(contract["indislive"]),int(contract["indnkeyatts"]),int(contract["indnatts"]),- tuple(- str(column)- for column in contract["index_columns"]- ),- tuple(- int(option)- for option in contract["column_options"]- ),- tuple(- str(opclass)- for opclass in contract["operator_classes"]- ),- tuple(- str(namespace)- for namespace in (- contract["operator_class_namespaces"]- )- ),- tuple(- bool(value)- for value in contract[- "column_collations_match"- ]- ),+ tuple(str(column) for column in contract["index_columns"]),+ tuple(int(option) for option in contract["column_options"]),+ tuple(str(opclass) for opclass in contract["operator_classes"]),+ tuple(str(namespace) for namespace in (contract["operator_class_namespaces"])),+ tuple(bool(value) for value in contract["column_collations_match"]),contract["expressions"],contract["predicate"],)except (KeyError, TypeError, ValueError):- raise RuntimeError(- _POSTGRES_MANAGED_SCHEMA_ERROR- ) from None- if unique_contract != (- "u",- expected_definition,- columns,- None,- None,- (),- source_schema,- key[1],- "i",- "p",- False,- "btree",- True,- False,- True,- True,- True,- len(columns),- len(columns),- columns,- (0,) * len(columns),- tuple(- _postgres_index_opclass(key[0], column)- for column in columns- ),- ("pg_catalog",) * len(columns),- (True,) * len(columns),- None,- None,- ) or int(contract["constraint_index_oid"]) <= 0:+ raise RuntimeError(_POSTGRES_MANAGED_SCHEMA_ERROR) from None+ if (+ unique_contract+ != (+ "u",+ expected_definition,+ columns,+ None,+ None,+ (),+ source_schema,+ key[1],+ "i",+ "p",+ False,+ "btree",+ True,+ False,+ True,+ True,+ True,+ len(columns),+ len(columns),+ columns,+ (0,) * len(columns),+ tuple(_postgres_index_opclass(key[0], column) for column in columns),+ ("pg_catalog",) * len(columns),+ (True,) * len(columns),+ None,+ None,+ )+ or int(contract["constraint_index_oid"]) <= 0+ ):raise RuntimeError(_POSTGRES_MANAGED_SCHEMA_ERROR)@staticmethod@@ -3640,9 +3722,7 @@ class PostgresDatabase:row["column_default"],)except (KeyError, TypeError, ValueError):- raise RuntimeError(- _POSTGRES_MANAGED_SCHEMA_ERROR- ) from None+ raise RuntimeError(_POSTGRES_MANAGED_SCHEMA_ERROR) from Noneif owner is None or name in seen:raise RuntimeError(_POSTGRES_MANAGED_SCHEMA_ERROR)if contract != (@@ -3693,6 +3773,7 @@ class PostgresDatabase:try:await self._validate_managed_schema(conn)await self._validate_websocket_ticket_schema(conn)+ await validate_postgresql_admission_authority_catalog(conn)except _PostgresMigrationRequiredError:raiseexcept _PostgresStartupDiagnosticError as exc:@@ -3707,9 +3788,7 @@ class PostgresDatabase:raise _PostgresManagedSchemaError(_POSTGRES_MANAGED_SCHEMA_ERROR,diagnostic_stage="managed-validation",- diagnostic_invariant=(- "managed-validation-unclassified"- ),+ diagnostic_invariant=("managed-validation-unclassified"),) from Noneraise _postgres_startup_error(_POSTGRES_SCHEMA_VALIDATION_ERROR,@@ -3800,12 +3879,8 @@ class PostgresDatabase:schema_oid = int(relation["schema_oid"])schema_name = str(relation["schema_name"])if not _postgres_ticket_relation_is_canonical(relation):- relation_masks = _postgres_ticket_relation_diagnostic_masks(- relation- )- for field, value in zip(- ("m", "a", "x", "n"), relation_masks, strict=True- ):+ relation_masks = _postgres_ticket_relation_diagnostic_masks(relation)+ for field, value in zip(("m", "a", "x", "n"), relation_masks, strict=True):census["r"][field] = valueif relation_masks == (0, 0, 0, 0):census["r"]["g"] = 1@@ -3952,10 +4027,7 @@ class PostgresDatabase:constraint_rows = []census["z"]["q"] |= 0x04rejected = True- actual_constraints = {- str(row["conname"]): row- for row in constraint_rows- }+ actual_constraints = {str(row["conname"]): row for row in constraint_rows}expected_constraint_names = {"ck_ws_ticket_bearer_expires_finite","ck_ws_ticket_consumed_at",@@ -3975,8 +4047,7 @@ class PostgresDatabase:"websocket_tickets_pkey",}constraint_ordinals = {- name: ordinal- for ordinal, name in enumerate(sorted(expected_constraint_names))+ name: ordinal for ordinal, name in enumerate(sorted(expected_constraint_names))}if set(actual_constraints) != expected_constraint_names:for name in expected_constraint_names - set(actual_constraints):@@ -3999,8 +4070,10 @@ class PostgresDatabase:raiseexcept Exception:q78_split = _postgres_q78_split_invariant(- {field: (0x3F if field == "x" else 0)- for field, _maximum, _width in _POSTGRES_Q78_SPLIT_INDEX_FIELDS},+ {+ field: (0x3F if field == "x" else 0)+ for field, _maximum, _width in _POSTGRES_Q78_SPLIT_INDEX_FIELDS+ },primary_binding=1,opclass_missing=3,opclass_extra=0,@@ -4135,36 +4208,29 @@ class PostgresDatabase:subphase=_postgres_q78_subphase(exc),)canonical_opclasses = {- str(row["opcname"]): int(row["opclass_oid"])- for row in canonical_opclass_rows+ str(row["opcname"]): int(row["opclass_oid"]) for row in canonical_opclass_rows}if set(canonical_opclasses) != {"text_ops", "timestamptz_ops"}:- census["o"]["m"] = (- int("text_ops" not in canonical_opclasses)- | (int("timestamptz_ops" not in canonical_opclasses) << 1)- )- census["o"]["e"] = int(- bool(set(canonical_opclasses) - {"text_ops", "timestamptz_ops"})+ census["o"]["m"] = int("text_ops" not in canonical_opclasses) | (+ int("timestamptz_ops" not in canonical_opclasses) << 1)+ census["o"]["e"] = int(bool(set(canonical_opclasses) - {"text_ops", "timestamptz_ops"}))rejected = Trueindex_oids: set[int] = set()index_identity_failures: set[str] = set()index_identity_alternates: set[str] = set()for row in index_rows:- operator_classes = tuple(- str(opclass) for opclass in row["operator_classes"]- )+ operator_classes = tuple(str(opclass) for opclass in row["operator_classes"])operator_class_oids = tuple(int(opclass_oid) for opclass_oid in row["operator_class_oids"])canonical_oids = tuple(- canonical_opclasses.get(opclass, -1)- for opclass in operator_classes+ canonical_opclasses.get(opclass, -1) for opclass in operator_classes)index_oid = int(row["index_oid"])- relkind, relkind_alternate, relkind_unexpected = (- _postgres_internal_character(row["index_relkind"])+ relkind, relkind_alternate, relkind_unexpected = _postgres_internal_character(+ row["index_relkind"])persistence, persistence_alternate, persistence_unexpected = (_postgres_internal_character(row["index_relpersistence"])@@ -4174,10 +4240,7 @@ class PostgresDatabase:and int(row["index_schema_oid"]) == schema_oidand str(row["index_schema"]) == schema_nameand not bool(row["index_is_partition"])- and tuple(- str(namespace)- for namespace in row["operator_class_namespaces"]- )+ and tuple(str(namespace) for namespace in row["operator_class_namespaces"])== ("pg_catalog",) * len(operator_classes)and operator_class_oids == canonical_oidsand index_oid > 0@@ -4213,10 +4276,7 @@ class PostgresDatabase:bool(row["indislive"]),int(row["indnkeyatts"]),int(row["indnatts"]),- tuple(- None if column is None else str(column)- for column in row["columns"]- ),+ tuple(None if column is None else str(column) for column in row["columns"]),tuple(int(option) for option in row["column_options"]),tuple(str(opclass) for opclass in row["operator_classes"]),tuple(bool(value) for value in row["column_collations_match"]),@@ -4227,37 +4287,105 @@ class PostgresDatabase:}expected_indexes = {"idx_ws_tickets_api_key": (- "btree", False, False, True, True, True,- 1, 1, ("api_key_id",), (0,), ("text_ops",), (True,), None, None,+ "btree",+ False,+ False,+ True,+ True,+ True,+ 1,+ 1,+ ("api_key_id",),+ (0,),+ ("text_ops",),+ (True,),+ None,+ None,),"idx_ws_tickets_bearer_family": (- "btree", False, False, True, True, True,- 1, 1, ("bearer_family_id",), (0,), ("text_ops",), (True,),- None, None,+ "btree",+ False,+ False,+ True,+ True,+ True,+ 1,+ 1,+ ("bearer_family_id",),+ (0,),+ ("text_ops",),+ (True,),+ None,+ None,),"idx_ws_tickets_campaign": (- "btree", False, False, True, True, True,- 1, 1, ("campaign_id",), (0,), ("text_ops",), (True,), None, None,+ "btree",+ False,+ False,+ True,+ True,+ True,+ 1,+ 1,+ ("campaign_id",),+ (0,),+ ("text_ops",),+ (True,),+ None,+ None,),"idx_ws_tickets_expires": (- "btree", False, False, True, True, True,- 1, 1, ("expires_at",), (0,), ("timestamptz_ops",), (True,),- None, None,+ "btree",+ False,+ False,+ True,+ True,+ True,+ 1,+ 1,+ ("expires_at",),+ (0,),+ ("timestamptz_ops",),+ (True,),+ None,+ None,),"idx_ws_tickets_user": (- "btree", False, False, True, True, True,- 1, 1, ("user_id",), (0,), ("text_ops",), (True,), None, None,+ "btree",+ False,+ False,+ True,+ True,+ True,+ 1,+ 1,+ ("user_id",),+ (0,),+ ("text_ops",),+ (True,),+ None,+ None,),"websocket_tickets_pkey": (- "btree", True, True, True, True, True,- 1, 1, ("ticket_hash",), (0,), ("text_ops",), (True,), None, None,+ "btree",+ True,+ True,+ True,+ True,+ True,+ 1,+ 1,+ ("ticket_hash",),+ (0,),+ ("text_ops",),+ (True,),+ None,+ None,),}if actual_indexes != expected_indexes:expected_index_names = tuple(expected_indexes)- index_ordinals = {- name: ordinal for ordinal, name in enumerate(expected_index_names)- }+ index_ordinals = {name: ordinal for ordinal, name in enumerate(expected_index_names)}actual_index_names = tuple(str(row["index_name"]) for row in index_rows)actual_index_name_set = set(actual_index_names)for name in set(expected_index_names) - actual_index_name_set:@@ -4275,18 +4403,26 @@ class PostgresDatabase:continueexpected = expected_indexes[name]for field, position in (- ("b", 0), ("u", 1), ("p", 2), ("v", 3),- ("r", 4), ("l", 5), ("k", 6), ("n", 7),- ("c", 8), ("d", 9), ("a", 10), ("j", 11),- ("s", 12), ("t", 13),+ ("b", 0),+ ("u", 1),+ ("p", 2),+ ("v", 3),+ ("r", 4),+ ("l", 5),+ ("k", 6),+ ("n", 7),+ ("c", 8),+ ("d", 9),+ ("a", 10),+ ("j", 11),+ ("s", 12),+ ("t", 13),):if actual[position] != expected[position]:census["i"][field] |= bitrejected = True- expected_index_ordinals = {- name: ordinal for ordinal, name in enumerate(expected_indexes)- }+ expected_index_ordinals = {name: ordinal for ordinal, name in enumerate(expected_indexes)}for name in index_identity_failures:ordinal = expected_index_ordinals.get(name)if ordinal is None:@@ -4325,9 +4461,7 @@ class PostgresDatabase:if row is None:continuebit = 1 << constraint_ordinals[name]- contype, alternate, unexpected = _postgres_internal_character(- row["contype"]- )+ contype, alternate, unexpected = _postgres_internal_character(row["contype"])mismatch = Falseif unexpected:census["q"]["x"] |= bit@@ -4358,11 +4492,7 @@ class PostgresDatabase:"fetchval","SELECT current_schema()",)- referenced_schema = (- raw_referenced_schema- if type(raw_referenced_schema) is str- else ""- )+ referenced_schema = raw_referenced_schema if type(raw_referenced_schema) is str else ""if not referenced_schema:census["z"]["x"] |= 0x20rejected = True@@ -4380,13 +4510,28 @@ class PostgresDatabase:)expected_foreign_keys = {"fk_ws_ticket_campaign": (- ("campaign_id",), referenced_schema, "campaigns", ("id",), "a", "c",+ ("campaign_id",),+ referenced_schema,+ "campaigns",+ ("id",),+ "a",+ "c",),"fk_ws_ticket_user": (- ("user_id",), referenced_schema, "users", ("id",), "a", "c",+ ("user_id",),+ referenced_schema,+ "users",+ ("id",),+ "a",+ "c",),"fk_ws_ticket_api_key": (- ("api_key_id",), referenced_schema, "api_keys", ("id",), "a", "c",+ ("api_key_id",),+ referenced_schema,+ "api_keys",+ ("id",),+ "a",+ "c",),"fk_ws_ticket_bearer_family": (("bearer_family_id", "user_id"),@@ -4422,10 +4567,7 @@ class PostgresDatabase:exc,subphase=_postgres_q78_subphase(exc),)- referenced_oids = {- str(row["relname"]): int(row["relation_oid"])- for row in referenced_rows- }+ referenced_oids = {str(row["relname"]): int(row["relation_oid"]) for row in referenced_rows}if set(referenced_oids) != {"api_keys","campaigns",@@ -4441,9 +4583,7 @@ class PostgresDatabase:census["q"]["b"] |= 1 << ordinalrejected = True- foreign_key_ordinals = {- name: ordinal for ordinal, name in enumerate(expected_foreign_keys)- }+ foreign_key_ordinals = {name: ordinal for ordinal, name in enumerate(expected_foreign_keys)}for name, expected in expected_foreign_keys.items():row = actual_constraints.get(name)if row is None:@@ -4460,8 +4600,7 @@ class PostgresDatabase:reference_identity_is_exact = (row["referenced_schema_oid"] is not Noneand int(row["referenced_schema_oid"]) == schema_oid- and int(row["referenced_oid"])- == referenced_oids.get(expected[2])+ and int(row["referenced_oid"]) == referenced_oids.get(expected[2]))for field, actual_value, expected_value in zip(("l", "s", "t", "r"), actual[:4], expected[:4], strict=True@@ -4473,9 +4612,7 @@ class PostgresDatabase:("u", row["confupdtype"], expected[4]),("d", row["confdeltype"], expected[5]),):- semantic, alternate, unexpected = _postgres_internal_character(- raw_value- )+ semantic, alternate, unexpected = _postgres_internal_character(raw_value)if unexpected:census["f"]["x"] |= bitrejected = True@@ -4491,51 +4628,35 @@ class PostgresDatabase:primary = actual_constraints.get("websocket_tickets_pkey")primary_index = next(- (- row for row in index_rows- if str(row["index_name"]) == "websocket_tickets_pkey"- ),+ (row for row in index_rows if str(row["index_name"]) == "websocket_tickets_pkey"),None,)if primary is not None:- if tuple(str(column) for column in primary["local_columns"]) != (- "ticket_hash",- ):+ if tuple(str(column) for column in primary["local_columns"]) != ("ticket_hash",):census["p"]["l"] = 1rejected = Trueif tuple(primary["remote_columns"]):census["p"]["r"] = 1rejected = True- if (- primary["referenced_schema"] is not None- or primary["referenced_table"] is not None- ):+ if primary["referenced_schema"] is not None or primary["referenced_table"] is not None:census["p"]["n"] = 1rejected = True- if (- primary_index is None- or int(primary["constraint_index_oid"])- != int(primary_index["index_oid"])+ if primary_index is None or int(primary["constraint_index_oid"]) != int(+ primary_index["index_oid"]):census["p"]["i"] = 1rejected = Trueexpected_check_definitions = {- "ck_ws_ticket_hash": (- "CHECK (ticket_hash ~ '^[0-9a-f]{64}$'::text)"- ),+ "ck_ws_ticket_hash": ("CHECK (ticket_hash ~ '^[0-9a-f]{64}$'::text)"),"ck_ws_ticket_kind": (- "CHECK (credential_kind = ANY "- "(ARRAY['bearer'::text, 'api_key'::text]))"+ "CHECK (credential_kind = ANY (ARRAY['bearer'::text, 'api_key'::text]))"),"ck_ws_ticket_created_at": "CHECK (created_at < expires_at)","ck_ws_ticket_expires_at": "CHECK (expires_at > created_at)",- "ck_ws_ticket_consumed_at": (- "CHECK (consumed_at IS NULL OR consumed_at < expires_at)"- ),+ "ck_ws_ticket_consumed_at": ("CHECK (consumed_at IS NULL OR consumed_at < expires_at)"),"ck_ws_ticket_bearer_expires_finite": (- "CHECK (bearer_expires_at IS NULL "- "OR isfinite(bearer_expires_at))"+ "CHECK (bearer_expires_at IS NULL OR isfinite(bearer_expires_at))"),"ck_ws_ticket_created_finite": "CHECK (isfinite(created_at))","ck_ws_ticket_expires_finite": "CHECK (isfinite(expires_at))",@@ -4572,18 +4693,14 @@ class PostgresDatabase:"AND required_scope = 'read'::text)"),}- check_ordinals = {- name: ordinal for ordinal, name in enumerate(expected_check_definitions)- }+ check_ordinals = {name: ordinal for ordinal, name in enumerate(expected_check_definitions)}for name, expected_definition in expected_check_definitions.items():row = actual_constraints.get(name)if row is None:continuebit = 1 << check_ordinals[name]constraint_bit = 1 << constraint_ordinals[name]- contype, alternate, unexpected = _postgres_internal_character(- row["contype"]- )+ contype, alternate, unexpected = _postgres_internal_character(row["contype"])if unexpected:census["h"]["x"] |= bitcensus["q"]["x"] |= constraint_bit@@ -4645,8 +4762,10 @@ class PostgresDatabase:async def save_campaign(self, c: Any) -> None:from ares.core.campaign import Campaign+async with self._pool.acquire() as conn:- await conn.execute("""+ await conn.execute(+ """INSERT INTO campaigns(id,name,client,operator,noise_profile,status,scope_json,targets_json,notes)VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9)ON CONFLICT(id) DO UPDATE SET@@ -4655,11 +4774,19 @@ class PostgresDatabase:scope_json=EXCLUDED.scope_json, targets_json=EXCLUDED.targets_json,notes=EXCLUDED.notes,updated_at=now()- """, c.id, c.name, c.client, c.operator,- c.noise_profile.value if hasattr(c.noise_profile, "value") else str(c.noise_profile),+ """,+ c.id,+ c.name,+ c.client,+ c.operator,+ c.noise_profile.value+ if hasattr(c.noise_profile, "value")+ else str(c.noise_profile),c.status.value if hasattr(c.status, "value") else str(c.status),json.dumps([s.model_dump() for s in c.scope]),- json.dumps(c.targets), c.notes)+ json.dumps(c.targets),+ c.notes,+ )async def get_campaign(self, campaign_id: str) -> dict[str, Any] | None:async with self._pool.acquire() as conn:@@ -4670,39 +4797,269 @@ class PostgresDatabase:self, page: int = 1, per_page: int = 50, operator: str | None = None) -> tuple[list[dict[str, Any]], int]:offset = (page - 1) * per_page- where = "WHERE operator=$1" if operator else ""+ where = "WHERE operator=$1" if operator else ""params = [operator] if operator else []async with self._pool.acquire() as conn:- total = await conn.fetchval(- f"SELECT COUNT(*) FROM campaigns {where}", *params- )+ total = await conn.fetchval(f"SELECT COUNT(*) FROM campaigns {where}", *params)rows = await conn.fetch(- f"SELECT * FROM campaigns {where} ORDER BY created_at DESC LIMIT ${ len(params)+1 } OFFSET ${ len(params)+2 }",- *params, per_page, offset,+ f"SELECT * FROM campaigns {where} ORDER BY created_at DESC LIMIT ${len(params) + 1} OFFSET ${len(params) + 2}",+ *params,+ per_page,+ offset,)return [self._row_to_dict(r) for r in rows], total or 0- async def delete_campaign(self, campaign_id: str) -> bool:- async with self._pool.acquire() as conn:- async with conn.transaction():- for statement in (- "DELETE FROM loot WHERE campaign_id=$1",- "DELETE FROM credentials WHERE campaign_id=$1",- "DELETE FROM hosts WHERE campaign_id=$1",- "DELETE FROM findings WHERE campaign_id=$1",- ):- await conn.execute(statement, campaign_id)- result = await conn.execute(- "DELETE FROM campaigns WHERE id=$1", campaign_id+ async def delete_campaign(+ self,+ campaign_id: str,+ ) -> bool:+ """Delete once through the stable compatibility receipt authority."""+ result = await self.delete_campaign_lifecycle(campaign_id)+ return result.result is FixedResult.APPLIED++ async def delete_campaign_lifecycle(+ self,+ campaign_id: str,+ *,+ operation_id: str | None = None,+ lifecycle_operation_id: str | None = None,+ principal_kind: str = "system",+ principal_subject_ref: str | None = None,+ principal_user_id: str | None = None,+ principal_authority_revision: int | None = None,+ ) -> OperationResult:+ """Delete a campaign with explicit immutable operation/principal binding."""+ if (+ operation_id is not None+ and lifecycle_operation_id is not None+ and operation_id != lifecycle_operation_id+ ):+ return OperationResult(FixedResult.INVALID_CONTRACT, None)+ resolved_operation_id = operation_id if operation_id is not None else lifecycle_operation_id+ if resolved_operation_id is None:+ if not valid_uuid(campaign_id):+ return OperationResult(FixedResult.INVALID_CONTRACT, None)+ resolved_operation_id = _campaign_delete_operation_id(campaign_id)+ if principal_subject_ref is None:+ if principal_kind != "system":+ return OperationResult(FixedResult.INVALID_CONTRACT, None)+ principal_subject_ref = SYSTEM_PRINCIPAL_SUBJECT_REF++ store = ExecutionLifecycleStore(self._pool, "postgresql")+ try:+ receipt_spec = store._receipt_spec(+ operation_id=resolved_operation_id,+ operation_code="campaign_delete",+ campaign_id=campaign_id,+ primary_target_id=campaign_id,+ principal_kind=principal_kind,+ principal_subject_ref=principal_subject_ref,+ principal_user_id=principal_user_id,+ principal_authority_revision=principal_authority_revision,+ )+ except ValueError:+ return OperationResult(FixedResult.INVALID_CONTRACT, None)++ async with store._transaction() as conn:+ await store._acquire_transaction_key(conn, resolved_operation_id)+ replay = await store._classify_receipt(conn, receipt_spec, current_revision=None)+ if replay is not None:+ return replay+ await store._acquire_transaction_key(conn, campaign_id)+ await conn.fetchrow(+ "SELECT singleton_id FROM execution_gateway_state WHERE singleton_id=1 FOR UPDATE"+ )+ campaign_row = await conn.fetchrow(+ "SELECT id FROM campaigns WHERE id=$1 FOR UPDATE", campaign_id+ )+ if campaign_row is None:+ return OperationResult(FixedResult.NOT_FOUND_OR_PURGED, None)+ await conn.fetch(+ "SELECT campaign_id FROM campaign_execution_authority_revisions "+ "WHERE campaign_id=$1 FOR UPDATE",+ campaign_id,+ )+ actor_grant_rows = await conn.fetch(+ "SELECT actor_user_id AS id FROM campaign_execution_actor_grants "+ "WHERE campaign_id=$1 ORDER BY actor_user_id FOR UPDATE",+ campaign_id,+ )+ destination_authority_rows = await conn.fetch(+ "SELECT campaign_id AS id FROM campaign_execution_destination_authorities "+ "WHERE campaign_id=$1 FOR UPDATE",+ campaign_id,+ )+ approval_authority_rows = await conn.fetch(+ "SELECT id FROM execution_approval_authorities WHERE campaign_id=$1 "+ "ORDER BY id FOR UPDATE",+ campaign_id,+ )+ logical_rows = await conn.fetch(+ "SELECT id,closed_at FROM logical_executions WHERE campaign_id=$1 "+ "ORDER BY id FOR UPDATE",+ campaign_id,+ )+ attempt_rows = await conn.fetch(+ "SELECT id,state,ordinal FROM execution_attempts WHERE campaign_id=$1 "+ "ORDER BY ordinal,id FOR UPDATE",+ campaign_id,+ )+ destination_observation_rows = await conn.fetch(+ "SELECT attempt_id || ':' || ordinal::text AS id "+ "FROM execution_attempt_destination_observations WHERE campaign_id=$1 "+ "ORDER BY attempt_id,ordinal FOR UPDATE",+ campaign_id,+ )+ credential_observation_rows = await conn.fetch(+ "SELECT attempt_id || ':' || ordinal::text AS id "+ "FROM execution_attempt_credential_observations WHERE campaign_id=$1 "+ "ORDER BY attempt_id,ordinal FOR UPDATE",+ campaign_id,+ )+ budget_rows = await conn.fetch(+ "SELECT id,budget_kind FROM campaign_execution_budgets WHERE campaign_id=$1 "+ "ORDER BY budget_kind,id FOR UPDATE",+ campaign_id,+ )+ ledger_rows = await conn.fetch(+ "SELECT id,budget_kind FROM campaign_execution_budget_ledger "+ "WHERE campaign_id=$1 ORDER BY budget_kind,id FOR UPDATE",+ campaign_id,+ )+ await conn.fetch(+ "SELECT id FROM hosts WHERE campaign_id=$1 ORDER BY ip_address,id FOR UPDATE",+ campaign_id,+ )+ for table in ("findings", "credentials", "loot"):+ await conn.fetch(+ f"SELECT id FROM {table} WHERE campaign_id=$1 ORDER BY id FOR UPDATE",+ campaign_id,)- return result == "DELETE 1"+ link_rows = await conn.fetch(+ "SELECT id FROM execution_output_links WHERE campaign_id=$1 ORDER BY id FOR UPDATE",+ campaign_id,+ )+ outbox_rows = await conn.fetch(+ "SELECT id,publication_state FROM execution_publication_outbox "+ "WHERE campaign_id=$1 ORDER BY id FOR UPDATE",+ campaign_id,+ )+ approval_rows = await conn.fetch(+ "SELECT id FROM execution_attempt_approvals WHERE campaign_id=$1 "+ "ORDER BY id FOR UPDATE",+ campaign_id,+ )+ blocked = await conn.fetchval(+ "SELECT EXISTS(SELECT 1 FROM execution_attempts WHERE campaign_id=$1 "+ "AND state IN ('accepted','queued','dispatching','running','cancelling',"+ "'settlement_pending')) "+ "OR EXISTS(SELECT 1 FROM logical_executions WHERE campaign_id=$1 "+ "AND closed_at IS NULL) "+ "OR EXISTS(SELECT 1 FROM execution_publication_outbox WHERE campaign_id=$1 "+ "AND publication_state='claimed')",+ campaign_id,+ )+ if blocked:+ raise RuntimeError("Campaign lifecycle deletion is blocked")++ async def delete_exact(statement: str, expected: tuple[str, ...]) -> None:+ deleted = await conn.fetch(statement, campaign_id)+ observed = tuple(sorted(str(row["id"]) for row in deleted))+ if observed != tuple(sorted(expected)):+ raise RuntimeError("Campaign lifecycle deletion invariant failed")++ await delete_exact(+ "DELETE FROM execution_output_links WHERE campaign_id=$1 RETURNING id",+ tuple(str(row["id"]) for row in link_rows),+ )+ await delete_exact(+ "DELETE FROM execution_publication_outbox WHERE campaign_id=$1 RETURNING id",+ tuple(str(row["id"]) for row in outbox_rows),+ )+ await delete_exact(+ "DELETE FROM execution_attempt_approvals WHERE campaign_id=$1 RETURNING id",+ tuple(str(row["id"]) for row in approval_rows),+ )+ await delete_exact(+ "DELETE FROM execution_approval_authorities WHERE campaign_id=$1 RETURNING id",+ tuple(str(row["id"]) for row in approval_authority_rows),+ )+ await delete_exact(+ "DELETE FROM execution_attempt_destination_observations WHERE campaign_id=$1 "+ "RETURNING attempt_id || ':' || ordinal::text AS id",+ tuple(str(row["id"]) for row in destination_observation_rows),+ )+ await delete_exact(+ "DELETE FROM execution_attempt_credential_observations WHERE campaign_id=$1 "+ "RETURNING attempt_id || ':' || ordinal::text AS id",+ tuple(str(row["id"]) for row in credential_observation_rows),+ )+ await delete_exact(+ "DELETE FROM campaign_execution_budget_ledger WHERE campaign_id=$1 RETURNING id",+ tuple(str(row["id"]) for row in ledger_rows),+ )+ for attempt in reversed(attempt_rows):+ deleted = await conn.fetchrow(+ "DELETE FROM execution_attempts WHERE id=$1 RETURNING id",+ attempt["id"],+ )+ if deleted is None or str(deleted["id"]) != str(attempt["id"]):+ raise RuntimeError("Campaign lifecycle deletion invariant failed")+ await delete_exact(+ "DELETE FROM logical_executions WHERE campaign_id=$1 RETURNING id",+ tuple(str(row["id"]) for row in logical_rows),+ )+ await delete_exact(+ "DELETE FROM campaign_execution_budgets WHERE campaign_id=$1 RETURNING id",+ tuple(str(row["id"]) for row in budget_rows),+ )+ await delete_exact(+ "DELETE FROM campaign_execution_actor_grants WHERE campaign_id=$1 "+ "RETURNING actor_user_id AS id",+ tuple(str(row["id"]) for row in actor_grant_rows),+ )+ await delete_exact(+ "DELETE FROM campaign_execution_destination_authorities WHERE campaign_id=$1 "+ "RETURNING campaign_id AS id",+ tuple(str(row["id"]) for row in destination_authority_rows),+ )+ authority_deleted = await conn.fetch(+ "DELETE FROM campaign_execution_authority_revisions "+ "WHERE campaign_id=$1 RETURNING campaign_id AS id",+ campaign_id,+ )+ if len(authority_deleted) > 1:+ raise RuntimeError("Campaign lifecycle deletion invariant failed")+ for statement in (+ "DELETE FROM loot WHERE campaign_id=$1 RETURNING id",+ "DELETE FROM credentials WHERE campaign_id=$1 RETURNING id",+ "DELETE FROM hosts WHERE campaign_id=$1 RETURNING id",+ "DELETE FROM findings WHERE campaign_id=$1 RETURNING id",+ ):+ await conn.fetch(statement, campaign_id)+ await store._insert_receipt(+ conn,+ receipt_spec,+ result=FixedResult.APPLIED,+ exact_replay_code=FixedResult.REPLAYED,+ result_identity=campaign_id,+ result_revision=None,+ result_fields=(("deleted", True),),+ )+ deleted_campaign = await conn.fetchrow(+ "DELETE FROM campaigns WHERE id=$1 RETURNING id", campaign_id+ )+ if deleted_campaign is None or str(deleted_campaign["id"]) != campaign_id:+ raise RuntimeError("Campaign lifecycle deletion invariant failed")+ return OperationResult(FixedResult.APPLIED, None)# ── Findings ───────────────────────────────────────────────────────────────async def save_finding(self, campaign_id: str, f: Any, module_id: str = "") -> None:async with self._pool.acquire() as conn:- await conn.execute("""+ await conn.execute(+ """INSERT INTO findings(id,campaign_id,module_id,title,description,severity,cvss_score,cvss_vector,confidence,mitre_technique,mitre_tactic,evidence_json,remediation,host,trace_id,@@ -4712,36 +5069,49 @@ class PostgresDatabase:title=EXCLUDED.title, description=EXCLUDED.description,severity=EXCLUDED.severity, evidence_json=EXCLUDED.evidence_json,validated=EXCLUDED.validated, false_positive=EXCLUDED.false_positive- """, f.id, campaign_id, module_id or getattr(f, "module_id", ""),- f.title, f.description,+ """,+ f.id,+ campaign_id,+ module_id or getattr(f, "module_id", ""),+ f.title,+ f.description,f.severity.value if hasattr(f.severity, "value") else str(f.severity),- getattr(f, "cvss_score", 0.0), getattr(f, "cvss_vector", ""),- f.confidence, f.mitre_technique, f.mitre_tactic,- json.dumps(f.evidence), f.remediation, f.host,+ getattr(f, "cvss_score", 0.0),+ getattr(f, "cvss_vector", ""),+ f.confidence,+ f.mitre_technique,+ f.mitre_tactic,+ json.dumps(f.evidence),+ f.remediation,+ f.host,getattr(f, "trace_id", ""),int(bool(getattr(f, "validated", False))),- int(bool(getattr(f, "false_positive", False))))+ int(bool(getattr(f, "false_positive", False))),+ )async def list_findings(self,- campaign_id: str,- page: int = 1,- per_page: int = 50,- severity: str | None = None,+ campaign_id: str,+ page: int = 1,+ per_page: int = 50,+ severity: str | None = None,false_positive: bool | None = None,- validated: bool | None = None,+ validated: bool | None = None,) -> tuple[list[dict[str, Any]], int]:conditions = ["campaign_id=$1"]params: list[Any] = [campaign_id]if severity:- params.append(severity); conditions.append(f"severity=${len(params)}")+ params.append(severity)+ conditions.append(f"severity=${len(params)}")if false_positive is not None:- params.append(int(false_positive)); conditions.append(f"false_positive=${len(params)}")+ params.append(int(false_positive))+ conditions.append(f"false_positive=${len(params)}")if validated is not None:- params.append(int(validated)); conditions.append(f"validated=${len(params)}")+ params.append(int(validated))+ conditions.append(f"validated=${len(params)}")- where = " AND ".join(conditions)+ where = " AND ".join(conditions)offset = (page - 1) * per_pageasync with self._pool.acquire() as conn:@@ -4749,7 +5119,7 @@ class PostgresDatabase:params_page = params + [per_page, offset]rows = await conn.fetch(f"SELECT * FROM findings WHERE {where} ORDER BY discovered_at DESC"- f" LIMIT ${len(params)+1} OFFSET ${len(params)+2}",+ f" LIMIT ${len(params) + 1} OFFSET ${len(params) + 2}",*params_page,)return [self._row_to_dict(r) for r in rows], total or 0@@ -4773,7 +5143,14 @@ class PostgresDatabase:"SELECT severity, COUNT(*) as n FROM findings WHERE campaign_id=$1 GROUP BY severity",campaign_id,)- stats: dict[str, Any] = {"total": 0, "critical":0,"high":0,"medium":0,"low":0,"info":0}+ stats: dict[str, Any] = {+ "total": 0,+ "critical": 0,+ "high": 0,+ "medium": 0,+ "low": 0,+ "info": 0,+ }for r in rows:stats[r["severity"]] = r["n"]stats["total"] += r["n"]@@ -4812,10 +5189,7 @@ class PostgresDatabase:period_start,next_month,)- series = [- {"date": row["finding_date"].isoformat(), "count": int(row["n"])}- for row in rows- ]+ series = [{"date": row["finding_date"].isoformat(), "count": int(row["n"])} for row in rows]return {"period": period,"label": "Security signals this cycle",@@ -4911,17 +5285,34 @@ class PostgresDatabase:async def upsert_host(self, h: Any) -> str:async with self._pool.acquire() as conn:- await conn.execute("""+ canonical_id = await conn.fetchval(+ """INSERT INTO hosts(id,campaign_id,ip_address,hostname,fqdn,os,os_version,domain,is_dc,open_ports_json,tags_json)VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11)ON CONFLICT(campaign_id,ip_address) DO UPDATE SEThostname=EXCLUDED.hostname, os=EXCLUDED.os, is_dc=EXCLUDED.is_dc,- open_ports_json=EXCLUDED.open_ports_json, last_seen=now()- """, h.id, h.campaign_id, h.ip_address, h.hostname, h.fqdn,- h.os, h.os_version, h.domain, int(h.is_dc),- json.dumps(h.open_ports), json.dumps(h.tags))- return h.id+ fqdn=EXCLUDED.fqdn, os=EXCLUDED.os,+ os_version=EXCLUDED.os_version, domain=EXCLUDED.domain,+ is_dc=EXCLUDED.is_dc, open_ports_json=EXCLUDED.open_ports_json,+ tags_json=EXCLUDED.tags_json, last_seen=now()+ RETURNING id+ """,+ h.id,+ h.campaign_id,+ h.ip_address,+ h.hostname,+ h.fqdn,+ h.os,+ h.os_version,+ h.domain,+ int(h.is_dc),+ json.dumps(h.open_ports),+ json.dumps(h.tags),+ )+ if canonical_id is None:+ raise RuntimeError("Canonical host persistence failed")+ return str(canonical_id)async def get_hosts(self, campaign_id: str) -> list[dict]:async with self._pool.acquire() as conn:@@ -4934,13 +5325,27 @@ class PostgresDatabase:async def save_credential(self, c: Any) -> None:async with self._pool.acquire() as conn:- await conn.execute("""+ await conn.execute(+ """INSERT INTO credentials(id,campaign_id,host_id,username,secret_enc,cred_type,domain,source_module,notes)VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9)- ON CONFLICT(id) DO NOTHING- """, c.id, c.campaign_id, c.host_id, c.username,- self._enc_val(c.secret), c.cred_type, c.domain, c.source_module, c.notes)+ ON CONFLICT(id) DO UPDATE SET+ host_id=EXCLUDED.host_id,username=EXCLUDED.username,+ secret_enc=EXCLUDED.secret_enc,cred_type=EXCLUDED.cred_type,+ domain=EXCLUDED.domain,source_module=EXCLUDED.source_module,+ notes=EXCLUDED.notes+ """,+ c.id,+ c.campaign_id,+ c.host_id,+ c.username,+ self._enc_val(c.secret),+ c.cred_type,+ c.domain,+ c.source_module,+ c.notes,+ )async def get_credentials(self, campaign_id: str, decrypt: bool = False) -> list[dict]:async with self._pool.acquire() as conn:@@ -4961,7 +5366,8 @@ class PostgresDatabase:Mirrors database.py implementation — required by engine._persist_vault_credentials()."""async with self._pool.acquire() as conn:- await conn.execute("""+ await conn.execute(+ """INSERT INTO credentials(id,campaign_id,host_id,username,secret_enc,cred_type,domain,source_module,notes)VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9)@@ -4969,9 +5375,17 @@ class PostgresDatabase:secret_enc = EXCLUDED.secret_enc,source_module = EXCLUDED.source_module,notes = EXCLUDED.notes- """, cred.id, cred.campaign_id, cred.host_id, cred.username,- cred.secret, # already vault-encrypted — store verbatim, no _enc_val()- cred.cred_type, cred.domain, cred.source_module, cred.notes)+ """,+ cred.id,+ cred.campaign_id,+ cred.host_id,+ cred.username,+ cred.secret, # already vault-encrypted — store verbatim, no _enc_val()+ cred.cred_type,+ cred.domain,+ cred.source_module,+ cred.notes,+ )async def load_credentials_raw(self, campaign_id: str) -> list[dict]:"""@@ -4992,15 +5406,34 @@ class PostgresDatabase:async def save_loot(self, l: Any) -> None:content_str = json.dumps(l.content) if isinstance(l.content, (dict, list)) else l.contentasync with self._pool.acquire() as conn:- await conn.execute("""+ await conn.execute(+ """INSERT INTO loot(id,campaign_id,host_id,loot_type,name,description,content_enc,path_on_target,source_module,tags_json)VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10)- ON CONFLICT(id) DO NOTHING- """, l.id, l.campaign_id, l.host_id, l.loot_type, l.name, l.description,- self._enc_val(content_str), l.path_on_target, l.source_module,- json.dumps(l.tags))+ ON CONFLICT(id) DO UPDATE SET+ host_id=EXCLUDED.host_id,loot_type=EXCLUDED.loot_type,+ name=EXCLUDED.name,description=EXCLUDED.description,+ content_enc=EXCLUDED.content_enc,+ path_on_target=EXCLUDED.path_on_target,+ source_module=EXCLUDED.source_module,tags_json=EXCLUDED.tags_json+ """,+ l.id,+ l.campaign_id,+ l.host_id,+ l.loot_type,+ l.name,+ l.description,+ self._enc_val(content_str),+ l.path_on_target,+ l.source_module,+ json.dumps(l.tags),+ )++ def execution_lifecycle_store(self) -> ExecutionLifecycleStore:+ """Return the additive internal lifecycle persistence primitive."""+ return ExecutionLifecycleStore(self._pool, "postgresql")async def get_loot(self, campaign_id: str, decrypt: bool = False) -> list[dict]:async with self._pool.acquire() as conn:@@ -5064,37 +5497,52 @@ class PostgresDatabase:async def campaign_summary(self, campaign_id: str) -> dict[str, Any]:findings = await self.get_findings(campaign_id)- hosts = await self.get_hosts(campaign_id)- creds = await self.get_credentials(campaign_id)- loot = await self.get_loot(campaign_id)+ hosts = await self.get_hosts(campaign_id)+ creds = await self.get_credentials(campaign_id)+ loot = await self.get_loot(campaign_id)return {- "campaign_id": campaign_id,- "findings": findings,- "finding_count": len(findings),- "host_count": len(hosts),+ "campaign_id": campaign_id,+ "findings": findings,+ "finding_count": len(findings),+ "host_count": len(hosts),"credential_count": len(creds),- "loot_count": len(loot),+ "loot_count": len(loot),}# ── Audit ──────────────────────────────────────────────────────────────────- async def audit(self, actor: str, action: str, detail: str = "",- campaign_id: str | None = None, module_id: str | None = None) -> None:+ async def audit(+ self,+ actor: str,+ action: str,+ detail: str = "",+ campaign_id: str | None = None,+ module_id: str | None = None,+ ) -> None:async with self._pool.acquire() as conn:await conn.execute("INSERT INTO audit_log(campaign_id,actor,action,detail,module_id) VALUES($1,$2,$3,$4,$5)",- campaign_id, actor, action, detail, module_id,+ campaign_id,+ actor,+ action,+ detail,+ module_id,)# ── Users ──────────────────────────────────────────────────────────────────- async def create_user(self, username: str, password: str, role: str,- created_by: str = "system") -> str:+ async def create_user(+ self, username: str, password: str, role: str, created_by: str = "system"+ ) -> str:user_id = str(uuid.uuid4())async with self._pool.acquire() as conn:await conn.execute("INSERT INTO users(id,username,hashed_password,role,created_by) VALUES($1,$2,$3,$4,$5)",- user_id, username, hash_password(password), role, created_by,+ user_id,+ username,+ hash_password(password),+ role,+ created_by,)logger.info("user_created", username=username, role=role)return user_id@@ -5108,9 +5556,7 @@ class PostgresDatabase:async def get_user_by_id(self, user_id: str) -> dict[str, Any] | None:async with self._pool.acquire() as conn:- row = await conn.fetchrow(- "SELECT * FROM users WHERE id=$1 AND is_active=1", user_id- )+ row = await conn.fetchrow("SELECT * FROM users WHERE id=$1 AND is_active=1", user_id)return self._row_to_dict(row) if row else Noneasync def resolve_access_token_principal(@@ -5164,15 +5610,11 @@ class PostgresDatabase:async def user_exists(self, username: str) -> bool:async with self._pool.acquire() as conn:- return bool(await conn.fetchval(- "SELECT 1 FROM users WHERE username=$1", username- ))+ return bool(await conn.fetchval("SELECT 1 FROM users WHERE username=$1", username))async def update_password(self, user_id: str, new_hash: str) -> None:async with self._pool.acquire() as conn:- await conn.execute(- "UPDATE users SET hashed_password=$1 WHERE id=$2", new_hash, user_id- )+ await conn.execute("UPDATE users SET hashed_password=$1 WHERE id=$2", new_hash, user_id)async def list_users(self) -> list[dict[str, Any]]:async with self._pool.acquire() as conn:@@ -5186,25 +5628,35 @@ class PostgresDatabase:n = await conn.fetchval("SELECT COUNT(*) FROM users")if n == 0:await self.create_user("admin", admin_password, "team_lead", "bootstrap")- logger.warning("default_admin_created",- msg="CHANGE password immediately: POST /auth/change-password")+ logger.warning(+ "default_admin_created",+ msg="CHANGE password immediately: POST /auth/change-password",+ )return Truereturn False# ── API Keys ───────────────────────────────────────────────────────────────- async def create_api_key(self, user_id: str, name: str, scopes: str = "read",- expires_days: int | None = None) -> tuple[str, str]:- raw_key = "ares_" + secrets.token_urlsafe(40)+ async def create_api_key(+ self, user_id: str, name: str, scopes: str = "read", expires_days: int | None = None+ ) -> tuple[str, str]:+ raw_key = "ares_" + secrets.token_urlsafe(40)key_prefix = raw_key[:12]- key_id = str(uuid.uuid4())- expires_at = datetime.now(timezone.utc) + timedelta(days=expires_days) \- if expires_days else None+ key_id = str(uuid.uuid4())+ expires_at = (+ datetime.now(timezone.utc) + timedelta(days=expires_days) if expires_days else None+ )async with self._pool.acquire() as conn:await conn.execute("INSERT INTO api_keys(id,user_id,name,key_hash,key_prefix,scopes,expires_at) ""VALUES($1,$2,$3,$4,$5,$6,$7)",- key_id, user_id, name, hash_password(raw_key), key_prefix, scopes, expires_at,+ key_id,+ user_id,+ name,+ hash_password(raw_key),+ key_prefix,+ scopes,+ expires_at,)return key_id, raw_key@@ -5252,7 +5704,8 @@ class PostgresDatabase:async with self._pool.acquire() as conn:rows = await conn.fetch("SELECT id,name,key_prefix,scopes,is_active,last_used,expires_at,created_at "- "FROM api_keys WHERE user_id=$1 AND is_active=1 ORDER BY created_at DESC", user_id,+ "FROM api_keys WHERE user_id=$1 AND is_active=1 ORDER BY created_at DESC",+ user_id,)return [self._row_to_dict(r) for r in rows]@@ -5274,9 +5727,7 @@ class PostgresDatabase:@staticmethodasync def _purge_websocket_ticket_rows(connection: Any) -> None:- await connection.execute(- "DELETE FROM websocket_tickets WHERE expires_at <= now()"- )+ await connection.execute("DELETE FROM websocket_tickets WHERE expires_at <= now()")async def issue_websocket_ticket(self,@@ -5437,9 +5888,7 @@ class PostgresDatabase:consumed = ConsumedWebSocketTicket(campaign_id=row["campaign_id"],user_id=row["user_id"],- credential_kind=WebSocketTicketCredentialKind(- row["credential_kind"]- ),+ credential_kind=WebSocketTicketCredentialKind(row["credential_kind"]),bearer_subject=row["bearer_subject"],bearer_jti=row["bearer_jti"],bearer_expires_at=row["bearer_expires_at"],@@ -5602,12 +6051,10 @@ class PostgresDatabase:user_id: str,auth_epoch: int,) -> tuple[str, str]:- family_id, raw_token, _ = (- await PostgresDatabase._insert_initial_family_token_with_expiry(- conn,- user_id=user_id,- auth_epoch=auth_epoch,- )+ family_id, raw_token, _ = await PostgresDatabase._insert_initial_family_token_with_expiry(+ conn,+ user_id=user_id,+ auth_epoch=auth_epoch,)return family_id, raw_token@@ -5621,8 +6068,7 @@ class PostgresDatabase:async with self._pool.acquire() as conn:async with conn.transaction():row = await conn.fetchrow(- "SELECT auth_epoch FROM users WHERE id=$1 AND is_active=1 "- "FOR UPDATE",+ "SELECT auth_epoch FROM users WHERE id=$1 AND is_active=1 FOR UPDATE",user_id,)if row is None:@@ -5647,17 +6093,23 @@ class PostgresDatabase:"FROM users WHERE username=$1 FOR UPDATE",username,)- if row is None or not bool(row["is_active"]) or not verify_password(- password,- row["hashed_password"],+ if (+ row is None+ or not bool(row["is_active"])+ or not verify_password(+ password,+ row["hashed_password"],+ )):return SessionIssueResult(SessionIssueStatus.INVALID)- family_id, raw_token, absolute_expiry = (- await self._insert_initial_family_token_with_expiry(- conn,- user_id=row["id"],- auth_epoch=int(row["auth_epoch"]),- )+ (+ family_id,+ raw_token,+ absolute_expiry,+ ) = await self._insert_initial_family_token_with_expiry(+ conn,+ user_id=row["id"],+ auth_epoch=int(row["auth_epoch"]),)access_token = token_factory({@@ -5697,8 +6149,7 @@ class PostgresDatabase:reason: str,) -> bool:family = await conn.fetchrow(- "SELECT absolute_expires_at,state FROM refresh_token_families "- "WHERE id=$1 FOR UPDATE",+ "SELECT absolute_expires_at,state FROM refresh_token_families WHERE id=$1 FOR UPDATE",family_id,)if family is None:@@ -5855,17 +6306,17 @@ class PostgresDatabase:await conn.execute("INSERT INTO revoked_access_tokens(jti,user_id,expires_at) VALUES($1,$2,$3) ""ON CONFLICT(jti) DO NOTHING",- jti, user_id, parsed_expires_at,- )- await conn.execute(- "DELETE FROM revoked_access_tokens WHERE expires_at < now()"+ jti,+ user_id,+ parsed_expires_at,)+ await conn.execute("DELETE FROM revoked_access_tokens WHERE expires_at < now()")async def is_access_token_revoked(self, jti: str) -> bool:async with self._pool.acquire() as conn:- return bool(await conn.fetchval(- "SELECT 1 FROM revoked_access_tokens WHERE jti=$1", jti- ))+ return bool(+ await conn.fetchval("SELECT 1 FROM revoked_access_tokens WHERE jti=$1", jti)+ )async def revoke_all_refresh_tokens(self, user_id: str) -> None:async with self._pool.acquire() as conn:@@ -5893,8 +6344,7 @@ class PostgresDatabase:async with self._pool.acquire() as conn:async with conn.transaction():owner = await conn.fetchval(- "SELECT 1 FROM refresh_token_families "- "WHERE id=$1 AND user_id=$2 FOR UPDATE",+ "SELECT 1 FROM refresh_token_families WHERE id=$1 AND user_id=$2 FOR UPDATE",family_id,user_id,)@@ -5918,9 +6368,7 @@ class PostgresDatabase:"'auth-system','logout_current','')")return SessionRevocationResult(- SessionRevocationStatus.REVOKED- if changed- else SessionRevocationStatus.ALREADY_REVOKED+ SessionRevocationStatus.REVOKED if changed else SessionRevocationStatus.ALREADY_REVOKED)async def revoke_refresh_cookie_session(@@ -5941,9 +6389,7 @@ class PostgresDatabase:if row is None:return SessionRevocationResult(SessionRevocationStatus.INVALID)if row["family_state"] != "active":- return SessionRevocationResult(- SessionRevocationStatus.ALREADY_REVOKED- )+ return SessionRevocationResult(SessionRevocationStatus.ALREADY_REVOKED)reason = "logout_current" if row["state"] == "active" else "replay"changed = await self._revoke_family_rows(conn,@@ -5957,14 +6403,11 @@ class PostgresDatabase:else "logout_cookie_replay_family_revoked")await conn.execute(- "INSERT INTO audit_log(actor,action,detail) VALUES("- "'auth-system',$1,'')",+ "INSERT INTO audit_log(actor,action,detail) VALUES('auth-system',$1,'')",action,)return SessionRevocationResult(SessionRevocationStatus.REVOKED)- return SessionRevocationResult(- SessionRevocationStatus.ALREADY_REVOKED- )+ return SessionRevocationResult(SessionRevocationStatus.ALREADY_REVOKED)async def revoke_all_sessions(self,@@ -6052,8 +6495,7 @@ class PostgresDatabase:reason=reason,)await conn.execute(- "INSERT INTO audit_log(actor,action,detail) VALUES("- "'auth-system',$1,'')",+ "INSERT INTO audit_log(actor,action,detail) VALUES('auth-system',$1,'')",reason,)return True@@ -6075,22 +6517,28 @@ class PostgresDatabase:async def save_bypass_outcome(self,technique_id: str,- edr_vendor: str,- edr_version: str,- success: bool,- campaign_id: str,- notes: str = "",+ edr_vendor: str,+ edr_version: str,+ success: bool,+ campaign_id: str,+ notes: str = "",) -> None:"""Persist bypass technique outcome for cross-session learning."""import time as _time+try:async with self._pool.acquire() as conn:await conn.execute("""INSERT INTO bypass_outcomes(technique_id, edr_vendor, edr_version, success, campaign_id, notes, ts)VALUES ($1, $2, $3, $4, $5, $6, $7)""",- technique_id, edr_vendor, edr_version,- int(success), campaign_id, notes[:500], _time.time(),+ technique_id,+ edr_vendor,+ edr_version,+ int(success),+ campaign_id,+ notes[:500],+ _time.time(),)except Exception:await self._ensure_bypass_outcomes_table()@@ -6099,18 +6547,24 @@ class PostgresDatabase:"""INSERT INTO bypass_outcomes(technique_id, edr_vendor, edr_version, success, campaign_id, notes, ts)VALUES ($1, $2, $3, $4, $5, $6, $7)""",- technique_id, edr_vendor, edr_version,- int(success), campaign_id, notes[:500], _time.time(),+ technique_id,+ edr_vendor,+ edr_version,+ int(success),+ campaign_id,+ notes[:500],+ _time.time(),)async def get_bypass_success_rate(self,technique_id: str,- edr_vendor: str,- min_samples: int = 3,+ edr_vendor: str,+ min_samples: int = 3,) -> float | None:"""Return historical success rate for a bypass technique against an EDR vendor."""import time as _time+try:async with self._pool.acquire() as conn:row = await conn.fetchrow(@@ -6118,7 +6572,9 @@ class PostgresDatabase:FROM bypass_outcomesWHERE technique_id = $1 AND edr_vendor = $2AND ts > $3""",- technique_id, edr_vendor, _time.time() - 7_776_000,+ technique_id,+ edr_vendor,+ _time.time() - 7_776_000,)if not row or row["total"] < min_samples:return None@@ -6149,6 +6605,7 @@ class PostgresDatabase:"""Export all campaigns + findings to JSON (same interface as SQLite backend)."""import json as _jsonfrom pathlib import Path+ts = datetime.now(timezone.utc).strftime("%Y%m%d_%H%M%S")if not output_path:backup_dir = Path.home() / ".ares" / "backups"@@ -6156,18 +6613,26 @@ class PostgresDatabase:output_path = str(backup_dir / f"ares_export_{ts}.json")async with self._pool.acquire() as conn:- campaigns = [self._row_to_dict(r)- for r in await conn.fetch("SELECT * FROM campaigns ORDER BY created_at DESC")]+ campaigns = [+ self._row_to_dict(r)+ for r in await conn.fetch("SELECT * FROM campaigns ORDER BY created_at DESC")+ ]for c in campaigns:cid = c["id"]async with self._pool.acquire() as conn:- c["_findings"] = [self._row_to_dict(r)- for r in await conn.fetch(- "SELECT * FROM findings WHERE campaign_id=$1 ORDER BY discovered_at DESC",- cid)]- c["_hosts"] = [self._row_to_dict(r)- for r in await conn.fetch(- "SELECT * FROM hosts WHERE campaign_id=$1 ORDER BY first_seen", cid)]+ c["_findings"] = [+ self._row_to_dict(r)+ for r in await conn.fetch(+ "SELECT * FROM findings WHERE campaign_id=$1 ORDER BY discovered_at DESC",+ cid,+ )+ ]+ c["_hosts"] = [+ self._row_to_dict(r)+ for r in await conn.fetch(+ "SELECT * FROM hosts WHERE campaign_id=$1 ORDER BY first_seen", cid+ )+ ]export = {"export_version": "1.0", "exported_at": ts, "campaigns": campaigns}with open(output_path, "w") as fh:diff --git a/ares/db/schema.py b/ares/db/schema.pyindex 0e81a1c..cb0b08e 100644--- a/ares/db/schema.py+++ b/ares/db/schema.py@@ -16,7 +16,12 @@ Tables (v5 additions marked ★):"""from __future__ import annotations-SCHEMA_VERSION = 8+from ares.db.execution_lifecycle import (+ sqlite_admission_authority_runtime_script,+ sqlite_lifecycle_runtime_script,+)++SCHEMA_VERSION = 9CREATE_TABLES = """PRAGMA journal_mode = WAL;@@ -447,7 +452,7 @@ CREATE INDEX IF NOT EXISTS idx_ws_tickets_api_keyON websocket_tickets(api_key_id);CREATE INDEX IF NOT EXISTS idx_ws_tickets_bearer_familyON websocket_tickets(bearer_family_id);-"""+""" + sqlite_lifecycle_runtime_script() + sqlite_admission_authority_runtime_script()# ── Migration: v4 → v5 ────────────────────────────────────────────────────────# Applied automatically by AresDatabase.connect() when SCHEMA_VERSION mismatch.diff --git a/ares/goal/engine.py b/ares/goal/engine.pyindex 394c395..052cd1d 100644--- a/ares/goal/engine.py+++ b/ares/goal/engine.py@@ -24,10 +24,11 @@ Planning algorithm (backward chaining):"""from __future__ import annotations+import jsonimport timefrom dataclasses import dataclass, fieldfrom enum import Enum-from typing import Any, TYPE_CHECKING+from typing import TYPE_CHECKING, Anyfrom ares.core.logger import get_loggerfrom ares.state.target_state import CompromiseLevel, OperatorSession@@ -332,8 +333,46 @@ class GoalEngine:self.registry = registryself.session = sessionself.vault = vault- # Build capability graph from registry for dynamic chain resolution- self._capability_graph = CapabilityGraph.from_registry(registry)+ # Planning infrastructure stays dormant unless the private repository-+ # test planning seam invokes plan(). Production construction and+ # execute() do not call registry/plugin hooks.+ self._capability_graph: CapabilityGraph | None = None+ # Private test-only admission binding. No production setting, request,+ # plugin, or environment variable can configure this seam while the+ # generation-11 descriptor catalog remains ineligible.+ self._c_live_test_coordinator: Any | None = None+ self._c_live_test_principal: Any | None = None+ self._c_live_test_parent_key: str | None = None+ self._c_live_test_planning_enabled = False++ def _configure_c_live_test_planning(self) -> None:+ """Enable the pure deterministic planner for repository tests only.++ Production settings, requests, plugins, and environment state have no+ route to this leading-underscore seam. With production descriptors+ ineligible, public Goal planning therefore remains fail-closed.+ """+ self._c_live_test_planning_enabled = True++ def _configure_c_live_test_dispatch(+ self,+ *,+ coordinator: Any,+ principal: Any,+ idempotency_key: str,+ ) -> None:+ """Bind a coordinator to pure, deterministic Goal wiring tests only."""+ from ares.db.execution_lifecycle import TrustedPrincipal, valid_uuid++ if (+ not callable(getattr(coordinator, "execute_module", None))+ or type(principal) is not TrustedPrincipal+ or not valid_uuid(idempotency_key)+ ):+ raise ValueError("invalid C-LIVE Goal test dispatch binding")+ self._c_live_test_coordinator = coordinator+ self._c_live_test_principal = principal+ self._c_live_test_parent_key = idempotency_keydef plan(self,@@ -344,6 +383,8 @@ class GoalEngine:Build an attack plan for the given goal.Context may include: dc, domain, targets, noise_profile, etc."""+ if not self._c_live_test_planning_enabled:+ raise PermissionError("C-LIVE Goal planning is non-dispatchable")context = context or {}# Coerce string → Goal enumif isinstance(goal, str):@@ -361,6 +402,9 @@ class GoalEngine:logger.info("goal_plan_start", goal=goal.value, context_keys=list(context.keys()))+ if self._capability_graph is None:+ self._capability_graph = CapabilityGraph.from_registry(self.registry)+# Choose chain: prefer primary, fall back if modules not availablechain = self._select_chain(defn, context)steps = self._build_steps(chain, context, defn)@@ -398,6 +442,8 @@ class GoalEngine:# 2. Capability-based dynamic chain from REQUIRES/OUTPUTSavailable_mids = [getattr(cls, "MODULE_ID", "") for cls in self.registry.all()]+ if self._capability_graph is None:+ raise RuntimeError("goal capability graph was not initialized")dynamic_chain = self._capability_graph.resolve_chain(goal_required_outputs=defn.required_outputs,available_modules=available_mids,@@ -531,36 +577,141 @@ class GoalEngine:plan: GoalAttackPlan,campaign: Any,) -> dict[str, Any]:- """- Execute a GoalAttackPlan using the ARES async engine.- Returns aggregated results.- """- from ares.core.engine import AresEngine, ExecutionPlan-- exec_plan = ExecutionPlan()-- # Build parallel stages based on step dependencies- # Steps with no depends_on run in first stage; others follow- stage0 = [s.module_id for s in plan.steps if not s.depends_on]- remaining = [s for s in plan.steps if s.depends_on]+ """Dispatch a completely frozen Goal plan through C-LIVE admission.- if stage0:- exec_plan.add_stage("goal_stage_0", stage0)+ The ordinary production constructor is intentionally non-dispatchable:+ C-LIVE-v1 wires safety but does not activate any descriptor. Only the+ private deterministic test seam above can exercise this fan-out.+ """+ from ares.core.execution_admission import (+ DispatchDispositionV1,+ DispatchRequestV1,+ canonical_intent_digest,+ )- # Simple sequential for now — future: full DAG from depends_on- for step in remaining:- exec_plan.add_stage(f"step_{step.step_num}", [step.module_id])+ def _fixed_non_dispatchable() -> dict[str, Any]:+ return {+ "goal": plan.goal.value,+ "achieved": False,+ "steps_run": 0,+ "duration_s": 0.0,+ "status": "non_dispatchable",+ "results": [],+ "session": {},+ }- engine = AresEngine()- engine._registry = self.registry # reuse GoalEngine's registry — avoid re-loading modules- t0 = time.monotonic()- results = await engine.run_plan(exec_plan, campaign, plan.context, actor_role="operator")+ if (+ self._c_live_test_coordinator is None+ or self._c_live_test_principal is None+ or self._c_live_test_parent_key is None+ or getattr(campaign, "id", None) is None+ ):+ return _fixed_non_dispatchable()++ # Freeze every child, occurrence, ordinal, and parameter before any+ # admission can cross the effect boundary. Appending or changing any+ # later child changes the digest bound into every admission receipt.+ occurrence_by_module: dict[str, int] = {}+ children: list[dict[str, Any]] = []+ for module_ordinal, step in enumerate(plan.steps):+ if (+ type(step) is not GoalAttackStep+ or type(step.module_id) is not str+ or not step.module_id+ or type(step.step_num) is not int+ or step.step_num < 1+ or step.step_num - 1 > 9_007_199_254_740_991+ or module_ordinal > 9_007_199_254_740_991+ or not isinstance(step.params, dict)+ ):+ return _fixed_non_dispatchable()+ occurrence = occurrence_by_module.get(step.module_id, 0)+ occurrence_by_module[step.module_id] = occurrence + 1+ children.append(+ {+ "module_id": step.module_id,+ "params": dict(step.params),+ "occurrence": occurrence,+ "stage_ordinal": module_ordinal,+ "decision_ordinal": step.step_num - 1,+ "module_ordinal": module_ordinal,+ }+ )+ if not children:+ return _fixed_non_dispatchable()+ try:+ # A JSON round trip is the deep-freeze boundary. It severs every+ # caller-owned nested dict/list reference before the first await,+ # so a completed child cannot mutate a later child's bound bytes.+ frozen_intent = json.loads(+ json.dumps(+ {+ "goal": plan.goal.value,+ "children": children,+ },+ sort_keys=True,+ separators=(",", ":"),+ ensure_ascii=False,+ allow_nan=False,+ )+ )+ if (+ type(frozen_intent) is not dict+ or type(frozen_intent.get("children")) is not list+ ):+ raise ValueError+ children = frozen_intent["children"]+ whole_intent_digest = canonical_intent_digest(frozen_intent)+ except (TypeError, ValueError, json.JSONDecodeError):+ return _fixed_non_dispatchable()++ t0 = time.monotonic()+ results: list[dict[str, Any]] = []+ status = "terminal"+ for child in children:+ dispatch_request = DispatchRequestV1(+ campaign_id=campaign.id,+ module_id=child["module_id"],+ ingress_code="goal_api",+ idempotency_key=self._c_live_test_parent_key,+ raw_parameters=child["params"],+ whole_intent_digest=whole_intent_digest,+ occurrence=child["occurrence"],+ stage_ordinal=child["stage_ordinal"],+ decision_ordinal=child["decision_ordinal"],+ module_ordinal=child["module_ordinal"],+ )+ outcome = await self._c_live_test_coordinator.execute_module(+ self._c_live_test_principal,+ dispatch_request,+ campaign,+ )+ identity = outcome.identity+ results.append(+ {+ "module_id": child["module_id"],+ "disposition": outcome.disposition.value,+ "attempt_id": None if identity is None else identity.attempt_id,+ "logical_execution_id": (+ None if identity is None else identity.logical_execution_id+ ),+ "lifecycle_result": outcome.lifecycle_result.value,+ "terminal_committed": bool(outcome.terminal_committed),+ }+ )+ if outcome.disposition not in {+ DispatchDispositionV1.TERMINAL,+ DispatchDispositionV1.REPLAYED,+ }:+ status = outcome.disposition.value+ breakreturn {- "goal": plan.goal.value,- "achieved": self.check_goal_achieved(plan.goal),- "steps_run": len(plan.steps),+ "goal": plan.goal.value,+ "achieved": self.check_goal_achieved(plan.goal) if status == "terminal" else False,+ "steps_run": len(results),"duration_s": round(time.monotonic() - t0, 2),- "results": results,- "session": self.session.stats(),+ "status": status,+ "results": results,+ "session": self.session.stats(),}diff --git a/ares/modules/sdk.py b/ares/modules/sdk.pyindex ab56002..125f4dd 100644--- a/ares/modules/sdk.py+++ b/ares/modules/sdk.py@@ -55,6 +55,7 @@ Quick start:result = await self.execute(ctx)return result.findings, result.raw"""+from __future__ import annotations# ── Core base ──────────────────────────────────────────────────────────────────@@ -119,16 +120,17 @@ import math# ── Decorators / helpers ──────────────────────────────────────────────────────+def module_metadata(- module_id: str,- name: str,- category: str,+ module_id: str,+ name: str,+ category: str,description: str,- author: str = "Community",- opsec: OpsecLevel = OpsecLevel.LOW,- requires: list[str] | None = None,- outputs: list[str] | None = None,- mitre: list[str] | None = None,+ author: str = "Community",+ opsec: OpsecLevel = OpsecLevel.LOW,+ requires: list[str] | None = None,+ outputs: list[str] | None = None,+ mitre: list[str] | None = None,) -> Any:"""Class decorator to set all module metadata cleanly.@@ -150,7 +152,9 @@ def module_metadata("""if not isinstance(category, str) or not category.strip():raise ValueError("module_metadata category must be a non-empty string")- if not isinstance(opsec, OpsecLevel) and str(opsec) not in {level.value for level in OpsecLevel}:+ if not isinstance(opsec, OpsecLevel) and str(opsec) not in {+ level.value for level in OpsecLevel+ }:raise ValueError("module_metadata opsec must be an OpsecLevel or valid opsec level string")for field_name, value in (("requires", requires),@@ -163,22 +167,21 @@ def module_metadata(raise ValueError(f"module_metadata {field_name} must be a list of strings")def decorator(cls: type) -> type:- cls.MODULE_ID = module_id- cls.MODULE_NAME = name- cls.MODULE_CATEGORY = category+ cls.MODULE_ID = module_id+ cls.MODULE_NAME = name+ cls.MODULE_CATEGORY = categorycls.MODULE_DESCRIPTION = description- cls.MODULE_AUTHOR = author- cls.OPSEC_LEVEL = opsec- cls.REQUIRES = requires or []- cls.OUTPUTS = outputs or []- cls.MITRE_TECHNIQUES = mitre or []+ cls.MODULE_AUTHOR = author+ cls.OPSEC_LEVEL = opsec+ cls.REQUIRES = requires or []+ cls.OUTPUTS = outputs or []+ cls.MITRE_TECHNIQUES = mitre or []errors = validate_module_class(cls)if errors:- raise ValueError(- f"Module class {cls.__name__!r} has validation errors: {errors}"- )+ raise ValueError(f"Module class {cls.__name__!r} has validation errors: {errors}")return cls+return decorator@@ -198,6 +201,7 @@ def requires_privilege(level: str) -> Any:def decorator(cls: type) -> type:cls.REQUIRED_PRIVILEGE = level.strip()return cls+return decorator@@ -222,14 +226,19 @@ def timeout(seconds: int | float) -> Any:cls.MODULE_TIMEOUT_SECONDS = secondscls.DEFAULT_TIMEOUT_S = secondsreturn cls+return decorator# ── TestHelper — makes unit testing modules trivial ───────────────────────────+class ModuleTestHelper:"""- Helper for unit-testing modules without a full engine.+ Static preview helper for module metadata and request-shape tests.++ C-LIVE-v1 intentionally does not execute module code through the public+ SDK. Effectful tests use the sealed coordinator's private test seam.Usage:helper = ModuleTestHelper(KerberoastModule)@@ -244,18 +253,19 @@ class ModuleTestHelper:from ares.core.noise import NoiseControllerself.module_class = module_class- self.settings = AresSettings()+ self.settings = AresSettings()# NOTE: scope defaults to 0.0.0.0/0 for test harness.# Override via ModuleTestHelper(scope_cidrs=[...]) in integration tests._scope = [ScopeEntry(cidr=s) for s in (scope_cidrs or ["0.0.0.0/0"])]- self.campaign = Campaign(- name="test-campaign", client="test",+ self.campaign = Campaign(+ name="test-campaign",+ client="test",scope=_scope,noise_profile=NoiseProfile.NORMAL,operator="test",)- self.noise = NoiseController(self.campaign)- self.module = module_class(+ self.noise = NoiseController(self.campaign)+ self.module = module_class(settings=self.settings,campaign=self.campaign,noise=self.noise,@@ -263,9 +273,9 @@ class ModuleTestHelper:def make_context(self,- target: str = "10.0.0.1",- domain: str = "",- params: dict[str, Any] | None = None,+ target: str = "10.0.0.1",+ domain: str = "",+ params: dict[str, Any] | None = None,dry_run: bool = True,**kwargs: Any,) -> ExecutionContext:@@ -277,33 +287,45 @@ class ModuleTestHelper:context_params.setdefault(requirement, True)return ExecutionContext.build(- campaign = self.campaign,- target = target,- module_id = self.module_class.MODULE_ID,- domain = domain,- params = context_params,- dry_run = dry_run,+ campaign=self.campaign,+ target=target,+ module_id=self.module_class.MODULE_ID,+ domain=domain,+ params=context_params,+ dry_run=dry_run,)async def validate(self, ctx: ExecutionContext) -> None:- """Run validate() and surface errors clearly."""- await self.module.validate(ctx)+ """Validate the preview envelope without invoking module code."""+ if not isinstance(ctx, ExecutionContext):+ raise TypeError("SDK preview requires an ExecutionContext")async def run(self, ctx: ExecutionContext) -> ModuleResult:- """Run execute() and return the structured result."""- return await self.module.execute(ctx)+ """Return a static preview; never call validate(), execute(), or run()."""+ if not isinstance(ctx, ExecutionContext):+ raise TypeError("SDK preview requires an ExecutionContext")+ return ModuleResult(+ status="preview_only",+ module_id=self.module_class.MODULE_ID,+ raw={+ "preview": True,+ "would_execute": False,+ "target": ctx.target,+ "module_id": self.module_class.MODULE_ID,+ },+ )async def run_full(self,- target: str = "10.0.0.1",- domain: str = "",- params: dict[str, Any] | None = None,+ target: str = "10.0.0.1",+ domain: str = "",+ params: dict[str, Any] | None = None,dry_run: bool = True,) -> ModuleResult:- """One-liner: build context, validate, execute, return result."""- ctx = self.make_context(target=target, domain=domain,- params=params, dry_run=dry_run)- await self.validate(ctx)+ """One-liner static preview; ``dry_run=False`` is rejected."""+ if dry_run is not True:+ raise PermissionError("public SDK helpers are preview-only")+ ctx = self.make_context(target=target, domain=domain, params=params, dry_run=dry_run)return await self.run(ctx)def report(self, result: ModuleResult) -> dict[str, Any]:@@ -322,27 +344,53 @@ class ModuleTestHelper:# ── Public API surface ────────────────────────────────────────────────────────__all__ = [# Base- "BaseModule", "ModuleResult", "OpsecLevel", "validate_module_class",+ "BaseModule",+ "ModuleResult",+ "OpsecLevel",+ "validate_module_class",# Context"ExecutionContext",# Errors- "AresError", "ModuleError", "ModuleValidationError", "ModuleTimeoutError",- "NetworkError", "ConnectionRefused", "ConnectionTimeout", "HostUnreachable",- "CredentialError", "AuthenticationFailed", "AccountLocked", "CredentialExpired",- "NoCredentialsAvailable", "ExecutionError", "SandboxError",- "ScopeError", "OpsecError", "DetectionSignal", "HoneypotDetected",- "InsufficientPrivilege", "InvalidContext",+ "AresError",+ "ModuleError",+ "ModuleValidationError",+ "ModuleTimeoutError",+ "NetworkError",+ "ConnectionRefused",+ "ConnectionTimeout",+ "HostUnreachable",+ "CredentialError",+ "AuthenticationFailed",+ "AccountLocked",+ "CredentialExpired",+ "NoCredentialsAvailable",+ "ExecutionError",+ "SandboxError",+ "ScopeError",+ "OpsecError",+ "DetectionSignal",+ "HoneypotDetected",+ "InsufficientPrivilege",+ "InvalidContext",# Campaign types- "Finding", "Severity",+ "Finding",+ "Severity",# Logging"get_logger",# MITRE- "TechniqueLibrary", "TechniqueMapper",+ "TechniqueLibrary",+ "TechniqueMapper",# Normalize- "ArtifactStore", "HostArtifact", "UserArtifact", "CredentialArtifact",- "HashArtifact", "PermissionArtifact",+ "ArtifactStore",+ "HostArtifact",+ "UserArtifact",+ "CredentialArtifact",+ "HashArtifact",+ "PermissionArtifact",# Decorators- "module_metadata", "requires_privilege", "timeout",+ "module_metadata",+ "requires_privilege",+ "timeout",# Testing"ModuleTestHelper",]diff --git a/ares/strategy/engine.py b/ares/strategy/engine.pyindex d5f8a2c..54adb50 100644--- a/ares/strategy/engine.py+++ b/ares/strategy/engine.py@@ -12,6 +12,7 @@ from __future__ import annotationsimport asyncioimport timeimport json+from collections.abc import Mappingfrom typing import Anyfrom ares.core.logger import get_logger, audit@@ -55,6 +56,226 @@ class StrategyEngine:self._notifier = notifier or OperatorNotifier()self._kb = OutcomeKnowledgeBase()self._target_state = TargetStateMap()+ # There is intentionally no production configuration surface for this+ # seam. The generation-11 catalog currently makes every descriptor+ # ineligible, so production Strategy must stop before planning or any+ # effect. Tests may populate the private, canonical plan below to+ # exercise the coordinator wiring without enabling a production path.+ self._c_live_test_coordinator: Any | None = None+ self._c_live_test_principal: Any | None = None+ self._c_live_test_parent_key: str | None = None+ self._c_live_test_plan_json: str | None = None+ self._c_live_test_plan_digest: str | None = None++ def _configure_c_live_test_plan(+ self,+ *,+ coordinator: Any,+ principal: Any,+ idempotency_key: str,+ plan: tuple[Mapping[str, Any], ...],+ ) -> None:+ """Install one pure deterministic plan for C-LIVE wiring tests only.++ This leading-underscore seam is not read from settings, environment,+ request data, or a plugin. Production construction therefore cannot+ activate Strategy while descriptors remain ineligible.+ """+ from ares.core.execution_admission import canonical_intent_digest+ from ares.db.execution_lifecycle import TrustedPrincipal, valid_uuid++ if (+ not callable(getattr(coordinator, "execute_module", None))+ or type(principal) is not TrustedPrincipal+ or not valid_uuid(idempotency_key)+ or type(plan) is not tuple+ ):+ raise ValueError("invalid deterministic C-LIVE strategy test plan")++ occurrence_by_module: dict[str, int] = {}+ normalized: list[dict[str, Any]] = []+ for module_ordinal, value in enumerate(plan):+ if not isinstance(value, Mapping) or set(value) - {+ "module_id",+ "params",+ "stage_ordinal",+ "decision_ordinal",+ }:+ raise ValueError("invalid deterministic C-LIVE strategy test plan")+ module_id = value.get("module_id")+ params = value.get("params", {})+ stage_ordinal = value.get("stage_ordinal", module_ordinal)+ decision_ordinal = value.get("decision_ordinal", 0)+ if (+ type(module_id) is not str+ or not module_id+ or not isinstance(params, Mapping)+ or type(stage_ordinal) is not int+ or type(decision_ordinal) is not int+ or not 0 <= stage_ordinal <= 9_007_199_254_740_991+ or not 0 <= decision_ordinal <= 9_007_199_254_740_991+ ):+ raise ValueError("invalid deterministic C-LIVE strategy test plan")+ occurrence = occurrence_by_module.get(module_id, 0)+ occurrence_by_module[module_id] = occurrence + 1+ normalized.append(+ {+ "module_id": module_id,+ "params": dict(params),+ "occurrence": occurrence,+ "stage_ordinal": stage_ordinal,+ "decision_ordinal": decision_ordinal,+ "module_ordinal": module_ordinal,+ }+ )++ try:+ plan_json = json.dumps(+ normalized,+ sort_keys=True,+ separators=(",", ":"),+ ensure_ascii=False,+ allow_nan=False,+ )+ frozen_plan = json.loads(plan_json)+ digest = canonical_intent_digest(frozen_plan)+ except (TypeError, ValueError) as exc:+ raise ValueError("invalid deterministic C-LIVE strategy test plan") from exc++ self._c_live_test_coordinator = coordinator+ self._c_live_test_principal = principal+ self._c_live_test_parent_key = idempotency_key+ self._c_live_test_plan_json = plan_json+ self._c_live_test_plan_digest = digest++ @staticmethod+ def _c_live_non_dispatchable(goal: str) -> EngagementResult:+ return EngagementResult(+ goal=goal,+ total_rounds=0,+ final_status="non_dispatchable",+ rounds=[],+ final_detection_score=0.0,+ modules_succeeded=[],+ modules_failed=[],+ knowledge_updates=0,+ elapsed_seconds=0.0,+ )++ async def _run_c_live_test_plan(self, campaign: Any, goal: str) -> EngagementResult:+ """Dispatch the already-frozen test plan through admission, in order."""+ from ares.core.engine import is_successful_module_outcome+ from ares.core.execution_admission import (+ DispatchDispositionV1,+ DispatchRequestV1,+ canonical_intent_digest,+ )++ started_at = time.monotonic()+ if (+ self._c_live_test_coordinator is None+ or self._c_live_test_principal is None+ or self._c_live_test_parent_key is None+ or self._c_live_test_plan_json is None+ or self._c_live_test_plan_digest is None+ ):+ return self._c_live_non_dispatchable(goal)++ # Decode and verify the *complete* plan before the first coordinator+ # call. No provider, planner, module, notifier, or network helper runs+ # while this fan-out is being formed.+ try:+ children = json.loads(self._c_live_test_plan_json)+ if (+ type(children) is not list+ or canonical_intent_digest(children) != self._c_live_test_plan_digest+ or not children+ ):+ raise ValueError+ except (TypeError, ValueError, json.JSONDecodeError):+ return self._c_live_non_dispatchable(goal)++ round_outcomes: list[ModuleOutcome] = []+ modules_executed: list[str] = []+ succeeded: list[str] = []+ failed: list[str] = []+ final_status = "terminal"++ for child in children:+ module_id = child["module_id"]+ request = DispatchRequestV1(+ campaign_id=campaign.id,+ module_id=module_id,+ ingress_code="strategy",+ idempotency_key=self._c_live_test_parent_key,+ raw_parameters=child["params"],+ whole_intent_digest=self._c_live_test_plan_digest,+ occurrence=child["occurrence"],+ stage_ordinal=child["stage_ordinal"],+ decision_ordinal=child["decision_ordinal"],+ module_ordinal=child["module_ordinal"],+ )+ outcome = await self._c_live_test_coordinator.execute_module(+ self._c_live_test_principal,+ request,+ campaign,+ )+ modules_executed.append(module_id)+ if outcome.disposition is DispatchDispositionV1.REPLAYED:+ round_outcomes.append(+ ModuleOutcome(+ module_id=module_id,+ success=False,+ quality=0.0,+ evidence="durable_terminal_replay",+ )+ )+ continue+ if outcome.disposition is not DispatchDispositionV1.TERMINAL:+ final_status = outcome.disposition.value+ break++ result = outcome.module_result+ status = getattr(result, "outcome", None) or getattr(result, "status", "")+ success = is_successful_module_outcome(status)+ if success:+ succeeded.append(module_id)+ else:+ failed.append(module_id)+ round_outcomes.append(+ ModuleOutcome(+ module_id=module_id,+ success=success,+ quality=1.0 if success else 0.0,+ evidence=str(+ getattr(result, "outcome_message", "")+ or getattr(result, "error", "")+ or status+ )[:200],+ findings_count=len(getattr(result, "findings", ()) or ()),+ )+ )++ elapsed = max(0.0, time.monotonic() - started_at)+ round_result = RoundResult(+ round_num=1,+ plan_confidence=1.0,+ detection_score=0.0,+ modules_executed=modules_executed,+ outcomes=round_outcomes,+ stopped_reason="" if final_status == "terminal" else final_status,+ )+ return EngagementResult(+ goal=goal,+ total_rounds=1,+ final_status=final_status,+ rounds=[round_result],+ final_detection_score=0.0,+ modules_succeeded=succeeded,+ modules_failed=failed,+ knowledge_updates=0,+ elapsed_seconds=elapsed,+ )async def run_autonomous_engagement(self,@@ -85,6 +306,27 @@ class StrategyEngine:adversarial_sim: Run blue-team simulation after each planactor_role: RBAC role for module execution"""+ _ = (+ max_rounds,+ max_detection_probability,+ confidence_threshold,+ llm_backend,+ secondary_backend,+ adversarial_sim,+ actor_role,+ authorizations,+ forbidden_modules,+ allow_persistence,+ )+ # C-LIVE-v1 is safety wiring, not activation. With all production+ # descriptors disabled/ineligible, the public constructor always+ # returns here before legacy Strategy helpers, planning, notifications,+ # campaign runtime setup, or target-module execution.+ return await self._run_c_live_test_plan(campaign, goal)++ # The pre-C-LIVE autonomous implementation remains below only as+ # historical context during this bounded batch; it is unreachable from+ # the public entrypoint and every former effectful helper is fail-closed.start_time = time.monotonic()rounds: list[RoundResult] = []succeeded: list[str] = []@@ -491,92 +733,45 @@ class StrategyEngine:)async def _run_coverage_predictor(self, campaign: "Any") -> dict:- """Run opsec.coverage_predictor and return raw results."""- try:- from ares.modules.opsec.coverage_predictor import CoveragePredictorModule- from ares.core.noise import NoiseController- mod = CoveragePredictorModule(- settings=self._settings, campaign=campaign,- noise=NoiseController(campaign),- )- findings, raw = await mod.run(campaign=campaign)- return raw- except Exception as exc:- logger.warning("coverage_predictor_failed", error=str(exc)[:100])- return {"detection_score": 0.0, "wait_recommendation": {"hours": 0, "reason": "predictor unavailable"}}+ """Disabled C-LIVE-v1 helper; it never constructs or runs a module."""+ del campaign+ return {+ "detection_score": 0.0,+ "wait_recommendation": {+ "hours": 0,+ "reason": "c-live-strategy-non-dispatchable",+ },+ }async def _get_edr_context(self, campaign: "Any") -> dict:- """Get EDR bypass context from artifact store or return defaults."""- try:- from ares.modules.edr.bypass_adaptive import EDRAdaptiveBypassModule- from ares.core.noise import NoiseController- # Try to detect EDR vendor from fingerprint artifacts- edr_vendor = "unknown"- store = getattr(campaign, "_artifact_store", None)- if store:- for art in getattr(store, "_artifacts", []):- if hasattr(art, "edr_vendors") and art.edr_vendors:- edr_vendor = art.edr_vendors[0].value- break- mod = EDRAdaptiveBypassModule(- settings=self._settings, campaign=campaign,- noise=NoiseController(campaign),- )- findings, raw = await mod.run(edr_vendor=edr_vendor)- raw["edr_vendor"] = edr_vendor- return raw- except Exception as exc:- logger.warning("edr_context_failed", error=str(exc)[:100])- return {"edr_vendor": "unknown", "viable_techniques": [], "recommended_approach": None}+ """Disabled C-LIVE-v1 helper; it performs no artifact or module work."""+ del campaign+ return {+ "edr_vendor": "unknown",+ "viable_techniques": [],+ "recommended_approach": None,+ }async def _run_ai_planner(self, campaign: "Any", goal: str,llm_backend: str, secondary_backend: str,adversarial_sim: bool, extra_context: dict,) -> dict:- """Run ai.autonomous_planner and return raw results."""- try:- from ares.modules.ai.autonomous_planner import AIAutonomousPlannerModule- from ares.core.noise import NoiseController- mod = AIAutonomousPlannerModule(- settings=self._settings, campaign=campaign,- noise=NoiseController(campaign),- )- # Build context manually with extra data- from ares.modules.ai.autonomous_planner import CampaignContextBuilder, _build_user_prompt- builder = CampaignContextBuilder()- ctx = builder.build(campaign, vault=None, goal=goal)- ctx.update(extra_context)- findings, raw = await mod.run(- campaign=campaign, goal=goal,- llm_backend=llm_backend,- secondary_backend=secondary_backend,- adversarial_sim=adversarial_sim,- extra_context=extra_context,- )- return raw- except Exception as exc:- logger.warning("ai_planner_failed", error=str(exc)[:100])- return {"confidence_score": 0.0, "execution_plan": [], "warnings": [str(exc)[:100]]}+ """Disabled C-LIVE-v1 helper; no LLM or planning network is used."""+ del campaign, goal, llm_backend, secondary_backend, adversarial_sim, extra_context+ return {+ "confidence_score": 0.0,+ "execution_plan": [],+ "warnings": ["c-live-strategy-non-dispatchable"],+ }async def _run_single_module(self, module_id: str, campaign: "Any",params: dict, actor_role: str,) -> "Any":- """Execute a single module via AresEngine."""- try:- result = await self._engine.run_module(- module_id=module_id,- campaign=campaign,- params=params,- actor_role=actor_role,- timeout_seconds=120,- )- return result- except Exception as exc:- logger.warning("strategy_module_run_error",- module=module_id, error=str(exc)[:100])- raise+ """Reject the former direct-engine Strategy bypass."""+ del module_id, campaign, params, actor_role+ raise PermissionError("C-LIVE Strategy dispatch requires coordinator admission")def _build_base_params(self, campaign: "Any") -> dict:"""diff --git a/ares/worker/_subprocess_worker.py b/ares/worker/_subprocess_worker.pyindex bba3b7d..4754b97 100644--- a/ares/worker/_subprocess_worker.py+++ b/ares/worker/_subprocess_worker.py@@ -8,6 +8,7 @@ Parent process reads stdout — stderr is logged separately.Exit code 0 = success (even if module found nothing).Exit code 1 = crash (parent will log stderr)."""+from __future__ import annotationsimport asyncio@@ -18,6 +19,7 @@ from typing import Anytry:import resource as _resource+_HAS_RESOURCE = Trueexcept ImportError:_resource = None # type: ignore[assignment]@@ -46,10 +48,10 @@ def apply_capability_limits(caps: set[str], limits: dict[str, int]) -> None:if not _HAS_RESOURCE:return # Windows — resource limits not supportedtry:- cpu_s = limits.get("cpu_time_s", 30)- mem_mb = limits.get("memory_mb", 256)- nproc = limits.get("max_procs", 8)- nfiles = limits.get("max_files", 64)+ cpu_s = limits.get("cpu_time_s", 30)+ mem_mb = limits.get("memory_mb", 256)+ nproc = limits.get("max_procs", 8)+ nfiles = limits.get("max_files", 64)# CPU time (hard+soft)_resource.setrlimit(_resource.RLIMIT_CPU, (cpu_s, cpu_s + 5))@@ -68,7 +70,7 @@ def apply_capability_limits(caps: set[str], limits: dict[str, int]) -> None:_resource.setrlimit(_resource.RLIMIT_NOFILE, (nfiles, nfiles))except (AttributeError, ValueError, OSError):- pass # Platform doesn't support — fail open (log in parent)+ pass # Platform doesn't support — fail open (log in parent)def check_capability_boundary(module_id: str, caps: set[str]) -> None:@@ -82,21 +84,24 @@ def check_capability_boundary(module_id: str, caps: set[str]) -> None:di test environment."""if "cap_unsafe" in caps:- return # builtin modules — no restrictions+ return # builtin modules — no restrictionsimport os+if os.environ.get("ARES_WORKER_MODE") != "1":- return # skip di luar worker subprocess (contoh: unit test)+ return # skip di luar worker subprocess (contoh: unit test)forbidden_in_env = set()if "cap_exec" not in caps:import sys+for mod_name in list(sys.modules.keys()):if mod_name in ("subprocess", "os.system", "commands"):forbidden_in_env.add(mod_name)if forbidden_in_env:import sys+sys.stderr.write(f"[worker] CAPABILITY VIOLATION: module {module_id!r} "f"loaded forbidden modules {forbidden_in_env} "@@ -108,94 +113,99 @@ def check_capability_boundary(module_id: str, caps: set[str]) -> None:def serialize_finding(f: Any) -> dict[str, Any]:"""Convert Finding pydantic model to JSON-serializable dict."""return {- "id": str(f.id),- "title": f.title,- "description": f.description,- "severity": f.severity.value if hasattr(f.severity, "value") else str(f.severity),- "confidence": f.confidence,+ "id": str(f.id),+ "title": f.title,+ "description": f.description,+ "severity": f.severity.value if hasattr(f.severity, "value") else str(f.severity),+ "confidence": f.confidence,"mitre_technique": f.mitre_technique,- "mitre_tactic": f.mitre_tactic,- "evidence": f.evidence,- "remediation": f.remediation,- "host": f.host,- "module_id": f.module_id,- "validated": f.validated,- "false_positive": f.false_positive,- "discovered_at": f.discovered_at.isoformat() if f.discovered_at else None,+ "mitre_tactic": f.mitre_tactic,+ "evidence": f.evidence,+ "remediation": f.remediation,+ "host": f.host,+ "module_id": f.module_id,+ "validated": f.validated,+ "false_positive": f.false_positive,+ "discovered_at": f.discovered_at.isoformat() if f.discovered_at else None,}-async def run_module(payload: dict[str, Any]) -> dict[str, Any]:- """Load and execute the requested module with capability enforcement."""- module_id = payload["module_id"]- campaign_id = payload["campaign_id"]- params = payload.get("params", {})-- # ── v1.0.0: Apply capability-derived resource limits ──────────────────- caps = set(payload.get("capabilities", []))- limits = payload.get("resource_limits", {})- apply_capability_limits(caps, limits if limits else {- "cpu_time_s": 30, "memory_mb": 256, "max_procs": 4, "max_files": 64- })-- # Legacy memory limit (kept for backwards compat)- apply_memory_limit(payload.get("max_memory_mb"))-- # Dynamically load module from registry- from ares.core.plugin.loader import PluginLoader- from ares.core.config import get_settings- from ares.core.noise import NoiseController-- settings = get_settings()- loader = PluginLoader()- registry = loader.load_all()-- if module_id not in registry:- return {"success": False, "error": f"Module '{module_id}' not found", "findings": [], "raw": {}}-- # Load campaign from DB (or create minimal mock if not found)- try:- from ares.db.database import AresDatabase- async with AresDatabase(settings.db_path, settings.encryption_key_value) as db:- c_data = await db.get_campaign(campaign_id)- except (OSError, ValueError, KeyError):- c_data = None-- if c_data:- from ares.core.campaign import Campaign- campaign = Campaign(**c_data)- else:- from ares.core.campaign import Campaign, NoiseProfile- campaign = Campaign(name="worker", client="worker", noise_profile=NoiseProfile.NORMAL)-- cls = registry.get(module_id)- noise = NoiseController(campaign)- instance = cls(settings=settings, campaign=campaign, noise=noise) # type: ignore[misc]-- # ── v1.0.0: Check capability boundary AFTER module loads ──────────────- check_capability_boundary(module_id, caps)-- # Use execute(ctx) — consistent with engine.py (v0.9.0+ interface)- from ares.core.context import ExecutionContext as _ExCtx- ctx = _ExCtx.build(- campaign = campaign,- target = params.get("target", ""),- module_id = module_id,- domain = params.get("domain", ""),- params = params,- operator = params.get("operator", "worker"),- settings = settings,- noise = noise,+_WORKER_ADMISSION_ERROR = (+ "subprocess stdin execution requires a non-serializable coordinator capability"+)+++class _PrivateWorkerConsumer:+ """Process-local consumer used only by the sealed in-process test seam."""++ def __init__(self) -> None:+ self.pending: dict[str, tuple[str, ...]] = {}++ def _register_admitted_dispatch_context(self, context: Any) -> None:+ self.pending[context._dispatch_nonce] = (+ context.campaign_id,+ context.submission_id,+ context.logical_execution_id,+ context.attempt_id,+ context.module_id,+ str(context.attempt_revision),+ str(context._store_id),+ context._signature,+ )++ def _consume_registered_dispatch_context(self, context: Any) -> bool:+ expected = self.pending.pop(context._dispatch_nonce, None)+ return expected == (+ context.campaign_id,+ context.submission_id,+ context.logical_execution_id,+ context.attempt_id,+ context.module_id,+ str(context.attempt_revision),+ str(context._store_id),+ context._signature,+ )+++_PRIVATE_WORKER_CONSUMER = _PrivateWorkerConsumer()+++async def _run_module_in_process(+ payload: dict[str, Any],+ dispatch_context: Any,+ executor: Any,+) -> dict[str, Any]:+ """Private capability consumer; it is unreachable from serialized stdin."""+ from ares.core.execution_admission import consume_dispatch_context, mark_effect_started++ module_id = payload.get("module_id")+ campaign_id = payload.get("campaign_id")+ if type(module_id) is not str or type(campaign_id) is not str:+ raise PermissionError(_WORKER_ADMISSION_ERROR)+ context = consume_dispatch_context(+ dispatch_context,+ consumer=_PRIVATE_WORKER_CONSUMER,+ campaign_id=campaign_id,+ module_id=module_id,)- module_result = await instance.execute(ctx)- findings = module_result.findings- raw = module_result.raw+ mark_effect_started(context)+ result = executor(payload)+ if asyncio.iscoroutine(result):+ result = await result+ if type(result) is not dict:+ raise TypeError("private worker executor must return a dict")+ return result++async def run_module(payload: dict[str, Any]) -> dict[str, Any]:+ """Reject every serializable payload; sealed capabilities cannot cross stdin."""+ del payloadreturn {- "success": True,- "findings": [serialize_finding(f) for f in findings],- "raw": {k: str(v) if not isinstance(v, (int, float, str, bool, list, dict, type(None))) else v- for k, v in raw.items()},+ "success": False,+ "error": _WORKER_ADMISSION_ERROR,+ "code": "EXECUTION_ADMISSION_REQUIRED",+ "findings": [],+ "raw": {},}@@ -203,7 +213,7 @@ def main() -> None:"""Entry point: read JSON from stdin, write JSON to stdout."""try:raw_input = sys.stdin.read()- payload = json.loads(raw_input)+ payload = json.loads(raw_input)except Exception as e:sys.stderr.write(f"[worker] Failed to parse payload: {e}\n")sys.exit(1)@@ -217,10 +227,10 @@ def main() -> None:err = traceback.format_exc()sys.stderr.write(f"[worker] Unhandled exception:\n{err}\n")error_result = {- "success": False,- "error": err[-500:], # last 500 chars+ "success": False,+ "error": err[-500:], # last 500 chars"findings": [],- "raw": {},+ "raw": {},}sys.stdout.write(json.dumps(error_result))sys.stdout.flush()diff --git a/docker/README.md b/docker/README.mdindex 69bbdf3..80afc7f 100644--- a/docker/README.md+++ b/docker/README.md@@ -56,6 +56,12 @@ frontend together. Mixed workers are unsupported because managed ownership isrevision-exact. A container-image rollback does not downgrade the additiveschema; return to a compatible forward image instead.+Revision `0010` adds execution-lifecycle persistence without activating a live+gateway. Drain all processes externally, back up, migrate, and then start only+the matching 0010-aware API compatibility image. No supported operator budget+command exists in this phase, so do not configure execution capacity with+direct SQL. Legacy execution is not automatically disabled by the migration.+## Browser-session rolloutRefresh sessions use host-only HttpOnly cookies and CSRF/Origin validation.@@ -63,7 +69,8 @@ Access tokens remain in browser memory, and API keys remain the automationcredential. Deploy backend and frontend atomically, drain existing sockets,and require existing users to sign in again; the old browser refresh value isdeleted from `sessionStorage` and is not bridged into the cookie transport.-Mixed versions are unsupported. No revision `0010` is introduced: Alembic-remains at `0009`, so rollback replaces backend and frontend together without a-database downgrade. The nginx TLS log and HTTP redirect use `$uri`, and the+Mixed versions are unsupported. That browser-session change remains revision+`0009`; the current Alembic head is the separate additive revision `0010`.+Rollback replaces compatible application images without a database downgrade.+The nginx TLS log and HTTP redirect use `$uri`, and theredirect drops query strings instead of reflecting them.diff --git a/docs/ENGINE_FLOW.md b/docs/ENGINE_FLOW.mdindex cd917aa..29f2a98 100644--- a/docs/ENGINE_FLOW.md+++ b/docs/ENGINE_FLOW.md@@ -1,14 +1,16 @@# ARES Engine Flow-**Version:** 1.0.0+**Version:** 1.0.0 | **Runtime status:** C-LIVE-v1 safety wiring; descriptors inactive## Overview-This document traces the complete execution pipeline from user input to findings stored in the database.+The opening diagrams preserve the pre-C-LIVE target design for historical+context. They are inactive in C-LIVE-v1. The authoritative reachable effect+flow is [C-LIVE-v1 durable effect ordering](#c-live-v1-durable-effect-ordering).----## Pipeline Diagram+## Legacy pipeline diagram (inactive in C-LIVE-v1)```Operator Input (CLI / API)@@ -54,21 +56,26 @@ Operator Input (CLI / API)### AresEngine (`ares/core/engine.py`)-Orchestrates module execution. Key methods:+Historical method roles are shown below. Public calls now fail closed without a+sealed coordinator context:| Method | Description ||--------|-------------|-| `run_module(id, campaign, params)` | Run single module with timeout + retry |-| `run_plan(plan, campaign, params)` | Run ExecutionPlan (staged, parallel per stage) |+| `run_module(id, campaign, params)` | Reject unless given one valid single-use coordinator seal |+| `run_plan(plan, campaign, params)` | Reject unless every child has an admitted sealed context || `dry_run_plan(plan, params)` | Preview without executing |-**Retry logic:** `asyncio.TimeoutError` → retry up to 2 times with exponential backoff (2s, 4s). Original timeout status preserved even if retries fail with other exceptions.+**Retry status:** implicit timeout/exception retry is disabled. A retry is a new+coordinator-admitted deterministic child; uncertain work is never retried by+C-LIVE-v1.---### GoalEngine + CapabilityGraph (`ares/goal/engine.py`)-The planner that converts a high-level goal into an ordered execution chain.+This is retained deterministic planning logic. Production Goal planning is+fail-closed while descriptors are ineligible; only the private deterministic+repository-test seam may invoke it.**Chain resolution priority:**1. `preferred_chain` from GoalDefinition (if all modules available)@@ -147,3 +154,29 @@ path = graph.find_path("svc_sql", "Domain Admins")report = graph.path_to_report(path)# → {"steps": [{"from": "svc_sql", "to": "TGS:svc_sql", "attack": "ad.kerberoast", ...}], ...}```++---++## C-LIVE-v1 durable effect ordering++Reachable first-party live entrypoints use the sealed coordinator in this fixed+order:++```text+authenticate/revalidate+ -> admission APPLIED (ACCEPTED, revision 0)+ -> revalidate again+ -> QUEUED/APPLIED (revision 1)+ -> DISPATCHING/APPLIED (revision 2)+ -> RUNNING/APPLIED (revision 3)+ -> consume one process-local dispatch seal+ -> execute one module effect+ -> commit a known terminal outcome+ -> expose the redacted result+```++Every gate compares the exact lifecycle result; replay and conflict never own+dispatch. A retry or plan child has a deterministic child identity and repeats+the full ordering. A crash before `RUNNING` is stranded without effect. An+uncertain failure after `RUNNING` enters settlement-pending (or remains running)+and is never automatically retried; P1-F recovery is outside C-LIVE-v1.diff --git a/docs/api-reference.md b/docs/api-reference.mdindex 339668b..5fca4fb 100644--- a/docs/api-reference.md+++ b/docs/api-reference.md@@ -1,8 +1,9 @@# ARES API Reference> **Base URL:** `http://127.0.0.1:8080`-> API endpoints require authentication unless noted otherwise. Automation-> endpoints may accept `X-API-Key`; account/security management endpoints use+> API endpoints require authentication unless noted otherwise. Non-execution+> automation endpoints may accept `X-API-Key`; account/security management and+> every C-LIVE execution endpoint use> JWT/browser sessions only. Browser auth is same-origin and CSRF protected;> `GET /health` is unauthenticated. API keys are the supported automation> credential.@@ -300,12 +301,13 @@ Useful for verifying remediation between assessments.### `POST /campaigns/{id}/run`-Run an execution plan against the campaign.--Plans execute live by default; set `dry_run` to `true` for a preview. If any-module anywhere in the plan is classified `HIGH_NOISE`, the caller must have-the `team_lead` role. The complete plan is authorized before execution or-dry-run processing begins.+Preview an execution plan or submit it to the C-LIVE boundary. `dry_run=true`+is a local preview and executes no module code. A live submission is+bearer-only, requires a canonical lowercase UUIDv4 `Idempotency-Key`, rejects+raw secret material, and authorizes the complete plan before any child can be+admitted. In C-LIVE-v1 every production descriptor is ineligible, so a+production live request returns `409 descriptor_unavailable` with+`redispatched=false` and performs no module or broadcast effect.```json{@@ -315,9 +317,12 @@ dry-run processing begins.}```-**Response:** `202 Accepted`+An eligible private test seam responds synchronously only after every child is+durably terminal:++**Response:** `200 OK````json-{ "execution_id": "exec-abc123", "status": "running", "total_modules": 1 }+{ "campaign_id": "abc12345", "modules_run": 1, "children": [] }```---@@ -366,7 +371,12 @@ truth for dynamic dashboard forms.### `POST /modules/{module_id}/run`-Run a single module directly.+Preview one module or submit it to the bearer-only C-LIVE boundary. A live+submission requires a canonical lowercase UUIDv4 `Idempotency-Key` and accepts+opaque credential identifiers only. Production descriptors are ineligible in+C-LIVE-v1, so the production response is `409 descriptor_unavailable` with+`redispatched=false`; no module code or handler broadcast runs. `dry_run=true`+returns a local preview without module execution.```json{@@ -542,8 +552,11 @@ List active autonomous engagements.### `POST /strategy/engage`-Start an autonomous engagement. Backend RBAC still enforces restricted module-authorization.+Submit a Strategy execution intent to the bearer-only C-LIVE boundary. In+C-LIVE-v1 all production descriptors remain disabled/ineligible, so this route+returns the frozen synchronous non-dispatchable response and performs no LLM,+planning-network, module, or broadcast effect. A production planning provider+cannot be selected through this request.Request body:@@ -564,16 +577,14 @@ Notes:- `goal` can be `domain_admin`, `enterprise_admin`, `cloud_admin`,`data_exfil`, `persistence`, or `full_compromise`.-- `llm_backend` can be `claude`, `openai`, or `local`.-- The dashboard Strategy page uses the backend defaults. By default that means- Claude-backed planning, so `ANTHROPIC_API_KEY` must be present in the ARES- server environment.-- `llm_backend=openai` requires `OPENAI_API_KEY`.-- `llm_backend=local` expects Ollama at `http://localhost:11434`.-- ARES dashboard API keys authenticate callers to ARES. They are not LLM- provider keys.-- The endpoint returns immediately. Monitor progress through campaign events- or the dashboard `Live` page.+- Legacy `llm_backend` fields are accepted only as inert request compatibility+ data in this release; no Claude, OpenAI, Ollama, or other planning connection+ is opened.+- `X-API-Key` does not authorize this endpoint. Supply a current bearer and a+ canonical lowercase UUIDv4 `Idempotency-Key`.+- The response is synchronous. With the production descriptor gate closed it+ is non-dispatchable; an eligible private test seam may return terminal `200`+ only after durable settlement.---@@ -603,8 +614,9 @@ Generate an execution plan from a template.Template plans are deterministic and do not call an LLM. They return a plan foroperator review and do not execute modules automatically.-For LLM-backed planning, run module `ai.autonomous_planner` through the-`/modules/{module_id}/run` endpoint or the dashboard Modules page.+Production LLM-backed planning is inactive in C-LIVE-v1. The+`ai.autonomous_planner` descriptor cannot be activated through this endpoint or+the dashboard; production planning activation requires separate approval.---@@ -753,3 +765,29 @@ HTTP status codes:| 429 | Rate limit exceeded || 500 | Internal server error || 503 | Engine not ready |++---++## C-LIVE-v1 execution boundary++Live requests to `POST /modules/{module_id}/run`,+`POST /campaigns/{campaign_id}/run`, and `POST /strategy/engage` are+bearer-only. `X-API-Key` never authorizes execution. Every non-preview request+must carry `Idempotency-Key` as a canonical lowercase UUIDv4; missing or+malformed keys return `422` after bearer/role and campaign-existence checks.+Raw credential material is rejected. Callers may provide only opaque credential+identifiers.++C-LIVE-v1 is safety wiring, not descriptor activation. Production descriptors+remain ineligible, so production Strategy performs no LLM/network planning and+returns the generic non-dispatchable response. An eligible private test seam is+synchronous and returns a terminal `200` only after durable settlement.++An exact replay returns `409 execution_replayed_no_redispatch` with stable+identifiers and never re-executes module code or emits a handler broadcast.+Changed intent under the same key returns `409 idempotency_conflict`. Authority+staleness returns `409`, capacity exhaustion `429`, inconsistent budget state+`503`, invalid contracts `422`, invariant failures `500`, and purged lifecycle+targets `410`. An unconfirmed terminal state returns+`503 execution_settlement_unconfirmed`; clients must inspect status using the+same key rather than submit a new logical execution.diff --git a/docs/architecture.md b/docs/architecture.mdindex 1156bea..69d9cfc 100644--- a/docs/architecture.md+++ b/docs/architecture.md@@ -1,16 +1,20 @@# ARES Architecture-**Version:** 6.0.0 | **Status:** Active Development+**Version:** 6.0.0 | **Status:** C-LIVE-v1 safety wiring; descriptors inactive## Overview-ARES (Automated Red team Engagement System) is an open-source red team automation framework. It automates attack chains, tracks campaign state, and generates professional reports — covering AD/Windows, Linux/Container, and Cloud (AWS/Azure/GCP) environments.+ARES (Automated Red team Engagement System) contains orchestration, campaign+state, reporting, and module infrastructure for AD/Windows,+Linux/Container, and Cloud environments. C-LIVE-v1 does not activate production+module descriptors. The legacy topology and data-flow diagrams below describe a+target architecture, not a currently reachable execution path.ARES is **not** a C2 framework. It does not include implants, beacons, or persistent agents. It is an orchestration layer for red team techniques executed from the operator's machine.----## High-Level Architecture+## Legacy target architecture (inactive for C-LIVE-v1 effects)```┌─────────────────────────────────────────────────────────────────┐@@ -178,7 +182,7 @@ module = container.build_module("ad.kerberoast", campaign)----## Data Flow+## Legacy data flow (inactive for C-LIVE-v1 effects)### Single Module Execution@@ -304,3 +308,21 @@ ARES/│ └── integration/ End-to-end campaign tests└── docker/ Dockerfiles, docker/docker-compose.dev.yml, docker/docker-compose.prod.yml```++---++## C-LIVE-v1 coordinator boundary++`ares.core.execution_admission` is the sole first-party bridge from HTTP+authority and lifecycle admission to an in-process engine effect. It derives+submission, logical-execution, attempt, operation, fan-out, and retry-child UUIDs+with the lifecycle typed-length binding. The resulting dispatch capability is+process-local, nonserializable, bound to its coordinator/engine/store and work+identity, and single-use.++Public engine module/plan calls, SDK helpers, and the real subprocess stdin+entrypoint fail closed without that seal. Production Strategy and Goal planning+also fail closed while all production descriptors remain ineligible. The+certified surface covers reachable first-party product entrypoints; dormant+classes that can only be reached through arbitrary Python imports are not an+activated worker path.diff --git a/docs/database-migrations.md b/docs/database-migrations.mdindex 430dee1..ceb4e83 100644--- a/docs/database-migrations.md+++ b/docs/database-migrations.md@@ -8,12 +8,13 @@ an existing unversioned catalog.## Managed and unversioned databasesA managed database has one valid `alembic_version` relation and exactly one-known revision row. Revision `0009` is current and forward-only. Managed-revisions `0001` through `0008` use normal Alembic migration; malformed or-unknown version metadata is rejected.+known revision row. Revision `0011` is current and forward-only. Managed+revisions `0001` through `0010` require an operator-run Alembic migration;+malformed or unknown version metadata is rejected.An unversioned database has no Alembic version relation. The adoption verifier-accepts only the complete, audited runtime-bootstrap generations 6 and 7. It+accepts only the complete, audited runtime-bootstrap generations 6, 7, and the+exact SQLite runtime generation 10. Itdoes not use `schema_version`, table presence, or partial column matching asauthority. Unknown or locally modified catalogs require owner-reviewed manualrecovery and are not stamped.@@ -32,7 +33,7 @@ python -m ares.db.migrations verify-adoptionA supported unversioned catalog reports a fixed readiness identifier ending inits proven predecessor (`0006` or `0007`). A current managed database reports-`ARES-M2B-ALREADY-MANAGED:0009`. No version relation is created by verification.+`ARES-M2B-ALREADY-MANAGED:0011`. No version relation is created by verification.After adoption or normal migration, verify the managed contract:@@ -78,7 +79,7 @@ python -m ares.db.migrations adopt --confirm-adoption --confirm-external-backupPostgreSQL adoption uses one connection, one explicit transaction, and a stabletransaction-scoped advisory lock. Complete verification occurs under that lock;-the proven predecessor is stamped and upgraded through `0009` on the same+the proven predecessor is stamped and upgraded through `0011` on the sameconnection. DDL, data, and version metadata roll back together on failure.Concurrent adoption reports a fixed ownership-busy result. Objects in unrelatedschemas are not changed; unexpected objects in the selected schema are rejected.@@ -106,9 +107,78 @@ already-managed result.Diagnostics are fixed identifiers and never contain database URLs, credentials,paths, schema identities, SQL, rows, digests, or exception text. Direct or blind-`alembic stamp 0009` is unsupported. Application rollback does not remove+`alembic stamp 0011` is unsupported. Application rollback does not removeadditive schema or migration history.+## Revision 0011 authority and admission++Revision `0011` is an append-only child of the byte-protected `0010` lifecycle+catalog. It adds the C-core authority/admission store contract; it does not+activate an HTTP endpoint, execution engine, worker, or other C-live caller.+Authentication before C-core and live producer integration remain pending.++The migration adds five ordinary authority/observation relations:++1. `campaign_execution_actor_grants`+2. `campaign_execution_destination_authorities`+3. `execution_approval_authorities`+4. `execution_attempt_destination_observations`+5. `execution_attempt_credential_observations`++Existing actor and campaign authority rows gain state, binding-digest, and+latest-operation fields. Credential rows gain execution-authority state,+revision, binding-digest, and latest-operation fields. Logical submissions gain+an admission-authority contract version, canonical principal user identity, and+immutable-intent digest. Attempts gain the authority contract version, trusted+principal references, immutable-intent binding, relevant gateway/grant+revisions, and destination, credential, and approval binding digests.++Upgrade accepts only the exact protected `0010` catalog. Historical logical and+attempt rows are marked contract v2 without changing the meaning or replay of+their existing bindings. The migration fabricates no historical attempt+destination/credential observation and no historical approval. Current+campaign destination authority is initialized from the campaign's stored+destination configuration; current credential authority starts active at+revision zero with a deterministic row binding. Neither initialization is used+to reinterpret a historical v2 submission or receipt.++New initial and retry requests use contract v3. New v2 creation and v3-to-v2+downgrade are forbidden. Initial admission creates no operation receipt: the+logical submission remains its sole replay authority. Authority mutations use+receipt-bound operation UUIDs and the fifteen operation codes documented in+[`execution-lifecycle.md`](execution-lifecycle.md). Approval consumption is+single-use and occurs in the same transaction as admission.++Store failures (`invalid_contract`, `conflict_operation`, `authority_stale`,+and `capacity_unavailable`) leave no durable admission rows. Canonical policy+`REJECTED` and `BLOCKED` verdicts are applied terminal admissions and persist+only their logical execution, closing attempt, zero-count outbox row, and+outbox operation receipt; they consume no approval and reserve no budget.+The terminal outbox identity and publication key are derived from the admission+operation and are never caller-supplied. Initial admission still has no+separate admission receipt. Retry contract v3 admits only a canonical accepted+decision.++The migration, data backfill, and revision advance are atomic. A failed upgrade+must roll back and allow a successful retry. Downgrade is refused before+mutation when it could discard authority history or approval-consumption data;+operational recovery is forward-fix-only. Mixed `0010`/`0011` binaries are+unsupported. Validation covers fresh/bootstrap and supported upgrades on both+backends, rollback/retry, catalog drift, deletion/foreign-key history, the full+C-core admission inventory, and all P1-A/P1-B/transition/lifecycle families on+the resulting candidate ledger. C-live endpoint and authentication tests are+not implied by those gates.++## Revision 0010 execution-lifecycle persistence++Revision `0010` adds the eleven-table execution-lifecycle catalog described in+[`execution-lifecycle.md`](execution-lifecycle.md). It seeds no authority,+budget capacity, attempt, approval, output link, or outbox row, and initializes+the gateway singleton in `disabled` mode. It does not activate a gateway or+disable legacy execution paths. Its bytes and existing v2 row meanings are+protected. Mixed `0009`/`0010` binaries are unsupported, and downgrade is+refused before mutation.+## Revision 0009 token-family rolloutRevision `0009` adds refresh-token families, one-time lineage, userdiff --git a/docs/engine_design.md b/docs/engine_design.mdindex 7decaac..75a14de 100644--- a/docs/engine_design.md+++ b/docs/engine_design.md@@ -1,10 +1,15 @@# ARES Engine Design-**Version:** 1.0.0 | **Status:** Active+**Version:** 1.0.0 | **Status:** C-LIVE-v1 safety wiring; descriptors inactive## Overview-The ARES engine is a goal-oriented attack orchestration system. Operators define a *goal* (e.g., `domain_admin`). The engine plans a chain, executes modules, tracks state, and adapts when techniques fail.+The engine retains goal, module, and state-management components, but the+pre-C-LIVE adaptive execution design documented below is inactive in+C-LIVE-v1. Reachable effects require the sealed coordinator described in+[C-LIVE-v1 engine ownership](#c-live-v1-engine-ownership); public engine calls+and production Goal/Strategy planning fail closed while descriptors are+ineligible.---@@ -26,7 +31,7 @@ AresEngine----## Execution Lifecycle+## Legacy execution lifecycle (inactive in C-LIVE-v1)Every module execution follows this exact sequence:@@ -222,7 +227,7 @@ except AresError as e:----## GoalEngine vs AttackPlanner+## Legacy GoalEngine/AttackPlanner design (production inactive)**GoalEngine** (`ares/goal/engine.py`) — deterministic backward chaining:- Operator sets `Goal.DOMAIN_ADMIN`@@ -236,7 +241,7 @@ except AresError as e:- Returns ranked `Suggestion` list with rationale- Re-runs after each execution (adapts to discovered state)-They work together:+The following sequence is historical and is not a production C-LIVE-v1 path:```GoalEngine.plan() → initial deterministic chain@@ -248,7 +253,7 @@ GoalEngine.plan() → initial deterministic chain----## AdaptiveAttackStrategy+## Legacy AdaptiveAttackStrategy (production inactive)When a module fails, the engine doesn't stop — it pivots:@@ -314,3 +319,19 @@ Node types: `host`, `dc`, `credential`, `finding`, `pivot`Edge types: `lateral`, `compromise`, `credential`, `discovery`, `pivot`Frontend renders with D3.js or Cytoscape.js.++---++## C-LIVE-v1 engine ownership++The engine no longer owns admission or implicit retries. A coordinator must+first obtain exact `APPLIED` results for admission, queue, dispatch, and running,+then pass a sealed single-use context to the engine. The engine prepares a+sanitized result; persistence/publication is released only after the V3 terminal+commit succeeds. Exact admission or terminal replay never enters the engine.++Plan occurrences retain stage/module ordinals, including repeated module IDs.+Retry attempts use deterministic child identities and repeat principal+revalidation before queueing. Timeout, disconnect, cancellation, or an ordinary+exception is not by itself settlement proof. Uncertain work is parked without+automatic redispatch; INDETERMINATE recovery remains P1-F.diff --git a/docs/execution-lifecycle.md b/docs/execution-lifecycle.mdnew file mode 100644index 0000000..d863aca--- /dev/null+++ b/docs/execution-lifecycle.md@@ -0,0 +1,385 @@+# Execution-lifecycle persistence++Revision `0010` adds an additive, test-only persistence contract for future+canonical execution. It does not integrate the API, engine, CLI, SDK,+Strategy, Goal, workers, Redis, subprocesses, sandbox, modules, or plugins.+The existing `module_runs` relation and historical `DONE`, outcome, and success+values remain legacy-unclassified; they are never promoted to authoritative+success.++Revision `0011` extends that protected base with the P1-C authority-and-+admission contract. Its scope is **C-core only**: store requests, authority+producers, locking, durable admission/retry decisions, and replay. It does not+make an HTTP, engine, CLI, SDK, Strategy, Goal, worker, or module path use the+new admission boundary. Authentication before entry to C-core and every live+producer integration are C-live work and remain pending. Nothing in this+document claims that a current public execution endpoint is enforced by+C-core.++Revision `0010` is byte-protected. Revision `0011` is an append-only child; it+must not rewrite the `0010` migration or reinterpret rows created under its+version-2 binding contracts.++`execution_gateway_state.mode=disabled` means only that the new canonical+gateway is inactive. It does not disable or secure existing legacy engine+entry points. Operators who require a no-execution migration window must drain+those paths externally. Global fail-closed enforcement remains a later phase.++## Catalog++Generation 10 adds exactly eleven ordinary, permanent relations:++1. `logical_executions`+2. `execution_attempts`+3. `execution_actor_authority_revisions`+4. `campaign_execution_authority_revisions`+5. `campaign_execution_budgets`+6. `execution_attempt_approvals`+7. `campaign_execution_budget_ledger`+8. `execution_output_links`+9. `execution_publication_outbox`+10. `execution_gateway_state`+11. `execution_operation_receipts`++Operation receipts are append-only replay authority. Each globally unique+operation UUID binds a fixed operation code, immutable campaign and target+identities, a canonical principal kind/subject/user/authority revision,+explicit expected-revision presence, ownership facts, a version-2+length-framed request digest, the fixed first result, its exact replay code,+every resulting identity/revision with explicit presence, and the matching+version-2 result digest. Mutable `latest_operation_*` columns are lookup hints+only. Exact replay is answered entirely from the stored receipt: later target+revision, target deletion, authority change, or campaign deletion cannot+rewrite the historical result. A same operation UUID with any changed binding+is always `conflict_operation` before mutable target or authority lookup.+Receipt insertion and the corresponding domain mutation share one transaction+and savepoint, so neither can commit without the other. Receipt bindings+contain only sanitized lifecycle facts and never raw request, destination,+credential, evidence, diagnostic, or secret-derived material.++Receipts retain historical UUID facts without foreign keys to mutable campaign,+target, or principal rows. SQLite blocks receipt `UPDATE` and `DELETE` with two+exact catalog-fingerprinted triggers. PostgreSQL uses one exact+`BEFORE UPDATE OR DELETE` trigger whose exact function and trigger definitions+are catalog-fingerprinted. No other lifecycle trigger is permitted.++They use named row-local checks, named primary/unique/foreign-key constraints,+and deterministic indexes. PostgreSQL relations are ordinary logged heap+tables with RLS disabled and no policies, inheritance, partitioning, or rewrite+rules. The receipt immutability trigger is the sole allowed user trigger.+SQLite and PostgreSQL foreign keys are deferred where+whole-campaign deletion or the logical/attempt cycle requires transaction-wide+validation.++Identifiers are lowercase canonical RFC-4122 UUIDv4 strings. Descriptor and+catalog digests are 64 lowercase hexadecimal characters. Persisted counts and+Unix-millisecond timestamps use the exact `0..9007199254740991` range. Request+and policy contract versions are `1`; descriptor contract version is+`ares.module-descriptor.v2`; capability, descriptor-blocker, and policy-reason+masks are version `1` with explicit numeric allocations independent of enum+declaration order.++Raw parameters, destinations, credentials, evidence, result bodies, SQL,+exception text, URLs, DSNs, hostnames, worker addresses, and secret-derived+hashes do not belong in lifecycle or outbox rows.++## Attempts and settlement++The 15 durable states are `rejected`, `blocked`, `accepted`, `queued`,+`dispatching`, `running`, `cancelling`, `settlement_pending`, `succeeded`,+`partial`, `failed`, `skipped`, `cancelled`, `timed_out`, and `indeterminate`.+The frozen graph has 31 legal and 194 illegal ordered pairs.++`settlement_pending` is nonterminal, non-dispatchable, holds budget+reservations, invalidates its lease, exposes no authoritative outputs, forbids+retry, and publishes one recovery-required event. Its recovery deadline is+exactly 24 hours after entry. It may resolve only to a known authoritative+terminal result or to final `indeterminate`. Final `indeterminate` requires a+current authenticated admin, a persisted opaque resolver reference and+authority revision, bounded-recovery proof after the deadline, conservative+noise/exfiltration consumption, concurrency release, and one terminal event.++External module effect is forbidden before the successful+`dispatching -> running` CAS. A dispatch/start failure is a no-effect failure:+it releases every reservation and has no outputs. Dispatch ownership history,+lease generation, original duration, and original expiry remain immutable;+`lease_invalidated_at` marks inactive ownership.++Cancellation has three persisted shapes. Never-leased cancellation has no+dispatch/start history. Leased-but-not-started cancellation preserves lease+history but cannot produce success, partial, or timeout. Started cancellation+may resolve truthfully to success, partial, failed, cancelled, timed out, or+settlement pending. A cancellation request records intent only; the exact+owner may still win with an authoritative result. Cancellation acknowledgement+may produce `cancelled` only with proof that no terminal module result won.++Every transition has one authoritative operation UUID. Cancellation terminal+results use the acknowledgement operation, timeouts use the timeout operation,+settlement-pending entry uses its recovery operation, ordinary terminal states+use the terminal operation, and explicit logical closure uses the closure+operation. Cancellation acknowledgement presents the immutable post-CAS+request revision.++## C-core admission authority++C-core accepts an immutable caller intent and a trusted stable principal. The+intent contains identities and requested work, but no claims about current+gateway, role, ownership, descriptor, credential, approval, or budget+authority. It also contains no caller-chosen outbox identity or publication+key. The principal is established outside C-core. A caller cannot promote a+snapshot, role, revision, ownership flag, catalog digest, or budget claim to+authority by placing it in the intent.++C-live must authenticate before calling C-core. A missing, invalid, revoked,+deleted, inactive, or demoted live principal must be rejected before submission+lookup. That authentication boundary is pending and is not implemented or+claimed by the C-core store contract.++Once the stable principal has been established, exact replay is intentionally+independent of later mutable-authority changes. The logical submission row is+the sole admission replay authority. An exact request by the same stable+principal may replay after gateway or authority revision changes, or after a+mutable descriptor, destination, or credential authority row is deleted. A+different principal or any changed immutable intent conflicts. Historical+replay never means that an unauthenticated caller may reach submission lookup.++### Version-2 and version-3 bindings++| Stored binding | Creation authority | Exact replay | Changed binding | Mutable-authority lookup |+| --- | --- | --- | --- | --- |+| Historical v2 initial submission | Preserved `0010` row only | Preserved exactly | `conflict_operation` | Not required for exact replay |+| New v2 initial submission | Forbidden | Not applicable | `invalid_contract` | Not applicable |+| New v3 initial submission | Trusted principal plus immutable intent | Stored logical submission result | `conflict_operation` | Required only on first application |+| Historical v2 retry | Preserved v2 receipt/child binding only | Preserved exactly | `conflict_operation` | Not required for exact replay |+| New v2 retry | Forbidden | Not applicable | `invalid_contract` | Not applicable |+| New v3 retry | Trusted principal plus immutable retry intent | Stored retry receipt/result | `conflict_operation` | Required only on first application |++Version 3 binds the trusted principal and complete immutable intent. A v3 row+cannot be downgraded to v2, and new code cannot manufacture a v2 request to+bypass the v3 resolver. Existing v2 rows are neither upgraded in place nor+backfilled from current mutable authority.++Admission deliberately creates **no** `execution_operation_receipts` row.+`logical_executions` stores the admission operation, binding version, request+digest, first result, replay result, and result digest. This avoids two replay+authorities for one submission. Retry and authority mutations continue to use+operation receipts where their contracts require them.++### Transaction, lock, and result order++The first application of a v3 submission uses one transaction and a fixed lock+order. Contract shape is validated first. The store then locks the submission+identity and classifies an existing logical submission before consulting+mutable gateway or work authority. A matching row replays; a changed binding+conflicts. Only a new submission proceeds to locked reads of gateway, actor,+campaign, campaign grant, descriptor/catalog, destination, credential,+approval, and budget authority. The derived snapshot, logical execution,+attempt, optional approval consumption, budget reservations, and publication+state commit atomically.++The result precedence is fixed rather than dependent on query order:++1. Invalid input or an attempted untrusted authority claim is+ `invalid_contract`.+2. An existing submission is exact replay or `conflict_operation`.+3. A contradiction or incoherence in required persisted authority is+ `authority_stale`.+4. Current authority is reduced to the existing canonical policy kernel.+ Canonical `REJECTED` and `BLOCKED` verdicts are applied admission decisions,+ not store failures.+5. An otherwise accepted request without budget capacity is+ `capacity_unavailable`.+6. A fully current, policy-accepted, capacity-available first application is+ `applied`.++`invalid_contract`, `conflict_operation`, `authority_stale`, and+`capacity_unavailable` have complete zero durable delta. By contrast, an+applied canonical policy `REJECTED` or `BLOCKED` decision durably creates only+the terminal logical execution, its closing attempt, one zero-count outbox+row, and the outbox operation receipt required by the existing publication+contract. The store derives the terminal outbox identity and publication key+deterministically from the admission operation; the caller supplies neither.+No admission outbox identity is allocated for a canonical accepted decision.+An applied rejection or block consumes no approval and reserves no budget.+PostgreSQL uses row locks in the admitting transaction. SQLite uses its+serialized writer transaction; durability is independently observable from a+second connection. Retry uses the same authority derivation and locking rules+after its historical receipt check and admits only a canonical accepted+decision.++Gateway handling is explicit. `emergency_disabled` is not evaluated and is+applied as `BLOCKED`. `disabled` and `shadow_candidate` still run the canonical+policy evaluator, then are forced to `BLOCKED` with+`AUTHORITY_RESOLUTION_REQUIRED`. `enforced` honors the canonical evaluator.+The C-core role adapter maps `reporter` directly to+`BLOCKED`/`INSUFFICIENT_ROLE`; the unsupported core role `recon` is an+`authority_stale` zero-delta result rather than a new policy role.++### Authority rules and producers++Descriptor authority is the immutable module identity, descriptor contract+version `ares.module-descriptor.v2`, and semantic digest, bound to the current+gateway catalog digest/revision. No numeric per-descriptor revision is implied.++Destination authority requires complete extraction and proof that the complete+canonical destination set is within the campaign's persisted scope. The store+binds the campaign destination-authority revision/digest; it does not add a+live foreign key from a historical attempt to each destination.++Credential authority accepts only current opaque handles owned by the campaign+under the stored credential-authority revision. Raw and ambient credentials+remain forbidden. Historical logical/attempt snapshots contain immutable+identities and digests and have no live foreign keys to mutable descriptor,+destination, or credential authority rows.++An attempt-bound approval is current, exactly bound, and single-use. Admission+locks and consumes it in the same transaction as the attempt. Exact submission+replay does not consume it twice; conflict, stale-authority, capacity failure,+or rollback does not consume it at all.++Every authority producer is an operation-UUID mutation with an exact replay+receipt. Receipts retain binding contract v2; the admission/submission+authority contract is v3. The fifteen generation-11 authority operation codes+are:++1. `gateway_authority_update`+2. `actor_authority_activate`+3. `actor_authority_update`+4. `actor_authority_revoke`+5. `campaign_authority_activate`+6. `campaign_authority_update`+7. `campaign_authority_revoke`+8. `campaign_actor_grant_put`+9. `campaign_actor_grant_revoke`+10. `destination_authority_update`+11. `destination_authority_revoke`+12. `credential_authority_update`+13. `credential_authority_revoke`+14. `approval_authority_grant`+15. `approval_authority_revoke`++`campaign_actor_grant_put` is the sole operation with an optional primary+expected revision: it is absent for create and present for a CAS update. Its+secondary expected revision is always absent. Existing actor/campaign+`*_invalidate` codes remain distinct historical revision-bump operations; they+are not aliases for revoke.++## Admission, retry, closure, and budgets++Malformed, unknown-campaign, unresolved-ownership, or otherwise stale-authority+requests create no lifecycle row. Authentication belongs to the pending C-live+boundary described above. A canonical policy rejection or block is an applied+admission decision: it creates a logical execution, one closing terminal+attempt, no approval or budget row, one zero-count terminal outbox event, and+the corresponding outbox receipt. `preview_ready` received for live mode is+durably blocked. `emergency_disabled` is valid only for initial blocked+metadata. Revision `0011` authority producers change gateway state only through+their receipt-bound CAS contract.++For preview evaluation, canonical `PREVIEW_READY` is integrated as an applied+terminal `BLOCKED` attempt while preserving+`evaluation_mode=preview`, `policy_evaluation_state=evaluated`, and+`policy_verdict=preview_ready` in the immutable snapshot. It is not converted+to a live candidate or dispatchable state.++Submission identity is the lost-response authority for admission. The+`(campaign_id,submission_id)` row stores the admission operation UUID, binding+contract version, complete request digest, fixed first result, exact replay+code, and result binding. Its v2/v3 behavior is fixed by the table above.++Acceptance is one transaction containing the logical and attempt identities,+the exact derived descriptor/policy snapshot, an attempt-bound approval when+required, and reservations in all three configured budgets. Migration `0011`+does not infer current authority or capacity for historical work.++Retry always allocates a new child UUID, preserves a linear same-logical parent+chain, and revalidates every authority and policy fact. A retry-eligible parent+is failed or timed out, has no outputs, is non-closing, read-only, proven+idempotent, after-revalidation, and settled. The one exception is a proven+no-start/no-effect failure: settlement is not applicable, proof is+`no_dispatch`, termination confirmation is false, and all reservations were+released. Retry creation and `close_without_retry` lock the same logical and+parent rows and compete as mutually exclusive CAS operations. Permanent+closure authority and operation identity remain on the logical row after+outbox purge.++Budget arithmetic is literal: reservation adds to `reserved`; release removes+the reservation without consumption; consumption removes the reservation and+adds authoritative actual usage. Concurrency always releases with zero+consumption. Unknown final outcome consumes the full noise/exfiltration+reservation and releases concurrency. Both ledger revision fields record the+post-CAS budget revision, which makes lost-response replay non-duplicating.++## Outputs and publication++Output links are immutable observations of canonical finding, credential,+host, or loot IDs. An attempt may link each target once; multiple attempts may+observe the same target. Links preserve target identity, not a byte snapshot of+later-mutated entity fields. Identity-preserving UPSERT must retain the+canonical row ID and its links. Counts are distinct links for the current+attempt, and output links, budget settlement, terminal state, and outbox insert+commit in one transaction before publication.++The outbox is at-least-once. Consumers deduplicate with `publication_key`.+Claims use a 60-second lease; successful renewals add exactly 60 seconds.+Claim, reclaim, renewal, publication acknowledgement, retryable failure,+nonretryable failure, and poison are revisioned operation-UUID CAS mutations.+Retry delay is `min(2^(attempt-1)*1000,600000)` milliseconds for attempts+1–19. An expired twentieth claim is poisoned by an owner-independent CAS so it+cannot remain claimed forever. A lost publish acknowledgement may redeliver.+Publication failure never changes the committed attempt outcome.++Only succeeded and partial events may carry nonzero counts; partial requires+at least one link, and both event types must exactly match committed links.+Every other event has zero counts. Cross-row equality, approval existence,+immediate-child existence, and logical/attempt closer agreement are enforced+inside the locking transaction API, never by a trigger or cross-row CHECK.++## Startup, deletion, and rollout++A proven-empty ordinary SQLite file is upgraded canonically to Alembic head+and then verified at `0011`. Managed SQLite revisions `0001` through `0010` are+migration-required and are never silently upgraded. Exact recognized+unversioned catalogs remain adoption-required. Explicit raw SQLite URI or+in-memory use retains the bounded unstamped generation-10 fallback and its+nonauthoritative `SCHEMA_VERSION=9` marker. Empty PostgreSQL is always+migration-required and has no runtime fallback.++Lifecycle rows never block physical user deletion: immutable opaque subject+references remain while nullable live-user foreign keys become null. Direct+attempt or logical deletion is unsupported. Whole-campaign deletion locks the+campaign, lifecycle tree, and budgets; rejects active, open, recovery-pending,+or externally claimed work; then removes links, outbox, approvals, ledgers,+attempts leaf-to-root, logical executions, budgets, authority, and existing+campaign-owned rows in one transaction. Campaign deletion itself has an+operation receipt checked before the campaign row. Historical receipts are+retained. Existing callers that do not yet supply an operation/principal use+`delete_campaign(campaign_id)`, which derives a deterministic compatibility+operation UUID and fixed system principal while preserving the legacy literal+boolean result (`true` only for the first applied deletion). Explicit lifecycle+callers use `delete_campaign_lifecycle(...)` and retain the stable+`OperationResult` distinction between applied, replayed, and conflicting+bindings. Both forms replay exactly after the campaign is gone, and a reused+operation UUID with changed campaign or principal conflicts.++Deploy revision `0011` during an externally enforced drain: back up, stop old+processes, run the canonical migration, deploy the `0011`-aware C-core release,+and verify managed startup. The migration accepts only the exact protected+`0010` catalog, preserves every historical v2 binding unchanged, and never+infers current authority for an existing submission or receipt. A failed+upgrade must roll back completely and permit a successful retry. Downgrade is+refused before mutation, and mixed `0010`/`0011` application versions are+unsupported.++Gateway mode remains `disabled`; Strategy, Goal, workers, Redis, subprocesses,+shadow, public authentication/admission, and enforcement remain drained,+inactive, or C-live pending. Before a future activation surface exists, normal+and emergency rollback both retain `disabled`. Once `0011` data exists,+recovery is forward-fix-only; database downgrade is forbidden.++Validation of a candidate containing `0011` must cover the C-core admission+inventory on both backends, fresh and supported upgrades, rollback followed by+successful retry, exact catalog and drift checks, deletion/foreign-key history,+and the already-established P1-A, P1-B, transition, and lifecycle compatibility+families on that candidate ledger. This does not substitute for future C-live+authentication, endpoint, producer-integration, or end-to-end tests.diff --git a/docs/execution-policy.md b/docs/execution-policy.mdindex 3737962..bb16fcf 100644--- a/docs/execution-policy.md+++ b/docs/execution-policy.md@@ -54,13 +54,74 @@ statically policy-evaluable for 62 of 62 first-party IDs, but current ARES is:Positive preview and live-candidate tests use deliberately synthetic trustedfacts. They do not change those counts or claim readiness for a real module.+## C-core authority reduction++Revision `0011` supplies a store-only C-core resolver that can derive the+kernel's admission facts from persisted authority under the admitting+transaction. The public request contributes immutable intent; a trusted stable+principal is established outside C-core. Caller-supplied gateway mode,+revision, role, ownership, descriptor, destination, credential, approval,+policy, or budget claims are never authority. Initial contract-v3 intent also+forbids caller-supplied outbox identity and publication key.++C-live authentication and endpoint integration remain pending. A future live+caller must authenticate before C-core or submission lookup. After that stable+principal is established, an exact stored submission may replay without+re-reading mutable work authority; the same submission with a different+principal or immutable intent conflicts. This preserves lost-response recovery+without treating a stale or unauthenticated caller snapshot as authority.++For a first v3 application, the store classifies the logical submission before+locking and reducing mutable gateway, actor, campaign/grant, descriptor/catalog,+destination, credential, approval, and budget facts. The snapshot and all+admission effects commit atomically. Invalid contracts take precedence over+submission replay/conflict, which precedes stale authority and canonical policy+evaluation; capacity is considered only for an accepted decision.+`invalid_contract`, `conflict_operation`, `authority_stale`, and+`capacity_unavailable` have zero durable delta. Canonical policy `REJECTED` and+`BLOCKED` verdicts are instead applied admission decisions: they persist only+the terminal logical execution, closing attempt, zero-count outbox row, and+outbox operation receipt, with no approval consumption or budget reservation.+The store derives that terminal outbox identity and publication key+deterministically from the admission operation. An accepted initial admission+allocates neither from caller input.++Gateway mode does not bypass canonical reduction. `emergency_disabled` is+`NOT_EVALUATED` and durably `BLOCKED`. `disabled` and `shadow_candidate` are+evaluated, then forced to `BLOCKED` with `AUTHORITY_RESOLUTION_REQUIRED`;+`enforced` honors the evaluator result. The C-core adapter maps `reporter`+directly to `BLOCKED` with `INSUFFICIENT_ROLE`. The kernel has no `recon` role,+so a persisted `recon` principal is `authority_stale` with zero durable delta,+not a caller-selectable role translation.++Canonical `PREVIEW_READY` is a successful policy evaluation, but C-core stores+it as an applied terminal `BLOCKED` attempt. Its immutable snapshot retains+`evaluation_mode=preview` and `policy_verdict=preview_ready`; it never becomes+accepted or dispatchable work.++The logical submission is the sole replay authority for initial admission; no+admission operation receipt is created. Historical v2 replay remains exact,+new v2 creation is forbidden, and a v3 binding cannot be downgraded. Retry uses+the same persisted-authority reduction after its historical replay check.++Destination facts are complete canonical extraction plus campaign scope and+the campaign destination-authority revision/digest. Credential facts accept+only a current opaque campaign-owned handle and its authority revision; raw or+ambient credentials remain invalid. Attempt-bound approval is exact and+single-use, is consumed in the admission transaction, and is not consumed by+replay, conflict, stale authority, capacity failure, or rollback. Historical+attempt observations are immutable snapshots, not live foreign keys to mutable+authority rows.+## Dependencies and cutover boundary-Revision 0010 and an authoritative execution/attempt lifecycle remain-required before acceptance, durable reservation, live shadow correlation, or-result publication can exist. Module, credential, destination, lifecycle,+Revision `0010` remains the protected execution/attempt persistence base, and+revision `0011` adds the C-core authority and admission store contract. No live+snapshot adapter, authenticated endpoint, or execution consumer uses that+contract yet. C-live integration remains required before public acceptance,+live shadow correlation, or result publication can exist. Module, lifecycle,result-authority, cancellation, timeout-settlement, and transport blockers-remain unresolved.+outside the C-core store boundary remain unresolved.Strategy, Goal, CLI, SDK, execution chains, workers, Redis, isolatedsubprocesses, the sandbox, and LLM boundaries must converge on one authoritydiff --git a/docs/module-development.md b/docs/module-development.mdindex 23e87f2..4c11f73 100644--- a/docs/module-development.md+++ b/docs/module-development.md@@ -32,9 +32,9 @@ The sidecar is trusted first-party repository data, not metadata inferred fromclass names, categories, defaults, or plugins. External plugin metadata remainsuntrusted catalog data and receives neither a fallback first-party descriptornor future-gateway eligibility. Adding normal SDK class attributes is therefore-not sufficient to make a plugin eligible for the future gateway. No database-schema changes or Alembic revision `0010` are part of Phase 5C.1; the migration-head remains `0009`.+not sufficient to make a plugin eligible for the future gateway. Phase 5C.1+made no schema change. The later revision `0010` is additive test-only+persistence and does not make a module eligible or change any live ingress.The examples below describe the existing SDK surface. They are not proof thatall current ingresses apply the same policy, that dry-run is universallydiff --git a/docs/module_sdk.md b/docs/module_sdk.mdindex 713bfdd..ba9a9af 100644--- a/docs/module_sdk.md+++ b/docs/module_sdk.md@@ -1,6 +1,6 @@# ARES Module SDK-**Version:** 1.0.0 | **Status:** Active+**Version:** 1.0.0 | **Status:** authoring/preview only in C-LIVE-v1> Complete guide for ARES module authors.> Everything needed to build, test, sign, and publish an ARES module.@@ -8,6 +8,11 @@`ares.sdk` is the preferred public import path for new modules. The older`ares.modules.sdk` path remains available for existing modules.+> C-LIVE-v1 keeps all production descriptors disabled/ineligible. SDK authoring+> and metadata validation remain available, but `ModuleTestHelper.run` and+> `run_full` are preview-only and never invoke module `validate`, `run`, or+> `execute` methods.+---## Quick Start@@ -313,9 +318,11 @@ finding = self.finding(----## Testing Your Module+## Preview-only module validation-Use `ModuleTestHelper` from the SDK:+Use `ModuleTestHelper` to validate metadata, parameters, and the shape of a+dry-run preview. These examples do not execute `validate`, `run`, or `execute`+on the module class:```python# tests/test_my_module.py@@ -340,7 +347,7 @@ class TestMyModule:params={"dc": "10.0.0.1"},dry_run=True,)- assert result.status == "dry_run"+ assert result.status == "preview_only"@pytest.mark.asyncioasync def test_validate_missing_dc(self, helper):@@ -422,3 +429,16 @@ Before submitting a module to the ARES marketplace:- [ ] Unit tests with `ModuleTestHelper`- [ ] `@module_metadata` decorator validates clean (no errors)- [ ] Module signed with Ed25519 key++---++## C-LIVE-v1 SDK status++`ModuleTestHelper` is preview-only. Its `run` and `run_full` surfaces validate+and describe a module but do not invoke module `validate`, `run`, or `execute`+methods. Public engine calls also reject an absent, fabricated, stale,+transferred, or reused coordinator seal.++All production descriptors remain disabled/ineligible in C-LIVE-v1. Tests may+use a private deterministic plan/admission seam, but production cannot import or+configure that seam and the SDK never advertises it as executable capability.diff --git a/docs/modules.md b/docs/modules.mdindex 7700cdc..2264f69 100644--- a/docs/modules.md+++ b/docs/modules.md@@ -43,8 +43,9 @@ The canonical pre-side-effect gateway is deferred to Phase 5C.2. Until thatgateway exists, the sidecar does not add role, approval, capability,destination, credential, retry, or outcome enforcement. External pluginmetadata remains untrusted catalog data under the future contract and receives-no fallback descriptor or gateway eligibility. Phase 5C.1 adds no database-table, migration, or revision `0010`; the Alembic head remains `0009`.+no fallback descriptor or gateway eligibility. Phase 5C.1 itself added no+database table or migration. The later additive revision `0010` stores no+module readiness override and does not connect descriptors to live execution.## Safety Modeldiff --git a/docs/security-model.md b/docs/security-model.mdindex 0d6655e..fec9d04 100644--- a/docs/security-model.md+++ b/docs/security-model.md@@ -10,13 +10,13 @@ ARES is an offensive framework. This document explains how ARES protects the **o| Threat | Mitigation ||--------|------------|-| Community module exfiltrates data | SandboxRunner isolation (subprocess/Docker) + module signatures |+| Community module exfiltrates data | Production descriptors are disabled; the real subprocess stdin entry rejects every payload || Credential data leaked to logs | structlog sensitive field masking, vault encryption || Out-of-scope host attacked | CampaignGuardrail scope check on every operation || Lockout caused by spray | AccountLocked error stops ALL attempts, AdaptiveOpsecEngine || Operator machine compromised | Encrypted checkpoints, no plaintext secrets on disk || API unauthorized access | JWT bearer tokens, bcrypt hashing, rate limiting |-| Replay attack on API | JWT expiry (1 hour default), nonce in sensitive endpoints |+| Replay of live execution | Immutable UUIDv4 idempotency receipts; replay owns zero new dispatch or outbox delta || Module marketplace malware | SHA-256 signed manifests, trusted registry only |### What we do NOT protect against@@ -58,12 +58,16 @@ stored sensitive records.- REST API: HTTPS (TLS 1.2+) — use a reverse proxy (nginx/caddy)- WebSocket dashboard: WSS- Redis cluster connection: `redis+tls://` with cert pinning-- Inter-worker: subprocess stdin/stdout (local only)+- C-LIVE worker IPC: none; subprocess stdin payloads are rejected---## Module Isolation (SandboxRunner)+> The tiers below are a legacy target design and are not an active C-LIVE-v1+> dispatch path. Production descriptors remain ineligible; authenticated worker+> IPC or a serializable capability requires separate approval.+### Isolation tiers| Tier | Mechanism | Used for |@@ -95,7 +99,8 @@ resource.setrlimit(RLIMIT_NOFILE,(256, 256)) # 256 open file descriptors### Authentication-Most API endpoints require a valid JWT bearer token or an API key:+Most non-execution API endpoints require a valid JWT bearer token or may accept+an API key. C-LIVE execution endpoints are bearer-only:```httpAuthorization: Bearer eyJhbGci...@@ -418,3 +423,25 @@ ARES is intended for:**Do not use ARES against systems you do not own or have explicit written permission to test.**Anthropic and the ARES authors take no responsibility for misuse.++---++## C-LIVE-v1 execution authority++Execution is stricter than general API authentication. Only a current bearer+principal may submit live work; API keys and raw credential material are denied.+`operator` maps to lifecycle operator and `team_lead` to lifecycle team lead.+`reporter` and `recon` are rejected before admission, and `admin` is never+synthesized.++The bearer is revalidated before admission and again before queue ownership;+each child and retry repeats that check. Point-in-time revocation is enforced,+while transaction-linearizable revocation is outside this release. A canonical+UUIDv4 Idempotency-Key names one immutable submission. Replays and changed-intent+conflicts have zero new lifecycle/outbox delta, no target-module execution, and+no handler-initiated broadcast.++The only authorized effect capability is a nonserializable, process-local,+single-use seal issued after `RUNNING/APPLIED`. The subprocess stdin boundary+rejects all payloads, production descriptors remain ineligible, and uncertain+post-running work cannot auto-retry.diff --git a/docs/worker_architecture.md b/docs/worker_architecture.mdindex 0144d9c..9cd76ba 100644--- a/docs/worker_architecture.md+++ b/docs/worker_architecture.md@@ -1,10 +1,13 @@# ARES Worker Architecture-**Version:** 1.0.0 | **Status:** Active+**Version:** 1.0.0 | **Status:** legacy design; inactive in C-LIVE-v1## Overview-ARES executes modules in isolated workers — never in the engine main process. This prevents a buggy or malicious module from crashing the engine.+The diagrams through “Adding a Worker Node” preserve the legacy worker target+design only. They are not an active C-LIVE-v1 execution route. C-LIVE-v1 uses a+nonserializable in-process coordinator seal, and the real subprocess stdin+entrypoint rejects every payload.```┌─────────────────────────────────────────┐@@ -104,15 +107,15 @@ else: # unsigned----## Subprocess Worker Protocol+## Legacy subprocess worker protocol (inactive and rejected)-When `IsolationTier.SUBPROCESS` is used, ARES spawns:+The pre-C-LIVE design proposed spawning:```python -m ares.worker._subprocess_worker```-**Communication protocol (JSON over stdin/stdout):**+**Rejected historical protocol (JSON over stdin/stdout):**```Engine → Worker (stdin):@@ -256,3 +259,18 @@ ARES_REDIS_URL=redis://redis:6379 ares worker start --capabilities cloudWorkers auto-register and receive tasks matching their capability set.For Docker deployment, see `docker/docker-compose.prod.yml`; for local Dockerdevelopment, see `docker/docker-compose.dev.yml`.++---++## C-LIVE-v1 worker boundary++The legacy diagrams and launch examples above do not activate a C-LIVE-v1+dispatch path. A coordinator seal is deliberately nonserializable and cannot+cross stdin or a subprocess boundary. Consequently the real+`python -m ares.worker._subprocess_worker` entrypoint rejects every stdin+payload and executes no module code.++The valid-capability/single-use contract exists only in a private in-process+consumer used by the coordinator and its tests. Authenticated IPC, a serialized+seal, broker dispatch, remote-worker activation, and P1-F recovery all require+separate approval.diff --git a/frontend/src/api/client.test.ts b/frontend/src/api/client.test.tsindex f1ae71f..afa23f9 100644--- a/frontend/src/api/client.test.ts+++ b/frontend/src/api/client.test.ts@@ -170,3 +170,101 @@ describe("browser auth API facade", () => {expect((fetchMock.mock.calls[0]?.[1] as RequestInit).credentials).toBe("same-origin");});});++describe("C-LIVE-v1 idempotency", () => {+ beforeEach(() => {+ vi.restoreAllMocks();+ vi.resetModules();+ installBrowserPrimitives();+ });++ it("generates one Idempotency-Key for an effectful submission", async () => {+ const generated = "123e4567-e89b-42d3-a456-426614174000";+ vi.spyOn(globalThis.crypto, "randomUUID").mockReturnValue(generated);+ const fetchMock = vi.fn<(+ input: RequestInfo | URL,+ init?: RequestInit+ ) => Promise<Response>>(async () => new Response(JSON.stringify({ status: "ok" }), {+ status: 200,+ headers: { "Content-Type": "application/json" }+ }));+ vi.stubGlobal("fetch", fetchMock);+ const client = await import("./client");+ const result = await client.api.runModule(+ "recon.test",+ client.buildModuleRunPayload("campaign-a", {}, false)+ );+ const headers = new Headers(fetchMock.mock.calls[0]?.[1]?.headers);+ expect(headers.get("Idempotency-Key")).toBe(generated);+ expect(result.idempotency_key).toBe(generated);+ expect(fetchMock).toHaveBeenCalledTimes(1);+ });++ it("reuses the same Idempotency-Key for a transport retry", async () => {+ const generated = "123e4567-e89b-42d3-a456-426614174001";+ const uuid = vi.spyOn(globalThis.crypto, "randomUUID").mockReturnValue(generated);+ const fetchMock = vi.fn<(+ input: RequestInfo | URL,+ init?: RequestInit+ ) => Promise<Response>>()+ .mockRejectedValueOnce(new TypeError("network lost"))+ .mockResolvedValueOnce(new Response(JSON.stringify({ status: "ok" }), {+ status: 200,+ headers: { "Content-Type": "application/json" }+ }));+ vi.stubGlobal("fetch", fetchMock);+ const client = await import("./client");+ const payload = client.buildModuleRunPayload("campaign-a", { target: "host-a" }, false);+ await expect(client.api.runModule("recon.test", payload)).rejects.toMatchObject({+ idempotencyKey: generated+ });+ await client.api.runModule("recon.test", payload);+ const keys = fetchMock.mock.calls.map((call) => new Headers(call[1]?.headers).get("Idempotency-Key"));+ expect(keys).toEqual([generated, generated]);+ expect(uuid).toHaveBeenCalledTimes(1);+ });++ it("generates a different key for a distinct logical submission", async () => {+ const uuid = vi.spyOn(globalThis.crypto, "randomUUID")+ .mockReturnValueOnce("123e4567-e89b-42d3-a456-426614174002")+ .mockReturnValueOnce("123e4567-e89b-42d3-a456-426614174003");+ const fetchMock = vi.fn<(+ input: RequestInfo | URL,+ init?: RequestInit+ ) => Promise<Response>>(async () => new Response(JSON.stringify({ status: "ok" }), {+ status: 200,+ headers: { "Content-Type": "application/json" }+ }));+ vi.stubGlobal("fetch", fetchMock);+ const client = await import("./client");+ const payload = client.buildModuleRunPayload("campaign-a", {}, false);+ await client.api.runModule("recon.test", payload);+ await client.api.runModule("recon.test", payload);+ const keys = fetchMock.mock.calls.map((call) => new Headers(call[1]?.headers).get("Idempotency-Key"));+ expect(keys[0]).not.toBe(keys[1]);+ expect(uuid).toHaveBeenCalledTimes(2);+ });++ it("preserves and displays a caller-supplied Idempotency-Key", async () => {+ const supplied = "123e4567-e89b-42d3-a456-426614174004";+ const uuid = vi.spyOn(globalThis.crypto, "randomUUID");+ const fetchMock = vi.fn<(+ input: RequestInfo | URL,+ init?: RequestInit+ ) => Promise<Response>>(async () => new Response(JSON.stringify({ status: "ok" }), {+ status: 200,+ headers: { "Content-Type": "application/json" }+ }));+ vi.stubGlobal("fetch", fetchMock);+ const client = await import("./client");+ const result = await client.api.engageStrategy(+ { campaign_id: "campaign-a", goal: "domain_admin" },+ { idempotencyKey: supplied }+ );+ const headers = new Headers(fetchMock.mock.calls[0]?.[1]?.headers);+ expect(headers.get("Idempotency-Key")).toBe(supplied);+ expect(result.idempotency_key).toBe(supplied);+ expect(JSON.stringify(result)).toContain(supplied);+ expect(uuid).not.toHaveBeenCalled();+ });+});diff --git a/frontend/src/api/endpoints.ts b/frontend/src/api/endpoints.tsindex 506d213..8ee1c2f 100644--- a/frontend/src/api/endpoints.ts+++ b/frontend/src/api/endpoints.ts@@ -6,6 +6,8 @@ import type {CampaignGraph,ExecutionChain,Finding,+ LiveExecutionResponse,+ LiveSubmissionOptions,ModuleMeta,MonthlyFindingStats,ReportItem,@@ -24,7 +26,91 @@ import {} from "./http";import { beginIdentityTransition, installSessionIfCurrent } from "./session";+const UUID_V4 = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;+const pendingLiveSubmissions = new Map<string, string>();++function canonicalJson(value: unknown): string {+ if (Array.isArray(value)) {+ return `[${value.map(canonicalJson).join(",")}]`;+ }+ if (typeof value === "object" && value !== null) {+ return `{${Object.entries(value)+ .sort(([left], [right]) => left < right ? -1 : left > right ? 1 : 0)+ .map(([key, item]) => `${JSON.stringify(key)}:${canonicalJson(item)}`)+ .join(",")}}`;+ }+ return JSON.stringify(value) ?? "null";+}++function liveSubmissionFingerprint(path: string, body: Record<string, unknown>): string {+ return `${path}\u0000${canonicalJson(body)}`;+}++function canonicalIdempotencyKey(value: string): string {+ if (!UUID_V4.test(value)) {+ throw new ApiError(422, "Idempotency-Key must be a canonical lowercase UUIDv4");+ }+ return value;+}++function createIdempotencyKey(): string {+ const value = globalThis.crypto?.randomUUID?.();+ if (typeof value !== "string") {+ throw new ApiError(503, "Secure UUID generation unavailable");+ }+ return canonicalIdempotencyKey(value);+}++function attachIdempotencyKey(error: unknown, key: string): never {+ if ((typeof error === "object" && error !== null) || typeof error === "function") {+ Object.defineProperty(error, "idempotencyKey", {+ configurable: false,+ enumerable: true,+ value: key,+ writable: false+ });+ }+ throw error;+}++async function liveExecutionRequest(+ path: string,+ body: Record<string, unknown>,+ options: LiveSubmissionOptions = {}+): Promise<LiveExecutionResponse> {+ const fingerprint = liveSubmissionFingerprint(path, body);+ if (options.startNewSubmission) {+ pendingLiveSubmissions.delete(fingerprint);+ }+ const supplied = options.idempotencyKey === undefined+ ? undefined+ : canonicalIdempotencyKey(options.idempotencyKey);+ const key = supplied ?? pendingLiveSubmissions.get(fingerprint) ?? createIdempotencyKey();+ pendingLiveSubmissions.set(fingerprint, key);+ try {+ const result = await apiRequest<Record<string, unknown>>(path, {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ "Idempotency-Key": key+ },+ body: JSON.stringify(body)+ });+ if (pendingLiveSubmissions.get(fingerprint) === key) {+ pendingLiveSubmissions.delete(fingerprint);+ }+ return { ...result, idempotency_key: key };+ } catch (error) {+ attachIdempotencyKey(error, key);+ }+}++function clearPendingLiveSubmissions(): void {+ pendingLiveSubmissions.clear();+}+export async function login(username: string, password: string): Promise<TokenResponse> {+ clearPendingLiveSubmissions();const loginSession = beginIdentityTransition();const token = await withRefreshCookieLock(async () => {await bootstrapBrowserCsrf();@@ -50,12 +136,14 @@ export async function login(username: string, password: string): Promise<TokenRe}export async function logout(): Promise<void> {+ clearPendingLiveSubmissions();await withRefreshCookieLock(async () => {await browserMutationRequest<null>("/auth/logout");});}export async function logoutAll(): Promise<void> {+ clearPendingLiveSubmissions();await withRefreshCookieLock(async () => {await browserMutationRequest<null>("/auth/logout-all", {}, { authenticated: true });});@@ -97,24 +185,40 @@ export const api = {cvss: (id: string) => apiRequest<Record<string, unknown>>(`/campaigns/${encodeURIComponent(id)}/cvss`),restoreVault: (id: string) =>apiRequest<Record<string, unknown>>(`/campaigns/${encodeURIComponent(id)}/restore-vault`, { method: "POST" }),- runCampaign: (id: string, body: Record<string, unknown>) =>- apiRequest<Record<string, unknown>>(`/campaigns/${encodeURIComponent(id)}/run`, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify(body)- }),+ runCampaign: (+ id: string,+ body: Record<string, unknown>,+ options: LiveSubmissionOptions = {}+ ) => {+ const path = `/campaigns/${encodeURIComponent(id)}/run`;+ return body.dry_run === true+ ? apiRequest<Record<string, unknown>>(path, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(body)+ })+ : liveExecutionRequest(path, body, options);+ },diffCampaign: (id: string, otherId: string) =>apiRequest<Record<string, unknown>>(`/campaigns/${encodeURIComponent(id)}/diff/${encodeURIComponent(otherId)}`),modules: () => apiRequest<ModuleMeta[]>("/modules"),executionChains: () => apiRequest<ExecutionChain[]>("/modules/execution-chains"),- runModule: (moduleId: string, payload: ReturnType<typeof buildModuleRunPayload>) =>- apiRequest<Record<string, unknown>>(`/modules/${encodeURIComponent(moduleId)}/run`, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify(payload)- }),+ runModule: (+ moduleId: string,+ payload: ReturnType<typeof buildModuleRunPayload>,+ options: LiveSubmissionOptions = {}+ ) => {+ const path = `/modules/${encodeURIComponent(moduleId)}/run`;+ return payload.dry_run+ ? apiRequest<Record<string, unknown>>(path, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(payload)+ })+ : liveExecutionRequest(path, payload, options);+ },generateReport: (campaignId: string, format: string) =>apiRequest<Record<string, string>>(`/reports/${encodeURIComponent(campaignId)}?fmt=${encodeURIComponent(format)}`,@@ -153,12 +257,10 @@ export const api = {body: JSON.stringify({ global_params: globalParams })}),activeStrategy: () => apiRequest<Record<string, unknown>>("/strategy/active"),- engageStrategy: (body: Record<string, unknown>) =>- apiRequest<Record<string, unknown>>("/strategy/engage", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify(body)- }),+ engageStrategy: (+ body: Record<string, unknown>,+ options: LiveSubmissionOptions = {}+ ) => liveExecutionRequest("/strategy/engage", body, options),changePassword: (body: { current_password: string; new_password: string }) =>apiRequest<Record<string, string>>("/auth/change-password", {method: "POST",diff --git a/frontend/src/api/types.ts b/frontend/src/api/types.tsindex fe644dd..1402e7f 100644--- a/frontend/src/api/types.ts+++ b/frontend/src/api/types.ts@@ -19,6 +19,16 @@ export interface WebSocketTicketResponse {expires_in: 30;}+export interface LiveSubmissionOptions {+ idempotencyKey?: string;+ startNewSubmission?: boolean;+}++export interface LiveExecutionResponse {+ idempotency_key: string;+ [key: string]: unknown;+}+export interface Campaign {id: string;name: string;diff --git a/frontend/src/features/dashboard/DashboardPages.tsx b/frontend/src/features/dashboard/DashboardPages.tsxindex 8d0ef95..8594c74 100644--- a/frontend/src/features/dashboard/DashboardPages.tsx+++ b/frontend/src/features/dashboard/DashboardPages.tsx@@ -3261,10 +3261,27 @@ function opsecBadge(level?: string): string {function serializeError(value: unknown): unknown {if (value instanceof ApiError) {- return { name: value.name, status: value.status, detail: value.detail };+ const idempotencyKey = "idempotencyKey" in value+ && typeof value.idempotencyKey === "string"+ ? value.idempotencyKey+ : undefined;+ return {+ name: value.name,+ status: value.status,+ detail: value.detail,+ ...(idempotencyKey ? { idempotency_key: idempotencyKey } : {})+ };}if (value instanceof Error) {- return { name: value.name, message: value.message };+ const idempotencyKey = "idempotencyKey" in value+ && typeof value.idempotencyKey === "string"+ ? value.idempotencyKey+ : undefined;+ return {+ name: value.name,+ message: value.message,+ ...(idempotencyKey ? { idempotency_key: idempotencyKey } : {})+ };}return value;}diff --git a/migrations/versions/0010_execution_lifecycle.py b/migrations/versions/0010_execution_lifecycle.pynew file mode 100644index 0000000..69d1842--- /dev/null+++ b/migrations/versions/0010_execution_lifecycle.py@@ -0,0 +1,547 @@+"""Add the authoritative execution-lifecycle persistence catalog.++Revision ID: 0010+Revises: 0009+"""++from __future__ import annotations++import re+from importlib import import_module+from typing import Any++import sqlalchemy as sa+from alembic import op++revision = "0010"+down_revision = "0009"+branch_labels = None+depends_on = None++_PREVIOUS = import_module("migrations.versions.0009_refresh_token_families")+classify_unversioned_catalog = _PREVIOUS.classify_unversioned_catalog+_require_sqlite_alembic_version_relation = _PREVIOUS._require_sqlite_alembic_version_relation+_pg_validate_alembic_version_relation = _PREVIOUS._pg_validate_alembic_version_relation++_LIFECYCLE_COLUMNS: dict[str, tuple[str, ...]] = {+ "logical_executions": (+ "id",+ "submission_id",+ "campaign_id",+ "actor_subject_ref",+ "actor_user_id",+ "module_id",+ "ingress_code",+ "admission_operation_id",+ "submission_binding_contract_version",+ "submission_request_binding_digest",+ "submission_result_code",+ "submission_exact_replay_code",+ "submission_result_binding_digest",+ "highest_attempt_ordinal",+ "revision",+ "created_at",+ "closure_operation_id",+ "closure_authority_subject_ref",+ "closure_authority_user_id",+ "closure_authority_revision",+ "closing_attempt_id",+ "closed_at",+ ),+ "execution_attempts": (+ "id",+ "logical_execution_id",+ "campaign_id",+ "ordinal",+ "parent_attempt_id",+ "revision",+ "state",+ "closes_logical",+ "actor_subject_ref",+ "actor_user_id",+ "actor_authority_revision",+ "campaign_authority_revision",+ "destination_authority_revision",+ "credential_authority_revision",+ "request_contract_version",+ "evaluation_mode",+ "request_structure_valid",+ "canonicalization_complete",+ "unknown_fields_absent",+ "alternate_transport_absent",+ "bounded_shape_valid",+ "request_shape_units",+ "descriptor_contract_version",+ "descriptor_semantic_digest",+ "catalog_digest",+ "trusted_first_party_binding",+ "descriptor_binding_current",+ "descriptor_complete",+ "static_policy_evaluable",+ "minimum_role",+ "noise_class",+ "approval_policy",+ "capability_mask_version",+ "required_capability_mask",+ "descriptor_blocker_mask_version",+ "descriptor_blocker_mask",+ "preview_ready",+ "lifecycle_ready",+ "result_authority_ready",+ "transport_ready",+ "future_gateway_eligible",+ "authority_snapshots_complete",+ "authority_revisions_current",+ "actor_authenticated",+ "actor_active",+ "actor_role",+ "campaign_active",+ "actor_campaign_authorized",+ "approval_present",+ "approval_current",+ "approval_exactly_bound",+ "granted_capability_mask",+ "destination_extraction_complete",+ "destinations_in_scope",+ "credential_authority_resolved",+ "credential_authority_current",+ "opaque_handles_only",+ "permitted_handle_kinds_only",+ "raw_credentials_absent",+ "ambient_credentials_absent",+ "budget_authority_resolved",+ "budget_authority_current",+ "budget_capacity_available",+ "gateway_mode_snapshot",+ "gateway_decision_code",+ "policy_evaluation_state",+ "policy_contract_version",+ "policy_verdict",+ "policy_reason_mask_version",+ "policy_reason_mask",+ "external_effect_class",+ "idempotency_class",+ "retry_policy",+ "retry_disposition",+ "cancellation_ownership",+ "compensation_class",+ "timeout_origin",+ "timeout_limit_ms",+ "timeout_settlement",+ "outcome_code",+ "error_action_code",+ "settlement_state",+ "settlement_proof_code",+ "termination_confirmed",+ "dispatch_owner_ref",+ "lease_generation",+ "dispatch_lease_duration_ms",+ "lease_expires_at",+ "lease_invalidated_at",+ "queue_operation_id",+ "dispatch_operation_id",+ "start_operation_id",+ "cancellation_request_operation_id",+ "cancellation_request_revision",+ "cancellation_ack_operation_id",+ "timeout_operation_id",+ "settlement_pending_operation_id",+ "terminal_operation_id",+ "resolver_subject_ref",+ "resolver_user_id",+ "resolver_authority_revision",+ "bounded_recovery_proof_code",+ "created_at",+ "accepted_at",+ "queued_at",+ "dispatching_at",+ "started_at",+ "cancellation_requested_at",+ "cancellation_acknowledged_at",+ "timeout_observed_at",+ "settlement_pending_at",+ "recovery_deadline_at",+ "retry_child_bound_at",+ "finished_at",+ "settled_at",+ ),+ "execution_actor_authority_revisions": (+ "user_id",+ "revision",+ "latest_operation_id",+ "latest_operation_base_revision",+ "latest_operation_code",+ "updated_at",+ ),+ "campaign_execution_authority_revisions": (+ "campaign_id",+ "revision",+ "latest_operation_id",+ "latest_operation_base_revision",+ "latest_operation_code",+ "updated_at",+ ),+ "campaign_execution_budgets": (+ "id",+ "campaign_id",+ "budget_kind",+ "capacity_units",+ "reserved_units",+ "consumed_units",+ "revision",+ "latest_operation_id",+ "latest_operation_base_revision",+ "latest_operation_code",+ "created_at",+ "updated_at",+ ),+ "execution_attempt_approvals": (+ "id",+ "attempt_id",+ "campaign_id",+ "approval_ref",+ "approver_subject_ref",+ "approver_user_id",+ "authority_revision",+ "binding_digest",+ "bound_at",+ ),+ "campaign_execution_budget_ledger": (+ "id",+ "attempt_id",+ "campaign_id",+ "budget_id",+ "budget_kind",+ "reservation_units",+ "consumed_units",+ "disposition",+ "budget_revision_reserved",+ "budget_revision_settled",+ "reserved_at",+ "settled_at",+ ),+ "execution_output_links": (+ "id",+ "attempt_id",+ "campaign_id",+ "finding_id",+ "credential_id",+ "host_id",+ "loot_id",+ "created_at",+ ),+ "execution_publication_outbox": (+ "id",+ "publication_key",+ "attempt_id",+ "campaign_id",+ "event_code",+ "is_attempt_terminal",+ "finding_count",+ "credential_count",+ "host_count",+ "artifact_count",+ "publication_state",+ "delivery_attempt_count",+ "available_at",+ "claim_owner_ref",+ "lease_generation",+ "claimed_at",+ "lease_expires_at",+ "published_at",+ "poisoned_at",+ "failure_code",+ "claim_revision",+ "latest_operation_id",+ "latest_operation_code",+ "latest_operation_base_revision",+ "created_at",+ ),+ "execution_operation_receipts": (+ "operation_id",+ "operation_code",+ "campaign_id",+ "primary_target_id",+ "secondary_target_id",+ "principal_kind",+ "principal_subject_ref",+ "principal_user_id",+ "principal_authority_revision_present",+ "principal_authority_revision",+ "binding_contract_version",+ "request_binding_digest",+ "expected_revision_present",+ "expected_revision",+ "secondary_expected_revision_present",+ "secondary_expected_revision",+ "owner_ref",+ "lease_generation",+ "result_code",+ "exact_replay_code",+ "result_binding_digest",+ "result_identity",+ "result_revision_present",+ "result_revision",+ "secondary_result_identity",+ "secondary_result_revision_present",+ "secondary_result_revision",+ "created_at",+ ),+ "execution_gateway_state": (+ "singleton_id",+ "mode",+ "catalog_digest",+ "activation_revision",+ "activation_at",+ "revision",+ "updated_at",+ ),+}+++def _ddl_object_names(+ postgres_ddl: tuple[str, ...], lifecycle_tables: tuple[str, ...]+) -> tuple[frozenset[str], frozenset[str]]:+ constraints: set[str] = set()+ indexes: set[str] = set()+ for statement in postgres_ddl:+ table_match = re.match(r"CREATE TABLE ([a-z0-9_]+)", statement)+ alter_match = re.match(r"ALTER TABLE ([a-z0-9_]+)", statement)+ relation = (+ table_match.group(1)+ if table_match is not None+ else alter_match.group(1)+ if alter_match is not None+ else None+ )+ if relation in lifecycle_tables:+ constraints.update(re.findall(r"\bCONSTRAINT ([a-z0-9_]+)\b", statement))+ match = re.match(+ r"CREATE (?:UNIQUE )?INDEX ([a-z0-9_]+) ON ([a-z0-9_]+)",+ statement,+ )+ if match is not None and match.group(2) in lifecycle_tables:+ indexes.add(match.group(1))+ indexes.update(name for name in constraints if name.startswith(("pk_", "uq_")))+ return frozenset(constraints), frozenset(indexes)+++_BASE_CANDIDATE_INDEXES = frozenset(+ {+ "uq_findings_campaign_id_id",+ "uq_credentials_campaign_id_id",+ "uq_hosts_campaign_id_id",+ "uq_loot_campaign_id_id",+ }+)++_LIFECYCLE_CONTRACT: (+ tuple[+ tuple[str, ...],+ tuple[str, ...],+ tuple[str, ...],+ Any,+ frozenset[str],+ frozenset[str],+ ]+ | None+) = None+++def _lifecycle_contract() -> tuple[+ tuple[str, ...],+ tuple[str, ...],+ tuple[str, ...],+ Any,+ frozenset[str],+ frozenset[str],+]:+ global _LIFECYCLE_CONTRACT+ if _LIFECYCLE_CONTRACT is None:+ lifecycle = import_module("ares.db.execution_lifecycle")+ lifecycle_tables = tuple(lifecycle.LIFECYCLE_TABLES)+ postgres_ddl = tuple(lifecycle.POSTGRES_LIFECYCLE_DDL)+ constraint_names, index_names = _ddl_object_names(postgres_ddl, lifecycle_tables)+ _LIFECYCLE_CONTRACT = (+ lifecycle_tables,+ tuple(lifecycle.SQLITE_LIFECYCLE_DDL),+ postgres_ddl,+ lifecycle.validate_sqlite_lifecycle_catalog_rows,+ constraint_names,+ index_names,+ )+ return _LIFECYCLE_CONTRACT+++def _fail() -> None:+ raise RuntimeError("revision-0010 preflight failed")+++def _dialect() -> str:+ dialect = op.get_bind().dialect.name+ if dialect not in {"sqlite", "postgresql"}:+ _fail()+ return dialect+++def _column_names(inspector: Any, table: str) -> tuple[str, ...]:+ return tuple(str(item["name"]) for item in inspector.get_columns(table))+++def _preflight() -> str:+ bind = op.get_bind()+ dialect = _dialect()+ inspector = sa.inspect(bind)+ existing = set(inspector.get_table_names())+ lifecycle_tables, _, _, _, _, _ = _lifecycle_contract()+ if any(table in existing for table in lifecycle_tables):+ _fail()+ if not {"users", "campaigns", "findings", "credentials", "hosts", "loot"}.issubset(existing):+ _fail()+ return dialect+++def verify_managed_catalog(connection: Any) -> None:+ """Fail closed unless the connection exposes the exact lifecycle columns."""+ (+ lifecycle_tables,+ _,+ _,+ validate_sqlite_lifecycle_catalog_rows,+ lifecycle_constraint_names,+ lifecycle_index_names,+ ) = _lifecycle_contract()+ inspector = sa.inspect(connection)+ tables = set(inspector.get_table_names())+ if not set(lifecycle_tables).issubset(tables):+ _fail()+ for table, expected in _LIFECYCLE_COLUMNS.items():+ if _column_names(inspector, table) != expected:+ _fail()+ gateway = connection.execute(+ sa.text(+ "SELECT mode,revision,catalog_digest,activation_revision,activation_at "+ "FROM execution_gateway_state WHERE singleton_id=1"+ )+ ).fetchone()+ if gateway is None or tuple(gateway) != ("disabled", 0, None, None, None):+ _fail()+ dialect = connection.dialect.name+ if dialect == "sqlite":+ catalog_rows = connection.execute(+ sa.text(+ "SELECT type,name,sql FROM sqlite_schema "+ "WHERE sql IS NOT NULL AND ("+ "name IN :expected_names OR tbl_name IN :lifecycle_tables) "+ "ORDER BY type,name"+ ).bindparams(+ sa.bindparam(+ "expected_names",+ value=tuple(+ lifecycle_index_names | _BASE_CANDIDATE_INDEXES | set(lifecycle_tables)+ ),+ expanding=True,+ ),+ sa.bindparam("lifecycle_tables", value=lifecycle_tables, expanding=True),+ )+ ).fetchall()+ validate_sqlite_lifecycle_catalog_rows(catalog_rows)+ if dialect == "postgresql":+ constraint_rows = connection.execute(+ sa.text(+ "SELECT con.conname FROM pg_constraint con "+ "JOIN pg_class rel ON rel.oid=con.conrelid "+ "JOIN pg_namespace n ON n.oid=rel.relnamespace "+ "WHERE n.nspname=current_schema() "+ "AND rel.relname = ANY(:names) ORDER BY con.conname"+ ),+ {"names": list(lifecycle_tables)},+ ).fetchall()+ if frozenset(str(row[0]) for row in constraint_rows) != lifecycle_constraint_names:+ _fail()+ index_rows = connection.execute(+ sa.text(+ "SELECT indexname FROM pg_indexes WHERE schemaname=current_schema() "+ "AND tablename = ANY(:names) ORDER BY indexname"+ ),+ {"names": list(lifecycle_tables)},+ ).fetchall()+ if frozenset(str(row[0]) for row in index_rows) != lifecycle_index_names:+ _fail()+ base_index_rows = connection.execute(+ sa.text(+ "SELECT indexname FROM pg_indexes WHERE schemaname=current_schema() "+ "AND indexname = ANY(:names) ORDER BY indexname"+ ),+ {"names": list(_BASE_CANDIDATE_INDEXES)},+ ).fetchall()+ if frozenset(str(row[0]) for row in base_index_rows) != _BASE_CANDIDATE_INDEXES:+ _fail()+ relation_rows = connection.execute(+ sa.text(+ "SELECT c.relkind::text,c.relpersistence::text,c.relispartition,"+ "c.relrowsecurity,c.relforcerowsecurity FROM pg_class c "+ "JOIN pg_namespace n ON n.oid=c.relnamespace "+ "WHERE n.nspname=current_schema() AND c.relname=ANY(:names)"+ ),+ {"names": list(lifecycle_tables)},+ ).fetchall()+ if len(relation_rows) != len(lifecycle_tables) or any(+ tuple(row) != ("r", "p", False, False, False) for row in relation_rows+ ):+ _fail()+ trigger_rows = connection.execute(+ sa.text(+ "SELECT c.relname,t.tgname FROM pg_trigger t "+ "JOIN pg_class c ON c.oid=t.tgrelid "+ "WHERE NOT t.tgisinternal AND c.relname = ANY(:names) "+ "ORDER BY c.relname,t.tgname"+ ),+ {"names": list(lifecycle_tables)},+ ).fetchall()+ if tuple(tuple(row) for row in trigger_rows) != (+ ("execution_operation_receipts", "trg_eor_immutable"),+ ):+ _fail()+ policy_exists = connection.execute(+ sa.text(+ "SELECT EXISTS (SELECT 1 FROM pg_policy p "+ "JOIN pg_class c ON c.oid=p.polrelid "+ "WHERE c.relname = ANY(:names))"+ ),+ {"names": list(lifecycle_tables)},+ ).scalar_one()+ if policy_exists:+ _fail()+ lifecycle = import_module("ares.db.execution_lifecycle")+ if not lifecycle._POSTGRES_CATALOG_FINGERPRINT_V1:+ _fail()+ facts_sql = lifecycle._POSTGRES_CATALOG_FACTS_SQL.replace(+ "__NAMES__", "CAST(:lifecycle_names AS text[])"+ ).replace("__BASE_NAMES__", "CAST(:base_names AS text[])")+ fact_rows = connection.execute(+ sa.text(facts_sql),+ {+ "lifecycle_names": list(lifecycle_tables),+ "base_names": list(_BASE_CANDIDATE_INDEXES),+ },+ ).fetchall()+ if (+ lifecycle.postgresql_catalog_fingerprint(tuple(str(row[0]) for row in fact_rows))+ != lifecycle._POSTGRES_CATALOG_FINGERPRINT_V1+ ):+ _fail()+++def upgrade() -> None:+ dialect = _preflight()+ _, sqlite_ddl, postgres_ddl, _, _, _ = _lifecycle_contract()+ statements = sqlite_ddl if dialect == "sqlite" else postgres_ddl+ bind = op.get_bind()+ for statement in statements:+ bind.execute(sa.text(statement))+ verify_managed_catalog(bind)+++def downgrade() -> None:+ raise RuntimeError("revision-0010 downgrade is not supported")diff --git a/migrations/versions/0011_execution_admission_authority.py b/migrations/versions/0011_execution_admission_authority.pynew file mode 100644index 0000000..de1f8b8--- /dev/null+++ b/migrations/versions/0011_execution_admission_authority.py@@ -0,0 +1,644 @@+# ruff: noqa: E501, S608+"""Add independently persisted execution admission authority.++Revision ID: 0011+Revises: 0010+"""++from __future__ import annotations++import hashlib+import ipaddress+import json+import re+from importlib import import_module+from typing import Any++import sqlalchemy as sa+from alembic import op++revision = "0011"+down_revision = "0010"+branch_labels = None+depends_on = None++_PREVIOUS = import_module("migrations.versions.0010_execution_lifecycle")+classify_unversioned_catalog = _PREVIOUS.classify_unversioned_catalog+_require_sqlite_alembic_version_relation = _PREVIOUS._require_sqlite_alembic_version_relation+_pg_validate_alembic_version_relation = _PREVIOUS._pg_validate_alembic_version_relation+++def _fail() -> None:+ raise RuntimeError("revision-0011 preflight failed")+++def _dialect() -> str:+ dialect = op.get_bind().dialect.name+ if dialect not in {"sqlite", "postgresql"}:+ _fail()+ return dialect+++def _contract() -> tuple[tuple[str, ...], tuple[str, ...], tuple[str, ...]]:+ lifecycle = import_module("ares.db.execution_lifecycle")+ return (+ tuple(lifecycle.V11_AUTHORITY_TABLES),+ tuple(lifecycle.SQLITE_ADMISSION_AUTHORITY_V11_DDL),+ tuple(lifecycle.POSTGRES_ADMISSION_AUTHORITY_V11_DDL),+ )+++def _preflight() -> str:+ bind = op.get_bind()+ dialect = _dialect()+ # Revision 0011 accepts only the protected, exact revision-0010 catalog.+ # This check precedes owner resolution and every catalog/data mutation.+ _PREVIOUS.verify_managed_catalog(bind)+ tables, _, _ = _contract()+ existing = set(sa.inspect(bind).get_table_names())+ if not set(_PREVIOUS._LIFECYCLE_COLUMNS).issubset(existing):+ _fail()+ if any(table in existing for table in tables):+ _fail()+ return dialect+++def _deterministic_uuid(domain: bytes, *values: object) -> str:+ encoded = bytearray(domain + b"\x00")+ for value in values:+ item = str(value).encode("utf-8")+ encoded.extend(len(item).to_bytes(4, "big"))+ encoded.extend(item)+ digest = hashlib.sha256(encoded).hexdigest()+ return (+ digest[:8]+ + "-"+ + digest[8:12]+ + "-4"+ + digest[13:16]+ + "-8"+ + digest[17:20]+ + "-"+ + digest[20:32]+ )+++def _grant_binding_digest(campaign_id: object, actor_user_id: object) -> str:+ lifecycle = import_module("ares.db.execution_lifecycle")+ return lifecycle.canonical_operation_binding_digest(+ "campaign-actor-grant",+ (+ ("campaign_id", str(campaign_id)),+ ("actor_user_id", str(actor_user_id)),+ ("authority_state", "active"),+ ),+ )+++def _canonical_destination_authority(+ scope_json: object, targets_json: object+) -> tuple[int, str, str]:+ try:+ scope = json.loads(str(scope_json))+ targets = json.loads(str(targets_json))+ except (TypeError, ValueError, json.JSONDecodeError):+ _fail()+ if type(scope) is not list or type(targets) is not list:+ _fail()+ normalized: set[str] = set()+ for entry in scope:+ if type(entry) is not dict or set(entry) - {"cidr", "description"}:+ _fail()+ cidr = entry.get("cidr")+ if type(cidr) is not str or not cidr or "\x00" in cidr:+ _fail()+ try:+ canonical = str(ipaddress.ip_network(cidr, strict=False))+ except ValueError:+ _fail()+ normalized.add("scope:" + canonical)+ for entry in targets:+ if type(entry) is not str or not entry or "\x00" in entry:+ _fail()+ value = entry.strip()+ if not value:+ _fail()+ try:+ if "/" in value:+ value = str(ipaddress.ip_network(value, strict=False))+ else:+ value = str(ipaddress.ip_address(value))+ except ValueError:+ value = value.lower().rstrip(".")+ if not value or re.fullmatch(r"[a-z0-9][a-z0-9._-]{0,2047}", value) is None:+ _fail()+ normalized.add("target:" + value)+ values = tuple(sorted(normalized))+ lifecycle = import_module("ares.db.execution_lifecycle")+ return lifecycle.ExecutionLifecycleStore._destination_authority_facts(values)+++def _credential_binding_digest(row: Any) -> str:+ lifecycle = import_module("ares.db.execution_lifecycle")+ return lifecycle.ExecutionLifecycleStore._credential_authority_binding(row)+++def _actor_binding_digest(row: Any) -> str:+ lifecycle = import_module("ares.db.execution_lifecycle")+ return lifecycle.canonical_operation_binding_digest(+ "actor-authority",+ (+ ("user_id", str(row[0])),+ ("username", str(row[1])),+ ("role", str(row[2])),+ ("is_active", bool(row[3])),+ ("auth_epoch", int(row[4])),+ ),+ )+++def _campaign_binding_digest(row: Any, destination_binding: str) -> str:+ lifecycle = import_module("ares.db.execution_lifecycle")+ return lifecycle.canonical_operation_binding_digest(+ "campaign-authority",+ (+ ("campaign_id", str(row[0])),+ ("operator", str(row[1])),+ ("status", str(row[2])),+ ("noise_profile", str(row[3])),+ ("destination_binding_digest", destination_binding),+ ),+ )+++def _backfill_plan(bind: Any) -> tuple[tuple[tuple[Any, ...], ...], ...]:+ """Resolve and validate every compatibility authority before mutation."""+ campaign_rows = bind.execute(+ sa.text(+ "SELECT c.id,c.operator,c.scope_json,c.targets_json,u.id "+ "FROM campaigns c LEFT JOIN users u ON u.username=c.operator "+ "ORDER BY c.id,u.id"+ )+ ).fetchall()+ grouped: dict[str, list[tuple[Any, ...]]] = {}+ for row in campaign_rows:+ grouped.setdefault(str(row[0]), []).append(tuple(row))+ campaigns: list[tuple[Any, ...]] = []+ for campaign_id in sorted(grouped):+ matches = grouped[campaign_id]+ if len(matches) != 1 or matches[0][4] is None:+ _fail()+ row = matches[0]+ count, destination_digest, destination_binding = _canonical_destination_authority(+ row[2], row[3]+ )+ actor_user_id = str(row[4])+ campaigns.append(+ (+ str(row[0]),+ actor_user_id,+ _grant_binding_digest(row[0], actor_user_id),+ _deterministic_uuid(b"ares.migration-0011.grant", row[0], actor_user_id),+ count,+ destination_digest,+ destination_binding,+ _deterministic_uuid(b"ares.migration-0011.destination", row[0]),+ _campaign_binding_digest(+ bind.execute(+ sa.text(+ "SELECT id,operator,status,noise_profile FROM campaigns WHERE id=:id"+ ),+ {"id": row[0]},+ ).one(),+ destination_binding,+ ),+ )+ )+ actor_rows = bind.execute(+ sa.text(+ "SELECT a.user_id,u.username,u.role,u.is_active,u.auth_epoch "+ "FROM execution_actor_authority_revisions a JOIN users u ON u.id=a.user_id "+ "ORDER BY a.user_id"+ )+ ).fetchall()+ actors = tuple((str(row[0]), _actor_binding_digest(row)) for row in actor_rows)+ credential_rows = bind.execute(+ sa.text(+ "SELECT id,campaign_id,host_id,username,cred_type,domain,source_module "+ "FROM credentials ORDER BY id"+ )+ ).fetchall()+ credentials = tuple((str(row[0]), _credential_binding_digest(row)) for row in credential_rows)+ return tuple(campaigns), credentials, actors+++def _backfill(bind: Any, plan: tuple[tuple[tuple[Any, ...], ...], ...]) -> None:+ campaigns, credentials, actors = plan+ for (+ campaign_id,+ actor_user_id,+ grant_binding,+ grant_operation,+ count,+ destination_digest,+ destination_binding,+ destination_operation,+ campaign_binding,+ ) in campaigns:+ bind.execute(+ sa.text(+ "INSERT INTO campaign_execution_actor_grants("+ "campaign_id,actor_user_id,authority_state,revision,binding_digest,"+ "latest_operation_id,latest_operation_base_revision,latest_operation_code) "+ "VALUES(:campaign,:actor,'active',0,:binding,:operation,0,'put')"+ ),+ {+ "campaign": campaign_id,+ "actor": actor_user_id,+ "binding": grant_binding,+ "operation": grant_operation,+ },+ )+ bind.execute(+ sa.text(+ "UPDATE campaign_execution_authority_revisions "+ "SET authority_binding_digest=:binding WHERE campaign_id=:campaign"+ ),+ {"binding": campaign_binding, "campaign": campaign_id},+ )+ bind.execute(+ sa.text(+ "INSERT INTO campaign_execution_destination_authorities("+ "campaign_id,authority_state,revision,normalization_version,destination_count,"+ "destination_set_digest,binding_digest,latest_operation_id,"+ "latest_operation_base_revision,latest_operation_code) "+ "VALUES(:campaign,'active',0,1,:count,:destination,:binding,:operation,0,'update')"+ ),+ {+ "campaign": campaign_id,+ "count": count,+ "destination": destination_digest,+ "binding": destination_binding,+ "operation": destination_operation,+ },+ )+ for credential_id, binding_digest in credentials:+ bind.execute(+ sa.text(+ "UPDATE credentials SET execution_authority_binding_digest=:digest "+ "WHERE id=:credential"+ ),+ {"digest": binding_digest, "credential": credential_id},+ )+ for actor_user_id, binding_digest in actors:+ bind.execute(+ sa.text(+ "UPDATE execution_actor_authority_revisions "+ "SET authority_binding_digest=:binding WHERE user_id=:actor"+ ),+ {"binding": binding_digest, "actor": actor_user_id},+ )+ # Campaign ownership is resolved to one persisted user before mutation and+ # materialized as an explicit compatibility grant. Role alone never grants+ # access. No approval or attempt observation can be inferred historically;+ # historical logical/attempt rows retain their v2 defaults.+++_RECEIPT_COLUMNS = (+ "operation_id,operation_code,campaign_id,primary_target_id,secondary_target_id,"+ "principal_kind,principal_subject_ref,principal_user_id,"+ "principal_authority_revision_present,principal_authority_revision,"+ "binding_contract_version,request_binding_digest,expected_revision_present,"+ "expected_revision,secondary_expected_revision_present,secondary_expected_revision,"+ "owner_ref,lease_generation,result_code,exact_replay_code,result_binding_digest,"+ "result_identity,result_revision_present,result_revision,secondary_result_identity,"+ "secondary_result_revision_present,secondary_result_revision,created_at"+)++_V11_ADDED_COLUMNS: dict[str, tuple[str, ...]] = {+ "logical_executions": (+ "immutable_work_digest",+ "immutable_intent_digest",+ "canonical_principal_user_id",+ "admission_authority_contract_version",+ ),+ "execution_attempts": (+ "approval_authority_binding_digest",+ "credential_authority_binding_digest",+ "destination_authority_binding_digest",+ "campaign_actor_grant_revision",+ "gateway_activation_revision",+ "gateway_revision",+ "immutable_work_digest",+ "immutable_intent_digest",+ "trusted_principal_user_id",+ "trusted_principal_subject_ref",+ "authority_contract_version",+ ),+ "execution_actor_authority_revisions": (+ "authority_latest_operation_code",+ "authority_latest_operation_base_revision",+ "authority_latest_operation_id",+ "authority_binding_digest",+ "authority_revision",+ "authority_state",+ ),+ "campaign_execution_authority_revisions": (+ "authority_latest_operation_code",+ "authority_latest_operation_base_revision",+ "authority_latest_operation_id",+ "authority_binding_digest",+ "authority_revision",+ "authority_state",+ ),+ "credentials": (+ "execution_authority_latest_operation_code",+ "execution_authority_latest_operation_base_revision",+ "execution_authority_latest_operation_id",+ "execution_authority_binding_digest",+ "execution_authority_revision",+ "execution_authority_state",+ ),+}+++def _count(bind: Any, sql: str, values: dict[str, Any] | None = None) -> int:+ value = bind.execute(sa.text(sql), values or {}).scalar_one()+ return int(value)+++def _assert_downgrade_safe(+ bind: Any,+ plan: tuple[tuple[tuple[Any, ...], ...], ...],+) -> None:+ """Reject all v11 mutations and v3 admission data before changing catalog bytes."""+ lifecycle = import_module("ares.db.execution_lifecycle")+ additive_receipts = bind.execute(+ sa.text(+ "SELECT count(*) FROM execution_operation_receipts WHERE operation_code IN :codes"+ ).bindparams(sa.bindparam("codes", expanding=True)),+ {"codes": tuple(lifecycle.V11_ADDITIVE_OPERATION_CODES)},+ ).scalar_one()+ if int(additive_receipts):+ _fail()+ if _count(+ bind,+ "SELECT count(*) FROM logical_executions WHERE "+ "admission_authority_contract_version<>2 OR canonical_principal_user_id IS NOT NULL "+ "OR immutable_intent_digest IS NOT NULL OR immutable_work_digest IS NOT NULL",+ ):+ _fail()+ if _count(+ bind,+ "SELECT count(*) FROM execution_attempts WHERE authority_contract_version<>2 "+ "OR trusted_principal_subject_ref IS NOT NULL OR trusted_principal_user_id IS NOT NULL "+ "OR immutable_intent_digest IS NOT NULL OR immutable_work_digest IS NOT NULL "+ "OR gateway_revision IS NOT NULL "+ "OR gateway_activation_revision IS NOT NULL OR campaign_actor_grant_revision IS NOT NULL "+ "OR destination_authority_binding_digest IS NOT NULL "+ "OR credential_authority_binding_digest IS NOT NULL "+ "OR approval_authority_binding_digest IS NOT NULL",+ ):+ _fail()+ for table in (+ "execution_actor_authority_revisions",+ "campaign_execution_authority_revisions",+ ):+ if _count(+ bind,+ f"SELECT count(*) FROM {table} WHERE authority_state<>'active' "+ "OR authority_revision<>0 OR authority_latest_operation_id IS NOT NULL "+ "OR authority_latest_operation_base_revision IS NOT NULL "+ "OR authority_latest_operation_code IS NOT NULL",+ ):+ _fail()+ for table in (+ "execution_approval_authorities",+ "execution_attempt_destination_observations",+ "execution_attempt_credential_observations",+ ):+ if _count(bind, f"SELECT count(*) FROM {table}"):+ _fail()++ campaigns, credentials, actors = plan+ actual_grants = bind.execute(+ sa.text(+ "SELECT campaign_id,actor_user_id,authority_state,revision,binding_digest,"+ "latest_operation_id,latest_operation_base_revision,latest_operation_code "+ "FROM campaign_execution_actor_grants ORDER BY campaign_id,actor_user_id"+ )+ ).fetchall()+ expected_grants = tuple(+ (row[0], row[1], "active", 0, row[2], row[3], 0, "put") for row in campaigns+ )+ if tuple(tuple(row) for row in actual_grants) != expected_grants:+ _fail()+ actual_destinations = bind.execute(+ sa.text(+ "SELECT campaign_id,authority_state,revision,normalization_version,"+ "destination_count,destination_set_digest,binding_digest,latest_operation_id,"+ "latest_operation_base_revision,latest_operation_code "+ "FROM campaign_execution_destination_authorities ORDER BY campaign_id"+ )+ ).fetchall()+ expected_destinations = tuple(+ (row[0], "active", 0, 1, row[4], row[5], row[6], row[7], 0, "update") for row in campaigns+ )+ if tuple(tuple(row) for row in actual_destinations) != expected_destinations:+ _fail()+ actual_campaign_bindings = bind.execute(+ sa.text(+ "SELECT campaign_id,authority_binding_digest "+ "FROM campaign_execution_authority_revisions ORDER BY campaign_id"+ )+ ).fetchall()+ expected_campaign_bindings = tuple((row[0], row[8]) for row in campaigns)+ if tuple(tuple(row) for row in actual_campaign_bindings) != expected_campaign_bindings:+ _fail()+ actual_credentials = bind.execute(+ sa.text(+ "SELECT id,execution_authority_state,execution_authority_revision,"+ "execution_authority_binding_digest,execution_authority_latest_operation_id,"+ "execution_authority_latest_operation_base_revision,"+ "execution_authority_latest_operation_code FROM credentials ORDER BY id"+ )+ ).fetchall()+ expected_credentials = tuple(+ (credential_id, "active", 0, digest, None, None, None)+ for credential_id, digest in credentials+ )+ if tuple(tuple(row) for row in actual_credentials) != expected_credentials:+ _fail()+ actual_actor_bindings = bind.execute(+ sa.text(+ "SELECT user_id,authority_binding_digest "+ "FROM execution_actor_authority_revisions ORDER BY user_id"+ )+ ).fetchall()+ if tuple(tuple(row) for row in actual_actor_bindings) != actors:+ _fail()+++def _v10_receipt_create_statement(dialect: str) -> str:+ lifecycle = import_module("ares.db.execution_lifecycle")+ source = (+ lifecycle.POSTGRES_LIFECYCLE_DDL+ if dialect == "postgresql"+ else lifecycle.SQLITE_LIFECYCLE_DDL+ )+ return next(+ statement+ for statement in source+ if statement.startswith("CREATE TABLE execution_operation_receipts")+ )+++def _restore_v10_receipts(bind: Any, dialect: str) -> None:+ statement = _v10_receipt_create_statement(dialect)+ if dialect == "postgresql":+ operation = re.search(+ r"CONSTRAINT ck_eor_operation_code CHECK \((.*?)\),\n", statement, re.S+ )+ shape = re.search(+ r"CONSTRAINT ck_eor_operation_shape CHECK \((.*?)\),\n CONSTRAINT ck_eor_outbox_owner_shape",+ statement,+ re.S,+ )+ if operation is None or shape is None:+ _fail()+ for sql in (+ "ALTER TABLE execution_operation_receipts DROP CONSTRAINT ck_eor_operation_code",+ "ALTER TABLE execution_operation_receipts ADD CONSTRAINT ck_eor_operation_code CHECK ("+ + operation.group(1)+ + ")",+ "ALTER TABLE execution_operation_receipts DROP CONSTRAINT ck_eor_operation_shape",+ "ALTER TABLE execution_operation_receipts ADD CONSTRAINT ck_eor_operation_shape CHECK ("+ + shape.group(1)+ + ")",+ ):+ bind.execute(sa.text(sql))+ return+ for sql in (+ "DROP TRIGGER trg_eor_immutable_update",+ "DROP TRIGGER trg_eor_immutable_delete",+ "ALTER TABLE execution_operation_receipts RENAME TO execution_operation_receipts_v11",+ statement,+ "INSERT INTO execution_operation_receipts("+ + _RECEIPT_COLUMNS+ + ") SELECT "+ + _RECEIPT_COLUMNS+ + " FROM execution_operation_receipts_v11",+ "DROP TABLE execution_operation_receipts_v11",+ "CREATE TRIGGER trg_eor_immutable_update BEFORE UPDATE ON execution_operation_receipts "+ "BEGIN SELECT RAISE(ABORT,'immutable execution operation receipt'); END",+ "CREATE TRIGGER trg_eor_immutable_delete BEFORE DELETE ON execution_operation_receipts "+ "BEGIN SELECT RAISE(ABORT,'immutable execution operation receipt'); END",+ "CREATE INDEX ix_eor_campaign_created ON execution_operation_receipts(campaign_id,created_at,operation_id)",+ "CREATE INDEX ix_eor_primary_target ON execution_operation_receipts(primary_target_id,operation_code,created_at)",+ "CREATE INDEX ix_eor_principal_created ON execution_operation_receipts(principal_kind,principal_subject_ref,created_at,operation_id)",+ ):+ bind.execute(sa.text(sql))+++def _apply_downgrade(bind: Any, dialect: str) -> None:+ bind.execute(sa.text("DROP INDEX ix_credentials_execution_authority"))+ for table in (+ "execution_attempt_credential_observations",+ "execution_attempt_destination_observations",+ "execution_approval_authorities",+ "campaign_execution_destination_authorities",+ "campaign_execution_actor_grants",+ ):+ bind.execute(sa.text(f"DROP TABLE {table}"))+ _restore_v10_receipts(bind, dialect)+ for table, columns in _V11_ADDED_COLUMNS.items():+ for column in columns:+ bind.execute(sa.text(f"ALTER TABLE {table} DROP COLUMN {column}"))+++def verify_managed_catalog(connection: Any) -> None:+ lifecycle = import_module("ares.db.execution_lifecycle")+ inspector = sa.inspect(connection)+ tables = set(inspector.get_table_names())+ if not set(lifecycle.LIFECYCLE_TABLES).issubset(tables):+ _fail()+ if not set(lifecycle.V11_AUTHORITY_TABLES).issubset(tables):+ _fail()+ dialect = connection.dialect.name+ if dialect == "sqlite":+ rows = connection.execute(+ sa.text(+ "SELECT m.name,p.name FROM sqlite_schema AS m "+ "JOIN pragma_table_info(m.name) AS p "+ "WHERE m.type='table' AND m.name IN :names ORDER BY m.name,p.cid"+ ).bindparams(+ sa.bindparam(+ "names",+ value=tuple(lifecycle._V11_EXISTING_COLUMNS)+ + tuple(lifecycle.V11_AUTHORITY_TABLES),+ expanding=True,+ )+ )+ ).fetchall()+ lifecycle._validate_v11_columns(rows)+ receipt = connection.execute(+ sa.text(+ "SELECT sql FROM sqlite_schema WHERE type='table' "+ "AND name='execution_operation_receipts'"+ )+ ).fetchone()+ if receipt is None or not all(+ code in str(receipt[0]) for code in lifecycle.V11_OPERATION_CODES+ ):+ _fail()+ elif dialect == "postgresql":+ names = list(tuple(lifecycle._V11_EXISTING_COLUMNS) + lifecycle.V11_AUTHORITY_TABLES)+ rows = connection.execute(+ sa.text(+ "SELECT c.relname,a.attname FROM pg_class c "+ "JOIN pg_namespace n ON n.oid=c.relnamespace "+ "JOIN pg_attribute a ON a.attrelid=c.oid AND a.attnum>0 AND NOT a.attisdropped "+ "WHERE n.nspname=current_schema() AND c.relname=ANY(:names) "+ "ORDER BY c.relname,a.attnum"+ ),+ {"names": names},+ ).fetchall()+ lifecycle._validate_v11_columns(rows)+ definitions = connection.execute(+ sa.text(+ "SELECT con.conname,pg_get_constraintdef(con.oid,true) FROM pg_constraint con "+ "JOIN pg_class c ON c.oid=con.conrelid JOIN pg_namespace n ON n.oid=c.relnamespace "+ "WHERE n.nspname=current_schema() AND c.relname='execution_operation_receipts' "+ "AND con.conname IN ('ck_eor_operation_code','ck_eor_operation_shape')"+ )+ ).fetchall()+ operation = next(+ (str(row[1]) for row in definitions if str(row[0]) == "ck_eor_operation_code"),+ "",+ )+ if len(definitions) != 2 or not all(+ code in operation for code in lifecycle.V11_ADDITIVE_OPERATION_CODES+ ):+ _fail()+ else:+ _fail()+++def upgrade() -> None:+ dialect = _preflight()+ bind = op.get_bind()+ plan = _backfill_plan(bind)+ _, sqlite_ddl, postgres_ddl = _contract()+ for statement in sqlite_ddl if dialect == "sqlite" else postgres_ddl:+ bind.execute(sa.text(statement))+ _backfill(bind, plan)+ verify_managed_catalog(bind)+++def downgrade() -> None:+ dialect = _dialect()+ bind = op.get_bind()+ plan = _backfill_plan(bind)+ _assert_downgrade_safe(bind, plan)+ _apply_downgrade(bind, dialect)+ _PREVIOUS.verify_managed_catalog(bind)diff --git a/scripts/validation_lab.py b/scripts/validation_lab.pyindex ded8cba..d31873e 100644--- a/scripts/validation_lab.py+++ b/scripts/validation_lab.py@@ -11,6 +11,7 @@ import osimport reimport sysimport time+import uuidfrom dataclasses import dataclass, fieldfrom typing import Anyfrom urllib import error, parse, request@@ -119,6 +120,21 @@ def _is_canonical_csrf(value: object) -> bool:return len(decoded) == 32 and hmac.compare_digest(canonical, value)+def _canonical_idempotency_key(value: object) -> str | None:+ """Accept only a non-secret canonical lowercase UUIDv4 header value."""+ if value in {None, ""}:+ return None+ if not isinstance(value, str):+ raise ValidationLabError("idempotency-key-invalid")+ try:+ parsed = uuid.UUID(value)+ except (AttributeError, ValueError):+ raise ValidationLabError("idempotency-key-invalid") from None+ if parsed.version != 4 or str(parsed) != value:+ raise ValidationLabError("idempotency-key-invalid")+ return value++class ApiClient:"""Cookie-aware client whose representations never contain credentials."""@@ -164,6 +180,7 @@ class ApiClient:authenticated: bool = True,browser_headers: bool = False,empty_body: bool = False,+ idempotency_key: str | None = None,) -> ApiResult:expected = expect or {200}url = f"{self.base_url}{path}"@@ -183,6 +200,9 @@ class ApiClient:if self.access_token is None:raise ValidationLabError("access-authority-missing")headers["Authorization"] = f"Bearer {self.access_token}"+ canonical_key = _canonical_idempotency_key(idempotency_key)+ if canonical_key is not None:+ headers["Idempotency-Key"] = canonical_keyoutgoing = request.Request( # noqa: S310 - URL origin was strictly validatedurl, data=data, headers=headers, method=method@@ -417,6 +437,7 @@ def run_lab(args: argparse.Namespace) -> int:"global_params": {},"dry_run": True,},+ idempotency_key=args.idempotency_key,).bodyif (not isinstance(result, dict)@@ -431,6 +452,7 @@ def run_lab(args: argparse.Namespace) -> int:"/modules/ad.kerberoast/run",body={"campaign_id": campaign_id, "params": {}, "dry_run": True},expect={200},+ idempotency_key=args.idempotency_key,).body_validate_blocked_module_dry_run(result)@@ -541,6 +563,11 @@ def build_parser() -> argparse.ArgumentParser:default=os.getenv("ARES_LAB_BROWSER_ORIGIN") or os.getenv("ARES_BROWSER_ORIGIN"),)parser.add_argument("--username", default=os.getenv("ARES_LAB_USERNAME", "admin"))+ parser.add_argument(+ "--idempotency-key",+ default=os.getenv("ARES_LAB_IDEMPOTENCY_KEY"),+ help="Optional non-secret canonical UUIDv4 for preview requests.",+ )parser.add_argument("--allow-remote",action="store_true",diff --git a/tests/integration/test_api_post.py b/tests/integration/test_api_post.pyindex b0f6871..28dd89d 100644--- a/tests/integration/test_api_post.py+++ b/tests/integration/test_api_post.py@@ -24,6 +24,7 @@ Run: pytest tests/integration/test_api_post.py -v --timeout=30from __future__ import annotationsimport os+from unittest.mock import AsyncMock# ── env must be set BEFORE any ares import ────────────────────────────────────_SECRET = "integration-post-test-secret-32ab"@@ -302,7 +303,15 @@ class TestCampaignPostEndpoints:assert r.status_code == 200assert "x-total-count" in r.headers- def test_run_plan_dry_run(self, c, token, campaign_id):+ def test_run_plan_dry_run(self, c, token, campaign_id, monkeypatch):+ run_module = AsyncMock(+ side_effect=AssertionError("dry-run must not execute module code")+ )+ run_plan = AsyncMock(+ side_effect=AssertionError("dry-run must not enter the live plan engine")+ )+ monkeypatch.setattr(c.app.state.engine, "run_module", run_module)+ monkeypatch.setattr(c.app.state.engine, "run_plan", run_plan)r = c.post(f"/campaigns/{campaign_id}/run",json={@@ -320,7 +329,11 @@ class TestCampaignPostEndpoints:},headers=_auth(token),)- assert r.status_code in (200, 202), f"run plan: {r.text}"+ assert r.status_code == 200, f"run plan: {r.text}"+ assert r.json()["status"] == "dry_run_ok"+ assert "x-ares-attempt-id" not in r.headers+ run_module.assert_not_awaited()+ run_plan.assert_not_awaited()def test_campaign_not_found_returns_404(self, c, token):r = c.get("/campaigns/nonexistent-xyz-id", headers=_auth(token))diff --git a/tests/integration/test_postgres_auth_token_lifecycle.py b/tests/integration/test_postgres_auth_token_lifecycle.pyindex 13850bc..d635988 100644--- a/tests/integration/test_postgres_auth_token_lifecycle.py+++ b/tests/integration/test_postgres_auth_token_lifecycle.py@@ -16,6 +16,7 @@ from unittest.mock import Mockfrom urllib.parse import quotefrom uuid import uuid4+import httpximport pytestfrom ares.db import postgres as postgres_module@@ -257,6 +258,107 @@ def _require_fixed(condition: bool, message: str) -> None:pytest.fail(message, pytrace=False)+class _RejectingCLiveRuntime:+ """Prove an authentication rejection never reaches lifecycle admission."""++ def __init__(self) -> None:+ self.bind_calls = 0++ def bind(self, actor: object) -> None:+ del actor+ self.bind_calls += 1+ raise AssertionError("authentication rejection reached C-live admission")+++class _PostgresCLiveStoreBindingProbe:+ def __init__(self) -> None:+ self.store_ids: list[int] = []++ def _bind_admission_store(self, store: object) -> None:+ store_id = id(store)+ if self.store_ids and self.store_ids[-1] != store_id:+ raise PermissionError("cross-store binding")+ self.store_ids.append(store_id)+++class _PostgresCLiveEffectEngine(_PostgresCLiveStoreBindingProbe):+ """Deterministic module-effect boundary backed by the real PostgreSQL store."""++ def __init__(self) -> None:+ super().__init__()+ self._registrations: set[str] = set()+ self.effects: list[str] = []+ self.finalizations: list[str] = []++ def _register_admitted_dispatch_context(self, context: Any) -> None:+ self._bind_admission_store_id(context._store_id)+ self._registrations.add(context._dispatch_nonce)++ def _bind_admission_store_id(self, store_id: int) -> None:+ if not self.store_ids:+ self.store_ids.append(store_id)+ elif self.store_ids[-1] != store_id:+ raise PermissionError("cross-store dispatch context")++ def _consume_registered_dispatch_context(self, context: Any) -> bool:+ if context._dispatch_nonce not in self._registrations:+ return False+ self._registrations.remove(context._dispatch_nonce)+ return True++ async def run_module(+ self,+ module_id: str,+ campaign: Any,+ params: dict[str, Any],+ *,+ skip_validation: bool,+ timeout_seconds: int,+ actor_role: str,+ dispatch_context: Any,+ ) -> Any:+ del params, skip_validation, timeout_seconds+ from ares.core.engine import EngineModuleResult, ModuleStatus+ from ares.core.execution_admission import (+ consume_dispatch_context,+ mark_effect_started,+ )++ context = consume_dispatch_context(+ dispatch_context,+ consumer=self,+ campaign_id=campaign.id,+ module_id=module_id,+ )+ assert actor_role == "operator"+ mark_effect_started(context)+ self.effects.append(module_id)+ return EngineModuleResult(+ module_id=module_id,+ status=ModuleStatus.DONE,+ raw_output={"effect_count": len(self.effects)},+ duration_ms=1.0,+ )++ async def _finalize_committed_module_result(+ self,+ campaign: Any,+ module_id: str,+ result: Any,+ dispatch_context: Any,+ ) -> Any:+ from ares.core.execution_admission import consume_terminal_commit_context++ consume_terminal_commit_context(+ dispatch_context,+ consumer=self,+ campaign_id=campaign.id,+ module_id=module_id,+ )+ self.finalizations.append(module_id)+ return result++class _TransactionExitBarrier:def __init__(self,@@ -1701,3 +1803,348 @@ async def test_create_and_logout_follow_lock_order(later_token = await database.create_refresh_token(logout_first_user)assert later_tokenassert await _active_refresh_count(database, logout_first_user) == 1+++ "case",+ ("revoked-bearer", "deleted-user", "inactive-user", "demoted-role"),+ ids=("revoked-bearer", "deleted-user", "inactive-user", "demoted-role"),+)+async def test_postgres_c_live_authentication_precedes_submission_lookup(+ case: str,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ from ares.api.server import app+ from ares.core.config import get_settings+ from ares.core.security import create_access_token, decode_access_token++ async with _postgres_harness() as harness:+ database = harness.database+ user_id = await _insert_user(database)+ async with database._pool.acquire() as connection:+ subject = await connection.fetchval(+ "SELECT username FROM users WHERE id=$1",+ user_id,+ )+ async with connection.transaction():+ family_id, _refresh_token = await database._insert_initial_family_token(+ connection,+ user_id=user_id,+ auth_epoch=1,+ )++ settings = get_settings()+ token = create_access_token(+ {"sub": subject, "sid": family_id, "ver": 1},+ settings.secret_key_value,+ settings.ares_jwt_algorithm,+ )+ claims = decode_access_token(+ token,+ settings.secret_key_value,+ settings.ares_jwt_algorithm,+ )+ assert claims is not None+ jti = claims["jti"]++ async with database._pool.acquire() as connection:+ if case == "revoked-bearer":+ await connection.execute(+ "INSERT INTO revoked_access_tokens(jti,user_id,expires_at) "+ "VALUES($1,$2,now() + interval '1 hour')",+ jti,+ user_id,+ )+ elif case == "deleted-user":+ await connection.execute("DELETE FROM users WHERE id=$1", user_id)+ elif case == "inactive-user":+ await connection.execute(+ "UPDATE users SET is_active=0 WHERE id=$1",+ user_id,+ )+ else:+ await connection.execute(+ "UPDATE users SET role='reporter' WHERE id=$1",+ user_id,+ )++ campaign_reads = 0+ original_get_campaign = database.get_campaign++ async def tracked_get_campaign(campaign_id: str) -> dict[str, Any] | None:+ nonlocal campaign_reads+ campaign_reads += 1+ return await original_get_campaign(campaign_id)++ monkeypatch.setattr(database, "get_campaign", tracked_get_campaign)+ runtime = _RejectingCLiveRuntime()+ state = app.state+ missing = object()+ previous = {+ name: getattr(state, name, missing)+ for name in ("db", "engine", "c_live_runtime")+ }+ state.db = database+ state.engine = object()+ state.c_live_runtime = runtime+ try:+ transport = httpx.ASGITransport(app=app)+ async with httpx.AsyncClient(+ transport=transport,+ base_url="http://localhost",+ ) as client:+ response = await client.post(+ "/modules/opsec.coverage_predictor/run",+ json={+ "campaign_id": "10000000-0000-4000-8000-000000000001",+ "params": {"noise_profile": "stealth"},+ "dry_run": False,+ },+ headers={+ "Authorization": f"Bearer {token}",+ "Idempotency-Key": "10000000-0000-4000-8000-000000000002",+ },+ )+ finally:+ for name, value in previous.items():+ if value is missing:+ delattr(state, name)+ else:+ setattr(state, name, value)++ expected_status = 403 if case == "demoted-role" else 401+ assert response.status_code == expected_status+ assert response.json()["detail"] == (+ "live_execution_role_denied"+ if case == "demoted-role"+ else "Not authenticated"+ )+ assert campaign_reads == 0+ assert runtime.bind_calls == 0+ async with database._pool.acquire() as connection:+ assert await connection.fetchval("SELECT count(*) FROM logical_executions") == 0+++async def test_postgres_c_live_trusted_store_factory_is_coordinator_only(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ from ares.api.rbac import AuthenticatedUser+ from ares.api.server import _CLiveRuntime+ from ares.db.websocket_tickets import BearerTicketSource++ async with _postgres_harness() as harness:+ database = harness.database+ user_id = await _insert_user(database)+ async with database._pool.acquire() as connection:+ subject = await connection.fetchval(+ "SELECT username FROM users WHERE id=$1",+ user_id,+ )+ async with connection.transaction():+ family_id, _refresh_token = await database._insert_initial_family_token(+ connection,+ user_id=user_id,+ auth_epoch=1,+ )++ original_factory = database.execution_lifecycle_store+ stores: list[object] = []++ def tracked_factory() -> object:+ store = original_factory()+ stores.append(store)+ return store++ monkeypatch.setattr(database, "execution_lifecycle_store", tracked_factory)+ engine = _PostgresCLiveStoreBindingProbe()+ runtime = _CLiveRuntime(database, engine)+ actor = AuthenticatedUser(+ username=subject,+ role="operator",+ websocket_ticket_source=BearerTicketSource(+ user_id=user_id,+ subject=subject,+ jti="10000000-0000-4000-8000-000000000003",+ expires_at=datetime.now(timezone.utc) + timedelta(minutes=5),+ family_id=family_id,+ auth_epoch=1,+ ),+ )++ first_principal, first = runtime.bind(actor)+ second_principal, second = runtime.bind(actor)++ assert len(stores) == 1+ assert runtime.store is stores[0]+ assert first is not second+ assert first_principal is not second_principal+ assert engine.store_ids == [id(stores[0]), id(stores[0])]++[email protected]("route", ("module", "plan", "strategy"), ids=("module", "plan", "strategy"))+async def test_postgres_c_live_effectful_dispatch_and_replay(+ route: str,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ from ares.core.campaign import Campaign+ from ares.core.execution_admission import (+ DispatchDispositionV1,+ DispatchRequestV1,+ ExecutionAdmissionCoordinatorV1,+ RevalidatedPrincipalV1,+ canonical_intent_digest,+ )+ from ares.db.execution_lifecycle import (+ BudgetConfiguration,+ CampaignActorGrantMutation,+ FixedResult,+ GatewayAuthorityMutation,+ TrustedPrincipal,+ )+ from tests.integration.test_postgres_execution_lifecycle import (+ _postgres_p1c_authority_store,+ _postgres_p1c_eligible_descriptor,+ )+ from tests.unit.test_execution_lifecycle_persistence import _uuid++ async with _postgres_harness() as harness:+ database = harness.database+ _postgres_p1c_eligible_descriptor(monkeypatch)+ store, administrator, actor_id, campaign_id, _credential_id = (+ await _postgres_p1c_authority_store(database)+ )+ actor = TrustedPrincipal(actor_id, actor_id)+ assert (+ await store.put_campaign_actor_grant(+ administrator,+ CampaignActorGrantMutation(+ _uuid(13_010),+ campaign_id,+ actor_id,+ None,+ ),+ )+ ).result is FixedResult.APPLIED+ assert (+ await store.update_gateway_authority(+ administrator,+ GatewayAuthorityMutation(_uuid(13_011), 0, "enforced"),+ )+ ).result is FixedResult.APPLIED+ assert (+ await store.configure_campaign_budgets(+ BudgetConfiguration(+ campaign_id,+ _uuid(13_012),+ 20,+ _uuid(13_013),+ 20,+ _uuid(13_014),+ 4,+ _uuid(13_015),+ "actor",+ actor.subject_ref,+ actor.user_id,+ 0,+ )+ )+ ).result is FixedResult.APPLIED++ engine = _PostgresCLiveEffectEngine()++ async def revalidate(+ candidate: TrustedPrincipal,+ requested_campaign_id: str,+ module_id: str,+ ) -> RevalidatedPrincipalV1 | None:+ if (+ candidate != actor+ or requested_campaign_id != campaign_id+ or module_id != "opsec.coverage_predictor"+ ):+ return None+ return RevalidatedPrincipalV1(actor, 0, "operator")++ coordinator = ExecutionAdmissionCoordinatorV1(store, engine, revalidate)+ campaign = Campaign(+ id=campaign_id,+ name="PostgreSQL C-live",+ operator="legacy-username-is-not-authority",+ targets=["host.example"],+ )+ coordinates = {+ "module": ((0, 0, 0, 0),),+ "plan": ((0, 0, 0, 0), (1, 0, 0, 1)),+ "strategy": ((0, 0, 0, 0), (1, 1, 1, 0)),+ }[route]+ ingress_code = {+ "module": "api_module",+ "plan": "api_campaign_plan",+ "strategy": "strategy",+ }[route]+ whole_intent_digest = canonical_intent_digest(+ {+ "campaign_id": campaign_id,+ "route": route,+ "children": coordinates,+ }+ )+ requests = tuple(+ DispatchRequestV1(+ campaign_id=campaign_id,+ module_id="opsec.coverage_predictor",+ ingress_code=ingress_code,+ idempotency_key=_uuid(13_016),+ raw_parameters={"noise_profile": "stealth"},+ whole_intent_digest=whole_intent_digest,+ occurrence=occurrence,+ stage_ordinal=stage_ordinal,+ decision_ordinal=decision_ordinal,+ module_ordinal=module_ordinal,+ )+ for occurrence, stage_ordinal, decision_ordinal, module_ordinal in coordinates+ )++ applied = tuple(+ [await coordinator.execute_module(actor, request, campaign) for request in requests]+ )+ effect_count = len(engine.effects)+ replayed = tuple(+ [await coordinator.execute_module(actor, request, campaign) for request in requests]+ )++ assert all(+ outcome.disposition is DispatchDispositionV1.TERMINAL+ and outcome.lifecycle_result is FixedResult.APPLIED+ and outcome.effect_started+ and outcome.terminal_committed+ for outcome in applied+ )+ assert all(+ outcome.disposition is DispatchDispositionV1.REPLAYED+ and outcome.lifecycle_result is FixedResult.REPLAYED+ and not outcome.effect_started+ and not outcome.terminal_committed+ for outcome in replayed+ )+ assert [outcome.identity for outcome in replayed] == [+ outcome.identity for outcome in applied+ ]+ assert effect_count == len(requests)+ assert len(engine.effects) == effect_count+ assert len(engine.finalizations) == len(requests)+ assert len({outcome.identity.attempt_id for outcome in applied}) == len(requests)+ async with database._pool.acquire() as connection:+ terminal_count = await connection.fetchval(+ "SELECT count(*) FROM execution_attempts "+ "WHERE campaign_id=$1 AND state='succeeded'",+ campaign_id,+ )+ logical_count = await connection.fetchval(+ "SELECT count(*) FROM logical_executions WHERE campaign_id=$1",+ campaign_id,+ )+ assert terminal_count == logical_count == len(requests)diff --git a/tests/integration/test_postgres_execution_lifecycle.py b/tests/integration/test_postgres_execution_lifecycle.pynew file mode 100644index 0000000..5ed9895--- /dev/null+++ b/tests/integration/test_postgres_execution_lifecycle.py@@ -0,0 +1,6059 @@+"""Real PostgreSQL persistence-operation tests for lifecycle generation 10."""++from __future__ import annotations++import asyncio+import hashlib+import struct+from collections.abc import AsyncIterator+from contextlib import asynccontextmanager+from dataclasses import MISSING, FrozenInstanceError, fields, is_dataclass, replace+from typing import Any, get_type_hints++import asyncpg+import pytest+import pytest_asyncio++import ares.modules.descriptors as _descriptors+from ares.db.execution_lifecycle import (+ MAX_I53,+ SYSTEM_PRINCIPAL_SUBJECT_REF,+ ActorAuthorityMutation,+ AdmissionIntentV3,+ AdmissionRequest,+ ApprovalAuthorityGrant,+ ApprovalAuthorityMutation,+ AttemptState,+ BudgetConfiguration,+ BudgetReservation,+ BudgetSettlement,+ CampaignActorGrantMutation,+ CampaignAuthorityMutation,+ ClosureRequest,+ CredentialAuthorityMutation,+ DestinationAuthorityMutation,+ ExecutionLifecycleStore,+ FixedResult,+ GatewayAuthorityMutation,+ OperationResult,+ OutboxMutation,+ OutcomeCode,+ OutputKind,+ OutputObservation,+ RetryIntentV3,+ RetryRequest,+ TerminalCommitIntentV3,+ TerminalCommitRequest,+ TransitionRequest,+ TrustedPrincipal,+ validate_postgresql_lifecycle_catalog,+)+from ares.db.postgres import PostgresDatabase+from ares.modules.descriptors import (+ CancellationOwnership,+ CompensationClass,+ ContractState,+ ExternalEffectClass,+ IdempotencyClass,+ ResultContract,+ RetryEligibility,+ TimeoutPolicy,+ TimeoutSettlement,+)+from tests.integration.test_postgres_migration_portability import (+ _alembic,+ _migration_url,+ _MigrationHarness,+ _postgres_harness,+)+from tests.unit.test_execution_lifecycle_persistence import (+ _ACCEPTANCE_FACT_MUTATIONS,+ _EXPECTED_LEGAL,+ _ILLEGAL,+ _accepted_snapshot,+ _AdvancedClockLifecycleStore,+ _attempt_row,+ _blocked_snapshot,+ _build_source_state,+ _nonterminal_transition,+ _snapshot_case,+ _terminal_transition,+ _uuid,+)++_USER_ID = "00000000-0000-4000-8000-000000000001"+_CAMPAIGN_ID = "00000000-0000-4000-8000-000000000002"+_OPERATION_A = "00000000-0000-4000-8000-000000000003"+_OPERATION_B = "00000000-0000-4000-8000-000000000004"++_TERMINAL_TARGETS = frozenset(+ {+ "rejected",+ "blocked",+ "succeeded",+ "partial",+ "failed",+ "skipped",+ "cancelled",+ "timed_out",+ "indeterminate",+ }+)+++ ("_case", "field_name", "mutant"),+ _ACCEPTANCE_FACT_MUTATIONS,+ ids=[case for case, _field_name, _mutant in _ACCEPTANCE_FACT_MUTATIONS],+)+async def test_postgres_real_admission_rejects_each_invalid_fact(+ _case: str,+ field_name: str,+ mutant: Any,+ postgres_lifecycle_template: str,+) -> None:+ async with _cloned_postgres_harness(postgres_lifecycle_template) as harness:+ database = PostgresDatabase(_migration_url(harness.config, harness.database_name))+ await database.connect()+ connection = None+ observer = None+ results: list[FixedResult] = []+ try:+ snapshot = replace(_accepted_snapshot(), **{field_name: mutant})+ _store, _adapter, connection = await _postgres_transition_case(+ database,+ AttemptState.ACCEPTED,+ snapshot_override=snapshot,+ admission_results=results,+ expected_applied=False,+ )+ observer = await database._pool.acquire()+ logical_count = await observer.fetchval("SELECT COUNT(*) FROM logical_executions")+ attempt_count = await observer.fetchval("SELECT COUNT(*) FROM execution_attempts")+ ledger_count = await observer.fetchval(+ "SELECT COUNT(*) FROM campaign_execution_budget_ledger"+ )+ outbox_count = await observer.fetchval(+ "SELECT COUNT(*) FROM execution_publication_outbox"+ )+ admission_receipt_count = await observer.fetchval(+ "SELECT COUNT(*) FROM execution_operation_receipts WHERE operation_id = $1",+ _uuid(211),+ )+ reserved_total = await observer.fetchval(+ "SELECT COALESCE(SUM(reserved_units), 0) FROM campaign_execution_budgets"+ )+ assert results == [results[0]]+ assert results[0] is not FixedResult.APPLIED+ assert (logical_count, attempt_count, ledger_count, outbox_count) == (+ 0,+ 0,+ 0,+ 0,+ )+ assert admission_receipt_count == 0+ assert reserved_total == 0+ finally:+ if observer is not None:+ await database._pool.release(observer)+ if connection is not None:+ await database._pool.release(connection)+ await database.close()+++ ("field_name", "mutant"),+ [+ ("attempt_id", _uuid(890)),+ ("expected_revision", 1),+ ("target_state", AttemptState.DISPATCHING),+ ],+ ids=("attempt-binding", "revision-binding", "state-binding"),+)+async def test_postgres_transition_receipt_replay_and_binding_conflict(+ field_name: str,+ mutant: Any,+ postgres_lifecycle_template: str,+) -> None:+ async with _cloned_postgres_harness(postgres_lifecycle_template) as harness:+ database = PostgresDatabase(_migration_url(harness.config, harness.database_name))+ await database.connect()+ connection = None+ observer = None+ try:+ store, _adapter, connection = await _postgres_transition_case(+ database, AttemptState.ACCEPTED+ )+ request = TransitionRequest(+ _uuid(210),+ 0,+ AttemptState.QUEUED,+ _uuid(880),+ campaign_id=_uuid(201),+ actor_subject_ref=_uuid(200),+ actor_user_id=_uuid(200),+ actor_authority_revision=0,+ )+ applied = await store.transition_attempt(request)+ replayed = await store.transition_attempt(request)+ conflict = await store.transition_attempt(replace(request, **{field_name: mutant}))+ observer = await database._pool.acquire()+ row = await observer.fetchrow(+ "SELECT state, revision FROM execution_attempts WHERE id = $1",+ _uuid(210),+ )+ receipt_count = await observer.fetchval(+ "SELECT COUNT(*) FROM execution_operation_receipts WHERE operation_id = $1",+ _uuid(880),+ )+ assert applied.result is FixedResult.APPLIED+ assert replayed.result is FixedResult.REPLAYED+ assert conflict.result is FixedResult.CONFLICT_OPERATION+ assert tuple(row) == (AttemptState.QUEUED.value, 1)+ assert receipt_count == 1+ finally:+ if observer is not None:+ await database._pool.release(observer)+ if connection is not None:+ await database._pool.release(connection)+ await database.close()+++async def test_postgres_budget_replay_and_terminal_release_are_exact(+ postgres_lifecycle_template: str,+) -> None:+ async with _cloned_postgres_harness(postgres_lifecycle_template) as harness:+ database = PostgresDatabase(_migration_url(harness.config, harness.database_name))+ await database.connect()+ connection = None+ observer = None+ try:+ store, adapter, connection = await _postgres_transition_case(+ database, AttemptState.ACCEPTED+ )+ configuration = BudgetConfiguration(+ _uuid(201),+ _uuid(204),+ 20,+ _uuid(205),+ 20,+ _uuid(206),+ 1,+ _uuid(207),+ )+ replayed = await store.configure_campaign_budgets(configuration)+ conflict = await store.configure_campaign_budgets(+ replace(configuration, noise_capacity=21)+ )+ terminal = await _terminal_transition(+ store,+ adapter,+ AttemptState.SKIPPED,+ 880,+ )+ observer = await database._pool.acquire()+ balances = await observer.fetchrow(+ "SELECT COALESCE(SUM(reserved_units), 0), "+ "MIN(revision), MAX(revision) "+ "FROM campaign_execution_budgets WHERE campaign_id = $1",+ _uuid(201),+ )+ dispositions = await observer.fetch(+ "SELECT disposition FROM campaign_execution_budget_ledger "+ "WHERE attempt_id = $1 ORDER BY budget_kind",+ _uuid(210),+ )+ assert replayed.result is FixedResult.REPLAYED+ assert conflict.result is FixedResult.CONFLICT_OPERATION+ assert terminal.result is FixedResult.APPLIED+ assert tuple(balances) == (0, 2, 2)+ assert [row["disposition"] for row in dispositions] == [+ "released",+ "released",+ "released",+ ]+ finally:+ if observer is not None:+ await database._pool.release(observer)+ if connection is not None:+ await database._pool.release(connection)+ await database.close()+++async def test_postgres_outbox_replay_owner_binding_and_publish_are_exact(+ postgres_lifecycle_template: str,+) -> None:+ async with _cloned_postgres_harness(postgres_lifecycle_template) as harness:+ database = PostgresDatabase(_migration_url(harness.config, harness.database_name))+ await database.connect()+ connection = None+ observer = None+ try:+ store, _adapter, connection = await _postgres_transition_case(+ database, AttemptState.BLOCKED+ )+ claim = OutboxMutation(+ _uuid(212),+ 0,+ _uuid(880),+ _uuid(882),+ 0,+ _uuid(201),+ _uuid(210),+ _uuid(213),+ "execution_blocked",+ )+ applied = await store.claim_outbox(claim)+ replayed = await store.claim_outbox(claim)+ conflict = await store.claim_outbox(replace(claim, owner_ref=_uuid(883)))+ published = await store.publish_outbox(+ OutboxMutation(+ _uuid(212),+ 1,+ _uuid(881),+ _uuid(882),+ 1,+ _uuid(201),+ _uuid(210),+ _uuid(213),+ "execution_blocked",+ )+ )+ observer = await database._pool.acquire()+ row = await observer.fetchrow(+ "SELECT publication_state, claim_revision, delivery_attempt_count "+ "FROM execution_publication_outbox WHERE id = $1",+ _uuid(212),+ )+ receipt_count = await observer.fetchval(+ "SELECT COUNT(*) FROM execution_operation_receipts WHERE operation_id IN ($1, $2)",+ _uuid(880),+ _uuid(881),+ )+ assert applied.result is FixedResult.APPLIED+ assert replayed.result is FixedResult.REPLAYED+ assert conflict.result is FixedResult.CONFLICT_OPERATION+ assert published.result is FixedResult.APPLIED+ assert tuple(row) == ("published", 2, 1)+ assert receipt_count == 2+ finally:+ if observer is not None:+ await database._pool.release(observer)+ if connection is not None:+ await database._pool.release(connection)+ await database.close()+++async def test_postgres_terminal_output_commit_is_atomically_observable(+ postgres_lifecycle_template: str,+) -> None:+ async with _cloned_postgres_harness(postgres_lifecycle_template) as harness:+ database = PostgresDatabase(_migration_url(harness.config, harness.database_name))+ await database.connect()+ connection = None+ observer = None+ try:+ store, adapter, connection = await _postgres_transition_case(+ database, AttemptState.ACCEPTED+ )+ await _build_source_state(store, adapter, AttemptState.RUNNING)+ result = await _terminal_transition(+ store,+ adapter,+ AttemptState.PARTIAL,+ 880,+ )+ observer = await database._pool.acquire()+ attempt = await observer.fetchrow(+ "SELECT state, closes_logical FROM execution_attempts WHERE id = $1",+ _uuid(210),+ )+ link_count = await observer.fetchval(+ "SELECT COUNT(*) FROM execution_output_links "+ "WHERE attempt_id = $1 AND host_id = $2",+ _uuid(210),+ _uuid(260),+ )+ outbox_count = await observer.fetchval(+ "SELECT COUNT(*) FROM execution_publication_outbox "+ "WHERE attempt_id = $1 AND event_code = $2",+ _uuid(210),+ "execution_partial",+ )+ reserved_total = await observer.fetchval(+ "SELECT COALESCE(SUM(reserved_units), 0) "+ "FROM campaign_execution_budgets WHERE campaign_id = $1",+ _uuid(201),+ )+ assert result.result is FixedResult.APPLIED+ assert tuple(attempt) == (AttemptState.PARTIAL.value, True)+ assert link_count == 1+ assert outbox_count == 1+ assert reserved_total == 0+ finally:+ if observer is not None:+ await database._pool.release(observer)+ if connection is not None:+ await database._pool.release(connection)+ await database.close()+++async def test_postgres_settled_campaign_deletion_removes_lifecycle_tree(+ postgres_lifecycle_template: str,+) -> None:+ async with _cloned_postgres_harness(postgres_lifecycle_template) as harness:+ database = PostgresDatabase(_migration_url(harness.config, harness.database_name))+ await database.connect()+ connection = None+ observer = None+ try:+ store, adapter, connection = await _postgres_transition_case(+ database, AttemptState.ACCEPTED+ )+ terminal = await _terminal_transition(+ store,+ adapter,+ AttemptState.SKIPPED,+ 880,+ )+ await database._pool.release(connection)+ connection = None+ deleted = await database.delete_campaign_lifecycle(+ _uuid(201), lifecycle_operation_id=_uuid(884)+ )+ observer = await database._pool.acquire()+ counts = (+ await observer.fetchval("SELECT COUNT(*) FROM campaigns WHERE id = $1", _uuid(201)),+ await observer.fetchval(+ "SELECT COUNT(*) FROM logical_executions WHERE campaign_id = $1",+ _uuid(201),+ ),+ await observer.fetchval(+ "SELECT COUNT(*) FROM execution_attempts WHERE campaign_id = $1",+ _uuid(201),+ ),+ await observer.fetchval(+ "SELECT COUNT(*) FROM campaign_execution_budgets WHERE campaign_id = $1",+ _uuid(201),+ ),+ )+ assert terminal.result is FixedResult.APPLIED+ assert deleted.result is FixedResult.APPLIED+ assert counts == (0, 0, 0, 0)+ finally:+ if observer is not None:+ await database._pool.release(observer)+ if connection is not None:+ await database._pool.release(connection)+ await database.close()+++def _question_to_dollar(sql: str) -> str:+ parts = sql.split("?")+ return parts[0] + "".join(f"${index}{part}" for index, part in enumerate(parts[1:], 1))+++class _PostgresCursor:+ def __init__(self, rows: list[Any]) -> None:+ self._rows = rows++ async def fetchone(self) -> Any | None:+ return self._rows[0] if self._rows else None++ async def fetchall(self) -> list[Any]:+ return list(self._rows)+++class _PostgresConnectionAdapter:+ """Test-owned aiosqlite-shaped view over one real asyncpg connection."""++ def __init__(self, connection: Any) -> None:+ self._connection = connection++ async def execute(self, sql: str, params: tuple[Any, ...] = ()) -> _PostgresCursor:+ statement = _question_to_dollar(sql)+ if statement.lstrip().upper().startswith("SELECT") or " RETURNING " in statement.upper():+ rows = list(await self._connection.fetch(statement, *params))+ return _PostgresCursor(rows)+ await self._connection.execute(statement, *params)+ return _PostgresCursor([])++ async def commit(self) -> None:+ await self._connection.execute("COMMIT")++ async def rollback(self) -> None:+ await self._connection.execute("ROLLBACK")++ async def fetchrow(self, statement: str, *parameters: object):+ return await self._connection.fetchrow(_question_to_dollar(statement), *parameters)+++async def _replace_database_from_template(+ candidate: _MigrationHarness,+ template: _MigrationHarness,+) -> None:+ names = (candidate.database_name, template.database_name)+ if not all(name.replace("_", "").isalnum() for name in names):+ raise AssertionError("POSTGRES_TEMPLATE_NAME_INVALID")+ config = candidate.config+ connection = await asyncpg.connect(+ host=config.host,+ port=config.port,+ user=config.user,+ database=config.maintenance_database,+ )+ try:+ await connection.execute( # noqa: S608+ f'DROP DATABASE "{candidate.database_name}"'+ )+ await connection.execute( # noqa: S608+ f'CREATE DATABASE "{candidate.database_name}" TEMPLATE "{template.database_name}"'+ )+ finally:+ await connection.close()+++@asynccontextmanager+async def _cloned_postgres_harness(+ template: _MigrationHarness,+) -> AsyncIterator[_MigrationHarness]:+ async with _postgres_harness() as candidate:+ await _replace_database_from_template(candidate, template)+ yield candidate+++@pytest_asyncio.fixture(scope="module")+async def postgres_lifecycle_template() -> AsyncIterator[_MigrationHarness]:+ async with _postgres_harness() as template:+ await _alembic(template, "upgrade", "head", timeout=60.0)+ yield template+++async def _postgres_transition_case(+ database: PostgresDatabase,+ initial: str,+ *,+ snapshot_override: Any | None = None,+ admission_results: list[FixedResult] | None = None,+ expected_applied: bool = True,+) -> tuple[ExecutionLifecycleStore, _PostgresConnectionAdapter, Any]:+ async with database._pool.acquire() as gateway_connection:+ initial not in {"rejected", "blocked"} and await gateway_connection.execute(+ """+ UPDATE execution_gateway_state+ SET mode = 'enforced',+ catalog_digest = repeat('0', 64),+ activation_revision = 1,+ activation_at = updated_at,+ revision = revision + 1+ """+ )+ connection = await database._pool.acquire()+ handed_off = False+ try:+ result = await _initialize_postgres_transition_case(+ database,+ connection,+ initial,+ snapshot_override=snapshot_override,+ admission_results=admission_results,+ expected_applied=expected_applied,+ )+ handed_off = True+ return result+ finally:+ if not handed_off:+ await database._pool.release(connection)+++async def _initialize_postgres_transition_case(+ database: PostgresDatabase,+ connection: Any,+ initial: str,+ *,+ snapshot_override: Any | None,+ admission_results: list[FixedResult] | None,+ expected_applied: bool,+) -> tuple[ExecutionLifecycleStore, _PostgresConnectionAdapter, Any]:+ adapter = _PostgresConnectionAdapter(connection)+ await connection.execute(+ "INSERT INTO users(id,username,hashed_password,role,created_by) "+ "VALUES($1,'transition-user','fixed-hash','admin','fixed')",+ _uuid(200),+ )+ await connection.execute(+ "INSERT INTO campaigns(id,name) VALUES($1,'transition-campaign')",+ _uuid(201),+ )+ await connection.execute(+ "INSERT INTO hosts (id, campaign_id, ip_address) VALUES ($1, $2, $3)",+ _uuid(260),+ _uuid(201),+ "192.0.2.1",+ )++ store = ExecutionLifecycleStore(database._pool, "postgresql")+ assert (+ await store.ensure_actor_authority(_uuid(200), _uuid(202))+ ).result is FixedResult.APPLIED+ assert (+ await store.ensure_campaign_authority(_uuid(201), _uuid(203))+ ).result is FixedResult.APPLIED++ budgets = BudgetReservation(+ _uuid(201),+ _uuid(210),+ _uuid(204),+ _uuid(214),+ 2,+ 0,+ _uuid(205),+ _uuid(215),+ 3,+ 0,+ _uuid(206),+ _uuid(216),+ 0,+ _uuid(217),+ )+ if initial not in {"rejected", "blocked"}:+ configured = await store.configure_campaign_budgets(+ BudgetConfiguration(+ _uuid(201),+ _uuid(204),+ 20,+ _uuid(205),+ 20,+ _uuid(206),+ 1,+ _uuid(207),+ )+ )+ assert configured.result is FixedResult.APPLIED++ if initial == "accepted":+ snapshot = _accepted_snapshot()+ outbox_id = None+ publication_key = None+ request_budgets = budgets+ elif initial == "rejected":+ snapshot = replace(+ _blocked_snapshot(),+ policy_verdict="rejected",+ policy_reason_mask=1,+ )+ outbox_id = _uuid(212)+ publication_key = _uuid(213)+ request_budgets = None+ else:+ snapshot = _blocked_snapshot()+ outbox_id = _uuid(212)+ publication_key = _uuid(213)+ request_budgets = None+ if snapshot_override is not None:+ snapshot = snapshot_override+ await connection.execute(+ "UPDATE users SET role=$1 WHERE id=$2",+ snapshot.actor_role,+ _uuid(200),+ )+ admitted = await store._create_initial_execution_v2_for_migration_fixture(+ AdmissionRequest(+ _uuid(208),+ _uuid(209),+ _uuid(210),+ outbox_id,+ publication_key,+ _uuid(201),+ _uuid(200),+ _uuid(200),+ "test-transition",+ "sdk",+ AttemptState(initial),+ _uuid(211),+ snapshot,+ None,+ request_budgets,+ )+ )+ if admission_results is not None:+ admission_results.append(admitted.result)+ if expected_applied:+ assert admitted.result is FixedResult.APPLIED+ else:+ assert admitted.result is not FixedResult.APPLIED+ return store, adapter, connection+++async def _exercise_postgres_pair(+ database: PostgresDatabase,+ source: str,+ target: str,+) -> tuple[Any, tuple[Any, ...], tuple[Any, ...], tuple[Any, ...], Any, Any]:+ initial = source if source in {"rejected", "blocked"} else "accepted"+ store, adapter, connection = await _postgres_transition_case(database, initial)+ try:+ if source not in {"rejected", "blocked", "accepted"}:+ source_state = AttemptState(source)+ if source_state in {AttemptState.FAILED, AttemptState.SKIPPED}:+ result = await _terminal_transition(store, adapter, source_state, 270)+ assert result.result is FixedResult.APPLIED+ elif source_state is AttemptState.INDETERMINATE:+ await _build_source_state(+ store,+ adapter,+ AttemptState.SETTLEMENT_PENDING,+ )+ await connection.execute(+ "UPDATE users SET role = $1 WHERE id = $2",+ "admin",+ _uuid(200),+ )+ terminal_store = _AdvancedClockLifecycleStore(+ database._pool,+ "postgresql",+ )+ result = await _terminal_transition(+ terminal_store,+ adapter,+ source_state,+ 700,+ )+ assert result.result is FixedResult.APPLIED+ else:+ await _build_source_state(store, adapter, source_state)+ before_row = await _attempt_row(adapter)+ before = await _snapshot_case(adapter)+ if target in _TERMINAL_TARGETS:+ if target == AttemptState.INDETERMINATE.value:+ await connection.execute(+ "UPDATE users SET role = $1 WHERE id = $2",+ "admin",+ _uuid(200),+ )+ terminal_store = (+ _AdvancedClockLifecycleStore(database._pool, "postgresql")+ if target == AttemptState.INDETERMINATE.value+ else store+ )+ result = await _terminal_transition(terminal_store, adapter, AttemptState(target), 700)+ else:+ result = await _nonterminal_transition(store, adapter, AttemptState(target), 700)+ after_row = await _attempt_row(adapter)+ after = await _snapshot_case(adapter)+ finally:+ await database._pool.release(connection)+ async with database._pool.acquire() as observer:+ durable = await _snapshot_case(_PostgresConnectionAdapter(observer))+ return result, before, after, durable, before_row, after_row+++async def test_postgres_runtime_validates_0010_and_authority_cas_replays() -> None:+ async with _postgres_harness() as harness:+ await _alembic(harness, "upgrade", "head")+ database = PostgresDatabase(+ _migration_url(harness.config, harness.database_name),+ pool_min=1,+ pool_max=2,+ )+ await database.connect()+ try:+ async with database._pool.acquire() as connection:+ await validate_postgresql_lifecycle_catalog(connection)+ await connection.execute(+ "INSERT INTO users(id,username,hashed_password,role,created_by) "+ "VALUES($1,'fixed-user','fixed-hash','admin','fixed')",+ _USER_ID,+ )+ await connection.execute(+ "INSERT INTO campaigns(id,name) VALUES($1,'fixed-campaign')",+ _CAMPAIGN_ID,+ )+ store = ExecutionLifecycleStore(database._pool, "postgresql")+ created = await store.ensure_actor_authority(_USER_ID, _OPERATION_A)+ replay = await store.ensure_actor_authority(_USER_ID, _OPERATION_A)+ invalidated = await store.invalidate_actor_authority(_USER_ID, 0, _OPERATION_B)+ finally:+ await database.close()+ assert (created.result, replay.result, invalidated.result) == (+ FixedResult.APPLIED,+ FixedResult.REPLAYED,+ FixedResult.APPLIED,+ ), "PostgreSQL authority CAS changed"+++async def test_empty_postgres_runtime_refuses_without_fallback() -> None:+ async with _postgres_harness() as harness:+ database = PostgresDatabase(+ _migration_url(harness.config, harness.database_name),+ pool_min=1,+ pool_max=1,+ )+ with pytest.raises(RuntimeError, match="PostgreSQL schema migration required"):+ await database.connect()+ assert database._pool is None, "failed PostgreSQL startup retained a pool"+++ ("source", "target"),+ _EXPECTED_LEGAL,+ ids=[f"legal-{source}-{target}" for source, target in _EXPECTED_LEGAL],+)+async def test_postgres_real_store_legal_transition(source: str, target: str) -> None:+ async with _postgres_harness() as harness:+ await _alembic(harness, "upgrade", "head")+ database = PostgresDatabase(+ _migration_url(harness.config, harness.database_name),+ pool_min=1,+ pool_max=4,+ )+ await database.connect()+ try:+ result, before, after, durable, before_row, after_row = await _exercise_postgres_pair(+ database,+ source,+ target,+ )+ finally:+ await database.close()+ assert result.result is FixedResult.APPLIED, "legal PostgreSQL transition was not applied"+ assert int(after_row["revision"]) == int(before_row["revision"]) + 1, (+ "legal PostgreSQL transition changed revision incorrectly"+ )+ assert after_row["state"] == target, "legal PostgreSQL transition stored the wrong state"+ assert after != before, "legal PostgreSQL transition made no durable mutation"+ assert durable == after, "legal PostgreSQL transition was not visible on another connection"+++ ("source", "target"),+ _ILLEGAL,+ ids=[f"illegal-{source}-{target}" for source, target in _ILLEGAL],+)+async def test_postgres_real_store_illegal_transition(+ source: str,+ target: str,+ postgres_lifecycle_template: _MigrationHarness,+) -> None:+ async with _cloned_postgres_harness(postgres_lifecycle_template) as harness:+ database = PostgresDatabase(+ _migration_url(harness.config, harness.database_name),+ pool_min=1,+ pool_max=4,+ )+ await database.connect()+ try:+ result, before, after, durable, before_row, after_row = await _exercise_postgres_pair(+ database,+ source,+ target,+ )+ finally:+ await database.close()+ assert result.result is not FixedResult.APPLIED, "illegal PostgreSQL transition was applied"+ assert int(after_row["revision"]) == int(before_row["revision"]), (+ "illegal PostgreSQL transition changed revision"+ )+ assert after == before, "illegal PostgreSQL transition mutated physical state"+ assert durable == before, "illegal PostgreSQL transition mutated durable state"+++_POSTGRES_LITERAL_ROLE_CELLS = (+ ("reporter", "operator", False),+ ("reporter", "team_lead", False),+ ("reporter", "admin", False),+ ("operator", "operator", True),+ ("operator", "team_lead", False),+ ("operator", "admin", False),+ ("team_lead", "operator", True),+ ("team_lead", "team_lead", True),+ ("team_lead", "admin", False),+ ("admin", "operator", True),+ ("admin", "team_lead", True),+ ("admin", "admin", True),+)+++ ("actor_role", "minimum_role", "satisfies"),+ _POSTGRES_LITERAL_ROLE_CELLS,+ ids=[f"role-{actor}-{minimum}" for actor, minimum, _ in _POSTGRES_LITERAL_ROLE_CELLS],+)+async def test_postgres_real_admission_role_cell(+ actor_role: str,+ minimum_role: str,+ satisfies: bool,+) -> None:+ snapshot = replace(+ _accepted_snapshot(),+ actor_role=actor_role,+ minimum_role=minimum_role,+ )+ expected_state = AttemptState.ACCEPTED.value+ if not satisfies:+ denied = _blocked_snapshot()+ snapshot = replace(+ snapshot,+ policy_verdict=denied.policy_verdict,+ policy_reason_mask=denied.policy_reason_mask,+ gateway_mode_snapshot=denied.gateway_mode_snapshot,+ gateway_decision_code=denied.gateway_decision_code,+ )+ expected_state = AttemptState.BLOCKED.value+ async with _postgres_harness() as harness:+ await _alembic(harness, "upgrade", "head")+ database = PostgresDatabase(+ _migration_url(harness.config, harness.database_name),+ pool_min=1,+ pool_max=2,+ )+ await database.connect()+ try:+ _, adapter, connection = await _postgres_transition_case(+ database,+ expected_state,+ snapshot_override=snapshot,+ )+ row = await _attempt_row(adapter)+ finally:+ if "connection" in locals():+ await database._pool.release(connection)+ await database.close()+ assert row["state"] == expected_state, "PostgreSQL role admission stored the wrong state"+++class _ReturningCountStore(ExecutionLifecycleStore):+ def __init__(self, backend: Any, statement_fragment: str) -> None:+ super().__init__(backend, "postgresql")+ self._statement_fragment = statement_fragment+ self.returned_cardinalities: list[int] = []++ async def _returning_rows(+ self,+ connection: Any,+ sql: str,+ params: tuple[Any, ...],+ ) -> tuple[Any, ...]:+ rows = await super()._returning_rows(connection, sql, params)+ if self._statement_fragment in sql:+ self.returned_cardinalities.append(len(rows))+ return rows+++class _DuplicateReturningStore(ExecutionLifecycleStore):+ def __init__(self, backend: Any, statement_fragment: str) -> None:+ super().__init__(backend, "postgresql")+ self._statement_fragment = statement_fragment+ self.injected = False++ async def _returning_rows(+ self,+ connection: Any,+ sql: str,+ params: tuple[Any, ...],+ ) -> tuple[Any, ...]:+ rows = await super()._returning_rows(connection, sql, params)+ if not self.injected and self._statement_fragment in sql:+ self.injected = True+ return rows + rows+ return rows+++class _ZeroRowClassificationStore(ExecutionLifecycleStore):+ """Test seam which creates a real conflicting catalog row in the same transaction."""++ _FRAGMENTS = {+ "missing": "UPDATE execution_actor_authority_revisions SET",+ "stale-revision": "UPDATE execution_attempts SET state=",+ "stale-state": "UPDATE execution_attempts SET state=",+ "stale-authority": "UPDATE execution_attempts SET closes_logical=",+ "stale-owner": "UPDATE execution_attempts SET state=",+ "stale-generation": "UPDATE execution_attempts SET state=",+ "stale-lease": "UPDATE execution_publication_outbox SET",+ "stale-cancellation": "UPDATE execution_attempts SET state=",+ "operation-conflict": "INSERT INTO execution_actor_authority_revisions",+ }++ def __init__(self, backend: Any, case_alias: str) -> None:+ super().__init__(backend, "postgresql")+ self.case_alias = case_alias+ self.fault_fired = False+ self.fault_connection: Any | None = None+ self.transaction_connection: Any | None = None+ self.classifier_connection: Any | None = None+ self.fault_backend_pid: int | None = None+ self.transaction_backend_pid: int | None = None+ self.classifier_backend_pid: int | None = None+ self.fault_transaction_id: int | None = None+ self.transaction_id: int | None = None+ self.classifier_transaction_id: int | None = None++ async def _identity(self, connection: Any) -> tuple[int, int]:+ row = await connection.fetchrow(+ "SELECT pg_backend_pid() AS backend_pid, txid_current() AS transaction_id"+ )+ return int(row["backend_pid"]), int(row["transaction_id"])++ @asynccontextmanager+ async def _transaction(self) -> AsyncIterator[Any]:+ async with super()._transaction() as connection:+ self.transaction_connection = connection+ self.transaction_backend_pid, self.transaction_id = await self._identity(connection)+ yield connection++ async def _returning_rows(+ self,+ connection: Any,+ sql: str,+ params: tuple[Any, ...],+ ) -> tuple[Any, ...]:+ fragment = self._FRAGMENTS.get(self.case_alias)+ if not self.fault_fired and fragment is not None and fragment in sql:+ self.fault_fired = True+ self.fault_connection = connection+ self.fault_backend_pid, self.fault_transaction_id = await self._identity(connection)+ if self.case_alias == "missing":+ await connection.execute(+ "DELETE FROM execution_actor_authority_revisions WHERE user_id=$1",+ _uuid(200),+ )+ elif self.case_alias == "stale-revision":+ await connection.execute(+ "UPDATE execution_attempts SET revision=revision+1 WHERE id=$1",+ _uuid(210),+ )+ elif self.case_alias == "stale-state":+ await connection.execute(+ "UPDATE execution_attempts SET state='queued',queue_operation_id=$1,"+ "queued_at=accepted_at WHERE id=$2",+ _uuid(981),+ _uuid(210),+ )+ elif self.case_alias == "stale-authority":+ await connection.execute(+ "UPDATE execution_actor_authority_revisions "+ "SET revision=revision+1 WHERE user_id=$1",+ _uuid(200),+ )+ elif self.case_alias == "stale-owner":+ await connection.execute(+ "UPDATE execution_attempts SET dispatch_owner_ref=$1 WHERE id=$2",+ _uuid(298),+ _uuid(210),+ )+ elif self.case_alias == "stale-generation":+ await connection.execute(+ "UPDATE execution_attempts SET lease_generation=lease_generation+1 WHERE id=$1",+ _uuid(210),+ )+ elif self.case_alias == "stale-lease":+ await connection.execute(+ "UPDATE execution_publication_outbox "+ "SET lease_expires_at=claimed_at WHERE id=$1",+ _uuid(212),+ )+ elif self.case_alias == "stale-cancellation":+ await connection.execute(+ "UPDATE execution_attempts "+ "SET cancellation_request_revision=cancellation_request_revision+1 "+ "WHERE id=$1",+ _uuid(210),+ )+ elif self.case_alias == "operation-conflict":+ await connection.execute(+ "INSERT INTO execution_actor_authority_revisions("+ "user_id,revision,latest_operation_id,latest_operation_base_revision,"+ "latest_operation_code) VALUES($1,0,$2,0,'ensure')",+ _uuid(299),+ _uuid(962),+ )+ return ()+ return await super()._returning_rows(connection, sql, params)++ async def _record_classifier(self, connection: Any) -> None:+ self.classifier_connection = connection+ self.classifier_backend_pid, self.classifier_transaction_id = await self._identity(+ connection+ )++ async def _classify_zero_outbox(self, connection: Any, **kwargs: Any):+ await self._record_classifier(connection)+ return await super()._classify_zero_outbox(connection, **kwargs)++ async def _classify_zero_row(self, connection: Any, **kwargs: Any):+ await self._record_classifier(connection)+ return await super()._classify_zero_row(connection, **kwargs)+++class _TransactionBarrierStore(ExecutionLifecycleStore):+ def __init__(self, backend: Any, participant_count: int) -> None:+ super().__init__(backend, "postgresql")+ self._participant_count = participant_count+ self._entered = 0+ self.all_entered = asyncio.Event()+ self.backend_pids: list[int] = []++ @asynccontextmanager+ async def _transaction(self) -> AsyncIterator[Any]:+ async with super()._transaction() as connection:+ self.backend_pids.append(int(await connection.fetchval("SELECT pg_backend_pid()")))+ self._entered += 1+ if self._entered == self._participant_count:+ self.all_entered.set()+ await asyncio.wait_for(self.all_entered.wait(), timeout=10)+ yield connection+++class _PostgresAdmissionWinnerStore(ExecutionLifecycleStore):+ def __init__(+ self,+ backend: Any,+ admission_locked: asyncio.Event,+ revocation_attempted: asyncio.Event,+ ) -> None:+ super().__init__(backend, "postgresql")+ self._admission_locked = admission_locked+ self._revocation_attempted = revocation_attempted++ async def _resolve_principal(self, connection: Any, principal: object, *, suffix: str):+ resolved = await super()._resolve_principal(+ connection,+ principal,+ suffix=suffix,+ )+ self._admission_locked.set()+ await self._revocation_attempted.wait()+ return resolved+++class _PostgresRevocationContenderStore(ExecutionLifecycleStore):+ def __init__(self, backend: Any, revocation_attempted: asyncio.Event) -> None:+ super().__init__(backend, "postgresql")+ self._revocation_attempted = revocation_attempted++ async def _mutate_existing_authority_v11(self, *args: Any, **kwargs: Any):+ self._revocation_attempted.set()+ return await super()._mutate_existing_authority_v11(*args, **kwargs)+++class _TransactionProxy:+ def __init__(+ self,+ transaction: Any,+ *,+ rollback_started: asyncio.Event | None = None,+ rollback_continue: asyncio.Event | None = None,+ fail_rollback: bool = False,+ ) -> None:+ self._transaction = transaction+ self._rollback_started = rollback_started+ self._rollback_continue = rollback_continue+ self._fail_rollback = fail_rollback++ async def start(self) -> None:+ await self._transaction.start()++ async def commit(self) -> None:+ await self._transaction.commit()++ async def rollback(self) -> None:+ if self._rollback_started is not None:+ self._rollback_started.set()+ if self._rollback_continue is not None:+ await self._rollback_continue.wait()+ await self._transaction.rollback()+ if self._fail_rollback:+ raise RuntimeError("P1_A_PRIVATE_ROLLBACK_FAILURE")+++class _ConnectionProxy:+ def __init__(self, connection: Any, pool: _PoolFaultSeam) -> None:+ self._connection = connection+ self._pool = pool++ def transaction(self) -> _TransactionProxy:+ return _TransactionProxy(+ self._connection.transaction(),+ rollback_started=self._pool.rollback_started,+ rollback_continue=self._pool.rollback_continue,+ fail_rollback=self._pool.failure_point == "transaction-rollback",+ )++ def __getattr__(self, name: str) -> Any:+ return getattr(self._connection, name)+++class _PoolFaultSeam:+ """Delegates to one real pool and injects only after real cleanup completes."""++ def __init__(+ self,+ pool: Any,+ *,+ failure_point: str | None = None,+ rollback_started: asyncio.Event | None = None,+ rollback_continue: asyncio.Event | None = None,+ ) -> None:+ self._pool = pool+ self.failure_point = failure_point+ self.rollback_started = rollback_started+ self.rollback_continue = rollback_continue+ self.release_completed = asyncio.Event()++ async def acquire(self) -> _ConnectionProxy:+ return _ConnectionProxy(await self._pool.acquire(), self)++ async def release(self, connection: _ConnectionProxy) -> None:+ await self._pool.release(connection._connection)+ self.release_completed.set()+ if self.failure_point == "pool-release":+ raise RuntimeError("P1_A_PRIVATE_RELEASE_FAILURE")+++class _BlockingReceiptStore(ExecutionLifecycleStore):+ def __init__(self, backend: Any) -> None:+ super().__init__(backend, "postgresql")+ self.receipt_entered = asyncio.Event()+ self.backend_pid: int | None = None++ async def _insert_receipt(self, connection: Any, *args: Any, **kwargs: Any) -> None:+ self.backend_pid = int(await connection.fetchval("SELECT pg_backend_pid()"))+ self.receipt_entered.set()+ await asyncio.Event().wait()+++class _PrimaryReceiptFailureStore(ExecutionLifecycleStore):+ def __init__(self, backend: Any, primary: RuntimeError) -> None:+ super().__init__(backend, "postgresql")+ self.primary = primary+ self.backend_pid: int | None = None++ async def _insert_receipt(self, connection: Any, *args: Any, **kwargs: Any) -> None:+ self.backend_pid = int(await connection.fetchval("SELECT pg_backend_pid()"))+ raise self.primary+++async def _postgres_actor_authority_fixture(+ database: PostgresDatabase,+) -> ExecutionLifecycleStore:+ async with database._pool.acquire() as connection:+ await connection.execute(+ "INSERT INTO users(id,username,hashed_password,role,created_by) "+ "VALUES($1,'p1-a-user','fixed-hash','admin','fixed')",+ _uuid(940),+ )+ store = ExecutionLifecycleStore(database._pool, "postgresql")+ created = await store.ensure_actor_authority(_uuid(940), _uuid(941))+ assert created.result is FixedResult.APPLIED+ return store+++async def test_postgres_p1a_exact_one_returning_row_commits_once(+ postgres_lifecycle_template: _MigrationHarness,+) -> None:+ async with _cloned_postgres_harness(postgres_lifecycle_template) as harness:+ database = PostgresDatabase(+ _migration_url(harness.config, harness.database_name), pool_min=1, pool_max=2+ )+ await database.connect()+ try:+ await _postgres_actor_authority_fixture(database)+ store = _ReturningCountStore(+ database._pool, "UPDATE execution_actor_authority_revisions SET"+ )+ result = await store.invalidate_actor_authority(_uuid(940), 0, _uuid(942))+ async with database._pool.acquire() as observer:+ row = await observer.fetchrow(+ "SELECT revision FROM execution_actor_authority_revisions WHERE user_id=$1",+ _uuid(940),+ )+ receipts = await observer.fetchval(+ "SELECT count(*) FROM execution_operation_receipts WHERE operation_id=$1",+ _uuid(942),+ )+ assert (result.result, result.revision) == (FixedResult.APPLIED, 1)+ assert store.returned_cardinalities == [1]+ assert (int(row["revision"]), int(receipts)) == (1, 1)+ finally:+ await database.close()+++_POSTGRES_P1A_ZERO_ROW_CASES = (+ ("missing", FixedResult.CONFLICT_STATE),+ ("stale-revision", FixedResult.CONFLICT_REVISION),+ ("stale-state", FixedResult.CONFLICT_STATE),+ ("stale-authority", FixedResult.AUTHORITY_STALE),+ ("stale-owner", FixedResult.CONFLICT_OWNER),+ ("stale-generation", FixedResult.CONFLICT_GENERATION),+ ("stale-lease", FixedResult.CONFLICT_STATE),+ ("stale-cancellation", FixedResult.CONFLICT_REVISION),+ ("operation-conflict", FixedResult.CONFLICT_OPERATION),+)+++ ("case_alias", "expected"),+ _POSTGRES_P1A_ZERO_ROW_CASES,+ ids=[alias for alias, _expected in _POSTGRES_P1A_ZERO_ROW_CASES],+)+async def test_postgres_p1a_zero_row_is_classified_in_same_transaction(+ case_alias: str,+ expected: FixedResult,+ postgres_lifecycle_template: _MigrationHarness,+) -> None:+ async with _cloned_postgres_harness(postgres_lifecycle_template) as harness:+ database = PostgresDatabase(+ _migration_url(harness.config, harness.database_name), pool_min=1, pool_max=4+ )+ await database.connect()+ setup_connection = None+ try:+ snapshot_override = None+ if case_alias == "stale-authority":+ snapshot_override = replace(+ _accepted_snapshot(),+ actor_role="admin",+ idempotency_class="proven_idempotent",+ retry_policy="after_revalidation",+ )+ normal, adapter, setup_connection = await _postgres_transition_case(+ database,+ AttemptState.BLOCKED if case_alias == "stale-lease" else AttemptState.ACCEPTED,+ snapshot_override=snapshot_override,+ )+ store = _ZeroRowClassificationStore(database._pool, case_alias)+ before_attempt = await setup_connection.fetchrow(+ "SELECT state,revision,dispatch_owner_ref,lease_generation,"+ "cancellation_request_revision FROM execution_attempts WHERE id=$1",+ _uuid(210),+ )+ before_authority = await setup_connection.fetchrow(+ "SELECT revision FROM execution_actor_authority_revisions WHERE user_id=$1",+ _uuid(200),+ )+ before_outbox = await setup_connection.fetchrow(+ "SELECT publication_state,claim_revision,claim_owner_ref,lease_generation,"+ "lease_expires_at FROM execution_publication_outbox WHERE id=$1",+ _uuid(212),+ )+ if case_alias == "missing":+ result = await store.invalidate_actor_authority(_uuid(200), 0, _uuid(950))+ elif case_alias in {"stale-revision", "stale-state"}:+ result = await _nonterminal_transition(store, adapter, AttemptState.QUEUED, 951)+ elif case_alias == "stale-authority":+ terminal = await _terminal_transition(normal, adapter, AttemptState.FAILED, 952)+ assert terminal.result is FixedResult.APPLIED+ async with setup_connection.transaction():+ await setup_connection.execute(+ "UPDATE execution_attempts SET closes_logical=FALSE,"+ "retry_disposition='eligible' WHERE id=$1",+ _uuid(210),+ )+ await setup_connection.execute(+ "UPDATE logical_executions SET closure_operation_id=NULL,"+ "closure_authority_subject_ref=NULL,closure_authority_user_id=NULL,"+ "closure_authority_revision=NULL,closing_attempt_id=NULL,closed_at=NULL "+ "WHERE id=$1",+ _uuid(208),+ )+ before_attempt = await setup_connection.fetchrow(+ "SELECT state,revision,dispatch_owner_ref,lease_generation,"+ "cancellation_request_revision FROM execution_attempts WHERE id=$1",+ _uuid(210),+ )+ before_outbox = await setup_connection.fetchrow(+ "SELECT publication_state,claim_revision,claim_owner_ref,lease_generation,"+ "lease_expires_at FROM execution_publication_outbox WHERE id=$1",+ _uuid(212),+ )+ result = await store.close_without_retry(+ ClosureRequest(+ _uuid(208),+ _uuid(210),+ _uuid(955),+ int(before_attempt["revision"]),+ _uuid(956),+ _uuid(200),+ _uuid(200),+ 0,+ _uuid(201),+ )+ )+ elif case_alias in {"stale-owner", "stale-generation"}:+ await _build_source_state(normal, adapter, AttemptState.DISPATCHING)+ before_attempt = await setup_connection.fetchrow(+ "SELECT state,revision,dispatch_owner_ref,lease_generation,"+ "cancellation_request_revision FROM execution_attempts WHERE id=$1",+ _uuid(210),+ )+ result = await _nonterminal_transition(store, adapter, AttemptState.RUNNING, 957)+ elif case_alias == "stale-lease":+ claimed = await normal.claim_outbox(+ OutboxMutation(+ _uuid(212),+ 0,+ _uuid(958),+ _uuid(959),+ 0,+ _uuid(201),+ _uuid(210),+ _uuid(213),+ "execution_blocked",+ )+ )+ assert claimed.result is FixedResult.APPLIED+ before_outbox = await setup_connection.fetchrow(+ "SELECT publication_state,claim_revision,claim_owner_ref,lease_generation,"+ "lease_expires_at FROM execution_publication_outbox WHERE id=$1",+ _uuid(212),+ )+ result = await store.publish_outbox(+ OutboxMutation(+ _uuid(212),+ 1,+ _uuid(960),+ _uuid(959),+ 1,+ _uuid(201),+ _uuid(210),+ _uuid(213),+ "execution_blocked",+ )+ )+ elif case_alias == "stale-cancellation":+ await _build_source_state(normal, adapter, AttemptState.CANCELLING)+ before_attempt = await setup_connection.fetchrow(+ "SELECT state,revision,dispatch_owner_ref,lease_generation,"+ "cancellation_request_revision FROM execution_attempts WHERE id=$1",+ _uuid(210),+ )+ result = await _terminal_transition(store, adapter, AttemptState.CANCELLED, 961)+ else:+ await setup_connection.execute(+ "INSERT INTO users(id,username,hashed_password,role,created_by) "+ "VALUES($1,'p1-a-operation-conflict','fixed-hash','admin','fixed')",+ _uuid(299),+ )+ result = await store.ensure_actor_authority(_uuid(299), _uuid(962))++ assert result.result is expected+ async with database._pool.acquire() as observer:+ after_attempt = await observer.fetchrow(+ "SELECT state,revision,dispatch_owner_ref,lease_generation,"+ "cancellation_request_revision FROM execution_attempts WHERE id=$1",+ _uuid(210),+ )+ after_authority = await observer.fetchrow(+ "SELECT revision FROM execution_actor_authority_revisions WHERE user_id=$1",+ _uuid(200),+ )+ conflicting_authority = await observer.fetchval(+ "SELECT count(*) FROM execution_actor_authority_revisions WHERE user_id=$1",+ _uuid(299),+ )+ after_outbox = await observer.fetchrow(+ "SELECT publication_state,claim_revision,claim_owner_ref,lease_generation,"+ "lease_expires_at FROM execution_publication_outbox WHERE id=$1",+ _uuid(212),+ )+ assert tuple(after_attempt) == tuple(before_attempt)+ assert tuple(after_authority) == tuple(before_authority)+ assert (None if after_outbox is None else tuple(after_outbox)) == (+ None if before_outbox is None else tuple(before_outbox)+ )+ assert int(conflicting_authority) == 0+ assert store.fault_fired+ assert store.fault_connection is store.transaction_connection+ assert store.fault_backend_pid == store.transaction_backend_pid+ assert store.fault_transaction_id == store.transaction_id+ assert store.fault_connection is store.classifier_connection+ assert store.fault_backend_pid == store.classifier_backend_pid+ assert store.fault_transaction_id == store.classifier_transaction_id+ finally:+ if setup_connection is not None:+ await database._pool.release(setup_connection)+ await database.close()+++async def test_postgres_p1a_multiple_returning_rows_abort_atomically(+ postgres_lifecycle_template: _MigrationHarness,+) -> None:+ async with _cloned_postgres_harness(postgres_lifecycle_template) as harness:+ database = PostgresDatabase(+ _migration_url(harness.config, harness.database_name), pool_min=1, pool_max=2+ )+ await database.connect()+ try:+ await _postgres_actor_authority_fixture(database)+ store = _DuplicateReturningStore(+ database._pool, "UPDATE execution_actor_authority_revisions SET"+ )+ result = await store.invalidate_actor_authority(_uuid(940), 0, _uuid(943))+ async with database._pool.acquire() as observer:+ revision = await observer.fetchval(+ "SELECT revision FROM execution_actor_authority_revisions WHERE user_id=$1",+ _uuid(940),+ )+ receipt_count = await observer.fetchval(+ "SELECT count(*) FROM execution_operation_receipts WHERE operation_id=$1",+ _uuid(943),+ )+ assert store.injected+ assert result.result is FixedResult.INVARIANT_FAILURE+ assert (int(revision), int(receipt_count)) == (0, 0)+ finally:+ await database.close()+++async def test_postgres_p1a_concurrent_cas_has_one_winner_and_one_fixed_loser(+ postgres_lifecycle_template: _MigrationHarness,+) -> None:+ async with _cloned_postgres_harness(postgres_lifecycle_template) as harness:+ database = PostgresDatabase(+ _migration_url(harness.config, harness.database_name), pool_min=3, pool_max=3+ )+ await database.connect()+ observer = None+ try:+ await _postgres_actor_authority_fixture(database)+ observer = await database._pool.acquire()+ observer_pid = int(await observer.fetchval("SELECT pg_backend_pid()"))+ store = _TransactionBarrierStore(database._pool, 2)+ left = asyncio.create_task(store.invalidate_actor_authority(_uuid(940), 0, _uuid(944)))+ right = asyncio.create_task(store.invalidate_actor_authority(_uuid(940), 0, _uuid(945)))+ left_result, right_result = await asyncio.gather(left, right)+ row = await observer.fetchrow(+ "SELECT revision FROM execution_actor_authority_revisions WHERE user_id=$1",+ _uuid(940),+ )+ receipt_count = await observer.fetchval(+ "SELECT count(*) FROM execution_operation_receipts WHERE operation_id IN ($1,$2)",+ _uuid(944),+ _uuid(945),+ )+ assert sorted(+ (left_result.result, right_result.result), key=lambda item: item.value+ ) == [FixedResult.APPLIED, FixedResult.CONFLICT_REVISION]+ assert len(set(store.backend_pids)) == 2+ assert observer_pid not in set(store.backend_pids)+ assert (int(row["revision"]), int(receipt_count)) == (1, 1)+ finally:+ if observer is not None:+ await database._pool.release(observer)+ await database.close()+++async def test_postgres_p1a_cancellation_finishes_rollback_and_reuses_pool_slot(+ postgres_lifecycle_template: _MigrationHarness,+) -> None:+ async with _cloned_postgres_harness(postgres_lifecycle_template) as harness:+ database = PostgresDatabase(+ _migration_url(harness.config, harness.database_name), pool_min=1, pool_max=1+ )+ await database.connect()+ try:+ await _postgres_actor_authority_fixture(database)+ rollback_started = asyncio.Event()+ rollback_continue = asyncio.Event()+ pool = _PoolFaultSeam(+ database._pool,+ rollback_started=rollback_started,+ rollback_continue=rollback_continue,+ )+ store = _BlockingReceiptStore(pool)+ task = asyncio.create_task(store.invalidate_actor_authority(_uuid(940), 0, _uuid(946)))+ await asyncio.wait_for(store.receipt_entered.wait(), timeout=10)+ task.cancel()+ await asyncio.wait_for(rollback_started.wait(), timeout=10)+ task.cancel()+ rollback_continue.set()+ with pytest.raises(asyncio.CancelledError):+ await task+ assert pool.release_completed.is_set()+ async with database._pool.acquire() as observer:+ reused_pid = int(await observer.fetchval("SELECT pg_backend_pid()"))+ revision = await observer.fetchval(+ "SELECT revision FROM execution_actor_authority_revisions WHERE user_id=$1",+ _uuid(940),+ )+ receipts = await observer.fetchval(+ "SELECT count(*) FROM execution_operation_receipts WHERE operation_id=$1",+ _uuid(946),+ )+ assert reused_pid == store.backend_pid+ assert (int(revision), int(receipts)) == (0, 0)+ recovered = await ExecutionLifecycleStore(+ database._pool, "postgresql"+ ).invalidate_actor_authority(_uuid(940), 0, _uuid(947))+ assert recovered.result is FixedResult.APPLIED+ finally:+ await database.close()+++ "failure_point",+ ["transaction-rollback", "pool-release"],+ ids=("transaction-rollback", "pool-release"),+)+async def test_postgres_p1a_primary_failure_survives_cleanup_failure(+ failure_point: str,+ postgres_lifecycle_template: _MigrationHarness,+) -> None:+ async with _cloned_postgres_harness(postgres_lifecycle_template) as harness:+ database = PostgresDatabase(+ _migration_url(harness.config, harness.database_name), pool_min=1, pool_max=1+ )+ await database.connect()+ try:+ await _postgres_actor_authority_fixture(database)+ pool = _PoolFaultSeam(database._pool, failure_point=failure_point)+ primary = RuntimeError("P1_A_PRIMARY_FIXED")+ store = _PrimaryReceiptFailureStore(pool, primary)+ with pytest.raises(RuntimeError) as raised:+ await store.invalidate_actor_authority(_uuid(940), 0, _uuid(948))+ assert raised.value is primary+ assert "PRIVATE" not in str(raised.value)+ notes = tuple(getattr(raised.value, "__notes__", ()))+ expected_action = (+ "postgresql-rollback"+ if failure_point == "transaction-rollback"+ else "postgresql-release"+ )+ assert notes == (f"Execution lifecycle cleanup failed [{expected_action}]",)+ assert pool.release_completed.is_set()+ async with database._pool.acquire() as observer:+ reused_pid = int(await observer.fetchval("SELECT pg_backend_pid()"))+ revision = await observer.fetchval(+ "SELECT revision FROM execution_actor_authority_revisions WHERE user_id=$1",+ _uuid(940),+ )+ receipts = await observer.fetchval(+ "SELECT count(*) FROM execution_operation_receipts WHERE operation_id=$1",+ _uuid(948),+ )+ assert reused_pid == store.backend_pid+ assert (int(revision), int(receipts)) == (0, 0)+ finally:+ await database.close()+++_P1B_AUTHORITY_CASES = (+ ("actor-authority-ensure", "actor_authority_ensure"),+ ("campaign-authority-ensure", "campaign_authority_ensure"),+ ("actor-authority-invalidate", "actor_authority_invalidate"),+ ("campaign-authority-invalidate", "campaign_authority_invalidate"),+ ("budget-configure", "budget_configure"),+ ("budget-reserve", "budget_reserve"),+ ("budget-settle", "budget_settle"),+ ("admission", "admission"),+ ("retry-attempt", "retry"),+ ("attempt-transition", "queue"),+ ("settlement-pending", "settlement_pending"),+ ("expired-lease-settlement", "lease_loss"),+ ("terminal-commit", "terminal_failed"),+ ("close-without-retry", "close_without_retry"),+ ("outbox-claim", "outbox_claim"),+ ("outbox-reclaim", "outbox_reclaim"),+ ("outbox-poison", "outbox_poison"),+ ("outbox-renew", "outbox_renew"),+ ("outbox-publish", "outbox_publish"),+ ("outbox-fail-retryable", "outbox_retryable_failure"),+ ("outbox-fail-nonretryable", "outbox_nonretryable_failure"),+ ("outbox-purge", "outbox_purge"),+ ("campaign-delete", "campaign_delete"),+)++_POSTGRES_P1B_PUBLIC_METHOD_MAP = (+ ("actor-authority-ensure", "ExecutionLifecycleStore.ensure_actor_authority"),+ ("campaign-authority-ensure", "ExecutionLifecycleStore.ensure_campaign_authority"),+ ("actor-authority-invalidate", "ExecutionLifecycleStore.invalidate_actor_authority"),+ (+ "campaign-authority-invalidate",+ "ExecutionLifecycleStore.invalidate_campaign_authority",+ ),+ ("budget-configure", "ExecutionLifecycleStore.configure_campaign_budgets"),+ ("budget-reserve", "ExecutionLifecycleStore.reserve_budgets"),+ ("budget-settle", "ExecutionLifecycleStore.settle_budgets"),+ ("admission", "ExecutionLifecycleStore.create_initial_execution"),+ ("retry-attempt", "ExecutionLifecycleStore.create_retry_attempt"),+ ("attempt-transition", "ExecutionLifecycleStore.transition_attempt"),+ ("settlement-pending", "ExecutionLifecycleStore.enter_settlement_pending"),+ (+ "expired-lease-settlement",+ "ExecutionLifecycleStore.mark_expired_lease_settlement_pending",+ ),+ ("terminal-commit", "ExecutionLifecycleStore.commit_terminal_attempt"),+ ("close-without-retry", "ExecutionLifecycleStore.close_without_retry"),+ ("outbox-claim", "ExecutionLifecycleStore.claim_outbox"),+ ("outbox-reclaim", "ExecutionLifecycleStore.claim_outbox(reclaim=True)"),+ ("outbox-poison", "ExecutionLifecycleStore.poison_expired_attempt_twenty"),+ ("outbox-renew", "ExecutionLifecycleStore.renew_outbox"),+ ("outbox-publish", "ExecutionLifecycleStore.publish_outbox"),+ ("outbox-fail-retryable", "ExecutionLifecycleStore.fail_outbox(retryable=True)"),+ (+ "outbox-fail-nonretryable",+ "ExecutionLifecycleStore.fail_outbox(retryable=False)",+ ),+ ("outbox-purge", "ExecutionLifecycleStore.purge_outbox"),+ ("campaign-delete", "PostgresDatabase.delete_campaign_lifecycle"),+)++_P1B_BINDING_MUTATIONS = (+ "operation-code-transition",+ "primary-target-transition",+ "secondary-target-retry",+ "campaign-transition",+ "principal-kind-transition",+ "principal-subject-transition",+ "principal-user-transition",+ "principal-authority-revision-transition",+ "expected-revision-presence-transition",+ "expected-revision-value-transition",+ "secondary-expected-presence-budget",+ "secondary-expected-value-budget",+ "owner-presence-outbox",+ "lease-generation-outbox",+ "canonical-request-payload-terminal",+ "canonical-request-payload-budget",+ "submission-operation-id",+ "submission-actor-request",+)++_P1B_RETENTION_CASES = (+ "submission-lookup-precedes-gateway",+ "submission-replay-after-state-advance",+ "submission-changed-request-conflict",+ "receipt-update-rejected",+ "receipt-delete-rejected",+ "receipt-survives-campaign-delete",+ "receipt-survives-target-delete",+ "stored-result-independent-of-mutable-target",+)++_P1B_ATOMICITY_CASES = (+ "shared-authority-receipt-insert-rollback",+ "shared-budget-receipt-insert-rollback",+ "shared-admission-binding-insert-rollback",+ "shared-retry-receipt-insert-rollback",+ "shared-transition-receipt-insert-rollback",+ "shared-terminal-receipt-insert-rollback",+ "shared-outbox-receipt-insert-rollback",+ "shared-purge-receipt-insert-rollback",+ "shared-campaign-delete-receipt-insert-rollback",+ "exact-replay-no-duplicate-side-effects",+)++_P1B_CONCURRENCY_CASES = (+ "shared-submission-identical",+ "shared-authority-identical",+ "shared-transition-identical",+ "shared-budget-identical",+ "shared-outbox-identical",+ "shared-campaign-delete-identical",+)++_POSTGRES_P1B_LITERAL_NODE_COUNT = 88+_POSTGRES_P1B_LITERAL_NODE_ID_SHA256 = (+ "dcf4cc9ae54a5bc5c793215f42318b1fbb19f826563dc2ae3314c7302c687aa6"+)++assert len(_P1B_AUTHORITY_CASES) == 23+assert len({alias for alias, _operation_code in _P1B_AUTHORITY_CASES}) == 23+assert tuple(alias for alias, _method in _POSTGRES_P1B_PUBLIC_METHOD_MAP) == tuple(+ alias for alias, _operation_code in _P1B_AUTHORITY_CASES+)+assert (+ _POSTGRES_P1B_LITERAL_NODE_COUNT,+ len(_POSTGRES_P1B_LITERAL_NODE_ID_SHA256),+) == (88, 64)+assert (+ sum(+ map(+ len,+ (+ _P1B_AUTHORITY_CASES,+ _P1B_AUTHORITY_CASES,+ _P1B_BINDING_MUTATIONS,+ _P1B_RETENTION_CASES,+ _P1B_ATOMICITY_CASES,+ _P1B_CONCURRENCY_CASES,+ ),+ )+ )+ == _POSTGRES_P1B_LITERAL_NODE_COUNT+)+++def _postgres_p1b_independent_binding_digest(+ domain: str, values: tuple[tuple[str, str | int | bool | None], ...]+) -> str:+ encoded = bytearray(b"ares.execution-operation-binding.v2\x00")++ def frame(value: bytes) -> None:+ encoded.extend(struct.pack(">I", len(value)))+ encoded.extend(value)++ frame(domain.encode("ascii"))+ for name, value in values:+ frame(name.encode("ascii"))+ if value is None:+ encoded.extend(b"n")+ elif type(value) is bool:+ encoded.extend(b"b\x01" if value else b"b\x00")+ elif type(value) is int:+ encoded.extend(b"i")+ frame(value.to_bytes(8, "big"))+ else:+ encoded.extend(b"s")+ frame(value.encode("utf-8"))+ return hashlib.sha256(encoded).hexdigest()+++def _postgres_p1b_independent_request_digest(operation_code: str) -> str:+ no_revision = operation_code in {+ "actor_authority_ensure",+ "campaign_authority_ensure",+ "budget_configure",+ "admission",+ "outbox_insert",+ "campaign_delete",+ }+ dual_revision = operation_code in {"budget_reserve", "budget_settle"}+ owner_bound = operation_code in {+ "outbox_claim",+ "outbox_reclaim",+ "outbox_renew",+ "outbox_publish",+ "outbox_retryable_failure",+ "outbox_nonretryable_failure",+ }+ return _postgres_p1b_independent_binding_digest(+ operation_code + ".request",+ (+ ("operation_id", _uuid(3000)),+ ("operation_code", operation_code),+ ("campaign_id_present", True),+ ("campaign_id", _uuid(3002)),+ ("primary_target_id", _uuid(3001)),+ ("secondary_target_id_present", True),+ ("secondary_target_id", _uuid(3003)),+ ("principal_kind", "actor"),+ ("principal_subject_ref", _uuid(3004)),+ ("principal_user_id_present", True),+ ("principal_user_id", _uuid(3004)),+ ("principal_authority_revision_present", True),+ ("principal_authority_revision", 7),+ ("expected_revision_present", not no_revision),+ ("expected_revision", None if no_revision else 9),+ ("secondary_expected_revision_present", dual_revision),+ ("secondary_expected_revision", 11 if dual_revision else None),+ ("owner_ref_present", owner_bound),+ ("owner_ref", _uuid(3005) if owner_bound else None),+ ("lease_generation_present", owner_bound),+ ("lease_generation", 3 if owner_bound else None),+ ("literal_payload", "p1b"),+ ),+ )+++def _postgres_p1b_literal_spec(+ store: ExecutionLifecycleStore,+ operation_code: str,+ *,+ operation_id: str = _uuid(3000),+):+ no_revision = operation_code in {+ "actor_authority_ensure",+ "campaign_authority_ensure",+ "budget_configure",+ "admission",+ "outbox_insert",+ "campaign_delete",+ }+ dual_revision = operation_code in {"budget_reserve", "budget_settle"}+ owner_bound = operation_code in {+ "outbox_claim",+ "outbox_reclaim",+ "outbox_renew",+ "outbox_publish",+ "outbox_retryable_failure",+ "outbox_nonretryable_failure",+ }+ return store._receipt_spec(+ operation_id=operation_id,+ operation_code=operation_code,+ campaign_id=_uuid(3002),+ primary_target_id=_uuid(3001),+ secondary_target_id=_uuid(3003),+ principal_kind="actor",+ principal_subject_ref=_uuid(3004),+ principal_user_id=_uuid(3004),+ principal_authority_revision=7,+ expected_revision=None if no_revision else 9,+ secondary_expected_revision=11 if dual_revision else None,+ owner_ref=_uuid(3005) if owner_bound else None,+ lease_generation=3 if owner_bound else None,+ fields=(("literal_payload", "p1b"),),+ )+++async def _postgres_p1b_insert_receipt(store: ExecutionLifecycleStore, operation_code: str):+ spec = _postgres_p1b_literal_spec(store, operation_code)+ exact = (+ FixedResult.REPLAYED_BOUND_CHILD+ if operation_code == "retry"+ else FixedResult.REPLAYED_CLOSED+ if operation_code == "close_without_retry"+ else FixedResult.REPLAYED+ )+ async with store._transaction() as connection:+ await store._insert_receipt(+ connection,+ spec,+ result=FixedResult.APPLIED,+ exact_replay_code=exact,+ result_identity=_uuid(3001),+ result_revision=10,+ )+ return spec+++async def _postgres_p1b_effect_snapshot(+ database: PostgresDatabase, operation_id: str+) -> tuple[int, ...]:+ async with database._pool.acquire() as connection:+ row = await connection.fetchrow(+ "SELECT "+ "(SELECT count(*) FROM execution_operation_receipts),"+ "(SELECT count(*) FROM execution_operation_receipts WHERE operation_id=$1),"+ "(SELECT count(*) FROM execution_actor_authority_revisions),"+ "(SELECT COALESCE(sum(revision),0) FROM execution_actor_authority_revisions),"+ "(SELECT count(*) FROM campaign_execution_authority_revisions),"+ "(SELECT COALESCE(sum(revision),0) FROM campaign_execution_authority_revisions),"+ "(SELECT count(*) FROM campaign_execution_budgets),"+ "(SELECT COALESCE(sum(capacity_units),0) FROM campaign_execution_budgets),"+ "(SELECT COALESCE(sum(reserved_units),0) FROM campaign_execution_budgets),"+ "(SELECT COALESCE(sum(consumed_units),0) FROM campaign_execution_budgets),"+ "(SELECT COALESCE(sum(revision),0) FROM campaign_execution_budgets),"+ "(SELECT count(*) FROM campaign_execution_budget_ledger),"+ "(SELECT COALESCE(sum(reservation_units),0) "+ " FROM campaign_execution_budget_ledger),"+ "(SELECT COALESCE(sum(consumed_units),0) "+ " FROM campaign_execution_budget_ledger),"+ "(SELECT count(*) FROM logical_executions),"+ "(SELECT COALESCE(sum(revision),0) FROM logical_executions),"+ "(SELECT count(*) FROM execution_attempts),"+ "(SELECT COALESCE(sum(revision),0) FROM execution_attempts),"+ "(SELECT count(*) FROM execution_publication_outbox),"+ "(SELECT COALESCE(sum(claim_revision),0) FROM execution_publication_outbox),"+ "(SELECT COALESCE(sum(delivery_attempt_count),0) "+ " FROM execution_publication_outbox),"+ "(SELECT count(*) FROM campaigns)",+ operation_id,+ )+ return tuple(int(value) for value in row)+++async def _postgres_p1b_insert_principal(+ database: PostgresDatabase, *, role: str = "reporter"+) -> ExecutionLifecycleStore:+ async with database._pool.acquire() as connection:+ await connection.execute(+ "INSERT INTO users(id,username,hashed_password,role,created_by) "+ "VALUES($1,'p1b-public-user','fixed-hash',$2,'fixed')",+ _uuid(3400),+ role,+ )+ await connection.execute(+ "INSERT INTO campaigns(id,name) VALUES($1,'p1b-public-campaign')",+ _uuid(3401),+ )+ return ExecutionLifecycleStore(database._pool, "postgresql")+++async def _postgres_p1b_ensure_principal(+ database: PostgresDatabase, *, role: str = "reporter"+) -> ExecutionLifecycleStore:+ store = await _postgres_p1b_insert_principal(database, role=role)+ actor = await store.ensure_actor_authority(_uuid(3400), _uuid(3480))+ campaign = await store.ensure_campaign_authority(_uuid(3401), _uuid(3481))+ assert (actor.result, campaign.result) == (FixedResult.APPLIED, FixedResult.APPLIED)+ return store+++def _postgres_p1b_blocked_admission(operation_id: str) -> AdmissionRequest:+ return AdmissionRequest(+ _uuid(3410),+ _uuid(3411),+ _uuid(3412),+ _uuid(3413),+ _uuid(3414),+ _uuid(3401),+ _uuid(3400),+ _uuid(3400),+ "test.p1b-public",+ "sdk",+ AttemptState.BLOCKED,+ operation_id,+ _blocked_snapshot(),+ )+++def _postgres_p1b_budget_configuration(operation_id: str) -> BudgetConfiguration:+ return BudgetConfiguration(+ _uuid(3401),+ _uuid(3420),+ 20,+ _uuid(3421),+ 20,+ _uuid(3422),+ 1,+ operation_id,+ )+++def _postgres_p1b_budget_reservation(operation_id: str) -> BudgetReservation:+ return BudgetReservation(+ _uuid(3401),+ _uuid(3412),+ _uuid(3420),+ _uuid(3423),+ 2,+ 0,+ _uuid(3421),+ _uuid(3424),+ 3,+ 0,+ _uuid(3422),+ _uuid(3425),+ 0,+ operation_id,+ )+++def _postgres_p1b_budget_settlement(operation_id: str) -> BudgetSettlement:+ return BudgetSettlement(+ _uuid(3401),+ _uuid(3412),+ _uuid(3420),+ 2,+ 1,+ 1,+ _uuid(3421),+ 3,+ 2,+ 1,+ _uuid(3422),+ 1,+ operation_id,+ )+++async def _postgres_p1b_prepare_budget_attempt(+ database: PostgresDatabase,+) -> ExecutionLifecycleStore:+ store = await _postgres_p1b_ensure_principal(database)+ configured = await store.configure_campaign_budgets(+ _postgres_p1b_budget_configuration(_uuid(3482))+ )+ admitted = await store._create_initial_execution_v2_for_migration_fixture(+ _postgres_p1b_blocked_admission(_uuid(3483))+ )+ assert (configured.result, admitted.result) == (+ FixedResult.APPLIED,+ FixedResult.APPLIED,+ )+ return store+++async def _postgres_p1b_prepare_retryable_parent(+ database: PostgresDatabase,+) -> tuple[ExecutionLifecycleStore, int]:+ snapshot = replace(+ _accepted_snapshot(),+ actor_role="admin",+ idempotency_class="proven_idempotent",+ retry_policy="after_revalidation",+ )+ store, adapter, connection = await _postgres_transition_case(+ database,+ AttemptState.ACCEPTED,+ snapshot_override=snapshot,+ )+ try:+ terminal = await _terminal_transition(store, adapter, AttemptState.FAILED, 3470)+ assert terminal.result is FixedResult.APPLIED+ async with connection.transaction():+ await connection.execute(+ "UPDATE execution_attempts SET closes_logical=FALSE,"+ "retry_disposition='eligible' WHERE id=$1",+ _uuid(210),+ )+ await connection.execute(+ "UPDATE logical_executions SET closure_operation_id=NULL,"+ "closure_authority_subject_ref=NULL,closure_authority_user_id=NULL,"+ "closure_authority_revision=NULL,closing_attempt_id=NULL,closed_at=NULL "+ "WHERE id=$1",+ _uuid(208),+ )+ row = await connection.fetchrow(+ "SELECT revision,retry_disposition FROM execution_attempts WHERE id=$1",+ _uuid(210),+ )+ assert row["retry_disposition"] == "eligible"+ return store, int(row["revision"])+ finally:+ await database._pool.release(connection)+++async def _postgres_p1b_prepare_outbox(+ database: PostgresDatabase,+) -> ExecutionLifecycleStore:+ store, _adapter, connection = await _postgres_transition_case(database, AttemptState.BLOCKED)+ await database._pool.release(connection)+ return store+++async def _postgres_p1b_admission_case(+ database: PostgresDatabase,+) -> tuple[ExecutionLifecycleStore, AdmissionRequest]:+ store = await _postgres_p1b_ensure_principal(database)+ request = _postgres_p1b_blocked_admission(_uuid(3490))+ applied = await store._create_initial_execution_v2_for_migration_fixture(request)+ assert applied.result is FixedResult.APPLIED+ return store, request+++def _postgres_p1b_outbox_request(+ operation_id: str,+ expected_revision: int,+ *,+ owner_ref: str | None,+ lease_generation: int | None,+ purge_poisoned: bool | None = None,+) -> OutboxMutation:+ return OutboxMutation(+ _uuid(212),+ expected_revision,+ operation_id,+ owner_ref,+ lease_generation,+ _uuid(201),+ _uuid(210),+ _uuid(213),+ "execution_blocked",+ purge_poisoned,+ )+++_POSTGRES_P1B_PUBLIC_OPERATION_IDS = {+ alias: _uuid(3600 + index)+ for index, (alias, _operation_code) in enumerate(_P1B_AUTHORITY_CASES)+}+++async def _postgres_p1b_exercise_public_operation(+ case_alias: str,+ database: PostgresDatabase,+) -> tuple[+ OperationResult,+ OperationResult,+ OperationResult,+ tuple[int, ...],+ tuple[int, ...],+ tuple[int, ...],+ str,+]:+ operation_id = _POSTGRES_P1B_PUBLIC_OPERATION_IDS[case_alias]++ if case_alias == "actor-authority-ensure":+ store = await _postgres_p1b_insert_principal(database)++ async def invoke() -> OperationResult:+ return await store.ensure_actor_authority(_uuid(3400), operation_id)++ async def invoke_conflict() -> OperationResult:+ return await store.ensure_actor_authority(_uuid(3402), operation_id)++ elif case_alias == "campaign-authority-ensure":+ store = await _postgres_p1b_insert_principal(database)++ async def invoke() -> OperationResult:+ return await store.ensure_campaign_authority(_uuid(3401), operation_id)++ async def invoke_conflict() -> OperationResult:+ return await store.ensure_campaign_authority(_uuid(3402), operation_id)++ elif case_alias == "actor-authority-invalidate":+ store = await _postgres_p1b_insert_principal(database)+ setup = await store.ensure_actor_authority(_uuid(3400), _uuid(3480))+ assert setup.result is FixedResult.APPLIED++ async def invoke() -> OperationResult:+ return await store.invalidate_actor_authority(_uuid(3400), 0, operation_id)++ async def invoke_conflict() -> OperationResult:+ return await store.invalidate_actor_authority(_uuid(3400), 1, operation_id)++ elif case_alias == "campaign-authority-invalidate":+ store = await _postgres_p1b_insert_principal(database)+ setup = await store.ensure_campaign_authority(_uuid(3401), _uuid(3481))+ assert setup.result is FixedResult.APPLIED++ async def invoke() -> OperationResult:+ return await store.invalidate_campaign_authority(_uuid(3401), 0, operation_id)++ async def invoke_conflict() -> OperationResult:+ return await store.invalidate_campaign_authority(_uuid(3401), 1, operation_id)++ elif case_alias == "budget-configure":+ store = await _postgres_p1b_ensure_principal(database)+ request = _postgres_p1b_budget_configuration(operation_id)++ async def invoke() -> OperationResult:+ return await store.configure_campaign_budgets(request)++ async def invoke_conflict() -> OperationResult:+ return await store.configure_campaign_budgets(+ replace(request, noise_capacity=request.noise_capacity + 1)+ )++ elif case_alias == "budget-reserve":+ store = await _postgres_p1b_prepare_budget_attempt(database)+ request = _postgres_p1b_budget_reservation(operation_id)++ async def invoke() -> OperationResult:+ return await store.reserve_budgets(request)++ async def invoke_conflict() -> OperationResult:+ return await store.reserve_budgets(+ replace(request, noise_units=request.noise_units + 1)+ )++ elif case_alias == "budget-settle":+ store = await _postgres_p1b_prepare_budget_attempt(database)+ reserved = await store.reserve_budgets(_postgres_p1b_budget_reservation(_uuid(3484)))+ assert reserved.result is FixedResult.APPLIED+ request = _postgres_p1b_budget_settlement(operation_id)++ async def invoke() -> OperationResult:+ return await store.settle_budgets(request)++ async def invoke_conflict() -> OperationResult:+ return await store.settle_budgets(+ replace(request, noise_actual=request.noise_actual + 1)+ )++ elif case_alias == "admission":+ store = await _postgres_p1b_ensure_principal(database)+ request = _postgres_p1b_blocked_admission(operation_id)++ async def invoke() -> OperationResult:+ return await store._create_initial_execution_v2_for_migration_fixture(request)++ async def invoke_conflict() -> OperationResult:+ return await store._create_initial_execution_v2_for_migration_fixture(+ replace(request, module_id="test.p1b-public.changed")+ )++ elif case_alias == "retry-attempt":+ store, parent_revision = await _postgres_p1b_prepare_retryable_parent(database)+ async with database._pool.acquire() as connection:+ await connection.execute("UPDATE users SET role='reporter' WHERE id=$1", _uuid(200))+ child = AdmissionRequest(+ _uuid(208),+ _uuid(3440),+ _uuid(3441),+ _uuid(3442),+ _uuid(3443),+ _uuid(201),+ _uuid(200),+ _uuid(200),+ "test.p1b-retry",+ "sdk",+ AttemptState.BLOCKED,+ operation_id,+ replace(_blocked_snapshot(), gateway_mode_snapshot="enforced"),+ )+ request = RetryRequest(_uuid(208), _uuid(210), child, parent_revision)++ async def invoke() -> OperationResult:+ return await store._create_retry_attempt_v2_for_migration_fixture(request)++ async def invoke_conflict() -> OperationResult:+ return await store._create_retry_attempt_v2_for_migration_fixture(+ replace(request, child=replace(child, module_id="test.p1b-retry.changed"))+ )++ elif case_alias == "attempt-transition":+ store, _adapter, connection = await _postgres_transition_case(+ database, AttemptState.ACCEPTED+ )+ await database._pool.release(connection)+ request = TransitionRequest(+ _uuid(210),+ 0,+ AttemptState.QUEUED,+ operation_id,+ campaign_id=_uuid(201),+ actor_subject_ref=_uuid(200),+ actor_user_id=_uuid(200),+ actor_authority_revision=0,+ )++ async def invoke() -> OperationResult:+ return await store.transition_attempt(request)++ async def invoke_conflict() -> OperationResult:+ return await store.transition_attempt(replace(request, campaign_id=_uuid(299)))++ elif case_alias in {"settlement-pending", "expired-lease-settlement"}:+ store, adapter, connection = await _postgres_transition_case(+ database, AttemptState.ACCEPTED+ )+ try:+ await _build_source_state(store, adapter, AttemptState.RUNNING)+ row = await connection.fetchrow(+ "SELECT revision,dispatch_owner_ref,lease_generation "+ "FROM execution_attempts WHERE id=$1",+ _uuid(210),+ )+ if case_alias == "expired-lease-settlement":+ await connection.execute(+ "UPDATE execution_attempts SET lease_expires_at=created_at WHERE id=$1",+ _uuid(210),+ )+ finally:+ await database._pool.release(connection)+ request = TransitionRequest(+ _uuid(210),+ int(row["revision"]),+ AttemptState.SETTLEMENT_PENDING,+ operation_id,+ owner_ref=str(row["dispatch_owner_ref"]),+ lease_generation=int(row["lease_generation"]),+ outbox_id=_uuid(3450),+ publication_key=_uuid(3451),+ campaign_id=_uuid(201),+ )++ async def invoke() -> OperationResult:+ if case_alias == "expired-lease-settlement":+ return await store.mark_expired_lease_settlement_pending(request)+ return await store.enter_settlement_pending(request)++ async def invoke_conflict() -> OperationResult:+ changed = replace(request, publication_key=_uuid(3452))+ if case_alias == "expired-lease-settlement":+ return await store.mark_expired_lease_settlement_pending(changed)+ return await store.enter_settlement_pending(changed)++ elif case_alias == "terminal-commit":+ store, _adapter, connection = await _postgres_transition_case(+ database, AttemptState.ACCEPTED+ )+ await database._pool.release(connection)+ transition = TransitionRequest(+ _uuid(210),+ 0,+ AttemptState.FAILED,+ operation_id,+ outcome_code=OutcomeCode.CONFIRMED_FAILURE_NO_DISPATCH,+ authoritative_proof="no_dispatch",+ campaign_id=_uuid(201),+ actor_subject_ref=_uuid(200),+ actor_user_id=_uuid(200),+ actor_authority_revision=0,+ )+ settlement = BudgetSettlement(+ _uuid(201),+ _uuid(210),+ _uuid(204),+ 2,+ 0,+ 1,+ _uuid(205),+ 3,+ 0,+ 1,+ _uuid(206),+ 1,+ _uuid(3453),+ )+ request = TerminalCommitRequest(+ _uuid(208),+ _uuid(201),+ _uuid(3454),+ _uuid(3455),+ transition,+ settlement,+ )++ async def invoke() -> OperationResult:+ return await store.commit_terminal_attempt(request)++ async def invoke_conflict() -> OperationResult:+ return await store.commit_terminal_attempt(+ replace(request, publication_key=_uuid(3456))+ )++ elif case_alias == "close-without-retry":+ store, parent_revision = await _postgres_p1b_prepare_retryable_parent(database)+ request = ClosureRequest(+ _uuid(208),+ _uuid(210),+ _uuid(3457),+ parent_revision,+ operation_id,+ _uuid(200),+ _uuid(200),+ 0,+ _uuid(201),+ )++ async def invoke() -> OperationResult:+ return await store.close_without_retry(request)++ async def invoke_conflict() -> OperationResult:+ return await store.close_without_retry(replace(request, outbox_id=_uuid(3458)))++ elif case_alias.startswith("outbox-"):+ store = await _postgres_p1b_prepare_outbox(database)+ setup_owner = _uuid(3460)+ if case_alias == "outbox-claim":+ request = _postgres_p1b_outbox_request(+ operation_id, 0, owner_ref=_uuid(3461), lease_generation=0+ )++ async def invoke() -> OperationResult:+ return await store.claim_outbox(request)++ elif case_alias == "outbox-reclaim":+ setup_claim = await store.claim_outbox(+ _postgres_p1b_outbox_request(+ _uuid(3462), 0, owner_ref=setup_owner, lease_generation=0+ )+ )+ assert setup_claim.result is FixedResult.APPLIED+ async with database._pool.acquire() as connection:+ await connection.execute(+ "UPDATE execution_publication_outbox SET lease_expires_at=created_at "+ "WHERE id=$1",+ _uuid(212),+ )+ request = _postgres_p1b_outbox_request(+ operation_id, 1, owner_ref=_uuid(3461), lease_generation=1+ )++ async def invoke() -> OperationResult:+ return await store.claim_outbox(request, reclaim=True)++ elif case_alias == "outbox-poison":+ async with database._pool.acquire() as connection:+ await connection.execute(+ "UPDATE execution_publication_outbox SET "+ "publication_state='claimed',delivery_attempt_count=20,available_at=NULL,"+ "claim_owner_ref=$1,lease_generation=20,claimed_at=created_at,"+ "lease_expires_at=created_at,"+ "claim_revision=20,latest_operation_id=$2,latest_operation_code='reclaim',"+ "latest_operation_base_revision=19 WHERE id=$3",+ setup_owner,+ _uuid(3462),+ _uuid(212),+ )+ request = _postgres_p1b_outbox_request(+ operation_id, 20, owner_ref=None, lease_generation=None+ )++ async def invoke() -> OperationResult:+ return await store.poison_expired_attempt_twenty(request)++ elif case_alias in {+ "outbox-renew",+ "outbox-publish",+ "outbox-fail-retryable",+ "outbox-fail-nonretryable",+ }:+ setup_claim = await store.claim_outbox(+ _postgres_p1b_outbox_request(+ _uuid(3462), 0, owner_ref=setup_owner, lease_generation=0+ )+ )+ assert setup_claim.result is FixedResult.APPLIED+ request = _postgres_p1b_outbox_request(+ operation_id, 1, owner_ref=setup_owner, lease_generation=1+ )++ async def invoke() -> OperationResult:+ if case_alias == "outbox-renew":+ return await store.renew_outbox(request)+ if case_alias == "outbox-publish":+ return await store.publish_outbox(request)+ return await store.fail_outbox(+ request, retryable=case_alias == "outbox-fail-retryable"+ )++ else:+ assert case_alias == "outbox-purge"+ setup_claim = await store.claim_outbox(+ _postgres_p1b_outbox_request(+ _uuid(3462), 0, owner_ref=setup_owner, lease_generation=0+ )+ )+ published = await store.publish_outbox(+ _postgres_p1b_outbox_request(+ _uuid(3463), 1, owner_ref=setup_owner, lease_generation=1+ )+ )+ assert (setup_claim.result, published.result) == (+ FixedResult.APPLIED,+ FixedResult.APPLIED,+ )+ request = _postgres_p1b_outbox_request(+ operation_id,+ 2,+ owner_ref=None,+ lease_generation=None,+ purge_poisoned=False,+ )++ async def invoke() -> OperationResult:+ return await store.purge_outbox(+ request.outbox_id,+ request.expected_revision,+ request.operation_id,+ poisoned=False,+ campaign_id=request.campaign_id,+ attempt_id=request.attempt_id,+ publication_key=request.publication_key,+ event_code=request.event_code,+ )++ async def invoke_conflict() -> OperationResult:+ changed = replace(request, event_code="execution_rejected")+ if case_alias == "outbox-claim":+ return await store.claim_outbox(changed)+ if case_alias == "outbox-reclaim":+ return await store.claim_outbox(changed, reclaim=True)+ if case_alias == "outbox-poison":+ return await store.poison_expired_attempt_twenty(changed)+ if case_alias == "outbox-renew":+ return await store.renew_outbox(changed)+ if case_alias == "outbox-publish":+ return await store.publish_outbox(changed)+ if case_alias == "outbox-fail-retryable":+ return await store.fail_outbox(changed, retryable=True)+ if case_alias == "outbox-fail-nonretryable":+ return await store.fail_outbox(changed, retryable=False)+ return await store.purge_outbox(+ changed.outbox_id,+ changed.expected_revision,+ changed.operation_id,+ poisoned=False,+ campaign_id=changed.campaign_id,+ attempt_id=changed.attempt_id,+ publication_key=changed.publication_key,+ event_code=changed.event_code,+ )++ else:+ assert case_alias == "campaign-delete"+ async with database._pool.acquire() as connection:+ await connection.execute(+ "INSERT INTO campaigns(id,name) VALUES($1,'p1b-delete-campaign')",+ _uuid(3401),+ )++ async def invoke() -> OperationResult:+ return await database.delete_campaign_lifecycle(_uuid(3401), operation_id=operation_id)++ async def invoke_conflict() -> OperationResult:+ return await database.delete_campaign_lifecycle(+ _uuid(3401),+ operation_id=operation_id,+ principal_kind="actor",+ principal_subject_ref=_uuid(3400),+ principal_user_id=_uuid(3400),+ principal_authority_revision=0,+ )++ applied = await invoke()+ after_applied = await _postgres_p1b_effect_snapshot(database, operation_id)+ replayed = await invoke()+ after_replayed = await _postgres_p1b_effect_snapshot(database, operation_id)+ conflicted = await invoke_conflict()+ after_conflicted = await _postgres_p1b_effect_snapshot(database, operation_id)+ async with database._pool.acquire() as connection:+ if case_alias == "admission":+ submission = await connection.fetchrow(+ "SELECT admission_operation_id,submission_binding_contract_version,"+ "submission_result_code,submission_exact_replay_code "+ "FROM logical_executions WHERE campaign_id=$1 AND submission_id=$2",+ request.campaign_id,+ request.submission_id,+ )+ receipt_count = int(+ await connection.fetchval(+ "SELECT count(*) FROM execution_operation_receipts WHERE operation_id=$1",+ operation_id,+ )+ )+ assert tuple(submission.values()) == (+ operation_id,+ 2,+ FixedResult.APPLIED.value,+ FixedResult.REPLAYED.value,+ )+ assert receipt_count == 0+ recorded_operation_code = "admission"+ else:+ recorded_operation_code = str(+ await connection.fetchval(+ "SELECT operation_code FROM execution_operation_receipts WHERE operation_id=$1",+ operation_id,+ )+ )+ return (+ applied,+ replayed,+ conflicted,+ after_applied,+ after_replayed,+ after_conflicted,+ recorded_operation_code,+ )+++ ("_case_alias", "operation_code"),+ _P1B_AUTHORITY_CASES,+ ids=tuple(alias for alias, _code in _P1B_AUTHORITY_CASES),+)+def test_postgres_p1b_independent_literal_binding_vector(+ _case_alias: str, operation_code: str+) -> None:+ store = ExecutionLifecycleStore(None, "postgresql")+ spec = _postgres_p1b_literal_spec(store, operation_code)+ assert spec.request_binding_digest == _postgres_p1b_independent_request_digest(operation_code)+++ ("_case_alias", "operation_code"),+ _P1B_AUTHORITY_CASES,+ ids=tuple(alias for alias, _code in _P1B_AUTHORITY_CASES),+)+async def test_postgres_p1b_each_public_authority_replays_exactly(+ _case_alias: str,+ operation_code: str,+ postgres_lifecycle_template: _MigrationHarness,+) -> None:+ async with _cloned_postgres_harness(postgres_lifecycle_template) as harness:+ database = PostgresDatabase(_migration_url(harness.config, harness.database_name))+ await database.connect()+ try:+ (+ applied,+ replayed,+ conflicted,+ after_applied,+ after_replayed,+ after_conflicted,+ recorded_operation_code,+ ) = await _postgres_p1b_exercise_public_operation(_case_alias, database)+ finally:+ await database.close()+ expected_replay = (+ FixedResult.REPLAYED_BOUND_CHILD+ if operation_code == "retry"+ else FixedResult.REPLAYED_CLOSED+ if operation_code == "close_without_retry"+ else FixedResult.REPLAYED+ )+ assert applied.result is FixedResult.APPLIED+ assert replayed.result is expected_replay+ assert conflicted.result is FixedResult.CONFLICT_OPERATION+ assert after_applied == after_replayed == after_conflicted+ assert after_applied[1] == (0 if _case_alias == "admission" else 1)+ assert recorded_operation_code == operation_code++[email protected]("case_alias", _P1B_BINDING_MUTATIONS, ids=_P1B_BINDING_MUTATIONS)+async def test_postgres_p1b_each_binding_mutation_conflicts(+ case_alias: str, postgres_lifecycle_template: _MigrationHarness+) -> None:+ async with _cloned_postgres_harness(postgres_lifecycle_template) as harness:+ database = PostgresDatabase(_migration_url(harness.config, harness.database_name))+ await database.connect()+ try:+ if case_alias.startswith("submission-"):+ store, request = await _postgres_p1b_admission_case(database)+ changed_request = (+ replace(request, operation_id=_uuid(3491))+ if case_alias == "submission-operation-id"+ else replace(request, actor_subject_ref=_uuid(3492))+ )+ result = await store._create_initial_execution_v2_for_migration_fixture(+ changed_request+ )+ assert result.result is FixedResult.CONFLICT_OPERATION+ return+ store = ExecutionLifecycleStore(database._pool, "postgresql")+ operation_code = (+ "budget_reserve"+ if case_alias.startswith("secondary-expected-")+ else "outbox_claim"+ if case_alias == "lease-generation-outbox"+ else "outbox_poison"+ if case_alias == "owner-presence-outbox"+ else "terminal_failed"+ if case_alias == "canonical-request-payload-terminal"+ else "budget_configure"+ if case_alias == "canonical-request-payload-budget"+ else "queue"+ )+ spec = await _postgres_p1b_insert_receipt(store, operation_code)+ mutations = {+ "operation-code-transition": {"operation_code": "dispatch"},+ "primary-target-transition": {"primary_target_id": _uuid(3010)},+ "secondary-target-retry": {"secondary_target_id": _uuid(3011)},+ "campaign-transition": {"campaign_id": _uuid(3012)},+ "principal-kind-transition": {"principal_kind": "resolver"},+ "principal-subject-transition": {"principal_subject_ref": _uuid(3013)},+ "principal-user-transition": {"principal_user_id": _uuid(3014)},+ "principal-authority-revision-transition": {"principal_authority_revision": 8},+ "expected-revision-presence-transition": {"expected_revision": None},+ "expected-revision-value-transition": {"expected_revision": 10},+ "secondary-expected-presence-budget": {"secondary_expected_revision": None},+ "secondary-expected-value-budget": {"secondary_expected_revision": 12},+ "owner-presence-outbox": {"owner_ref": _uuid(3015), "lease_generation": 1},+ "lease-generation-outbox": {"lease_generation": 2},+ "canonical-request-payload-terminal": {"request_binding_digest": "a" * 64},+ "canonical-request-payload-budget": {"request_binding_digest": "b" * 64},+ }+ changed = replace(spec, **mutations[case_alias])+ async with store._transaction() as connection:+ result = await store._classify_receipt(connection, changed, current_revision=None)+ finally:+ await database.close()+ assert (result.result, result.revision) == (FixedResult.CONFLICT_OPERATION, None)++[email protected]("case_alias", _P1B_RETENTION_CASES, ids=_P1B_RETENTION_CASES)+async def test_postgres_p1b_submission_and_receipt_retention_contract(+ case_alias: str, postgres_lifecycle_template: _MigrationHarness+) -> None:+ async with _cloned_postgres_harness(postgres_lifecycle_template) as harness:+ database = PostgresDatabase(_migration_url(harness.config, harness.database_name))+ await database.connect()+ try:+ if case_alias.startswith("submission-"):+ store, request = await _postgres_p1b_admission_case(database)+ if case_alias == "submission-lookup-precedes-gateway":+ async with database._pool.acquire() as connection:+ await connection.execute(+ "UPDATE execution_gateway_state "+ "SET mode='emergency_disabled',catalog_digest=repeat('c',64),"+ "activation_revision=1,activation_at=updated_at,"+ "revision=revision+1 WHERE singleton_id=1"+ )+ candidate = request+ elif case_alias == "submission-replay-after-state-advance":+ async with database._pool.acquire() as connection:+ await connection.execute(+ "UPDATE logical_executions SET revision=revision+1 WHERE id=$1",+ request.logical_execution_id,+ )+ candidate = request+ else:+ candidate = replace(request, module_id="test.p1b.changed")+ result = await store._create_initial_execution_v2_for_migration_fixture(candidate)+ assert result.result is (+ FixedResult.CONFLICT_OPERATION+ if case_alias == "submission-changed-request-conflict"+ else FixedResult.REPLAYED+ )+ return+ store = ExecutionLifecycleStore(database._pool, "postgresql")+ spec = await _postgres_p1b_insert_receipt(store, "outbox_purge")+ if case_alias == "receipt-update-rejected":+ with pytest.raises(asyncpg.PostgresError) as raised:+ async with database._pool.acquire() as connection:+ await connection.execute(+ "UPDATE execution_operation_receipts "+ "SET result_revision=result_revision+1"+ )+ assert raised.value.sqlstate == "55000"+ elif case_alias == "receipt-delete-rejected":+ with pytest.raises(asyncpg.PostgresError) as raised:+ async with database._pool.acquire() as connection:+ await connection.execute("DELETE FROM execution_operation_receipts")+ assert raised.value.sqlstate == "55000"+ else:+ async with store._transaction() as connection:+ replay = await store._classify_receipt(connection, spec, current_revision=None)+ assert (replay.result, replay.revision) == (FixedResult.REPLAYED, 10)+ finally:+ await database.close()++[email protected]("case_alias", _P1B_ATOMICITY_CASES, ids=_P1B_ATOMICITY_CASES)+async def test_postgres_p1b_receipt_atomicity_and_nonduplication(+ case_alias: str, postgres_lifecycle_template: _MigrationHarness, monkeypatch+) -> None:+ async with _cloned_postgres_harness(postgres_lifecycle_template) as harness:+ database = PostgresDatabase(_migration_url(harness.config, harness.database_name))+ await database.connect()+ try:+ store = ExecutionLifecycleStore(database._pool, "postgresql")+ if case_alias == "exact-replay-no-duplicate-side-effects":+ spec = await _postgres_p1b_insert_receipt(store, "actor_authority_ensure")+ async with store._transaction() as connection:+ replay = await store._classify_receipt(connection, spec, current_revision=None)+ assert (replay.result, replay.revision) == (FixedResult.REPLAYED, 10)+ else:+ async with database._pool.acquire() as connection:+ await connection.execute(+ "INSERT INTO users(id,username,hashed_password,role,created_by) "+ "VALUES($1,'p1b-atomic','fixed','admin','fixed')",+ _uuid(3200),+ )++ async def fail_receipt(*_args, **_kwargs) -> None:+ raise RuntimeError("fixed-p1b-receipt-failure")++ monkeypatch.setattr(store, "_insert_receipt", fail_receipt)+ with pytest.raises(RuntimeError, match="fixed-p1b-receipt-failure"):+ await store.ensure_actor_authority(_uuid(3200), _uuid(3201))+ async with database._pool.acquire() as connection:+ authority = int(+ await connection.fetchval(+ "SELECT count(*) FROM execution_actor_authority_revisions "+ "WHERE user_id=$1",+ _uuid(3200),+ )+ )+ assert authority == 0+ async with database._pool.acquire() as connection:+ receipts = int(+ await connection.fetchval("SELECT count(*) FROM execution_operation_receipts")+ )+ finally:+ await database.close()+ assert receipts == (1 if case_alias == "exact-replay-no-duplicate-side-effects" else 0)++[email protected]("_case_alias", _P1B_CONCURRENCY_CASES, ids=_P1B_CONCURRENCY_CASES)+async def test_postgres_p1b_identical_operation_concurrency(+ _case_alias: str, postgres_lifecycle_template: _MigrationHarness+) -> None:+ async with _cloned_postgres_harness(postgres_lifecycle_template) as harness:+ database = PostgresDatabase(_migration_url(harness.config, harness.database_name))+ await database.connect()+ try:+ async with database._pool.acquire() as connection:+ await connection.execute(+ "INSERT INTO users(id,username,hashed_password,role,created_by) "+ "VALUES($1,'p1b-race','fixed','admin','fixed')",+ _uuid(3300),+ )+ first = ExecutionLifecycleStore(database._pool, "postgresql")+ second = ExecutionLifecycleStore(database._pool, "postgresql")+ results = await asyncio.gather(+ first.ensure_actor_authority(_uuid(3300), _uuid(3301)),+ second.ensure_actor_authority(_uuid(3300), _uuid(3301)),+ )+ async with database._pool.acquire() as connection:+ counts = (+ int(+ await connection.fetchval(+ "SELECT count(*) FROM execution_actor_authority_revisions "+ "WHERE user_id=$1",+ _uuid(3300),+ )+ ),+ int(+ await connection.fetchval(+ "SELECT count(*) FROM execution_operation_receipts "+ "WHERE operation_id=$1",+ _uuid(3301),+ )+ ),+ )+ finally:+ await database.close()+ assert {result.result for result in results} == {FixedResult.APPLIED, FixedResult.REPLAYED}+ assert counts == (1, 1)+++_POSTGRES_P1C_AUTHORITY_MUTATOR_ALIASES = (+ "gateway-update",+ "actor-activate",+ "actor-update",+ "actor-revoke",+ "campaign-activate",+ "campaign-update",+ "campaign-revoke",+ "grant-put",+ "grant-revoke",+ "destination-update",+ "destination-revoke",+ "credential-update",+ "credential-revoke",+ "approval-grant",+ "approval-revoke",+)++_POSTGRES_P1C_INITIAL_AUTHORITY_ALIASES = (+ "new-v3-applied",+ "v3-exact-replay",+ "v3-logical-id-conflict",+ "v3-attempt-id-conflict",+ "v3-operation-id-conflict",+ "v3-module-id-conflict",+ "v3-ingress-conflict",+ "v3-trusted-principal-conflict",+ "v3-after-gateway-change",+ "v3-after-authority-deletion",+ "v2-exact-replay",+ "v2-changed-intent-conflict",+ "v2-after-gateway-change",+ "v2-after-authority-deletion",+ "new-v2-rejected",+ "v3-row-downgrade-rejected",+)++_POSTGRES_P1C_AUTHORITY_DELETION_ALIASES = (+ "campaign-authority-cascade",+ "actor-authority-cascade",+ "destination-credential-authority-cascade",+ "snapshot-no-live-fk",+)++_POSTGRES_P1C_RETRY_AUTHORITY_ALIASES = (+ "v3-retry-applied",+ "v3-retry-exact-replay",+ "v3-retry-child-binding-conflict",+ "v3-retry-parent-revision-conflict",+ "v3-retry-after-authority-change",+ "v2-retry-exact-replay",+ "v2-retry-child-binding-conflict",+ "v2-retry-after-authority-change",+ "new-v2-retry-rejected",+ "v3-retry-downgrade-rejected",+)++_POSTGRES_P1C_PERSISTED_AUTHORITY_ALIASES = (+ "gateway-mode",+ "gateway-revision",+ "gateway-catalog-digest",+ "actor-identity",+ "actor-active",+ "actor-role",+ "actor-authority-revision",+ "campaign-status",+ "campaign-authority-revision",+ "campaign-ownership",+ "destination-extraction",+ "destination-campaign-scope",+ "destination-authority-revision",+ "credential-exists",+ "credential-ownership",+ "credential-authority-revision",+ "descriptor-module-identity",+ "descriptor-contract-version",+ "descriptor-semantic-digest",+ "policy-minimum-role",+ "policy-noise-class",+ "policy-required-capabilities",+ "policy-approval",+ "budget-authority-revisions",+ "budget-capacity",+)+++async def _postgres_p1c_authority_store(+ database: PostgresDatabase,+) -> tuple[ExecutionLifecycleStore, TrustedPrincipal, str, str, str]:+ principal_id = _uuid(12_000)+ actor_id = _uuid(12_001)+ campaign_id = _uuid(12_002)+ credential_id = _uuid(12_003)+ async with database._pool.acquire() as connection:+ await connection.executemany(+ "INSERT INTO users(id,username,hashed_password,role,created_by) "+ "VALUES($1,$2,'fixed',$3,'fixed')",+ (+ (principal_id, "p1c-admin", "admin"),+ (actor_id, "p1c-actor", "operator"),+ ),+ )+ await connection.execute(+ "INSERT INTO campaigns(id,name,operator,scope_json,targets_json) "+ "VALUES($1,'p1c-authority','p1c-admin','[]','[\"host.example\"]')",+ campaign_id,+ )+ await connection.execute(+ "INSERT INTO credentials(id,campaign_id,username,cred_type,source_module) "+ "VALUES($1,$2,'opaque-user','cleartext','p1c-fixture')",+ credential_id,+ campaign_id,+ )+ store = ExecutionLifecycleStore(database._pool, "postgresql")+ for user_id, operation in (+ (principal_id, _uuid(12_010)),+ (actor_id, _uuid(12_011)),+ ):+ assert (+ await store.ensure_actor_authority(user_id, operation)+ ).result is FixedResult.APPLIED+ assert (+ await store.ensure_campaign_authority(campaign_id, _uuid(12_012))+ ).result is FixedResult.APPLIED+ return (+ store,+ TrustedPrincipal(principal_id, principal_id),+ actor_id,+ campaign_id,+ credential_id,+ )+++def _postgres_p1c_v3_intent(campaign_id: str) -> AdmissionIntentV3:+ return AdmissionIntentV3(+ logical_execution_id=_uuid(12_500),+ submission_id=_uuid(12_501),+ attempt_id=_uuid(12_502),+ outbox_id=None,+ publication_key=None,+ campaign_id=campaign_id,+ module_id="opsec.coverage_predictor",+ ingress_code="sdk",+ operation_id=_uuid(12_503),+ evaluation_mode="live",+ raw_parameters={"noise_profile": "stealth"},+ )+++def _postgres_p1c_eligible_descriptor(monkeypatch) -> None:+ descriptor = replace(+ _descriptors.require_descriptor("opsec.coverage_predictor"),+ idempotency=IdempotencyClass.PROVEN_IDEMPOTENT,+ external_effect=ExternalEffectClass.READ_ONLY,+ retry_eligibility=RetryEligibility.AFTER_REVALIDATION,+ cancellation_ownership=CancellationOwnership.OWNED,+ compensation=CompensationClass.NOT_APPLICABLE,+ timeout=TimeoutPolicy(+ 30,+ _descriptors.TimeoutSource.MODULE_DEFINED_BOUNDED,+ TimeoutSettlement.PROVEN,+ ),+ result_contract=ResultContract(+ findings=ContractState.PROVEN_NONE,+ credentials=ContractState.PROVEN_NONE,+ discovered_hosts=ContractState.PROVEN_NONE,+ loot_artifacts=ContractState.PROVEN_NONE,+ authoritative_evidence=ContractState.SUPPORTED,+ ),+ future_gateway_eligible=True,+ blocker_codes=(),+ )+ descriptors = dict(_descriptors.FIRST_PARTY_DESCRIPTORS)+ descriptors[descriptor.module_id] = descriptor+ monkeypatch.setattr(_descriptors, "FIRST_PARTY_DESCRIPTORS", descriptors)+++def _postgres_p1c_v2_request(+ principal: TrustedPrincipal,+ campaign_id: str,+) -> AdmissionRequest:+ return AdmissionRequest(+ _uuid(12_500),+ _uuid(12_501),+ _uuid(12_502),+ _uuid(12_504),+ _uuid(12_505),+ campaign_id,+ principal.subject_ref,+ principal.user_id,+ "opsec.coverage_predictor",+ "sdk",+ AttemptState.BLOCKED,+ _uuid(12_503),+ replace(_blocked_snapshot(), actor_role="admin"),+ )+++async def _postgres_p1c_admission_counts(+ database: PostgresDatabase,+ operation_id: str,+) -> tuple[int, int, int, int]:+ async with database._pool.acquire() as observer:+ return (+ int(await observer.fetchval("SELECT count(*) FROM logical_executions")),+ int(await observer.fetchval("SELECT count(*) FROM execution_attempts")),+ int(await observer.fetchval("SELECT count(*) FROM execution_publication_outbox")),+ int(+ await observer.fetchval(+ "SELECT count(*) FROM execution_operation_receipts WHERE operation_id=$1",+ operation_id,+ )+ ),+ )+++async def _postgres_p1c_full_observer_snapshot(+ database: PostgresDatabase,+) -> tuple[str, ...]:+ inventories = (+ ("execution_gateway_state", "singleton_id"),+ ("users", "id"),+ ("campaigns", "id"),+ ("execution_actor_authority_revisions", "user_id"),+ ("campaign_execution_authority_revisions", "campaign_id"),+ ("campaign_execution_actor_grants", "campaign_id,actor_user_id"),+ ("campaign_execution_destination_authorities", "campaign_id"),+ ("credentials", "id"),+ ("execution_approval_authorities", "id"),+ ("campaign_execution_budgets", "id"),+ ("logical_executions", "id"),+ ("execution_attempts", "id"),+ ("execution_attempt_approvals", "id"),+ ("campaign_execution_budget_ledger", "id"),+ ("execution_publication_outbox", "id"),+ ("execution_operation_receipts", "operation_id"),+ ("execution_attempt_destination_observations", "attempt_id,ordinal"),+ ("execution_attempt_credential_observations", "attempt_id,ordinal"),+ )+ async with database._pool.acquire() as observer:+ snapshots: list[str] = []+ for table, order_by in inventories:+ statement = (+ "SELECT jsonb_build_object(" # noqa: S608 - frozen identifiers.+ "'count',count(*),'rows',COALESCE("+ f"jsonb_agg(to_jsonb(snapshot) ORDER BY {order_by}),"+ f"'[]'::jsonb))::text FROM {table} AS snapshot"+ )+ snapshots.append(str(await observer.fetchval(statement)))+ return tuple(snapshots)+++def _postgres_p1c_descriptor_mutation(+ monkeypatch,+ case_alias: str,+) -> None:+ source = _descriptors.require_descriptor("opsec.coverage_predictor")+ changes: dict[str, Any] = {}+ if case_alias == "descriptor-module-identity":+ changed = replace(+ source,+ module_id="opsec.coverage_predictor_changed",+ )+ descriptors = dict(_descriptors.FIRST_PARTY_DESCRIPTORS)+ descriptors["opsec.coverage_predictor"] = changed+ monkeypatch.setattr(_descriptors, "FIRST_PARTY_DESCRIPTORS", descriptors)+ return+ elif case_alias == "descriptor-contract-version":+ changed = object.__new__(type(source))+ for descriptor_field in source.__dataclass_fields__:+ object.__setattr__(changed, descriptor_field, getattr(source, descriptor_field))+ object.__setattr__(changed, "contract_version", "ares.module-descriptor.v1")+ object.__setattr__(+ changed,+ "semantic_digest",+ _descriptors.descriptor_semantic_digest(changed),+ )+ descriptors = dict(_descriptors.FIRST_PARTY_DESCRIPTORS)+ descriptors[source.module_id] = changed+ monkeypatch.setattr(_descriptors, "FIRST_PARTY_DESCRIPTORS", descriptors)+ return+ elif case_alias == "descriptor-semantic-digest":+ changed = replace(source, declared_outputs=source.declared_outputs + ("changed",))+ object.__setattr__(changed, "semantic_digest", "0" * 64)+ descriptors = dict(_descriptors.FIRST_PARTY_DESCRIPTORS)+ descriptors[source.module_id] = changed+ monkeypatch.setattr(_descriptors, "FIRST_PARTY_DESCRIPTORS", descriptors)+ return+ elif case_alias == "policy-minimum-role":+ changes["minimum_role"] = _descriptors.MinimumRole.TEAM_LEAD+ elif case_alias == "policy-noise-class":+ changes["opsec"] = _descriptors.OpsecClassification.HIGH_NOISE+ elif case_alias == "policy-required-capabilities":+ from ares.core.capabilities import Capability++ changes["required_capabilities"] = (Capability.CAP_NET,)+ elif case_alias == "policy-approval":+ changes["explicit_attempt_approval"] = True+ elif case_alias == "destination-extraction":+ changes["declared_outputs"] = source.declared_outputs + ("destination-changed",)+ descriptor = replace(source, **changes)+ descriptors = dict(_descriptors.FIRST_PARTY_DESCRIPTORS)+ descriptors[source.module_id] = descriptor+ monkeypatch.setattr(_descriptors, "FIRST_PARTY_DESCRIPTORS", descriptors)+++async def _postgres_p1c_corrupt_authority(+ database: PostgresDatabase,+ case_alias: str,+ *,+ campaign_id: str,+ credential_id: str,+ principal: TrustedPrincipal,+) -> None:+ async with database._pool.acquire() as connection:+ if case_alias == "gateway-mode":+ await connection.execute(+ "UPDATE execution_gateway_state SET mode='emergency_disabled',"+ "catalog_digest=repeat('0',64) WHERE singleton_id=1"+ )+ elif case_alias == "gateway-revision":+ await connection.execute(+ "UPDATE execution_gateway_state SET activation_revision=revision+2 "+ "WHERE singleton_id=1"+ )+ elif case_alias == "gateway-catalog-digest":+ await connection.execute(+ "UPDATE execution_gateway_state SET catalog_digest=repeat('0',64) "+ "WHERE singleton_id=1"+ )+ elif case_alias == "actor-identity":+ await connection.execute(+ "UPDATE users SET username='p1c-other' WHERE id=$1",+ principal.user_id,+ )+ elif case_alias == "actor-active":+ await connection.execute(+ "UPDATE users SET is_active=0 WHERE id=$1",+ principal.user_id,+ )+ elif case_alias == "actor-role":+ await connection.execute(+ "UPDATE users SET role='recon' WHERE id=$1",+ principal.user_id,+ )+ elif case_alias == "actor-authority-revision":+ await connection.execute(+ "UPDATE execution_actor_authority_revisions "+ "SET authority_revision=authority_revision+1,"+ "authority_binding_digest=repeat('0',64) WHERE user_id=$1",+ principal.user_id,+ )+ elif case_alias == "campaign-status":+ await connection.execute(+ "UPDATE campaigns SET status='completed' WHERE id=$1",+ campaign_id,+ )+ elif case_alias == "campaign-authority-revision":+ await connection.execute(+ "UPDATE campaign_execution_authority_revisions "+ "SET authority_revision=authority_revision+1,"+ "authority_binding_digest=repeat('0',64) WHERE campaign_id=$1",+ campaign_id,+ )+ elif case_alias == "campaign-ownership":+ await connection.execute(+ "UPDATE campaigns SET operator='changed-owner' WHERE id=$1",+ campaign_id,+ )+ elif case_alias == "destination-campaign-scope":+ await connection.execute(+ "UPDATE campaigns SET targets_json='[\"different.example\"]' WHERE id=$1",+ campaign_id,+ )+ elif case_alias == "destination-authority-revision":+ await connection.execute(+ "UPDATE campaign_execution_destination_authorities "+ "SET revision=revision+1,binding_digest=repeat('0',64) "+ "WHERE campaign_id=$1",+ campaign_id,+ )+ elif case_alias == "credential-exists":+ await connection.execute("DELETE FROM credentials WHERE id=$1", credential_id)+ elif case_alias == "credential-ownership":+ second_campaign = _uuid(12_980)+ await connection.execute(+ "INSERT INTO campaigns(id,name) VALUES($1,'p1c-other-campaign')",+ second_campaign,+ )+ await connection.execute(+ "UPDATE credentials SET campaign_id=$1 WHERE id=$2",+ second_campaign,+ credential_id,+ )+ elif case_alias == "credential-authority-revision":+ await connection.execute(+ "UPDATE credentials SET execution_authority_revision="+ "execution_authority_revision+1,"+ "execution_authority_binding_digest=repeat('0',64) WHERE id=$1",+ credential_id,+ )+ elif case_alias == "budget-authority-revisions":+ await connection.execute(+ "DELETE FROM campaign_execution_budgets "+ "WHERE campaign_id=$1 AND budget_kind='noise'",+ campaign_id,+ )+ elif case_alias == "budget-capacity":+ await connection.execute(+ "UPDATE campaign_execution_budgets SET reserved_units=capacity_units "+ "WHERE campaign_id=$1 AND budget_kind='concurrency'",+ campaign_id,+ )+++ "_case_alias",+ _POSTGRES_P1C_PERSISTED_AUTHORITY_ALIASES,+ ids=_POSTGRES_P1C_PERSISTED_AUTHORITY_ALIASES,+)+async def test_postgres_p1c_each_persisted_authority_contradiction_is_atomic(+ _case_alias: str,+ postgres_lifecycle_template: _MigrationHarness,+ monkeypatch,+) -> None:+ async with _cloned_postgres_harness(postgres_lifecycle_template) as harness:+ database = PostgresDatabase(_migration_url(harness.config, harness.database_name))+ await database.connect()+ try:+ _postgres_p1c_eligible_descriptor(monkeypatch)+ (+ store,+ principal,+ _actor_id,+ campaign_id,+ credential_id,+ ) = await _postgres_p1c_authority_store(database)+ assert (+ await store.put_campaign_actor_grant(+ principal,+ CampaignActorGrantMutation(+ _uuid(12_970),+ campaign_id,+ principal.user_id,+ None,+ ),+ )+ ).result is FixedResult.APPLIED+ assert (+ await store.update_gateway_authority(+ principal,+ GatewayAuthorityMutation(_uuid(12_971), 0, "enforced"),+ )+ ).result is FixedResult.APPLIED+ assert (+ await store.configure_campaign_budgets(+ BudgetConfiguration(+ campaign_id,+ _uuid(12_972),+ 10,+ _uuid(12_973),+ 10,+ _uuid(12_974),+ 1,+ _uuid(12_975),+ "actor",+ principal.subject_ref,+ principal.user_id,+ 0,+ )+ )+ ).result is FixedResult.APPLIED+ descriptor_cases = {+ "destination-extraction",+ "descriptor-module-identity",+ "descriptor-contract-version",+ "descriptor-semantic-digest",+ "policy-minimum-role",+ "policy-noise-class",+ "policy-required-capabilities",+ "policy-approval",+ }+ if _case_alias in descriptor_cases:+ _postgres_p1c_descriptor_mutation(monkeypatch, _case_alias)+ else:+ await _postgres_p1c_corrupt_authority(+ database,+ _case_alias,+ campaign_id=campaign_id,+ credential_id=credential_id,+ principal=principal,+ )+ intent = replace(+ _postgres_p1c_v3_intent(campaign_id),+ credential_ids=(credential_id,) if _case_alias.startswith("credential-") else (),+ )+ before = await _postgres_p1c_full_observer_snapshot(database)+ result = await store.create_initial_execution_v3(principal, intent)+ after = await _postgres_p1c_full_observer_snapshot(database)+ expected = (+ FixedResult.CAPACITY_UNAVAILABLE+ if _case_alias == "budget-capacity"+ else FixedResult.AUTHORITY_STALE+ )+ assert result.result is expected, (+ "persisted authority contradiction had the wrong precedence"+ )+ assert after == before, (+ "persisted authority contradiction created a durable side effect"+ )+ finally:+ await database.close()+++async def _postgres_p1c_prepare_retry_parent(+ database: PostgresDatabase,+ store: ExecutionLifecycleStore,+ principal: TrustedPrincipal,+ campaign_id: str,+) -> tuple[AdmissionIntentV3, int]:+ intent = _postgres_p1c_v3_intent(campaign_id)+ assert (+ await store.put_campaign_actor_grant(+ principal,+ CampaignActorGrantMutation(+ _uuid(12_540),+ campaign_id,+ principal.user_id,+ None,+ ),+ )+ ).result is FixedResult.APPLIED+ assert (+ await store.update_gateway_authority(+ principal,+ GatewayAuthorityMutation(_uuid(12_541), 0, "enforced"),+ )+ ).result is FixedResult.APPLIED+ assert (+ await store.configure_campaign_budgets(+ BudgetConfiguration(+ campaign_id,+ _uuid(12_542),+ 10,+ _uuid(12_543),+ 10,+ _uuid(12_544),+ 1,+ _uuid(12_545),+ "actor",+ principal.subject_ref,+ principal.user_id,+ 0,+ )+ )+ ).result is FixedResult.APPLIED+ assert (+ await store.create_initial_execution_v3(principal, intent)+ ).result is FixedResult.APPLIED+ transition = TransitionRequest(+ intent.attempt_id,+ 0,+ AttemptState.FAILED,+ _uuid(12_546),+ outcome_code=OutcomeCode.CONFIRMED_FAILURE_NO_DISPATCH,+ authoritative_proof="no_dispatch",+ campaign_id=campaign_id,+ actor_subject_ref=principal.subject_ref,+ actor_user_id=principal.user_id,+ actor_authority_revision=0,+ )+ terminal = TerminalCommitRequest(+ intent.logical_execution_id,+ campaign_id,+ _uuid(12_547),+ _uuid(12_548),+ transition,+ BudgetSettlement(+ campaign_id,+ intent.attempt_id,+ _uuid(12_542),+ 0,+ 0,+ 1,+ _uuid(12_543),+ 0,+ 0,+ 1,+ _uuid(12_544),+ 1,+ _uuid(12_549),+ "actor",+ principal.subject_ref,+ principal.user_id,+ 0,+ ),+ )+ result = await store.commit_terminal_attempt(terminal)+ assert result.result is FixedResult.APPLIED+ async with database._pool.acquire() as observer:+ parent = await observer.fetchrow(+ "SELECT revision,retry_disposition,closes_logical FROM execution_attempts WHERE id=$1",+ intent.attempt_id,+ )+ assert tuple(parent[1:]) == ("eligible", False)+ return intent, int(parent[0])+++def _postgres_p1c_retry_intent(+ parent: AdmissionIntentV3,+ parent_revision: int,+) -> RetryIntentV3:+ return RetryIntentV3(+ parent.logical_execution_id,+ parent.attempt_id,+ _uuid(12_560),+ None,+ None,+ _uuid(12_561),+ parent_revision,+ "live",+ parent.raw_parameters,+ )+++ "_case_alias",+ _POSTGRES_P1C_AUTHORITY_DELETION_ALIASES,+ ids=_POSTGRES_P1C_AUTHORITY_DELETION_ALIASES,+)+async def test_postgres_p1c_authority_deletion_and_fk_contract(+ _case_alias: str,+ postgres_lifecycle_template: _MigrationHarness,+ monkeypatch,+) -> None:+ async with _cloned_postgres_harness(postgres_lifecycle_template) as harness:+ database = PostgresDatabase(_migration_url(harness.config, harness.database_name))+ await database.connect()+ try:+ _postgres_p1c_eligible_descriptor(monkeypatch)+ (+ store,+ principal,+ actor_id,+ campaign_id,+ credential_id,+ ) = await _postgres_p1c_authority_store(database)+ grant_actor = principal.user_id if _case_alias == "snapshot-no-live-fk" else actor_id+ assert (+ await store.put_campaign_actor_grant(+ principal,+ CampaignActorGrantMutation(+ _uuid(12_950),+ campaign_id,+ grant_actor,+ None,+ ),+ )+ ).result is FixedResult.APPLIED+ if _case_alias == "campaign-authority-cascade":+ deleted = await database.delete_campaign_lifecycle(+ campaign_id,+ operation_id=_uuid(12_951),+ )+ async with database._pool.acquire() as observer:+ observed = await observer.fetchrow(+ "SELECT "+ "(SELECT count(*) FROM campaigns WHERE id=$1),"+ "(SELECT count(*) FROM campaign_execution_authority_revisions "+ "WHERE campaign_id=$1),"+ "(SELECT count(*) FROM campaign_execution_actor_grants "+ "WHERE campaign_id=$1),"+ "(SELECT count(*) FROM execution_operation_receipts "+ "WHERE operation_id=$2)",+ campaign_id,+ _uuid(12_951),+ )+ assert deleted.result is FixedResult.APPLIED, "campaign purge was rejected"+ assert tuple(observed) == (0, 0, 0, 1), (+ "campaign purge retained mutable authority or lost its receipt"+ )+ elif _case_alias == "actor-authority-cascade":+ async with database._pool.acquire() as connection:+ async with connection.transaction():+ await connection.execute(+ "DELETE FROM campaign_execution_actor_grants WHERE actor_user_id=$1",+ actor_id,+ )+ await connection.execute("DELETE FROM users WHERE id=$1", actor_id)+ async with database._pool.acquire() as observer:+ observed = await observer.fetchrow(+ "SELECT "+ "(SELECT count(*) FROM execution_actor_authority_revisions "+ "WHERE user_id=$1),"+ "(SELECT count(*) FROM users WHERE id=$1)",+ actor_id,+ )+ assert tuple(observed) == (0, 0), "actor authority did not cascade with user"+ elif _case_alias == "destination-credential-authority-cascade":+ deleted = await database.delete_campaign_lifecycle(+ campaign_id,+ operation_id=_uuid(12_952),+ )+ async with database._pool.acquire() as observer:+ observed = await observer.fetchrow(+ "SELECT "+ "(SELECT count(*) FROM campaign_execution_destination_authorities "+ "WHERE campaign_id=$1),"+ "(SELECT count(*) FROM credentials WHERE id=$2)",+ campaign_id,+ credential_id,+ )+ assert deleted.result is FixedResult.APPLIED, "campaign purge was rejected"+ assert tuple(observed) == (0, 0), (+ "campaign purge retained destination or credential authority"+ )+ else:+ intent = _postgres_p1c_v3_intent(campaign_id)+ applied = await store.create_initial_execution_v3(principal, intent)+ assert applied.result is FixedResult.APPLIED+ async with database._pool.acquire() as connection:+ async with connection.transaction():+ await connection.execute(+ "DELETE FROM campaign_execution_actor_grants WHERE campaign_id=$1",+ campaign_id,+ )+ await connection.execute(+ "DELETE FROM campaign_execution_destination_authorities "+ "WHERE campaign_id=$1",+ campaign_id,+ )+ await connection.execute(+ "DELETE FROM credentials WHERE id=$1",+ credential_id,+ )+ async with database._pool.acquire() as observer:+ observed = await observer.fetchrow(+ "SELECT authority_contract_version,trusted_principal_user_id,"+ "destination_authority_binding_digest,"+ "credential_authority_binding_digest "+ "FROM execution_attempts WHERE id=$1",+ intent.attempt_id,+ )+ assert observed is not None+ assert tuple(observed[:2]) == (+ 3,+ principal.user_id,+ ), "historical snapshot depended on live authority"+ assert all(isinstance(value, str) and len(value) == 64 for value in observed[2:]), (+ "historical snapshot lost authority digests"+ )+ purged = await database.delete_campaign_lifecycle(+ campaign_id,+ operation_id=_uuid(12_953),+ )+ async with database._pool.acquire() as observer:+ remaining = int(+ await observer.fetchval(+ "SELECT count(*) FROM execution_attempts WHERE id=$1",+ intent.attempt_id,+ )+ )+ assert purged.result is FixedResult.APPLIED, "historical campaign purge failed"+ assert remaining == 0, "historical snapshot survived campaign purge"+ finally:+ await database.close()+++async def test_postgres_actor_revocation_and_admission_are_linearized(+ postgres_lifecycle_template: _MigrationHarness,+ monkeypatch,+) -> None:+ async with _cloned_postgres_harness(postgres_lifecycle_template) as harness:+ database = PostgresDatabase(+ _migration_url(harness.config, harness.database_name),+ pool_min=3,+ pool_max=3,+ )+ await database.connect()+ admission_task: asyncio.Task[OperationResult] | None = None+ revocation_task: asyncio.Task[OperationResult] | None = None+ try:+ _postgres_p1c_eligible_descriptor(monkeypatch)+ (+ setup_store,+ principal,+ _actor_id,+ campaign_id,+ _credential_id,+ ) = await _postgres_p1c_authority_store(database)+ assert (+ await setup_store.put_campaign_actor_grant(+ principal,+ CampaignActorGrantMutation(+ _uuid(12_960),+ campaign_id,+ principal.user_id,+ None,+ ),+ )+ ).result is FixedResult.APPLIED+ assert (+ await setup_store.update_gateway_authority(+ principal,+ GatewayAuthorityMutation(_uuid(12_962), 0, "enforced"),+ )+ ).result is FixedResult.APPLIED+ assert (+ await setup_store.configure_campaign_budgets(+ BudgetConfiguration(+ campaign_id,+ _uuid(12_963),+ 10,+ _uuid(12_964),+ 10,+ _uuid(12_965),+ 1,+ _uuid(12_966),+ "actor",+ principal.subject_ref,+ principal.user_id,+ 0,+ )+ )+ ).result is FixedResult.APPLIED+ admission_locked = asyncio.Event()+ revocation_attempted = asyncio.Event()+ admission_store = _PostgresAdmissionWinnerStore(+ database._pool,+ admission_locked,+ revocation_attempted,+ )+ revocation_store = _PostgresRevocationContenderStore(+ database._pool,+ revocation_attempted,+ )+ intent = _postgres_p1c_v3_intent(campaign_id)+ revoke_operation_id = _uuid(12_961)+ admission_task = asyncio.create_task(+ admission_store.create_initial_execution_v3(principal, intent)+ )+ await asyncio.wait_for(admission_locked.wait(), timeout=10)+ revocation_task = asyncio.create_task(+ revocation_store.revoke_actor_authority(+ principal,+ ActorAuthorityMutation(+ revoke_operation_id,+ principal.user_id,+ 0,+ ),+ )+ )+ await asyncio.wait_for(revocation_attempted.wait(), timeout=10)+ admitted, revoked = await asyncio.wait_for(+ asyncio.gather(admission_task, revocation_task),+ timeout=30,+ )+ async with database._pool.acquire() as observer:+ observed_attempt = await observer.fetchrow(+ "SELECT state,actor_authority_revision FROM execution_attempts WHERE id=$1",+ intent.attempt_id,+ )+ observed_actor = await observer.fetchrow(+ "SELECT authority_state,authority_revision "+ "FROM execution_actor_authority_revisions WHERE user_id=$1",+ principal.user_id,+ )+ receipt_counts = await observer.fetchrow(+ "SELECT "+ "sum(CASE WHEN operation_id=$1 THEN 1 ELSE 0 END),"+ "sum(CASE WHEN operation_id=$2 THEN 1 ELSE 0 END) "+ "FROM execution_operation_receipts",+ intent.operation_id,+ revoke_operation_id,+ )+ finally:+ for task in (admission_task, revocation_task):+ if task is not None and not task.done():+ task.cancel()+ pending = tuple(+ task+ for task in (admission_task, revocation_task)+ if task is not None and not task.done()+ )+ if pending:+ await asyncio.gather(*pending, return_exceptions=True)+ await database.close()+ assert (admitted.result, revoked.result) == (+ FixedResult.APPLIED,+ FixedResult.APPLIED,+ ), "serialized admission/revocation result changed"+ assert tuple(observed_attempt) == ("accepted", 0), (+ "admission did not retain its locked actor authority revision"+ )+ assert tuple(observed_actor) == ("revoked", 1), "revocation did not serialize after admission"+ assert tuple(receipt_counts) == (0, 1), (+ "serialized operations wrote the wrong receipt cardinality"+ )+++ "_case_alias",+ _POSTGRES_P1C_RETRY_AUTHORITY_ALIASES,+ ids=_POSTGRES_P1C_RETRY_AUTHORITY_ALIASES,+)+async def test_postgres_p1c_retry_v2_v3_authority(+ _case_alias: str,+ postgres_lifecycle_template: _MigrationHarness,+ monkeypatch,+) -> None:+ async with _cloned_postgres_harness(postgres_lifecycle_template) as harness:+ database = PostgresDatabase(_migration_url(harness.config, harness.database_name))+ await database.connect()+ try:+ _postgres_p1c_eligible_descriptor(monkeypatch)+ (+ store,+ principal,+ _actor_id,+ campaign_id,+ _credential_id,+ ) = await _postgres_p1c_authority_store(database)+ if _case_alias.startswith("v2-") or _case_alias == "new-v2-retry-rejected":+ historical_store, parent_revision = await _postgres_p1b_prepare_retryable_parent(+ database+ )+ child = AdmissionRequest(+ _uuid(208),+ _uuid(12_570),+ _uuid(12_571),+ _uuid(12_572),+ _uuid(12_573),+ _uuid(201),+ _uuid(200),+ _uuid(200),+ "test-transition",+ "sdk",+ AttemptState.BLOCKED,+ _uuid(12_574),+ replace(+ _blocked_snapshot(),+ actor_role="admin",+ gateway_mode_snapshot="enforced",+ ),+ )+ request = RetryRequest(_uuid(208), _uuid(210), child, parent_revision)+ if _case_alias == "new-v2-retry-rejected":+ result = await historical_store.create_retry_attempt(request)+ assert result.result is FixedResult.INVALID_CONTRACT+ return+ assert (+ await historical_store._create_retry_attempt_v2_for_migration_fixture(request)+ ).result is FixedResult.APPLIED+ if _case_alias == "v2-retry-child-binding-conflict":+ candidate = replace(+ request,+ child=replace(child, module_id="test-transition.changed"),+ )+ expected = FixedResult.CONFLICT_OPERATION+ else:+ if _case_alias == "v2-retry-after-authority-change":+ async with database._pool.acquire() as connection:+ await connection.execute(+ "UPDATE users SET role='reporter' WHERE id=$1",+ _uuid(200),+ )+ candidate = request+ expected = FixedResult.REPLAYED_BOUND_CHILD+ result = await historical_store.replay_retry_attempt_v2(+ TrustedPrincipal(_uuid(200), _uuid(200)),+ candidate,+ )+ assert result.result is expected+ return++ parent, parent_revision = await _postgres_p1c_prepare_retry_parent(+ database,+ store,+ principal,+ campaign_id,+ )+ intent = _postgres_p1c_retry_intent(parent, parent_revision)+ applied = await store.create_retry_attempt_v3(principal, intent)+ assert applied.result is FixedResult.APPLIED+ if _case_alias == "v3-retry-applied":+ result = applied+ expected = FixedResult.APPLIED+ elif _case_alias == "v3-retry-exact-replay":+ result = await store.create_retry_attempt_v3(principal, intent)+ expected = FixedResult.REPLAYED_BOUND_CHILD+ elif _case_alias == "v3-retry-child-binding-conflict":+ result = await store.create_retry_attempt_v3(+ principal,+ replace(intent, child_attempt_id=_uuid(12_562)),+ )+ expected = FixedResult.CONFLICT_OPERATION+ elif _case_alias == "v3-retry-parent-revision-conflict":+ result = await store.create_retry_attempt_v3(+ principal,+ replace(intent, expected_parent_revision=parent_revision + 1),+ )+ expected = FixedResult.CONFLICT_OPERATION+ elif _case_alias == "v3-retry-after-authority-change":+ assert (+ await store.revoke_actor_authority(+ principal,+ ActorAuthorityMutation(+ _uuid(12_563),+ principal.user_id,+ 0,+ ),+ )+ ).result is FixedResult.APPLIED+ result = await store.create_retry_attempt_v3(principal, intent)+ expected = FixedResult.REPLAYED_BOUND_CHILD+ else:+ child = AdmissionRequest(+ parent.logical_execution_id,+ parent.submission_id,+ intent.child_attempt_id,+ _uuid(12_562),+ _uuid(12_563),+ campaign_id,+ principal.subject_ref,+ principal.user_id,+ parent.module_id,+ parent.ingress_code,+ AttemptState.BLOCKED,+ intent.operation_id,+ _blocked_snapshot(),+ )+ result = await store.replay_retry_attempt_v2(+ principal,+ RetryRequest(+ parent.logical_execution_id,+ parent.attempt_id,+ child,+ parent_revision,+ ),+ )+ expected = FixedResult.CONFLICT_OPERATION+ assert result.result is expected+ async with database._pool.acquire() as observer:+ child_count = int(+ await observer.fetchval(+ "SELECT count(*) FROM execution_attempts WHERE id=$1",+ intent.child_attempt_id,+ )+ )+ receipt_count = int(+ await observer.fetchval(+ "SELECT count(*) FROM execution_operation_receipts WHERE operation_id=$1",+ intent.operation_id,+ )+ )+ assert (child_count, receipt_count) == (1, 1)+ finally:+ await database.close()+++ "_case_alias",+ _POSTGRES_P1C_INITIAL_AUTHORITY_ALIASES,+ ids=_POSTGRES_P1C_INITIAL_AUTHORITY_ALIASES,+)+async def test_postgres_p1c_initial_v2_v3_submission_authority(+ _case_alias: str,+ postgres_lifecycle_template: _MigrationHarness,+ monkeypatch,+) -> None:+ async with _cloned_postgres_harness(postgres_lifecycle_template) as harness:+ database = PostgresDatabase(_migration_url(harness.config, harness.database_name))+ await database.connect()+ try:+ (+ store,+ principal,+ _actor_id,+ campaign_id,+ _credential_id,+ ) = await _postgres_p1c_authority_store(database)+ _postgres_p1c_eligible_descriptor(monkeypatch)+ assert (+ await store.put_campaign_actor_grant(+ principal,+ CampaignActorGrantMutation(_uuid(12_510), campaign_id, principal.user_id, None),+ )+ ).result is FixedResult.APPLIED+ intent = _postgres_p1c_v3_intent(campaign_id)+ v2_request = _postgres_p1c_v2_request(principal, campaign_id)++ if _case_alias.startswith("v2-") or _case_alias == "new-v2-rejected":+ if _case_alias == "new-v2-rejected":+ result = await store.create_initial_execution(v2_request)+ assert result.result is FixedResult.INVALID_CONTRACT, (+ "public fresh-v2 creation was accepted"+ )+ assert await _postgres_p1c_admission_counts(+ database, v2_request.operation_id+ ) == (0, 0, 0, 0), "fresh-v2 rejection created durable state"+ return++ assert (+ await store._create_initial_execution_v2_for_migration_fixture(v2_request)+ ).result is FixedResult.APPLIED+ if _case_alias == "v2-exact-replay":+ result = await store.replay_initial_execution_v2(principal, v2_request)+ expected = FixedResult.REPLAYED+ elif _case_alias == "v2-changed-intent-conflict":+ result = await store.replay_initial_execution_v2(+ principal,+ replace(+ v2_request,+ module_id="opsec.coverage_predictor.changed",+ ),+ )+ expected = FixedResult.CONFLICT_OPERATION+ elif _case_alias == "v2-after-gateway-change":+ assert (+ await store.update_gateway_authority(+ principal,+ GatewayAuthorityMutation(+ _uuid(12_511),+ 0,+ "shadow_candidate",+ ),+ )+ ).result is FixedResult.APPLIED+ result = await store.replay_initial_execution_v2(principal, v2_request)+ expected = FixedResult.REPLAYED+ else:+ async with database._pool.acquire() as connection:+ await connection.execute(+ "DELETE FROM campaign_execution_actor_grants WHERE campaign_id=$1",+ campaign_id,+ )+ await connection.execute(+ "DELETE FROM campaign_execution_destination_authorities "+ "WHERE campaign_id=$1",+ campaign_id,+ )+ result = await store.replay_initial_execution_v2(principal, v2_request)+ expected = FixedResult.REPLAYED+ assert result.result is expected, "historical v2 replay authority changed"+ return++ assert (+ await store.update_gateway_authority(+ principal,+ GatewayAuthorityMutation(_uuid(12_509), 0, "enforced"),+ )+ ).result is FixedResult.APPLIED+ assert (+ await store.configure_campaign_budgets(+ BudgetConfiguration(+ campaign_id,+ _uuid(12_530),+ 20,+ _uuid(12_531),+ 20,+ _uuid(12_532),+ 1,+ _uuid(12_533),+ "actor",+ principal.subject_ref,+ principal.user_id,+ 0,+ )+ )+ ).result is FixedResult.APPLIED+ applied = await store.create_initial_execution_v3(principal, intent)+ assert applied.result is FixedResult.APPLIED, "first v3 admission was not applied"+ if _case_alias == "new-v3-applied":+ result = applied+ expected = FixedResult.APPLIED+ elif _case_alias == "v3-exact-replay":+ result = await store.create_initial_execution_v3(principal, intent)+ expected = FixedResult.REPLAYED+ elif _case_alias == "v3-logical-id-conflict":+ result = await store.create_initial_execution_v3(+ principal,+ replace(intent, logical_execution_id=_uuid(12_520)),+ )+ expected = FixedResult.CONFLICT_OPERATION+ elif _case_alias == "v3-attempt-id-conflict":+ result = await store.create_initial_execution_v3(+ principal,+ replace(intent, attempt_id=_uuid(12_521)),+ )+ expected = FixedResult.CONFLICT_OPERATION+ elif _case_alias == "v3-operation-id-conflict":+ result = await store.create_initial_execution_v3(+ principal,+ replace(intent, operation_id=_uuid(12_522)),+ )+ expected = FixedResult.CONFLICT_OPERATION+ elif _case_alias == "v3-module-id-conflict":+ result = await store.create_initial_execution_v3(+ principal,+ replace(intent, module_id="opsec.coverage_predictor.changed"),+ )+ expected = FixedResult.CONFLICT_OPERATION+ elif _case_alias == "v3-ingress-conflict":+ result = await store.create_initial_execution_v3(+ principal,+ replace(intent, ingress_code="cli_module"),+ )+ expected = FixedResult.CONFLICT_OPERATION+ elif _case_alias == "v3-trusted-principal-conflict":+ changed = TrustedPrincipal(_uuid(12_523), _uuid(12_523))+ result = await store.create_initial_execution_v3(changed, intent)+ expected = FixedResult.CONFLICT_OPERATION+ elif _case_alias == "v3-after-gateway-change":+ assert (+ await store.update_gateway_authority(+ principal,+ GatewayAuthorityMutation(+ _uuid(12_524),+ 1,+ "shadow_candidate",+ ),+ )+ ).result is FixedResult.APPLIED+ result = await store.create_initial_execution_v3(principal, intent)+ expected = FixedResult.REPLAYED+ elif _case_alias == "v3-after-authority-deletion":+ async with database._pool.acquire() as connection:+ await connection.execute(+ "DELETE FROM campaign_execution_actor_grants WHERE campaign_id=$1",+ campaign_id,+ )+ await connection.execute(+ "DELETE FROM campaign_execution_destination_authorities "+ "WHERE campaign_id=$1",+ campaign_id,+ )+ result = await store.create_initial_execution_v3(principal, intent)+ expected = FixedResult.REPLAYED+ else:+ result = await store.replay_initial_execution_v2(principal, v2_request)+ expected = FixedResult.CONFLICT_OPERATION++ assert result.result is expected, "v3 submission replay authority changed"+ counts = await _postgres_p1c_admission_counts(database, intent.operation_id)+ assert counts[:3] == (1, 1, 0), "v3 accepted admission cardinality changed"+ assert counts[3] == 0, "initial admission created a redundant operation receipt"+ async with database._pool.acquire() as observer:+ durable = await observer.fetchrow(+ "SELECT state,authority_contract_version,retry_disposition "+ "FROM execution_attempts "+ "WHERE id=$1",+ intent.attempt_id,+ )+ reservations = int(+ await observer.fetchval(+ "SELECT count(*) FROM campaign_execution_budget_ledger "+ "WHERE attempt_id=$1 AND disposition='held'",+ intent.attempt_id,+ )+ )+ assert tuple(durable) == (+ AttemptState.ACCEPTED.value,+ 3,+ "not_applicable",+ )+ assert reservations == 3+ finally:+ await database.close()+++ "_case_alias",+ _POSTGRES_P1C_AUTHORITY_MUTATOR_ALIASES,+ ids=_POSTGRES_P1C_AUTHORITY_MUTATOR_ALIASES,+)+async def test_postgres_p1c_each_authority_mutator_is_exactly_replayable(+ _case_alias: str,+ postgres_lifecycle_template: _MigrationHarness,+ monkeypatch,+) -> None:+ async with _cloned_postgres_harness(postgres_lifecycle_template) as harness:+ database = PostgresDatabase(_migration_url(harness.config, harness.database_name))+ await database.connect()+ try:+ (+ store,+ principal,+ actor_id,+ campaign_id,+ credential_id,+ ) = await _postgres_p1c_authority_store(database)+ operation_id = _uuid(+ 12_100 + _POSTGRES_P1C_AUTHORITY_MUTATOR_ALIASES.index(_case_alias)+ )+ approval_id = _uuid(12_200)+ approval_ref = _uuid(12_201)+ if _case_alias == "gateway-update":+ request: Any = GatewayAuthorityMutation(operation_id, 0, "enforced")+ method_name = "update_gateway_authority"+ elif _case_alias.startswith("actor-"):+ action = _case_alias.removeprefix("actor-")+ expected_revision = 0+ if action == "activate":+ assert (+ await store.revoke_actor_authority(+ principal,+ ActorAuthorityMutation(_uuid(12_300), actor_id, 0),+ )+ ).result is FixedResult.APPLIED+ expected_revision = 1+ request = ActorAuthorityMutation(operation_id, actor_id, expected_revision)+ method_name = f"{action}_actor_authority"+ elif _case_alias.startswith("campaign-"):+ action = _case_alias.removeprefix("campaign-")+ expected_revision = 0+ if action == "activate":+ assert (+ await store.revoke_campaign_authority(+ principal,+ CampaignAuthorityMutation(_uuid(12_301), campaign_id, 0),+ )+ ).result is FixedResult.APPLIED+ expected_revision = 1+ request = CampaignAuthorityMutation(+ operation_id,+ campaign_id,+ expected_revision,+ )+ method_name = f"{action}_campaign_authority"+ elif _case_alias.startswith("grant-"):+ action = _case_alias.removeprefix("grant-")+ expected_revision = None+ if action == "revoke":+ assert (+ await store.put_campaign_actor_grant(+ principal,+ CampaignActorGrantMutation(_uuid(12_302), campaign_id, actor_id, None),+ )+ ).result is FixedResult.APPLIED+ expected_revision = 0+ request = CampaignActorGrantMutation(+ operation_id,+ campaign_id,+ actor_id,+ expected_revision,+ )+ method_name = f"{action}_campaign_actor_grant"+ elif _case_alias.startswith("destination-"):+ action = _case_alias.removeprefix("destination-")+ request = DestinationAuthorityMutation(operation_id, campaign_id, 0)+ method_name = f"{action}_destination_authority"+ elif _case_alias.startswith("credential-"):+ action = _case_alias.removeprefix("credential-")+ request = CredentialAuthorityMutation(operation_id, credential_id, 0)+ method_name = f"{action}_credential_authority"+ elif _case_alias == "approval-grant":+ request = ApprovalAuthorityGrant(+ operation_id,+ approval_id,+ approval_ref,+ campaign_id,+ _uuid(12_202),+ _uuid(12_203),+ actor_id,+ actor_id,+ "opsec.coverage_predictor",+ 0,+ )+ method_name = "grant_approval_authority"+ else:+ grant = ApprovalAuthorityGrant(+ _uuid(12_303),+ approval_id,+ approval_ref,+ campaign_id,+ _uuid(12_202),+ _uuid(12_203),+ actor_id,+ actor_id,+ "opsec.coverage_predictor",+ 0,+ )+ assert (+ await store.grant_approval_authority(principal, grant)+ ).result is FixedResult.APPLIED+ request = ApprovalAuthorityMutation(operation_id, approval_id, 0)+ method_name = "revoke_approval_authority"++ async def invoke() -> OperationResult:+ method = getattr(store, method_name)+ return await method(principal, request)++ def changed_request() -> Any:+ if type(request) is GatewayAuthorityMutation:+ return replace(request, mode="shadow_candidate")+ if type(request) in {+ ActorAuthorityMutation,+ CampaignAuthorityMutation,+ DestinationAuthorityMutation,+ CredentialAuthorityMutation,+ ApprovalAuthorityMutation,+ }:+ return replace(+ request,+ expected_revision=request.expected_revision + 1,+ )+ if type(request) is CampaignActorGrantMutation:+ expected = (+ 0 if request.expected_revision is None else request.expected_revision + 1+ )+ return replace(request, expected_revision=expected)+ if type(request) is ApprovalAuthorityGrant:+ return replace(request, granted_capability_mask=1)+ raise AssertionError("unsupported authority mutation request")++ async def observe_target() -> tuple[tuple[object, ...], ...]:+ table, where, parameters = {+ "gateway-update": (+ "execution_gateway_state",+ "singleton_id=1",+ (),+ ),+ "actor-activate": (+ "execution_actor_authority_revisions",+ "user_id=$1",+ (actor_id,),+ ),+ "actor-update": (+ "execution_actor_authority_revisions",+ "user_id=$1",+ (actor_id,),+ ),+ "actor-revoke": (+ "execution_actor_authority_revisions",+ "user_id=$1",+ (actor_id,),+ ),+ "campaign-activate": (+ "campaign_execution_authority_revisions",+ "campaign_id=$1",+ (campaign_id,),+ ),+ "campaign-update": (+ "campaign_execution_authority_revisions",+ "campaign_id=$1",+ (campaign_id,),+ ),+ "campaign-revoke": (+ "campaign_execution_authority_revisions",+ "campaign_id=$1",+ (campaign_id,),+ ),+ "grant-put": (+ "campaign_execution_actor_grants",+ "campaign_id=$1 AND actor_user_id=$2",+ (campaign_id, actor_id),+ ),+ "grant-revoke": (+ "campaign_execution_actor_grants",+ "campaign_id=$1 AND actor_user_id=$2",+ (campaign_id, actor_id),+ ),+ "destination-update": (+ "campaign_execution_destination_authorities",+ "campaign_id=$1",+ (campaign_id,),+ ),+ "destination-revoke": (+ "campaign_execution_destination_authorities",+ "campaign_id=$1",+ (campaign_id,),+ ),+ "credential-update": ("credentials", "id=$1", (credential_id,)),+ "credential-revoke": ("credentials", "id=$1", (credential_id,)),+ "approval-grant": (+ "execution_approval_authorities",+ "id=$1",+ (approval_id,),+ ),+ "approval-revoke": (+ "execution_approval_authorities",+ "id=$1",+ (approval_id,),+ ),+ }[_case_alias]+ async with database._pool.acquire() as observer:+ rows = await observer.fetch(+ f"SELECT * FROM {table} WHERE {where}", # noqa: S608+ *parameters,+ )+ return tuple(tuple(row.values()) for row in rows)++ applied = await invoke()+ async with database._pool.acquire() as observer:+ receipt_count_after_apply = int(+ await observer.fetchval(+ "SELECT count(*) FROM execution_operation_receipts WHERE operation_id=$1",+ operation_id,+ )+ )+ replayed = await invoke()+ async with database._pool.acquire() as observer:+ receipt_count_after_replay = int(+ await observer.fetchval(+ "SELECT count(*) FROM execution_operation_receipts WHERE operation_id=$1",+ operation_id,+ )+ )+ target_before_conflict = await observe_target()+ conflicting = await getattr(store, method_name)(+ principal,+ changed_request(),+ )+ target_after_conflict = await observe_target()+ async with database._pool.acquire() as observer:+ receipt_count_after_conflict = int(+ await observer.fetchval(+ "SELECT count(*) FROM execution_operation_receipts WHERE operation_id=$1",+ operation_id,+ )+ )++ receipt_first: OperationResult | None = None+ if _case_alias == "gateway-update":+ async with database._pool.acquire() as connection:+ await connection.execute(+ "UPDATE execution_gateway_state SET catalog_digest=repeat('f',64) "+ "WHERE singleton_id=1"+ )+ receipt_first = await invoke()+ elif _case_alias.startswith("credential-"):+ async with database._pool.acquire() as connection:+ await connection.execute(+ "DELETE FROM credentials WHERE id=$1",+ credential_id,+ )+ receipt_first = await invoke()+ elif _case_alias.startswith("approval-"):+ if _case_alias == "approval-grant":+ descriptors = dict(_descriptors.FIRST_PARTY_DESCRIPTORS)+ descriptors["opsec.coverage_predictor"] = replace(+ descriptors["opsec.coverage_predictor"],+ minimum_role=_descriptors.MinimumRole.TEAM_LEAD,+ )+ monkeypatch.setattr(+ _descriptors,+ "FIRST_PARTY_DESCRIPTORS",+ descriptors,+ )+ async with database._pool.acquire() as connection:+ await connection.execute(+ "DELETE FROM execution_approval_authorities WHERE id=$1",+ approval_id,+ )+ receipt_first = await invoke()+ assert (applied.result, replayed.result) == (+ FixedResult.APPLIED,+ FixedResult.REPLAYED,+ ), "authority mutation lost exact replay"+ assert conflicting.result is FixedResult.CONFLICT_OPERATION, (+ "authority mutation accepted a changed same-operation binding"+ )+ assert target_after_conflict == target_before_conflict, (+ "changed authority mutation altered its target"+ )+ assert (+ receipt_count_after_apply+ == receipt_count_after_replay+ == receipt_count_after_conflict+ == 1+ ), "authority mutation replay duplicated its receipt"+ if receipt_first is not None:+ assert receipt_first.result is FixedResult.REPLAYED, (+ "authority mutation replay consulted mutable current authority"+ )+ finally:+ await database.close()+++_POSTGRES_P1C_TERMINAL_V3_ALIASES = (+ "invalid-contract-before-receipt",+ "v3-binding-vector-and-operation-codes",+ "receipt-replay-after-target-deletion",+ "receipt-replay-zero-mutable-reads",+ "changed-intent-conflict-operation",+ "known-success-atomic",+ "known-failure-atomic",+ "acknowledged-cancellation-atomic",+ "acknowledged-timeout-atomic",+ "uncertain-outcome-invalid-contract",+ "single-transaction-zero-nested-acquire",+ "derive-exact-three-held-ledgers",+ "missing-ledger-inconsistent-set-rollback",+ "duplicate-extra-ledger-inconsistent-set-rollback",+ "wrong-kind-ledger-inconsistent-set-rollback",+ "wrong-campaign-attempt-ledger-inconsistent-set-rollback",+ "non-held-ledger-conflict-operation-rollback",+ "current-budget-lock-no-toctou",+ "budget-capacity-inconsistent-set-rollback",+ "budget-write-failure-rollback",+ "output-write-failure-rollback",+ "terminal-write-failure-rollback",+ "logical-closure-write-failure-rollback",+ "outbox-write-failure-rollback",+ "receipt-write-failure-rollback",+ "public-intent-excludes-derived-fields",+ "missing-attempt-not-found-or-purged",+ "non-running-attempt-conflict-state",+ "stale-attempt-revision-conflict",+ "invariant-failure-rollback",+ "cancellation-rollback-and-reuse",+ "exception-rollback-and-reuse",+ "legacy-terminal-apply-replay-bytes-unchanged",+ "legacy-v3-crossing-conflict-operation",+ "changed-outcome-conflict-operation",+ "changed-result-digest-conflict-operation",+ "cancellation-caller-result-digest-invalid-contract",+ "timeout-caller-result-digest-invalid-contract",+ "canonical-output-order-exact-replay",+ "terminal-operation-and-system-principal-namespace",+ "derived-revision-overflow-invariant-failure-rollback",+)++_POSTGRES_P1C_TERMINAL_RESULT_DIGEST = hashlib.sha256(+ b"postgres-p1c-terminal-v3-known-result"+).hexdigest()+_POSTGRES_P1C_LEGACY_TERMINAL_REQUEST_DIGEST = (+ "da5caf4a079873de9cdea7f31a284bcac45bdd3526c602038aaeb66147fc5cb8"+)+_POSTGRES_P1C_LEGACY_TERMINAL_RESULT_DIGEST = (+ "0b15cef8a5886d92669f712e36c80a91e4e10d00a1e0d92d6a479ad1bde08278"+)+_POSTGRES_P1C_LEGACY_OUTBOX_REQUEST_DIGEST = (+ "5dccdba355c4feef9cd6df03d5d6b3c8af06feee7ee618108615a35a545425e7"+)+_POSTGRES_P1C_LEGACY_OUTBOX_RESULT_DIGEST = (+ "7a50d0b26f31239a9fba139b28affd32750988bb7d6dc360c0a570ea8856a0d3"+)+_POSTGRES_P1C_LEGACY_BUDGET_REQUEST_DIGEST = (+ "e0d4a8b6ca4ea2e38967e3158283cd1fa175279a41b1c55490cebbf76b48a9a1"+)+_POSTGRES_P1C_LEGACY_BUDGET_RESULT_DIGEST = (+ "04f8900897528d734dd7f4fd030af712b34e2cd18ddf929f247b20494f5ddcad"+)+_POSTGRES_P1C_TERMINAL_NODE_COUNT = 41+_POSTGRES_P1C_TERMINAL_NODE_ID_SHA256 = (+ "5e3de1839318f51847db713d93210f0104228d03c75501f3c401afa0010d3489"+)+++def _postgres_p1c_terminal_inventory_digest() -> str:+ encoded = bytearray(b"ares.p1c-terminal-v3-postgres-test-inventory.v1\x00")+ for alias in _POSTGRES_P1C_TERMINAL_V3_ALIASES:+ node_id = (+ "tests/integration/test_postgres_execution_lifecycle.py::"+ f"test_postgres_p1c_terminal_v3_seam[{alias}]"+ ).encode()+ encoded.extend(struct.pack(">I", len(node_id)))+ encoded.extend(node_id)+ return hashlib.sha256(encoded).hexdigest()+++assert len(_POSTGRES_P1C_TERMINAL_V3_ALIASES) == _POSTGRES_P1C_TERMINAL_NODE_COUNT+assert len(set(_POSTGRES_P1C_TERMINAL_V3_ALIASES)) == _POSTGRES_P1C_TERMINAL_NODE_COUNT+assert _postgres_p1c_terminal_inventory_digest() == _POSTGRES_P1C_TERMINAL_NODE_ID_SHA256+++def _postgres_p1c_terminal_binding_digest(+ domain: str,+ values: tuple[tuple[str, str | int | bool | None], ...],+) -> str:+ """Independent literal oracle for the protected v2 typed framing."""+ encoded = bytearray(b"ares.execution-operation-binding.v2\x00")++ def frame(value: bytes) -> None:+ encoded.extend(struct.pack(">I", len(value)))+ encoded.extend(value)++ frame(domain.encode("ascii"))+ seen: set[str] = set()+ for name, value in values:+ assert name not in seen, "PostgreSQL terminal oracle contains a duplicate field"+ seen.add(name)+ frame(name.encode("ascii"))+ if value is None:+ encoded.extend(b"n")+ elif type(value) is bool:+ encoded.extend(b"b\x01" if value else b"b\x00")+ elif type(value) is int:+ encoded.extend(b"i")+ frame(value.to_bytes(8, "big", signed=False))+ elif type(value) is str:+ encoded.extend(b"s")+ frame(value.encode("utf-8"))+ else: # pragma: no cover - a broken independent oracle must be loud.+ raise AssertionError("unsupported PostgreSQL terminal oracle value")+ return hashlib.sha256(encoded).hexdigest()+++def _postgres_p1c_terminal_operation_id(attempt_id: str) -> str:+ digest = _postgres_p1c_terminal_binding_digest(+ "terminal-commit-operation-id.v3",+ (("attempt_id", attempt_id), ("action", "commit-known-settled")),+ )+ return (+ digest[:8]+ + "-"+ + digest[8:12]+ + "-4"+ + digest[13:16]+ + "-8"+ + digest[17:20]+ + "-"+ + digest[20:32]+ )+++def _postgres_p1c_terminal_operation_code(outcome: OutcomeCode) -> str:+ return {+ OutcomeCode.CONFIRMED_SUCCESS: "terminal_succeeded",+ OutcomeCode.CONFIRMED_FAILURE: "terminal_failed",+ OutcomeCode.CONFIRMED_CANCELLED_NO_RESULT: "cancellation_acknowledgement",+ OutcomeCode.CONFIRMED_TIMEOUT_TERMINATED: "timeout",+ }[outcome]+++def _postgres_p1c_terminal_request_digest(intent: TerminalCommitIntentV3) -> str:+ operation_id = _postgres_p1c_terminal_operation_id(intent.attempt_id)+ operation_code = _postgres_p1c_terminal_operation_code(intent.outcome_code)+ canonical_outputs = tuple(+ sorted(+ intent.outputs,+ key=lambda item: (item.kind.value, item.target_id, item.link_id),+ )+ )+ output_fields = tuple(+ field+ for index, output in enumerate(canonical_outputs)+ for field in (+ (f"output_{index}_link_id", output.link_id),+ (f"output_{index}_kind", output.kind.value),+ (f"output_{index}_target_id", output.target_id),+ )+ )+ return _postgres_p1c_terminal_binding_digest(+ "execution-terminal-commit.v3.request",+ (+ ("terminal_commit_contract_version", 3),+ ("logical_execution_id", intent.logical_execution_id),+ ("campaign_id", intent.campaign_id),+ ("attempt_id", intent.attempt_id),+ ("operation_id", operation_id),+ ("expected_attempt_revision", intent.expected_attempt_revision),+ ("operation_code", operation_code),+ ("outcome_code", intent.outcome_code.value),+ ("noise_actual", intent.noise_actual),+ ("exfiltration_actual", intent.exfiltration_actual),+ ("concurrency_actual", intent.concurrency_actual),+ (+ "execution_result_digest_present",+ intent.execution_result_digest is not None,+ ),+ ("execution_result_digest", intent.execution_result_digest),+ ("output_count", len(canonical_outputs)),+ )+ + output_fields,+ )+++def _postgres_p1c_terminal_derived_uuid(operation_id: str, label: str) -> str:+ digest = hashlib.sha256((operation_id + "\x00" + label).encode("ascii")).hexdigest()+ return (+ digest[:8]+ + "-"+ + digest[8:12]+ + "-4"+ + digest[13:16]+ + "-8"+ + digest[17:20]+ + "-"+ + digest[20:32]+ )+++def _postgres_p1c_terminal_result_digest(intent: TerminalCommitIntentV3) -> str:+ operation_id = _postgres_p1c_terminal_operation_id(intent.attempt_id)+ operation_code = _postgres_p1c_terminal_operation_code(intent.outcome_code)+ target, proof = {+ OutcomeCode.CONFIRMED_SUCCESS: (AttemptState.SUCCEEDED, "local_completion"),+ OutcomeCode.CONFIRMED_FAILURE: (AttemptState.FAILED, "local_completion"),+ OutcomeCode.CONFIRMED_CANCELLED_NO_RESULT: (+ AttemptState.CANCELLED,+ "cancellation_no_result_ack",+ ),+ OutcomeCode.CONFIRMED_TIMEOUT_TERMINATED: (+ AttemptState.TIMED_OUT,+ "timeout_termination_ack",+ ),+ }[intent.outcome_code]+ post_revision = intent.expected_attempt_revision + 1+ outbox_id = _postgres_p1c_terminal_derived_uuid(operation_id, "terminal-outbox")+ publication_key = _postgres_p1c_terminal_derived_uuid(+ operation_id,+ "terminal-publication",+ )+ return _postgres_p1c_terminal_binding_digest(+ "execution-terminal-commit.v3.result",+ (+ ("result_code", FixedResult.APPLIED.value),+ ("exact_replay_code", FixedResult.REPLAYED.value),+ ("result_identity_present", True),+ ("result_identity", intent.attempt_id),+ ("result_revision_present", True),+ ("result_revision", post_revision),+ ("secondary_result_identity_present", True),+ ("secondary_result_identity", intent.logical_execution_id),+ ("secondary_result_revision_present", True),+ ("secondary_result_revision", 1),+ ("state", target.value),+ ("revision", post_revision),+ ("closes_logical", True),+ ("finding_count", 0),+ ("credential_count", 0),+ ("host_count", 0),+ ("artifact_count", 0),+ ("outbox_id", outbox_id),+ ("terminal_commit_contract_version", 3),+ ("operation_id", operation_id),+ ("operation_code", operation_code),+ ("campaign_id", intent.campaign_id),+ ("logical_execution_id", intent.logical_execution_id),+ ("attempt_id", intent.attempt_id),+ ("outcome_code", intent.outcome_code.value),+ ("authoritative_proof", proof),+ ("retry_eligible", False),+ (+ "execution_result_digest_present",+ intent.execution_result_digest is not None,+ ),+ ("execution_result_digest", intent.execution_result_digest),+ ("publication_key", publication_key),+ ),+ )+++async def _postgres_p1c_terminal_case(+ database: PostgresDatabase,+ *,+ predecessor: AttemptState = AttemptState.RUNNING,+) -> tuple[ExecutionLifecycleStore, _PostgresConnectionAdapter, Any, int]:+ store, adapter, connection = await _postgres_transition_case(database, AttemptState.ACCEPTED)+ if predecessor is AttemptState.ACCEPTED:+ return store, adapter, connection, 0+ dispatched = await _nonterminal_transition(store, adapter, AttemptState.DISPATCHING, 20_100)+ assert dispatched.result is FixedResult.APPLIED, "terminal fixture dispatch failed"+ running = await _nonterminal_transition(store, adapter, AttemptState.RUNNING, 20_101)+ assert running.result is FixedResult.APPLIED, "terminal fixture start failed"+ if predecessor is AttemptState.CANCELLING:+ cancelling = await _nonterminal_transition(store, adapter, AttemptState.CANCELLING, 20_102)+ assert cancelling.result is FixedResult.APPLIED, "terminal fixture cancel failed"+ return store, adapter, connection, 3+ assert predecessor is AttemptState.RUNNING, "unsupported terminal fixture predecessor"+ return store, adapter, connection, 2+++def _postgres_p1c_terminal_intent(+ expected_revision: int,+ *,+ outcome: OutcomeCode = OutcomeCode.CONFIRMED_SUCCESS,+ execution_result_digest: str | None | object = ...,+ outputs: tuple[OutputObservation, ...] = (),+ noise_actual: int = 1,+ exfiltration_actual: int = 2,+ concurrency_actual: int = 0,+) -> TerminalCommitIntentV3:+ if execution_result_digest is ...:+ execution_result_digest = (+ None+ if outcome+ in {+ OutcomeCode.CONFIRMED_CANCELLED_NO_RESULT,+ OutcomeCode.CONFIRMED_TIMEOUT_TERMINATED,+ }+ else _POSTGRES_P1C_TERMINAL_RESULT_DIGEST+ )+ return TerminalCommitIntentV3(+ logical_execution_id=_uuid(208),+ campaign_id=_uuid(201),+ attempt_id=_uuid(210),+ expected_attempt_revision=expected_revision,+ outcome_code=outcome,+ noise_actual=noise_actual,+ exfiltration_actual=exfiltration_actual,+ concurrency_actual=concurrency_actual,+ execution_result_digest=execution_result_digest, # type: ignore[arg-type]+ outputs=outputs,+ )+++async def _postgres_p1c_terminal_receipt(+ connection: Any,+ attempt_id: str = _uuid(210),+) -> Any:+ return await connection.fetchrow(+ "SELECT operation_id,operation_code,campaign_id,primary_target_id,"+ "secondary_target_id,principal_kind,principal_subject_ref,principal_user_id,"+ "principal_authority_revision_present,principal_authority_revision,"+ "binding_contract_version,request_binding_digest,result_code,exact_replay_code,"+ "result_binding_digest,result_identity,result_revision,secondary_result_identity,"+ "secondary_result_revision FROM execution_operation_receipts WHERE operation_id=$1",+ _postgres_p1c_terminal_operation_id(attempt_id),+ )+++async def _postgres_p1c_terminal_state(connection: Any) -> Any:+ return await connection.fetchrow(+ "SELECT state,revision,outcome_code,settlement_state,settlement_proof_code,"+ "termination_confirmed,closes_logical,retry_disposition,terminal_operation_id,"+ "cancellation_ack_operation_id,timeout_operation_id "+ "FROM execution_attempts WHERE id=$1",+ _uuid(210),+ )+++async def _postgres_p1c_terminal_receipt_snapshot(+ connection: Any,+) -> tuple[tuple[object, ...], ...]:+ rows = await connection.fetch(+ "SELECT * FROM execution_operation_receipts WHERE campaign_id=$1 ORDER BY operation_id",+ _uuid(201),+ )+ return tuple(tuple(row) for row in rows)+++async def _postgres_p1c_terminal_snapshot(+ connection: Any,+) -> tuple[tuple[str, tuple[tuple[object, ...], ...]], ...]:+ tables = (+ "logical_executions",+ "execution_attempts",+ "campaign_execution_budgets",+ "campaign_execution_budget_ledger",+ "execution_output_links",+ "execution_publication_outbox",+ "execution_operation_receipts",+ "hosts",+ )+ observed = []+ for table in tables:+ rows = await connection.fetch(+ f"SELECT * FROM {table} ORDER BY 1" # noqa: S608 - fixed tuple.+ )+ observed.append((table, tuple(tuple(row) for row in rows)))+ return tuple(observed)+++def _postgres_p1c_legacy_terminal_request(+ operation_id: str,+ expected_revision: int,+) -> TerminalCommitRequest:+ return TerminalCommitRequest(+ _uuid(208),+ _uuid(201),+ _uuid(20_200),+ _uuid(20_201),+ TransitionRequest(+ _uuid(210),+ expected_revision,+ AttemptState.SUCCEEDED,+ operation_id,+ owner_ref=_uuid(220),+ lease_generation=1,+ outcome_code=OutcomeCode.CONFIRMED_SUCCESS,+ authoritative_proof="local_completion",+ campaign_id=_uuid(201),+ ),+ BudgetSettlement(+ _uuid(201),+ _uuid(210),+ _uuid(204),+ 2,+ 1,+ 1,+ _uuid(205),+ 3,+ 2,+ 1,+ _uuid(206),+ 1,+ _uuid(20_202),+ ),+ )+++class _PostgresP1CTerminalPoolProbe:+ def __init__(self, pool: Any) -> None:+ self._pool = pool+ self.acquire_count = 0+ self.release_count = 0+ self.connection_identities: set[int] = set()++ async def acquire(self) -> Any:+ connection = await self._pool.acquire()+ self.acquire_count += 1+ self.connection_identities.add(id(connection))+ return connection++ async def release(self, connection: Any) -> None:+ self.release_count += 1+ await self._pool.release(connection)+++class _PostgresP1CTerminalTraceStore(ExecutionLifecycleStore):+ def __init__(+ self,+ backend: Any,+ *,+ receipt_only: bool = False,+ ledger_mutation: str | None = None,+ fail_at: str | None = None,+ cancel_at: str | None = None,+ duplicate_terminal_returning: bool = False,+ ) -> None:+ super().__init__(backend, "postgresql")+ self.receipt_only = receipt_only+ self.ledger_mutation = ledger_mutation+ self.fail_at = fail_at+ self.cancel_at = cancel_at+ self.duplicate_terminal_returning = duplicate_terminal_returning+ self.transaction_entries = 0+ self.connection_identities: set[int] = set()+ self.read_events: list[str] = []+ self.lock_events: list[tuple[str, str | None]] = []+ self.budget_writes = 0+ self.budget_lock_ids: list[str] = []+ self.output_insert_order: list[str] = []++ @asynccontextmanager+ async def _transaction(self) -> AsyncIterator[Any]:+ self.transaction_entries += 1+ async with super()._transaction() as connection:+ self.connection_identities.add(id(connection))+ yield connection++ async def _fetchrow(self, connection: Any, sql: str, params: Any) -> Any:+ self.connection_identities.add(id(connection))+ if "execution_operation_receipts" in sql:+ self.read_events.append("receipt")+ elif "pg_advisory_xact_lock" not in sql:+ self.read_events.append("mutable")+ if "FROM execution_attempts WHERE id=" in sql:+ assert sql.endswith(" FOR UPDATE"), "terminal attempt read was not locked"+ self.lock_events.append(("attempt", str(params[0])))+ if self.receipt_only and not (+ "execution_operation_receipts" in sql or "pg_advisory_xact_lock" in sql+ ):+ raise AssertionError("exact terminal replay read a mutable target")+ if "FROM campaign_execution_budgets WHERE id=" in sql:+ assert sql.endswith(" FOR UPDATE"), "terminal budget read was not locked"+ self.budget_lock_ids.append(str(params[0]))+ self.lock_events.append(("budget", str(params[0])))+ if "FROM logical_executions WHERE id=" in sql:+ assert sql.endswith(" FOR UPDATE"), "terminal logical read was not locked"+ self.lock_events.append(("logical", str(params[0])))+ return await super()._fetchrow(connection, sql, params)++ async def _fetchall(self, connection: Any, sql: str, params: Any) -> Any:+ self.connection_identities.add(id(connection))+ self.read_events.append("mutable")+ if self.receipt_only:+ raise AssertionError("exact terminal replay read a mutable target set")+ rows = tuple(await super()._fetchall(connection, sql, params))+ if "FROM campaign_execution_budget_ledger" not in sql or not rows:+ return rows+ assert sql.endswith(" FOR UPDATE"), "terminal ledger set was not locked"+ self.lock_events.append(("ledgers", str(params[0])))+ if self.ledger_mutation == "duplicate":+ return rows + (rows[0],)+ if self.ledger_mutation is None:+ return rows+ changed = [dict(row) for row in rows]+ if self.ledger_mutation == "wrong-kind":+ changed[0]["budget_kind"] = "artifact"+ elif self.ledger_mutation == "wrong-campaign":+ changed[0]["campaign_id"] = _uuid(20_300)+ elif self.ledger_mutation == "wrong-attempt":+ changed[0]["attempt_id"] = _uuid(20_301)+ elif self.ledger_mutation == "non-held":+ changed[0]["disposition"] = "released"+ else: # pragma: no cover - constructor/dispatcher drift must be loud.+ raise AssertionError(f"unknown PostgreSQL ledger mutation: {self.ledger_mutation}")+ return tuple(changed)++ async def _returning_rows(self, connection: Any, sql: str, params: Any) -> Any:+ self.connection_identities.add(id(connection))+ rows = await super()._returning_rows(connection, sql, params)+ if (+ self.duplicate_terminal_returning+ and "UPDATE execution_attempts SET state=" in sql+ and rows+ ):+ return rows + rows+ return rows++ async def cas_update_one(+ self,+ connection: Any,+ sql: str,+ params: Any,+ **kwargs: Any,+ ) -> Any:+ row = await super().cas_update_one(connection, sql, params, **kwargs)+ if "UPDATE campaign_execution_budgets" in sql:+ self.budget_writes += 1+ if self.fail_at == "budget" and self.budget_writes == 2:+ raise RuntimeError("fixed-postgres-terminal-budget-write-failure")+ if self.fail_at == "terminal" and "UPDATE execution_attempts SET state=" in sql:+ raise RuntimeError("fixed-postgres-terminal-attempt-write-failure")+ if self.fail_at == "logical" and "UPDATE logical_executions SET closure" in sql:+ raise RuntimeError("fixed-postgres-terminal-logical-write-failure")+ return row++ async def _insert_output_links(self, *args: Any, **kwargs: Any) -> Any:+ counts = await super()._insert_output_links(*args, **kwargs)+ if self.fail_at == "output":+ raise RuntimeError("fixed-postgres-terminal-output-write-failure")+ if self.fail_at == "exception":+ raise RuntimeError("fixed-postgres-terminal-exception")+ if self.cancel_at == "output":+ raise asyncio.CancelledError+ return counts++ async def update_exact_set(+ self,+ connection: Any,+ sql: str,+ params: Any,+ **kwargs: Any,+ ) -> Any:+ result = await super().update_exact_set(connection, sql, params, **kwargs)+ if "INSERT INTO execution_output_links" in sql:+ self.output_insert_order.append(str(params[0]))+ return result++ async def _insert_terminal_outbox(self, *args: Any, **kwargs: Any) -> Any:+ result = await super()._insert_terminal_outbox(*args, **kwargs)+ if self.fail_at == "outbox":+ raise RuntimeError("fixed-postgres-terminal-outbox-write-failure")+ return result++ async def _insert_terminal_v3_receipt(self, *args: Any, **kwargs: Any) -> Any:+ result = await super()._insert_terminal_v3_receipt(*args, **kwargs)+ if self.fail_at == "receipt":+ raise RuntimeError("fixed-postgres-terminal-receipt-write-failure")+ return result+++async def _postgres_p1c_assert_terminal_rollback(+ connection: Any,+ store: ExecutionLifecycleStore,+ intent: TerminalCommitIntentV3,+ *,+ expected_result: FixedResult | None = None,+ expected_exception: type[BaseException] | None = None,+) -> OperationResult | None:+ before = await _postgres_p1c_terminal_snapshot(connection)+ if expected_exception is None:+ result = await store.commit_terminal_attempt_v3(intent)+ assert result.result is expected_result, "terminal rollback result changed"+ else:+ with pytest.raises(expected_exception):+ await store.commit_terminal_attempt_v3(intent)+ result = None+ after = await _postgres_p1c_terminal_snapshot(connection)+ assert after == before, "PostgreSQL terminal failure committed partial state"+ return result+++ "case_alias",+ _POSTGRES_P1C_TERMINAL_V3_ALIASES,+ ids=_POSTGRES_P1C_TERMINAL_V3_ALIASES,+)+async def test_postgres_p1c_terminal_v3_seam( # noqa: C901, PLR0912, PLR0915+ case_alias: str,+ postgres_lifecycle_template: _MigrationHarness,+) -> None:+ if case_alias == "public-intent-excludes-derived-fields":+ declared_fields = fields(TerminalCommitIntentV3)+ public_fields = tuple(item.name for item in declared_fields)+ assert public_fields == (+ "logical_execution_id",+ "campaign_id",+ "attempt_id",+ "expected_attempt_revision",+ "outcome_code",+ "noise_actual",+ "exfiltration_actual",+ "concurrency_actual",+ "execution_result_digest",+ "outputs",+ ), "terminal public authority surface changed"+ forbidden = {+ "operation_id",+ "principal_kind",+ "principal_subject_ref",+ "principal_user_id",+ "principal_authority_revision",+ "actor_subject_ref",+ "actor_user_id",+ "actor_authority_revision",+ "campaign_authority_revision",+ "budget_id",+ "budget_ids",+ "ledger_id",+ "ledger_ids",+ "reserved_units",+ "budget_revision",+ "current_budget_revision",+ "retry_eligibility",+ "retry_eligible",+ "policy_result",+ "closure_disposition",+ "receipt_classification",+ }+ assert not forbidden.intersection(public_fields), (+ "caller authority leaked into terminal intent"+ )+ assert get_type_hints(TerminalCommitIntentV3) == {+ "logical_execution_id": str,+ "campaign_id": str,+ "attempt_id": str,+ "expected_attempt_revision": int,+ "outcome_code": OutcomeCode,+ "noise_actual": int,+ "exfiltration_actual": int,+ "concurrency_actual": int,+ "execution_result_digest": str | None,+ "outputs": tuple[OutputObservation, ...],+ }, "terminal public annotations changed"+ assert all(item.default is MISSING for item in declared_fields[:-1])+ assert declared_fields[-1].default == ()+ params = TerminalCommitIntentV3.__dataclass_params__+ assert is_dataclass(TerminalCommitIntentV3)+ assert (+ params.init,+ params.repr,+ params.eq,+ params.order,+ params.unsafe_hash,+ params.frozen,+ ) == (True, False, False, False, False, True)+ assert tuple(TerminalCommitIntentV3.__slots__) == public_fields+ assert TerminalCommitIntentV3.__hash__ is None+ baseline = _postgres_p1c_terminal_intent(2)+ assert not hasattr(baseline, "__dict__"), "terminal intent lost its slot boundary"+ with pytest.raises(FrozenInstanceError):+ baseline.campaign_id = _uuid(20_299)+ values = {item.name: getattr(baseline, item.name) for item in fields(baseline)}+ for name in sorted(forbidden):+ with pytest.raises(TypeError):+ TerminalCommitIntentV3(**values, **{name: "caller-controlled"})+ return++ if case_alias == "missing-attempt-not-found-or-purged":+ async with _cloned_postgres_harness(postgres_lifecycle_template) as harness:+ database = PostgresDatabase(_migration_url(harness.config, harness.database_name))+ await database.connect()+ try:+ intent = _postgres_p1c_terminal_intent(0)+ result = await ExecutionLifecycleStore(+ database._pool, "postgresql"+ ).commit_terminal_attempt_v3(intent)+ async with database._pool.acquire() as observer:+ receipt = await _postgres_p1c_terminal_receipt(observer)+ finally:+ await database.close()+ assert (result.result, result.revision) == (+ FixedResult.NOT_FOUND_OR_PURGED,+ None,+ )+ assert receipt is None, "missing PostgreSQL attempt created a receipt"+ return++ if case_alias == "v3-binding-vector-and-operation-codes":+ cases = (+ (OutcomeCode.CONFIRMED_SUCCESS, AttemptState.RUNNING, "terminal_succeeded"),+ (OutcomeCode.CONFIRMED_FAILURE, AttemptState.RUNNING, "terminal_failed"),+ (+ OutcomeCode.CONFIRMED_CANCELLED_NO_RESULT,+ AttemptState.CANCELLING,+ "cancellation_acknowledgement",+ ),+ (OutcomeCode.CONFIRMED_TIMEOUT_TERMINATED, AttemptState.RUNNING, "timeout"),+ )+ for outcome, predecessor, operation_code in cases:+ async with _cloned_postgres_harness(postgres_lifecycle_template) as harness:+ database = PostgresDatabase(_migration_url(harness.config, harness.database_name))+ await database.connect()+ setup_connection = None+ try:+ store, _adapter, setup_connection, revision = await _postgres_p1c_terminal_case(+ database,+ predecessor=predecessor,+ )+ intent = _postgres_p1c_terminal_intent(revision, outcome=outcome)+ result = await store.commit_terminal_attempt_v3(intent)+ receipt = await _postgres_p1c_terminal_receipt(setup_connection)+ finally:+ if setup_connection is not None:+ await database._pool.release(setup_connection)+ await database.close()+ assert result.result is FixedResult.APPLIED, "terminal binding case failed"+ assert receipt["operation_id"] == _postgres_p1c_terminal_operation_id(intent.attempt_id)+ assert receipt["operation_code"] == operation_code+ assert receipt["binding_contract_version"] == 2+ assert receipt["request_binding_digest"] == _postgres_p1c_terminal_request_digest(+ intent+ )+ assert receipt["result_binding_digest"] == _postgres_p1c_terminal_result_digest(intent)+ assert receipt["result_binding_digest"] != intent.execution_result_digest, (+ "terminal receipt result binding conflated the execution-result digest"+ )+ return++ if case_alias == "legacy-v3-crossing-conflict-operation":+ for first in ("legacy", "v3"):+ async with _cloned_postgres_harness(postgres_lifecycle_template) as harness:+ database = PostgresDatabase(_migration_url(harness.config, harness.database_name))+ await database.connect()+ setup_connection = None+ try:+ store, _adapter, setup_connection, revision = await _postgres_p1c_terminal_case(+ database+ )+ intent = _postgres_p1c_terminal_intent(revision)+ operation_id = _postgres_p1c_terminal_operation_id(intent.attempt_id)+ legacy = _postgres_p1c_legacy_terminal_request(operation_id, revision)+ if first == "legacy":+ applied = await store.commit_terminal_attempt(legacy)+ crossed = await store.commit_terminal_attempt_v3(intent)+ else:+ applied = await store.commit_terminal_attempt_v3(intent)+ crossed = await store.commit_terminal_attempt(legacy)+ finally:+ if setup_connection is not None:+ await database._pool.release(setup_connection)+ await database.close()+ assert (applied.result, crossed.result) == (+ FixedResult.APPLIED,+ FixedResult.CONFLICT_OPERATION,+ ), f"legacy/V3 {first}-first receipt crossing was reinterpreted"+ return++ if case_alias == "derived-revision-overflow-invariant-failure-rollback":+ for target in ("budget", "logical", "actual-max"):+ async with _cloned_postgres_harness(postgres_lifecycle_template) as harness:+ database = PostgresDatabase(_migration_url(harness.config, harness.database_name))+ await database.connect()+ setup_connection = None+ try:+ store, _adapter, setup_connection, revision = await _postgres_p1c_terminal_case(+ database+ )+ intent = _postgres_p1c_terminal_intent(revision)+ if target == "budget":+ await setup_connection.execute(+ "UPDATE campaign_execution_budgets SET revision=$1,"+ "latest_operation_base_revision=$2 "+ "WHERE campaign_id=$3 AND budget_kind='noise'",+ MAX_I53,+ MAX_I53 - 1,+ _uuid(201),+ )+ elif target == "logical":+ await setup_connection.execute(+ "UPDATE logical_executions SET revision=$1 WHERE id=$2",+ MAX_I53,+ _uuid(208),+ )+ else:+ await setup_connection.execute(+ "UPDATE campaign_execution_budgets SET capacity_units=$1,"+ "reserved_units=$1,consumed_units=0 "+ "WHERE campaign_id=$2 AND budget_kind='noise'",+ MAX_I53,+ _uuid(201),+ )+ await setup_connection.execute(+ "UPDATE campaign_execution_budget_ledger SET reservation_units=$1 "+ "WHERE attempt_id=$2 AND budget_kind='noise'",+ MAX_I53,+ _uuid(210),+ )+ budget_revision = await setup_connection.fetchval(+ "SELECT revision FROM campaign_execution_budgets "+ "WHERE campaign_id=$1 AND budget_kind='noise'",+ _uuid(201),+ )+ intent = replace(intent, noise_actual=MAX_I53)+ if target in {"budget", "logical"}:+ await _postgres_p1c_assert_terminal_rollback(+ setup_connection,+ store,+ intent,+ expected_result=FixedResult.INVARIANT_FAILURE,+ )+ else:+ applied = await store.commit_terminal_attempt_v3(intent)+ budget = await setup_connection.fetchrow(+ "SELECT capacity_units,reserved_units,consumed_units,revision "+ "FROM campaign_execution_budgets "+ "WHERE campaign_id=$1 AND budget_kind='noise'",+ _uuid(201),+ )+ ledger = await setup_connection.fetchrow(+ "SELECT reservation_units,consumed_units,disposition "+ "FROM campaign_execution_budget_ledger "+ "WHERE attempt_id=$1 AND budget_kind='noise'",+ _uuid(210),+ )+ assert applied.result is FixedResult.APPLIED+ assert tuple(budget[:3]) == (MAX_I53, 0, MAX_I53)+ assert budget["revision"] == budget_revision + 1+ assert tuple(ledger) == (MAX_I53, MAX_I53, "consumed")+ finally:+ if setup_connection is not None:+ await database._pool.release(setup_connection)+ await database.close()+ return++ predecessor = (+ AttemptState.CANCELLING+ if case_alias+ in {+ "acknowledged-cancellation-atomic",+ "cancellation-caller-result-digest-invalid-contract",+ }+ else AttemptState.ACCEPTED+ if case_alias == "non-running-attempt-conflict-state"+ else AttemptState.RUNNING+ )+ async with _cloned_postgres_harness(postgres_lifecycle_template) as harness:+ database = PostgresDatabase(_migration_url(harness.config, harness.database_name))+ await database.connect()+ setup_connection = None+ try:+ base_store, _adapter, setup_connection, revision = await _postgres_p1c_terminal_case(+ database, predecessor=predecessor+ )+ store: ExecutionLifecycleStore = base_store+ intent = _postgres_p1c_terminal_intent(revision)++ if case_alias == "invalid-contract-before-receipt":+ trace = _PostgresP1CTerminalTraceStore(database._pool)+ output = OutputObservation(_uuid(20_610), OutputKind.HOST, _uuid(260))+ duplicate_link = OutputObservation(+ output.link_id,+ OutputKind.HOST,+ _uuid(20_611),+ )+ duplicate_target = OutputObservation(+ _uuid(20_612),+ OutputKind.HOST,+ output.target_id,+ )+ too_many_outputs = tuple(+ OutputObservation(+ _uuid(21_000 + index),+ OutputKind.HOST,+ _uuid(22_000 + index),+ )+ for index in range(257)+ )+ invalids = (+ replace(intent, expected_attempt_revision=MAX_I53),+ replace(intent, expected_attempt_revision=True),+ replace(intent, expected_attempt_revision=-1),+ replace(intent, expected_attempt_revision=MAX_I53 + 1),+ replace(intent, attempt_id="not-a-canonical-uuid"),+ replace(intent, noise_actual=True),+ replace(intent, exfiltration_actual=True),+ replace(intent, concurrency_actual=True),+ replace(intent, noise_actual=-1),+ replace(intent, noise_actual=MAX_I53 + 1),+ replace(intent, concurrency_actual=1),+ replace(intent, execution_result_digest=None),+ replace(+ intent,+ execution_result_digest=_POSTGRES_P1C_TERMINAL_RESULT_DIGEST.upper(),+ ),+ replace(intent, execution_result_digest="a" * 63),+ replace(intent, outputs=(output, output)),+ replace(intent, outputs=(output, duplicate_link)),+ replace(intent, outputs=(output, duplicate_target)),+ replace(intent, outputs=[output]), # type: ignore[arg-type]+ replace(intent, outputs=too_many_outputs),+ replace(+ intent,+ outcome_code=OutcomeCode.CONFIRMED_FAILURE,+ outputs=(output,),+ ),+ )+ before = await _postgres_p1c_terminal_snapshot(setup_connection)+ results = tuple([await trace.commit_terminal_attempt_v3(item) for item in invalids])+ assert all(item.result is FixedResult.INVALID_CONTRACT for item in results)+ assert trace.transaction_entries == 0, "invalid intent entered a transaction"+ assert await _postgres_p1c_terminal_snapshot(setup_connection) == before+ elif case_alias == "receipt-replay-after-target-deletion":+ applied = await store.commit_terminal_attempt_v3(intent)+ receipt_before = await _postgres_p1c_terminal_receipt(setup_connection)+ deleted = await database.delete_campaign_lifecycle(+ _uuid(201), lifecycle_operation_id=_uuid(20_303)+ )+ absence = await setup_connection.fetchrow(+ "SELECT "+ "(SELECT COUNT(*) FROM campaigns WHERE id=$1),"+ "(SELECT COUNT(*) FROM logical_executions WHERE campaign_id=$1),"+ "(SELECT COUNT(*) FROM execution_attempts WHERE campaign_id=$1),"+ "(SELECT COUNT(*) FROM campaign_execution_budgets WHERE campaign_id=$1),"+ "(SELECT COUNT(*) FROM campaign_execution_budget_ledger WHERE campaign_id=$1),"+ "(SELECT COUNT(*) FROM execution_output_links WHERE campaign_id=$1),"+ "(SELECT COUNT(*) FROM execution_publication_outbox WHERE campaign_id=$1),"+ "(SELECT COUNT(*) FROM campaign_execution_authority_revisions "+ "WHERE campaign_id=$1)",+ _uuid(201),+ )+ trace = _PostgresP1CTerminalTraceStore(+ database._pool,+ receipt_only=True,+ )+ replayed = await trace.commit_terminal_attempt_v3(intent)+ receipt_after = await _postgres_p1c_terminal_receipt(setup_connection)+ assert deleted.result is FixedResult.APPLIED+ assert (applied.result, replayed.result, replayed.revision) == (+ FixedResult.APPLIED,+ FixedResult.REPLAYED,+ revision + 1,+ )+ assert tuple(absence) == (0, 0, 0, 0, 0, 0, 0, 0), (+ "terminal replay retained a mutable lifecycle target"+ )+ assert tuple(receipt_before) == tuple(receipt_after), (+ "terminal replay receipt changed after mutable-target deletion"+ )+ assert trace.transaction_entries == 1+ elif case_alias == "receipt-replay-zero-mutable-reads":+ applied = await store.commit_terminal_attempt_v3(intent)+ trace = _PostgresP1CTerminalTraceStore(+ database._pool,+ receipt_only=True,+ )+ replayed = await trace.commit_terminal_attempt_v3(intent)+ assert (applied.result, replayed.result) == (+ FixedResult.APPLIED,+ FixedResult.REPLAYED,+ )+ assert trace.transaction_entries == 1+ elif case_alias == "changed-intent-conflict-operation":+ applied = await store.commit_terminal_attempt_v3(intent)+ receipt_only = _PostgresP1CTerminalTraceStore(+ database._pool,+ receipt_only=True,+ )+ usage_changed = await receipt_only.commit_terminal_attempt_v3(+ replace(intent, noise_actual=0)+ )+ output_changed = await receipt_only.commit_terminal_attempt_v3(+ replace(+ intent,+ outputs=(+ OutputObservation(+ _uuid(20_613),+ OutputKind.HOST,+ _uuid(260),+ ),+ ),+ )+ )+ assert (applied.result, usage_changed.result, output_changed.result) == (+ FixedResult.APPLIED,+ FixedResult.CONFLICT_OPERATION,+ FixedResult.CONFLICT_OPERATION,+ )+ assert receipt_only.transaction_entries == 2+ elif case_alias in {+ "known-success-atomic",+ "known-failure-atomic",+ "acknowledged-cancellation-atomic",+ "acknowledged-timeout-atomic",+ }:+ outcome, state, proof, event_code = {+ "known-success-atomic": (+ OutcomeCode.CONFIRMED_SUCCESS,+ AttemptState.SUCCEEDED,+ "local_completion",+ "execution_succeeded",+ ),+ "known-failure-atomic": (+ OutcomeCode.CONFIRMED_FAILURE,+ AttemptState.FAILED,+ "local_completion",+ "execution_failed",+ ),+ "acknowledged-cancellation-atomic": (+ OutcomeCode.CONFIRMED_CANCELLED_NO_RESULT,+ AttemptState.CANCELLED,+ "cancellation_no_result_ack",+ "execution_cancelled",+ ),+ "acknowledged-timeout-atomic": (+ OutcomeCode.CONFIRMED_TIMEOUT_TERMINATED,+ AttemptState.TIMED_OUT,+ "timeout_termination_ack",+ "execution_timed_out",+ ),+ }[case_alias]+ intent = _postgres_p1c_terminal_intent(revision, outcome=outcome)+ result = await store.commit_terminal_attempt_v3(intent)+ operation_id = _postgres_p1c_terminal_operation_id(intent.attempt_id)+ outbox_id = _postgres_p1c_terminal_derived_uuid(+ operation_id,+ "terminal-outbox",+ )+ publication_key = _postgres_p1c_terminal_derived_uuid(+ operation_id,+ "terminal-publication",+ )+ attempt = await _postgres_p1c_terminal_state(setup_connection)+ logical = await setup_connection.fetchrow(+ "SELECT closure_operation_id,closing_attempt_id,revision "+ "FROM logical_executions WHERE id=$1",+ _uuid(208),+ )+ receipt = await _postgres_p1c_terminal_receipt(setup_connection)+ outbox = await setup_connection.fetchrow(+ "SELECT id,publication_key,attempt_id,campaign_id,event_code,"+ "is_attempt_terminal,finding_count,credential_count,host_count,"+ "artifact_count,latest_operation_id,latest_operation_code,"+ "latest_operation_base_revision "+ "FROM execution_publication_outbox WHERE attempt_id=$1",+ _uuid(210),+ )+ settled_ledgers = await setup_connection.fetchval(+ "SELECT COUNT(*) FROM campaign_execution_budget_ledger "+ "WHERE attempt_id=$1 AND disposition IN ('consumed','released') "+ "AND budget_revision_settled IS NOT NULL",+ _uuid(210),+ )+ assert (result.result, result.revision) == (+ FixedResult.APPLIED,+ revision + 1,+ )+ assert tuple(attempt) == (+ state.value,+ revision + 1,+ outcome.value,+ "settled",+ proof,+ True,+ True,+ "closed_without_retry",+ operation_id+ if outcome in {OutcomeCode.CONFIRMED_SUCCESS, OutcomeCode.CONFIRMED_FAILURE}+ else None,+ operation_id if outcome is OutcomeCode.CONFIRMED_CANCELLED_NO_RESULT else None,+ operation_id if outcome is OutcomeCode.CONFIRMED_TIMEOUT_TERMINATED else None,+ ), "known PostgreSQL terminal settlement changed"+ assert tuple(logical) == (operation_id, _uuid(210), 1), (+ "known terminal outcome did not close its logical execution exactly"+ )+ assert tuple(receipt) == (+ operation_id,+ _postgres_p1c_terminal_operation_code(outcome),+ _uuid(201),+ _uuid(210),+ _uuid(208),+ "system",+ SYSTEM_PRINCIPAL_SUBJECT_REF,+ None,+ False,+ None,+ 2,+ _postgres_p1c_terminal_request_digest(intent),+ FixedResult.APPLIED.value,+ FixedResult.REPLAYED.value,+ _postgres_p1c_terminal_result_digest(intent),+ _uuid(210),+ revision + 1,+ _uuid(208),+ 1,+ ), "known terminal receipt facts changed"+ assert tuple(outbox) == (+ outbox_id,+ publication_key,+ _uuid(210),+ _uuid(201),+ event_code,+ True,+ 0,+ 0,+ 0,+ 0,+ publication_key,+ "insert",+ 0,+ ), "known terminal outcome emitted the wrong publication"+ assert int(settled_ledgers) == 3, (+ "known PostgreSQL terminal budget settlement was incomplete"+ )+ elif case_alias == "uncertain-outcome-invalid-contract":+ uncertain = replace(+ intent,+ outcome_code=OutcomeCode.UNKNOWN_AFTER_RECOVERY,+ execution_result_digest=None,+ )+ trace = _PostgresP1CTerminalTraceStore(database._pool)+ await _postgres_p1c_assert_terminal_rollback(+ setup_connection,+ trace,+ uncertain,+ expected_result=FixedResult.INVALID_CONTRACT,+ )+ assert trace.transaction_entries == 0, (+ "uncertain outcome reached receipt or mutable storage"+ )+ elif case_alias == "single-transaction-zero-nested-acquire":+ pool_probe = _PostgresP1CTerminalPoolProbe(database._pool)+ trace = _PostgresP1CTerminalTraceStore(pool_probe)+ applied = await trace.commit_terminal_attempt_v3(intent)+ assert applied.result is FixedResult.APPLIED+ assert trace.transaction_entries == 1+ assert (pool_probe.acquire_count, pool_probe.release_count) == (1, 1)+ assert len(pool_probe.connection_identities) == 1+ assert trace.connection_identities == pool_probe.connection_identities+ assert trace.read_events[0] == "receipt", (+ "terminal apply read mutable state before receipt classification"+ )+ elif case_alias == "derive-exact-three-held-ledgers":+ applied = await store.commit_terminal_attempt_v3(intent)+ ledgers = await setup_connection.fetch(+ "SELECT budget_kind,disposition,consumed_units "+ "FROM campaign_execution_budget_ledger WHERE attempt_id=$1 "+ "ORDER BY CASE budget_kind WHEN 'noise' THEN 1 "+ "WHEN 'exfiltration' THEN 2 ELSE 3 END",+ _uuid(210),+ )+ assert applied.result is FixedResult.APPLIED+ assert tuple(tuple(row) for row in ledgers) == (+ ("noise", "consumed", 1),+ ("exfiltration", "consumed", 2),+ ("concurrency", "released", 0),+ )+ elif case_alias == "missing-ledger-inconsistent-set-rollback":+ await setup_connection.execute(+ "DELETE FROM campaign_execution_budget_ledger "+ "WHERE attempt_id=$1 AND budget_kind='noise'",+ _uuid(210),+ )+ await _postgres_p1c_assert_terminal_rollback(+ setup_connection,+ store,+ intent,+ expected_result=FixedResult.INCONSISTENT_BUDGET_SET,+ )+ elif case_alias in {+ "duplicate-extra-ledger-inconsistent-set-rollback",+ "wrong-kind-ledger-inconsistent-set-rollback",+ "wrong-campaign-attempt-ledger-inconsistent-set-rollback",+ "non-held-ledger-conflict-operation-rollback",+ }:+ mutations, expected = {+ "duplicate-extra-ledger-inconsistent-set-rollback": (+ ("duplicate",),+ FixedResult.INCONSISTENT_BUDGET_SET,+ ),+ "wrong-kind-ledger-inconsistent-set-rollback": (+ ("wrong-kind",),+ FixedResult.INCONSISTENT_BUDGET_SET,+ ),+ "wrong-campaign-attempt-ledger-inconsistent-set-rollback": (+ ("wrong-campaign", "wrong-attempt"),+ FixedResult.INCONSISTENT_BUDGET_SET,+ ),+ "non-held-ledger-conflict-operation-rollback": (+ ("non-held",),+ FixedResult.CONFLICT_OPERATION,+ ),+ }[case_alias]+ for mutation in mutations:+ trace = _PostgresP1CTerminalTraceStore(+ database._pool,+ ledger_mutation=mutation,+ )+ await _postgres_p1c_assert_terminal_rollback(+ setup_connection,+ trace,+ intent,+ expected_result=expected,+ )+ elif case_alias == "current-budget-lock-no-toctou":+ for index, kind in enumerate(("noise", "exfiltration", "concurrency")):+ await setup_connection.execute(+ "UPDATE campaign_execution_budgets SET revision=2,"+ "latest_operation_id=$1,latest_operation_base_revision=1,"+ "latest_operation_code='configure' "+ "WHERE campaign_id=$2 AND budget_kind=$3",+ _uuid(20_310 + index),+ _uuid(201),+ kind,+ )+ expected_budget_ids = tuple(+ str(row["budget_id"])+ for row in await setup_connection.fetch(+ "SELECT budget_id FROM campaign_execution_budget_ledger "+ "WHERE attempt_id=$1 ORDER BY CASE budget_kind "+ "WHEN 'noise' THEN 1 WHEN 'exfiltration' THEN 2 ELSE 3 END",+ _uuid(210),+ )+ )+ trace = _PostgresP1CTerminalTraceStore(database._pool)+ applied = await trace.commit_terminal_attempt_v3(intent)+ revisions = await setup_connection.fetch(+ "SELECT revision FROM campaign_execution_budgets WHERE campaign_id=$1 "+ "ORDER BY CASE budget_kind WHEN 'noise' THEN 1 "+ "WHEN 'exfiltration' THEN 2 ELSE 3 END",+ _uuid(201),+ )+ assert applied.result is FixedResult.APPLIED+ assert tuple(trace.budget_lock_ids) == expected_budget_ids+ assert tuple(trace.lock_events) == (+ ("attempt", _uuid(210)),+ ("ledgers", _uuid(210)),+ *(("budget", budget_id) for budget_id in expected_budget_ids),+ ("logical", _uuid(208)),+ ), "PostgreSQL terminal row-lock order or cardinality changed"+ assert tuple(int(row["revision"]) for row in revisions) == (3, 3, 3)+ elif case_alias == "budget-capacity-inconsistent-set-rollback":+ await setup_connection.execute(+ "UPDATE campaign_execution_budgets SET reserved_units=0 "+ "WHERE campaign_id=$1 AND budget_kind='noise'",+ _uuid(201),+ )+ await _postgres_p1c_assert_terminal_rollback(+ setup_connection,+ store,+ intent,+ expected_result=FixedResult.INCONSISTENT_BUDGET_SET,+ )+ elif case_alias in {+ "budget-write-failure-rollback",+ "output-write-failure-rollback",+ "terminal-write-failure-rollback",+ "logical-closure-write-failure-rollback",+ "outbox-write-failure-rollback",+ "receipt-write-failure-rollback",+ }:+ fail_at = {+ "budget-write-failure-rollback": "budget",+ "output-write-failure-rollback": "output",+ "terminal-write-failure-rollback": "terminal",+ "logical-closure-write-failure-rollback": "logical",+ "outbox-write-failure-rollback": "outbox",+ "receipt-write-failure-rollback": "receipt",+ }[case_alias]+ if fail_at == "output":+ intent = replace(+ intent,+ outputs=(OutputObservation(_uuid(20_320), OutputKind.HOST, _uuid(260)),),+ )+ trace = _PostgresP1CTerminalTraceStore(+ database._pool,+ fail_at=fail_at,+ )+ await _postgres_p1c_assert_terminal_rollback(+ setup_connection,+ trace,+ intent,+ expected_exception=RuntimeError,+ )+ elif case_alias == "non-running-attempt-conflict-state":+ result = await _postgres_p1c_assert_terminal_rollback(+ setup_connection,+ store,+ replace(intent, expected_attempt_revision=revision + 1),+ expected_result=FixedResult.CONFLICT_STATE,+ )+ assert result is not None+ assert result.revision == revision, (+ "attempt-state precedence did not dominate stale revision"+ )+ elif case_alias == "stale-attempt-revision-conflict":+ await _postgres_p1c_assert_terminal_rollback(+ setup_connection,+ store,+ replace(intent, expected_attempt_revision=revision - 1),+ expected_result=FixedResult.CONFLICT_REVISION,+ )+ elif case_alias == "invariant-failure-rollback":+ trace = _PostgresP1CTerminalTraceStore(+ database._pool,+ duplicate_terminal_returning=True,+ )+ await _postgres_p1c_assert_terminal_rollback(+ setup_connection,+ trace,+ intent,+ expected_result=FixedResult.INVARIANT_FAILURE,+ )+ elif case_alias == "cancellation-rollback-and-reuse":+ trace = _PostgresP1CTerminalTraceStore(+ database._pool,+ cancel_at="output",+ )+ await _postgres_p1c_assert_terminal_rollback(+ setup_connection,+ trace,+ intent,+ expected_exception=asyncio.CancelledError,+ )+ reused = await base_store.commit_terminal_attempt_v3(intent)+ assert reused.result is FixedResult.APPLIED+ elif case_alias == "exception-rollback-and-reuse":+ trace = _PostgresP1CTerminalTraceStore(+ database._pool,+ fail_at="exception",+ )+ await _postgres_p1c_assert_terminal_rollback(+ setup_connection,+ trace,+ intent,+ expected_exception=RuntimeError,+ )+ reused = await base_store.commit_terminal_attempt_v3(intent)+ assert reused.result is FixedResult.APPLIED+ elif case_alias == "legacy-terminal-apply-replay-bytes-unchanged":+ operation_id = _uuid(20_400)+ legacy = _postgres_p1c_legacy_terminal_request(operation_id, revision)+ applied = await store.commit_terminal_attempt(legacy)+ receipt_snapshot_before = await _postgres_p1c_terminal_receipt_snapshot(+ setup_connection+ )+ receipt_before = await setup_connection.fetchrow(+ "SELECT * FROM execution_operation_receipts WHERE operation_id=$1",+ operation_id,+ )+ protected_vectors = await setup_connection.fetch(+ "SELECT operation_id,operation_code,binding_contract_version,"+ "request_binding_digest,result_binding_digest "+ "FROM execution_operation_receipts WHERE operation_id=ANY($1::text[]) "+ "ORDER BY operation_id",+ [_uuid(20_200), _uuid(20_202), operation_id],+ )+ replayed = await store.commit_terminal_attempt(legacy)+ receipt_snapshot_after = await _postgres_p1c_terminal_receipt_snapshot(+ setup_connection+ )+ receipt_after = await setup_connection.fetchrow(+ "SELECT * FROM execution_operation_receipts WHERE operation_id=$1",+ operation_id,+ )+ assert (applied.result, replayed.result) == (+ FixedResult.APPLIED,+ FixedResult.REPLAYED,+ )+ assert receipt_snapshot_after == receipt_snapshot_before, (+ "legacy replay changed a top or subordinate receipt"+ )+ assert tuple(receipt_before) == tuple(receipt_after)+ assert receipt_before["operation_code"] == "terminal_succeeded"+ assert receipt_before["binding_contract_version"] == 2+ assert (+ receipt_before["request_binding_digest"]+ == _POSTGRES_P1C_LEGACY_TERMINAL_REQUEST_DIGEST+ ), "legacy terminal request binding bytes drifted"+ assert (+ receipt_before["result_binding_digest"]+ == _POSTGRES_P1C_LEGACY_TERMINAL_RESULT_DIGEST+ ), "legacy terminal result binding bytes drifted"+ assert {str(row["operation_id"]): tuple(row)[1:] for row in protected_vectors} == {+ _uuid(20_200): (+ "outbox_insert",+ 2,+ _POSTGRES_P1C_LEGACY_OUTBOX_REQUEST_DIGEST,+ _POSTGRES_P1C_LEGACY_OUTBOX_RESULT_DIGEST,+ ),+ _uuid(20_202): (+ "budget_settle",+ 2,+ _POSTGRES_P1C_LEGACY_BUDGET_REQUEST_DIGEST,+ _POSTGRES_P1C_LEGACY_BUDGET_RESULT_DIGEST,+ ),+ operation_id: (+ "terminal_succeeded",+ 2,+ _POSTGRES_P1C_LEGACY_TERMINAL_REQUEST_DIGEST,+ _POSTGRES_P1C_LEGACY_TERMINAL_RESULT_DIGEST,+ ),+ }, "legacy top/budget/outbox receipt vectors drifted"+ elif case_alias == "changed-outcome-conflict-operation":+ applied = await store.commit_terminal_attempt_v3(intent)+ receipt_only = _PostgresP1CTerminalTraceStore(+ database._pool,+ receipt_only=True,+ )+ changed = await receipt_only.commit_terminal_attempt_v3(+ replace(+ intent,+ outcome_code=OutcomeCode.CONFIRMED_FAILURE,+ outputs=(),+ execution_result_digest=hashlib.sha256(b"changed-outcome").hexdigest(),+ )+ )+ assert (applied.result, changed.result) == (+ FixedResult.APPLIED,+ FixedResult.CONFLICT_OPERATION,+ )+ assert receipt_only.transaction_entries == 1+ elif case_alias == "changed-result-digest-conflict-operation":+ applied = await store.commit_terminal_attempt_v3(intent)+ receipt_only = _PostgresP1CTerminalTraceStore(+ database._pool,+ receipt_only=True,+ )+ changed = await receipt_only.commit_terminal_attempt_v3(+ replace(+ intent,+ execution_result_digest=hashlib.sha256(b"changed-result").hexdigest(),+ )+ )+ assert (applied.result, changed.result) == (+ FixedResult.APPLIED,+ FixedResult.CONFLICT_OPERATION,+ )+ assert receipt_only.transaction_entries == 1+ elif case_alias in {+ "cancellation-caller-result-digest-invalid-contract",+ "timeout-caller-result-digest-invalid-contract",+ }:+ outcome = (+ OutcomeCode.CONFIRMED_CANCELLED_NO_RESULT+ if case_alias.startswith("cancellation")+ else OutcomeCode.CONFIRMED_TIMEOUT_TERMINATED+ )+ invalid = _postgres_p1c_terminal_intent(+ revision,+ outcome=outcome,+ execution_result_digest=_POSTGRES_P1C_TERMINAL_RESULT_DIGEST,+ )+ trace = _PostgresP1CTerminalTraceStore(database._pool)+ await _postgres_p1c_assert_terminal_rollback(+ setup_connection,+ trace,+ invalid,+ expected_result=FixedResult.INVALID_CONTRACT,+ )+ assert trace.transaction_entries == 0, (+ "non-result outcome reached receipt or mutable storage"+ )+ elif case_alias == "canonical-output-order-exact-replay":+ await setup_connection.execute(+ "INSERT INTO hosts(id,campaign_id,ip_address) VALUES($1,$2,$3)",+ _uuid(20_500),+ _uuid(201),+ "192.0.2.2",+ )+ await setup_connection.execute(+ "INSERT INTO loot(id,campaign_id,host_id,loot_type,name) "+ "VALUES($1,$2,$3,$4,$5)",+ _uuid(20_503),+ _uuid(201),+ _uuid(260),+ "artifact",+ "fixed-output",+ )+ outputs = (+ OutputObservation(_uuid(20_502), OutputKind.HOST, _uuid(20_500)),+ OutputObservation(_uuid(20_503), OutputKind.ARTIFACT, _uuid(20_503)),+ OutputObservation(_uuid(20_501), OutputKind.HOST, _uuid(260)),+ )+ forward = replace(intent, outputs=outputs)+ reversed_intent = replace(intent, outputs=tuple(reversed(outputs)))+ trace = _PostgresP1CTerminalTraceStore(database._pool)+ applied = await trace.commit_terminal_attempt_v3(forward)+ replayed = await trace.commit_terminal_attempt_v3(reversed_intent)+ rows = await setup_connection.fetch(+ "SELECT id,host_id,loot_id FROM execution_output_links "+ "WHERE attempt_id=$1 ORDER BY "+ "CASE WHEN loot_id IS NOT NULL THEN 0 ELSE 1 END,host_id,id",+ _uuid(210),+ )+ assert (applied.result, replayed.result) == (+ FixedResult.APPLIED,+ FixedResult.REPLAYED,+ )+ assert _postgres_p1c_terminal_request_digest(+ forward+ ) == _postgres_p1c_terminal_request_digest(reversed_intent)+ assert tuple(trace.output_insert_order) == (+ _uuid(20_503),+ _uuid(20_501),+ _uuid(20_502),+ ), "PostgreSQL output persistence did not use canonical semantic order"+ assert tuple(tuple(row) for row in rows) == (+ (_uuid(20_503), None, _uuid(20_503)),+ (_uuid(20_501), _uuid(260), None),+ (_uuid(20_502), _uuid(20_500), None),+ )+ elif case_alias == "terminal-operation-and-system-principal-namespace":+ applied = await store.commit_terminal_attempt_v3(intent)+ receipt = await _postgres_p1c_terminal_receipt(setup_connection)+ actor = await setup_connection.fetchrow(+ "SELECT actor_subject_ref,actor_user_id FROM execution_attempts WHERE id=$1",+ _uuid(210),+ )+ assert applied.result is FixedResult.APPLIED+ assert tuple(receipt[:11]) == (+ _postgres_p1c_terminal_operation_id(_uuid(210)),+ "terminal_succeeded",+ _uuid(201),+ _uuid(210),+ _uuid(208),+ "system",+ SYSTEM_PRINCIPAL_SUBJECT_REF,+ None,+ False,+ None,+ 2,+ )+ assert tuple(actor) == (_uuid(200), _uuid(200))+ assert SYSTEM_PRINCIPAL_SUBJECT_REF != str(actor[0]), (+ "reserved system subject collided with the persisted actor"+ )+ assert ("system", SYSTEM_PRINCIPAL_SUBJECT_REF) != (+ "actor",+ str(actor[0]),+ )+ else: # pragma: no cover - tuple/dispatcher drift must be loud.+ raise AssertionError(f"unhandled PostgreSQL terminal alias: {case_alias}")+ finally:+ if setup_connection is not None:+ await database._pool.release(setup_connection)+ await database.close()diff --git a/tests/integration/test_postgres_execution_lifecycle_migration.py b/tests/integration/test_postgres_execution_lifecycle_migration.pynew file mode 100644index 0000000..fd6175c--- /dev/null+++ b/tests/integration/test_postgres_execution_lifecycle_migration.py@@ -0,0 +1,1109 @@+"""Real PostgreSQL 16 catalog tests for revision 0010."""++from __future__ import annotations++import hashlib+import json++import pytest++from ares.db.execution_lifecycle import (+ POSTGRES_LIFECYCLE_DDL,+ V11_AUTHORITY_TABLES,+ validate_postgresql_admission_authority_catalog,+ validate_postgresql_lifecycle_catalog,+)+from tests.integration.test_postgres_migration_portability import (+ _alembic,+ _migration_url,+ _postgres_harness,+)++_EXPECTED_LIFECYCLE_TABLES = (+ "campaign_execution_authority_revisions",+ "campaign_execution_budget_ledger",+ "campaign_execution_budgets",+ "execution_actor_authority_revisions",+ "execution_attempt_approvals",+ "execution_attempts",+ "execution_gateway_state",+ "execution_operation_receipts",+ "execution_output_links",+ "execution_publication_outbox",+ "logical_executions",+)+# Independently reproduced from two clean PostgreSQL-16 catalogs using only the+# handwritten catalog queries below after freezing the revision-0010 P1-B DDL.+_POSTGRES_LITERAL_ORACLE_FINGERPRINT_V1 = (+ "94e0e4fd279991da5ed029521cec92810d8738d4b4bc0de1254fc2fd96230ff1"+)++_P1B_LOGICAL_EXECUTION_COLUMNS = (+ "id",+ "submission_id",+ "campaign_id",+ "actor_subject_ref",+ "actor_user_id",+ "module_id",+ "ingress_code",+ "admission_operation_id",+ "submission_binding_contract_version",+ "submission_request_binding_digest",+ "submission_result_code",+ "submission_exact_replay_code",+ "submission_result_binding_digest",+ "highest_attempt_ordinal",+ "revision",+ "created_at",+ "closure_operation_id",+ "closure_authority_subject_ref",+ "closure_authority_user_id",+ "closure_authority_revision",+ "closing_attempt_id",+ "closed_at",+)++_P1B_RECEIPT_COLUMNS = (+ "operation_id",+ "operation_code",+ "campaign_id",+ "primary_target_id",+ "secondary_target_id",+ "principal_kind",+ "principal_subject_ref",+ "principal_user_id",+ "principal_authority_revision_present",+ "principal_authority_revision",+ "binding_contract_version",+ "request_binding_digest",+ "expected_revision_present",+ "expected_revision",+ "secondary_expected_revision_present",+ "secondary_expected_revision",+ "owner_ref",+ "lease_generation",+ "result_code",+ "exact_replay_code",+ "result_binding_digest",+ "result_identity",+ "result_revision_present",+ "result_revision",+ "secondary_result_identity",+ "secondary_result_revision_present",+ "secondary_result_revision",+ "created_at",+)++_POSTGRES_LITERAL_DRIFT_CASES = (+ ("relation-persistence", "ALTER TABLE execution_gateway_state SET UNLOGGED"),+ ("relation-rls", "ALTER TABLE execution_attempts ENABLE ROW LEVEL SECURITY"),+ ("relation-force-rls", "ALTER TABLE execution_attempts FORCE ROW LEVEL SECURITY"),+ ("column-order-extra", "ALTER TABLE execution_attempts ADD COLUMN catalog_drift BIGINT"),+ ("column-type", "ALTER TABLE execution_attempts ALTER COLUMN state TYPE VARCHAR(64)"),+ ("column-nullability", "ALTER TABLE execution_attempts ALTER COLUMN state DROP NOT NULL"),+ ("column-default", "ALTER TABLE execution_attempts ALTER COLUMN revision SET DEFAULT 1"),+ (+ "column-collation",+ "ALTER TABLE execution_attempts ALTER COLUMN bounded_recovery_proof_code "+ 'TYPE TEXT COLLATE "C"',+ ),+ ("check-definition", "ALTER TABLE execution_attempts DROP CONSTRAINT ck_ea_history_dnf"),+ (+ "foreign-key-deferrability",+ "ALTER TABLE execution_attempts ALTER CONSTRAINT fk_ea_logical_campaign NOT DEFERRABLE",+ ),+ (+ "index-key-order",+ "DROP INDEX ix_ea_logical_state; CREATE INDEX ix_ea_logical_state "+ "ON execution_attempts (state, logical_execution_id, ordinal)",+ ),+ (+ "index-predicate",+ "DROP INDEX uq_ea_one_child; CREATE UNIQUE INDEX uq_ea_one_child "+ "ON execution_attempts (logical_execution_id, parent_attempt_id) "+ "WHERE parent_attempt_id IS NULL",+ ),+ (+ "index-method",+ "DROP INDEX ix_eol_attempt; CREATE INDEX ix_eol_attempt "+ "ON execution_output_links USING HASH (attempt_id)",+ ),+ ("unexpected-index", "CREATE INDEX ix_ea_catalog_drift ON execution_attempts (id)"),+ (+ "unexpected-trigger",+ "CREATE FUNCTION lifecycle_catalog_drift() RETURNS trigger LANGUAGE plpgsql "+ "AS 'BEGIN RETURN NEW; END'; CREATE TRIGGER lifecycle_catalog_drift "+ "BEFORE UPDATE ON execution_attempts FOR EACH ROW "+ "EXECUTE FUNCTION lifecycle_catalog_drift()",+ ),+ (+ "unexpected-policy",+ "ALTER TABLE execution_attempts ENABLE ROW LEVEL SECURITY; "+ "CREATE POLICY lifecycle_catalog_drift ON execution_attempts USING (true)",+ ),+ (+ "unexpected-rule",+ "CREATE RULE lifecycle_catalog_drift AS ON UPDATE TO execution_gateway_state "+ "DO ALSO NOTHING",+ ),+)++# Generation-11 catalog authority is intentionally specified here as literal+# mutations rather than by reusing migration or validator constants. Every+# case receives a fresh database at revision 0011.+_POSTGRES_V11_LITERAL_DRIFT_CASES = (+ (+ "relation-presence",+ "DROP TABLE campaign_execution_actor_grants CASCADE",+ ),+ (+ "relation-kind",+ "DROP TABLE execution_attempt_destination_observations CASCADE; "+ "CREATE VIEW execution_attempt_destination_observations AS SELECT "+ "NULL::text AS attempt_id,NULL::text AS campaign_id,NULL::bigint AS ordinal,"+ "NULL::text AS destination_ref_digest,NULL::bigint AS authority_revision,"+ "NULL::bigint AS normalization_version,NULL::bigint AS observed_at WHERE false",+ ),+ (+ "relation-persistence",+ "ALTER TABLE campaign_execution_actor_grants SET UNLOGGED",+ ),+ (+ "relation-partition",+ "DROP TABLE execution_attempt_destination_observations CASCADE; "+ "CREATE TABLE execution_attempt_destination_observations("+ "attempt_id TEXT NOT NULL,campaign_id TEXT NOT NULL,ordinal BIGINT NOT NULL,"+ "destination_ref_digest TEXT NOT NULL,authority_revision BIGINT NOT NULL,"+ "normalization_version BIGINT NOT NULL,observed_at BIGINT NOT NULL DEFAULT "+ "((EXTRACT(epoch FROM clock_timestamp())*1000)::bigint)) "+ "PARTITION BY RANGE (ordinal)",+ ),+ (+ "relation-rls",+ "ALTER TABLE campaign_execution_actor_grants ENABLE ROW LEVEL SECURITY",+ ),+ (+ "relation-force-rls",+ "ALTER TABLE campaign_execution_actor_grants FORCE ROW LEVEL SECURITY",+ ),+ (+ "column-order-extra",+ "ALTER TABLE campaign_execution_actor_grants ADD COLUMN catalog_drift BIGINT",+ ),+ (+ "column-presence",+ "ALTER TABLE campaign_execution_actor_grants DROP COLUMN binding_digest CASCADE",+ ),+ (+ "column-type",+ "ALTER TABLE campaign_execution_actor_grants ALTER COLUMN authority_state TYPE VARCHAR(64)",+ ),+ (+ "column-nullability",+ "ALTER TABLE campaign_execution_actor_grants ALTER COLUMN authority_state DROP NOT NULL",+ ),+ (+ "column-default",+ "ALTER TABLE campaign_execution_actor_grants ALTER COLUMN revision SET DEFAULT 1",+ ),+ (+ "column-collation",+ 'ALTER TABLE execution_approval_authorities ALTER COLUMN module_id TYPE TEXT COLLATE "C"',+ ),+ (+ "primary-key-presence",+ "ALTER TABLE campaign_execution_actor_grants DROP CONSTRAINT pk_ceag",+ ),+ (+ "primary-key-order",+ "ALTER TABLE campaign_execution_actor_grants DROP CONSTRAINT pk_ceag; "+ "ALTER TABLE campaign_execution_actor_grants ADD CONSTRAINT pk_ceag "+ "PRIMARY KEY (actor_user_id,campaign_id)",+ ),+ (+ "unique-presence",+ "ALTER TABLE execution_approval_authorities DROP CONSTRAINT uq_eapa_ref",+ ),+ (+ "unique-key-order",+ "ALTER TABLE execution_attempt_destination_observations "+ "DROP CONSTRAINT uq_eado_attempt_destination; "+ "ALTER TABLE execution_attempt_destination_observations "+ "ADD CONSTRAINT uq_eado_attempt_destination "+ "UNIQUE (destination_ref_digest,attempt_id)",+ ),+ (+ "check-presence",+ "ALTER TABLE campaign_execution_actor_grants DROP CONSTRAINT ck_ceag_shape",+ ),+ (+ "check-definition",+ "ALTER TABLE campaign_execution_actor_grants DROP CONSTRAINT ck_ceag_shape; "+ "ALTER TABLE campaign_execution_actor_grants ADD CONSTRAINT ck_ceag_shape "+ "CHECK (revision >= 0)",+ ),+ (+ "foreign-key-presence",+ "ALTER TABLE execution_attempt_destination_observations DROP CONSTRAINT fk_eado_attempt",+ ),+ (+ "foreign-key-local-columns",+ "ALTER TABLE execution_attempt_credential_observations "+ "DROP CONSTRAINT fk_eaco_attempt; "+ "ALTER TABLE execution_attempt_credential_observations "+ "ADD CONSTRAINT fk_eaco_attempt FOREIGN KEY (campaign_id,credential_id) "+ "REFERENCES execution_attempts(campaign_id,id) "+ "ON UPDATE NO ACTION ON DELETE NO ACTION DEFERRABLE INITIALLY DEFERRED",+ ),+ (+ "foreign-key-referenced-relation",+ "ALTER TABLE execution_attempt_destination_observations "+ "DROP CONSTRAINT fk_eado_attempt; "+ "ALTER TABLE execution_attempt_destination_observations "+ "ADD CONSTRAINT fk_eado_attempt FOREIGN KEY (campaign_id,attempt_id) "+ "REFERENCES logical_executions(campaign_id,id) "+ "ON UPDATE NO ACTION ON DELETE NO ACTION DEFERRABLE INITIALLY DEFERRED",+ ),+ (+ "foreign-key-referenced-columns",+ "ALTER TABLE execution_attempt_destination_observations "+ "DROP CONSTRAINT fk_eado_attempt; "+ "ALTER TABLE execution_attempt_destination_observations "+ "ADD CONSTRAINT fk_eado_attempt FOREIGN KEY (campaign_id,attempt_id) "+ "REFERENCES execution_attempts(logical_execution_id,id) "+ "ON UPDATE NO ACTION ON DELETE NO ACTION DEFERRABLE INITIALLY DEFERRED",+ ),+ (+ "foreign-key-update-action",+ "ALTER TABLE execution_attempt_destination_observations "+ "DROP CONSTRAINT fk_eado_attempt; "+ "ALTER TABLE execution_attempt_destination_observations "+ "ADD CONSTRAINT fk_eado_attempt FOREIGN KEY (campaign_id,attempt_id) "+ "REFERENCES execution_attempts(campaign_id,id) "+ "ON UPDATE CASCADE ON DELETE NO ACTION DEFERRABLE INITIALLY DEFERRED",+ ),+ (+ "foreign-key-delete-action",+ "ALTER TABLE execution_attempt_destination_observations "+ "DROP CONSTRAINT fk_eado_attempt; "+ "ALTER TABLE execution_attempt_destination_observations "+ "ADD CONSTRAINT fk_eado_attempt FOREIGN KEY (campaign_id,attempt_id) "+ "REFERENCES execution_attempts(campaign_id,id) "+ "ON UPDATE NO ACTION ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED",+ ),+ (+ "foreign-key-deferrability",+ "ALTER TABLE execution_attempt_destination_observations "+ "ALTER CONSTRAINT fk_eado_attempt NOT DEFERRABLE",+ ),+ (+ "foreign-key-initially-deferred",+ "ALTER TABLE execution_attempt_destination_observations "+ "ALTER CONSTRAINT fk_eado_attempt DEFERRABLE INITIALLY IMMEDIATE",+ ),+ (+ "foreign-key-validation",+ "ALTER TABLE execution_attempt_destination_observations "+ "DROP CONSTRAINT fk_eado_attempt; "+ "ALTER TABLE execution_attempt_destination_observations "+ "ADD CONSTRAINT fk_eado_attempt FOREIGN KEY (campaign_id,attempt_id) "+ "REFERENCES execution_attempts(campaign_id,id) "+ "ON UPDATE NO ACTION ON DELETE NO ACTION DEFERRABLE INITIALLY DEFERRED NOT VALID",+ ),+ (+ "explicit-index-presence",+ "DROP INDEX ix_ceag_actor_state",+ ),+ (+ "backing-index-presence",+ "ALTER TABLE execution_attempt_destination_observations "+ "DROP CONSTRAINT uq_eado_attempt_destination",+ ),+ (+ "index-key-order",+ "DROP INDEX ix_ceag_actor_state; CREATE INDEX ix_ceag_actor_state "+ "ON campaign_execution_actor_grants(authority_state,actor_user_id,campaign_id)",+ ),+ (+ "index-uniqueness",+ "DROP INDEX ix_ceag_actor_state; CREATE UNIQUE INDEX ix_ceag_actor_state "+ "ON campaign_execution_actor_grants(actor_user_id,authority_state,campaign_id)",+ ),+ (+ "index-method",+ "DROP INDEX ix_ceag_actor_state; CREATE INDEX ix_ceag_actor_state "+ "ON campaign_execution_actor_grants USING HASH(actor_user_id)",+ ),+ (+ "index-predicate",+ "DROP INDEX ix_ceag_actor_state; CREATE INDEX ix_ceag_actor_state "+ "ON campaign_execution_actor_grants(actor_user_id,authority_state,campaign_id) "+ "WHERE authority_state='active'",+ ),+ (+ "index-expression",+ "DROP INDEX ix_ceag_actor_state; CREATE INDEX ix_ceag_actor_state "+ "ON campaign_execution_actor_grants((lower(actor_user_id)),authority_state,campaign_id)",+ ),+ (+ "index-validity",+ "SET allow_system_table_mods=on; "+ "UPDATE pg_catalog.pg_index SET indisvalid=false "+ "WHERE indexrelid='ix_ceag_actor_state'::regclass",+ ),+ (+ "index-readiness",+ "SET allow_system_table_mods=on; "+ "UPDATE pg_catalog.pg_index SET indisready=false "+ "WHERE indexrelid='ix_ceag_actor_state'::regclass",+ ),+ (+ "altered-column-check",+ "ALTER TABLE logical_executions DROP CONSTRAINT "+ "logical_executions_admission_authority_contract_version_check",+ ),+ (+ "credential-authority-check",+ "ALTER TABLE credentials DROP CONSTRAINT credentials_execution_authority_state_check",+ ),+ (+ "additive-receipt-operation-code",+ "ALTER TABLE execution_operation_receipts DROP CONSTRAINT ck_eor_operation_code",+ ),+ (+ "unexpected-relation",+ "CREATE TABLE campaign_execution_unexpected_authority(id TEXT PRIMARY KEY)",+ ),+ (+ "unexpected-constraint",+ "ALTER TABLE campaign_execution_actor_grants ADD CONSTRAINT "+ "ck_ceag_catalog_drift CHECK (true)",+ ),+ (+ "unexpected-index",+ "CREATE INDEX ix_ceag_catalog_drift ON campaign_execution_actor_grants(campaign_id)",+ ),+ (+ "unexpected-trigger",+ "CREATE FUNCTION admission_authority_catalog_drift() RETURNS trigger "+ "LANGUAGE plpgsql AS 'BEGIN RETURN NEW; END'; "+ "CREATE TRIGGER admission_authority_catalog_drift BEFORE UPDATE "+ "ON campaign_execution_actor_grants FOR EACH ROW "+ "EXECUTE FUNCTION admission_authority_catalog_drift()",+ ),+ (+ "unexpected-policy",+ "CREATE POLICY admission_authority_catalog_drift "+ "ON campaign_execution_actor_grants USING (true)",+ ),+ (+ "unexpected-rule",+ "CREATE RULE admission_authority_catalog_drift AS ON UPDATE "+ "TO campaign_execution_actor_grants DO ALSO NOTHING",+ ),+)++_POSTGRES_V11_LITERAL_DRIFT_COUNT = 45+_POSTGRES_V11_LITERAL_DRIFT_ALIASES_SHA256 = (+ "95c34bebd5d9d0663b08e9604749e083ee67e57b987adee190c23c8c9ed2ddc9"+)+++ ("case_alias", "mutation"),+ _POSTGRES_V11_LITERAL_DRIFT_CASES,+ ids=[case[0] for case in _POSTGRES_V11_LITERAL_DRIFT_CASES],+)+async def test_postgres_generation_11_validator_rejects_literal_catalog_drift(+ case_alias: str,+ mutation: str,+) -> None:+ aliases = tuple(case[0] for case in _POSTGRES_V11_LITERAL_DRIFT_CASES)+ assert len(aliases) == _POSTGRES_V11_LITERAL_DRIFT_COUNT+ assert len(set(aliases)) == _POSTGRES_V11_LITERAL_DRIFT_COUNT+ assert (+ hashlib.sha256(("\n".join(aliases) + "\n").encode()).hexdigest()+ == _POSTGRES_V11_LITERAL_DRIFT_ALIASES_SHA256+ )+ assert case_alias in aliases++ async with _postgres_harness() as harness:+ await _alembic(harness, "upgrade", "0011")+ import asyncpg++ connection = await asyncpg.connect(+ _migration_url(+ harness.config,+ harness.database_name,+ ordinary_driver=True,+ )+ )+ try:+ await connection.execute(mutation)+ with pytest.raises(+ RuntimeError,+ match="Incompatible admission authority schema",+ ):+ await validate_postgresql_admission_authority_catalog(connection)+ finally:+ await connection.close()+++async def _independent_postgres_catalog_fingerprint(connection) -> str:+ names = list(_EXPECTED_LIFECYCLE_TABLES)+ facts: list[tuple[object, ...]] = []+ queries = (+ (+ "relation",+ "SELECT c.relname,c.relkind::text,c.relpersistence::text,c.relispartition,"+ "c.relrowsecurity,c.relforcerowsecurity,c.reloptions "+ "FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace "+ "WHERE n.nspname=current_schema() AND c.relname=ANY($1::text[]) "+ "ORDER BY c.relname",+ (names,),+ ),+ (+ "column",+ "SELECT c.relname,a.attnum,a.attname,format_type(a.atttypid,a.atttypmod),"+ "a.attndims,a.attnotnull,pg_get_expr(d.adbin,d.adrelid,false),"+ "a.attidentity::text,a.attgenerated::text,coalesce(coll.collname,'') "+ "FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace "+ "JOIN pg_attribute a ON a.attrelid=c.oid AND a.attnum>0 AND NOT a.attisdropped "+ "LEFT JOIN pg_attrdef d ON d.adrelid=a.attrelid AND d.adnum=a.attnum "+ "LEFT JOIN pg_collation coll ON coll.oid=nullif(a.attcollation,0) "+ "WHERE n.nspname=current_schema() AND c.relname=ANY($1::text[]) "+ "ORDER BY c.relname,a.attnum",+ (names,),+ ),+ (+ "constraint",+ "SELECT c.relname,con.conname,con.contype::text,"+ "pg_get_constraintdef(con.oid,false),con.conkey::text,"+ "coalesce(rn.nspname,''),coalesce(rr.relname,''),"+ "coalesce(con.confkey::text,''),con.confmatchtype::text,"+ "con.confupdtype::text,con.confdeltype::text,con.condeferrable,"+ "con.condeferred,con.convalidated FROM pg_class c "+ "JOIN pg_namespace n ON n.oid=c.relnamespace "+ "JOIN pg_constraint con ON con.conrelid=c.oid "+ "LEFT JOIN pg_class rr ON rr.oid=con.confrelid "+ "LEFT JOIN pg_namespace rn ON rn.oid=rr.relnamespace "+ "WHERE n.nspname=current_schema() AND c.relname=ANY($1::text[]) "+ "ORDER BY c.relname,con.conname",+ (names,),+ ),+ (+ "index",+ "SELECT c.relname,idx.relname,i.indisunique,i.indisprimary,i.indisvalid,"+ "i.indisready,am.amname,i.indkey::text,i.indnkeyatts,i.indnatts,"+ "pg_get_expr(i.indexprs,i.indrelid,false),"+ "pg_get_expr(i.indpred,i.indrelid,false),pg_get_indexdef(i.indexrelid,0,false) "+ "FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace "+ "JOIN pg_index i ON i.indrelid=c.oid JOIN pg_class idx ON idx.oid=i.indexrelid "+ "JOIN pg_am am ON am.oid=idx.relam "+ "WHERE n.nspname=current_schema() AND c.relname=ANY($1::text[]) "+ "ORDER BY c.relname,idx.relname",+ (names,),+ ),+ (+ "trigger",+ "SELECT c.relname,t.tgname,t.tgenabled::text,t.tgisinternal,"+ "pg_get_triggerdef(t.oid,false) FROM pg_trigger t "+ "JOIN pg_class c ON c.oid=t.tgrelid "+ "JOIN pg_namespace n ON n.oid=c.relnamespace "+ "WHERE n.nspname=current_schema() AND NOT t.tgisinternal "+ "AND c.relname=ANY($1::text[]) ORDER BY c.relname,t.tgname",+ (names,),+ ),+ (+ "function",+ "SELECT n.nspname,p.proname,pg_get_function_identity_arguments(p.oid),"+ "pg_get_function_result(p.oid),l.lanname,p.prosecdef,p.proleakproof,"+ "p.provolatile::text,p.proparallel::text,pg_get_functiondef(p.oid) "+ "FROM pg_proc p JOIN pg_namespace n ON n.oid=p.pronamespace "+ "JOIN pg_language l ON l.oid=p.prolang "+ "WHERE n.nspname=current_schema() "+ "AND p.proname='execution_operation_receipt_immutable' "+ "ORDER BY n.nspname,p.proname,pg_get_function_identity_arguments(p.oid)",+ (),+ ),+ )+ for kind, query, arguments in queries:+ for row in await connection.fetch(query, *arguments):+ facts.append((kind, *tuple(row)))+ absence = await connection.fetchrow(+ "SELECT (SELECT count(*) FROM pg_policy p JOIN pg_class c ON c.oid=p.polrelid "+ "JOIN pg_namespace n ON n.oid=c.relnamespace WHERE n.nspname=current_schema() "+ "AND c.relname=ANY($1::text[])),"+ "(SELECT count(*) FROM pg_inherits h JOIN pg_class c ON c.oid=h.inhrelid "+ "JOIN pg_namespace n ON n.oid=c.relnamespace WHERE n.nspname=current_schema() "+ "AND c.relname=ANY($1::text[])),"+ "(SELECT count(*) FROM pg_rewrite r JOIN pg_class c ON c.oid=r.ev_class "+ "JOIN pg_namespace n ON n.oid=c.relnamespace WHERE n.nspname=current_schema() "+ "AND r.rulename<>'_RETURN' AND c.relname=ANY($1::text[]))",+ names,+ )+ gateway = await connection.fetchrow(+ "SELECT singleton_id,mode,catalog_digest,activation_revision,activation_at,revision "+ "FROM execution_gateway_state"+ )+ facts.append(("absence", *tuple(absence)))+ facts.append(("gateway", *tuple(gateway)))+ payload = json.dumps(facts, ensure_ascii=True, separators=(",", ":"))+ return hashlib.sha256(payload.encode("ascii")).hexdigest()+++ ("case_alias", "mutation"),+ _POSTGRES_LITERAL_DRIFT_CASES,+ ids=[case[0] for case in _POSTGRES_LITERAL_DRIFT_CASES],+)+async def test_postgres_runtime_validator_rejects_literal_catalog_drift(+ case_alias: str,+ mutation: str,+) -> None:+ del case_alias+ async with _postgres_harness() as harness:+ await _alembic(harness, "upgrade", "0010")+ import asyncpg++ connection = await asyncpg.connect(+ _migration_url(+ harness.config,+ harness.database_name,+ ordinary_driver=True,+ )+ )+ try:+ await connection.execute(mutation)+ with pytest.raises(+ RuntimeError,+ match="Incompatible execution lifecycle schema",+ ):+ await validate_postgresql_lifecycle_catalog(connection)+ finally:+ await connection.close()+++async def test_postgres_head_0010_has_exact_lifecycle_relation_shape() -> None:+ async with _postgres_harness() as harness:+ await _alembic(harness, "upgrade", "0010")+ import asyncpg++ connection = await asyncpg.connect(+ _migration_url(+ harness.config,+ harness.database_name,+ ordinary_driver=True,+ )+ )+ try:+ revision = await connection.fetchval("SELECT version_num FROM alembic_version")+ rows = await connection.fetch(+ "SELECT c.relname,c.relkind::text,c.relpersistence::text,"+ "c.relispartition,c.relrowsecurity,c.relforcerowsecurity "+ "FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace "+ "WHERE n.nspname=current_schema() AND c.relname=ANY($1::text[]) "+ "ORDER BY c.relname",+ list(_EXPECTED_LIFECYCLE_TABLES),+ )+ trigger_rows = await connection.fetch(+ "SELECT c.relname,t.tgname,t.tgenabled::text,t.tgisinternal,"+ "pg_get_triggerdef(t.oid,false) AS definition FROM pg_trigger t "+ "JOIN pg_class c ON c.oid=t.tgrelid "+ "JOIN pg_namespace n ON n.oid=c.relnamespace "+ "WHERE n.nspname=current_schema() AND NOT t.tgisinternal "+ "AND c.relname=ANY($1::text[]) ORDER BY c.relname,t.tgname",+ list(_EXPECTED_LIFECYCLE_TABLES),+ )+ function_rows = await connection.fetch(+ "SELECT p.proname,pg_get_function_identity_arguments(p.oid) AS arguments,"+ "pg_get_function_result(p.oid) AS result,l.lanname,p.prosecdef,"+ "p.proleakproof,p.provolatile::text,p.proparallel::text,"+ "pg_get_functiondef(p.oid) AS definition FROM pg_proc p "+ "JOIN pg_namespace n ON n.oid=p.pronamespace "+ "JOIN pg_language l ON l.oid=p.prolang "+ "WHERE n.nspname=current_schema() "+ "AND p.proname='execution_operation_receipt_immutable' "+ "ORDER BY p.proname,pg_get_function_identity_arguments(p.oid)"+ )+ policy_count = await connection.fetchval(+ "SELECT count(*) FROM pg_policy p JOIN pg_class c ON c.oid=p.polrelid "+ "JOIN pg_namespace n ON n.oid=c.relnamespace "+ "WHERE n.nspname=current_schema() AND c.relname=ANY($1::text[])",+ list(_EXPECTED_LIFECYCLE_TABLES),+ )+ logical_columns = await connection.fetch(+ "SELECT a.attname FROM pg_class c "+ "JOIN pg_namespace n ON n.oid=c.relnamespace "+ "JOIN pg_attribute a ON a.attrelid=c.oid "+ "AND a.attnum>0 AND NOT a.attisdropped "+ "WHERE n.nspname=current_schema() AND c.relname='logical_executions' "+ "ORDER BY a.attnum"+ )+ receipt_columns = await connection.fetch(+ "SELECT a.attname FROM pg_class c "+ "JOIN pg_namespace n ON n.oid=c.relnamespace "+ "JOIN pg_attribute a ON a.attrelid=c.oid "+ "AND a.attnum>0 AND NOT a.attisdropped "+ "WHERE n.nspname=current_schema() "+ "AND c.relname='execution_operation_receipts' ORDER BY a.attnum"+ )+ receipt_constraints = await connection.fetch(+ "SELECT con.conname,con.contype::text,pg_get_constraintdef(con.oid,false) "+ "AS definition FROM pg_constraint con "+ "JOIN pg_class c ON c.oid=con.conrelid "+ "JOIN pg_namespace n ON n.oid=c.relnamespace "+ "WHERE n.nspname=current_schema() "+ "AND c.relname='execution_operation_receipts' ORDER BY con.conname"+ )+ finally:+ await connection.close()+ assert revision == "0010", "PostgreSQL head changed"+ assert tuple(str(row["relname"]) for row in rows) == _EXPECTED_LIFECYCLE_TABLES, (+ "PostgreSQL lifecycle inventory changed"+ )+ assert all(+ tuple(+ row[key]+ for key in (+ "relkind",+ "relpersistence",+ "relispartition",+ "relrowsecurity",+ "relforcerowsecurity",+ )+ )+ == ("r", "p", False, False, False)+ for row in rows+ ), "PostgreSQL relation metadata changed"+ assert tuple(str(row["attname"]) for row in logical_columns) == (+ _P1B_LOGICAL_EXECUTION_COLUMNS+ ), "submission authority columns changed"+ assert tuple(str(row["attname"]) for row in receipt_columns) == _P1B_RECEIPT_COLUMNS, (+ "receipt-v2 column order changed"+ )+ assert tuple(+ (str(row["relname"]), str(row["tgname"]), str(row["tgenabled"]), row["tgisinternal"])+ for row in trigger_rows+ ) == (("execution_operation_receipts", "trg_eor_immutable", "O", False),), (+ "PostgreSQL receipt immutability trigger allowlist changed"+ )+ assert "BEFORE DELETE OR UPDATE" in str(trigger_rows[0]["definition"]), (+ "PostgreSQL receipt immutability trigger events changed"+ )+ assert "EXECUTE FUNCTION execution_operation_receipt_immutable()" in str(+ trigger_rows[0]["definition"]+ ), "PostgreSQL receipt immutability trigger function changed"+ assert tuple(+ (+ str(row["proname"]),+ str(row["arguments"]),+ str(row["result"]),+ str(row["lanname"]),+ row["prosecdef"],+ row["proleakproof"],+ str(row["provolatile"]),+ str(row["proparallel"]),+ )+ for row in function_rows+ ) == (+ (+ "execution_operation_receipt_immutable",+ "",+ "trigger",+ "plpgsql",+ False,+ False,+ "v",+ "u",+ ),+ ), "PostgreSQL receipt immutability function allowlist changed"+ assert "immutable execution operation receipt" in str(function_rows[0]["definition"]), (+ "PostgreSQL receipt immutability error changed"+ )+ assert "55000" in str(function_rows[0]["definition"]), (+ "PostgreSQL receipt immutability SQLSTATE changed"+ )+ constraint_definitions = {+ str(row["conname"]): (str(row["contype"]), str(row["definition"]))+ for row in receipt_constraints+ }+ assert constraint_definitions["ck_eor_contract"][0] == "c", (+ "receipt-v2 contract constraint type changed"+ )+ assert "binding_contract_version = 2" in constraint_definitions["ck_eor_contract"][1], (+ "receipt-v2 contract check changed"+ )+ assert "ck_eor_principal_shape" in constraint_definitions, (+ "receipt principal-shape check missing"+ )+ assert "ck_eor_presence" in constraint_definitions, "receipt presence-bit check missing"+ assert "ck_eor_operation_shape" in constraint_definitions, (+ "receipt operation-specific revision-presence check missing"+ )+ assert "ck_eor_outbox_owner_shape" in constraint_definitions, (+ "receipt outbox owner/generation check missing"+ )+ assert not any(kind == "f" for kind, _definition in constraint_definitions.values()), (+ "historical receipts gained a target foreign key"+ )+ assert int(policy_count) == 0, "PostgreSQL lifecycle policy object appeared"+++async def test_postgres_empty_database_upgrades_through_exact_head_0011() -> None:+ async with _postgres_harness() as harness:+ await _alembic(harness, "upgrade", "head")+ import asyncpg++ connection = await asyncpg.connect(+ _migration_url(+ harness.config,+ harness.database_name,+ ordinary_driver=True,+ )+ )+ try:+ revision = await connection.fetchval("SELECT version_num FROM alembic_version")+ tables = {+ str(row["table_name"])+ for row in await connection.fetch(+ "SELECT table_name FROM information_schema.tables "+ "WHERE table_schema=current_schema() AND table_type='BASE TABLE'"+ )+ }+ gateway = await connection.fetch("SELECT mode,revision FROM execution_gateway_state")+ await validate_postgresql_lifecycle_catalog(connection)+ await validate_postgresql_admission_authority_catalog(connection)+ finally:+ await connection.close()+ assert revision == "0011", "PostgreSQL migration head changed"+ assert set(_EXPECTED_LIFECYCLE_TABLES).issubset(tables), "lifecycle tables missing"+ assert set(V11_AUTHORITY_TABLES).issubset(tables), "admission-authority tables missing"+ assert [tuple(row.values()) for row in gateway] == [("disabled", 0)], (+ "gateway was enabled by migration"+ )++[email protected]("_case", ["empty", "v2-populated"], ids=("empty", "v2-populated"))+async def test_postgres_revision_0011_upgrades_supported_0010_catalog(_case: str) -> None:+ async with _postgres_harness() as harness:+ await _alembic(harness, "upgrade", "0010")+ import asyncpg++ connection = await asyncpg.connect(+ _migration_url(harness.config, harness.database_name, ordinary_driver=True)+ )+ actor_id = "00000000-0000-4000-8000-000000001201"+ campaign_id = "00000000-0000-4000-8000-000000001202"+ try:+ if _case == "v2-populated":+ async with connection.transaction():+ await connection.execute(+ "INSERT INTO users(id,username,hashed_password,role,created_by) "+ "VALUES($1,$2,$3,$4,$5)",+ actor_id,+ "migration-owner",+ "fixed",+ "admin",+ "fixed",+ )+ await connection.execute(+ "INSERT INTO campaigns(id,name,operator,scope_json,targets_json) "+ "VALUES($1,$2,$3,$4,$5)",+ campaign_id,+ "migration-campaign",+ "migration-owner",+ '[{"cidr":"10.12.0.0/24"}]',+ '["Host.Example."]',+ )+ await connection.execute(+ "INSERT INTO execution_actor_authority_revisions("+ "user_id,latest_operation_id,latest_operation_code) "+ "VALUES($1,$2,'ensure')",+ actor_id,+ "00000000-0000-4000-8000-000000001203",+ )+ await connection.execute(+ "INSERT INTO campaign_execution_authority_revisions("+ "campaign_id,latest_operation_id,latest_operation_code) "+ "VALUES($1,$2,'ensure')",+ campaign_id,+ "00000000-0000-4000-8000-000000001204",+ )+ await connection.execute(+ "INSERT INTO credentials(id,campaign_id,username,cred_type,source_module) "+ "VALUES($1,$2,$3,$4,$5)",+ "00000000-0000-4000-8000-000000001205",+ campaign_id,+ "opaque-user",+ "cleartext",+ "migration-fixture",+ )+ finally:+ await connection.close()++ await _alembic(harness, "upgrade", "0011")+ connection = await asyncpg.connect(+ _migration_url(harness.config, harness.database_name, ordinary_driver=True)+ )+ try:+ await validate_postgresql_admission_authority_catalog(connection)+ revision = await connection.fetchval("SELECT version_num FROM alembic_version")+ observed_counts: list[int] = []+ for table in V11_AUTHORITY_TABLES:+ observed_counts.append(+ int(+ await connection.fetchval(+ f"SELECT count(*) FROM {table}" # noqa: S608 - frozen table tuple.+ )+ )+ )+ counts = tuple(observed_counts)+ if _case == "v2-populated":+ grant = await connection.fetchrow(+ "SELECT authority_state,revision FROM campaign_execution_actor_grants "+ "WHERE campaign_id=$1 AND actor_user_id=$2",+ campaign_id,+ actor_id,+ )+ destination = await connection.fetchrow(+ "SELECT authority_state,revision,normalization_version,destination_count "+ "FROM campaign_execution_destination_authorities WHERE campaign_id=$1",+ campaign_id,+ )+ credential = await connection.fetchrow(+ "SELECT execution_authority_state,execution_authority_revision,"+ "execution_authority_binding_digest FROM credentials WHERE campaign_id=$1",+ campaign_id,+ )+ finally:+ await connection.close()+ assert revision == "0011", "supported PostgreSQL upgrade missed revision 0011"+ if _case == "empty":+ assert counts == (0,) * len(V11_AUTHORITY_TABLES), (+ "empty PostgreSQL upgrade fabricated authority"+ )+ else:+ assert counts == (1, 1, 0, 0, 0), "PostgreSQL v2 backfill cardinality changed"+ assert tuple(grant.values()) == ("active", 0), "compatibility grant changed"+ assert tuple(destination.values()) == ("active", 0, 1, 2), (+ "destination backfill changed"+ )+ assert tuple(credential.values())[:2] == ("active", 0), (+ "credential authority backfill changed"+ )+ assert len(str(tuple(credential.values())[2])) == 64, "credential binding changed"+++async def test_postgres_revision_0011_downgrade_refuses_before_mutation() -> None:+ async with _postgres_harness() as harness:+ await _alembic(harness, "upgrade", "head")+ import asyncpg++ connection = await asyncpg.connect(+ _migration_url(harness.config, harness.database_name, ordinary_driver=True)+ )+ try:+ async with connection.transaction():+ await connection.execute(+ "INSERT INTO users(id,username,hashed_password,role,created_by) "+ "VALUES($1,$2,$3,$4,$5)",+ "00000000-0000-4000-8000-000000001211",+ "downgrade-owner",+ "fixed",+ "admin",+ "fixed",+ )+ await connection.execute(+ "INSERT INTO execution_actor_authority_revisions("+ "user_id,latest_operation_id,latest_operation_code,authority_revision) "+ "VALUES($1,$2,'ensure',1)",+ "00000000-0000-4000-8000-000000001211",+ "00000000-0000-4000-8000-000000001212",+ )+ before = tuple(+ tuple(row.values())+ for row in await connection.fetch(+ "SELECT table_name,column_name,ordinal_position,data_type,is_nullable "+ "FROM information_schema.columns WHERE table_schema=current_schema() "+ "ORDER BY table_name,ordinal_position"+ )+ )+ finally:+ await connection.close()+ with pytest.raises(RuntimeError):+ await _alembic(harness, "downgrade", "0010")+ connection = await asyncpg.connect(+ _migration_url(harness.config, harness.database_name, ordinary_driver=True)+ )+ try:+ after = tuple(+ tuple(row.values())+ for row in await connection.fetch(+ "SELECT table_name,column_name,ordinal_position,data_type,is_nullable "+ "FROM information_schema.columns WHERE table_schema=current_schema() "+ "ORDER BY table_name,ordinal_position"+ )+ )+ revision = await connection.fetchval("SELECT version_num FROM alembic_version")+ await validate_postgresql_admission_authority_catalog(connection)+ finally:+ await connection.close()+ assert before == after, "PostgreSQL downgrade refusal mutated catalog"+ assert revision == "0011", "PostgreSQL downgrade refusal changed revision"+++async def test_postgres_revision_0011_failed_upgrade_rolls_back_and_retry_succeeds() -> None:+ async with _postgres_harness() as harness:+ await _alembic(harness, "upgrade", "0010")+ with pytest.raises(RuntimeError):+ await _alembic(+ harness,+ "upgrade",+ "0011",+ fault="0011-after-authority-ddl",+ )+ import asyncpg++ connection = await asyncpg.connect(+ _migration_url(harness.config, harness.database_name, ordinary_driver=True)+ )+ try:+ revision_after_failure = await connection.fetchval(+ "SELECT version_num FROM alembic_version"+ )+ tables_after_failure = {+ str(row["table_name"])+ for row in await connection.fetch(+ "SELECT table_name FROM information_schema.tables "+ "WHERE table_schema=current_schema() AND table_type='BASE TABLE'"+ )+ }+ await validate_postgresql_lifecycle_catalog(connection)+ finally:+ await connection.close()+ assert revision_after_failure == "0010", "failed PostgreSQL upgrade advanced revision"+ assert set(V11_AUTHORITY_TABLES).isdisjoint(tables_after_failure), (+ "failed PostgreSQL upgrade left generation-11 relations"+ )++ await _alembic(harness, "upgrade", "0011", timeout=60.0)+ connection = await asyncpg.connect(+ _migration_url(harness.config, harness.database_name, ordinary_driver=True)+ )+ try:+ revision = await connection.fetchval("SELECT version_num FROM alembic_version")+ await validate_postgresql_admission_authority_catalog(connection)+ finally:+ await connection.close()+ assert revision == "0011", "PostgreSQL retry did not reach revision 0011"+++async def test_postgres_catalog_matches_independent_literal_fingerprint() -> None:+ async with _postgres_harness() as harness:+ await _alembic(harness, "upgrade", "0010")+ import asyncpg++ connection = await asyncpg.connect(+ _migration_url(harness.config, harness.database_name, ordinary_driver=True)+ )+ try:+ observed = await _independent_postgres_catalog_fingerprint(connection)+ index_row = await connection.fetchrow(+ "SELECT base.relname,idx.relname,am.amname,i.indisunique,i.indisprimary,"+ "i.indisvalid,i.indisready,i.indnkeyatts,i.indnatts,a.attname,"+ "opc_ns.nspname||'.'||opc.opcname,coll_ns.nspname||'.'||coll.collname,"+ "i.indoption::text,pg_get_expr(i.indexprs,i.indrelid,false),"+ "pg_get_expr(i.indpred,i.indrelid,false) FROM pg_index i "+ "JOIN pg_class idx ON idx.oid=i.indexrelid "+ "JOIN pg_class base ON base.oid=i.indrelid "+ "JOIN pg_namespace ns ON ns.oid=idx.relnamespace "+ "JOIN pg_am am ON am.oid=idx.relam "+ "JOIN pg_attribute a ON a.attrelid=i.indrelid AND a.attnum=i.indkey[0] "+ "JOIN pg_opclass opc ON opc.oid=i.indclass[0] "+ "JOIN pg_namespace opc_ns ON opc_ns.oid=opc.opcnamespace "+ "JOIN pg_collation coll ON coll.oid=i.indcollation[0] "+ "JOIN pg_namespace coll_ns ON coll_ns.oid=coll.collnamespace "+ "WHERE ns.nspname=current_schema() AND idx.relname='ix_eol_attempt'"+ )+ finally:+ await connection.close()+ assert observed == _POSTGRES_LITERAL_ORACLE_FINGERPRINT_V1, (+ "PostgreSQL whole-catalog fingerprint changed"+ )+ assert tuple(index_row) == (+ "execution_output_links",+ "ix_eol_attempt",+ "btree",+ False,+ False,+ True,+ True,+ 1,+ 1,+ "attempt_id",+ "pg_catalog.text_ops",+ "pg_catalog.default",+ "0",+ None,+ None,+ ), "operational attempt index changed"+++def test_postgres_cyclic_foreign_key_is_added_after_attempt_candidate_key() -> None:+ logical_index = next(+ index+ for index, statement in enumerate(POSTGRES_LIFECYCLE_DDL)+ if statement.startswith("CREATE TABLE logical_executions")+ )+ attempt_index = next(+ index+ for index, statement in enumerate(POSTGRES_LIFECYCLE_DDL)+ if statement.startswith("CREATE TABLE execution_attempts")+ )+ closing_index = next(+ index+ for index, statement in enumerate(POSTGRES_LIFECYCLE_DDL)+ if statement.startswith("ALTER TABLE logical_executions ADD CONSTRAINT")+ )+ assert (logical_index, attempt_index, closing_index) == (0, 1, 2), (+ "PostgreSQL cyclic foreign-key order changed"+ )+ assert "DEFERRABLE INITIALLY DEFERRED" in POSTGRES_LIFECYCLE_DDL[closing_index], (+ "closing foreign key lost deferral"+ )+++def test_postgres_receipt_immutability_ddl_follows_receipt_relation() -> None:+ receipt_index = next(+ index+ for index, statement in enumerate(POSTGRES_LIFECYCLE_DDL)+ if statement.startswith("CREATE TABLE execution_operation_receipts")+ )+ function_index = next(+ index+ for index, statement in enumerate(POSTGRES_LIFECYCLE_DDL)+ if statement.startswith("CREATE FUNCTION execution_operation_receipt_immutable()")+ )+ trigger_index = next(+ index+ for index, statement in enumerate(POSTGRES_LIFECYCLE_DDL)+ if statement.startswith("CREATE TRIGGER trg_eor_immutable")+ )+ assert receipt_index < function_index < trigger_index, (+ "receipt immutability DDL dependency order changed"+ )+ assert "ERRCODE='55000'" in POSTGRES_LIFECYCLE_DDL[function_index], (+ "receipt immutability SQLSTATE changed"+ )+ assert "BEFORE UPDATE OR DELETE" in POSTGRES_LIFECYCLE_DDL[trigger_index], (+ "receipt immutability trigger events changed"+ )diff --git a/tests/integration/test_postgres_migration_portability.py b/tests/integration/test_postgres_migration_portability.pyindex e6307bd..1a88bf1 100644--- a/tests/integration/test_postgres_migration_portability.py+++ b/tests/integration/test_postgres_migration_portability.py@@ -1,4 +1,5 @@"""Real PostgreSQL execution tests for the historical Alembic chain."""+from __future__ import annotationsimport asyncio@@ -126,55 +127,142 @@ _POSTGRES_INDEX_TABLES = {}_EXPECTED_COLUMN_ORDER = {"campaigns": (- "id", "name", "client", "operator", "noise_profile", "status",- "scope_json", "targets_json", "notes", "created_at", "updated_at",+ "id",+ "name",+ "client",+ "operator",+ "noise_profile",+ "status",+ "scope_json",+ "targets_json",+ "notes",+ "created_at",+ "updated_at",),"module_runs": (- "id", "campaign_id", "module_id", "outcome", "success",- "duration_ms", "completed_at",+ "id",+ "campaign_id",+ "module_id",+ "outcome",+ "success",+ "duration_ms",+ "completed_at",),"findings": (- "id", "campaign_id", "module_id", "title", "description",- "severity", "confidence", "mitre_technique", "mitre_tactic",- "cvss_score", "cvss_vector", "evidence_json", "remediation",- "host", "validated", "false_positive", "discovered_at", "trace_id",+ "id",+ "campaign_id",+ "module_id",+ "title",+ "description",+ "severity",+ "confidence",+ "mitre_technique",+ "mitre_tactic",+ "cvss_score",+ "cvss_vector",+ "evidence_json",+ "remediation",+ "host",+ "validated",+ "false_positive",+ "discovered_at",+ "trace_id",),"hosts": (- "id", "campaign_id", "ip_address", "hostname", "fqdn", "os",- "os_version", "domain", "is_dc", "open_ports_json", "tags_json",- "first_seen", "last_seen",+ "id",+ "campaign_id",+ "ip_address",+ "hostname",+ "fqdn",+ "os",+ "os_version",+ "domain",+ "is_dc",+ "open_ports_json",+ "tags_json",+ "first_seen",+ "last_seen",),"credentials": (- "id", "campaign_id", "host_id", "username", "secret_enc",- "cred_type", "domain", "source_module", "notes", "cracked",- "cracked_value_enc", "captured_at",+ "id",+ "campaign_id",+ "host_id",+ "username",+ "secret_enc",+ "cred_type",+ "domain",+ "source_module",+ "notes",+ "cracked",+ "cracked_value_enc",+ "captured_at",),"loot": (- "id", "campaign_id", "host_id", "loot_type", "name",- "description", "content_enc", "size_bytes", "path_on_target",- "source_module", "tags_json", "captured_at",+ "id",+ "campaign_id",+ "host_id",+ "loot_type",+ "name",+ "description",+ "content_enc",+ "size_bytes",+ "path_on_target",+ "source_module",+ "tags_json",+ "captured_at",),"audit_log": (- "id", "campaign_id", "actor", "action", "detail", "module_id",+ "id",+ "campaign_id",+ "actor",+ "action",+ "detail",+ "module_id","timestamp",),"users": (- "id", "username", "hashed_password", "role", "is_active",- "created_by", "created_at", "last_login",+ "id",+ "username",+ "hashed_password",+ "role",+ "is_active",+ "created_by",+ "created_at",+ "last_login",),"api_keys": (- "id", "user_id", "name", "key_hash", "key_prefix", "scopes",- "is_active", "last_used", "expires_at", "created_at",+ "id",+ "user_id",+ "name",+ "key_hash",+ "key_prefix",+ "scopes",+ "is_active",+ "last_used",+ "expires_at",+ "created_at",),"refresh_tokens": (- "id", "user_id", "is_revoked", "expires_at", "created_at",+ "id",+ "user_id",+ "is_revoked",+ "expires_at",+ "created_at","used_at",),"revoked_access_tokens": (- "jti", "user_id", "revoked_at", "expires_at",+ "jti",+ "user_id",+ "revoked_at",+ "expires_at",),"rate_limit_events": (- "id", "ip_address", "bucket", "username", "blocked", "timestamp",+ "id",+ "ip_address",+ "bucket",+ "username",+ "blocked",+ "timestamp",),}_POSTGRES_INTEGER_COLUMNS = {@@ -392,13 +480,9 @@ class _OwnedWorker:@dataclass(frozen=True)class _PostgresCatalogContract:tables: tuple[str, ...]- columns: tuple[- tuple[str, str, str, bool, str | None], ...- ]+ columns: tuple[tuple[str, str, str, bool, str | None], ...]primary_keys: tuple[tuple[str, tuple[str, ...]], ...]- unique_constraints: tuple[- tuple[str, str, tuple[str, ...]], ...- ]+ unique_constraints: tuple[tuple[str, str, tuple[str, ...]], ...]checks: tuple[tuple[str, str, str], ...]foreign_keys: tuple[tuple[@@ -412,9 +496,7 @@ class _PostgresCatalogContract:],...,]- indexes: tuple[- tuple[str, str, tuple[str, ...], bool, str | None], ...- ]+ indexes: tuple[tuple[str, str, tuple[str, ...], bool, str | None], ...]sequences: tuple[str, ...]@@ -513,15 +595,9 @@ def _requires_candidate_origin(name: str) -> bool:def _path_is_within_candidate(path: object, candidate_root: Path) -> bool:try:- resolved_path = os.path.normcase(- str(Path(path).resolve(strict=False))- )- resolved_root = os.path.normcase(- str(candidate_root.resolve(strict=True))- )- return os.path.commonpath((resolved_path, resolved_root)) == (- resolved_root- )+ resolved_path = os.path.normcase(str(Path(path).resolve(strict=False)))+ resolved_root = os.path.normcase(str(candidate_root.resolve(strict=True)))+ return os.path.commonpath((resolved_path, resolved_root)) == (resolved_root)except (OSError, RuntimeError, TypeError, ValueError):return False@@ -539,8 +615,7 @@ def _module_origin_is_candidate_local(if spec_origin not in {None, "built-in", "frozen"}:concrete_origins.append(spec_origin)concrete_is_local = not concrete_origins or all(- _path_is_within_candidate(origin, candidate_root)- for origin in concrete_origins+ _path_is_within_candidate(origin, candidate_root) for origin in concrete_origins)search_locations = getattr(spec, "submodule_search_locations", None)if search_locations is None:@@ -552,14 +627,9 @@ def _module_origin_is_candidate_local(locations = tuple(search_locations)has_locations = bool(locations)locations_are_local = has_locations and all(- _path_is_within_candidate(location, candidate_root)- for location in locations+ _path_is_within_candidate(location, candidate_root) for location in locations)- return (- concrete_is_local- and locations_are_local- and (bool(concrete_origins) or has_locations)- )+ return concrete_is_local and locations_are_local and (bool(concrete_origins) or has_locations)def _spec_origin_is_candidate_local(@@ -571,8 +641,7 @@ def _spec_origin_is_candidate_local(if spec_origin not in {None, "built-in", "frozen"}:concrete_origins.append(spec_origin)concrete_is_local = not concrete_origins or all(- _path_is_within_candidate(origin, candidate_root)- for origin in concrete_origins+ _path_is_within_candidate(origin, candidate_root) for origin in concrete_origins)search_locations = getattr(spec, "submodule_search_locations", None)if search_locations is None:@@ -582,14 +651,9 @@ def _spec_origin_is_candidate_local(locations = tuple(search_locations)has_locations = bool(locations)locations_are_local = has_locations and all(- _path_is_within_candidate(location, candidate_root)- for location in locations+ _path_is_within_candidate(location, candidate_root) for location in locations)- return (- concrete_is_local- and locations_are_local- and (bool(concrete_origins) or has_locations)- )+ return concrete_is_local and locations_are_local and (bool(concrete_origins) or has_locations)def _relative_path_is_first_party(relative_path: Path) -> bool:@@ -598,10 +662,10 @@ def _relative_path_is_first_party(relative_path: Path) -> bool:return Falseif folded_parts[0] in {"ares", "migrations"}:return True- return (- len(folded_parts) >= 2- and folded_parts[:2] in {("tests", "unit"), ("tests", "integration")}- )+ return len(folded_parts) >= 2 and folded_parts[:2] in {+ ("tests", "unit"),+ ("tests", "integration"),+ }def _frame_file_is_first_party(@@ -630,8 +694,7 @@ def _frame_file_is_first_party(return (len(folded_parts) >= 3and folded_parts[-3:-1] == ("migrations", "versions")- and re.fullmatch(r"[0-9]{4}_[a-z0-9_]+\.py", folded_parts[-1])- is not None+ and re.fullmatch(r"[0-9]{4}_[a-z0-9_]+\.py", folded_parts[-1]) is not None)@@ -733,9 +796,7 @@ class _CandidateOriginLedger:raw_file = globals_map.get("__file__")try:normalized_file = (- os.fspath(raw_file)- if isinstance(raw_file, (str, os.PathLike))- else None+ os.fspath(raw_file) if isinstance(raw_file, (str, os.PathLike)) else None)except TypeError:normalized_file = None@@ -819,18 +880,13 @@ def _loaded_first_party_origins_are_candidate_local(def _assert_candidate_origin_boundary(ledger: _CandidateOriginLedger | None = None,) -> None:- ledgers = (- (ledger,)- if ledger is not None- else tuple(_ACTIVE_ORIGIN_LEDGERS)- )+ ledgers = (ledger,) if ledger is not None else tuple(_ACTIVE_ORIGIN_LEDGERS)for active_ledger in ledgers:active_ledger.observe_modules(sys.modules)if not (_path_is_within_candidate(__file__, _REPO_ROOT)and all(- not active_ledger.violated- and active_ledger.installed_exactly()+ not active_ledger.violated and active_ledger.installed_exactly()for active_ledger in ledgers)and _loaded_first_party_origins_are_candidate_local(@@ -838,9 +894,7 @@ def _assert_candidate_origin_boundary(_REPO_ROOT,)):- raise RuntimeError(- "first-party migration import escaped the source candidate"- )+ raise RuntimeError("first-party migration import escaped the source candidate")@contextmanager@@ -995,10 +1049,7 @@ def _prepare_child_migration(raise RuntimeError("worker-payload-error")postgres_config = _child_postgres_config()database_name = payload.get("database_name")- if (- not isinstance(database_name, str)- or _SAFE_DATABASE_NAME.fullmatch(database_name) is None- ):+ if not isinstance(database_name, str) or _SAFE_DATABASE_NAME.fullmatch(database_name) is None:raise RuntimeError("worker-payload-error")if database_name == postgres_config.maintenance_database:raise RuntimeError("worker-payload-error")@@ -1021,12 +1072,11 @@ def _prepare_child_migration("0005-before-alter","0005-after-alter","0006-after-rename",+ "0011-after-authority-ddl",}):raise RuntimeError("worker-payload-error")- action = (- command.upgrade if operation == "upgrade" else command.downgrade- )+ action = command.upgrade if operation == "upgrade" else command.downgradereturn config, action, revision, fault@@ -1146,46 +1196,68 @@ def _alembic_worker_entry(channel: Any) -> None:):raise RuntimeError("worker-target-error")if mode == "migrate" and fault is not None:- from alembic.operations import Operations-- original_alter = Operations.alter_column-- def _failing_alter(- operations: Operations,- table_name: str,- column_name: str,- *args: object,- **kwargs: object,- ) -> object:- is_trace = (- table_name == "findings"- and column_name == "trace_id"- )- is_credential = (- table_name == "credentials"- and column_name- in {"cracked_value", "cracked_value_enc"}+ if fault == "0011-after-authority-ddl":+ from sqlalchemy.engine import Connection++ from ares.db.execution_lifecycle import (+ POSTGRES_ADMISSION_AUTHORITY_V11_DDL,)- if fault == "0005-before-alter" and is_trace:- raise RuntimeError("worker-test-error")- result = original_alter(- operations,- table_name,- column_name,- *args,- **kwargs,++ original_execute = Connection.execute+ final_authority_ddl = " ".join(+ POSTGRES_ADMISSION_AUTHORITY_V11_DDL[-1].split())- if (- fault == "0005-after-alter"- and is_trace- ) or (- fault == "0006-after-rename"- and is_credential- ):- raise RuntimeError("worker-test-error")- return result-- Operations.alter_column = _failing_alter++ def _fail_after_authority_ddl(+ connection: Connection,+ statement: object,+ *args: object,+ **kwargs: object,+ ) -> object:+ result = original_execute(+ connection,+ statement,+ *args,+ **kwargs,+ )+ if " ".join(str(statement).split()) == final_authority_ddl:+ raise RuntimeError("worker-test-error")+ return result++ Connection.execute = _fail_after_authority_ddl+ else:+ from alembic.operations import Operations++ original_alter = Operations.alter_column++ def _failing_alter(+ operations: Operations,+ table_name: str,+ column_name: str,+ *args: object,+ **kwargs: object,+ ) -> object:+ is_trace = table_name == "findings" and column_name == "trace_id"+ is_credential = table_name == "credentials" and column_name in {+ "cracked_value",+ "cracked_value_enc",+ }+ if fault == "0005-before-alter" and is_trace:+ raise RuntimeError("worker-test-error")+ result = original_alter(+ operations,+ table_name,+ column_name,+ *args,+ **kwargs,+ )+ if (fault == "0005-after-alter" and is_trace) or (+ fault == "0006-after-rename" and is_credential+ ):+ raise RuntimeError("worker-test-error")+ return result++ Operations.alter_column = _failing_alterelif mode in {"success","success-dirty-origin",@@ -1277,10 +1349,7 @@ def _add_fixed_cleanup_note(action: str,cleanup_error: Exception,) -> None:- primary.add_note(- f"Alembic worker cleanup failed [{action}: "- f"{type(cleanup_error).__name__}]"- )+ primary.add_note(f"Alembic worker cleanup failed [{action}: {type(cleanup_error).__name__}]")def _close_unowned_endpoint(@@ -1345,11 +1414,7 @@ async def _settle_worker(if worker.closed:raise RuntimeError("Alembic worker ownership was already closed")if worker.death_proven:- exit_code = (- -1- if worker.settled_exit_code is None- else worker.settled_exit_code- )+ exit_code = -1 if worker.settled_exit_code is None else worker.settled_exit_code_close_settled_worker_resources(worker)return exit_codeprocess = worker.process@@ -1406,9 +1471,7 @@ async def _receive_worker_frame(except (BrokenPipeError, EOFError, OSError):worker.eof = Truereturn None- if not isinstance(frame, tuple) or not all(- isinstance(item, str) for item in frame- ):+ if not isinstance(frame, tuple) or not all(isinstance(item, str) for item in frame):raise RuntimeError("Alembic worker failed [ProtocolError]")return frameif not worker.process.is_alive():@@ -1449,9 +1512,7 @@ async def _run_worker(raise RuntimeError("worker-pipe-construction-error")parent_channel, child_channel = pipe_resourcesexcept Exception as exc:- primary = RuntimeError(- f"Alembic worker startup failed [{type(exc).__name__}]"- )+ primary = RuntimeError(f"Alembic worker startup failed [{type(exc).__name__}]")for index, endpoint in enumerate(pipe_resources):_close_unowned_endpoint(endpoint,@@ -1466,9 +1527,7 @@ async def _run_worker(name="ares-alembic-worker",)except Exception as exc:- primary = RuntimeError(- f"Alembic worker startup failed [{type(exc).__name__}]"- )+ primary = RuntimeError(f"Alembic worker startup failed [{type(exc).__name__}]")_close_unowned_endpoint(parent_channel,"close-parent-endpoint",@@ -1495,16 +1554,10 @@ async def _run_worker(worker.child_closed = Trueparent_channel.send(("PAYLOAD", payload))except Exception as exc:- worker.may_have_started = (- worker.may_have_started or _process_may_have_started(process)- )- primary = RuntimeError(- f"Alembic worker startup failed [{type(exc).__name__}]"- )+ worker.may_have_started = worker.may_have_started or _process_may_have_started(process)+ primary = RuntimeError(f"Alembic worker startup failed [{type(exc).__name__}]")try:- await asyncio.shield(- _settle_worker(worker, terminate=True)- )+ await asyncio.shield(_settle_worker(worker, terminate=True))except Exception as cleanup_error:_add_fixed_cleanup_note(primary,@@ -1538,9 +1591,7 @@ async def _run_worker(terminate=False,)if after_setup_error is None and exit_code == 70:- raise RuntimeError(- f"Alembic worker failed [{ready[1]}]"- ) from None+ raise RuntimeError(f"Alembic worker failed [{ready[1]}]") from Noneraise RuntimeError("Alembic worker failed [ProtocolError]")if started is not None:started.set()@@ -1571,9 +1622,7 @@ async def _run_worker(if terminal == ("OK",) and exit_code == 0:returnif terminal[0] == "ERROR" and exit_code == 70:- raise RuntimeError(- f"Alembic worker failed [{terminal[1]}]"- ) from None+ raise RuntimeError(f"Alembic worker failed [{terminal[1]}]") from Noneraise RuntimeError("Alembic worker failed [ProtocolError]")except TimeoutError:protocol_failure = True@@ -1587,13 +1636,9 @@ async def _run_worker(finally:if worker in _OWNED_WORKERS:try:- await asyncio.shield(- _settle_worker(worker, terminate=protocol_failure)- )+ await asyncio.shield(_settle_worker(worker, terminate=protocol_failure))except RuntimeError:- raise RuntimeError(- "Alembic worker settlement failed"- ) from None+ raise RuntimeError("Alembic worker settlement failed") from Noneasync def _alembic(@@ -1602,6 +1647,7 @@ async def _alembic(revision: str,*,fault: str | None = None,+ timeout: float = _WORKER_TIMEOUT_SECONDS,) -> None:if operation not in {"upgrade", "downgrade"}:raise AssertionError("unknown migration operation")@@ -1615,14 +1661,12 @@ async def _alembic(payload["fault"] = faultawait _run_worker(payload,- timeout=_WORKER_TIMEOUT_SECONDS,+ timeout=timeout,)def _sanitized_setup_failure(action: str, exc: Exception) -> RuntimeError:- return RuntimeError(- f"PostgreSQL migration setup failed [{action}: {type(exc).__name__}]"- )+ return RuntimeError(f"PostgreSQL migration setup failed [{action}: {type(exc).__name__}]")async def _attempt_cleanup(@@ -1646,15 +1690,12 @@ async def _settle_owned_workers_for_cleanup(try:await _settle_worker(worker, terminate=True)except Exception as exc:- failures.append(- f"settle-alembic-worker: {type(exc).__name__}"- )+ failures.append(f"settle-alembic-worker: {type(exc).__name__}")return not _OWNED_WORKERS@asynccontextmanager-async def _postgres_harness(-) -> AsyncIterator[_MigrationHarness]:+async def _postgres_harness() -> AsyncIterator[_MigrationHarness]:config = _postgres_config()try:import asyncpg@@ -1706,9 +1747,7 @@ async def _postgres_harness()finally:primary_failure = sys.exception()- workers_settled = await _settle_owned_workers_for_cleanup(- cleanup_failures- )+ workers_settled = await _settle_owned_workers_for_cleanup(cleanup_failures)if creation_attempted and admin is not None and workers_settled:async def _drop_database() -> None:@@ -1724,10 +1763,7 @@ async def _postgres_harness(timeout=_POSTGRES_OPERATION_TIMEOUT_SECONDS,)await asyncio.wait_for(- admin.execute(- f'DROP DATABASE IF EXISTS "{database_name}" '- "WITH (FORCE)"- ),+ admin.execute(f'DROP DATABASE IF EXISTS "{database_name}" WITH (FORCE)'),timeout=_POSTGRES_OPERATION_TIMEOUT_SECONDS,)@@ -1747,13 +1783,10 @@ async def _postgres_harness(if cleanup_failures:if primary_failure is not None:for failure in cleanup_failures:- primary_failure.add_note(- f"PostgreSQL migration cleanup failure [{failure}]"- )+ primary_failure.add_note(f"PostgreSQL migration cleanup failure [{failure}]")else:raise RuntimeError(- "PostgreSQL migration cleanup failed: "- + "; ".join(cleanup_failures)+ "PostgreSQL migration cleanup failed: " + "; ".join(cleanup_failures)) from None@@ -2113,12 +2146,8 @@ def _isolation_fingerprint_has_no_ares_state(fingerprint: _PostgresIsolationFingerprint,) -> bool:forbidden_relations = _EXPECTED_TABLES | {"alembic_version"}- return (- not fingerprint.versions- and all(- str(relation[1]) not in forbidden_relations- for relation in fingerprint.relations- )+ return not fingerprint.versions and all(+ str(relation[1]) not in forbidden_relations for relation in fingerprint.relations)@@ -2168,8 +2197,7 @@ async def _database_revision(except Exception as cleanup_error:if primary is not None:primary.add_note(- "PostgreSQL migration revision cleanup failed "- f"[{type(cleanup_error).__name__}]"+ f"PostgreSQL migration revision cleanup failed [{type(cleanup_error).__name__}]")else:raise _sanitized_setup_failure(@@ -2179,14 +2207,10 @@ async def _database_revision(async def _version(connection: Any) -> str | None:- exists = await connection.fetchval(- "SELECT to_regclass('alembic_version') IS NOT NULL"- )+ exists = await connection.fetchval("SELECT to_regclass('alembic_version') IS NOT NULL")if not exists:return None- value = await connection.fetchval(- "SELECT version_num FROM alembic_version"- )+ value = await connection.fetchval("SELECT version_num FROM alembic_version")return None if value is None else str(value)@@ -2509,9 +2533,7 @@ def _fixed_postgres_contract(revision: str) -> _PostgresCatalogContract:if table in tables}if revision == "0001":- order["findings"] = tuple(- column for column in order["findings"] if column != "trace_id"- )+ order["findings"] = tuple(column for column in order["findings"] if column != "trace_id")if revision < "0006":order["credentials"] = tuple("cracked_value" if column == "cracked_value_enc" else column@@ -2520,11 +2542,7 @@ def _fixed_postgres_contract(revision: str) -> _PostgresCatalogContract:columns: list[tuple[str, str, str, bool, str | None]] = []for table in ordered_tables:for column in order[table]:- canonical_column = (- "cracked_value_enc"- if column == "cracked_value"- else column- )+ canonical_column = "cracked_value_enc" if column == "cracked_value" else columnkey = (table, canonical_column)if key in _POSTGRES_INTEGER_COLUMNS:data_type = "integer"@@ -2549,11 +2567,7 @@ def _fixed_postgres_contract(revision: str) -> _PostgresCatalogContract:primary_keys = tuple((table,- (- "jti"- if table == "revoked_access_tokens"- else "id",- ),+ ("jti" if table == "revoked_access_tokens" else "id",),)for table in ordered_tables)@@ -2596,9 +2610,7 @@ def _fixed_postgres_contract(revision: str) -> _PostgresCatalogContract:if revision == "0001":index_names.discard("idx_findings_cvss")if revision < "0003":- index_names.difference_update(- {"idx_rle_ip", "idx_rle_timestamp", "idx_rle_blocked"}- )+ index_names.difference_update({"idx_rle_ip", "idx_rle_timestamp", "idx_rle_blocked"})if revision < "0004":index_names.discard("idx_rat_expires")indexes = tuple(@@ -2618,15 +2630,9 @@ def _fixed_postgres_contract(revision: str) -> _PostgresCatalogContract:(table,name,- (- f"{column}isnullorisfinite{column}"- if nullable- else f"isfinite{column}"- ),- )- for (table, column), (name, nullable) in (- _POSTGRES_FINITE_TIMESTAMP_CONSTRAINTS.items()+ (f"{column}isnullorisfinite{column}" if nullable else f"isfinite{column}"),)+ for (table, column), (name, nullable) in (_POSTGRES_FINITE_TIMESTAMP_CONSTRAINTS.items())if table in tables]if revision >= "0003":@@ -2656,9 +2662,7 @@ def _fixed_legacy_postgres_contract(revision: str,) -> _PostgresCatalogContract:repaired = _fixed_postgres_contract(revision)- tables = tuple(- table for table in repaired.tables if table != "module_runs"- )+ tables = tuple(table for table in repaired.tables if table != "module_runs")columns = tuple((table,@@ -2666,8 +2670,7 @@ def _fixed_legacy_postgres_contract(data_type,(True- if table == "findings"- and column in {"cvss_score", "cvss_vector", "trace_id"}+ if table == "findings" and column in {"cvss_score", "cvss_vector", "trace_id"}else nullable),default,@@ -2675,9 +2678,7 @@ def _fixed_legacy_postgres_contract(for table, column, data_type, nullable, default in repaired.columnsif table != "module_runs")- indexes = tuple(- index for index in repaired.indexes if index[0] != "module_runs"- ) + (+ indexes = tuple(index for index in repaired.indexes if index[0] != "module_runs") + (("findings","idx_findings_validated",@@ -2690,9 +2691,7 @@ def _fixed_legacy_postgres_contract(repaired,tables=tables,columns=columns,- primary_keys=tuple(- item for item in repaired.primary_keys if item[0] != "module_runs"- ),+ primary_keys=tuple(item for item in repaired.primary_keys if item[0] != "module_runs"),checks=(),foreign_keys=(),indexes=tuple(sorted(indexes)),@@ -2764,9 +2763,7 @@ def _postgres_runtime_legacy_recipe(return _PostgresLegacyRecipe(constraints_to_drop=tuple((table, constraint)- for introduced, table, constraint in (- _POSTGRES_RUNTIME_LEGACY_CONSTRAINT_RECIPE- )+ for introduced, table, constraint in (_POSTGRES_RUNTIME_LEGACY_CONSTRAINT_RECIPE)if introduced <= revision),tables_to_drop=("module_runs",),@@ -2835,9 +2832,7 @@ def test_postgres_legacy_recipe_and_oracle_have_no_mutable_alias() -> None:oracle = _fixed_legacy_postgres_contract("0005")recipe_constraints = list(recipe.constraints_to_drop)oracle_tables = list(oracle.tables)- recipe_constraints.append(- ("synthetic_table", "synthetic_constraint")- )+ recipe_constraints.append(("synthetic_table", "synthetic_constraint"))oracle_tables.append("synthetic_table")independent = (tuple(recipe_constraints) != recipe.constraints_to_drop@@ -3067,11 +3062,7 @@ async def test_owned_worker_completion_and_error_are_settled() -> None:def test_worker_ready_operation_and_settlement_budgets_are_independent() -> None:- worst_case = (- _WORKER_READY_SECONDS- + _WORKER_TIMEOUT_SECONDS- + (2 * _WORKER_SETTLE_SECONDS)- )+ worst_case = _WORKER_READY_SECONDS + _WORKER_TIMEOUT_SECONDS + (2 * _WORKER_SETTLE_SECONDS)budgets_are_independent = (_WORKER_READY_SECONDS == 15.0and _WORKER_TIMEOUT_SECONDS == 25.0@@ -3257,18 +3248,10 @@ def _integration_origin_probe() -> Iterator[Callable[[], None]]:finder = _IntegrationOriginProbeFinder(name, spec)parent_name, _, child_name = name.rpartition(".")- parent = (- importlib.import_module(parent_name)- if parent_name- else None- )+ parent = importlib.import_module(parent_name) if parent_name else Nonemissing = object()previous_module = sys.modules.pop(name, missing)- previous_attribute = (- parent.__dict__.get(child_name, missing)- if parent is not None- else missing- )+ previous_attribute = parent.__dict__.get(child_name, missing) if parent is not None else missingsys.meta_path.insert(0, finder)def _import_then_remove() -> None:@@ -3377,10 +3360,7 @@ def test_integration_origin_ledger_rechecks_reused_code("__name__": "migrations.versions.integration_reused_probe","__package__": "migrations.versions","__file__": str(- _REPO_ROOT- / "migrations"- / "versions"- / "0006_integration_reused_probe.py"+ _REPO_ROOT / "migrations" / "versions" / "0006_integration_reused_probe.py"),},)@@ -3390,10 +3370,7 @@ def test_integration_origin_ledger_rechecks_reused_code("__name__": "migrations.versions.integration_reused_probe","__package__": "migrations.versions","__file__": str(- tmp_path- / "migrations"- / "versions"- / "0007_integration_reused_probe.py"+ tmp_path / "migrations" / "versions" / "0007_integration_reused_probe.py"),},)@@ -3418,9 +3395,7 @@ def test_integration_origin_ledger_ignores_unrelated_migrations_directory({"__name__": "third_party.integration_origin_probe","__package__": "third_party",- "__file__": str(- tmp_path / "migrations" / "integration_origin_probe.py"- ),+ "__file__": str(tmp_path / "migrations" / "integration_origin_probe.py"),},)with _candidate_origin_boundary(isolated=True):@@ -3465,15 +3440,14 @@ class _IpcConfidentialityAudit:returnif isinstance(value, bytes):lowered = value.lower()- if any(- marker.encode("utf-8") in value- for marker in self.forbidden_values- ) or b"postgresql" in lowered:+ if (+ any(marker.encode("utf-8") in value for marker in self.forbidden_values)+ or b"postgresql" in lowered+ ):self.sensitive_seen = Truereturnif isinstance(value, int) and any(- marker.isdecimal() and int(marker) == value- for marker in self.forbidden_values+ marker.isdecimal() and int(marker) == value for marker in self.forbidden_values):self.sensitive_seen = Truereturn@@ -3589,9 +3563,7 @@ async def test_migration_ipc_uses_only_fixed_control_data(for name, value in canonical_values.items():monkeypatch.setenv(name, value)real_context = multiprocessing.get_context("spawn")- audit = _IpcConfidentialityAudit(- tuple(canonical_values.values())- )+ audit = _IpcConfidentialityAudit(tuple(canonical_values.values()))audited_context = _AuditedSpawnContext(real_context, audit)monkeypatch.setattr(multiprocessing,@@ -3617,19 +3589,13 @@ async def test_migration_ipc_uses_only_fixed_control_data(and getattr(audited_context.child_endpoint, "closed", False))expected_received = (- [("READY", 1), ("OK", 1)]- if should_succeed- else [("READY", 1), ("ERROR", 2)]+ [("READY", 1), ("OK", 1)] if should_succeed else [("READY", 1), ("ERROR", 2)])result_safe = ((caught is None if should_succeed else type(caught) is RuntimeError)- and (- should_succeed- or str(caught) == "Alembic worker failed [RuntimeError]"- )+ and (should_succeed or str(caught) == "Alembic worker failed [RuntimeError]")and audit.process_args_safe- and audit.sent_signatures- == [("PAYLOAD", 2), ("GO", 1)]+ and audit.sent_signatures == [("PAYLOAD", 2), ("GO", 1)]and audit.received_signatures == expected_receivedand not audit.sensitive_seenand not audit.unsafe_object_seen@@ -3853,9 +3819,7 @@ class _ProcessFailureContext:class _StartFailureContext:def __init__(self, *, fail_parent_close_once: bool = False) -> None:- self.parent = _ConstructionEndpoint(- fail_close_once=fail_parent_close_once- )+ self.parent = _ConstructionEndpoint(fail_close_once=fail_parent_close_once)self.child = _ConstructionEndpoint()self.process = _NeverStartedProcess()@@ -3890,8 +3854,7 @@ async def test_worker_pipe_construction_failure_leaves_no_owned_resource(caught = errorfailed_closed = (type(caught) is RuntimeError- and str(caught)- == "Alembic worker startup failed [_WorkerConstructionError]"+ and str(caught) == "Alembic worker startup failed [_WorkerConstructionError]"and bool(getattr(caught, "__suppress_context__", False))and not _OWNED_WORKERS)@@ -3916,11 +3879,7 @@ async def test_worker_partial_pipe_result_closes_obtained_endpoint(await _run_worker({"mode": "success"}, timeout=1.0)except RuntimeError as error:caught = error- failed_closed = (- type(caught) is RuntimeError- and context.endpoint.closed- and not _OWNED_WORKERS- )+ failed_closed = type(caught) is RuntimeError and context.endpoint.closed and not _OWNED_WORKERS_require_fixed(failed_closed,"partial Pipe construction leaked its obtained endpoint",@@ -4009,13 +3968,9 @@ async def test_worker_start_failure_preserves_fixed_primary_when_close_fails(retained = tuple(_OWNED_WORKERS)primary_preserved = (type(caught) is RuntimeError- and str(caught)- == "Alembic worker startup failed [_WorkerStartError]"+ and str(caught) == "Alembic worker startup failed [_WorkerStartError]"and tuple(getattr(caught, "__notes__", ()))- == (- "Alembic worker cleanup failed "- "[settle-startup-worker: RuntimeError]",- )+ == ("Alembic worker cleanup failed [settle-startup-worker: RuntimeError]",)and len(retained) == 1)if retained:@@ -4068,9 +4023,7 @@ class _AmbiguousStartContext:self,**kwargs: object,) -> _AmbiguousStartProcess:- self.process = _AmbiguousStartProcess(- self._context.Process(**kwargs)- )+ self.process = _AmbiguousStartProcess(self._context.Process(**kwargs))return self.process@@ -4090,9 +4043,8 @@ async def test_worker_ambiguous_start_failure_settles_real_child(await _run_worker({"mode": "success"}, timeout=1.0)except RuntimeError as error:caught = error- endpoints_closed = (- context.endpoints is not None- and all(endpoint.closed for endpoint in context.endpoints)+ endpoints_closed = context.endpoints is not None and all(+ endpoint.closed for endpoint in context.endpoints)child_settled = (context.process is not None@@ -4100,10 +4052,7 @@ async def test_worker_ambiguous_start_failure_settles_real_child(and not context.process.is_alive())_require_fixed(- type(caught) is RuntimeError- and endpoints_closed- and child_settled- and not _OWNED_WORKERS,+ type(caught) is RuntimeError and endpoints_closed and child_settled and not _OWNED_WORKERS,"ambiguous Process.start failure left a live child or endpoint",)@@ -4186,9 +4135,7 @@ async def test_unproven_worker_death_retains_ownership_and_blocks_cleanup(except RuntimeError:failed = Truecleanup_failures: list[str] = []- cleanup_allowed = await _settle_owned_workers_for_cleanup(- cleanup_failures- )+ cleanup_allowed = await _settle_owned_workers_for_cleanup(cleanup_failures)retained = worker in _OWNED_WORKERSprocess._alive = Falseprocess.exitcode = -9@@ -4217,10 +4164,7 @@ async def test_empty_postgres_base_to_0006_uses_only_alembic() -> None:""")no_alembic_version = (- await connection.fetchval(- "SELECT to_regclass('alembic_version') IS NULL"- )- is True+ await connection.fetchval("SELECT to_regclass('alembic_version') IS NULL") is True)finally:await connection.close()@@ -4245,9 +4189,7 @@ async def test_empty_postgres_base_to_0006_uses_only_alembic() -> None:)}reached_revision = await _version(connection) == "0006"- migration_only_tables = (- tables == _EXPECTED_TABLES | {"alembic_version"}- )+ migration_only_tables = tables == _EXPECTED_TABLES | {"alembic_version"}finally:await connection.close()@@ -4269,13 +4211,10 @@ async def test_explicit_postgres_target_excludes_environment_decoy(async with _postgres_harness() as decoy:distinct_safe_targets = (selected.database_name != decoy.database_name- and selected.database_name- != selected.config.maintenance_database+ and selected.database_name != selected.config.maintenance_databaseand decoy.database_name != decoy.config.maintenance_database- and _SAFE_DATABASE_NAME.fullmatch(selected.database_name)- is not None- and _SAFE_DATABASE_NAME.fullmatch(decoy.database_name)- is not None+ and _SAFE_DATABASE_NAME.fullmatch(selected.database_name) is not None+ and _SAFE_DATABASE_NAME.fullmatch(decoy.database_name) is not None)_require_fixed(distinct_safe_targets,@@ -4293,10 +4232,9 @@ async def test_explicit_postgres_target_excludes_environment_decoy(decoy.config,decoy.database_name,)- empty_baselines = (- _isolation_fingerprint_has_no_ares_state(selected_before)- and _isolation_fingerprint_has_no_ares_state(decoy_before)- )+ empty_baselines = _isolation_fingerprint_has_no_ares_state(+ selected_before+ ) and _isolation_fingerprint_has_no_ares_state(decoy_before)_require_fixed(empty_baselines,"PostgreSQL isolation baselines were not empty",@@ -4517,10 +4455,9 @@ async def test_postgres_revision_round_trip_preserves_rows() -> None:}finally:await connection.close()- parent_is_repaired = (- {"cvss_score", "cvss_vector"}.issubset(parent_columns)- and "trace_id" not in parent_columns- )+ parent_is_repaired = {"cvss_score", "cvss_vector"}.issubset(+ parent_columns+ ) and "trace_id" not in parent_columns_require_fixed(parent_is_repaired,"PostgreSQL revision 0002 downgrade contradicted its parent",@@ -4624,15 +4561,8 @@ async def test_postgres_0006_catalog_types_defaults_fks_and_indexes() -> None:expected_type = "timestamp with time zone"else:expected_type = "text"- expected_nullable = (- "YES"- if key in _POSTGRES_NULLABLE_COLUMNS- else "NO"- )- if (- data_type != expected_type- or nullable != expected_nullable- ):+ expected_nullable = "YES" if key in _POSTGRES_NULLABLE_COLUMNS else "NO"+ if data_type != expected_type or nullable != expected_nullable:columns_are_exact = Falsebreakif not columns_are_exact:@@ -4748,10 +4678,7 @@ async def test_postgres_0006_catalog_types_defaults_fks_and_indexes() -> None:GROUP BY index_class.relname""",)- indexes = {- str(row["index_name"]): tuple(row["columns"])- for row in index_rows- }+ indexes = {str(row["index_name"]): tuple(row["columns"]) for row in index_rows}primary_key_tables = {str(row["table_name"])for row in await connection.fetch(@@ -4871,22 +4798,16 @@ async def test_postgres_all_timestamp_columns_reject_infinity() -> None:(str(row["table_name"]),str(row["constraint_name"]),- ): " ".join(- str(row["definition"]).lower().replace('"', "").split()- )+ ): " ".join(str(row["definition"]).lower().replace('"', "").split())for row in constraint_rows}semantic_constraints_match = Truefor (table,column,- ), (name, nullable) in (- _POSTGRES_FINITE_TIMESTAMP_CONSTRAINTS.items()- ):+ ), (name, nullable) in _POSTGRES_FINITE_TIMESTAMP_CONSTRAINTS.items():definition = observed_constraints.get((table, name), "")- compact = definition.replace(" ", "").replace("(", "").replace(- ")", ""- )+ compact = definition.replace(" ", "").replace("(", "").replace(")", "")has_finite = f"isfinite{column}" in compacthas_nullable = f"{column}isnullor" in compactif not has_finite or has_nullable != nullable:@@ -4933,7 +4854,7 @@ async def test_postgres_all_timestamp_columns_reject_infinity() -> None:connection,(f'UPDATE "{table}" ' # noqa: S608- f'SET "{column}"=\'infinity\'::timestamptz '+ f"SET \"{column}\"='infinity'::timestamptz "f'WHERE "{key_name}"=$1'),key_value,@@ -4950,7 +4871,7 @@ async def test_postgres_all_timestamp_columns_reject_infinity() -> None:connection,(f'UPDATE "{table}" ' # noqa: S608- f'SET "{column}"=\'-infinity\'::timestamptz '+ f"SET \"{column}\"='-infinity'::timestamptz "f'WHERE "{key_name}"=$1'),key_value,@@ -5061,9 +4982,7 @@ async def test_postgres_0006_enforces_complete_relational_contract() -> None:breakforeign_keys_rejected = True- for table, local, _remote, _action in sorted(- _EXPECTED_FOREIGN_KEYS- ):+ for table, local, _remote, _action in sorted(_EXPECTED_FOREIGN_KEYS):key_name, key_value = key_by_table[table]statement = (f'UPDATE "{table}" SET "{local}"=$1 ' # noqa: S608@@ -5150,11 +5069,9 @@ async def test_postgres_0006_enforces_complete_relational_contract() -> None:) AS audit_cleared""")- campaign_actions_enforced = (- campaign_actions is not None- and tuple(campaign_actions.values())- == (0, 0, 0, 0, 0, True)- )+ campaign_actions_enforced = campaign_actions is not None and tuple(+ campaign_actions.values()+ ) == (0, 0, 0, 0, 0, True)finally:await transaction.rollback()@@ -5173,10 +5090,9 @@ async def test_postgres_0006_enforces_complete_relational_contract() -> None:AS refresh_tokens""")- user_cascade_enforced = (- user_actions is not None- and tuple(user_actions.values()) == (0, 0)- )+ user_cascade_enforced = user_actions is not None and tuple(+ user_actions.values()+ ) == (0, 0)finally:await transaction.rollback()@@ -5201,17 +5117,12 @@ async def test_postgres_0006_enforces_complete_relational_contract() -> None:AS rate_limit""")- timestamp_defaults_execute = (- timestamp_values is not None- and all(- isinstance(value, datetime)- and value.utcoffset() is not None- for value in timestamp_values.values()- )+ timestamp_defaults_execute = timestamp_values is not None and all(+ isinstance(value, datetime) and value.utcoffset() is not None+ for value in timestamp_values.values())- integer_defaults_execute = (- await connection.fetchrow(- """+ integer_defaults_execute = await connection.fetchrow(+ """SELECT(SELECT success=0 FROM module_runs LIMIT 1) AS run,(@@ -5228,11 +5139,9 @@ async def test_postgres_0006_enforces_complete_relational_contract() -> None:(SELECT blocked=0 FROM rate_limit_events LIMIT 1)AS rate_limit"""- ))- integer_defaults_match = (- integer_defaults_execute is not None- and all(integer_defaults_execute.values())+ integer_defaults_match = integer_defaults_execute is not None and all(+ integer_defaults_execute.values())audit_second = await connection.fetchval(@@ -5275,9 +5184,8 @@ async def test_postgres_0006_enforces_complete_relational_contract() -> None:"192.0.2.22","synthetic-bucket",)- monotonic_sequences = (- int(audit_third) > int(audit_second)- and int(rate_third) > int(rate_second)+ monotonic_sequences = int(audit_third) > int(audit_second) and int(rate_third) > int(+ rate_second)finally:await connection.close()@@ -5411,11 +5319,7 @@ async def test_postgres_0003_blocked_integer_contract_is_enforced() -> None:and valid_contract["timestamps_present"] is True)_require_fixed(- valid_values- and rejected == 4- and invalid_rows == 0- and check_is_semantic- and reusable,+ valid_values and rejected == 4 and invalid_rows == 0 and check_is_semantic and reusable,"PostgreSQL blocked integer contract was not enforced",)@@ -5423,10 +5327,7 @@ async def test_postgres_0003_blocked_integer_contract_is_enforced() -> None:connection = await _connect(harness)try:removed = (- await connection.fetchval(- "SELECT to_regclass('rate_limit_events') IS NULL"- )- is True+ await connection.fetchval("SELECT to_regclass('rate_limit_events') IS NULL") is True)finally:await connection.close()@@ -5446,9 +5347,7 @@ async def test_postgres_0003_blocked_integer_contract_is_enforced() -> None:2,)except Exception as exc:- reupgrade_rejected = (- type(exc).__name__ == "CheckViolationError"- )+ reupgrade_rejected = type(exc).__name__ == "CheckViolationError"finally:await connection.close()_require_fixed(@@ -5504,10 +5403,7 @@ async def test_postgres_0005_trace_normalization_round_trip() -> None:)finally:await connection.close()- upgraded_correctly = (- upgraded is not None- and tuple(upgraded.values()) == (3, 0, 2, 1, 3)- )+ upgraded_correctly = upgraded is not None and tuple(upgraded.values()) == (3, 0, 2, 1, 3)_require_fixed(upgraded_correctly,"PostgreSQL trace normalization changed protected state",@@ -5548,10 +5444,7 @@ async def test_postgres_0005_trace_normalization_round_trip() -> None:)finally:await connection.close()- reupgraded_correctly = (- reupgraded is not None- and tuple(reupgraded.values()) == (4, 0, 3, 1)- )+ reupgraded_correctly = reupgraded is not None and tuple(reupgraded.values()) == (4, 0, 3, 1)_require_fixed(reupgraded_correctly,"PostgreSQL trace re-upgrade diverged",@@ -5581,13 +5474,8 @@ async def _install_postgres_version_failure(connection: Any) -> None:async def _remove_postgres_version_failure(connection: Any) -> None:- await connection.execute(- "DROP TRIGGER IF EXISTS migration_version_failure "- "ON alembic_version"- )- await connection.execute(- "DROP FUNCTION IF EXISTS migration_version_failure()"- )+ await connection.execute("DROP TRIGGER IF EXISTS migration_version_failure ON alembic_version")+ await connection.execute("DROP FUNCTION IF EXISTS migration_version_failure()")@pytest.mark.asyncio@@ -5703,11 +5591,11 @@ async def test_postgres_0005_failure_boundaries_roll_back_atomically(await _alembic(harness, "downgrade", "0004")connection = await _connect(harness)try:- recovered = (- await _version(connection) == result_revision- and await _postgres_catalog_contract(connection)- == _fixed_postgres_contract(result_revision)- )+ recovered = await _version(+ connection+ ) == result_revision and await _postgres_catalog_contract(+ connection+ ) == _fixed_postgres_contract(result_revision)finally:await connection.close()_require_fixed(@@ -5726,16 +5614,8 @@ async def test_postgres_0006_failure_after_rename_rolls_back_atomically(async with _postgres_harness() as harness:starting_revision = "0005" if direction == "upgrade" else "0006"result_revision = "0006" if direction == "upgrade" else "0005"- source_column = (- "cracked_value"- if direction == "upgrade"- else "cracked_value_enc"- )- result_column = (- "cracked_value_enc"- if direction == "upgrade"- else "cracked_value"- )+ source_column = "cracked_value" if direction == "upgrade" else "cracked_value_enc"+ result_column = "cracked_value_enc" if direction == "upgrade" else "cracked_value"await _alembic(harness, "upgrade", starting_revision)connection = await _connect(harness)try:@@ -5769,22 +5649,14 @@ async def test_postgres_0006_failure_after_rename_rolls_back_atomically(harness,"upgrade","0006",- fault=(- "0006-after-rename"- if boundary == "rename"- else None- ),+ fault=("0006-after-rename" if boundary == "rename" else None),)else:await _alembic(harness,"downgrade","0005",- fault=(- "0006-after-rename"- if boundary == "rename"- else None- ),+ fault=("0006-after-rename" if boundary == "rename" else None),)except RuntimeError:failed = True@@ -5795,15 +5667,11 @@ async def test_postgres_0006_failure_after_rename_rolls_back_atomically(await _remove_postgres_version_failure(connection)after_contract = await _postgres_catalog_contract(connection)source_value_query = (- "SELECT count(*) FROM credentials "- "WHERE cracked_value IS NOT NULL"+ "SELECT count(*) FROM credentials WHERE cracked_value IS NOT NULL"if source_column == "cracked_value"- else "SELECT count(*) FROM credentials "- "WHERE cracked_value_enc IS NOT NULL"- )- unchanged_value = await connection.fetchval(- source_value_query+ else "SELECT count(*) FROM credentials WHERE cracked_value_enc IS NOT NULL")+ unchanged_value = await connection.fetchval(source_value_query)current_revision = await _version(connection)reusable = await connection.fetchval("SELECT 1") == 1finally:@@ -5824,15 +5692,11 @@ async def test_postgres_0006_failure_after_rename_rolls_back_atomically(connection = await _connect(harness)try:result_value_query = (- "SELECT count(*) FROM credentials "- "WHERE cracked_value IS NOT NULL"+ "SELECT count(*) FROM credentials WHERE cracked_value IS NOT NULL"if result_column == "cracked_value"- else "SELECT count(*) FROM credentials "- "WHERE cracked_value_enc IS NOT NULL"- )- recovered_value = await connection.fetchval(- result_value_query+ else "SELECT count(*) FROM credentials WHERE cracked_value_enc IS NOT NULL")+ recovered_value = await connection.fetchval(result_value_query)recovered = (await _version(connection) == result_revisionand await _postgres_catalog_contract(connection)@@ -5853,22 +5717,14 @@ async def _transform_postgres_runtime_legacy_catalog() -> None:recipe = _postgres_runtime_legacy_recipe(revision)for table, name in recipe.constraints_to_drop:- await connection.execute(- f'ALTER TABLE "{table}" DROP CONSTRAINT "{name}"'- )+ await connection.execute(f'ALTER TABLE "{table}" DROP CONSTRAINT "{name}"')for table in recipe.tables_to_drop:await connection.execute(f'DROP TABLE "{table}"')for table, column in recipe.nullable_columns:- await connection.execute(- f'ALTER TABLE "{table}" ALTER COLUMN "{column}" DROP NOT NULL'- )+ await connection.execute(f'ALTER TABLE "{table}" ALTER COLUMN "{column}" DROP NOT NULL')for name, table, columns in recipe.indexes_to_create:- rendered_columns = ", ".join(- f'"{column}"' for column in columns- )- await connection.execute(- f'CREATE INDEX "{name}" ON "{table}" ({rendered_columns})'- )+ rendered_columns = ", ".join(f'"{column}"' for column in columns)+ await connection.execute(f'CREATE INDEX "{name}" ON "{table}" ({rendered_columns})')async def _seed_postgres_legacy_catalog(@@ -6022,8 +5878,7 @@ async def test_complete_postgres_runtime_legacy_catalogs_are_preserved(finally:await connection.close()_require_fixed(- initial_contract- == _fixed_legacy_postgres_contract(legacy_revision),+ initial_contract == _fixed_legacy_postgres_contract(legacy_revision),"constructed PostgreSQL legacy catalog diverged",)@@ -6051,13 +5906,8 @@ async def test_complete_postgres_runtime_legacy_catalogs_are_preserved(""")structural_drift_deferred = (- await connection.fetchval(- "SELECT to_regclass('module_runs') IS NULL"- )- is True- and not (- await _postgres_catalog_contract(connection)- ).foreign_keys+ await connection.fetchval("SELECT to_regclass('module_runs') IS NULL") is True+ and not (await _postgres_catalog_contract(connection)).foreign_keys)current_revision = await _version(connection)reusable = await connection.fetchval("SELECT 1") == 1@@ -6065,8 +5915,7 @@ async def test_complete_postgres_runtime_legacy_catalogs_are_preserved(await connection.close()preserved = (row_counts is not None- and tuple(row_counts.values())- == (1, 1, 1, 1, 1, 1, 1, 1, 1)+ and tuple(row_counts.values()) == (1, 1, 1, 1, 1, 1, 1, 1, 1)and protected_value_present == 1and structural_drift_deferredand current_revision == "0006"@@ -6093,16 +5942,10 @@ async def test_postgres_legacy_missing_column_variants(connection = await _connect(harness)try:if revision == "0002":- await connection.execute(- "ALTER TABLE findings DROP COLUMN cvss_score"- )- await connection.execute(- "ALTER TABLE findings DROP COLUMN cvss_vector"- )+ await connection.execute("ALTER TABLE findings DROP COLUMN cvss_score")+ await connection.execute("ALTER TABLE findings DROP COLUMN cvss_vector")else:- await connection.execute(- "ALTER TABLE findings DROP COLUMN trace_id"- )+ await connection.execute("ALTER TABLE findings DROP COLUMN trace_id")finally:await connection.close()@@ -6143,17 +5986,14 @@ async def test_postgres_0006_catalog_variants(variant: str) -> None:try:if variant == "target-only":await connection.execute(- "ALTER TABLE credentials "- "RENAME COLUMN cracked_value TO cracked_value_enc"+ "ALTER TABLE credentials RENAME COLUMN cracked_value TO cracked_value_enc")elif variant == "both":await connection.execute("ALTER TABLE credentials ADD COLUMN cracked_value_enc TEXT")else:- await connection.execute(- "ALTER TABLE credentials DROP COLUMN cracked_value"- )+ await connection.execute("ALTER TABLE credentials DROP COLUMN cracked_value")finally:await connection.close()@@ -6255,33 +6095,20 @@ async def _prepare_postgres_0006_variant(if variant == "source-only":returnif variant == "target-only":- await connection.execute(- f'ALTER TABLE credentials RENAME COLUMN "{source}" TO "{target}"'- )+ await connection.execute(f'ALTER TABLE credentials RENAME COLUMN "{source}" TO "{target}"')returnif variant == "both":- await connection.execute(- f'ALTER TABLE credentials ADD COLUMN "{target}" TEXT'- )+ await connection.execute(f'ALTER TABLE credentials ADD COLUMN "{target}" TEXT')returnif variant == "neither":- await connection.execute(- f'ALTER TABLE credentials DROP COLUMN "{source}"'- )+ await connection.execute(f'ALTER TABLE credentials DROP COLUMN "{source}"')returnif variant == "target-default-null-equivalent":- await connection.execute(- f'ALTER TABLE credentials DROP COLUMN "{source}"'- )- await connection.execute(- f'ALTER TABLE credentials ADD COLUMN "{target}" '- "TEXT DEFAULT NULL"- )+ await connection.execute(f'ALTER TABLE credentials DROP COLUMN "{source}"')+ await connection.execute(f'ALTER TABLE credentials ADD COLUMN "{target}" TEXT DEFAULT NULL')returnif variant.startswith("wrong-target-"):- await connection.execute(- f'ALTER TABLE credentials DROP COLUMN "{source}"'- )+ await connection.execute(f'ALTER TABLE credentials DROP COLUMN "{source}"')inspected = targetif variant.endswith("-type"):definition = "VARCHAR(64)"@@ -6291,21 +6118,17 @@ async def _prepare_postgres_0006_variant(definition = "TEXT DEFAULT ''::text"else:raise AssertionError("unknown PostgreSQL target variant")- await connection.execute(- f'ALTER TABLE credentials ADD COLUMN "{inspected}" {definition}'- )+ await connection.execute(f'ALTER TABLE credentials ADD COLUMN "{inspected}" {definition}')returnif variant == "source-default-null-equivalent":await connection.execute(- f'ALTER TABLE credentials ALTER COLUMN "{source}" '- "SET DEFAULT NULL"+ f'ALTER TABLE credentials ALTER COLUMN "{source}" SET DEFAULT NULL')returnif variant.startswith("wrong-source-"):if variant.endswith("-type"):await connection.execute(- f'ALTER TABLE credentials ALTER COLUMN "{source}" '- "TYPE VARCHAR(64)"+ f'ALTER TABLE credentials ALTER COLUMN "{source}" TYPE VARCHAR(64)')elif variant.endswith("-nullability"):await connection.execute(@@ -6313,8 +6136,7 @@ async def _prepare_postgres_0006_variant()elif variant.endswith("-default"):await connection.execute(- f'ALTER TABLE credentials ALTER COLUMN "{source}" '- "SET DEFAULT ''::text"+ f"ALTER TABLE credentials ALTER COLUMN \"{source}\" SET DEFAULT ''::text")else:raise AssertionError("unknown PostgreSQL source variant")@@ -6381,7 +6203,9 @@ async def test_postgres_0006_exact_column_state_machine(value_column = (sourceif source in present_columns- else target if target in present_columns else None+ else target+ if target in present_columns+ else None)await connection.execute("INSERT INTO campaigns(id, name) VALUES($1, $2)",@@ -6414,12 +6238,8 @@ async def test_postgres_0006_exact_column_state_machine("password","synthetic-marker",)- before_catalog = await _postgres_credential_catalog_fingerprint(- connection- )- before_rows = await connection.fetchval(- "SELECT count(*) FROM credentials"- )+ before_catalog = await _postgres_credential_catalog_fingerprint(connection)+ before_rows = await connection.fetchval("SELECT count(*) FROM credentials")finally:await connection.close()@@ -6434,12 +6254,8 @@ async def test_postgres_0006_exact_column_state_machine(connection = await _connect(harness)try:- after_catalog = await _postgres_credential_catalog_fingerprint(- connection- )- after_rows = await connection.fetchval(- "SELECT count(*) FROM credentials"- )+ after_catalog = await _postgres_credential_catalog_fingerprint(connection)+ after_rows = await connection.fetchval("SELECT count(*) FROM credentials")target_definition = await connection.fetchrow("""SELECT data_type, udt_name, is_nullable, column_default@@ -6531,3 +6347,27 @@ async def test_postgres_0006_exact_column_state_machine(reusable,"PostgreSQL revision 0006 left connection unusable",)+++def test_revision_0010_postgres_ddl_has_ten_tables_and_dialect_cycle_order() -> None:+ from ares.db.execution_lifecycle import (+ LIFECYCLE_TABLES,+ POSTGRES_LIFECYCLE_DDL,+ )++ created = tuple(+ statement.split("(", maxsplit=1)[0].removeprefix("CREATE TABLE ").strip()+ for statement in POSTGRES_LIFECYCLE_DDL+ if statement.startswith("CREATE TABLE ")+ )+ closing_index = next(+ index+ for index, statement in enumerate(POSTGRES_LIFECYCLE_DDL)+ if statement.startswith("ALTER TABLE logical_executions ADD CONSTRAINT")+ )+ _require_fixed(created == LIFECYCLE_TABLES, "lifecycle DDL order changed")+ _require_fixed(closing_index == 2, "cyclic foreign-key order changed")+ _require_fixed(+ "DEFERRABLE INITIALLY DEFERRED" in POSTGRES_LIFECYCLE_DDL[closing_index],+ "cyclic foreign-key deferral changed",+ )diff --git a/tests/integration/test_postgres_runtime_smoke.py b/tests/integration/test_postgres_runtime_smoke.pyindex 9adc704..8a50018 100644--- a/tests/integration/test_postgres_runtime_smoke.py+++ b/tests/integration/test_postgres_runtime_smoke.py@@ -1520,14 +1520,14 @@ async def test_postgres_runtime_schema_and_transaction_smoke() -> None:"""SELECT EXISTS(SELECT 1 FROM alembic_version- WHERE version_num='0009'+ WHERE version_num='0011')"""))_require_fixed(managed_revision_is_current,- "Runtime smoke must use exact managed revision 0009",+ "Runtime smoke must use exact managed revision 0011",)relation_metadata = await connection.fetchrow("""diff --git a/tests/integration/test_postgres_schema_reconciliation.py b/tests/integration/test_postgres_schema_reconciliation.pyindex 2e31c39..1b02509 100644--- a/tests/integration/test_postgres_schema_reconciliation.py+++ b/tests/integration/test_postgres_schema_reconciliation.py@@ -279,6 +279,10 @@ _EXPECTED_FOREIGN_KEYS = ()_EXPECTED_UNIQUES = (+ ("findings", "uq_findings_campaign_id_id", ("campaign_id", "id")),+ ("credentials", "uq_credentials_campaign_id_id", ("campaign_id", "id")),+ ("hosts", "uq_hosts_campaign_id_id", ("campaign_id", "id")),+ ("loot", "uq_loot_campaign_id_id", ("campaign_id", "id")),("hosts", "uq_hosts_campaign_ip", ("campaign_id", "ip_address")),("refresh_token_families",@@ -858,7 +862,7 @@ class _PureManagedConnection:self,*,revision_present: bool = True,- revision_values: tuple[object, ...] = ("0009",),+ revision_values: tuple[object, ...] = ("0011",),) -> None:self.revision_present = revision_presentself.revision_values = revision_values@@ -1137,6 +1141,17 @@ async def _run_init("_validate_websocket_ticket_schema",_validate_ticket,)+ async def _validate_lifecycle(_connection: object) -> None:+ return None++ monkeypatch.setattr(+ "ares.db.postgres.validate_postgresql_lifecycle_catalog",+ _validate_lifecycle,+ )+ monkeypatch.setattr(+ "ares.db.postgres.validate_postgresql_admission_authority_catalog",+ _validate_lifecycle,+ )database = PostgresDatabase("synthetic")database._pool = _PurePool(connection)with patch("ares.db.postgres.logger.info", return_value=None):@@ -1144,7 +1159,10 @@ async def _run_init(return validated[email protected]("revision", ["0001", "0004", "0007", "0008"])+ "revision",+ ["0001", "0004", "0007", "0008", "0009", "0010"],+)def test_revision_classifier_requires_migration_for_known_older_heads(revision: str,) -> None:@@ -1165,10 +1183,10 @@ def test_revision_classifier_requires_migration_for_known_older_heads((),(None,),("",),- ("0009", "0009"),- ("0009", "0008"),+ ("0011", "0011"),+ ("0011", "0010"),("9999",),- (" 0009",),+ (" 0011",),],)def test_revision_classifier_rejects_malformed_or_unknown_state(@@ -1186,7 +1204,7 @@ def test_revision_classifier_rejects_malformed_or_unknown_state(def test_revision_classifier_accepts_only_exact_managed_head() -> None:- accepted = _classify_postgres_revision(("0009",)) == "0009"+ accepted = _classify_postgres_revision(("0011",)) == "0011"_require_fixed(accepted, "managed PostgreSQL revision was rejected")@@ -1602,7 +1620,7 @@ async def test_managed_inventory_rejects_catalog_drift(@pytest.mark.parametrize("revision_values",- [("0003",), (), ("unknown",), ("0009", "0008")],+ [("0003",), (), ("unknown",), ("0011", "0010")],)@pytest.mark.asyncioasync def test_versioned_failure_never_enters_runtime_fallback(@@ -1782,7 +1800,7 @@ async def test_real_postgres_managed_startup_preserves_unrelated_objects("Managed-startup fixture must reach revision 0007 before 0008",)await harness._alembic(target, "upgrade", "0008")- await harness._alembic(target, "upgrade", "0009")+ await harness._alembic(target, "upgrade", "0011")connection = await harness._connect(target)try:await connection.execute(@@ -1804,7 +1822,7 @@ async def test_real_postgres_managed_startup_preserves_unrelated_objects("""SELECT(- SELECT version_num='0009'+ SELECT version_num='0011'FROM alembic_version) AS managed,(@@ -1856,7 +1874,7 @@ async def test_real_postgres_older_revision_requires_migration_and_recovers(and pools[0].close_count == 1)- await harness._alembic(target, "upgrade", "0009")+ await harness._alembic(target, "upgrade", "0011")try:recovered_state = (await _fixed_connect_result(database) == "connected"@@ -1893,24 +1911,24 @@ async def test_real_postgres_invalid_revision_state_closes_and_recovers(operations = {"empty": ("DELETE FROM alembic_version",- "INSERT INTO alembic_version(version_num) VALUES('0009')",+ "INSERT INTO alembic_version(version_num) VALUES('0011')",),"multiple": ("INSERT INTO alembic_version(version_num) VALUES('0007')","DELETE FROM alembic_version WHERE version_num='0007'",),"malformed": (- "UPDATE alembic_version SET version_num=' 0009'",- "UPDATE alembic_version SET version_num='0009'",+ "UPDATE alembic_version SET version_num=' 0011'",+ "UPDATE alembic_version SET version_num='0011'",),"unknown": ("UPDATE alembic_version SET version_num='9999'",- "UPDATE alembic_version SET version_num='0009'",+ "UPDATE alembic_version SET version_num='0011'",),}mutation, repair = operations[revision_state]async with harness._postgres_harness() as target:- await harness._alembic(target, "upgrade", "0009")+ await harness._alembic(target, "upgrade", "0011")connection = await harness._connect(target)try:await connection.execute(mutation)@@ -2138,7 +2156,7 @@ async def test_real_postgres_managed_catalog_drift_never_falls_back(}statement = statements[drift]async with harness._postgres_harness() as target:- await harness._alembic(target, "upgrade", "0009")+ await harness._alembic(target, "upgrade", "0011")connection = await harness._connect(target)try:await connection.execute(statement)@@ -2912,7 +2930,7 @@ async def test_real_postgres_runtime_origin_converges_without_data_loss()finally:await connection.close()- await harness._alembic(target, "upgrade", "0009")+ await harness._alembic(target, "upgrade", "0011")pools = _audit_runtime_pools(monkeypatch)database = _runtime_database(target)try:@@ -3028,7 +3046,7 @@ async def test_real_postgres_supported_legacy_objects_converge()finally:await connection.close()- await harness._alembic(target, "upgrade", "0009")+ await harness._alembic(target, "upgrade", "0011")pools = _audit_runtime_pools(monkeypatch)database = _runtime_database(target)try:diff --git a/tests/integration/test_postgres_unversioned_adoption.py b/tests/integration/test_postgres_unversioned_adoption.pyindex 3e40588..7b56bbf 100644--- a/tests/integration/test_postgres_unversioned_adoption.py+++ b/tests/integration/test_postgres_unversioned_adoption.py@@ -209,8 +209,8 @@ async def test_real_postgres_generation_adopts_atomically(predecessor,None,AdoptionExit.OK,- "0009",- "ARES-M2B-ALREADY-MANAGED:0009",+ "0011",+ "ARES-M2B-ALREADY-MANAGED:0011",)@@ -358,6 +358,6 @@ async def test_real_postgres_adoption_rerun_is_verified_noop(revision = await _revision(url)assert (first.exit_code, second.diagnostic, revision) == (AdoptionExit.OK,- "ARES-M2B-ALREADY-MANAGED:0009",- "0009",+ "ARES-M2B-ALREADY-MANAGED:0011",+ "0011",)diff --git a/tests/integration/test_postgres_websocket_tickets.py b/tests/integration/test_postgres_websocket_tickets.pyindex bc6921e..bdac2b0 100644--- a/tests/integration/test_postgres_websocket_tickets.py+++ b/tests/integration/test_postgres_websocket_tickets.py@@ -42,7 +42,9 @@ _SAFE_EXCEPTION_TYPE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")_POSTGRES_OPERATION_TIMEOUT_SECONDS = 15.0_MIGRATION_PROCESS_TIMEOUT_SECONDS = 45.0_MIGRATION_ACTIONS = frozenset({"upgrade", "downgrade"})-_MIGRATION_REVISIONS = frozenset({"0006", "0007", "0008", "0009"})+_MIGRATION_REVISIONS = frozenset(+ {"0006", "0007", "0008", "0009", "0010", "0011", "head"}+)_OWNED_MIGRATION_PROCESSES: set[Any] = set()@@ -619,7 +621,7 @@ async def _postgres_harness(database = PostgresDatabase(dsn, pool_min=1, pool_max=8)if initialize_runtime:try:- _run_ticket_migration(test_database, "upgrade", "0009")+ _run_ticket_migration(test_database, "upgrade", "head")await _bounded_operation("runtime-initialize",database.connect(),diff --git a/tests/unit/db/test_database.py b/tests/unit/db/test_database.pyindex a038706..bcaf64c 100644--- a/tests/unit/db/test_database.py+++ b/tests/unit/db/test_database.py@@ -11,13 +11,13 @@ import tempfilefrom datetime import datetime, timedelta, timezonefrom pathlib import Pathfrom typing import Any-from urllib.parse import unquote, urlparsefrom unittest.mock import AsyncMock, patch+from urllib.parse import unquote, urlparseimport pytestimport ares.core.plugin.loader as plugin_loader_module-from ares.core.campaign import Campaign, Finding, NoiseProfile, Severity, ScopeEntry+from ares.core.campaign import Campaign, Finding, NoiseProfile, ScopeEntry, Severityfrom ares.core.config import AresSettingsfrom ares.core.engine import AresEngine, ExecutionPlan, ModuleStatusfrom ares.core.plugin.loader import ModuleRegistry, PluginLoader@@ -25,13 +25,12 @@ from ares.db.database import AresDatabase, Credential, Host, Lootfrom ares.modules.base import BaseModulefrom ares.modules.reporting.report_gen import (BROWSER_PDF_TIMEOUT_SECONDS,- ReportDependencyError,- ReportGenerator,WINDOWS_EDGE_ELEVATED_PDF_MESSAGE,WINDOWS_WEASYPRINT_NATIVE_HINT,+ ReportDependencyError,+ ReportGenerator,)-# ── Fixtures ──────────────────────────────────────────────────────────────────@pytest.fixture@@ -906,3 +905,33 @@ class TestReportGenerator:gen = ReportGenerator()with pytest.raises(ValueError, match="Unknown format"):gen.generate(campaign, fmt="excel")+++async def test_raw_sqlite_uri_uses_unstamped_runtime_generation_ten(+ tmp_path: Path,+) -> None:+ path = tmp_path / "runtime-generation-ten.db"+ uri = f"file:{path.resolve().as_posix()}?mode=rwc"+ database = AresDatabase(uri)+ await database.connect()+ try:+ async with database._conn.execute(+ "SELECT mode,revision FROM execution_gateway_state"+ ) as cursor:+ gateway = await cursor.fetchone()+ async with database._conn.execute(+ "SELECT count(*) FROM sqlite_schema WHERE name='alembic_version'"+ ) as cursor:+ managed_count = int((await cursor.fetchone())[0])+ async with database._conn.execute(+ "SELECT count(*) FROM sqlite_schema WHERE name='schema_version'"+ ) as cursor:+ legacy_marker_count = int((await cursor.fetchone())[0])+ finally:+ await database.close()+ assert (tuple(gateway), managed_count, legacy_marker_count) == (+ ("disabled", 0),+ 0,+ 1,+ ), "raw SQLite runtime generation changed"diff --git a/tests/unit/test_ad_bind_behavior.py b/tests/unit/test_ad_bind_behavior.pyindex d4a2178..b923115 100644--- a/tests/unit/test_ad_bind_behavior.py+++ b/tests/unit/test_ad_bind_behavior.py@@ -51,11 +51,7 @@ def _install_fake_ldap3(monkeypatch, *, bind_outcomes=None):return Truedef search(self, *args, **kwargs):- self.result = {- "controls": {- "1.2.840.113556.1.4.319": {"value": {"cookie": b""}}- }- }+ self.result = {"controls": {"1.2.840.113556.1.4.319": {"value": {"cookie": b""}}}}self.entries = []return True@@ -196,9 +192,7 @@ def test_asreproast_capture_uses_impacket_no_preauth_api(monkeypatch):monkeypatch.setattr(kerberosv5, "getKerberosTGT", fake_get_kerberos_tgt)- raw = asreproast_mod._capture_asrep_raw(- "10.0.0.5", "lab.local", "legacy-nonpreauth"- )+ raw = asreproast_mod._capture_asrep_raw("10.0.0.5", "lab.local", "legacy-nonpreauth")assert raw == b"raw-asrep"assert captured["password"] == ""@@ -238,7 +232,9 @@ async def test_kerberoast_empty_target_fails_fast_before_tgs_worker(monkeypatch)def test_ad_kerberos_execution_chain_metadata_is_guided_and_targeted():from ares.core.execution_chains import list_execution_chains- chain = next(item for item in list_execution_chains() if item["id"] == "ad-kerberos-exposure-chain")+ chain = next(+ item for item in list_execution_chains() if item["id"] == "ad-kerberos-exposure-chain"+ )stages = chain["stages"]targeted = next(stage for stage in stages if stage["module_ids"] == ["ad.kerberoast"])@@ -562,7 +558,9 @@ async def test_kerberoast_tgs_timeout_after_spn_enumeration_is_actionable(monkeyassert time.monotonic() - started < 1.0assert exc_info.value.action == "abort"- assert "LDAP/SPN enumeration succeeded and found 2 Kerberoastable candidate account(s)" in str(exc_info.value)+ assert "LDAP/SPN enumeration succeeded and found 2 Kerberoastable candidate account(s)" in str(+ exc_info.value+ )assert "Kerberos TGS request timed out before a hash was confirmed" in str(exc_info.value)assert "Password1!" not in str(exc_info.value)@@ -722,6 +720,7 @@ async def test_enum_computers_config_error_does_not_retry(monkeypatch, minimal_cfrom unittest.mock import AsyncMock, patchfrom ares.core.engine import AresEngine+ from ares.core.execution_admission import _mint_test_dispatch_contextfrom ares.core.config import AresSettingsfrom ares.core.noise import JitterEnginefrom ares.modules.ad.enum_computers import ADEnumComputersModule@@ -739,6 +738,7 @@ async def test_enum_computers_config_error_does_not_retry(monkeypatch, minimal_creturn await original_fetch(self, *args, **kwargs)monkeypatch.setattr(ADEnumComputersModule, "_fetch_computers", counted_fetch)+async def no_noise_sleep(*args, **kwargs):return None@@ -751,7 +751,14 @@ async def test_enum_computers_config_error_does_not_retry(monkeypatch, minimal_c"use_ldaps": False,}with patch("ares.core.engine.asyncio.sleep", new=AsyncMock()) as retry_sleep:- result = await engine.run_module("ad.enum_computers", minimal_campaign, params)+ result = await engine.run_module(+ "ad.enum_computers",+ minimal_campaign,+ params,+ dispatch_context=_mint_test_dispatch_context(+ engine, minimal_campaign.id, "ad.enum_computers"+ ),+ )assert calls == 1assert retry_sleep.await_count == 0@@ -769,6 +776,7 @@ async def test_enum_computers_ldaps_network_failure_is_not_module_error(from ares.core.config import AresSettingsfrom ares.core.engine import AresEngine+ from ares.core.execution_admission import _mint_test_dispatch_contextfrom ares.core.noise import JitterEngineengine = AresEngine(settings=AresSettings())@@ -794,7 +802,14 @@ async def test_enum_computers_ldaps_network_failure_is_not_module_error("use_ldaps": True,}with patch("ares.core.engine.asyncio.sleep", new=AsyncMock()):- result = await engine.run_module("ad.enum_computers", minimal_campaign, params)+ result = await engine.run_module(+ "ad.enum_computers",+ minimal_campaign,+ params,+ dispatch_context=_mint_test_dispatch_context(+ engine, minimal_campaign.id, "ad.enum_computers"+ ),+ )assert result.outcome == "network_error"assert result.findings == []@@ -818,8 +833,7 @@ async def test_asreproast_candidate_kerberos_failure_is_candidate_aware(monkeypadef skewed_asrep(*args, **kwargs):raise RuntimeError(- "Kerberos SessionError: KRB_AP_ERR_SKEW(Clock skew too great) "- "password=Password1!"+ "Kerberos SessionError: KRB_AP_ERR_SKEW(Clock skew too great) password=Password1!")monkeypatch.setattr(module, "_ldap_get_nopreauth", fake_candidates)diff --git a/tests/unit/test_api_endpoints.py b/tests/unit/test_api_endpoints.pyindex c0032fd..93626bb 100644--- a/tests/unit/test_api_endpoints.py+++ b/tests/unit/test_api_endpoints.py@@ -19,6 +19,7 @@ from __future__ import annotationsimport asyncioimport base64import hashlib+import jsonimport osfrom datetime import datetime, timedelta, timezonefrom types import SimpleNamespace@@ -28,6 +29,7 @@ from unittest.mock import AsyncMock, MagicMock, patchimport httpximport pytestfrom fastapi import HTTPException+from fastapi.responses import JSONResponsefrom fastapi.security import OAuth2PasswordRequestForm# ── env bootstrap (before any ares import) ────────────────────────────────────@@ -42,6 +44,8 @@ os.environ.setdefault("ARES_BROWSER_ORIGIN", "http://localhost:5173")_MOCK_PRINCIPAL_ROLES: dict[str, str] = {}+_C_LIVE_TEST_KEY = "11111111-1111-4111-8111-111111111111"+_PRODUCTION_C_LIVE_DESCRIPTOR_GATE: Any = Nonedef _settings():@@ -66,7 +70,144 @@ def _make_token(username: str, role: str) -> str:def _auth(username: str, role: str) -> dict:- return {"Authorization": f"Bearer {_make_token(username, role)}"}+ return {+ "Authorization": f"Bearer {_make_token(username, role)}",+ "Idempotency-Key": _C_LIVE_TEST_KEY,+ }+++class _UnitLiveCoordinator:+ def __init__(self, engine: Any, role: str) -> None:+ self._engine = engine+ self._role = role++ async def execute_module(self, principal: Any, request: Any, campaign: Any) -> Any:+ del principal+ from ares.core.execution_admission import (+ DispatchDispositionV1,+ DispatchOutcomeV1,+ _identity,+ )+ from ares.db.execution_lifecycle import FixedResult++ result = await self._engine.run_module(+ request.module_id,+ campaign,+ dict(request.raw_parameters),+ actor_role=self._role,+ )+ return DispatchOutcomeV1(+ DispatchDispositionV1.TERMINAL,+ _identity(request),+ FixedResult.APPLIED,+ 4,+ result,+ True,+ True,+ )+++class _UnitLiveRuntime:+ def __init__(self, app: Any) -> None:+ self._app = app++ def bind(self, actor: Any) -> tuple[Any, _UnitLiveCoordinator]:+ from ares.api.server import get_engine+ from ares.db.execution_lifecycle import TrustedPrincipal++ provider = self._app.dependency_overrides.get(get_engine)+ engine = provider() if provider is not None else self._app.state.engine+ source = actor.websocket_ticket_source+ principal = TrustedPrincipal(source.user_id, source.user_id)+ return principal, _UnitLiveCoordinator(engine, actor.role)+++def _c_live_result(module_id: str = "plugin.safe") -> Any:+ result = SimpleNamespace(+ module_id=module_id,+ status="done",+ findings=[],+ error="",+ duration_ms=1.0,+ )+ result.model_dump = lambda: {+ "module_id": module_id,+ "status": "done",+ "findings": [],+ "validation_results": [],+ "raw_output": {},+ "error": "",+ "duration_ms": 1.0,+ }+ return result+++class _RecordingLiveCoordinator:+ def __init__(self, outcome_factory: Any = None) -> None:+ self.requests: list[Any] = []+ self.principals: list[Any] = []+ self._outcome_factory = outcome_factory++ async def execute_module(self, principal: Any, request: Any, campaign: Any) -> Any:+ del campaign+ from ares.core.execution_admission import (+ DispatchDispositionV1,+ DispatchOutcomeV1,+ _identity,+ )+ from ares.db.execution_lifecycle import FixedResult++ self.principals.append(principal)+ self.requests.append(request)+ if self._outcome_factory is not None:+ return self._outcome_factory(request)+ return DispatchOutcomeV1(+ DispatchDispositionV1.TERMINAL,+ _identity(request),+ FixedResult.APPLIED,+ 4,+ _c_live_result(request.module_id),+ True,+ True,+ )+++class _RecordingLiveRuntime:+ def __init__(self, coordinator: _RecordingLiveCoordinator) -> None:+ self.coordinator = coordinator++ def bind(self, actor: Any) -> tuple[Any, _RecordingLiveCoordinator]:+ from ares.db.execution_lifecycle import TrustedPrincipal++ source = actor.websocket_ticket_source+ return TrustedPrincipal(source.user_id, source.user_id), self.coordinator+++def _nonterminal_outcome(result: Any, disposition: Any) -> Any:+ from ares.core.execution_admission import (+ DispatchIdentityV1,+ DispatchOutcomeV1,+ )++ identity = DispatchIdentityV1(+ "10000000-0000-4000-8000-000000000001",+ "10000000-0000-4000-8000-000000000002",+ "10000000-0000-4000-8000-000000000003",+ "10000000-0000-4000-8000-000000000004",+ "10000000-0000-4000-8000-000000000005",+ "10000000-0000-4000-8000-000000000006",+ "10000000-0000-4000-8000-000000000007",+ "10000000-0000-4000-8000-000000000008",+ )+ return DispatchOutcomeV1(+ disposition,+ identity,+ result,+ 0,+ None,+ disposition.value == "indeterminate",+ False,+ )def _issued_session(username: str = "admin", role: str = "team_lead"):@@ -259,14 +400,16 @@ def test_module_outcome_success_mapping(outcome: str, expected: bool) -> None:@pytest.fixture(scope="module")def _app_mock_db():+ global _PRODUCTION_C_LIVE_DESCRIPTOR_GATE# Clear lru_cache so unit tests always use UNIT env vars,# not a cached instance from a previous integration test run.from ares.core.config import get_settings as _get_settings_fn_get_settings_fn.cache_clear()+ import ares.api.server as _serverfrom ares.api.server import app as _app- from ares.api.server import get_db, get_settings+ from ares.api.server import get_c_live_runtime, get_db, get_settingsfrom ares.core.config import AresSettingsmock_db = _make_mock_db()@@ -277,9 +420,14 @@ def _app_mock_db():_app.dependency_overrides[get_db] = lambda: mock_db_app.dependency_overrides[get_settings] = lambda: fake_settings+ _app.dependency_overrides[get_c_live_runtime] = lambda: _UnitLiveRuntime(_app)+ original_descriptor_gate = _server._c_live_descriptor_gate+ _PRODUCTION_C_LIVE_DESCRIPTOR_GATE = original_descriptor_gate+ _server._c_live_descriptor_gate = lambda _module_id, _role: Noneyield _app, mock_db+ _server._c_live_descriptor_gate = original_descriptor_gate_app.dependency_overrides.clear()# Clear cache again so the next test module starts fresh_get_settings_fn.cache_clear()@@ -325,6 +473,64 @@ def aclient(_app_mock_db):asyncio.run(client.aclose())+def c_live_route(aclient: Any) -> Any:+ """Install one request-local fake admission runtime without changing production."""+ from ares.api.server import get_c_live_runtime, get_engine++ client, db, app = aclient+ original_engine = app.dependency_overrides.get(get_engine)+ original_runtime = app.dependency_overrides.get(get_c_live_runtime)+ original_resolver_side_effect = db.resolve_access_token_principal.side_effect+ original_resolver_return = db.resolve_access_token_principal.return_value+ engine = SimpleNamespace(+ registry=MagicMock(),+ run_module=AsyncMock(return_value=_c_live_result()),+ run_plan=AsyncMock(),+ dry_run_module=MagicMock(+ return_value={"status": "dry_run_ok", "module_id": "plugin.safe"}+ ),+ dry_run_plan=MagicMock(+ return_value={"status": "dry_run_ok", "modules": [], "would_execute": True}+ ),+ )+ app.dependency_overrides[get_engine] = lambda: engine+ db.is_access_token_revoked.return_value = False+ db.get_campaign.side_effect = None+ db.get_campaign.return_value = {+ "id": "camp-c-live",+ "name": "C-LIVE",+ "client": "Internal",+ "operator": "legacy-username-must-not-authorize",+ "noise_profile": "normal",+ "status": "created",+ "scope_json": "[]",+ "targets_json": "[]",+ "notes": "",+ }++ def install(coordinator: _RecordingLiveCoordinator) -> None:+ app.dependency_overrides[get_c_live_runtime] = lambda: _RecordingLiveRuntime(+ coordinator+ )++ install(_RecordingLiveCoordinator())+ try:+ yield client, db, app, engine, install+ finally:+ db.is_access_token_revoked.return_value = False+ db.resolve_access_token_principal.side_effect = original_resolver_side_effect+ db.resolve_access_token_principal.return_value = original_resolver_return+ if original_engine is None:+ app.dependency_overrides.pop(get_engine, None)+ else:+ app.dependency_overrides[get_engine] = original_engine+ if original_runtime is None:+ app.dependency_overrides.pop(get_c_live_runtime, None)+ else:+ app.dependency_overrides[get_c_live_runtime] = original_runtime++# ── Health ────────────────────────────────────────────────────────────────────@@ -1805,31 +2011,44 @@ class TestHighNoiseAuthorizationPolicy:self, aclient: Any) -> None:c, db, app = aclient- from ares.api.server import get_engine+ from ares.api.server import get_c_live_runtime, get_engine_, high_noise_module = self._module_classes()engine = self._engine({"plugin.dynamic-high": high_noise_module})+ runtime = MagicMock()+ original_runtime = app.dependency_overrides[get_c_live_runtime]db.get_campaign.reset_mock()+ db.get_campaign.side_effect = None+ db.get_campaign.return_value = Noneapp.dependency_overrides[get_engine] = lambda: engine+ app.dependency_overrides[get_c_live_runtime] = lambda: runtimetry:- response = await c.post(- "/modules/plugin.dynamic-high/run",- json={- "campaign_id": "camp-plan-policy",- "params": {"target": "target-marker"},- "dry_run": False,- },- headers=_auth("operator-user", "operator"),- )+ with patch(+ "ares.api.server._broadcast_event",+ new_callable=AsyncMock,+ ) as broadcast:+ response = await c.post(+ "/modules/plugin.dynamic-high/run",+ json={+ "campaign_id": "camp-plan-policy",+ "params": {"target": "target-marker"},+ "dry_run": False,+ },+ headers=_auth("operator-user", "operator"),+ )finally:app.dependency_overrides.pop(get_engine, None)+ app.dependency_overrides[get_c_live_runtime] = original_runtime- assert response.status_code == 403- assert response.json()["detail"] == (- "'plugin.dynamic-high' is HIGH_NOISE — team_lead only."- )+ # Live authority starts with the durable campaign identity; legacy+ # module classes are not an execution-authority source.+ assert response.status_code == 404+ assert response.json()["detail"] == "Campaign not found"+ db.get_campaign.assert_awaited_once_with("camp-plan-policy")+ engine.registry.get.assert_not_called()+ runtime.bind.assert_not_called()engine.run_module.assert_not_awaited()- db.get_campaign.assert_not_awaited()+ broadcast.assert_not_awaited()@pytest.mark.asyncioasync def test_single_module_team_lead_high_noise_reaches_engine(@@ -1922,20 +2141,17 @@ class TestHighNoiseAuthorizationPolicy:app.dependency_overrides.pop(get_engine, None)assert response.status_code == 200- assert response.json() == {- "campaign_id": "camp-plan-policy",- "modules_run": 1,- "results": {- "plugin.safe": {- "status": "done",- "findings_count": 0,- "error": "",- "duration_ms": 1.0,- }- },- }- engine.run_plan.assert_awaited_once()- assert engine.run_plan.await_args.kwargs["actor_role"] == "operator"+ payload = response.json()+ assert payload["campaign_id"] == "camp-plan-policy"+ assert payload["modules_run"] == 1+ assert [child["module_id"] for child in payload["children"]] == [+ "plugin.safe"+ ]+ assert payload["children"][0]["status"] == "done"+ assert payload["children"][0]["execution"]["attempt_id"]+ engine.run_module.assert_awaited_once()+ assert engine.run_module.await_args.kwargs["actor_role"] == "operator"+ engine.run_plan.assert_not_awaited()@pytest.mark.parametrize("stages",@@ -1979,7 +2195,13 @@ class TestHighNoiseAuthorizationPolicy:finally:app.dependency_overrides.pop(get_engine, None)- assert response.status_code == 403+ assert response.status_code == 200+ expected_modules = [module_id for _name, module_ids in stages for module_id in module_ids]+ assert [+ call.args[0] for call in engine.run_module.await_args_list+ ] == expected_modules+ # The legacy HIGH_NOISE class is not an authority source. Descriptor+ # minimum-role metadata is the sole live role gate.engine.run_plan.assert_not_awaited()engine.dry_run_plan.assert_not_called()@@ -2007,7 +2229,9 @@ class TestHighNoiseAuthorizationPolicy:app.dependency_overrides.pop(get_engine, None)assert response.status_code == 200- engine.run_plan.assert_awaited_once()+ engine.run_module.assert_awaited_once()+ assert engine.run_module.await_args.kwargs["actor_role"] == "team_lead"+ engine.run_plan.assert_not_awaited()@pytest.mark.asyncioasync def test_duplicate_high_noise_plan_detail_is_safe_and_deterministic(@@ -2055,11 +2279,8 @@ class TestHighNoiseAuthorizationPolicy:finally:app.dependency_overrides.pop(get_engine, None)- assert response.status_code == 403- assert response.json()["detail"] == (- "'plugin.alpha-high', 'plugin.zeta-high' "- "are HIGH_NOISE — team_lead only."- )+ assert response.status_code == 422+ assert response.json()["detail"] == "raw_secret_material_forbidden"for sensitive_marker in ("plan-param-marker","target-marker",@@ -2067,6 +2288,7 @@ class TestHighNoiseAuthorizationPolicy:"evidence-marker",):assert sensitive_marker not in response.text+ engine.run_module.assert_not_awaited()engine.run_plan.assert_not_awaited()@pytest.mark.parametrize(@@ -2228,8 +2450,10 @@ class TestHighNoiseAuthorizationPolicy:app.dependency_overrides.pop(get_engine, None)assert response.status_code == 200- engine.registry.get.assert_called_once_with("plugin.unknown")- engine.run_plan.assert_awaited_once()+ engine.registry.get.assert_not_called()+ engine.run_module.assert_awaited_once()+ assert engine.run_module.await_args.args[0] == "plugin.unknown"+ engine.run_plan.assert_not_awaited()engine.dry_run_plan.assert_not_called()@pytest.mark.asyncio@@ -2284,8 +2508,9 @@ class TestHighNoiseAuthorizationPolicy:finally:app.dependency_overrides.pop(get_engine, None)- assert response.status_code == 403- engine.dry_run_plan.assert_not_called()+ assert response.status_code == 200+ assert response.json()["status"] == "dry_run_ok"+ engine.dry_run_plan.assert_called_once()engine.run_plan.assert_not_awaited()@pytest.mark.asyncio@@ -2341,6 +2566,7 @@ class TestHighNoiseAuthorizationPolicy:assert response.status_code == 404engine.registry.get.assert_not_called()+ engine.run_module.assert_not_awaited()engine.run_plan.assert_not_awaited()@pytest.mark.asyncio@@ -2366,8 +2592,12 @@ class TestHighNoiseAuthorizationPolicy:finally:app.dependency_overrides.pop(get_engine, None)- assert response.status_code == 404+ # The legacy campaign.operator username is not canonical execution+ # authority. The durable campaign grant is enforced by admission.+ assert response.status_code == 200+ assert response.json()["modules_run"] == 1engine.registry.get.assert_not_called()+ engine.run_module.assert_awaited_once()engine.run_plan.assert_not_awaited()@pytest.mark.asyncio@@ -2420,6 +2650,510 @@ class TestHighNoiseAuthorizationPolicy:engine.run_plan.assert_not_awaited()+ "case",+ [+ "missing-bearer",+ "invalid-bearer",+ "revoked-bearer",+ "deleted-user",+ "inactive-user",+ "demoted-role",+ "exact-replay-no-engine",+ "conflict-no-engine",+ ],+)+async def test_c_live_http_authentication_and_submission_lookup(+ case: str,+ c_live_route: Any,+) -> None:+ from ares.core.execution_admission import DispatchDispositionV1+ from ares.db.execution_lifecycle import FixedResult++ client, db, _app, engine, install = c_live_route+ db.get_campaign.reset_mock()+ coordinator = _RecordingLiveCoordinator()+ username = f"c-live-{case}"+ headers = _auth(username, "operator")+ expected_status = 401+ if case == "missing-bearer":+ headers = {"Idempotency-Key": _C_LIVE_TEST_KEY}+ elif case == "invalid-bearer":+ headers = {+ "Authorization": "Bearer invalid.c-live.token",+ "Idempotency-Key": _C_LIVE_TEST_KEY,+ }+ elif case == "revoked-bearer":+ db.is_access_token_revoked.return_value = True+ elif case in {"deleted-user", "inactive-user"}:+ db.resolve_access_token_principal.side_effect = None+ db.resolve_access_token_principal.return_value = None+ elif case == "demoted-role":+ headers = _auth(username, "reporter")+ expected_status = 403+ elif case == "exact-replay-no-engine":+ coordinator = _RecordingLiveCoordinator(+ lambda _request: _nonterminal_outcome(+ FixedResult.REPLAYED,+ DispatchDispositionV1.REPLAYED,+ )+ )+ expected_status = 409+ else:+ coordinator = _RecordingLiveCoordinator(+ lambda _request: _nonterminal_outcome(+ FixedResult.CONFLICT_OPERATION,+ DispatchDispositionV1.CONFLICT,+ )+ )+ expected_status = 409+ install(coordinator)++ response = await client.post(+ "/modules/plugin.safe/run",+ json={"campaign_id": "camp-c-live", "params": {}, "dry_run": False},+ headers=headers,+ )++ assert response.status_code == expected_status+ engine.run_module.assert_not_awaited()+ if case in {"exact-replay-no-engine", "conflict-no-engine"}:+ assert len(coordinator.requests) == 1+ assert len(coordinator.principals) == 1+ assert coordinator.principals[0].subject_ref == coordinator.principals[0].user_id+ assert coordinator.principals[0].user_id == f"mock-user-{username}"+ assert coordinator.principals[0].subject_ref != username+ assert db.get_campaign.await_count == 1+ else:+ assert not coordinator.requests+ db.get_campaign.assert_not_awaited()++[email protected]("route", ["module", "plan", "strategy"])+async def test_c_live_authenticated_dispatch_uses_v3_admission(+ route: str,+ c_live_route: Any,+ monkeypatch: Any,+) -> None:+ import ares.api.server as server++ client, _db, _app, engine, install = c_live_route+ coordinator = _RecordingLiveCoordinator()+ install(coordinator)+ headers = _auth(f"c-live-{route}", "operator")+ if route == "module":+ response = await client.post(+ "/modules/plugin.safe/run",+ json={"campaign_id": "camp-c-live", "params": {}, "dry_run": False},+ headers=headers,+ )+ expected_ingress = "api_module"+ elif route == "plan":+ response = await client.post(+ "/campaigns/camp-c-live/run",+ json={+ "plan": {"stages": [{"name": "one", "modules": ["plugin.safe"]}]},+ "global_params": {},+ "dry_run": False,+ },+ headers=headers,+ )+ expected_ingress = "api_campaign_plan"+ else:+ monkeypatch.setattr(+ server,+ "_strategy_test_plan",+ lambda _body: {"stages": [{"name": "one", "modules": ["plugin.safe"]}]},+ )+ response = await client.post(+ "/strategy/engage",+ json={"campaign_id": "camp-c-live"},+ headers=headers,+ )+ expected_ingress = "strategy"++ assert response.status_code == 200+ assert [item.ingress_code for item in coordinator.requests] == [expected_ingress]+ engine.run_module.assert_not_awaited()++[email protected]("route", ["module", "plan", "strategy"])+async def test_c_live_admission_denial_prevents_engine(+ route: str,+ c_live_route: Any,+ monkeypatch: Any,+) -> None:+ import ares.api.server as server+ from ares.core.execution_admission import DispatchDispositionV1+ from ares.db.execution_lifecycle import FixedResult++ client, _db, _app, engine, install = c_live_route+ coordinator = _RecordingLiveCoordinator(+ lambda _request: _nonterminal_outcome(+ FixedResult.AUTHORITY_STALE,+ DispatchDispositionV1.NON_DISPATCHABLE,+ )+ )+ install(coordinator)+ headers = _auth(f"c-live-denied-{route}", "operator")+ if route == "module":+ response = await client.post(+ "/modules/plugin.safe/run",+ json={"campaign_id": "camp-c-live", "params": {}, "dry_run": False},+ headers=headers,+ )+ elif route == "plan":+ response = await client.post(+ "/campaigns/camp-c-live/run",+ json={+ "plan": {"stages": [{"name": "one", "modules": ["plugin.safe"]}]},+ "global_params": {},+ "dry_run": False,+ },+ headers=headers,+ )+ else:+ monkeypatch.setattr(+ server,+ "_strategy_test_plan",+ lambda _body: {"stages": [{"name": "one", "modules": ["plugin.safe"]}]},+ )+ response = await client.post(+ "/strategy/engage",+ json={"campaign_id": "camp-c-live"},+ headers=headers,+ )++ assert response.status_code == 409+ assert response.json()["type"] == "execution_authority_stale"+ engine.run_module.assert_not_awaited()++[email protected]("case", ["missing", "invalid"])+async def test_c_live_idempotency_key_validation(case: str, c_live_route: Any) -> None:+ client, db, _app, engine, _install = c_live_route+ headers = {+ "Authorization": f"Bearer {_make_token(f'key-{case}', 'operator')}"+ }+ if case == "invalid":+ headers["Idempotency-Key"] = "11111111-1111-1111-8111-111111111111"+ db.get_campaign.reset_mock()++ response = await client.post(+ "/modules/plugin.safe/run",+ json={"campaign_id": "camp-c-live", "params": {}, "dry_run": False},+ headers=headers,+ )++ assert response.status_code == 422+ assert response.json()["detail"] == (+ "idempotency_key_required" if case == "missing" else "idempotency_key_invalid"+ )+ assert db.get_campaign.await_count == 1+ engine.run_module.assert_not_awaited()+++async def test_c_live_api_key_execution_is_denied(c_live_route: Any) -> None:+ client, db, _app, engine, _install = c_live_route+ db.verify_api_key.reset_mock()+ response = await client.post(+ "/modules/plugin.safe/run",+ json={"campaign_id": "camp-c-live", "params": {}, "dry_run": False},+ headers={"X-API-Key": "opaque-api-key", "Idempotency-Key": _C_LIVE_TEST_KEY},+ )++ assert response.status_code == 403+ assert response.json()["detail"] == "api_key_execution_denied"+ db.verify_api_key.assert_not_awaited()+ engine.run_module.assert_not_awaited()+++async def test_c_live_raw_credential_material_is_rejected(c_live_route: Any) -> None:+ client, _db, _app, engine, _install = c_live_route+ response = await client.post(+ "/modules/plugin.safe/run",+ json={+ "campaign_id": "camp-c-live",+ "params": {"password": "must-never-cross-live-boundary"},+ "dry_run": False,+ },+ headers=_auth("raw-secret-user", "operator"),+ )++ assert response.status_code == 422+ assert response.json()["detail"] == "raw_secret_material_forbidden"+ engine.run_module.assert_not_awaited()++[email protected]("route", ["module", "plan"])+async def test_c_live_http_preview_executes_no_module_code(+ route: str,+ c_live_route: Any,+) -> None:+ client, _db, _app, engine, _install = c_live_route+ headers = {"Authorization": f"Bearer {_make_token(f'preview-{route}', 'operator')}"}+ if route == "module":+ response = await client.post(+ "/modules/plugin.safe/run",+ json={"campaign_id": "camp-c-live", "params": {}, "dry_run": True},+ headers=headers,+ )+ engine.dry_run_module.assert_called_once()+ else:+ response = await client.post(+ "/campaigns/camp-c-live/run",+ json={+ "plan": {"stages": [{"name": "one", "modules": ["plugin.safe"]}]},+ "global_params": {},+ "dry_run": True,+ },+ headers=headers,+ )+ engine.dry_run_plan.assert_called_once()+ assert response.status_code == 200+ engine.run_module.assert_not_awaited()++[email protected]("authority", ["credential", "approval"])+def test_c_live_required_authority_module_is_non_dispatchable(authority: str) -> None:+ from ares.modules.descriptors import ContractState, FIRST_PARTY_DESCRIPTORS++ assert _PRODUCTION_C_LIVE_DESCRIPTOR_GATE is not None+ if authority == "approval":+ descriptors = [+ item for item in FIRST_PARTY_DESCRIPTORS.values() if item.explicit_attempt_approval+ ]+ else:+ descriptors = [+ item+ for item in FIRST_PARTY_DESCRIPTORS.values()+ if item.credential_policy.state is not ContractState.NOT_APPLICABLE+ ]+ assert descriptors+ assert {+ _PRODUCTION_C_LIVE_DESCRIPTOR_GATE(item.module_id, "team_lead")+ for item in descriptors+ } == {"descriptor_unavailable"}+++def test_c_live_production_descriptor_seam_cannot_escape_tests() -> None:+ from ares.modules.descriptors import FIRST_PARTY_DESCRIPTORS++ assert len(FIRST_PARTY_DESCRIPTORS) == 62+ assert _PRODUCTION_C_LIVE_DESCRIPTOR_GATE is not None+ assert all(+ not item.future_gateway_eligible+ and _PRODUCTION_C_LIVE_DESCRIPTOR_GATE(item.module_id, "team_lead")+ == "descriptor_unavailable"+ for item in FIRST_PARTY_DESCRIPTORS.values()+ )+++def test_c_live_response_loss_status_inspection_is_stable_and_effect_free() -> None:+ from ares.api.server import _c_live_error_response+ from ares.core.execution_admission import DispatchDispositionV1+ from ares.db.execution_lifecycle import FixedResult++ outcome = _nonterminal_outcome(+ FixedResult.REPLAYED,+ DispatchDispositionV1.REPLAYED,+ )+ first = _c_live_error_response(outcome)+ second = _c_live_error_response(outcome)+ assert first.status_code == second.status_code == 409+ assert json.loads(first.body) == json.loads(second.body)+ assert json.loads(first.body)["redispatched"] is False+ assert json.loads(first.body)["execution"] == {+ "submission_id": "10000000-0000-4000-8000-000000000001",+ "logical_execution_id": "10000000-0000-4000-8000-000000000002",+ "attempt_id": "10000000-0000-4000-8000-000000000003",+ }+++async def test_c_live_repeated_module_response_preserves_occurrence_and_stable_ids(+ c_live_route: Any,+) -> None:+ client, _db, _app, _engine, install = c_live_route+ coordinator = _RecordingLiveCoordinator()+ install(coordinator)+ response = await client.post(+ "/campaigns/camp-c-live/run",+ json={+ "plan": {+ "stages": [+ {"name": "repeat", "modules": ["plugin.safe", "plugin.safe"]}+ ]+ },+ "global_params": {},+ "dry_run": False,+ },+ headers=_auth("repeat-user", "operator"),+ )++ assert response.status_code == 200+ children = response.json()["children"]+ assert [item["occurrence"] for item in children] == [0, 1]+ assert [item["module_id"] for item in children] == ["plugin.safe", "plugin.safe"]+ assert children[0]["execution"]["attempt_id"] != children[1]["execution"]["attempt_id"]+ assert {item.idempotency_key for item in coordinator.requests} == {_C_LIVE_TEST_KEY}+ assert len({item.whole_intent_digest for item in coordinator.requests}) == 1+++ ("role_case", "expected_status"),+ [+ ("operator", 200),+ ("team-lead", 200),+ ("reporter", 403),+ ("recon", 403),+ ("admin-not-synthesized", 401),+ ],+ ids=(+ "operator",+ "team-lead",+ "reporter",+ "recon",+ "admin-not-synthesized",+ ),+)+async def test_c_live_role_mapping(+ role_case: str,+ expected_status: int,+ c_live_route: Any,+) -> None:+ client, db, _app, engine, _install = c_live_route+ role = {+ "team-lead": "team_lead",+ "admin-not-synthesized": "admin",+ }.get(role_case, role_case)+ db.get_campaign.reset_mock()+ response = await client.post(+ "/modules/plugin.safe/run",+ json={"campaign_id": "camp-c-live", "params": {}, "dry_run": False},+ headers=_auth(f"role-{role_case}", role),+ )++ assert response.status_code == expected_status+ engine.run_module.assert_not_awaited()+ if expected_status != 200:+ db.get_campaign.assert_not_awaited()+++ "case",+ [+ "applied",+ "replayed",+ "changed-conflict",+ "invalid-contract",+ "conflict-state",+ "authority-stale",+ "capacity-failure",+ "terminal-policy-outcome",+ "settlement-pending",+ "descriptor-unavailable",+ ],+)+async def test_c_live_http_result_mapping(case: str, c_live_route: Any) -> None:+ from ares.api.server import _c_live_error_response, _c_live_unavailable_response+ from ares.core.execution_admission import DispatchDispositionV1+ from ares.db.execution_lifecycle import FixedResult++ client, _db, _app, _engine, install = c_live_route+ if case == "applied":+ install(_RecordingLiveCoordinator())+ response = await client.post(+ "/modules/plugin.safe/run",+ json={"campaign_id": "camp-c-live", "params": {}, "dry_run": False},+ headers=_auth("mapping-applied", "operator"),+ )+ assert response.status_code == 200+ assert "execution" in response.json()+ return+ if case == "descriptor-unavailable":+ response = _c_live_unavailable_response("descriptor_unavailable")+ expected_status, expected_type = 409, "descriptor_unavailable"+ elif case == "invalid-contract":+ coordinator = _RecordingLiveCoordinator()+ install(coordinator)+ response = await client.post(+ "/campaigns/camp-c-live/run",+ json={"plan": {"stages": []}, "global_params": {}, "dry_run": False},+ headers=_auth("mapping-invalid-contract", "operator"),+ )+ assert coordinator.requests == []+ expected_status, expected_type = 422, "invalid_contract"+ else:+ cases = {+ "replayed": (+ FixedResult.REPLAYED,+ DispatchDispositionV1.REPLAYED,+ 409,+ "execution_replayed_no_redispatch",+ ),+ "changed-conflict": (+ FixedResult.CONFLICT_OPERATION,+ DispatchDispositionV1.CONFLICT,+ 409,+ "idempotency_conflict",+ ),+ "conflict-state": (+ FixedResult.CONFLICT_STATE,+ DispatchDispositionV1.CONFLICT,+ 409,+ "execution_not_dispatchable",+ ),+ "authority-stale": (+ FixedResult.AUTHORITY_STALE,+ DispatchDispositionV1.NON_DISPATCHABLE,+ 409,+ "execution_authority_stale",+ ),+ "capacity-failure": (+ FixedResult.CAPACITY_UNAVAILABLE,+ DispatchDispositionV1.NON_DISPATCHABLE,+ 429,+ "execution_capacity_unavailable",+ ),+ "terminal-policy-outcome": (+ FixedResult.APPLIED,+ DispatchDispositionV1.NON_DISPATCHABLE,+ 409,+ "execution_not_dispatchable",+ ),+ "settlement-pending": (+ FixedResult.APPLIED,+ DispatchDispositionV1.INDETERMINATE,+ 503,+ "execution_settlement_unconfirmed",+ ),+ }+ result, disposition, expected_status, expected_type = cases[case]+ response = _c_live_error_response(_nonterminal_outcome(result, disposition))+ if isinstance(response, httpx.Response):+ payload = response.json()+ elif isinstance(response, JSONResponse):+ payload = json.loads(response.body)+ else:+ raise AssertionError(+ "unsupported response type: "+ f"{type(response).__module__}.{type(response).__qualname__}"+ )+ assert response.status_code == expected_status+ assert payload["detail"] == payload["type"] == expected_type+ assert payload["redispatched"] is False++class TestModuleRunEndpoint:def setup_method(self) -> None:_reset_rate_limiter()@@ -2554,17 +3288,17 @@ class TestModuleRunEndpoint:assert campaign.targets == ["127.0.0.1"]@pytest.mark.asyncio # type: ignore[untyped-decorator]- async def test_kerberoast_dashboard_payload_passes_api_validation(- self, aclient: Any- ) -> None:+ async def test_kerberoast_dashboard_payload_passes_api_validation(self, aclient: Any) -> None:c, db, app = aclient- from ares.api.server import get_engine+ from ares.api.server import get_c_live_runtime, get_enginefrom ares.modules.ad.kerberoast import KerberoastModulecaptured: dict[str, Any] = {}+ registry_calls: list[str] = []class FakeRegistry:def get(self, module_id: str) -> Any:+ registry_calls.append(module_id)return KerberoastModule if module_id == "ad.kerberoast" else Noneclass FakeResult:@@ -2611,38 +3345,46 @@ class TestModuleRunEndpoint:"created_at": "2026-06-27 02:15:19","updated_at": "2026-06-27 02:15:19",}+ runtime = MagicMock()+ original_runtime = app.dependency_overrides[get_c_live_runtime]app.dependency_overrides[get_engine] = lambda: FakeEngine()+ app.dependency_overrides[get_c_live_runtime] = lambda: runtimetry:- r = await c.post(- "/modules/ad.kerberoast/run",- json={- "campaign_id": "camp-kerberoast",- "params": {- "dc": "10.0.0.5",- "domain": "corp.local",- "username": "svc-roast",- "password": "Passw0rd!",- "use_ldaps": False,- "target_user": "sqlsvc",+ with patch(+ "ares.api.server._broadcast_event",+ new_callable=AsyncMock,+ ) as broadcast:+ r = await c.post(+ "/modules/ad.kerberoast/run",+ json={+ "campaign_id": "camp-kerberoast",+ "params": {+ "dc": "10.0.0.5",+ "domain": "corp.local",+ "username": "svc-roast",+ "password": "Passw0rd!",+ "use_ldaps": False,+ "target_user": "sqlsvc",+ },+ "dry_run": False,},- "dry_run": False,- },- headers=_auth("admin", "team_lead"),- )+ headers=_auth("admin", "team_lead"),+ )finally:app.dependency_overrides.pop(get_engine, None)+ app.dependency_overrides[get_c_live_runtime] = original_runtime- assert r.status_code == 200- assert captured["module_id"] == "ad.kerberoast"- assert captured["actor_role"] == "team_lead"- assert captured["params"] == {- "dc": "10.0.0.5",- "domain": "corp.local",- "username": "svc-roast",- "password": "Passw0rd!",- "use_ldaps": False,- "target_user": "sqlsvc",+ assert r.status_code == 422+ assert r.json() == {+ "code": 422,+ "detail": "raw_secret_material_forbidden",+ "type": "api_error",}+ assert "Passw0rd!" not in r.text+ assert captured == {}+ assert registry_calls == []+ runtime.bind.assert_not_called()+ broadcast.assert_not_awaited()@pytest.mark.asyncio # type: ignore[untyped-decorator]async def test_module_result_redacts_sensitive_hash_evidence(@@ -2963,7 +3705,7 @@ class TestReportEndpoints:) -> None:c, _, app = aclientimport ares.modules.reporting.report_gen as report_gen- from ares.api.server import get_db, get_engine+ from ares.api.server import get_c_live_runtime, get_db, get_enginefrom ares.core.campaign import Campaign, Finding, NoiseProfile, ScopeEntry, Severityfrom ares.core.engine import EngineModuleResult, ModuleStatusfrom ares.core.security import create_access_token@@ -2986,7 +3728,8 @@ class TestReportEndpoints:)assert issued.session is not Nonereal_auth = {- "Authorization": f"Bearer {issued.session.access_token}"+ "Authorization": f"Bearer {issued.session.access_token}",+ "Idempotency-Key": _C_LIVE_TEST_KEY,}original_db = getattr(app.state, "db", None)campaign = Campaign(@@ -2999,8 +3742,46 @@ class TestReportEndpoints:)await real_db.save_campaign(campaign)+ registry_calls: list[str] = []+ module_calls: list[str] = []++ def finding_for(module_id: str) -> Finding:+ if module_id == "ad.asreproast":+ return Finding(+ title="ASREPRoast Hashes Captured (1)",+ description="Captured one AS-REP hash.",+ severity=Severity.HIGH,+ validated=True,+ module_id=module_id,+ mitre_technique="T1558.004",+ mitre_tactic="Credential Access",+ evidence={+ "hash_count": 1,+ "sample_hash": "[email protected]:abcdef",+ },+ remediation="Require Kerberos pre-authentication.",+ host="10.10.10.20",+ )+ return Finding(+ title="Kerberoast Hashes Captured (1)",+ description="Captured one TGS hash.",+ severity=Severity.CRITICAL,+ validated=True,+ module_id=module_id,+ mitre_technique="T1558.003",+ mitre_tactic="Credential Access",+ evidence={+ "hash_count": 1,+ "accounts": ["svc-sql"],+ "sample_hash": "$krb5tgs$23$*svc-sql$LAB.LOCAL$svc/sql*abcdef",+ },+ remediation="Rotate service account credentials.",+ host="10.10.10.20",+ )+class FakeRegistry:def get(self, module_id: str) -> Any:+ registry_calls.append(module_id)return Noneclass FakeEngine:@@ -3016,39 +3797,8 @@ class TestReportEndpoints:params: dict[str, Any],actor_role: str = "",) -> EngineModuleResult:- if module_id == "ad.asreproast":- finding = Finding(- title="ASREPRoast Hashes Captured (1)",- description="Captured one AS-REP hash.",- severity=Severity.HIGH,- validated=True,- module_id=module_id,- mitre_technique="T1558.004",- mitre_tactic="Credential Access",- evidence={- "hash_count": 1,- "sample_hash": "[email protected]:abcdef",- },- remediation="Require Kerberos pre-authentication.",- host="10.10.10.20",- )- else:- finding = Finding(- title="Kerberoast Hashes Captured (1)",- description="Captured one TGS hash.",- severity=Severity.CRITICAL,- validated=True,- module_id=module_id,- mitre_technique="T1558.003",- mitre_tactic="Credential Access",- evidence={- "hash_count": 1,- "accounts": ["svc-sql"],- "sample_hash": "$krb5tgs$23$*svc-sql$LAB.LOCAL$svc/sql*abcdef",- },- remediation="Rotate service account credentials.",- host="10.10.10.20",- )+ module_calls.append(module_id)+ finding = finding_for(module_id)result = EngineModuleResult(module_id=module_id,status=ModuleStatus.DONE,@@ -3069,11 +3819,32 @@ class TestReportEndpoints:def generator_factory(*args: Any, **kwargs: Any) -> Any:return real_report_generator(output_dir=str(tmp_path / "reports"), **kwargs)+ async def effect_counts() -> tuple[int, ...]:+ cursor = await real_db.conn.execute(+ """+ SELECT+ (SELECT COUNT(*) FROM logical_executions),+ (SELECT COUNT(*) FROM execution_attempts),+ (SELECT COUNT(*) FROM execution_publication_outbox),+ (SELECT COUNT(*) FROM execution_operation_receipts),+ (SELECT COUNT(*) FROM module_runs),+ (SELECT COUNT(*) FROM findings)+ """+ )+ row = await cursor.fetchone()+ await cursor.close()+ return tuple(int(value) for value in row)++ runtime = MagicMock()+ original_runtime = app.dependency_overrides[get_c_live_runtime]app.state.db = real_dbapp.dependency_overrides[get_db] = lambda: real_dbapp.dependency_overrides[get_engine] = lambda: FakeEngine(real_db)+ app.dependency_overrides[get_c_live_runtime] = lambda: runtimemonkeypatch.setattr(report_gen, "ReportGenerator", generator_factory)try:+ before_effects = await effect_counts()+ assert before_effects == (0, 0, 0, 0, 0, 0)common_params = {"dc": "10.10.10.20","domain": "lab.local",@@ -3081,26 +3852,68 @@ class TestReportEndpoints:"password": "CorrectHorseBatteryStaple!","use_ldaps": False,}- asrep = await c.post(- f"/modules/ad.asreproast/run",- headers=real_auth,- json={- "campaign_id": campaign.id,- "params": common_params,- "dry_run": False,- },- )- kerb = await c.post(- f"/modules/ad.kerberoast/run",- headers=real_auth,- json={- "campaign_id": campaign.id,- "params": {**common_params, "target_user": "svc-sql"},- "dry_run": False,- },- )- assert asrep.status_code == 200- assert kerb.status_code == 200+ with patch(+ "ares.api.server._broadcast_event",+ new_callable=AsyncMock,+ ) as broadcast:+ asrep = await c.post(+ "/modules/ad.asreproast/run",+ headers=real_auth,+ json={+ "campaign_id": campaign.id,+ "params": common_params,+ "dry_run": False,+ },+ )+ kerb = await c.post(+ "/modules/ad.kerberoast/run",+ headers=real_auth,+ json={+ "campaign_id": campaign.id,+ "params": {**common_params, "target_user": "svc-sql"},+ "dry_run": False,+ },+ )+ assert asrep.status_code == 422+ assert kerb.status_code == 422+ assert asrep.json() == {+ "code": 422,+ "detail": "raw_secret_material_forbidden",+ "type": "api_error",+ }+ assert kerb.json() == {+ "code": 422,+ "detail": "raw_secret_material_forbidden",+ "type": "api_error",+ }+ assert "CorrectHorseBatteryStaple!" not in asrep.text+ assert "CorrectHorseBatteryStaple!" not in kerb.text+ assert registry_calls == []+ assert module_calls == []+ runtime.bind.assert_not_called()+ broadcast.assert_not_awaited()+ assert await effect_counts() == before_effects++ # Seed equivalent historical rows explicitly after proving the two+ # rejected requests had zero effect, so the persisted report-path+ # assertions below remain independent of the live boundary.+ for module_id in ("ad.asreproast", "ad.kerberoast"):+ finding = finding_for(module_id)+ result = EngineModuleResult(+ module_id=module_id,+ status=ModuleStatus.DONE,+ findings=[finding],+ raw_output={"confirmed": 1},+ duration_ms=12.0,+ )+ await real_db.save_finding(campaign.id, finding, module_id)+ await real_db.record_module_run(+ campaign.id,+ module_id,+ result.outcome,+ True,+ result.duration_ms,+ )# Legacy/current dashboard rows may be visible even if the validated# flag is not populated; report hydration must not use a stricter@@ -3118,8 +3931,7 @@ class TestReportEndpoints:assert findings_response.status_code == 200assert len(findings_response.json()) == 2assert all(- row["evidence_json"] == '{"redacted":true}'- for row in findings_response.json()+ row["evidence_json"] == '{"redacted":true}' for row in findings_response.json())assert "$krb5asrep$" not in findings_response.textassert "$krb5tgs$" not in findings_response.text@@ -3141,6 +3953,7 @@ class TestReportEndpoints:finally:app.dependency_overrides.pop(get_db, None)app.dependency_overrides.pop(get_engine, None)+ app.dependency_overrides[get_c_live_runtime] = original_runtimeapp.state.db = original_dbawait real_db.close()diff --git a/tests/unit/test_cli_reporting_goal_planning.py b/tests/unit/test_cli_reporting_goal_planning.pyindex 7bf452f..0866646 100644--- a/tests/unit/test_cli_reporting_goal_planning.py+++ b/tests/unit/test_cli_reporting_goal_planning.py@@ -14,10 +14,11 @@ import tempfilefrom contextlib import contextmanagerfrom datetime import datetimefrom pathlib import Path+from types import SimpleNamespacefrom typing import Any-from unittest.mock import AsyncMock, MagicMock, patch, PropertyMock-import pytest+from unittest.mock import AsyncMock, MagicMock, PropertyMock, patch+import pytest# ─────────────────────────────────────────────────────────────# HELPERS@@ -784,7 +785,9 @@ class TestGoalEngine:registry = _make_mock_registry(module_ids or ["ad.enum_users", "ad.kerberoast"])session = OperatorSession(campaign_id="test-001")- return GoalEngine(registry=registry, session=session)+ engine = GoalEngine(registry=registry, session=session)+ engine._configure_c_live_test_planning()+ return enginedef test_plan_domain_admin(self):from ares.goal.engine import Goal@@ -854,6 +857,77 @@ class TestGoalEngine:# Steps derived from context should reference the domainassert isinstance(step.params, dict)+ @pytest.mark.asyncio+ async def test_c_live_goal_execute_uses_admitted_plan_dispatch(self):+ from ares.core.execution_admission import DispatchDispositionV1+ from ares.db.execution_lifecycle import FixedResult, TrustedPrincipal+ from ares.goal.engine import (+ GOAL_DEFINITIONS,+ Goal,+ GoalAttackPlan,+ GoalAttackStep,+ GoalEngine,+ )++ engine = self._make_engine(["ad.enum_users", "ad.enum_spn"])+ production_engine = GoalEngine(registry=engine.registry, session=engine.session)+ with pytest.raises(PermissionError, match="non-dispatchable"):+ production_engine.plan(Goal.DOMAIN_ADMIN)++ nested_params = {"hosts": ["dc01.corp.test"]}+ plan = GoalAttackPlan(+ goal=Goal.DOMAIN_ADMIN,+ definition=GOAL_DEFINITIONS[Goal.DOMAIN_ADMIN],+ steps=[+ GoalAttackStep(1, "ad.enum_users", "frozen", {"nested": nested_params}),+ GoalAttackStep(2, "ad.enum_spn", "frozen", {"nested": nested_params}),+ ],+ )+ production_result = await production_engine.execute(+ plan,+ SimpleNamespace(id="00000000-0000-4000-8000-000000000024"),+ )+ assert production_result["status"] == "non_dispatchable"+ assert production_result["steps_run"] == 0++ requests = []++ async def execute_module(principal, request, campaign):+ del principal, campaign+ requests.append(request)+ if len(requests) == 1:+ nested_params["hosts"][0] = "caller-mutated-after-first-effect"+ request.raw_parameters["nested"]["hosts"].append("first-child-mutation")+ return SimpleNamespace(+ disposition=DispatchDispositionV1.TERMINAL,+ identity=None,+ lifecycle_result=FixedResult.APPLIED,+ terminal_committed=True,+ )++ coordinator = SimpleNamespace(execute_module=AsyncMock(side_effect=execute_module))+ engine._configure_c_live_test_dispatch(+ coordinator=coordinator,+ principal=TrustedPrincipal(+ "00000000-0000-4000-8000-000000000022",+ "00000000-0000-4000-8000-000000000022",+ ),+ idempotency_key="00000000-0000-4000-8000-000000000023",+ )++ result = await engine.execute(+ plan,+ SimpleNamespace(id="00000000-0000-4000-8000-000000000024"),+ )++ assert result["status"] == "terminal"+ assert coordinator.execute_module.await_count == 2+ assert requests[0].ingress_code == "goal_api"+ assert requests[0].module_id == "ad.enum_users"+ assert requests[1].module_id == "ad.enum_spn"+ assert requests[0].whole_intent_digest == requests[1].whole_intent_digest+ assert requests[1].raw_parameters == {"nested": {"hosts": ["dc01.corp.test"]}}+class TestAttackPlanner:@@ -1221,3 +1295,126 @@ class TestReportCampaignRoundTrip:spn_stage = next(i for i, s in enumerate(stages) if "ad.enum_spn" in s)krbst_stage = next(i for i, s in enumerate(stages) if "ad.kerberoast" in s)assert krbst_stage > spn_stage+++def test_c_live_cli_dispatch_is_bearer_http_only(monkeypatch):+ import ares.cli.typer_main as cli++ key = "00000000-0000-4000-8000-000000000047"+ captured: dict[str, Any] = {}+ response = MagicMock()+ response.status = 200+ response.read.return_value = b'{"status":"accepted"}'+ response.__enter__.return_value = response+ response.__exit__.return_value = False+ opener = MagicMock()+ opener.open.return_value = response+ monkeypatch.setenv("ARES_API_URL", "https://ares.example.test:8443")+ monkeypatch.setenv("ARES_ACCESS_TOKEN", "opaque-test-bearer")++ def build_opener(*handlers):+ captured["handlers"] = handlers+ return opener++ monkeypatch.setattr(cli.urllib_request, "build_opener", build_opener)+ monkeypatch.setattr(cli.ssl, "create_default_context", MagicMock(return_value=MagicMock()))++ result = cli._c_live_http_post(+ "/modules/ad.test/run",+ {"campaign_id": "campaign-47", "params": {}, "dry_run": False},+ key,+ )++ assert result["status"] == 200+ opener.open.assert_called_once()+ outgoing = opener.open.call_args.args[0]+ assert outgoing.full_url == "https://ares.example.test:8443/modules/ad.test/run"+ assert outgoing.get_method() == "POST"+ assert outgoing.get_header("Authorization") == "Bearer opaque-test-bearer"+ assert outgoing.get_header("Idempotency-key") == key+ assert json.loads(outgoing.data) == {+ "campaign_id": "campaign-47",+ "dry_run": False,+ "params": {},+ }+ assert any(+ isinstance(handler, cli.urllib_request.HTTPSHandler)+ for handler in captured["handlers"]+ )+++def test_c_live_cli_preview_executes_no_module_code(monkeypatch):+ import ares.cli.typer_main as cli++ dispatch = MagicMock(side_effect=AssertionError("preview crossed HTTP boundary"))+ monkeypatch.setattr(cli, "_c_live_http_post", dispatch)++ asyncio.run(+ cli._run_chain(+ "domain_admin",+ "10.0.0.1",+ "campaign-47",+ "CORP.LOCAL",+ "normal",+ False,+ True,+ "00000000-0000-4000-8000-000000000047",+ )+ )+ cli.goal_run(+ "domain_admin",+ "campaign-47",+ "10.0.0.1",+ "CORP.LOCAL",+ True,+ "00000000-0000-4000-8000-000000000047",+ )++ dispatch.assert_not_called()+++def test_c_live_cli_transport_contract_covers_url_token_campaign_key_tls_and_errors(+ monkeypatch,+):+ import ares.cli.typer_main as cli++ key = "00000000-0000-4000-8000-000000000096"+ monkeypatch.delenv("ARES_API_URL", raising=False)+ with pytest.raises(cli._CLiveCliError, match="api-url"):+ cli._c_live_api_url()++ monkeypatch.setenv("ARES_API_URL", "http://ares.example.test")+ with pytest.raises(cli._CLiveCliError, match="tls-required"):+ cli._c_live_api_url()++ monkeypatch.setenv("ARES_API_URL", "http://127.0.0.1:8000")+ assert cli._c_live_api_url() == ("http://127.0.0.1:8000", False)+ monkeypatch.setenv("ARES_API_URL", "https://ares.example.test")+ assert cli._c_live_api_url() == ("https://ares.example.test", True)++ monkeypatch.delenv("ARES_ACCESS_TOKEN", raising=False)+ monkeypatch.setattr(cli.getpass, "getpass", MagicMock(return_value="prompted-bearer"))+ assert cli._c_live_bearer() == "prompted-bearer"+ with pytest.raises(cli._CLiveCliError, match="idempotency-key"):+ cli._c_live_idempotency_key("not-a-uuid")+ assert cli._c_live_idempotency_key(key) == key++ post = MagicMock(return_value={"status": 200, "body": {}, "idempotency_key": key})+ monkeypatch.setattr(cli, "_c_live_http_post", post)+ asyncio.run(+ cli._run_chain(+ "domain_admin",+ "10.0.0.1",+ "campaign with spaces",+ "CORP.LOCAL",+ "normal",+ False,+ False,+ key,+ )+ )+ post.assert_called_once()+ path, body, supplied_key = post.call_args.args+ assert path == "/campaigns/campaign%20with%20spaces/run"+ assert body["dry_run"] is False+ assert supplied_key == keydiff --git a/tests/unit/test_engine.py b/tests/unit/test_engine.pyindex 949405f..19d3016 100644--- a/tests/unit/test_engine.py+++ b/tests/unit/test_engine.py@@ -5,9 +5,11 @@ Modules used in engine tests are mocked to return instantly.This tests ENGINE behavior (planning, parallelism, semaphore, timeout, retry)not individual module behavior (which is tested in test_modules.py)."""+from __future__ import annotationsimport asyncio+from types import SimpleNamespacefrom typing import Anyfrom unittest.mock import patch, AsyncMock@@ -16,11 +18,23 @@ import pytestfrom ares.core.campaign import Campaign, NoiseProfile, ScopeEntryfrom ares.core.config import AresSettingsfrom ares.core.engine import AresEngine, ExecutionPlan, ModuleStatus+from ares.core.execution_admission import (+ DispatchDispositionV1,+ DispatchOutcomeV1,+ DispatchRequestV1,+ ExecutionAdmissionCoordinatorV1,+ RevalidatedPrincipalV1,+ _mint_test_dispatch_context,+ _mint_test_plan_context,+ canonical_intent_digest,+)from ares.core.notifier import build_notifier_from_settings+from ares.db.execution_lifecycle import FixedResult, OperationResult, TrustedPrincipal# ── Fixtures ──────────────────────────────────────────────────────────────────+@pytest.fixturedef settings() -> AresSettings:return AresSettings(@@ -43,15 +57,25 @@ def campaign() -> Campaign:def _fast_run(**kwargs: Any):"""Instant async mock run — returns no findings, no raw data."""+async def _inner(**kw: Any):return [], {}+return _inner(**kwargs)+def _admitted(engine: AresEngine, campaign: Campaign, module_id: str, ordinal: int = 0):+ return _mint_test_dispatch_context(engine, campaign.id, module_id, ordinal=ordinal)+++def _admitted_plan(engine: AresEngine, campaign: Campaign, plan: ExecutionPlan):+ return _mint_test_plan_context(engine, campaign.id, tuple(plan.all_module_ids()))++# ── Engine Tests ──────────────────────────────────────────────────────────────-class TestAsyncEngine:+class TestAsyncEngine:def test_blank_webhook_url_disables_notifier(self, settings: AresSettings) -> None:"""Blank/whitespace webhook config is disabled, not validated as a URL."""settings.ares_webhook_url = " "@@ -64,12 +88,15 @@ class TestAsyncEngine:build_notifier_from_settings(settings)@pytest.mark.asyncio- async def test_run_module_not_found(- self, settings: AresSettings, campaign: Campaign- ) -> None:+ async def test_run_module_not_found(self, settings: AresSettings, campaign: Campaign) -> None:engine = AresEngine(settings=settings)engine.load_modules()- result = await engine.run_module("nonexistent.module", campaign, {})+ result = await engine.run_module(+ "nonexistent.module",+ campaign,+ {},+ dispatch_context=_admitted(engine, campaign, "nonexistent.module"),+ )assert result.status == ModuleStatus.FAILEDassert "not found" in (result.error or "")@@ -107,6 +134,7 @@ class TestAsyncEngine:campaign,params,actor_role="team_lead",+ dispatch_context=_admitted(engine, campaign, "ad.kerberoast"),)assert result.status == ModuleStatus.DONE@@ -140,6 +168,7 @@ class TestAsyncEngine:campaign,params,actor_role="team_lead",+ dispatch_context=_admitted(engine, campaign, "ad.kerberoast"),)assert result.status == ModuleStatus.FAILED@@ -175,13 +204,16 @@ class TestAsyncEngine:"password": "Passw0rd!","target_user": "sqlsvc",}- with patch.object(KerberoastModule, "execute", classified_timeout), \- patch("ares.core.engine.asyncio.sleep", new=AsyncMock()) as retry_sleep:+ with (+ patch.object(KerberoastModule, "execute", classified_timeout),+ patch("ares.core.engine.asyncio.sleep", new=AsyncMock()) as retry_sleep,+ ):result = await engine.run_module("ad.kerberoast",campaign,params,actor_role="team_lead",+ dispatch_context=_admitted(engine, campaign, "ad.kerberoast"),)assert calls == 1@@ -227,9 +259,16 @@ class TestAsyncEngine:"username": "[email protected]","password": "Passw0rd!",}- with patch.object(ASREPRoastModule, "execute", candidate_failure), \- patch("ares.core.engine.asyncio.sleep", new=AsyncMock()) as retry_sleep:- result = await engine.run_module("ad.asreproast", campaign, params)+ with (+ patch.object(ASREPRoastModule, "execute", candidate_failure),+ patch("ares.core.engine.asyncio.sleep", new=AsyncMock()) as retry_sleep,+ ):+ result = await engine.run_module(+ "ad.asreproast",+ campaign,+ params,+ dispatch_context=_admitted(engine, campaign, "ad.asreproast"),+ )assert calls == 1assert retry_sleep.await_count == 0@@ -271,7 +310,12 @@ class TestAsyncEngine:"use_ldaps": False,}with patch("ares.core.engine.asyncio.sleep", new=AsyncMock()) as retry_sleep:- result = await engine.run_module("ad.enum_users", campaign, params)+ result = await engine.run_module(+ "ad.enum_users",+ campaign,+ params,+ dispatch_context=_admitted(engine, campaign, "ad.enum_users"),+ )assert calls == 1assert retry_sleep.await_count == 0@@ -310,9 +354,16 @@ class TestAsyncEngine:"password": "Passw0rd!","target_user": "sqlsvc",}- with patch.object(KerberoastModule, "execute", classified_clock_skew), \- patch("ares.core.engine.asyncio.sleep", new=AsyncMock()) as retry_sleep:- result = await engine.run_module("ad.kerberoast", campaign, params)+ with (+ patch.object(KerberoastModule, "execute", classified_clock_skew),+ patch("ares.core.engine.asyncio.sleep", new=AsyncMock()) as retry_sleep,+ ):+ result = await engine.run_module(+ "ad.kerberoast",+ campaign,+ params,+ dispatch_context=_admitted(engine, campaign, "ad.kerberoast"),+ )assert calls == 1assert retry_sleep.await_count == 0@@ -352,25 +403,56 @@ class TestAsyncEngine:"password": "Passw0rd!","target_user": "sqlsvc",}- with patch.object(KerberoastModule, "execute", transient_then_classified), \- patch("ares.core.engine.asyncio.sleep", new=AsyncMock()) as retry_sleep:+ with (+ patch.object(KerberoastModule, "execute", transient_then_classified),+ patch("ares.core.engine.asyncio.sleep", new=AsyncMock()) as retry_sleep,+ ):result = await engine.run_module("ad.kerberoast",campaign,params,actor_role="team_lead",+ dispatch_context=_admitted(engine, campaign, "ad.kerberoast"),)- assert calls == 2- assert retry_sleep.await_count == 1+ assert calls == 1+ assert retry_sleep.await_count == 0assert result.outcome == "network_error"- assert "found 2 Kerberoastable candidate account(s)" in result.outcome_message- assert "Kerberos TGS request timed out" in result.outcome_message+ assert "temporary KDC reachability failure" in result.outcome_message++ generic_engine = AresEngine(settings=settings)+ generic_engine.load_modules()+ generic_calls = 0++ async def generic_opaque_failure(self_unused: Any, ctx: Any) -> Any:+ nonlocal generic_calls+ generic_calls += 1+ raise RuntimeError("temporary KDC reachability failure")++ with (+ patch.object(KerberoastModule, "execute", generic_opaque_failure),+ patch("ares.core.engine.asyncio.sleep", new=AsyncMock()) as generic_sleep,+ ):+ generic_result = await generic_engine.run_module(+ "ad.kerberoast",+ campaign,+ params,+ actor_role="team_lead",+ dispatch_context=_admitted(+ generic_engine,+ campaign,+ "ad.kerberoast",+ ),+ )++ assert generic_calls == 1+ assert generic_sleep.await_count == 0+ assert generic_result.status is ModuleStatus.FAILED+ assert generic_result.outcome == "module_error"+ assert "temporary KDC reachability failure" in generic_result.outcome_message@pytest.mark.asyncio- async def test_run_module_timeout(- self, settings: AresSettings, campaign: Campaign- ) -> None:+ async def test_run_module_timeout(self, settings: AresSettings, campaign: Campaign) -> None:engine = AresEngine(settings=settings)engine.load_modules()@@ -381,6 +463,7 @@ class TestAsyncEngine:async def slow_execute(self_unused, ctx):await asyncio.sleep(999)from ares.modules.base import ModuleResult+return ModuleResult(status="success", module_id="linux.container")async def slow_run(self_unused, **kwargs):@@ -390,9 +473,13 @@ class TestAsyncEngine:mid = "linux.container"if mid in engine.registry:cls = engine.registry.get(mid)- with patch.object(cls, "execute", slow_execute), patch.object(cls, "run", slow_run):+ with patch.object(cls, "execute", slow_execute), patch.object(cls, "run", slow_run):result = await engine.run_module(- mid, campaign, {"target": "10.0.0.5"}, timeout_seconds=1+ mid,+ campaign,+ {"target": "10.0.0.5"},+ timeout_seconds=1,+ dispatch_context=_admitted(engine, campaign, mid),)assert result.status == ModuleStatus.TIMEOUT@@ -406,7 +493,7 @@ class TestAsyncEngine:# Mock both modules so test runs in ms, not 20+ seconds on real filesystemfast = AsyncMock(return_value=([], {}))- privesc_cls = engine.registry.get("linux.privesc")+ privesc_cls = engine.registry.get("linux.privesc")container_cls = engine.registry.get("linux.container")patches = []@@ -418,18 +505,19 @@ class TestAsyncEngine:with patches[0] if patches else _noop_ctx():ctx = patches[1] if len(patches) > 1 else _noop_ctx()with ctx:- plan = (ExecutionPlan()- .add_stage("recon", ["linux.privesc", "linux.container"])+ plan = ExecutionPlan().add_stage("recon", ["linux.privesc", "linux.container"])+ results = await engine.run_plan(+ plan,+ campaign,+ timeout_per_module=5,+ dispatch_context=_admitted_plan(engine, campaign, plan),)- results = await engine.run_plan(plan, campaign, timeout_per_module=5)- assert "linux.privesc" in results+ assert "linux.privesc" in resultsassert "linux.container" in results@pytest.mark.asyncio- async def test_plan_progress_callback(- self, settings: AresSettings, campaign: Campaign- ) -> None:+ async def test_plan_progress_callback(self, settings: AresSettings, campaign: Campaign) -> None:"""Progress callback should be called for each module."""engine = AresEngine(settings=settings)engine.load_modules()@@ -446,7 +534,11 @@ class TestAsyncEngine:with ctx:plan = ExecutionPlan().add_stage("test", ["linux.container"])await engine.run_plan(- plan, campaign, on_progress=on_progress, timeout_per_module=5+ plan,+ campaign,+ on_progress=on_progress,+ timeout_per_module=5,+ dispatch_context=_admitted_plan(engine, campaign, plan),)assert len(events) >= 1@@ -459,7 +551,7 @@ class TestAsyncEngine:engine.load_modules()fast = AsyncMock(return_value=([], {}))- privesc_cls = engine.registry.get("linux.privesc")+ privesc_cls = engine.registry.get("linux.privesc")container_cls = engine.registry.get("linux.container")patches = []@@ -471,19 +563,309 @@ class TestAsyncEngine:with patches[0] if patches else _noop_ctx():ctx = patches[1] if len(patches) > 1 else _noop_ctx()with ctx:- plan = ExecutionPlan().add_stage(- "test", ["linux.privesc", "linux.container"]- )+ plan = ExecutionPlan().add_stage("test", ["linux.privesc", "linux.container"])results = await engine.run_plan(- plan, campaign, timeout_per_module=5+ plan,+ campaign,+ timeout_per_module=5,+ dispatch_context=_admitted_plan(engine, campaign, plan),)assert len(results) == 2+ @pytest.mark.asyncio+ async def test_c_live_public_run_module_rejects_unsealed_dispatch(+ self, settings: AresSettings, campaign: Campaign+ ) -> None:+ engine = AresEngine(settings=settings)+ result = await engine.run_module("test.never", campaign, {})+ assert result.status is ModuleStatus.FAILED+ assert "sealed admission context" in (result.error or "")+ assert engine._registry is None++ @pytest.mark.asyncio+ async def test_c_live_public_run_plan_rejects_unsealed_dispatch(+ self, settings: AresSettings, campaign: Campaign+ ) -> None:+ engine = AresEngine(settings=settings)+ plan = ExecutionPlan().add_stage("blocked", ["test.never"])+ results = await engine.run_plan(plan, campaign)+ assert results["test.never"].status is ModuleStatus.FAILED+ assert "sealed plan context" in (results["test.never"].error or "")+ assert engine._registry is None++ @pytest.mark.parametrize(+ "case",+ [+ "fabricated",+ "stale-revision",+ "reused",+ "cross-module",+ "cross-attempt",+ "cross-campaign",+ "cross-submission",+ "cross-store",+ ],+ )+ @pytest.mark.asyncio+ async def test_c_live_sealed_dispatch_context_rejection(+ self,+ case: str,+ settings: AresSettings,+ campaign: Campaign,+ ) -> None:+ engine = AresEngine(settings=settings)+ store_a = SimpleNamespace(+ lifecycle_mutations=[],+ attempt_mutations=[],+ terminal_mutations=[],+ outbox_mutations=[],+ broadcasts=[],+ )+ sealed_module = "ad.c_live_reuse_probe" if case == "reused" else "test.never"+ context = _mint_test_dispatch_context(+ engine,+ campaign.id,+ sealed_module,+ store=store_a,+ )+ if case == "cross-store":+ with pytest.raises(PermissionError, match="different admission store"):+ _mint_test_dispatch_context(+ engine,+ campaign.id,+ "test.never",+ store=object(),+ ordinal=1,+ )+ assert engine._registry is None+ return+ if case == "fabricated":+ candidate: Any = object()+ else:+ candidate = context+ if case == "stale-revision":+ candidate.attempt_revision = 2+ elif case == "cross-attempt":+ candidate.attempt_id = "77777777-7777-4777-8777-777777777777"+ elif case == "cross-submission":+ candidate.submission_id = "88888888-8888-4888-8888-888888888888"++ target_campaign = campaign+ target_module = sealed_module+ if case == "cross-module":+ target_module = "test.other"+ elif case == "cross-campaign":+ target_campaign = Campaign(+ name="other",+ client="ACME",+ scope=[ScopeEntry(cidr="10.0.0.0/8")],+ noise_profile=NoiseProfile.NORMAL,+ )++ if case == "reused":+ from ares.core.plugin.loader import ModuleRegistry+ from ares.modules.base import BaseModule, ModuleResult++ effects: list[str] = []++ class CountingRegistry(ModuleRegistry):+ def __init__(self) -> None:+ super().__init__()+ self.lookups: list[tuple[str, str]] = []++ def __contains__(self, module_id: str) -> bool:+ self.lookups.append(("contains", module_id))+ return super().__contains__(module_id)++ def get(self, module_id: str):+ self.lookups.append(("get", module_id))+ return super().get(module_id)++ class ReuseProbeModule(BaseModule):+ MODULE_ID = "ad.c_live_reuse_probe"+ MODULE_NAME = "C-LIVE reuse probe"+ MODULE_CATEGORY = "ad"+ MODULE_DESCRIPTION = "No-network sealed-context reuse probe"++ async def validate(self, ctx: Any) -> None:+ return None++ async def execute(self, ctx: Any) -> ModuleResult:+ effects.append(context.attempt_id)+ return ModuleResult(status="success", module_id=self.MODULE_ID, raw={})++ registry = CountingRegistry()+ registry.register(ReuseProbeModule)+ engine._registry = registry+ engine.notifier = SimpleNamespace(+ should_notify=lambda _severity: True,+ notify_finding=AsyncMock(),+ )+ first = await engine.run_module(+ target_module,+ target_campaign,+ {},+ dispatch_context=candidate,+ )+ assert first.status is ModuleStatus.DONE+ assert effects == [context.attempt_id]+ assert engine._registry is registry+ registry_identity = id(engine._registry)++ def observable_snapshot() -> tuple[Any, ...]:+ runtime_states = engine._runtime_states._states+ return (+ id(engine._registry),+ len(engine._registry),+ engine._registry._registry.get(target_module) is ReuseProbeModule,+ tuple(registry.lookups),+ tuple(effects),+ tuple(sorted(engine._admitted_dispatch_contexts)),+ engine._admission_store_id,+ tuple(sorted(runtime_states)),+ tuple((key, id(value)) for key, value in sorted(runtime_states.items())),+ tuple(store_a.lifecycle_mutations),+ tuple(store_a.attempt_mutations),+ tuple(store_a.terminal_mutations),+ tuple(store_a.outbox_mutations),+ tuple(store_a.broadcasts),+ engine.notifier.notify_finding.await_count,+ tuple(campaign.findings),+ context._consumed,+ context._effect_started,+ context._terminal_committed,+ context._finalized,+ )++ before_reuse = observable_snapshot()+ rejected = await engine.run_module(+ target_module,+ target_campaign,+ {},+ dispatch_context=candidate,+ )+ assert rejected.status is ModuleStatus.FAILED+ assert (+ rejected.error+ == "dispatch context is stale, transferred, fabricated, or already used"+ )+ assert observable_snapshot() == before_reuse+ assert id(engine._registry) == registry_identity+ assert effects == [context.attempt_id]+ assert context._consumed is True+ assert context._effect_started is True+ return+ rejected = await engine.run_module(+ target_module,+ target_campaign,+ {},+ dispatch_context=candidate,+ )+ assert rejected.status is ModuleStatus.FAILED+ assert engine._registry is None+ if case != "fabricated":+ burned = await engine.run_module(+ "test.never",+ campaign,+ {},+ dispatch_context=context,+ )+ assert "already used" in (burned.error or "") or "fabricated" in (burned.error or "")++ @pytest.mark.asyncio+ async def test_c_live_retry_creates_v3_child_before_redispatch(+ self, settings: AresSettings, campaign: Campaign, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ principal = TrustedPrincipal(+ "99999999-9999-4999-8999-999999999999",+ "99999999-9999-4999-8999-999999999999",+ )+ store = SimpleNamespace(+ create_retry_attempt_v3=AsyncMock(+ return_value=OperationResult(FixedResult.APPLIED, 0)+ )+ )+ engine = AresEngine(settings=settings)++ async def revalidate(*_args: Any):+ return RevalidatedPrincipalV1(principal, 0, "team_lead")++ coordinator = ExecutionAdmissionCoordinatorV1(store, engine, revalidate)+ expected = DispatchOutcomeV1(+ DispatchDispositionV1.TERMINAL,+ None,+ FixedResult.APPLIED,+ 4,+ terminal_committed=True,+ )+ advance = AsyncMock(return_value=expected)+ monkeypatch.setattr(coordinator, "_advance_and_execute", advance)+ request = DispatchRequestV1(+ campaign_id=campaign.id,+ module_id="test.retry",+ ingress_code="api_module",+ idempotency_key="aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa",+ raw_parameters={},+ whole_intent_digest=canonical_intent_digest({"module": "test.retry"}),+ )+ result = await coordinator.retry_module(+ principal,+ request,+ campaign,+ logical_execution_id="bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb",+ parent_attempt_id="cccccccc-cccc-4ccc-8ccc-cccccccccccc",+ expected_parent_revision=4,+ )+ assert result is expected+ store.create_retry_attempt_v3.assert_awaited_once()+ advance.assert_awaited_once()++ @pytest.mark.asyncio+ async def test_c_live_retry_non_applied_child_never_redispatches(+ self, settings: AresSettings, campaign: Campaign, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ principal = TrustedPrincipal(+ "99999999-9999-4999-8999-999999999999",+ "99999999-9999-4999-8999-999999999999",+ )+ store = SimpleNamespace(+ create_retry_attempt_v3=AsyncMock(+ return_value=OperationResult(FixedResult.REPLAYED_BOUND_CHILD, 0)+ )+ )+ engine = AresEngine(settings=settings)++ async def revalidate(*_args: Any):+ return RevalidatedPrincipalV1(principal, 0, "team_lead")++ coordinator = ExecutionAdmissionCoordinatorV1(store, engine, revalidate)+ advance = AsyncMock()+ monkeypatch.setattr(coordinator, "_advance_and_execute", advance)+ request = DispatchRequestV1(+ campaign_id=campaign.id,+ module_id="test.retry",+ ingress_code="api_module",+ idempotency_key="aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa",+ raw_parameters={},+ whole_intent_digest=canonical_intent_digest({"module": "test.retry"}),+ )+ result = await coordinator.retry_module(+ principal,+ request,+ campaign,+ logical_execution_id="bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb",+ parent_attempt_id="cccccccc-cccc-4ccc-8ccc-cccccccccccc",+ expected_parent_revision=4,+ )+ assert result.disposition is DispatchDispositionV1.REPLAYED+ advance.assert_not_awaited()+# ── Helpers ───────────────────────────────────────────────────────────────────from contextlib import contextmanager+@contextmanagerdef _noop_ctx():"""No-op context manager for optional patches."""diff --git a/tests/unit/test_execution_lifecycle_migration.py b/tests/unit/test_execution_lifecycle_migration.pynew file mode 100644index 0000000..ce398f4--- /dev/null+++ b/tests/unit/test_execution_lifecycle_migration.py@@ -0,0 +1,723 @@+"""Real SQLite migration tests for revision 0010."""++from __future__ import annotations++import hashlib+import json+import re+import sqlite3+from types import SimpleNamespace++import pytest+import sqlalchemy as sa+from alembic import command+from alembic.config import Config+from sqlalchemy.engine import Connection++from ares.db.execution_lifecycle import (+ LIFECYCLE_TABLES,+ SQLITE_LIFECYCLE_DDL,+ V11_AUTHORITY_TABLES,+ sqlite_admission_authority_runtime_script,+ validate_sqlite_admission_authority_catalog,+ validate_sqlite_lifecycle_catalog,+)+from ares.db.migrations.adoption import migration_config+from ares.db.schema import CREATE_TABLES++# Independently derived from the handwritten whole-catalog oracle below after+# freezing the revision-0010 P1-B DDL. This does not call the production+# lifecycle validator or expected-fact builder.+_SQLITE_CATALOG_FINGERPRINT_V1 = "087c437f1fb02a37bcdbe9e9312485410c01d0673d587429dbc6c6d34ad22e12"++_P1B_LOGICAL_EXECUTION_COLUMNS = (+ "id",+ "submission_id",+ "campaign_id",+ "actor_subject_ref",+ "actor_user_id",+ "module_id",+ "ingress_code",+ "admission_operation_id",+ "submission_binding_contract_version",+ "submission_request_binding_digest",+ "submission_result_code",+ "submission_exact_replay_code",+ "submission_result_binding_digest",+ "highest_attempt_ordinal",+ "revision",+ "created_at",+ "closure_operation_id",+ "closure_authority_subject_ref",+ "closure_authority_user_id",+ "closure_authority_revision",+ "closing_attempt_id",+ "closed_at",+)++_P1B_RECEIPT_COLUMNS = (+ "operation_id",+ "operation_code",+ "campaign_id",+ "primary_target_id",+ "secondary_target_id",+ "principal_kind",+ "principal_subject_ref",+ "principal_user_id",+ "principal_authority_revision_present",+ "principal_authority_revision",+ "binding_contract_version",+ "request_binding_digest",+ "expected_revision_present",+ "expected_revision",+ "secondary_expected_revision_present",+ "secondary_expected_revision",+ "owner_ref",+ "lease_generation",+ "result_code",+ "exact_replay_code",+ "result_binding_digest",+ "result_identity",+ "result_revision_present",+ "result_revision",+ "secondary_result_identity",+ "secondary_result_revision_present",+ "secondary_result_revision",+ "created_at",+)++_P1B_SQLITE_RECEIPT_TRIGGERS = (+ (+ "trg_eor_immutable_delete",+ "execution_operation_receipts",+ "CREATE TRIGGER trg_eor_immutable_delete BEFORE DELETE "+ "ON execution_operation_receipts BEGIN "+ "SELECT RAISE(ABORT,'immutable execution operation receipt'); END",+ ),+ (+ "trg_eor_immutable_update",+ "execution_operation_receipts",+ "CREATE TRIGGER trg_eor_immutable_update BEFORE UPDATE "+ "ON execution_operation_receipts BEGIN "+ "SELECT RAISE(ABORT,'immutable execution operation receipt'); END",+ ),+)+++def _independent_sqlite_catalog_fingerprint(connection: sqlite3.Connection) -> str:+ rows = connection.execute(+ "SELECT type,name,tbl_name,sql FROM sqlite_schema "+ "WHERE name NOT LIKE 'sqlite_%' ORDER BY type,name"+ ).fetchall()+ normalized = tuple(+ tuple("" if value is None else re.sub(r"\s+", " ", str(value)).strip() for value in row)+ for row in rows+ )+ payload = json.dumps(normalized, ensure_ascii=True, separators=(",", ":"))+ return hashlib.sha256(payload.encode("ascii")).hexdigest()+++def _run(path: str, operation: str, revision: str) -> None:+ with migration_config() as configured:+ config: Config = configured+ config.cmd_opts = SimpleNamespace(x=[f"db_url=sqlite:///{path}"])+ getattr(command, operation)(config, revision)+++def _revision(path: str) -> str:+ connection = sqlite3.connect(path)+ try:+ return str(connection.execute("SELECT version_num FROM alembic_version").fetchone()[0])+ finally:+ connection.close()+++def test_empty_database_upgrades_through_exact_head_0010(tmp_path) -> None:+ path = tmp_path / "managed.db"+ _run(path.as_posix(), "upgrade", "0010")+ connection = sqlite3.connect(path)+ try:+ tables = {+ str(row[0])+ for row in connection.execute("SELECT name FROM sqlite_schema WHERE type='table'")+ }+ gateway = connection.execute("SELECT mode,revision FROM execution_gateway_state").fetchall()+ finally:+ connection.close()+ assert _revision(path.as_posix()) == "0010", "migration head changed"+ assert set(LIFECYCLE_TABLES).issubset(tables), "lifecycle tables missing"+ assert gateway == [("disabled", 0)], "gateway was enabled by migration"+++def test_empty_database_upgrades_through_exact_head_0011(tmp_path) -> None:+ path = tmp_path / "managed.db"+ _run(path.as_posix(), "upgrade", "head")+ connection = sqlite3.connect(path)+ try:+ tables = {+ str(row[0])+ for row in connection.execute("SELECT name FROM sqlite_schema WHERE type='table'")+ }+ gateway = connection.execute("SELECT mode,revision FROM execution_gateway_state").fetchall()+ validate_sqlite_lifecycle_catalog(connection)+ validate_sqlite_admission_authority_catalog(connection)+ finally:+ connection.close()+ assert _revision(path.as_posix()) == "0011", "migration head changed"+ assert set(LIFECYCLE_TABLES).issubset(tables), "lifecycle tables missing"+ assert set(V11_AUTHORITY_TABLES).issubset(tables), "admission-authority tables missing"+ assert gateway == [("disabled", 0)], "gateway was enabled by migration"+++def test_sqlite_catalog_matches_independent_literal_fingerprint(tmp_path) -> None:+ path = tmp_path / "managed.db"+ _run(path.as_posix(), "upgrade", "0010")+ connection = sqlite3.connect(path)+ try:+ observed = _independent_sqlite_catalog_fingerprint(connection)+ index_row = connection.execute(+ "SELECT type,name,tbl_name,sql FROM sqlite_schema "+ "WHERE type='index' AND name='ix_eol_attempt'"+ ).fetchone()+ index_columns = tuple(connection.execute("PRAGMA index_xinfo(ix_eol_attempt)"))+ validate_sqlite_lifecycle_catalog(connection)+ finally:+ connection.close()+ assert observed == _SQLITE_CATALOG_FINGERPRINT_V1, "SQLite whole-catalog fingerprint changed"+ assert tuple(index_row) == (+ "index",+ "ix_eol_attempt",+ "execution_output_links",+ "CREATE INDEX ix_eol_attempt ON execution_output_links(attempt_id)",+ ), "operational attempt index definition changed"+ assert index_columns == (+ (0, 1, "attempt_id", 0, "BINARY", 1),+ (1, -1, None, 0, "BINARY", 0),+ ), "operational attempt index signature changed"+++def test_sqlite_validator_rejects_missing_operational_attempt_index() -> None:+ connection = sqlite3.connect(":memory:")+ try:+ connection.executescript(CREATE_TABLES)+ connection.execute("DROP INDEX ix_eol_attempt")+ with pytest.raises(RuntimeError, match="Incompatible execution lifecycle schema"):+ validate_sqlite_lifecycle_catalog(connection)+ finally:+ connection.close()+++def test_sqlite_validator_rejects_wrong_operational_attempt_index_key() -> None:+ connection = sqlite3.connect(":memory:")+ try:+ connection.executescript(CREATE_TABLES)+ connection.execute("DROP INDEX ix_eol_attempt")+ connection.execute("CREATE INDEX ix_eol_attempt ON execution_output_links(campaign_id)")+ with pytest.raises(RuntimeError, match="Incompatible execution lifecycle schema"):+ validate_sqlite_lifecycle_catalog(connection)+ finally:+ connection.close()++[email protected]("table", LIFECYCLE_TABLES, ids=LIFECYCLE_TABLES)+def test_each_lifecycle_table_is_created_once(tmp_path, table: str) -> None:+ path = tmp_path / "managed.db"+ _run(path.as_posix(), "upgrade", "0010")+ connection = sqlite3.connect(path)+ try:+ count = connection.execute(+ "SELECT count(*) FROM sqlite_schema WHERE type='table' AND name=?",+ (table,),+ ).fetchone()[0]+ finally:+ connection.close()+ assert count == 1, "lifecycle relation count changed"+++def test_attempt_contract_version_columns_are_exact_and_ordered(tmp_path) -> None:+ path = tmp_path / "managed.db"+ _run(path.as_posix(), "upgrade", "0010")+ connection = sqlite3.connect(path)+ try:+ rows = connection.execute("PRAGMA table_info(execution_attempts)").fetchall()+ table_sql = str(+ connection.execute(+ "SELECT sql FROM sqlite_schema WHERE type='table' AND name='execution_attempts'"+ ).fetchone()[0]+ )+ finally:+ connection.close()+ columns = tuple(str(row[1]) for row in rows)+ assert columns.index("policy_contract_version") == (+ columns.index("policy_evaluation_state") + 1+ ), "policy contract column order changed"+ assert {str(row[1]): (str(row[2]), int(row[3])) for row in rows}[+ "request_contract_version"+ ] == ("INTEGER", 1), "request contract type changed"+ assert "request_contract_version=1" in table_sql, "request version check missing"+ assert "policy_contract_version=1" in table_sql, "policy version check missing"+ assert "descriptor_contract_version='ares.module-descriptor.v2'" in table_sql, (+ "descriptor contract check changed"+ )+++def test_p1b_submission_authority_and_receipt_schema_are_exact(tmp_path) -> None:+ path = tmp_path / "managed.db"+ _run(path.as_posix(), "upgrade", "0010")+ connection = sqlite3.connect(path)+ try:+ logical_columns = tuple(+ str(row[1]) for row in connection.execute("PRAGMA table_info(logical_executions)")+ )+ receipt_columns = tuple(+ str(row[1])+ for row in connection.execute("PRAGMA table_info(execution_operation_receipts)")+ )+ receipt_sql = str(+ connection.execute(+ "SELECT sql FROM sqlite_schema "+ "WHERE type='table' AND name='execution_operation_receipts'"+ ).fetchone()[0]+ )+ receipt_foreign_keys = tuple(+ connection.execute("PRAGMA foreign_key_list(execution_operation_receipts)")+ )+ finally:+ connection.close()+ assert logical_columns == _P1B_LOGICAL_EXECUTION_COLUMNS, "submission authority columns changed"+ assert receipt_columns == _P1B_RECEIPT_COLUMNS, "receipt-v2 column order changed"+ assert "binding_contract_version=2" in receipt_sql, "receipt-v2 contract check changed"+ assert "principal_kind IN ('actor','resolver')" in receipt_sql, (+ "receipt actor/resolver principal shape changed"+ )+ assert "principal_kind IN ('worker','system')" in receipt_sql, (+ "receipt worker/system principal shape changed"+ )+ assert "expected_revision_present=1" in receipt_sql, (+ "receipt revision-presence contract changed"+ )+ assert "CONSTRAINT ck_eor_operation_shape" in receipt_sql, (+ "receipt operation-specific revision-presence contract missing"+ )+ assert "CONSTRAINT ck_eor_outbox_owner_shape" in receipt_sql, (+ "receipt outbox owner/generation contract missing"+ )+ assert receipt_foreign_keys == (), "historical receipts gained a target foreign key"+++def test_p1b_sqlite_receipt_immutability_objects_are_exact(tmp_path) -> None:+ path = tmp_path / "managed.db"+ _run(path.as_posix(), "upgrade", "0010")+ connection = sqlite3.connect(path)+ try:+ rows = connection.execute(+ "SELECT name,tbl_name,sql FROM sqlite_schema "+ "WHERE type='trigger' AND tbl_name='execution_operation_receipts' "+ "ORDER BY name"+ ).fetchall()+ finally:+ connection.close()+ observed = tuple(+ (str(name), str(table), re.sub(r"\s+", " ", str(sql)).strip()) for name, table, sql in rows+ )+ assert observed == _P1B_SQLITE_RECEIPT_TRIGGERS, (+ "SQLite receipt immutability trigger allowlist changed"+ )+++def test_sqlite_cyclic_foreign_key_is_inline_and_deferred() -> None:+ logical = SQLITE_LIFECYCLE_DDL[0]+ attempts = SQLITE_LIFECYCLE_DDL[1]+ assert logical.startswith("CREATE TABLE logical_executions"), "logical relation order changed"+ assert attempts.startswith("CREATE TABLE execution_attempts"), "attempt relation order changed"+ assert (+ "FOREIGN KEY (id,closing_attempt_id) "+ "REFERENCES execution_attempts(logical_execution_id,id) "+ "ON UPDATE NO ACTION ON DELETE NO ACTION DEFERRABLE INITIALLY DEFERRED"+ ) in logical, "closing foreign key changed"+++def test_runtime_and_migration_lifecycle_catalogs_match(tmp_path) -> None:+ migration_path = tmp_path / "migration.db"+ runtime_path = tmp_path / "runtime.db"+ _run(migration_path.as_posix(), "upgrade", "0010")+ runtime = sqlite3.connect(runtime_path)+ try:+ generation_11 = sqlite_admission_authority_runtime_script()+ assert CREATE_TABLES.endswith(generation_11), "runtime generation-11 suffix changed"+ runtime.executescript(CREATE_TABLES[: -len(generation_11)])+ finally:+ runtime.close()++ def catalog(path) -> tuple[tuple[str, str, str], ...]:+ connection = sqlite3.connect(path)+ try:+ rows = connection.execute(+ "SELECT type,name,replace(replace(sql,'IF NOT EXISTS ',''),' OR IGNORE','') "+ "FROM sqlite_schema WHERE type IN ('table','index','trigger') "+ "AND (tbl_name IN (?,?,?,?,?,?,?,?,?,?,?) "+ "OR name IN (?,?,?,?,?,?,?,?,?,?,?)) "+ "AND sql IS NOT NULL ORDER BY type,name",+ (*LIFECYCLE_TABLES, *LIFECYCLE_TABLES),+ ).fetchall()+ return tuple((str(row[0]), str(row[1]), str(row[2])) for row in rows)+ finally:+ connection.close()++ assert catalog(migration_path) == catalog(runtime_path), (+ "runtime and migration lifecycle catalogs differ"+ )+++_SQLITE_CATALOG_DRIFTS = (+ (+ "logical-type",+ "logical_executions",+ "actor_subject_ref TEXT NOT NULL",+ "actor_subject_ref INTEGER NOT NULL",+ ),+ ("logical-null", "logical_executions", "actor_user_id TEXT,", "actor_user_id TEXT NOT NULL,"),+ (+ "logical-default",+ "logical_executions",+ "revision INTEGER NOT NULL DEFAULT 0",+ "revision INTEGER NOT NULL DEFAULT 1",+ ),+ (+ "logical-unique-order",+ "logical_executions",+ "UNIQUE (campaign_id,id)",+ "UNIQUE (id,campaign_id)",+ ),+ (+ "logical-fk-action",+ "logical_executions",+ "ON UPDATE NO ACTION ON DELETE NO ACTION",+ "ON UPDATE CASCADE ON DELETE NO ACTION",+ ),+ (+ "logical-fk-deferral",+ "logical_executions",+ "DEFERRABLE INITIALLY DEFERRED",+ "DEFERRABLE INITIALLY IMMEDIATE",+ ),+ (+ "attempt-check",+ "execution_attempts",+ "request_contract_version=1",+ "request_contract_version IN (1,2)",+ ),+ (+ "attempt-column-order",+ "execution_attempts",+ "policy_evaluation_state TEXT NOT NULL,\n policy_contract_version INTEGER NOT NULL",+ "policy_contract_version INTEGER NOT NULL,\n policy_evaluation_state TEXT NOT NULL",+ ),+ (+ "receipt-contract",+ "execution_operation_receipts",+ "binding_contract_version=2",+ "binding_contract_version IN (1,2)",+ ),+ (+ "submission-contract",+ "logical_executions",+ "submission_binding_contract_version=2",+ "submission_binding_contract_version IN (1,3)",+ ),+ (+ "receipt-trigger-action",+ "trg_eor_immutable_update",+ "BEFORE UPDATE",+ "AFTER UPDATE",+ ),+ (+ "receipt-result-null",+ "execution_operation_receipts",+ "result_binding_digest TEXT NOT NULL",+ "result_binding_digest TEXT",+ ),+ (+ "outbox-count-check",+ "execution_publication_outbox",+ "finding_count BETWEEN 0 AND 9007199254740991",+ "finding_count>=0",+ ),+ ("gateway-mode", "execution_gateway_state", "'emergency_disabled'", "'compatibility_enabled'"),+ (+ "index-order",+ "ix_ea_logical_state",+ "logical_execution_id,state,ordinal",+ "ordinal,state,logical_execution_id",+ ),+ (+ "index-predicate",+ "uq_ea_one_child",+ "WHERE parent_attempt_id IS NOT NULL",+ "WHERE parent_attempt_id IS NULL",+ ),+)+++ ("_case", "object_name", "old", "new"),+ _SQLITE_CATALOG_DRIFTS,+ ids=tuple(case[0] for case in _SQLITE_CATALOG_DRIFTS),+)+def test_sqlite_validator_rejects_each_literal_catalog_drift(+ _case: str, object_name: str, old: str, new: str+) -> None:+ connection = sqlite3.connect(":memory:")+ try:+ connection.execute("PRAGMA foreign_keys=ON")+ connection.executescript(CREATE_TABLES)+ connection.execute("PRAGMA writable_schema=ON")+ cursor = connection.execute(+ "UPDATE sqlite_schema SET sql=replace(sql,?,?) WHERE name=? AND instr(sql,?)>0",+ (old, new, object_name, old),+ )+ connection.execute("PRAGMA writable_schema=OFF")+ assert cursor.rowcount == 1, "catalog mutation did not apply"+ with pytest.raises(RuntimeError, match="Incompatible execution lifecycle schema"):+ validate_sqlite_lifecycle_catalog(connection)+ finally:+ connection.close()+++def test_revision_0010_downgrade_refuses_before_mutation(tmp_path) -> None:+ path = tmp_path / "managed.db"+ _run(path.as_posix(), "upgrade", "0010")+ connection = sqlite3.connect(path)+ try:+ before = tuple(+ connection.execute(+ "SELECT type,name,coalesce(sql,'') FROM sqlite_schema ORDER BY type,name"+ ).fetchall()+ )+ finally:+ connection.close()+ with pytest.raises(RuntimeError, match="revision-0010 downgrade is not supported"):+ _run(path.as_posix(), "downgrade", "0009")+ connection = sqlite3.connect(path)+ try:+ after = tuple(+ connection.execute(+ "SELECT type,name,coalesce(sql,'') FROM sqlite_schema ORDER BY type,name"+ ).fetchall()+ )+ finally:+ connection.close()+ assert before == after, "downgrade refusal mutated the catalog"+ assert _revision(path.as_posix()) == "0010", "downgrade changed revision"++[email protected]("_case", ["empty", "v2-populated"], ids=("empty", "v2-populated"))+def test_revision_0011_upgrades_supported_0010_catalog(tmp_path, _case: str) -> None:+ path = tmp_path / f"supported-{_case}.db"+ _run(path.as_posix(), "upgrade", "0010")+ actor_id = "00000000-0000-4000-8000-000000001101"+ campaign_id = "00000000-0000-4000-8000-000000001102"+ if _case == "v2-populated":+ connection = sqlite3.connect(path)+ try:+ connection.execute("PRAGMA foreign_keys=ON")+ connection.execute(+ "INSERT INTO users(id,username,hashed_password,role,created_by) VALUES(?,?,?,?,?)",+ (actor_id, "migration-owner", "fixed", "admin", "fixed"),+ )+ connection.execute(+ "INSERT INTO campaigns(id,name,operator,scope_json,targets_json) VALUES(?,?,?,?,?)",+ (+ campaign_id,+ "migration-campaign",+ "migration-owner",+ '[{"cidr":"10.11.0.0/24"}]',+ '["Host.Example."]',+ ),+ )+ connection.execute(+ "INSERT INTO execution_actor_authority_revisions("+ "user_id,latest_operation_id,latest_operation_code) VALUES(?,?,'ensure')",+ (actor_id, "00000000-0000-4000-8000-000000001103"),+ )+ connection.execute(+ "INSERT INTO campaign_execution_authority_revisions("+ "campaign_id,latest_operation_id,latest_operation_code) VALUES(?,?,'ensure')",+ (campaign_id, "00000000-0000-4000-8000-000000001104"),+ )+ connection.execute(+ "INSERT INTO credentials(id,campaign_id,username,cred_type,source_module) "+ "VALUES(?,?,?,?,?)",+ (+ "00000000-0000-4000-8000-000000001105",+ campaign_id,+ "opaque-user",+ "cleartext",+ "migration-fixture",+ ),+ )+ connection.commit()+ finally:+ connection.close()++ _run(path.as_posix(), "upgrade", "0011")+ connection = sqlite3.connect(path)+ try:+ validate_sqlite_admission_authority_catalog(connection)+ counts = tuple(+ int(+ connection.execute(+ f"SELECT count(*) FROM {table}" # noqa: S608 - frozen table tuple.+ ).fetchone()[0]+ )+ for table in V11_AUTHORITY_TABLES+ )+ if _case == "v2-populated":+ grant = connection.execute(+ "SELECT authority_state,revision FROM campaign_execution_actor_grants "+ "WHERE campaign_id=? AND actor_user_id=?",+ (campaign_id, actor_id),+ ).fetchone()+ destination = connection.execute(+ "SELECT authority_state,revision,normalization_version,destination_count "+ "FROM campaign_execution_destination_authorities WHERE campaign_id=?",+ (campaign_id,),+ ).fetchone()+ credential = connection.execute(+ "SELECT execution_authority_state,execution_authority_revision,"+ "execution_authority_binding_digest FROM credentials WHERE campaign_id=?",+ (campaign_id,),+ ).fetchone()+ finally:+ connection.close()+ assert _revision(path.as_posix()) == "0011", "supported upgrade missed revision 0011"+ if _case == "empty":+ assert counts == (0,) * len(V11_AUTHORITY_TABLES), "empty upgrade fabricated authority"+ else:+ assert counts == (1, 1, 0, 0, 0), "v2 authority backfill cardinality changed"+ assert tuple(grant) == ("active", 0), "compatibility campaign grant changed"+ assert tuple(destination) == ("active", 0, 1, 2), "destination backfill changed"+ assert tuple(credential[:2]) == ("active", 0), "credential authority backfill changed"+ assert re.fullmatch(r"[0-9a-f]{64}", str(credential[2])), (+ "credential binding backfill changed"+ )+++def test_revision_0011_downgrade_refuses_before_mutation(tmp_path) -> None:+ path = tmp_path / "managed.db"+ _run(path.as_posix(), "upgrade", "head")+ connection = sqlite3.connect(path)+ try:+ connection.execute(+ "INSERT INTO users(id,username,hashed_password,role,created_by) VALUES(?,?,?,?,?)",+ (+ "00000000-0000-4000-8000-000000001111",+ "downgrade-owner",+ "fixed",+ "admin",+ "fixed",+ ),+ )+ connection.execute(+ "INSERT INTO execution_actor_authority_revisions("+ "user_id,latest_operation_id,latest_operation_code,authority_revision) "+ "VALUES(?,?,'ensure',1)",+ (+ "00000000-0000-4000-8000-000000001111",+ "00000000-0000-4000-8000-000000001112",+ ),+ )+ connection.commit()+ before = tuple(+ connection.execute(+ "SELECT type,name,coalesce(sql,'') FROM sqlite_schema ORDER BY type,name"+ ).fetchall()+ )+ finally:+ connection.close()+ with pytest.raises(RuntimeError, match="revision-0011 preflight failed"):+ _run(path.as_posix(), "downgrade", "0010")+ connection = sqlite3.connect(path)+ try:+ after = tuple(+ connection.execute(+ "SELECT type,name,coalesce(sql,'') FROM sqlite_schema ORDER BY type,name"+ ).fetchall()+ )+ validate_sqlite_admission_authority_catalog(connection)+ finally:+ connection.close()+ assert before == after, "revision-0011 downgrade refusal mutated catalog"+ assert _revision(path.as_posix()) == "0011", "revision-0011 downgrade changed revision"+++def test_revision_0011_failed_upgrade_rolls_back_and_retry_succeeds(tmp_path, monkeypatch) -> None:+ path = tmp_path / "managed.db"+ _run(path.as_posix(), "upgrade", "0010")+ original_execute = Connection.execute++ def fail_after_catalog_mutation(self, statement, *args, **kwargs):+ result = original_execute(self, statement, *args, **kwargs)+ if (+ str(statement)+ .lstrip()+ .startswith("CREATE TABLE execution_attempt_credential_observations")+ ):+ raise RuntimeError("injected revision-0011 failure")+ return result++ monkeypatch.setattr(Connection, "execute", fail_after_catalog_mutation)+ engine = sa.create_engine(f"sqlite:///{path}")+ try:+ with engine.connect() as migration_connection:+ migration_connection.exec_driver_sql("PRAGMA foreign_keys=ON")+ migration_connection.commit()+ migration_connection.exec_driver_sql("BEGIN IMMEDIATE")+ with pytest.raises(RuntimeError, match="injected revision-0011 failure"):+ with migration_config(migration_connection) as config:+ command.upgrade(config, "0011")+ if migration_connection.in_transaction():+ migration_connection.rollback()+ finally:+ engine.dispose()+ connection = sqlite3.connect(path)+ try:+ tables_after_failure = {+ str(row[0])+ for row in connection.execute("SELECT name FROM sqlite_schema WHERE type='table'")+ }+ validate_sqlite_lifecycle_catalog(connection)+ finally:+ connection.close()+ assert _revision(path.as_posix()) == "0010", "failed upgrade advanced revision"+ assert set(V11_AUTHORITY_TABLES).isdisjoint(tables_after_failure), (+ "failed upgrade left generation-11 relations"+ )++ monkeypatch.setattr(Connection, "execute", original_execute)+ _run(path.as_posix(), "upgrade", "0011")+ connection = sqlite3.connect(path)+ try:+ validate_sqlite_admission_authority_catalog(connection)+ finally:+ connection.close()+ assert _revision(path.as_posix()) == "0011", "retry did not reach revision 0011"+++def test_migration_seeds_no_authority_budget_attempt_or_outbox_rows(tmp_path) -> None:+ path = tmp_path / "managed.db"+ _run(path.as_posix(), "upgrade", "0010")+ connection = sqlite3.connect(path)+ try:+ counts = tuple(+ int(+ connection.execute(+ f"SELECT count(*) FROM {table}" # noqa: S608 - fixed names+ ).fetchone()[0]+ )+ for table in LIFECYCLE_TABLES+ if table != "execution_gateway_state"+ )+ finally:+ connection.close()+ assert counts == (0,) * 10, "migration seeded lifecycle authority"diff --git a/tests/unit/test_execution_lifecycle_persistence.py b/tests/unit/test_execution_lifecycle_persistence.pynew file mode 100644index 0000000..61443c3--- /dev/null+++ b/tests/unit/test_execution_lifecycle_persistence.py@@ -0,0 +1,6833 @@+"""Deterministic SQLite contract tests for revision-0010 lifecycle storage."""++from __future__ import annotations++import asyncio+import hashlib+import sqlite3+import struct+from collections.abc import AsyncIterator+from contextlib import asynccontextmanager+from dataclasses import MISSING, FrozenInstanceError, fields, is_dataclass, replace+from typing import Any, get_type_hints++import aiosqlite+import pytest++import ares.modules.descriptors as descriptor_module+from ares.core.capabilities import Capability+from ares.db.database import AresDatabase+from ares.db.execution_lifecycle import (+ ACTOR_ROLES,+ CAPABILITY_BITS_V1,+ DESCRIPTOR_BLOCKER_BITS_V1,+ LIFECYCLE_TABLES,+ MAX_I53,+ OUTBOX_LEASE_MS,+ SYSTEM_PRINCIPAL_SUBJECT_REF,+ ActorAuthorityMutation,+ AdmissionIntentV3,+ AdmissionRequest,+ ApprovalAuthorityGrant,+ ApprovalAuthorityMutation,+ AttemptPolicySnapshot,+ AttemptState,+ BudgetConfiguration,+ BudgetReservation,+ BudgetSettlement,+ CampaignActorGrantMutation,+ CampaignAuthorityMutation,+ ClosureRequest,+ CredentialAuthorityMutation,+ DestinationAuthorityMutation,+ ExecutionLifecycleStore,+ FixedResult,+ GatewayAuthorityMutation,+ OperationResult,+ OutboxMutation,+ OutcomeCode,+ OutputKind,+ OutputObservation,+ PolicyReasonBit,+ RetryIntentV3,+ RetryRequest,+ TerminalCommitIntentV3,+ TerminalCommitRequest,+ TransitionRequest,+ TrustedPrincipal,+ _AbortOperationError,+ canonical_operation_binding_digest,+ retry_delay_ms,+ valid_uuid,+ validate_sqlite_lifecycle_catalog,+)+from ares.db.schema import CREATE_TABLES, SCHEMA_VERSION+from ares.modules.descriptors import (+ CancellationOwnership,+ CompensationClass,+ ContractState,+ DestinationCardinality,+ DestinationKind,+ DestinationSpec,+ ExternalEffectClass,+ IdempotencyClass,+ MinimumRole,+ ModuleDescriptor,+ OpsecClassification,+ ResultContract,+ RetryEligibility,+ ScopeSemantics,+ TimeoutPolicy,+ TimeoutSettlement,+)++_UUIDS = (+ "00000000-0000-4000-8000-000000000001",+ "00000000-0000-4000-8000-000000000002",+ "00000000-0000-4000-8000-000000000003",+ "00000000-0000-4000-8000-000000000004",+ "00000000-0000-4000-8000-000000000005",+ "00000000-0000-4000-8000-000000000006",+ "00000000-0000-4000-8000-000000000007",+ "00000000-0000-4000-8000-000000000008",+)++_STATE_VALUES = (+ "rejected",+ "blocked",+ "accepted",+ "queued",+ "dispatching",+ "running",+ "cancelling",+ "settlement_pending",+ "succeeded",+ "partial",+ "failed",+ "skipped",+ "cancelled",+ "timed_out",+ "indeterminate",+)++_EXPECTED_LEGAL = frozenset(+ {+ ("accepted", "queued"),+ ("accepted", "dispatching"),+ ("accepted", "cancelling"),+ ("accepted", "skipped"),+ ("accepted", "failed"),+ ("queued", "dispatching"),+ ("queued", "cancelling"),+ ("queued", "skipped"),+ ("queued", "failed"),+ ("dispatching", "running"),+ ("dispatching", "cancelling"),+ ("dispatching", "failed"),+ ("dispatching", "settlement_pending"),+ ("running", "cancelling"),+ ("running", "succeeded"),+ ("running", "partial"),+ ("running", "failed"),+ ("running", "timed_out"),+ ("running", "settlement_pending"),+ ("cancelling", "succeeded"),+ ("cancelling", "partial"),+ ("cancelling", "failed"),+ ("cancelling", "cancelled"),+ ("cancelling", "timed_out"),+ ("cancelling", "settlement_pending"),+ ("settlement_pending", "succeeded"),+ ("settlement_pending", "partial"),+ ("settlement_pending", "failed"),+ ("settlement_pending", "cancelled"),+ ("settlement_pending", "timed_out"),+ ("settlement_pending", "indeterminate"),+ }+)++_ALL_ORDERED_PAIRS = tuple((source, target) for source in _STATE_VALUES for target in _STATE_VALUES)+_ILLEGAL = tuple(pair for pair in _ALL_ORDERED_PAIRS if pair not in _EXPECTED_LEGAL)+++ ("source", "target"),+ tuple(sorted(_EXPECTED_LEGAL)),+ ids=lambda value: value,+)+async def test_each_legal_transition_is_frozen(tmp_path, source: str, target: str) -> None:+ result, before, after, observer = await _exercise_transition_pair(+ tmp_path / f"legal-{source}-{target}.db", source, target+ )+ assert result is FixedResult.APPLIED, "legal persistence transition failed"+ assert after != before, "legal persistence transition did not mutate"+ assert observer == after, "legal transition was not durably observable"+++ ("source", "target"),+ _ILLEGAL,+ ids=lambda value: value,+)+async def test_each_illegal_transition_is_rejected(tmp_path, source: str, target: str) -> None:+ result, before, after, observer = await _exercise_transition_pair(+ tmp_path / f"illegal-{source}-{target}.db", source, target+ )+ assert result is not FixedResult.APPLIED, "illegal persistence transition applied"+ assert after == before, "illegal persistence transition mutated state"+ assert observer == before, "illegal transition leaked a committed mutation"+++def test_transition_matrix_has_exact_recomputed_totals() -> None:+ assert len(_EXPECTED_LEGAL) == 31, "legal transition total changed"+ assert len(_ILLEGAL) == 194, "illegal transition total changed"+ assert len(_ALL_ORDERED_PAIRS) == 225, "state matrix total changed"+++def test_self_transitions_are_never_legal() -> None:+ assert all((state, state) in _ILLEGAL for state in _STATE_VALUES), "self transition accepted"+++def test_runtime_catalog_has_exact_eleven_tables_and_disabled_gateway() -> None:+ connection = sqlite3.connect(":memory:")+ try:+ connection.execute("PRAGMA foreign_keys=ON")+ connection.executescript(CREATE_TABLES)+ validate_sqlite_lifecycle_catalog(connection)+ rows = connection.execute(+ "SELECT name FROM sqlite_schema WHERE type='table' "+ "AND name IN (?,?,?,?,?,?,?,?,?,?,?) ORDER BY name",+ LIFECYCLE_TABLES,+ ).fetchall()+ gateway = connection.execute(+ "SELECT mode,revision,catalog_digest,activation_revision,activation_at "+ "FROM execution_gateway_state"+ ).fetchall()+ finally:+ connection.close()+ assert tuple(row[0] for row in rows) == tuple(sorted(LIFECYCLE_TABLES)), (+ "lifecycle table inventory changed"+ )+ assert gateway == [("disabled", 0, None, None, None)], "gateway bootstrap changed"+ assert SCHEMA_VERSION == 9, "legacy schema marker changed"+++def _independent_binding_digest(+ domain: str, values: tuple[tuple[str, str | int | bool | None], ...]+) -> str:+ import struct++ encoded = bytearray(b"ares.execution-operation-binding.v2\x00")++ def frame(value: bytes) -> None:+ encoded.extend(struct.pack(">I", len(value)))+ encoded.extend(value)++ frame(domain.encode("ascii"))+ for name, value in values:+ frame(name.encode("ascii"))+ if value is None:+ encoded.extend(b"n")+ elif type(value) is bool:+ encoded.extend(b"b\x01" if value else b"b\x00")+ elif type(value) is int:+ encoded.extend(b"i")+ frame(value.to_bytes(8, "big"))+ else:+ encoded.extend(b"s")+ frame(value.encode("utf-8"))+ return hashlib.sha256(encoded).hexdigest()+++def test_operation_binding_uses_independent_typed_length_framing() -> None:+ fields = (("alpha", "value"), ("beta", 7), ("gamma", True), ("delta", None))+ expected = "ef0eb625d5c662f1f1b30a1e72facc1871aa242627ccd7756f706eecc4b6401d"+ assert _independent_binding_digest("test.operation", fields) == expected, (+ "independent operation binding oracle changed"+ )+ assert canonical_operation_binding_digest("test.operation", fields) == expected, (+ "operation binding canonicalization changed"+ )+++async def test_authority_receipt_replay_is_stable_after_later_revision() -> None:+ connection = await _new_connection()+ try:+ await connection.executemany(+ "INSERT INTO users(id,username,hashed_password,role,created_by) VALUES(?,?,?,?,?)",+ (+ (_uuid(900), "receipt-a", "fixed-hash", "admin", "fixed"),+ (_uuid(901), "receipt-b", "fixed-hash", "admin", "fixed"),+ ),+ )+ await connection.commit()+ store = ExecutionLifecycleStore(connection, "sqlite")+ applied = await store.ensure_actor_authority(_uuid(900), _uuid(902))+ replayed = await store.ensure_actor_authority(_uuid(900), _uuid(902))+ conflicted = await store.ensure_actor_authority(_uuid(901), _uuid(902))+ invalidated = await store.invalidate_actor_authority(_uuid(900), 0, _uuid(903))+ replayed_after_revision = await store.ensure_actor_authority(_uuid(900), _uuid(902))+ counts = await (+ await connection.execute(+ "SELECT (SELECT count(*) FROM execution_actor_authority_revisions),"+ "(SELECT count(*) FROM execution_operation_receipts)"+ )+ ).fetchone()+ finally:+ await connection.close()+ assert (+ applied.result,+ replayed.result,+ conflicted.result,+ invalidated.result,+ replayed_after_revision.result,+ ) == (+ FixedResult.APPLIED,+ FixedResult.REPLAYED,+ FixedResult.CONFLICT_OPERATION,+ FixedResult.APPLIED,+ FixedResult.REPLAYED,+ ), "authority receipt classification changed"+ assert tuple(counts) == (1, 2), "authority receipt cardinality changed"+++async def test_receipt_failure_rolls_back_domain_mutation(monkeypatch) -> None:+ connection = await _new_connection()+ try:+ await connection.execute(+ "INSERT INTO users(id,username,hashed_password,role,created_by) VALUES(?,?,?,?,?)",+ (_uuid(910), "receipt-rollback", "fixed-hash", "admin", "fixed"),+ )+ await connection.commit()+ store = ExecutionLifecycleStore(connection, "sqlite")++ async def fail_receipt(*_args, **_kwargs) -> None:+ raise RuntimeError("fixed-receipt-failure")++ monkeypatch.setattr(store, "_insert_receipt", fail_receipt)+ with pytest.raises(RuntimeError, match="fixed-receipt-failure"):+ await store.ensure_actor_authority(_uuid(910), _uuid(911))+ counts = await (+ await connection.execute(+ "SELECT (SELECT count(*) FROM execution_actor_authority_revisions),"+ "(SELECT count(*) FROM execution_operation_receipts)"+ )+ ).fetchone()+ finally:+ await connection.close()+ assert tuple(counts) == (0, 0), "receipt failure split the atomic mutation"+++async def test_forced_zero_row_cas_never_reports_applied(monkeypatch) -> None:+ connection = await _new_connection()+ try:+ await connection.execute(+ "INSERT INTO users(id,username,hashed_password,role,created_by) VALUES(?,?,?,?,?)",+ (_uuid(920), "zero-row", "fixed-hash", "admin", "fixed"),+ )+ await connection.commit()+ store = ExecutionLifecycleStore(connection, "sqlite")+ assert (+ await store.ensure_actor_authority(_uuid(920), _uuid(921))+ ).result is FixedResult.APPLIED, "zero-row authority setup failed"++ async def zero_rows(*_args, **_kwargs):+ return ()++ monkeypatch.setattr(store, "_returning_rows", zero_rows)+ result = await store.invalidate_actor_authority(_uuid(920), 0, _uuid(922))+ row = await (+ await connection.execute(+ "SELECT revision FROM execution_actor_authority_revisions WHERE user_id=?",+ (_uuid(920),),+ )+ ).fetchone()+ finally:+ await connection.close()+ assert result.result is FixedResult.CONFLICT_REVISION, "zero-row CAS reported success"+ assert int(row[0]) == 0, "zero-row CAS mutated authority"+++async def test_unexpected_returning_set_rolls_back_and_fails_fixed(monkeypatch) -> None:+ connection = await _new_connection()+ try:+ await connection.execute(+ "INSERT INTO users(id,username,hashed_password,role,created_by) VALUES(?,?,?,?,?)",+ (_uuid(930), "returning-set", "fixed-hash", "admin", "fixed"),+ )+ await connection.commit()+ store = ExecutionLifecycleStore(connection, "sqlite")+ assert (+ await store.ensure_actor_authority(_uuid(930), _uuid(931))+ ).result is FixedResult.APPLIED, "returning-set authority setup failed"+ original = store._returning_rows++ async def duplicate_rows(*args, **kwargs):+ rows = await original(*args, **kwargs)+ return rows + rows++ monkeypatch.setattr(store, "_returning_rows", duplicate_rows)+ result = await store.invalidate_actor_authority(_uuid(930), 0, _uuid(932))+ row = await (+ await connection.execute(+ "SELECT revision FROM execution_actor_authority_revisions WHERE user_id=?",+ (_uuid(930),),+ )+ ).fetchone()+ receipt = await (+ await connection.execute(+ "SELECT count(*) FROM execution_operation_receipts WHERE operation_id=?",+ (_uuid(932),),+ )+ ).fetchone()+ finally:+ await connection.close()+ assert result.result is FixedResult.INVARIANT_FAILURE, "returned-set mismatch was accepted"+ assert (int(row[0]), int(receipt[0])) == (0, 0), "returned-set mismatch split atomic state"+++ ("value", "accepted"),+ [+ ("00000000-0000-4000-8000-000000000001", True),+ ("00000000-0000-5000-8000-000000000001", False),+ ("00000000-0000-4000-7000-000000000001", False),+ ("00000000-0000-4000-8000-00000000000A", False),+ (True, False),+ (1, False),+ (None, False),+ ],+ ids=("valid", "wrong-version", "wrong-variant", "uppercase", "bool", "int", "none"),+)+def test_uuid_contract_is_exact(value: object, accepted: bool) -> None:+ assert valid_uuid(value) is accepted, "UUID contract changed"+++def test_stable_mask_allocations_are_literal() -> None:+ assert CAPABILITY_BITS_V1 == {+ "network": 1,+ "execution": 2,+ "filesystem": 4,+ "process": 8,+ }, "capability allocation changed"+ assert DESCRIPTOR_BLOCKER_BITS_V1 == {+ "ambient_credentials_forbidden": 1,+ "cancellation_ownership_unproven": 2,+ "dynamic_destination_unbounded": 4,+ "default_factory_unevaluated": 8,+ "llm_egress_policy_required": 16,+ "lifecycle_contract_unproven": 32,+ "raw_credential_input": 64,+ "result_authority_unproven": 128,+ "sensitive_nonempty_default": 256,+ }, "descriptor blocker allocation changed"+ assert {member.name: member.value for member in PolicyReasonBit} == {+ "INVALID_CONTRACT": 1,+ "INCONSISTENT_CONTRACT": 2,+ "INVALID_REQUEST": 4,+ "DESCRIPTOR_UNTRUSTED": 8,+ "DESCRIPTOR_BINDING_INVALID": 16,+ "DESCRIPTOR_INCOMPLETE": 32,+ "STATIC_POLICY_UNAVAILABLE": 64,+ "AUTHORITY_RESOLUTION_REQUIRED": 128,+ "STALE_AUTHORITY": 256,+ "ACTOR_UNAUTHENTICATED": 512,+ "ACTOR_INACTIVE": 1_024,+ "CAMPAIGN_INACTIVE": 2_048,+ "CAMPAIGN_UNAUTHORIZED": 4_096,+ "INSUFFICIENT_ROLE": 8_192,+ "HIGH_NOISE_ROLE_REQUIRED": 16_384,+ "APPROVAL_REQUIRED": 32_768,+ "APPROVAL_STALE": 65_536,+ "APPROVAL_BINDING_INVALID": 131_072,+ "CAPABILITY_REQUIRED": 262_144,+ "DESTINATION_RESOLUTION_REQUIRED": 524_288,+ "DESTINATION_OUT_OF_SCOPE": 1_048_576,+ "CREDENTIAL_AUTHORITY_REQUIRED": 2_097_152,+ "CREDENTIAL_AUTHORITY_STALE": 4_194_304,+ "RAW_CREDENTIAL_FORBIDDEN": 8_388_608,+ "AMBIENT_CREDENTIAL_FORBIDDEN": 16_777_216,+ "CREDENTIAL_HANDLE_POLICY_VIOLATION": 33_554_432,+ "BUDGET_AUTHORITY_REQUIRED": 67_108_864,+ "BUDGET_AUTHORITY_STALE": 134_217_728,+ "BUDGET_CAPACITY_UNAVAILABLE": 268_435_456,+ "DESCRIPTOR_BLOCKED": 536_870_912,+ "PREVIEW_NOT_READY": 1_073_741_824,+ "LIFECYCLE_NOT_READY": 2_147_483_648,+ "RESULT_AUTHORITY_NOT_READY": 4_294_967_296,+ "TRANSPORT_NOT_READY": 8_589_934_592,+ "FUTURE_GATEWAY_INELIGIBLE": 17_179_869_184,+ }, "policy reason allocation changed"+++ ("actor", "minimum", "satisfies"),+ tuple(+ (actor, minimum, actor_rank >= minimum_rank and actor != "reporter")+ for actor, actor_rank in (("reporter", 0), ("operator", 1), ("team_lead", 2), ("admin", 3))+ for minimum, minimum_rank in (("operator", 1), ("team_lead", 2), ("admin", 3))+ ),+ ids=lambda value: value,+)+async def test_every_actor_minimum_role_pair(actor: str, minimum: str, satisfies: bool) -> None:+ persisted_state, result = await _persist_role_cell(actor, minimum, satisfies)+ assert result is FixedResult.APPLIED, "role admission did not commit"+ assert persisted_state == ("accepted" if satisfies else "blocked"), (+ "role admission state changed"+ )+ assert actor in ACTOR_ROLES, "actor role domain changed"+++ ("attempt", "delay"),+ tuple((attempt, min((1 << (attempt - 1)) * 1_000, 600_000)) for attempt in range(1, 20)),+ ids=lambda value: str(value),+)+def test_each_retry_delay_is_bounded(attempt: int, delay: int) -> None:+ assert retry_delay_ms(attempt) == delay, "outbox retry delay changed"+++def test_public_operation_records_are_immutable_and_unhashable() -> None:+ request = TransitionRequest(+ _UUIDS[0],+ 0,+ AttemptState.QUEUED,+ _UUIDS[1],+ campaign_id=_UUIDS[2],+ actor_subject_ref=_UUIDS[3],+ actor_user_id=_UUIDS[3],+ actor_authority_revision=0,+ )+ mutation = OutboxMutation(+ _UUIDS[2],+ 0,+ _UUIDS[3],+ _UUIDS[4],+ 0,+ _UUIDS[5],+ _UUIDS[6],+ _UUIDS[7],+ "execution_failed",+ )+ assert request.__hash__ is None, "transition request became hashable"+ assert mutation.__hash__ is None, "outbox mutation became hashable"+ assert tuple(field.name for field in fields(request)) == (+ "attempt_id",+ "expected_revision",+ "target_state",+ "operation_id",+ "owner_ref",+ "lease_generation",+ "lease_duration_ms",+ "cancellation_request_revision",+ "outcome_code",+ "authoritative_proof",+ "resolver_subject_ref",+ "resolver_user_id",+ "resolver_authority_revision",+ "outbox_id",+ "publication_key",+ "campaign_id",+ "actor_subject_ref",+ "actor_user_id",+ "actor_authority_revision",+ ), "transition request shape changed"+++async def _new_connection(path: str = ":memory:") -> aiosqlite.Connection:+ connection = await aiosqlite.connect(path)+ connection.row_factory = aiosqlite.Row+ await connection.execute("PRAGMA foreign_keys=ON")+ await connection.executescript(CREATE_TABLES)+ return connection+++def _uuid(number: int) -> str:+ return f"00000000-0000-4000-8000-{number:012x}"+++_P1C_AUTHORITY_MUTATOR_ALIASES = (+ "gateway-update",+ "actor-activate",+ "actor-update",+ "actor-revoke",+ "campaign-activate",+ "campaign-update",+ "campaign-revoke",+ "grant-put",+ "grant-revoke",+ "destination-update",+ "destination-revoke",+ "credential-update",+ "credential-revoke",+ "approval-grant",+ "approval-revoke",+)++_P1C_INITIAL_AUTHORITY_ALIASES = (+ "new-v3-applied",+ "v3-exact-replay",+ "v3-logical-id-conflict",+ "v3-attempt-id-conflict",+ "v3-operation-id-conflict",+ "v3-module-id-conflict",+ "v3-ingress-conflict",+ "v3-trusted-principal-conflict",+ "v3-after-gateway-change",+ "v3-after-authority-deletion",+ "v2-exact-replay",+ "v2-changed-intent-conflict",+ "v2-after-gateway-change",+ "v2-after-authority-deletion",+ "new-v2-rejected",+ "v3-row-downgrade-rejected",+)++_P1C_UNTRUSTED_AUTHORITY_CLAIM_ALIASES = (+ "gateway-mode-claim",+ "gateway-revision-claim",+ "actor-user-claim",+ "actor-role-claim",+ "actor-revision-claim",+ "campaign-status-claim",+ "campaign-revision-claim",+ "campaign-owner-claim",+ "descriptor-authority-claim",+ "destination-authority-claim",+ "credential-authority-claim",+ "budget-authority-claim",+)++_P1C_AUTHORITY_DELETION_ALIASES = (+ "campaign-authority-cascade",+ "actor-authority-cascade",+ "destination-credential-authority-cascade",+ "snapshot-no-live-fk",+)++_P1C_PERSISTED_AUTHORITY_ALIASES = (+ "gateway-mode",+ "gateway-revision",+ "gateway-catalog-digest",+ "actor-identity",+ "actor-active",+ "actor-role",+ "actor-authority-revision",+ "campaign-status",+ "campaign-authority-revision",+ "campaign-ownership",+ "destination-extraction",+ "destination-campaign-scope",+ "destination-authority-revision",+ "credential-exists",+ "credential-ownership",+ "credential-authority-revision",+ "descriptor-module-identity",+ "descriptor-contract-version",+ "descriptor-semantic-digest",+ "policy-minimum-role",+ "policy-noise-class",+ "policy-required-capabilities",+ "policy-approval",+ "budget-authority-revisions",+ "budget-capacity",+)++_P1C_RETRY_AUTHORITY_ALIASES = (+ "v3-retry-applied",+ "v3-retry-exact-replay",+ "v3-retry-child-binding-conflict",+ "v3-retry-parent-revision-conflict",+ "v3-retry-after-authority-change",+ "v2-retry-exact-replay",+ "v2-retry-child-binding-conflict",+ "v2-retry-after-authority-change",+ "new-v2-retry-rejected",+ "v3-retry-downgrade-rejected",+)+++async def _p1c_sqlite_authority_store(+ tmp_path: Any,+) -> tuple[+ AresDatabase,+ ExecutionLifecycleStore,+ TrustedPrincipal,+ str,+ str,+ str,+]:+ database = AresDatabase(tmp_path / "p1c-authority.db")+ await database.connect()+ principal_id = _uuid(12_000)+ actor_id = _uuid(12_001)+ campaign_id = _uuid(12_002)+ credential_id = _uuid(12_003)+ await database.conn.executemany(+ "INSERT INTO users(id,username,hashed_password,role,created_by) VALUES(?,?,?,?,?)",+ (+ (principal_id, "p1c-admin", "fixed", "admin", "fixed"),+ (actor_id, "p1c-actor", "fixed", "operator", "fixed"),+ ),+ )+ await database.conn.execute(+ "INSERT INTO campaigns(id,name,operator,scope_json,targets_json) VALUES(?,?,?,?,?)",+ (campaign_id, "p1c-authority", "p1c-admin", "[]", '["host.example"]'),+ )+ await database.conn.execute(+ "INSERT INTO credentials(id,campaign_id,username,cred_type,source_module) "+ "VALUES(?,?,?,?,?)",+ (credential_id, campaign_id, "opaque-user", "cleartext", "p1c-fixture"),+ )+ await database.conn.commit()+ store = ExecutionLifecycleStore(database.conn, "sqlite")+ for user_id, operation in (+ (principal_id, _uuid(12_010)),+ (actor_id, _uuid(12_011)),+ ):+ assert (+ await store.ensure_actor_authority(user_id, operation)+ ).result is FixedResult.APPLIED+ assert (+ await store.ensure_campaign_authority(campaign_id, _uuid(12_012))+ ).result is FixedResult.APPLIED+ return (+ database,+ store,+ TrustedPrincipal(principal_id, principal_id),+ actor_id,+ campaign_id,+ credential_id,+ )+++def _p1c_v3_intent(campaign_id: str) -> AdmissionIntentV3:+ return AdmissionIntentV3(+ logical_execution_id=_uuid(12_500),+ submission_id=_uuid(12_501),+ attempt_id=_uuid(12_502),+ outbox_id=None,+ publication_key=None,+ campaign_id=campaign_id,+ module_id="opsec.coverage_predictor",+ ingress_code="sdk",+ operation_id=_uuid(12_503),+ evaluation_mode="live",+ raw_parameters={"noise_profile": "stealth"},+ )+++def _p1c_eligible_descriptor(monkeypatch: pytest.MonkeyPatch) -> ModuleDescriptor:+ source = descriptor_module.FIRST_PARTY_DESCRIPTORS["opsec.coverage_predictor"]+ values = {+ field.name: getattr(source, field.name) for field in fields(ModuleDescriptor) if field.init+ }+ values.update(+ idempotency=IdempotencyClass.PROVEN_IDEMPOTENT,+ external_effect=ExternalEffectClass.READ_ONLY,+ retry_eligibility=RetryEligibility.AFTER_REVALIDATION,+ cancellation_ownership=CancellationOwnership.OWNED,+ compensation=CompensationClass.NOT_APPLICABLE,+ timeout=TimeoutPolicy(+ source.timeout.seconds,+ source.timeout.source,+ TimeoutSettlement.PROVEN,+ ),+ result_contract=ResultContract(+ findings=ContractState.PROVEN_NONE,+ credentials=ContractState.PROVEN_NONE,+ discovered_hosts=ContractState.PROVEN_NONE,+ loot_artifacts=ContractState.PROVEN_NONE,+ authoritative_evidence=ContractState.SUPPORTED,+ ),+ blocker_codes=(),+ future_gateway_eligible=True,+ )+ descriptor = ModuleDescriptor(**values)+ descriptors = dict(descriptor_module.FIRST_PARTY_DESCRIPTORS)+ descriptors[descriptor.module_id] = descriptor+ monkeypatch.setattr(descriptor_module, "FIRST_PARTY_DESCRIPTORS", descriptors)+ return descriptor+++ "_case_alias",+ _P1C_UNTRUSTED_AUTHORITY_CLAIM_ALIASES,+ ids=_P1C_UNTRUSTED_AUTHORITY_CLAIM_ALIASES,+)+def test_admission_intent_rejects_each_untrusted_authority_claim(+ _case_alias: str,+) -> None:+ intent = _p1c_v3_intent(_uuid(12_002))+ claims: dict[str, object] = {+ "gateway-mode-claim": "enforced",+ "gateway-revision-claim": 7,+ "actor-user-claim": _uuid(12_900),+ "actor-role-claim": "admin",+ "actor-revision-claim": 7,+ "campaign-status-claim": "running",+ "campaign-revision-claim": 7,+ "campaign-owner-claim": _uuid(12_901),+ "descriptor-authority-claim": "a" * 64,+ "destination-authority-claim": "b" * 64,+ "credential-authority-claim": "c" * 64,+ "budget-authority-claim": 7,+ }+ field_name = _case_alias.removesuffix("-claim").replace("-", "_")+ with pytest.raises(TypeError):+ replace(intent, **{field_name: claims[_case_alias]})+++ "_case_alias",+ _P1C_AUTHORITY_DELETION_ALIASES,+ ids=_P1C_AUTHORITY_DELETION_ALIASES,+)+async def test_sqlite_p1c_authority_deletion_and_fk_contract(+ tmp_path, monkeypatch, _case_alias: str+) -> None:+ _p1c_eligible_descriptor(monkeypatch)+ (+ database,+ store,+ principal,+ actor_id,+ campaign_id,+ credential_id,+ ) = await _p1c_sqlite_authority_store(tmp_path)+ try:+ grant_actor = principal.user_id if _case_alias == "snapshot-no-live-fk" else actor_id+ assert (+ await store.put_campaign_actor_grant(+ principal,+ CampaignActorGrantMutation(_uuid(12_950), campaign_id, grant_actor, None),+ )+ ).result is FixedResult.APPLIED+ if _case_alias == "campaign-authority-cascade":+ deleted = await database.delete_campaign_lifecycle(+ campaign_id,+ operation_id=_uuid(12_951),+ )+ observed = await (+ await database.conn.execute(+ "SELECT "+ "(SELECT count(*) FROM campaigns WHERE id=?),"+ "(SELECT count(*) FROM campaign_execution_authority_revisions "+ "WHERE campaign_id=?),"+ "(SELECT count(*) FROM campaign_execution_actor_grants "+ "WHERE campaign_id=?),"+ "(SELECT count(*) FROM execution_operation_receipts "+ "WHERE operation_id=?)",+ (campaign_id, campaign_id, campaign_id, _uuid(12_951)),+ )+ ).fetchone()+ assert deleted.result is FixedResult.APPLIED, "campaign purge was rejected"+ assert tuple(observed) == (0, 0, 0, 1), (+ "campaign purge retained mutable authority or lost its receipt"+ )+ elif _case_alias == "actor-authority-cascade":+ await database.conn.execute(+ "DELETE FROM campaign_execution_actor_grants WHERE actor_user_id=?",+ (actor_id,),+ )+ await database.conn.execute("DELETE FROM users WHERE id=?", (actor_id,))+ await database.conn.commit()+ observed = await (+ await database.conn.execute(+ "SELECT "+ "(SELECT count(*) FROM execution_actor_authority_revisions "+ "WHERE user_id=?),"+ "(SELECT count(*) FROM users WHERE id=?)",+ (actor_id, actor_id),+ )+ ).fetchone()+ assert tuple(observed) == (0, 0), "actor authority did not cascade with user"+ elif _case_alias == "destination-credential-authority-cascade":+ deleted = await database.delete_campaign_lifecycle(+ campaign_id,+ operation_id=_uuid(12_952),+ )+ observed = await (+ await database.conn.execute(+ "SELECT "+ "(SELECT count(*) FROM campaign_execution_destination_authorities "+ "WHERE campaign_id=?),"+ "(SELECT count(*) FROM credentials WHERE id=?)",+ (campaign_id, credential_id),+ )+ ).fetchone()+ assert deleted.result is FixedResult.APPLIED, "campaign purge was rejected"+ assert tuple(observed) == (0, 0), (+ "campaign purge retained destination or credential authority"+ )+ else:+ intent = _p1c_v3_intent(campaign_id)+ applied = await store.create_initial_execution_v3(principal, intent)+ assert applied.result is FixedResult.APPLIED+ await database.conn.execute(+ "DELETE FROM campaign_execution_actor_grants WHERE campaign_id=?",+ (campaign_id,),+ )+ await database.conn.execute(+ "DELETE FROM campaign_execution_destination_authorities WHERE campaign_id=?",+ (campaign_id,),+ )+ await database.conn.execute("DELETE FROM credentials WHERE id=?", (credential_id,))+ await database.conn.commit()+ observed = await (+ await database.conn.execute(+ "SELECT authority_contract_version,trusted_principal_user_id,"+ "destination_authority_binding_digest,credential_authority_binding_digest "+ "FROM execution_attempts WHERE id=?",+ (intent.attempt_id,),+ )+ ).fetchone()+ assert observed is not None, "historical snapshot row is missing"+ assert tuple(observed[:2]) == (+ 3,+ principal.user_id,+ ), "historical snapshot depended on live authority"+ assert all(isinstance(value, str) and len(value) == 64 for value in observed[2:]), (+ "historical snapshot lost authority digests"+ )+ purged = await database.delete_campaign_lifecycle(+ campaign_id,+ operation_id=_uuid(12_953),+ )+ remaining = await (+ await database.conn.execute(+ "SELECT count(*) FROM execution_attempts WHERE id=?",+ (intent.attempt_id,),+ )+ ).fetchone()+ assert purged.result is FixedResult.APPLIED, "historical campaign purge failed"+ assert int(remaining[0]) == 0, "historical snapshot survived campaign purge"+ finally:+ await database.close()+++async def test_sqlite_actor_revocation_and_admission_are_linearized(tmp_path, monkeypatch) -> None:+ _p1c_eligible_descriptor(monkeypatch)+ (+ database,+ setup_store,+ principal,+ _actor_id,+ campaign_id,+ _credential_id,+ ) = await _p1c_sqlite_authority_store(tmp_path)+ contender_connection = await aiosqlite.connect((tmp_path / "p1c-authority.db").as_posix())+ contender_connection.row_factory = aiosqlite.Row+ await contender_connection.execute("PRAGMA foreign_keys=ON")+ await contender_connection.execute("PRAGMA busy_timeout=5000")+ await contender_connection.commit()+ admission_entered = asyncio.Event()+ revocation_attempted = asyncio.Event()+ admission_store = _SQLiteWinnerBarrierStore(+ database.conn,+ admission_entered,+ revocation_attempted,+ )+ revocation_store = _SQLiteContenderBarrierStore(+ contender_connection,+ revocation_attempted,+ )+ admission_task: asyncio.Task[OperationResult] | None = None+ revocation_task: asyncio.Task[OperationResult] | None = None+ try:+ assert (+ await setup_store.put_campaign_actor_grant(+ principal,+ CampaignActorGrantMutation(_uuid(12_960), campaign_id, principal.user_id, None),+ )+ ).result is FixedResult.APPLIED+ await _p1c_enable_acceptance(setup_store, principal, campaign_id)+ intent = _p1c_v3_intent(campaign_id)+ revoke_operation_id = _uuid(12_961)+ admission_task = asyncio.create_task(+ admission_store.create_initial_execution_v3(principal, intent)+ )+ await asyncio.wait_for(admission_entered.wait(), timeout=2)+ revocation_task = asyncio.create_task(+ revocation_store.revoke_actor_authority(+ principal,+ ActorAuthorityMutation(revoke_operation_id, principal.user_id, 0),+ )+ )+ await asyncio.wait_for(revocation_attempted.wait(), timeout=2)+ admitted, revoked = await asyncio.wait_for(+ asyncio.gather(admission_task, revocation_task),+ timeout=10,+ )+ observed_attempt = await (+ await database.conn.execute(+ "SELECT state,actor_authority_revision FROM execution_attempts WHERE id=?",+ (intent.attempt_id,),+ )+ ).fetchone()+ observed_actor = await (+ await database.conn.execute(+ "SELECT authority_state,authority_revision "+ "FROM execution_actor_authority_revisions WHERE user_id=?",+ (principal.user_id,),+ )+ ).fetchone()+ receipt_counts = await (+ await database.conn.execute(+ "SELECT "+ "sum(CASE WHEN operation_id=? THEN 1 ELSE 0 END),"+ "sum(CASE WHEN operation_id=? THEN 1 ELSE 0 END) "+ "FROM execution_operation_receipts",+ (intent.operation_id, revoke_operation_id),+ )+ ).fetchone()+ finally:+ for task in (admission_task, revocation_task):+ if task is not None and not task.done():+ task.cancel()+ pending = tuple(+ task+ for task in (admission_task, revocation_task)+ if task is not None and not task.done()+ )+ if pending:+ await asyncio.gather(*pending, return_exceptions=True)+ await contender_connection.close()+ await database.close()+ assert (admitted.result, revoked.result) == (+ FixedResult.APPLIED,+ FixedResult.APPLIED,+ ), "serialized admission/revocation result changed"+ assert tuple(observed_attempt) == ("accepted", 0), (+ "admission did not retain its locked actor authority revision"+ )+ assert tuple(observed_actor) == ("revoked", 1), "revocation did not serialize after admission"+ assert tuple(receipt_counts) == (0, 1), (+ "serialized operations wrote the wrong receipt cardinality"+ )+++def _p1c_v2_request(principal: TrustedPrincipal, campaign_id: str) -> AdmissionRequest:+ return AdmissionRequest(+ _uuid(12_500),+ _uuid(12_501),+ _uuid(12_502),+ _uuid(12_504),+ _uuid(12_505),+ campaign_id,+ principal.subject_ref,+ principal.user_id,+ "opsec.coverage_predictor",+ "sdk",+ AttemptState.BLOCKED,+ _uuid(12_503),+ replace(_blocked_snapshot(), actor_role="admin"),+ )+++async def _p1c_admission_counts(+ connection: aiosqlite.Connection, operation_id: str+) -> tuple[int, int, int, int]:+ values = []+ for statement, parameters in (+ ("SELECT count(*) FROM logical_executions", ()),+ ("SELECT count(*) FROM execution_attempts", ()),+ ("SELECT count(*) FROM execution_publication_outbox", ()),+ (+ "SELECT count(*) FROM execution_operation_receipts WHERE operation_id=?",+ (operation_id,),+ ),+ ):+ row = await (await connection.execute(statement, parameters)).fetchone()+ values.append(int(row[0]))+ return tuple(values) # type: ignore[return-value]+++async def _p1c_zero_delta_snapshot(+ connection: aiosqlite.Connection,+) -> tuple[int, ...]:+ row = await (+ await connection.execute(+ "SELECT "+ "(SELECT count(*) FROM logical_executions),"+ "(SELECT count(*) FROM execution_attempts),"+ "(SELECT count(*) FROM execution_publication_outbox),"+ "(SELECT count(*) FROM execution_attempt_approvals),"+ "(SELECT count(*) FROM campaign_execution_budget_ledger),"+ "(SELECT count(*) FROM execution_attempt_destination_observations),"+ "(SELECT count(*) FROM execution_attempt_credential_observations),"+ "(SELECT coalesce(sum(reserved_units),0) "+ "FROM campaign_execution_budgets),"+ "(SELECT coalesce(sum(consumed_units),0) "+ "FROM campaign_execution_budgets)"+ )+ ).fetchone()+ return tuple(int(value) for value in row)+++def _p1c_mutate_descriptor_without_rebinding(+ descriptor: ModuleDescriptor,+ case_alias: str,+) -> None:+ if case_alias == "destination-extraction":+ value: object = (+ DestinationSpec(+ DestinationKind.HOST,+ "noise_profile",+ DestinationCardinality.SCALAR,+ ScopeSemantics.PRIMARY_CAMPAIGN,+ ContractState.SUPPORTED,+ ),+ )+ field_name = "destinations"+ else:+ field_name, value = {+ "descriptor-module-identity": ("module_id", "opsec.changed_identity"),+ "descriptor-contract-version": (+ "contract_version",+ "ares.module-descriptor.invalid",+ ),+ "descriptor-semantic-digest": ("semantic_digest", "0" * 64),+ "policy-minimum-role": ("minimum_role", MinimumRole.TEAM_LEAD),+ "policy-noise-class": ("opsec", OpsecClassification.HIGH_NOISE),+ "policy-required-capabilities": (+ "required_capabilities",+ (Capability.CAP_NET,),+ ),+ "policy-approval": ("explicit_attempt_approval", True),+ }[case_alias]+ object.__setattr__(descriptor, field_name, value)+ if field_name != "semantic_digest":+ object.__setattr__(+ descriptor,+ "semantic_digest",+ hashlib.sha256(case_alias.encode("ascii")).hexdigest(),+ )+++ "_case_alias",+ _P1C_PERSISTED_AUTHORITY_ALIASES,+ ids=_P1C_PERSISTED_AUTHORITY_ALIASES,+)+async def test_sqlite_p1c_each_persisted_authority_contradiction_is_atomic(+ tmp_path, monkeypatch, _case_alias: str+) -> None:+ descriptor = _p1c_eligible_descriptor(monkeypatch)+ (+ database,+ store,+ principal,+ _actor_id,+ campaign_id,+ credential_id,+ ) = await _p1c_sqlite_authority_store(tmp_path)+ try:+ assert (+ await store.put_campaign_actor_grant(+ principal,+ CampaignActorGrantMutation(_uuid(12_700), campaign_id, principal.user_id, None),+ )+ ).result is FixedResult.APPLIED+ await _p1c_enable_acceptance(store, principal, campaign_id)+ intent = _p1c_v3_intent(campaign_id)+ if _case_alias.startswith("credential-"):+ intent = replace(intent, credential_ids=(credential_id,))++ if _case_alias == "gateway-mode":+ await database.conn.execute("PRAGMA ignore_check_constraints=ON")+ await database.conn.execute(+ "UPDATE execution_gateway_state SET mode='invalid-persisted-mode'"+ )+ await database.conn.execute("PRAGMA ignore_check_constraints=OFF")+ elif _case_alias == "gateway-revision":+ await database.conn.execute(+ "UPDATE execution_gateway_state SET activation_revision=revision+1"+ )+ elif _case_alias == "gateway-catalog-digest":+ await database.conn.execute(+ "UPDATE execution_gateway_state SET catalog_digest=?",+ ("0" * 64,),+ )+ elif _case_alias == "actor-identity":+ principal = TrustedPrincipal(_uuid(12_701), _uuid(12_701))+ elif _case_alias == "actor-active":+ await database.conn.execute(+ "UPDATE users SET is_active=0 WHERE id=?", (principal.user_id,)+ )+ elif _case_alias == "actor-role":+ await database.conn.execute("PRAGMA ignore_check_constraints=ON")+ await database.conn.execute(+ "UPDATE users SET role='recon' WHERE id=?", (principal.user_id,)+ )+ await database.conn.execute("PRAGMA ignore_check_constraints=OFF")+ elif _case_alias == "actor-authority-revision":+ await database.conn.execute(+ "UPDATE execution_actor_authority_revisions "+ "SET authority_revision=authority_revision+1 WHERE user_id=?",+ (principal.user_id,),+ )+ elif _case_alias == "campaign-status":+ await database.conn.execute(+ "UPDATE campaigns SET status='completed' WHERE id=?", (campaign_id,)+ )+ elif _case_alias == "campaign-authority-revision":+ await database.conn.execute(+ "UPDATE campaign_execution_authority_revisions "+ "SET authority_revision=authority_revision+1 WHERE campaign_id=?",+ (campaign_id,),+ )+ elif _case_alias == "campaign-ownership":+ await database.conn.execute(+ "UPDATE campaigns SET operator='different-owner' WHERE id=?",+ (campaign_id,),+ )+ elif _case_alias == "destination-campaign-scope":+ await database.conn.execute(+ "UPDATE campaigns SET targets_json='[\"other.example\"]' WHERE id=?",+ (campaign_id,),+ )+ elif _case_alias == "destination-authority-revision":+ await database.conn.execute(+ "UPDATE campaign_execution_destination_authorities "+ "SET revision=revision+1 WHERE campaign_id=?",+ (campaign_id,),+ )+ elif _case_alias == "credential-exists":+ await database.conn.execute("DELETE FROM credentials WHERE id=?", (credential_id,))+ elif _case_alias == "credential-ownership":+ other_campaign = _uuid(12_702)+ await database.conn.execute(+ "INSERT INTO campaigns(id,name) VALUES(?,?)",+ (other_campaign, "other-authority"),+ )+ await database.conn.execute(+ "UPDATE credentials SET campaign_id=? WHERE id=?",+ (other_campaign, credential_id),+ )+ elif _case_alias == "credential-authority-revision":+ await database.conn.execute(+ "UPDATE credentials SET execution_authority_revision="+ "execution_authority_revision+1 WHERE id=?",+ (credential_id,),+ )+ elif _case_alias in {+ "destination-extraction",+ "descriptor-module-identity",+ "descriptor-contract-version",+ "descriptor-semantic-digest",+ "policy-minimum-role",+ "policy-noise-class",+ "policy-required-capabilities",+ "policy-approval",+ }:+ _p1c_mutate_descriptor_without_rebinding(descriptor, _case_alias)+ elif _case_alias == "budget-authority-revisions":+ await database.conn.execute(+ "UPDATE campaign_execution_budgets SET revision=revision+1,"+ "latest_operation_code='reserve' WHERE budget_kind='noise' "+ "AND campaign_id=?",+ (campaign_id,),+ )+ else:+ await database.conn.execute(+ "UPDATE campaign_execution_budgets SET reserved_units=capacity_units "+ "WHERE budget_kind='concurrency' AND campaign_id=?",+ (campaign_id,),+ )+ await database.conn.commit()+ before = await _p1c_zero_delta_snapshot(database.conn)+ result = await store.create_initial_execution_v3(principal, intent)+ observer = await aiosqlite.connect((tmp_path / "p1c-authority.db").as_posix())+ try:+ after = await _p1c_zero_delta_snapshot(observer)+ finally:+ await observer.close()+ expected = (+ FixedResult.CAPACITY_UNAVAILABLE+ if _case_alias == "budget-capacity"+ else FixedResult.AUTHORITY_STALE+ )+ assert result.result is expected, "persisted contradiction classification changed"+ assert after == before, "persisted contradiction leaked durable admission state"+ finally:+ await database.close()+++async def _p1c_enable_acceptance(+ store: ExecutionLifecycleStore,+ principal: TrustedPrincipal,+ campaign_id: str,+) -> None:+ assert (+ await store.update_gateway_authority(+ principal,+ GatewayAuthorityMutation(_uuid(12_530), 0, "enforced"),+ )+ ).result is FixedResult.APPLIED+ assert (+ await store.configure_campaign_budgets(+ BudgetConfiguration(+ campaign_id,+ _uuid(12_531),+ 10,+ _uuid(12_532),+ 10,+ _uuid(12_533),+ 1,+ _uuid(12_534),+ "actor",+ principal.subject_ref,+ principal.user_id,+ 0,+ )+ )+ ).result is FixedResult.APPLIED+++async def _p1c_fail_accepted_parent_for_retry(+ connection: aiosqlite.Connection,+ store: ExecutionLifecycleStore,+ principal: TrustedPrincipal,+ intent: AdmissionIntentV3,+) -> int:+ budgets = await (+ await connection.execute(+ "SELECT budget_kind,id,revision FROM campaign_execution_budgets "+ "WHERE campaign_id=? ORDER BY budget_kind",+ (intent.campaign_id,),+ )+ ).fetchall()+ by_kind = {str(row[0]): (str(row[1]), int(row[2])) for row in budgets}+ transition = TransitionRequest(+ intent.attempt_id,+ 0,+ AttemptState.FAILED,+ _uuid(12_540),+ outcome_code=OutcomeCode.CONFIRMED_FAILURE_NO_DISPATCH,+ authoritative_proof="no_dispatch",+ campaign_id=intent.campaign_id,+ actor_subject_ref=principal.subject_ref,+ actor_user_id=principal.user_id,+ actor_authority_revision=0,+ )+ settlement = BudgetSettlement(+ intent.campaign_id,+ intent.attempt_id,+ by_kind["noise"][0],+ intent.noise_units,+ 0,+ by_kind["noise"][1],+ by_kind["exfiltration"][0],+ intent.exfiltration_units,+ 0,+ by_kind["exfiltration"][1],+ by_kind["concurrency"][0],+ by_kind["concurrency"][1],+ _uuid(12_541),+ "actor",+ principal.subject_ref,+ principal.user_id,+ 0,+ )+ result = await store.commit_terminal_attempt(+ TerminalCommitRequest(+ intent.logical_execution_id,+ intent.campaign_id,+ _uuid(12_542),+ _uuid(12_543),+ transition,+ settlement,+ )+ )+ assert result.result is FixedResult.APPLIED, "v3 retry parent did not fail"+ observed = await (+ await connection.execute(+ "SELECT revision,retry_disposition FROM execution_attempts WHERE id=?",+ (intent.attempt_id,),+ )+ ).fetchone()+ assert tuple(observed) == (1, "eligible"), "v3 retry parent was not promoted"+ return 1+++def _p1c_v3_retry_intent(intent: AdmissionIntentV3) -> RetryIntentV3:+ return RetryIntentV3(+ intent.logical_execution_id,+ intent.attempt_id,+ _uuid(12_550),+ None,+ None,+ _uuid(12_551),+ 1,+ "live",+ intent.raw_parameters,+ )+++def _p1c_v2_retry_request(principal: TrustedPrincipal) -> RetryRequest:+ child = AdmissionRequest(+ _uuid(4),+ _uuid(12_560),+ _uuid(12_561),+ _uuid(12_562),+ _uuid(12_563),+ _uuid(2),+ principal.subject_ref,+ principal.user_id,+ "test.module",+ "sdk",+ AttemptState.BLOCKED,+ _uuid(12_564),+ replace(_blocked_snapshot(), actor_role="admin"),+ )+ return RetryRequest(_uuid(4), _uuid(6), child, 0)+++ "_case_alias",+ _P1C_RETRY_AUTHORITY_ALIASES,+ ids=_P1C_RETRY_AUTHORITY_ALIASES,+)+async def test_sqlite_p1c_retry_v2_v3_authority(tmp_path, monkeypatch, _case_alias: str) -> None:+ if _case_alias.startswith("v2-") or _case_alias == "new-v2-retry-rejected":+ connection = await _new_connection((tmp_path / "p1c-v2-retry.db").as_posix())+ principal = TrustedPrincipal(_uuid(1), _uuid(1))+ request = _p1c_v2_retry_request(principal)+ try:+ await _insert_retryable_attempt(connection)+ store = ExecutionLifecycleStore(connection, "sqlite")+ if _case_alias == "new-v2-retry-rejected":+ result = await store.create_retry_attempt(request)+ attempts = await (+ await connection.execute("SELECT count(*) FROM execution_attempts")+ ).fetchone()+ assert result.result is FixedResult.INVALID_CONTRACT, (+ "public fresh-v2 retry was accepted"+ )+ assert int(attempts[0]) == 1, "fresh-v2 rejection created a child"+ return+ assert (+ await store._create_retry_attempt_v2_for_migration_fixture(request)+ ).result is FixedResult.APPLIED+ if _case_alias == "v2-retry-child-binding-conflict":+ request = replace(+ request,+ child=replace(request.child, attempt_id=_uuid(12_565)),+ )+ expected = FixedResult.CONFLICT_OPERATION+ else:+ if _case_alias == "v2-retry-after-authority-change":+ await connection.execute(+ "UPDATE execution_actor_authority_revisions "+ "SET authority_revision=authority_revision+1 WHERE user_id=?",+ (principal.user_id,),+ )+ await connection.commit()+ expected = FixedResult.REPLAYED_BOUND_CHILD+ result = await store.replay_retry_attempt_v2(principal, request)+ assert result.result is expected, "historical v2 retry replay changed"+ finally:+ await connection.close()+ return++ _p1c_eligible_descriptor(monkeypatch)+ (+ database,+ store,+ principal,+ _actor_id,+ campaign_id,+ _credential_id,+ ) = await _p1c_sqlite_authority_store(tmp_path)+ try:+ assert (+ await store.put_campaign_actor_grant(+ principal,+ CampaignActorGrantMutation(_uuid(12_570), campaign_id, principal.user_id, None),+ )+ ).result is FixedResult.APPLIED+ await _p1c_enable_acceptance(store, principal, campaign_id)+ initial = _p1c_v3_intent(campaign_id)+ assert (+ await store.create_initial_execution_v3(principal, initial)+ ).result is FixedResult.APPLIED+ await _p1c_fail_accepted_parent_for_retry(database.conn, store, principal, initial)+ intent = _p1c_v3_retry_intent(initial)+ applied = await store.create_retry_attempt_v3(principal, intent)+ assert applied.result is FixedResult.APPLIED, "first v3 retry was not applied"+ if _case_alias == "v3-retry-applied":+ result = applied+ expected = FixedResult.APPLIED+ elif _case_alias == "v3-retry-exact-replay":+ result = await store.create_retry_attempt_v3(principal, intent)+ expected = FixedResult.REPLAYED_BOUND_CHILD+ elif _case_alias == "v3-retry-child-binding-conflict":+ result = await store.create_retry_attempt_v3(+ principal,+ replace(intent, child_attempt_id=_uuid(12_571)),+ )+ expected = FixedResult.CONFLICT_OPERATION+ elif _case_alias == "v3-retry-parent-revision-conflict":+ result = await store.create_retry_attempt_v3(+ principal,+ replace(intent, expected_parent_revision=2),+ )+ expected = FixedResult.CONFLICT_OPERATION+ elif _case_alias == "v3-retry-after-authority-change":+ assert (+ await store.update_actor_authority(+ principal,+ ActorAuthorityMutation(_uuid(12_572), principal.user_id, 0),+ )+ ).result is FixedResult.APPLIED+ result = await store.create_retry_attempt_v3(principal, intent)+ expected = FixedResult.REPLAYED_BOUND_CHILD+ else:+ result = await store.replay_retry_attempt_v2(+ principal,+ RetryRequest(+ intent.logical_execution_id,+ intent.parent_attempt_id,+ AdmissionRequest(+ intent.logical_execution_id,+ initial.submission_id,+ intent.child_attempt_id,+ _uuid(12_573),+ _uuid(12_574),+ campaign_id,+ principal.subject_ref,+ principal.user_id,+ initial.module_id,+ initial.ingress_code,+ AttemptState.BLOCKED,+ intent.operation_id,+ replace(_blocked_snapshot(), actor_role="admin"),+ ),+ intent.expected_parent_revision,+ ),+ )+ expected = FixedResult.CONFLICT_OPERATION+ assert result.result is expected, "v3 retry replay authority changed"+ rows = await (+ await database.conn.execute(+ "SELECT id,parent_attempt_id,authority_contract_version "+ "FROM execution_attempts WHERE logical_execution_id=? ORDER BY ordinal",+ (initial.logical_execution_id,),+ )+ ).fetchall()+ receipts = await (+ await database.conn.execute(+ "SELECT count(*) FROM execution_operation_receipts WHERE operation_id=?",+ (intent.operation_id,),+ )+ ).fetchone()+ assert tuple(tuple(row) for row in rows) == (+ (initial.attempt_id, None, 3),+ (intent.child_attempt_id, initial.attempt_id, 3),+ ), "v3 retry child binding changed"+ assert int(receipts[0]) == 1, "v3 retry lost or duplicated its receipt"+ finally:+ await database.close()+++ "_case_alias",+ _P1C_INITIAL_AUTHORITY_ALIASES,+ ids=_P1C_INITIAL_AUTHORITY_ALIASES,+)+async def test_sqlite_p1c_initial_v2_v3_submission_authority(+ tmp_path, monkeypatch, _case_alias: str+) -> None:+ _p1c_eligible_descriptor(monkeypatch)+ (+ database,+ store,+ principal,+ _actor_id,+ campaign_id,+ _credential_id,+ ) = await _p1c_sqlite_authority_store(tmp_path)+ try:+ grant = CampaignActorGrantMutation(_uuid(12_510), campaign_id, principal.user_id, None)+ assert (+ await store.put_campaign_actor_grant(principal, grant)+ ).result is FixedResult.APPLIED+ intent = _p1c_v3_intent(campaign_id)+ v2_request = _p1c_v2_request(principal, campaign_id)++ if _case_alias.startswith("v2-") or _case_alias == "new-v2-rejected":+ if _case_alias == "new-v2-rejected":+ result = await store.create_initial_execution(v2_request)+ assert result.result is FixedResult.INVALID_CONTRACT, (+ "public fresh-v2 creation was accepted"+ )+ assert await _p1c_admission_counts(database.conn, v2_request.operation_id) == (+ 0,+ 0,+ 0,+ 0,+ ), "fresh-v2 rejection created durable state"+ return++ assert (+ await store._create_initial_execution_v2_for_migration_fixture(v2_request)+ ).result is FixedResult.APPLIED+ if _case_alias == "v2-exact-replay":+ result = await store.replay_initial_execution_v2(principal, v2_request)+ expected = FixedResult.REPLAYED+ elif _case_alias == "v2-changed-intent-conflict":+ result = await store.replay_initial_execution_v2(+ principal,+ replace(v2_request, module_id="opsec.coverage_predictor.changed"),+ )+ expected = FixedResult.CONFLICT_OPERATION+ elif _case_alias == "v2-after-gateway-change":+ assert (+ await store.update_gateway_authority(+ principal,+ GatewayAuthorityMutation(_uuid(12_511), 0, "enforced"),+ )+ ).result is FixedResult.APPLIED+ result = await store.replay_initial_execution_v2(principal, v2_request)+ expected = FixedResult.REPLAYED+ else:+ await database.conn.execute(+ "DELETE FROM campaign_execution_actor_grants WHERE campaign_id=?",+ (campaign_id,),+ )+ await database.conn.execute(+ "DELETE FROM campaign_execution_destination_authorities WHERE campaign_id=?",+ (campaign_id,),+ )+ await database.conn.commit()+ result = await store.replay_initial_execution_v2(principal, v2_request)+ expected = FixedResult.REPLAYED+ assert result.result is expected, "historical v2 replay authority changed"+ return++ await _p1c_enable_acceptance(store, principal, campaign_id)+ applied = await store.create_initial_execution_v3(principal, intent)+ assert applied.result is FixedResult.APPLIED, "first v3 admission was not applied"+ if _case_alias == "new-v3-applied":+ result = applied+ expected = FixedResult.APPLIED+ elif _case_alias == "v3-exact-replay":+ result = await store.create_initial_execution_v3(principal, intent)+ expected = FixedResult.REPLAYED+ elif _case_alias == "v3-logical-id-conflict":+ result = await store.create_initial_execution_v3(+ principal, replace(intent, logical_execution_id=_uuid(12_520))+ )+ expected = FixedResult.CONFLICT_OPERATION+ elif _case_alias == "v3-attempt-id-conflict":+ result = await store.create_initial_execution_v3(+ principal, replace(intent, attempt_id=_uuid(12_521))+ )+ expected = FixedResult.CONFLICT_OPERATION+ elif _case_alias == "v3-operation-id-conflict":+ result = await store.create_initial_execution_v3(+ principal, replace(intent, operation_id=_uuid(12_522))+ )+ expected = FixedResult.CONFLICT_OPERATION+ elif _case_alias == "v3-module-id-conflict":+ result = await store.create_initial_execution_v3(+ principal, replace(intent, module_id="opsec.coverage_predictor.changed")+ )+ expected = FixedResult.CONFLICT_OPERATION+ elif _case_alias == "v3-ingress-conflict":+ result = await store.create_initial_execution_v3(+ principal, replace(intent, ingress_code="cli_module")+ )+ expected = FixedResult.CONFLICT_OPERATION+ elif _case_alias == "v3-trusted-principal-conflict":+ changed = TrustedPrincipal(_uuid(12_523), _uuid(12_523))+ result = await store.create_initial_execution_v3(changed, intent)+ expected = FixedResult.CONFLICT_OPERATION+ elif _case_alias == "v3-after-gateway-change":+ assert (+ await store.update_gateway_authority(+ principal,+ GatewayAuthorityMutation(_uuid(12_524), 1, "shadow_candidate"),+ )+ ).result is FixedResult.APPLIED+ result = await store.create_initial_execution_v3(principal, intent)+ expected = FixedResult.REPLAYED+ elif _case_alias == "v3-after-authority-deletion":+ await database.conn.execute(+ "DELETE FROM campaign_execution_actor_grants WHERE campaign_id=?",+ (campaign_id,),+ )+ await database.conn.execute(+ "DELETE FROM campaign_execution_destination_authorities WHERE campaign_id=?",+ (campaign_id,),+ )+ await database.conn.commit()+ result = await store.create_initial_execution_v3(principal, intent)+ expected = FixedResult.REPLAYED+ else:+ result = await store.replay_initial_execution_v2(principal, v2_request)+ expected = FixedResult.CONFLICT_OPERATION++ assert result.result is expected, "v3 submission replay authority changed"+ counts = await _p1c_admission_counts(database.conn, intent.operation_id)+ assert counts[:3] == (1, 1, 0), "v3 accepted admission cardinality changed"+ assert counts[3] == 0, "initial admission created a redundant operation receipt"+ attempt = await (+ await database.conn.execute(+ "SELECT state,retry_disposition FROM execution_attempts WHERE id=?",+ (intent.attempt_id,),+ )+ ).fetchone()+ reservations = await (+ await database.conn.execute(+ "SELECT count(*) FROM campaign_execution_budget_ledger WHERE attempt_id=?",+ (intent.attempt_id,),+ )+ ).fetchone()+ assert tuple(attempt) == (+ "accepted",+ "not_applicable",+ ), "v3 acceptance state changed"+ assert int(reservations[0]) == 3, "v3 acceptance missed budget reservations"+ finally:+ await database.close()+++ "_case_alias",+ _P1C_AUTHORITY_MUTATOR_ALIASES,+ ids=_P1C_AUTHORITY_MUTATOR_ALIASES,+)+async def test_sqlite_p1c_each_authority_mutator_is_exactly_replayable(+ tmp_path, monkeypatch, _case_alias: str+) -> None:+ descriptor = (+ _p1c_eligible_descriptor(monkeypatch)+ if _case_alias in {"gateway-update", "approval-grant"}+ else None+ )+ (+ database,+ store,+ principal,+ actor_id,+ campaign_id,+ credential_id,+ ) = await _p1c_sqlite_authority_store(tmp_path)+ operation_id = _uuid(12_100 + _P1C_AUTHORITY_MUTATOR_ALIASES.index(_case_alias))+ approval_id = _uuid(12_200)+ approval_ref = _uuid(12_201)+ try:+ if _case_alias == "gateway-update":+ request: Any = GatewayAuthorityMutation(operation_id, 0, "enforced")+ method_name = "update_gateway_authority"+ elif _case_alias.startswith("actor-"):+ action = _case_alias.removeprefix("actor-")+ expected_revision = 0+ if action == "activate":+ assert (+ await store.revoke_actor_authority(+ principal,+ ActorAuthorityMutation(_uuid(12_300), actor_id, 0),+ )+ ).result is FixedResult.APPLIED+ expected_revision = 1+ request = ActorAuthorityMutation(operation_id, actor_id, expected_revision)+ method_name = f"{action}_actor_authority"+ elif _case_alias.startswith("campaign-"):+ action = _case_alias.removeprefix("campaign-")+ expected_revision = 0+ if action == "activate":+ assert (+ await store.revoke_campaign_authority(+ principal,+ CampaignAuthorityMutation(_uuid(12_301), campaign_id, 0),+ )+ ).result is FixedResult.APPLIED+ expected_revision = 1+ request = CampaignAuthorityMutation(operation_id, campaign_id, expected_revision)+ method_name = f"{action}_campaign_authority"+ elif _case_alias.startswith("grant-"):+ action = _case_alias.removeprefix("grant-")+ expected_revision = None+ if action == "revoke":+ assert (+ await store.put_campaign_actor_grant(+ principal,+ CampaignActorGrantMutation(_uuid(12_302), campaign_id, actor_id, None),+ )+ ).result is FixedResult.APPLIED+ expected_revision = 0+ request = CampaignActorGrantMutation(+ operation_id, campaign_id, actor_id, expected_revision+ )+ method_name = f"{action}_campaign_actor_grant"+ elif _case_alias.startswith("destination-"):+ action = _case_alias.removeprefix("destination-")+ request = DestinationAuthorityMutation(operation_id, campaign_id, 0)+ method_name = f"{action}_destination_authority"+ elif _case_alias.startswith("credential-"):+ action = _case_alias.removeprefix("credential-")+ request = CredentialAuthorityMutation(operation_id, credential_id, 0)+ method_name = f"{action}_credential_authority"+ elif _case_alias == "approval-grant":+ request = ApprovalAuthorityGrant(+ operation_id,+ approval_id,+ approval_ref,+ campaign_id,+ _uuid(12_202),+ _uuid(12_203),+ actor_id,+ actor_id,+ "opsec.coverage_predictor",+ 0,+ )+ method_name = "grant_approval_authority"+ else:+ grant = ApprovalAuthorityGrant(+ _uuid(12_303),+ approval_id,+ approval_ref,+ campaign_id,+ _uuid(12_202),+ _uuid(12_203),+ actor_id,+ actor_id,+ "opsec.coverage_predictor",+ 0,+ )+ assert (+ await store.grant_approval_authority(principal, grant)+ ).result is FixedResult.APPLIED+ request = ApprovalAuthorityMutation(operation_id, approval_id, 0)+ method_name = "revoke_approval_authority"++ async def invoke() -> OperationResult:+ method = getattr(store, method_name)+ return await method(principal, request)++ def changed_request() -> Any:+ if type(request) is GatewayAuthorityMutation:+ return replace(request, mode="shadow_candidate")+ if type(request) in {+ ActorAuthorityMutation,+ CampaignAuthorityMutation,+ DestinationAuthorityMutation,+ CredentialAuthorityMutation,+ ApprovalAuthorityMutation,+ }:+ return replace(request, expected_revision=request.expected_revision + 1)+ if type(request) is CampaignActorGrantMutation:+ expected = 0 if request.expected_revision is None else request.expected_revision + 1+ return replace(request, expected_revision=expected)+ if type(request) is ApprovalAuthorityGrant:+ return replace(request, granted_capability_mask=1)+ raise AssertionError("unsupported authority mutation request")++ async def observe_target() -> tuple[tuple[object, ...], ...]:+ table, where, parameters = {+ "gateway-update": (+ "execution_gateway_state",+ "singleton_id=1",+ (),+ ),+ "actor-activate": (+ "execution_actor_authority_revisions",+ "user_id=?",+ (actor_id,),+ ),+ "actor-update": (+ "execution_actor_authority_revisions",+ "user_id=?",+ (actor_id,),+ ),+ "actor-revoke": (+ "execution_actor_authority_revisions",+ "user_id=?",+ (actor_id,),+ ),+ "campaign-activate": (+ "campaign_execution_authority_revisions",+ "campaign_id=?",+ (campaign_id,),+ ),+ "campaign-update": (+ "campaign_execution_authority_revisions",+ "campaign_id=?",+ (campaign_id,),+ ),+ "campaign-revoke": (+ "campaign_execution_authority_revisions",+ "campaign_id=?",+ (campaign_id,),+ ),+ "grant-put": (+ "campaign_execution_actor_grants",+ "campaign_id=? AND actor_user_id=?",+ (campaign_id, actor_id),+ ),+ "grant-revoke": (+ "campaign_execution_actor_grants",+ "campaign_id=? AND actor_user_id=?",+ (campaign_id, actor_id),+ ),+ "destination-update": (+ "campaign_execution_destination_authorities",+ "campaign_id=?",+ (campaign_id,),+ ),+ "destination-revoke": (+ "campaign_execution_destination_authorities",+ "campaign_id=?",+ (campaign_id,),+ ),+ "credential-update": ("credentials", "id=?", (credential_id,)),+ "credential-revoke": ("credentials", "id=?", (credential_id,)),+ "approval-grant": (+ "execution_approval_authorities",+ "id=?",+ (approval_id,),+ ),+ "approval-revoke": (+ "execution_approval_authorities",+ "id=?",+ (approval_id,),+ ),+ }[_case_alias]+ rows = await (+ await database.conn.execute(+ f"SELECT * FROM {table} WHERE {where}", # noqa: S608+ parameters,+ )+ ).fetchall()+ return tuple(tuple(row) for row in rows)++ applied = await invoke()+ receipt_count_after_apply = int(+ (+ await (+ await database.conn.execute(+ "SELECT count(*) FROM execution_operation_receipts WHERE operation_id=?",+ (operation_id,),+ )+ ).fetchone()+ )[0]+ )+ replayed = await invoke()+ receipt_count_after_replay = int(+ (+ await (+ await database.conn.execute(+ "SELECT count(*) FROM execution_operation_receipts WHERE operation_id=?",+ (operation_id,),+ )+ ).fetchone()+ )[0]+ )+ target_before_conflict = await observe_target()+ method = getattr(store, method_name)+ conflicting = await method(principal, changed_request())+ target_after_conflict = await observe_target()+ receipt_count_after_conflict = int(+ (+ await (+ await database.conn.execute(+ "SELECT count(*) FROM execution_operation_receipts WHERE operation_id=?",+ (operation_id,),+ )+ ).fetchone()+ )[0]+ )+ receipt_first: OperationResult | None = None+ if _case_alias == "gateway-update":+ assert descriptor is not None+ _p1c_mutate_descriptor_without_rebinding(+ descriptor,+ "descriptor-semantic-digest",+ )+ receipt_first = await invoke()+ elif _case_alias.startswith("credential-"):+ await database.conn.execute("DELETE FROM credentials WHERE id=?", (credential_id,))+ await database.conn.commit()+ receipt_first = await invoke()+ elif _case_alias.startswith("approval-"):+ if descriptor is not None:+ _p1c_mutate_descriptor_without_rebinding(+ descriptor,+ "descriptor-semantic-digest",+ )+ await database.conn.execute(+ "DELETE FROM execution_approval_authorities WHERE id=?",+ (approval_id,),+ )+ await database.conn.commit()+ receipt_first = await invoke()+ assert (applied.result, replayed.result) == (+ FixedResult.APPLIED,+ FixedResult.REPLAYED,+ ), "authority mutation lost exact replay"+ assert conflicting.result is FixedResult.CONFLICT_OPERATION, (+ "changed authority mutation reused an immutable operation"+ )+ assert target_after_conflict == target_before_conflict, (+ "changed authority mutation altered its target"+ )+ assert (+ receipt_count_after_apply+ == receipt_count_after_replay+ == receipt_count_after_conflict+ == 1+ ), "authority mutation replay duplicated its receipt"+ if receipt_first is not None:+ assert receipt_first.result is FixedResult.REPLAYED, (+ "authority mutation replay consulted mutable current authority"+ )+ finally:+ await database.close()+++_P1B_AUTHORITY_CASES = (+ ("actor-authority-ensure", "actor_authority_ensure"),+ ("campaign-authority-ensure", "campaign_authority_ensure"),+ ("actor-authority-invalidate", "actor_authority_invalidate"),+ ("campaign-authority-invalidate", "campaign_authority_invalidate"),+ ("budget-configure", "budget_configure"),+ ("budget-reserve", "budget_reserve"),+ ("budget-settle", "budget_settle"),+ ("admission", "admission"),+ ("retry-attempt", "retry"),+ ("attempt-transition", "queue"),+ ("settlement-pending", "settlement_pending"),+ ("expired-lease-settlement", "lease_loss"),+ ("terminal-commit", "terminal_failed"),+ ("close-without-retry", "close_without_retry"),+ ("outbox-claim", "outbox_claim"),+ ("outbox-reclaim", "outbox_reclaim"),+ ("outbox-poison", "outbox_poison"),+ ("outbox-renew", "outbox_renew"),+ ("outbox-publish", "outbox_publish"),+ ("outbox-fail-retryable", "outbox_retryable_failure"),+ ("outbox-fail-nonretryable", "outbox_nonretryable_failure"),+ ("outbox-purge", "outbox_purge"),+ ("campaign-delete", "campaign_delete"),+)++_P1B_PUBLIC_METHOD_MAP = (+ ("actor-authority-ensure", "ExecutionLifecycleStore.ensure_actor_authority"),+ ("campaign-authority-ensure", "ExecutionLifecycleStore.ensure_campaign_authority"),+ ("actor-authority-invalidate", "ExecutionLifecycleStore.invalidate_actor_authority"),+ (+ "campaign-authority-invalidate",+ "ExecutionLifecycleStore.invalidate_campaign_authority",+ ),+ ("budget-configure", "ExecutionLifecycleStore.configure_campaign_budgets"),+ ("budget-reserve", "ExecutionLifecycleStore.reserve_budgets"),+ ("budget-settle", "ExecutionLifecycleStore.settle_budgets"),+ ("admission", "ExecutionLifecycleStore.create_initial_execution"),+ ("retry-attempt", "ExecutionLifecycleStore.create_retry_attempt"),+ ("attempt-transition", "ExecutionLifecycleStore.transition_attempt"),+ ("settlement-pending", "ExecutionLifecycleStore.enter_settlement_pending"),+ (+ "expired-lease-settlement",+ "ExecutionLifecycleStore.mark_expired_lease_settlement_pending",+ ),+ ("terminal-commit", "ExecutionLifecycleStore.commit_terminal_attempt"),+ ("close-without-retry", "ExecutionLifecycleStore.close_without_retry"),+ ("outbox-claim", "ExecutionLifecycleStore.claim_outbox"),+ ("outbox-reclaim", "ExecutionLifecycleStore.claim_outbox(reclaim=True)"),+ ("outbox-poison", "ExecutionLifecycleStore.poison_expired_attempt_twenty"),+ ("outbox-renew", "ExecutionLifecycleStore.renew_outbox"),+ ("outbox-publish", "ExecutionLifecycleStore.publish_outbox"),+ ("outbox-fail-retryable", "ExecutionLifecycleStore.fail_outbox(retryable=True)"),+ (+ "outbox-fail-nonretryable",+ "ExecutionLifecycleStore.fail_outbox(retryable=False)",+ ),+ ("outbox-purge", "ExecutionLifecycleStore.purge_outbox"),+ ("campaign-delete", "AresDatabase.delete_campaign_lifecycle"),+)++_P1B_LITERAL_NODE_COUNT = 88+_P1B_LITERAL_NODE_IDS_SHA256 = "77398973391e0092ee8a3979e31ff3cd364d53b786683bae0503266357699f90"++_P1B_BINDING_MUTATIONS = (+ "operation-code-transition",+ "primary-target-transition",+ "secondary-target-retry",+ "campaign-transition",+ "principal-kind-transition",+ "principal-subject-transition",+ "principal-user-transition",+ "principal-authority-revision-transition",+ "expected-revision-presence-transition",+ "expected-revision-value-transition",+ "secondary-expected-presence-budget",+ "secondary-expected-value-budget",+ "owner-presence-outbox",+ "lease-generation-outbox",+ "canonical-request-payload-terminal",+ "canonical-request-payload-budget",+ "submission-operation-id",+ "submission-actor-request",+)++_P1B_RETENTION_CASES = (+ "submission-lookup-precedes-gateway",+ "submission-replay-after-state-advance",+ "submission-changed-request-conflict",+ "receipt-update-rejected",+ "receipt-delete-rejected",+ "receipt-survives-campaign-delete",+ "receipt-survives-target-delete",+ "stored-result-independent-of-mutable-target",+)++_P1B_ATOMICITY_CASES = (+ "shared-authority-receipt-insert-rollback",+ "shared-budget-receipt-insert-rollback",+ "shared-admission-binding-insert-rollback",+ "shared-retry-receipt-insert-rollback",+ "shared-transition-receipt-insert-rollback",+ "shared-terminal-receipt-insert-rollback",+ "shared-outbox-receipt-insert-rollback",+ "shared-purge-receipt-insert-rollback",+ "shared-campaign-delete-receipt-insert-rollback",+ "exact-replay-no-duplicate-side-effects",+)++_P1B_CONCURRENCY_CASES = (+ "shared-submission-identical",+ "shared-authority-identical",+ "shared-transition-identical",+ "shared-budget-identical",+ "shared-outbox-identical",+ "shared-campaign-delete-identical",+)+++def _p1b_literal_spec(+ store: ExecutionLifecycleStore,+ operation_code: str,+ *,+ operation_id: str = _uuid(3000),+ primary_target_id: str = _uuid(3001),+):+ no_revision = operation_code in {+ "actor_authority_ensure",+ "campaign_authority_ensure",+ "budget_configure",+ "admission",+ "outbox_insert",+ "campaign_delete",+ }+ dual_revision = operation_code in {"budget_reserve", "budget_settle"}+ owner_bound = operation_code in {+ "outbox_claim",+ "outbox_reclaim",+ "outbox_renew",+ "outbox_publish",+ "outbox_retryable_failure",+ "outbox_nonretryable_failure",+ }+ return store._receipt_spec(+ operation_id=operation_id,+ operation_code=operation_code,+ campaign_id=_uuid(3002),+ primary_target_id=primary_target_id,+ secondary_target_id=_uuid(3003),+ principal_kind="actor",+ principal_subject_ref=_uuid(3004),+ principal_user_id=_uuid(3004),+ principal_authority_revision=7,+ expected_revision=None if no_revision else 9,+ secondary_expected_revision=11 if dual_revision else None,+ owner_ref=_uuid(3005) if owner_bound else None,+ lease_generation=3 if owner_bound else None,+ fields=(("literal_payload", "p1b"),),+ )+++def _p1b_independent_request_digest(operation_code: str) -> str:+ no_revision = operation_code in {+ "actor_authority_ensure",+ "campaign_authority_ensure",+ "budget_configure",+ "admission",+ "outbox_insert",+ "campaign_delete",+ }+ dual_revision = operation_code in {"budget_reserve", "budget_settle"}+ owner_bound = operation_code in {+ "outbox_claim",+ "outbox_reclaim",+ "outbox_renew",+ "outbox_publish",+ "outbox_retryable_failure",+ "outbox_nonretryable_failure",+ }+ return _independent_binding_digest(+ operation_code + ".request",+ (+ ("operation_id", _uuid(3000)),+ ("operation_code", operation_code),+ ("campaign_id_present", True),+ ("campaign_id", _uuid(3002)),+ ("primary_target_id", _uuid(3001)),+ ("secondary_target_id_present", True),+ ("secondary_target_id", _uuid(3003)),+ ("principal_kind", "actor"),+ ("principal_subject_ref", _uuid(3004)),+ ("principal_user_id_present", True),+ ("principal_user_id", _uuid(3004)),+ ("principal_authority_revision_present", True),+ ("principal_authority_revision", 7),+ ("expected_revision_present", not no_revision),+ ("expected_revision", None if no_revision else 9),+ ("secondary_expected_revision_present", dual_revision),+ ("secondary_expected_revision", 11 if dual_revision else None),+ ("owner_ref_present", owner_bound),+ ("owner_ref", _uuid(3005) if owner_bound else None),+ ("lease_generation_present", owner_bound),+ ("lease_generation", 3 if owner_bound else None),+ ("literal_payload", "p1b"),+ ),+ )+++async def _p1b_insert_literal_receipt(+ connection: aiosqlite.Connection,+ operation_code: str,+ *,+ operation_id: str = _uuid(3000),+) -> tuple[ExecutionLifecycleStore, Any]:+ store = ExecutionLifecycleStore(connection, "sqlite")+ spec = _p1b_literal_spec(store, operation_code, operation_id=operation_id)+ exact = (+ FixedResult.REPLAYED_BOUND_CHILD+ if operation_code == "retry"+ else FixedResult.REPLAYED_CLOSED+ if operation_code == "close_without_retry"+ else FixedResult.REPLAYED+ )+ async with store._transaction() as transaction:+ await store._insert_receipt(+ transaction,+ spec,+ result=FixedResult.APPLIED,+ exact_replay_code=exact,+ result_identity=_uuid(3001),+ result_revision=10,+ )+ return store, spec+++async def _p1b_admission_case() -> tuple[+ aiosqlite.Connection, ExecutionLifecycleStore, AdmissionRequest+]:+ connection = await _new_connection()+ await connection.execute(+ "INSERT INTO users(id,username,hashed_password,role,created_by) VALUES(?,?,?,?,?)",+ (_uuid(3100), "p1b-admission", "fixed-hash", "admin", "fixed"),+ )+ await connection.execute(+ "INSERT INTO campaigns(id,name) VALUES(?,?)", (_uuid(3101), "p1b-admission")+ )+ await connection.execute(+ "UPDATE execution_gateway_state SET mode='enforced',catalog_digest=?,"+ "activation_revision=1,activation_at=1,revision=1 WHERE singleton_id=1",+ ("c" * 64,),+ )+ await connection.commit()+ store = ExecutionLifecycleStore(connection, "sqlite")+ assert (+ await store.ensure_actor_authority(_uuid(3100), _uuid(3102))+ ).result is FixedResult.APPLIED+ assert (+ await store.ensure_campaign_authority(_uuid(3101), _uuid(3103))+ ).result is FixedResult.APPLIED+ snapshot = replace(+ _blocked_snapshot(),+ actor_role="admin",+ gateway_mode_snapshot="enforced",+ policy_verdict="blocked",+ policy_reason_mask=PolicyReasonBit.INSUFFICIENT_ROLE.value,+ )+ request = AdmissionRequest(+ _uuid(3104),+ _uuid(3105),+ _uuid(3106),+ _uuid(3107),+ _uuid(3108),+ _uuid(3101),+ _uuid(3100),+ _uuid(3100),+ "test.p1b",+ "sdk",+ AttemptState.BLOCKED,+ _uuid(3109),+ snapshot,+ )+ assert (+ await store._create_initial_execution_v2_for_migration_fixture(request)+ ).result is FixedResult.APPLIED+ return connection, store, request+++async def _p1b_public_snapshot(+ connection: aiosqlite.Connection,+) -> tuple[tuple[str, tuple[tuple[object, ...], ...]], ...]:+ tables = (+ "campaigns",+ "execution_actor_authority_revisions",+ "campaign_execution_authority_revisions",+ "campaign_execution_budgets",+ "campaign_execution_budget_ledger",+ "logical_executions",+ "execution_attempts",+ "execution_publication_outbox",+ "execution_operation_receipts",+ )+ snapshot = []+ for table in tables:+ rows = await (+ await connection.execute(+ f"SELECT * FROM {table} ORDER BY 1" # noqa: S608 - frozen table tuple.+ )+ ).fetchall()+ snapshot.append((table, tuple(tuple(row) for row in rows)))+ return tuple(snapshot)+++async def _p1b_prepare_admission() -> tuple[+ aiosqlite.Connection, ExecutionLifecycleStore, AdmissionRequest+]:+ connection = await _new_connection()+ await connection.execute(+ "INSERT INTO users(id,username,hashed_password,role,created_by) VALUES(?,?,?,?,?)",+ (_uuid(3400), "p1b-public-admission", "fixed-hash", "admin", "fixed"),+ )+ await connection.execute(+ "INSERT INTO campaigns(id,name) VALUES(?,?)",+ (_uuid(3401), "p1b-public-admission"),+ )+ await connection.execute(+ "UPDATE execution_gateway_state SET mode='enforced',catalog_digest=?,"+ "activation_revision=1,activation_at=1,revision=1 WHERE singleton_id=1",+ ("c" * 64,),+ )+ await connection.commit()+ store = ExecutionLifecycleStore(connection, "sqlite")+ assert (+ await store.ensure_actor_authority(_uuid(3400), _uuid(3402))+ ).result is FixedResult.APPLIED+ assert (+ await store.ensure_campaign_authority(_uuid(3401), _uuid(3403))+ ).result is FixedResult.APPLIED+ request = AdmissionRequest(+ _uuid(3404),+ _uuid(3405),+ _uuid(3406),+ _uuid(3407),+ _uuid(3408),+ _uuid(3401),+ _uuid(3400),+ _uuid(3400),+ "test.p1b.public",+ "sdk",+ AttemptState.BLOCKED,+ _uuid(3409),+ replace(+ _blocked_snapshot(),+ actor_role="admin",+ gateway_mode_snapshot="enforced",+ ),+ )+ return connection, store, request+++ ("_case_alias", "operation_code"),+ _P1B_AUTHORITY_CASES,+ ids=tuple(alias for alias, _code in _P1B_AUTHORITY_CASES),+)+def test_sqlite_p1b_independent_literal_binding_vector(+ _case_alias: str, operation_code: str+) -> None:+ assert tuple(alias for alias, _method in _P1B_PUBLIC_METHOD_MAP) == tuple(+ alias for alias, _code in _P1B_AUTHORITY_CASES+ )+ assert (_P1B_LITERAL_NODE_COUNT, len(_P1B_LITERAL_NODE_IDS_SHA256)) == (88, 64)+ store = ExecutionLifecycleStore(None, "sqlite")+ spec = _p1b_literal_spec(store, operation_code)+ assert spec.request_binding_digest == _p1b_independent_request_digest(operation_code)+++async def _p1b_run_public_triplet(+ connection: aiosqlite.Connection,+ apply_call: Any,+ replay_call: Any,+ conflict_call: Any,+) -> tuple[OperationResult, OperationResult, OperationResult, str]:+ applied = await apply_call()+ after_apply = await _p1b_public_snapshot(connection)+ replayed = await replay_call()+ after_replay = await _p1b_public_snapshot(connection)+ conflicted = await conflict_call()+ after_conflict = await _p1b_public_snapshot(connection)+ assert after_apply == after_replay == after_conflict, (+ "public operation replay or binding conflict duplicated a durable side effect"+ )+ receipt = await (+ await connection.execute(+ "SELECT operation_code FROM execution_operation_receipts ORDER BY rowid DESC LIMIT 1"+ )+ ).fetchone()+ return applied, replayed, conflicted, str(receipt[0])+++async def _p1b_insert_outbox_state(+ connection: aiosqlite.Connection,+ *,+ state: str,+ expired: bool = False,+ twentieth: bool = False,+) -> OutboxMutation:+ await _insert_retryable_attempt(connection)+ claimed = state == "claimed"+ terminal = state in {"published", "poisoned"}+ delivery_count = 20 if twentieth else (1 if state != "pending" else 0)+ revision = 20 if twentieth else (1 if state != "pending" else 0)+ owner = _uuid(3510) if claimed else None+ lease_generation = 20 if twentieth else (1 if claimed else 0)+ expires = 1 if expired else (MAX_I53 - OUTBOX_LEASE_MS - 1 if claimed else None)+ latest_code = (+ "nonretryable_failure"+ if state == "poisoned"+ else "publish"+ if state == "published"+ else "claim"+ if state == "claimed"+ else "insert"+ )+ failure = "delivery_nonretryable" if state == "poisoned" else None+ await connection.execute(+ "INSERT INTO execution_publication_outbox("+ "id,publication_key,attempt_id,campaign_id,event_code,is_attempt_terminal,"+ "publication_state,delivery_attempt_count,available_at,claim_owner_ref,"+ "lease_generation,claimed_at,lease_expires_at,published_at,poisoned_at,"+ "failure_code,claim_revision,latest_operation_id,latest_operation_code,"+ "latest_operation_base_revision,created_at) "+ "VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",+ (+ _uuid(3500),+ _uuid(3501),+ _uuid(6),+ _uuid(2),+ "recovery_required",+ 0,+ state,+ delivery_count,+ 1 if state == "pending" else None,+ owner,+ lease_generation,+ 1 if terminal or claimed else None,+ expires,+ 1 if state == "published" else None,+ 1 if state == "poisoned" else None,+ failure,+ revision,+ _uuid(3501) if state == "pending" else _uuid(3504),+ latest_code,+ max(0, revision - 1),+ 1,+ ),+ )+ await connection.commit()+ return OutboxMutation(+ _uuid(3500),+ revision,+ _uuid(3505),+ owner_ref=(+ _uuid(3511)+ if state == "pending"+ else _uuid(3510)+ if state == "claimed" and not twentieth+ else None+ ),+ lease_generation=(+ lease_generation if state in {"pending", "claimed"} and not twentieth else None+ ),+ campaign_id=_uuid(2),+ attempt_id=_uuid(6),+ publication_key=_uuid(3501),+ event_code="recovery_required",+ )+++async def _p1b_exercise_public_operation(+ case_alias: str, tmp_path: Any+) -> tuple[OperationResult, OperationResult, OperationResult, str]:+ if case_alias == "campaign-delete":+ database = AresDatabase(tmp_path / "p1b-public-delete.db")+ await database.connect()+ try:+ await database.conn.executemany(+ "INSERT INTO campaigns(id,name) VALUES(?,?)",+ (+ (_uuid(3600), "p1b-public-delete"),+ (_uuid(3601), "p1b-public-delete-conflict"),+ ),+ )+ await database.conn.commit()+ operation_id = _uuid(3602)+ return await _p1b_run_public_triplet(+ database.conn,+ lambda: database.delete_campaign_lifecycle(_uuid(3600), operation_id=operation_id),+ lambda: database.delete_campaign_lifecycle(_uuid(3600), operation_id=operation_id),+ lambda: database.delete_campaign_lifecycle(_uuid(3601), operation_id=operation_id),+ )+ finally:+ await database.close()++ if case_alias == "admission":+ connection, store, request = await _p1b_prepare_admission()+ try:+ applied = await store._create_initial_execution_v2_for_migration_fixture(request)+ after_apply = await _p1b_public_snapshot(connection)+ replayed = await store._create_initial_execution_v2_for_migration_fixture(request)+ after_replay = await _p1b_public_snapshot(connection)+ conflicted = await store._create_initial_execution_v2_for_migration_fixture(+ replace(request, module_id="test.p1b.public.changed")+ )+ after_conflict = await _p1b_public_snapshot(connection)+ assert after_apply == after_replay == after_conflict+ submission = await (+ await connection.execute(+ "SELECT admission_operation_id,submission_binding_contract_version,"+ "submission_result_code,submission_exact_replay_code "+ "FROM logical_executions WHERE campaign_id=? AND submission_id=?",+ (request.campaign_id, request.submission_id),+ )+ ).fetchone()+ receipt_count = await (+ await connection.execute(+ "SELECT count(*) FROM execution_operation_receipts WHERE operation_id=?",+ (request.operation_id,),+ )+ ).fetchone()+ assert tuple(submission) == (+ request.operation_id,+ 2,+ FixedResult.APPLIED.value,+ FixedResult.REPLAYED.value,+ )+ assert int(receipt_count[0]) == 0+ return applied, replayed, conflicted, "admission"+ finally:+ await connection.close()++ if case_alias in {"actor-authority-ensure", "actor-authority-invalidate"}:+ connection = await _new_connection()+ try:+ await connection.executemany(+ "INSERT INTO users(id,username,hashed_password,role,created_by) VALUES(?,?,?,?,?)",+ (+ (_uuid(3410), "p1b-public-actor", "fixed", "admin", "fixed"),+ (_uuid(3411), "p1b-public-actor-conflict", "fixed", "admin", "fixed"),+ ),+ )+ await connection.commit()+ store = ExecutionLifecycleStore(connection, "sqlite")+ operation_id = _uuid(3412)+ if case_alias.endswith("invalidate"):+ assert (+ await store.ensure_actor_authority(_uuid(3410), _uuid(3413))+ ).result is FixedResult.APPLIED++ async def apply() -> OperationResult:+ return await store.invalidate_actor_authority(_uuid(3410), 0, operation_id)++ async def conflict() -> OperationResult:+ return await store.invalidate_actor_authority(_uuid(3410), 1, operation_id)+ else:++ async def apply() -> OperationResult:+ return await store.ensure_actor_authority(_uuid(3410), operation_id)++ async def conflict() -> OperationResult:+ return await store.ensure_actor_authority(_uuid(3411), operation_id)++ return await _p1b_run_public_triplet(connection, apply, apply, conflict)+ finally:+ await connection.close()++ if case_alias in {"campaign-authority-ensure", "campaign-authority-invalidate"}:+ connection = await _new_connection()+ try:+ await connection.executemany(+ "INSERT INTO campaigns(id,name) VALUES(?,?)",+ (+ (_uuid(3420), "p1b-public-campaign"),+ (_uuid(3421), "p1b-public-campaign-conflict"),+ ),+ )+ await connection.commit()+ store = ExecutionLifecycleStore(connection, "sqlite")+ operation_id = _uuid(3422)+ if case_alias.endswith("invalidate"):+ assert (+ await store.ensure_campaign_authority(_uuid(3420), _uuid(3423))+ ).result is FixedResult.APPLIED++ async def apply() -> OperationResult:+ return await store.invalidate_campaign_authority(_uuid(3420), 0, operation_id)++ async def conflict() -> OperationResult:+ return await store.invalidate_campaign_authority(_uuid(3420), 1, operation_id)+ else:++ async def apply() -> OperationResult:+ return await store.ensure_campaign_authority(_uuid(3420), operation_id)++ async def conflict() -> OperationResult:+ return await store.ensure_campaign_authority(_uuid(3421), operation_id)++ return await _p1b_run_public_triplet(connection, apply, apply, conflict)+ finally:+ await connection.close()++ if case_alias in {"budget-configure", "budget-reserve", "budget-settle"}:+ connection = await _new_connection()+ try:+ await _insert_retryable_attempt(connection)+ store = ExecutionLifecycleStore(connection, "sqlite")+ configuration = BudgetConfiguration(+ _uuid(2), _uuid(3430), 20, _uuid(3431), 20, _uuid(3432), 2, _uuid(3433)+ )+ if case_alias == "budget-configure":+ return await _p1b_run_public_triplet(+ connection,+ lambda: store.configure_campaign_budgets(configuration),+ lambda: store.configure_campaign_budgets(configuration),+ lambda: store.configure_campaign_budgets(+ replace(configuration, noise_capacity=19)+ ),+ )+ assert (+ await store.configure_campaign_budgets(configuration)+ ).result is FixedResult.APPLIED+ reservation = BudgetReservation(+ _uuid(2),+ _uuid(6),+ _uuid(3430),+ _uuid(3434),+ 4,+ 0,+ _uuid(3431),+ _uuid(3435),+ 5,+ 0,+ _uuid(3432),+ _uuid(3436),+ 0,+ _uuid(3437),+ )+ if case_alias == "budget-reserve":+ return await _p1b_run_public_triplet(+ connection,+ lambda: store.reserve_budgets(reservation),+ lambda: store.reserve_budgets(reservation),+ lambda: store.reserve_budgets(replace(reservation, noise_units=3)),+ )+ assert (await store.reserve_budgets(reservation)).result is FixedResult.APPLIED+ settlement = BudgetSettlement(+ _uuid(2),+ _uuid(6),+ _uuid(3430),+ 4,+ 3,+ 1,+ _uuid(3431),+ 5,+ 2,+ 1,+ _uuid(3432),+ 1,+ _uuid(3438),+ )+ return await _p1b_run_public_triplet(+ connection,+ lambda: store.settle_budgets(settlement),+ lambda: store.settle_budgets(settlement),+ lambda: store.settle_budgets(replace(settlement, noise_actual=2)),+ )+ finally:+ await connection.close()++ if case_alias in {"retry-attempt", "close-without-retry"}:+ connection = await _new_connection()+ try:+ await _insert_retryable_attempt(connection)+ store = ExecutionLifecycleStore(connection, "sqlite")+ if case_alias == "close-without-retry":+ request = ClosureRequest(+ _uuid(4), _uuid(6), _uuid(3440), 0, _uuid(3441), _uuid(1), _uuid(1), 0, _uuid(2)+ )+ return await _p1b_run_public_triplet(+ connection,+ lambda: store.close_without_retry(request),+ lambda: store.close_without_retry(request),+ lambda: store.close_without_retry(replace(request, outbox_id=_uuid(3442))),+ )+ child = AdmissionRequest(+ _uuid(4),+ _uuid(3443),+ _uuid(3444),+ _uuid(3445),+ _uuid(3446),+ _uuid(2),+ _uuid(1),+ _uuid(1),+ "test.p1b.retry",+ "sdk",+ AttemptState.BLOCKED,+ _uuid(3447),+ replace(_blocked_snapshot(), actor_role="admin"),+ )+ request = RetryRequest(_uuid(4), _uuid(6), child, 0)+ return await _p1b_run_public_triplet(+ connection,+ lambda: store._create_retry_attempt_v2_for_migration_fixture(request),+ lambda: store._create_retry_attempt_v2_for_migration_fixture(request),+ lambda: store._create_retry_attempt_v2_for_migration_fixture(+ replace(request, child=replace(child, module_id="test.p1b.retry.changed"))+ ),+ )+ finally:+ await connection.close()++ if case_alias.startswith("outbox-"):+ state = "pending" if case_alias == "outbox-claim" else "claimed"+ connection = await _new_connection()+ try:+ request = await _p1b_insert_outbox_state(+ connection,+ state=state,+ expired=case_alias in {"outbox-reclaim", "outbox-poison"},+ twentieth=case_alias == "outbox-poison",+ )+ if case_alias == "outbox-reclaim":+ request = replace(request, owner_ref=_uuid(3511))+ store = ExecutionLifecycleStore(connection, "sqlite")+ changed = replace(request, event_code="logical_execution_closed")+ if case_alias == "outbox-claim":++ async def call(candidate=request):+ return await store.claim_outbox(candidate)+ elif case_alias == "outbox-reclaim":++ async def call(candidate=request):+ return await store.claim_outbox(candidate, reclaim=True)+ elif case_alias == "outbox-poison":++ async def call(candidate=request):+ return await store.poison_expired_attempt_twenty(candidate)+ elif case_alias == "outbox-renew":++ async def call(candidate=request):+ return await store.renew_outbox(candidate)+ elif case_alias == "outbox-publish":++ async def call(candidate=request):+ return await store.publish_outbox(candidate)+ elif case_alias == "outbox-fail-retryable":++ async def call(candidate=request):+ return await store.fail_outbox(candidate, retryable=True)+ elif case_alias == "outbox-fail-nonretryable":++ async def call(candidate=request):+ return await store.fail_outbox(candidate, retryable=False)+ else:+ prior = replace(request, operation_id=_uuid(3506))+ published = await store.publish_outbox(prior)+ assert published.result is FixedResult.APPLIED+ request = replace(+ request,+ expected_revision=published.revision,+ operation_id=_uuid(3505),+ owner_ref=None,+ lease_generation=None,+ purge_poisoned=False,+ )+ changed = replace(request, event_code="logical_execution_closed")++ async def call(candidate=request):+ return await store.purge_outbox(+ candidate.outbox_id,+ candidate.expected_revision,+ candidate.operation_id,+ poisoned=bool(candidate.purge_poisoned),+ campaign_id=candidate.campaign_id,+ attempt_id=candidate.attempt_id,+ publication_key=candidate.publication_key,+ event_code=candidate.event_code,+ )++ return await _p1b_run_public_triplet(+ connection,+ call,+ call,+ lambda: call(changed),+ )+ finally:+ await connection.close()++ connection, store = await _new_transition_case(":memory:", AttemptState.ACCEPTED)+ try:+ if case_alias == "attempt-transition":+ request = TransitionRequest(+ _uuid(210),+ 0,+ AttemptState.QUEUED,+ _uuid(3450),+ campaign_id=_uuid(201),+ actor_subject_ref=_uuid(200),+ actor_user_id=_uuid(200),+ actor_authority_revision=0,+ )+ return await _p1b_run_public_triplet(+ connection,+ lambda: store.transition_attempt(request),+ lambda: store.transition_attempt(request),+ lambda: store.transition_attempt(+ replace(request, target_state=AttemptState.CANCELLING)+ ),+ )++ dispatched = await _nonterminal_transition(+ store, connection, AttemptState.DISPATCHING, 3451+ )+ assert dispatched.result is FixedResult.APPLIED+ running = await _nonterminal_transition(store, connection, AttemptState.RUNNING, 3452)+ assert running.result is FixedResult.APPLIED+ if case_alias in {"settlement-pending", "expired-lease-settlement"}:+ request = TransitionRequest(+ _uuid(210),+ 2,+ AttemptState.SETTLEMENT_PENDING,+ _uuid(3453),+ owner_ref=_uuid(220),+ lease_generation=1,+ outbox_id=_uuid(3454),+ publication_key=_uuid(3455),+ campaign_id=_uuid(201),+ )+ active_store = (+ _AdvancedClockLifecycleStore(connection, "sqlite")+ if case_alias == "expired-lease-settlement"+ else store+ )+ method = (+ active_store.mark_expired_lease_settlement_pending+ if case_alias == "expired-lease-settlement"+ else active_store.enter_settlement_pending+ )+ return await _p1b_run_public_triplet(+ connection,+ lambda: method(request),+ lambda: method(request),+ lambda: method(replace(request, publication_key=_uuid(3456))),+ )++ assert case_alias == "terminal-commit"+ transition = TransitionRequest(+ _uuid(210),+ 2,+ AttemptState.FAILED,+ _uuid(3457),+ owner_ref=_uuid(220),+ lease_generation=1,+ outcome_code=OutcomeCode.CONFIRMED_FAILURE,+ authoritative_proof="worker_terminal_ack",+ campaign_id=_uuid(201),+ )+ request = TerminalCommitRequest(+ _uuid(208),+ _uuid(201),+ _uuid(3458),+ _uuid(3459),+ transition,+ BudgetSettlement(+ _uuid(201),+ _uuid(210),+ _uuid(204),+ 2,+ 0,+ 1,+ _uuid(205),+ 3,+ 0,+ 1,+ _uuid(206),+ 1,+ _uuid(3460),+ ),+ )+ return await _p1b_run_public_triplet(+ connection,+ lambda: store.commit_terminal_attempt(request),+ lambda: store.commit_terminal_attempt(request),+ lambda: store.commit_terminal_attempt(replace(request, publication_key=_uuid(3461))),+ )+ finally:+ await connection.close()+++ ("case_alias", "_operation_code"),+ _P1B_AUTHORITY_CASES,+ ids=tuple(alias for alias, _code in _P1B_AUTHORITY_CASES),+)+async def test_sqlite_p1b_each_public_authority_replays_exactly(+ case_alias: str, _operation_code: str, tmp_path+) -> None:+ applied, replayed, conflicted, recorded_operation_code = await _p1b_exercise_public_operation(+ case_alias, tmp_path+ )+ expected_replay = (+ FixedResult.REPLAYED_BOUND_CHILD+ if case_alias == "retry-attempt"+ else FixedResult.REPLAYED_CLOSED+ if case_alias == "close-without-retry"+ else FixedResult.REPLAYED+ )+ assert (applied.result, replayed.result, conflicted.result) == (+ FixedResult.APPLIED,+ expected_replay,+ FixedResult.CONFLICT_OPERATION,+ )+ assert recorded_operation_code == _operation_code++[email protected]("case_alias", _P1B_BINDING_MUTATIONS, ids=_P1B_BINDING_MUTATIONS)+async def test_sqlite_p1b_each_binding_mutation_conflicts(case_alias: str) -> None:+ if case_alias.startswith("submission-"):+ connection, store, request = await _p1b_admission_case()+ try:+ changed = (+ replace(request, operation_id=_uuid(3110))+ if case_alias == "submission-operation-id"+ else replace(request, module_id="test.p1b.changed")+ )+ result = await store._create_initial_execution_v2_for_migration_fixture(changed)+ finally:+ await connection.close()+ assert result.result is FixedResult.CONFLICT_OPERATION+ return+ connection = await _new_connection()+ try:+ operation_code = (+ "budget_reserve"+ if case_alias.startswith("secondary-expected-")+ or case_alias == "canonical-request-payload-budget"+ else "outbox_claim"+ if case_alias in {"owner-presence-outbox", "lease-generation-outbox"}+ else "retry"+ if case_alias == "secondary-target-retry"+ else "terminal_failed"+ if case_alias == "canonical-request-payload-terminal"+ else "queue"+ )+ store, spec = await _p1b_insert_literal_receipt(connection, operation_code)+ mutations = {+ "operation-code-transition": {"operation_code": "dispatch"},+ "primary-target-transition": {"primary_target_id": _uuid(3010)},+ "secondary-target-retry": {"secondary_target_id": _uuid(3011)},+ "campaign-transition": {"campaign_id": _uuid(3012)},+ "principal-kind-transition": {"principal_kind": "resolver"},+ "principal-subject-transition": {"principal_subject_ref": _uuid(3013)},+ "principal-user-transition": {"principal_user_id": _uuid(3014)},+ "principal-authority-revision-transition": {"principal_authority_revision": 8},+ "expected-revision-presence-transition": {"expected_revision": None},+ "expected-revision-value-transition": {"expected_revision": 10},+ "secondary-expected-presence-budget": {"secondary_expected_revision": None},+ "secondary-expected-value-budget": {"secondary_expected_revision": 12},+ "owner-presence-outbox": {"owner_ref": None, "lease_generation": None},+ "lease-generation-outbox": {"lease_generation": 4},+ "canonical-request-payload-terminal": {"request_binding_digest": "a" * 64},+ "canonical-request-payload-budget": {"request_binding_digest": "b" * 64},+ }+ changed = replace(spec, **mutations[case_alias])+ async with store._transaction() as transaction:+ result = await store._classify_receipt(transaction, changed, current_revision=None)+ finally:+ await connection.close()+ assert (result.result, result.revision) == (FixedResult.CONFLICT_OPERATION, None)++[email protected]("case_alias", _P1B_RETENTION_CASES, ids=_P1B_RETENTION_CASES)+async def test_sqlite_p1b_submission_and_receipt_retention_contract(case_alias: str) -> None:+ if case_alias.startswith("submission-"):+ connection, store, request = await _p1b_admission_case()+ try:+ if case_alias == "submission-lookup-precedes-gateway":+ await connection.execute(+ "UPDATE execution_gateway_state SET mode='emergency_disabled',"+ "catalog_digest=?,activation_revision=2,activation_at=2,"+ "revision=revision+1",+ ("d" * 64,),+ )+ await connection.commit()+ candidate = request+ elif case_alias == "submission-replay-after-state-advance":+ await connection.execute(+ "UPDATE logical_executions SET revision=revision+1 WHERE id=?",+ (request.logical_execution_id,),+ )+ await connection.commit()+ candidate = request+ else:+ candidate = replace(request, module_id="test.p1b.changed")+ result = await store._create_initial_execution_v2_for_migration_fixture(candidate)+ finally:+ await connection.close()+ assert result.result is (+ FixedResult.CONFLICT_OPERATION+ if case_alias == "submission-changed-request-conflict"+ else FixedResult.REPLAYED+ )+ return+ connection = await _new_connection()+ try:+ store, spec = await _p1b_insert_literal_receipt(connection, "outbox_purge")+ if case_alias == "receipt-update-rejected":+ with pytest.raises(+ sqlite3.IntegrityError,+ match="immutable execution operation receipt",+ ):+ await connection.execute(+ "UPDATE execution_operation_receipts SET result_revision=result_revision+1"+ )+ elif case_alias == "receipt-delete-rejected":+ with pytest.raises(+ sqlite3.IntegrityError,+ match="immutable execution operation receipt",+ ):+ await connection.execute("DELETE FROM execution_operation_receipts")+ else:+ async with store._transaction() as transaction:+ result = await store._classify_receipt(transaction, spec, current_revision=None)+ assert (result.result, result.revision) == (FixedResult.REPLAYED, 10)+ finally:+ await connection.close()++[email protected]("case_alias", _P1B_ATOMICITY_CASES, ids=_P1B_ATOMICITY_CASES)+async def test_sqlite_p1b_receipt_atomicity_and_nonduplication(+ case_alias: str, monkeypatch+) -> None:+ connection = await _new_connection()+ store = ExecutionLifecycleStore(connection, "sqlite")+ try:+ if case_alias == "exact-replay-no-duplicate-side-effects":+ store, spec = await _p1b_insert_literal_receipt(connection, "actor_authority_ensure")+ async with store._transaction() as transaction:+ replay = await store._classify_receipt(transaction, spec, current_revision=None)+ assert (replay.result, replay.revision) == (FixedResult.REPLAYED, 10)+ else:+ await connection.execute(+ "INSERT INTO users(id,username,hashed_password,role,created_by) VALUES(?,?,?,?,?)",+ (_uuid(3200), "p1b-atomic", "fixed", "admin", "fixed"),+ )+ await connection.commit()++ async def fail_receipt(*_args, **_kwargs) -> None:+ raise RuntimeError("fixed-p1b-receipt-failure")++ monkeypatch.setattr(store, "_insert_receipt", fail_receipt)+ with pytest.raises(RuntimeError, match="fixed-p1b-receipt-failure"):+ await store.ensure_actor_authority(_uuid(3200), _uuid(3201))+ authority = int(+ (+ await (+ await connection.execute(+ "SELECT count(*) FROM execution_actor_authority_revisions "+ "WHERE user_id=?",+ (_uuid(3200),),+ )+ ).fetchone()+ )[0]+ )+ assert authority == 0+ receipt_row = await (+ await connection.execute("SELECT count(*) FROM execution_operation_receipts")+ ).fetchone()+ receipts = int(receipt_row[0])+ finally:+ await connection.close()+ assert receipts == (1 if case_alias == "exact-replay-no-duplicate-side-effects" else 0)++[email protected]("_case_alias", _P1B_CONCURRENCY_CASES, ids=_P1B_CONCURRENCY_CASES)+async def test_sqlite_p1b_identical_operation_concurrency(tmp_path, _case_alias: str) -> None:+ path = (tmp_path / "p1b-identical.db").as_posix()+ first = await _new_connection(path)+ await first.execute(+ "INSERT INTO users(id,username,hashed_password,role,created_by) VALUES(?,?,?,?,?)",+ (_uuid(3300), "p1b-race", "fixed", "admin", "fixed"),+ )+ await first.commit()+ second = await aiosqlite.connect(path)+ second.row_factory = aiosqlite.Row+ await second.execute("PRAGMA foreign_keys=ON")+ try:+ results = await asyncio.gather(+ ExecutionLifecycleStore(first, "sqlite").ensure_actor_authority(+ _uuid(3300), _uuid(3301)+ ),+ ExecutionLifecycleStore(second, "sqlite").ensure_actor_authority(+ _uuid(3300), _uuid(3301)+ ),+ )+ observed = await (+ await first.execute(+ "SELECT (SELECT count(*) FROM execution_actor_authority_revisions),"+ "(SELECT count(*) FROM execution_operation_receipts)"+ )+ ).fetchone()+ finally:+ await second.close()+ await first.close()+ assert {result.result for result in results} == {FixedResult.APPLIED, FixedResult.REPLAYED}+ assert tuple(observed) == (1, 1)+++def _blocked_snapshot() -> AttemptPolicySnapshot:+ return AttemptPolicySnapshot(+ actor_authority_revision=0,+ campaign_authority_revision=0,+ destination_authority_revision=0,+ credential_authority_revision=0,+ evaluation_mode="live",+ request_structure_valid=True,+ canonicalization_complete=True,+ unknown_fields_absent=True,+ alternate_transport_absent=True,+ bounded_shape_valid=True,+ request_shape_units=1,+ descriptor_semantic_digest="a" * 64,+ catalog_digest="b" * 64,+ trusted_first_party_binding=True,+ descriptor_binding_current=True,+ descriptor_complete=True,+ static_policy_evaluable=True,+ minimum_role="operator",+ noise_class="low",+ approval_policy="none",+ required_capability_mask=1,+ descriptor_blocker_mask=0,+ preview_ready=False,+ lifecycle_ready=False,+ result_authority_ready=False,+ transport_ready=False,+ future_gateway_eligible=False,+ authority_snapshots_complete=True,+ authority_revisions_current=True,+ actor_authenticated=True,+ actor_active=True,+ actor_role="reporter",+ campaign_active=True,+ actor_campaign_authorized=True,+ approval_present=False,+ approval_current=False,+ approval_exactly_bound=False,+ granted_capability_mask=0,+ destination_extraction_complete=True,+ destinations_in_scope=True,+ credential_authority_resolved=True,+ credential_authority_current=True,+ opaque_handles_only=True,+ permitted_handle_kinds_only=True,+ raw_credentials_absent=True,+ ambient_credentials_absent=True,+ budget_authority_resolved=True,+ budget_authority_current=True,+ budget_capacity_available=False,+ gateway_mode_snapshot="disabled",+ gateway_decision_code="none",+ policy_evaluation_state="evaluated",+ policy_verdict="blocked",+ policy_reason_mask=PolicyReasonBit.INSUFFICIENT_ROLE.value,+ external_effect_class="read_only",+ idempotency_class="unproven_current_contract",+ retry_policy="blocked_unproven_prior_attempt",+ retry_disposition="forbidden",+ cancellation_ownership="unproven_current_contract",+ compensation_class="unproven_current_contract",+ timeout_origin="observed_legacy_engine_default",+ timeout_limit_ms=1_000,+ timeout_settlement="unproven_current_contract",+ )+++async def _persist_role_cell(actor: str, minimum: str, satisfies: bool) -> tuple[str, FixedResult]:+ connection = await _new_connection()+ try:+ await connection.execute(+ "INSERT INTO users(id,username,hashed_password,role,created_by) VALUES(?,?,?,?,?)",+ (_uuid(110), "role-cell", "fixed-hash", actor, "fixed"),+ )+ await connection.execute(+ "INSERT INTO campaigns(id,name) VALUES(?,?)", (_uuid(111), "role-cell")+ )+ await connection.execute(+ "UPDATE execution_gateway_state SET mode='enforced',catalog_digest=?,"+ "activation_revision=1,activation_at=1,revision=1 WHERE singleton_id=1",+ ("c" * 64,),+ )+ await connection.commit()+ store = ExecutionLifecycleStore(connection, "sqlite")+ assert (+ await store.ensure_actor_authority(_uuid(110), _uuid(112))+ ).result is FixedResult.APPLIED, "actor authority setup failed"+ assert (+ await store.ensure_campaign_authority(_uuid(111), _uuid(113))+ ).result is FixedResult.APPLIED, "campaign authority setup failed"+ budgets = None+ initial_state = AttemptState.BLOCKED+ snapshot = replace(+ _blocked_snapshot(),+ actor_role=actor,+ minimum_role=minimum,+ gateway_mode_snapshot="enforced",+ policy_verdict="blocked",+ policy_reason_mask=PolicyReasonBit.INSUFFICIENT_ROLE.value,+ )+ if satisfies:+ configured = await store.configure_campaign_budgets(+ BudgetConfiguration(+ _uuid(111), _uuid(114), 10, _uuid(115), 10, _uuid(116), 1, _uuid(117)+ )+ )+ assert configured.result is FixedResult.APPLIED, "budget setup failed"+ budgets = BudgetReservation(+ _uuid(111),+ _uuid(120),+ _uuid(114),+ _uuid(121),+ 1,+ 0,+ _uuid(115),+ _uuid(122),+ 1,+ 0,+ _uuid(116),+ _uuid(123),+ 0,+ _uuid(124),+ )+ initial_state = AttemptState.ACCEPTED+ snapshot = replace(+ snapshot,+ preview_ready=True,+ lifecycle_ready=True,+ result_authority_ready=True,+ transport_ready=True,+ future_gateway_eligible=True,+ budget_capacity_available=True,+ gateway_mode_snapshot="enforced",+ granted_capability_mask=1,+ policy_verdict="live_candidate",+ policy_reason_mask=0,+ )+ result = await store._create_initial_execution_v2_for_migration_fixture(+ AdmissionRequest(+ _uuid(118),+ _uuid(119),+ _uuid(120),+ _uuid(125) if not satisfies else None,+ _uuid(126) if not satisfies else None,+ _uuid(111),+ _uuid(110),+ _uuid(110),+ "test.role-cell",+ "sdk",+ initial_state,+ _uuid(127),+ snapshot,+ budgets=budgets,+ )+ )+ row = await (+ await connection.execute(+ "SELECT state FROM execution_attempts WHERE id=?", (_uuid(120),)+ )+ ).fetchone()+ return str(row[0]), result.result+ finally:+ await connection.close()+++def _accepted_snapshot() -> AttemptPolicySnapshot:+ return replace(+ _blocked_snapshot(),+ actor_role="operator",+ granted_capability_mask=1,+ preview_ready=True,+ lifecycle_ready=True,+ result_authority_ready=True,+ transport_ready=True,+ future_gateway_eligible=True,+ budget_capacity_available=True,+ gateway_mode_snapshot="enforced",+ policy_verdict="live_candidate",+ policy_reason_mask=0,+ )+++_ACCEPTANCE_FACT_MUTATIONS = (+ ("evaluation-mode", "evaluation_mode", "preview"),+ ("request-structure", "request_structure_valid", False),+ ("canonicalization", "canonicalization_complete", False),+ ("unknown-fields", "unknown_fields_absent", False),+ ("alternate-transport", "alternate_transport_absent", False),+ ("bounded-shape", "bounded_shape_valid", False),+ ("descriptor-trust", "trusted_first_party_binding", False),+ ("descriptor-current", "descriptor_binding_current", False),+ ("descriptor-complete", "descriptor_complete", False),+ ("static-policy", "static_policy_evaluable", False),+ ("descriptor-blocker", "descriptor_blocker_mask", 1),+ ("preview-ready", "preview_ready", False),+ ("lifecycle-ready", "lifecycle_ready", False),+ ("result-ready", "result_authority_ready", False),+ ("transport-ready", "transport_ready", False),+ ("gateway-eligible", "future_gateway_eligible", False),+ ("authority-snapshots", "authority_snapshots_complete", False),+ ("authority-current", "authority_revisions_current", False),+ ("actor-authenticated", "actor_authenticated", False),+ ("actor-active", "actor_active", False),+ ("campaign-active", "campaign_active", False),+ ("campaign-authorized", "actor_campaign_authorized", False),+ ("minimum-role", "minimum_role", "admin"),+ ("high-noise", "noise_class", "high_noise"),+ ("capability-all-of", "granted_capability_mask", 0),+ ("destination-extraction", "destination_extraction_complete", False),+ ("destination-scope", "destinations_in_scope", False),+ ("credential-resolved", "credential_authority_resolved", False),+ ("credential-current", "credential_authority_current", False),+ ("opaque-handles", "opaque_handles_only", False),+ ("handle-kinds", "permitted_handle_kinds_only", False),+ ("raw-credentials", "raw_credentials_absent", False),+ ("ambient-credentials", "ambient_credentials_absent", False),+ ("budget-resolved", "budget_authority_resolved", False),+ ("budget-current", "budget_authority_current", False),+ ("budget-capacity", "budget_capacity_available", False),+ ("gateway-decision", "gateway_decision_code", "emergency_disabled"),+ ("policy-state", "policy_evaluation_state", "not_evaluated"),+ ("policy-verdict", "policy_verdict", "preview_ready"),+ ("policy-reason", "policy_reason_mask", 1),+)+++ ("_case", "field_name", "mutant"),+ _ACCEPTANCE_FACT_MUTATIONS,+ ids=tuple(item[0] for item in _ACCEPTANCE_FACT_MUTATIONS),+)+async def test_each_acceptance_fact_fails_before_insert(+ _case: str, field_name: str, mutant: object+) -> None:+ connection = await _new_connection()+ try:+ await connection.execute(+ "INSERT INTO users(id,username,hashed_password,role,created_by) VALUES(?,?,?,?,?)",+ (_uuid(940), "admission-fact", "fixed-hash", "operator", "fixed"),+ )+ await connection.execute(+ "INSERT INTO campaigns(id,name) VALUES(?,?)", (_uuid(941), "admission-fact")+ )+ await connection.execute(+ "UPDATE execution_gateway_state SET mode='enforced',catalog_digest=?,"+ "activation_revision=1,activation_at=1,revision=1 WHERE singleton_id=1",+ ("c" * 64,),+ )+ await connection.commit()+ store = ExecutionLifecycleStore(connection, "sqlite")+ assert (+ await store.ensure_actor_authority(_uuid(940), _uuid(942))+ ).result is FixedResult.APPLIED, "admission actor setup failed"+ assert (+ await store.ensure_campaign_authority(_uuid(941), _uuid(943))+ ).result is FixedResult.APPLIED, "admission campaign setup failed"+ assert (+ await store.configure_campaign_budgets(+ BudgetConfiguration(+ _uuid(941), _uuid(944), 10, _uuid(945), 10, _uuid(946), 1, _uuid(947)+ )+ )+ ).result is FixedResult.APPLIED, "admission budget setup failed"+ snapshot = replace(_accepted_snapshot(), actor_role="operator", **{field_name: mutant})+ request = AdmissionRequest(+ _uuid(948),+ _uuid(949),+ _uuid(950),+ None,+ None,+ _uuid(941),+ _uuid(940),+ _uuid(940),+ "test.admission-fact",+ "sdk",+ AttemptState.ACCEPTED,+ _uuid(951),+ snapshot,+ budgets=BudgetReservation(+ _uuid(941),+ _uuid(950),+ _uuid(944),+ _uuid(952),+ 1,+ 0,+ _uuid(945),+ _uuid(953),+ 1,+ 0,+ _uuid(946),+ _uuid(954),+ 0,+ _uuid(955),+ ),+ )+ result = await store._create_initial_execution_v2_for_migration_fixture(request)+ counts = await (+ await connection.execute(+ "SELECT (SELECT count(*) FROM logical_executions),"+ "(SELECT count(*) FROM execution_attempts),"+ "(SELECT count(*) FROM campaign_execution_budget_ledger)"+ )+ ).fetchone()+ finally:+ await connection.close()+ assert result.result is not FixedResult.APPLIED, "invalid acceptance fact committed"+ assert tuple(counts) == (0, 0, 0), "invalid acceptance fact left partial state"+++class _AdvancedClockLifecycleStore(ExecutionLifecycleStore):+ @property+ def _now_sql(self) -> str:+ return "9007199254740990"+++async def _new_transition_case(+ path: str, initial: AttemptState+) -> tuple[aiosqlite.Connection, ExecutionLifecycleStore]:+ connection = await _new_connection(path)+ await connection.execute(+ "INSERT INTO users(id,username,hashed_password,role,created_by) VALUES(?,?,?,?,?)",+ (_uuid(200), "transition-admin", "fixed-hash", "admin", "fixed"),+ )+ await connection.execute(+ "INSERT INTO campaigns(id,name) VALUES(?,?)", (_uuid(201), "transition-case")+ )+ await connection.execute(+ "UPDATE execution_gateway_state SET mode='enforced',catalog_digest=?,"+ "activation_revision=1,activation_at=1,revision=1 WHERE singleton_id=1",+ ("c" * 64,),+ )+ await connection.commit()+ store = ExecutionLifecycleStore(connection, "sqlite")+ assert (+ await store.ensure_actor_authority(_uuid(200), _uuid(202))+ ).result is FixedResult.APPLIED, "transition actor authority setup failed"+ assert (+ await store.ensure_campaign_authority(_uuid(201), _uuid(203))+ ).result is FixedResult.APPLIED, "transition campaign authority setup failed"+ if initial is AttemptState.ACCEPTED:+ assert (+ await store.configure_campaign_budgets(+ BudgetConfiguration(+ _uuid(201), _uuid(204), 20, _uuid(205), 20, _uuid(206), 1, _uuid(207)+ )+ )+ ).result is FixedResult.APPLIED, "transition budget setup failed"+ budgets = BudgetReservation(+ _uuid(201),+ _uuid(210),+ _uuid(204),+ _uuid(214),+ 2,+ 0,+ _uuid(205),+ _uuid(215),+ 3,+ 0,+ _uuid(206),+ _uuid(216),+ 0,+ _uuid(217),+ )+ request = AdmissionRequest(+ _uuid(208),+ _uuid(209),+ _uuid(210),+ None,+ None,+ _uuid(201),+ _uuid(200),+ _uuid(200),+ "test.transition",+ "sdk",+ AttemptState.ACCEPTED,+ _uuid(211),+ replace(_accepted_snapshot(), actor_role="admin"),+ budgets=budgets,+ )+ else:+ snapshot = replace(+ _blocked_snapshot(),+ actor_role="admin",+ gateway_mode_snapshot="enforced",+ policy_verdict="rejected" if initial is AttemptState.REJECTED else "blocked",+ policy_reason_mask=(+ PolicyReasonBit.INVALID_REQUEST.value+ if initial is AttemptState.REJECTED+ else PolicyReasonBit.INSUFFICIENT_ROLE.value+ ),+ )+ request = AdmissionRequest(+ _uuid(208),+ _uuid(209),+ _uuid(210),+ _uuid(212),+ _uuid(213),+ _uuid(201),+ _uuid(200),+ _uuid(200),+ "test.transition",+ "sdk",+ initial,+ _uuid(211),+ snapshot,+ )+ assert (+ await store._create_initial_execution_v2_for_migration_fixture(request)+ ).result is FixedResult.APPLIED, "transition admission setup failed"+ await connection.execute(+ "INSERT INTO hosts(id,campaign_id,ip_address) VALUES(?,?,?)",+ (_uuid(260), _uuid(201), "192.0.2.1"),+ )+ await connection.commit()+ return connection, store+++async def _attempt_row(connection: aiosqlite.Connection):+ return await (+ await connection.execute(+ "SELECT state,revision,dispatch_owner_ref,lease_generation,"+ "cancellation_request_revision,start_operation_id FROM execution_attempts "+ "WHERE id=?",+ (_uuid(210),),+ )+ ).fetchone()+++async def _nonterminal_transition(+ store: ExecutionLifecycleStore,+ connection: aiosqlite.Connection,+ target: AttemptState,+ operation_number: int,+):+ row = await _attempt_row(connection)+ state = AttemptState(str(row[0]))+ revision = int(row[1])+ dispatched = row[2] is not None+ values: dict[str, object] = {}+ if target is AttemptState.DISPATCHING:+ values = {"owner_ref": _uuid(220), "lease_generation": 1, "lease_duration_ms": 1_000}+ elif dispatched:+ values = {"owner_ref": _uuid(220), "lease_generation": int(row[3])}+ if state is AttemptState.CANCELLING:+ values["cancellation_request_revision"] = int(row[4])+ values["campaign_id"] = _uuid(201)+ if "owner_ref" not in values:+ values.update(+ actor_subject_ref=_uuid(200),+ actor_user_id=_uuid(200),+ actor_authority_revision=0,+ )+ request = TransitionRequest(_uuid(210), revision, target, _uuid(operation_number), **values)+ if target is AttemptState.SETTLEMENT_PENDING:+ request = replace(+ request,+ outbox_id=_uuid(operation_number + 1),+ publication_key=_uuid(operation_number + 2),+ )+ return await store.enter_settlement_pending(request)+ return await store.transition_attempt(request)+++async def _terminal_transition(+ store: ExecutionLifecycleStore,+ connection: aiosqlite.Connection,+ target: AttemptState,+ operation_number: int,+):+ row = await _attempt_row(connection)+ state = AttemptState(str(row[0]))+ revision = int(row[1])+ started = row[5] is not None+ values: dict[str, object] = {}+ if row[2] is not None and target is not AttemptState.INDETERMINATE:+ values.update(owner_ref=_uuid(220), lease_generation=int(row[3]))+ if state is AttemptState.CANCELLING:+ values["cancellation_request_revision"] = int(row[4])+ outcome = {+ AttemptState.SUCCEEDED: OutcomeCode.CONFIRMED_SUCCESS,+ AttemptState.PARTIAL: OutcomeCode.CONFIRMED_PARTIAL,+ AttemptState.SKIPPED: OutcomeCode.ORCHESTRATION_SKIPPED,+ AttemptState.CANCELLED: OutcomeCode.CONFIRMED_CANCELLED_NO_RESULT,+ AttemptState.TIMED_OUT: OutcomeCode.CONFIRMED_TIMEOUT_TERMINATED,+ AttemptState.INDETERMINATE: OutcomeCode.UNKNOWN_AFTER_RECOVERY,+ }.get(target)+ if target is AttemptState.FAILED:+ outcome = (+ OutcomeCode.CONFIRMED_FAILURE if started else OutcomeCode.CONFIRMED_FAILURE_NO_DISPATCH+ )+ proof = {+ AttemptState.SUCCEEDED: "worker_terminal_ack",+ AttemptState.PARTIAL: "worker_terminal_ack",+ AttemptState.FAILED: "worker_terminal_ack" if started else "no_dispatch",+ AttemptState.SKIPPED: "no_dispatch",+ AttemptState.CANCELLED: "cancellation_no_result_ack",+ AttemptState.TIMED_OUT: "timeout_termination_ack",+ AttemptState.INDETERMINATE: "bounded_recovery_exhausted",+ }.get(target)+ if target is AttemptState.INDETERMINATE:+ values.update(+ resolver_subject_ref=_uuid(200),+ resolver_user_id=_uuid(200),+ resolver_authority_revision=0,+ )+ transition = TransitionRequest(+ _uuid(210),+ revision,+ target,+ _uuid(operation_number),+ outcome_code=outcome,+ authoritative_proof=proof,+ campaign_id=_uuid(201),+ actor_subject_ref=(+ None if "owner_ref" in values or "resolver_subject_ref" in values else _uuid(200)+ ),+ actor_user_id=(+ None if "owner_ref" in values or "resolver_subject_ref" in values else _uuid(200)+ ),+ actor_authority_revision=(+ None if "owner_ref" in values or "resolver_subject_ref" in values else 0+ ),+ **values,+ )+ assert not (+ transition.resolver_subject_ref is not None and transition.actor_subject_ref is not None+ ), "transition principal bindings overlapped"+ budget_rows = await (+ await connection.execute(+ "SELECT budget_kind,id,revision FROM campaign_execution_budgets "+ "WHERE campaign_id=? ORDER BY CASE budget_kind WHEN 'noise' THEN 1 "+ "WHEN 'exfiltration' THEN 2 ELSE 3 END",+ (_uuid(201),),+ )+ ).fetchall()+ budget_by_kind = {str(item[0]): (str(item[1]), int(item[2])) for item in budget_rows}+ full = target is AttemptState.INDETERMINATE+ if not budget_by_kind:+ budget_by_kind = {+ "noise": (_uuid(204), 0),+ "exfiltration": (_uuid(205), 0),+ "concurrency": (_uuid(206), 0),+ }+ settlement = BudgetSettlement(+ _uuid(201),+ _uuid(210),+ budget_by_kind["noise"][0],+ 2,+ 2 if full else 0,+ budget_by_kind["noise"][1],+ budget_by_kind["exfiltration"][0],+ 3,+ 3 if full else 0,+ budget_by_kind["exfiltration"][1],+ budget_by_kind["concurrency"][0],+ budget_by_kind["concurrency"][1],+ _uuid(operation_number + 1),+ )+ outputs = (+ (OutputObservation(_uuid(operation_number + 4), OutputKind.HOST, _uuid(260)),)+ if target is AttemptState.PARTIAL+ else ()+ )+ return await store.commit_terminal_attempt(+ TerminalCommitRequest(+ _uuid(208),+ _uuid(201),+ _uuid(operation_number + 2),+ _uuid(operation_number + 3),+ transition,+ settlement,+ outputs,+ )+ )+++async def _build_source_state(+ store: ExecutionLifecycleStore,+ connection: aiosqlite.Connection,+ source: AttemptState,+) -> None:+ if source is AttemptState.ACCEPTED:+ return+ if source is AttemptState.QUEUED:+ result = await _nonterminal_transition(store, connection, source, 230)+ elif source is AttemptState.DISPATCHING:+ result = await _nonterminal_transition(store, connection, source, 231)+ else:+ result = await _nonterminal_transition(store, connection, AttemptState.DISPATCHING, 231)+ assert result.result is FixedResult.APPLIED, "source dispatch failed"+ if source is AttemptState.CANCELLING and False:+ return+ result = await _nonterminal_transition(store, connection, AttemptState.RUNNING, 232)+ if source in {AttemptState.RUNNING}:+ pass+ elif source is AttemptState.CANCELLING:+ assert result.result is FixedResult.APPLIED, "source start failed"+ result = await _nonterminal_transition(store, connection, source, 233)+ elif source is AttemptState.SETTLEMENT_PENDING:+ assert result.result is FixedResult.APPLIED, "source start failed"+ result = await _nonterminal_transition(store, connection, source, 234)+ elif source in {+ AttemptState.SUCCEEDED,+ AttemptState.PARTIAL,+ AttemptState.TIMED_OUT,+ AttemptState.INDETERMINATE,+ }:+ assert result.result is FixedResult.APPLIED, "source start failed"+ if source is AttemptState.INDETERMINATE:+ pending = await _nonterminal_transition(+ store, connection, AttemptState.SETTLEMENT_PENDING, 234+ )+ assert pending.result is FixedResult.APPLIED, "source recovery failed"+ store = _AdvancedClockLifecycleStore(connection, "sqlite")+ result = await _terminal_transition(store, connection, source, 270)+ elif source in {AttemptState.FAILED, AttemptState.SKIPPED}:+ raise AssertionError("terminal source must use no-dispatch builder")+ elif source is AttemptState.CANCELLED:+ assert result.result is FixedResult.APPLIED, "source start failed"+ cancelling = await _nonterminal_transition(+ store, connection, AttemptState.CANCELLING, 233+ )+ assert cancelling.result is FixedResult.APPLIED, "source cancel failed"+ result = await _terminal_transition(store, connection, source, 270)+ else:+ raise AssertionError("unsupported source state")+ assert result.result is FixedResult.APPLIED, "source transition failed"+++async def _snapshot_case(+ connection: aiosqlite.Connection,+) -> tuple[tuple[str, tuple[tuple[object, ...], ...]], ...]:+ tables = (+ "logical_executions",+ "execution_attempts",+ "campaign_execution_budgets",+ "campaign_execution_budget_ledger",+ "execution_output_links",+ "execution_publication_outbox",+ "execution_operation_receipts",+ "hosts",+ )+ observed = []+ for table in tables:+ rows = await (+ await connection.execute(+ f"SELECT * FROM {table} ORDER BY 1" # noqa: S608 - fixed tuple.+ )+ ).fetchall()+ observed.append((table, tuple(tuple(row) for row in rows)))+ return tuple(observed)+++async def _exercise_transition_pair(path, source: str, target: str):+ source_state = AttemptState(source)+ target_state = AttemptState(target)+ initial = (+ source_state+ if source_state in {AttemptState.REJECTED, AttemptState.BLOCKED}+ else AttemptState.ACCEPTED+ )+ connection, store = await _new_transition_case(path.as_posix(), initial)+ observer = await aiosqlite.connect(path.as_posix())+ try:+ if initial is AttemptState.ACCEPTED:+ if source_state in {AttemptState.FAILED, AttemptState.SKIPPED}:+ result = await _terminal_transition(store, connection, source_state, 270)+ assert result.result is FixedResult.APPLIED, "terminal source setup failed"+ else:+ await _build_source_state(store, connection, source_state)+ before = await _snapshot_case(connection)+ if target_state in {+ AttemptState.QUEUED,+ AttemptState.DISPATCHING,+ AttemptState.RUNNING,+ AttemptState.CANCELLING,+ AttemptState.SETTLEMENT_PENDING,+ }:+ result = await _nonterminal_transition(store, connection, target_state, 400)+ elif target_state in {+ AttemptState.SUCCEEDED,+ AttemptState.PARTIAL,+ AttemptState.FAILED,+ AttemptState.SKIPPED,+ AttemptState.CANCELLED,+ AttemptState.TIMED_OUT,+ AttemptState.INDETERMINATE,+ }:+ if (+ target_state is AttemptState.INDETERMINATE+ and source_state is AttemptState.SETTLEMENT_PENDING+ ):+ store = _AdvancedClockLifecycleStore(connection, "sqlite")+ result = await _terminal_transition(store, connection, target_state, 400)+ else:+ row = await _attempt_row(connection)+ result = await store.transition_attempt(+ TransitionRequest(+ _uuid(210),+ int(row[1]),+ target_state,+ _uuid(400),+ campaign_id=_uuid(201),+ actor_subject_ref=_uuid(200),+ actor_user_id=_uuid(200),+ actor_authority_revision=0,+ )+ )+ after = await _snapshot_case(connection)+ observer.row_factory = aiosqlite.Row+ durable = await _snapshot_case(observer)+ return result.result, before, after, durable+ finally:+ await observer.close()+ await connection.close()+++async def _insert_retryable_attempt(connection: aiosqlite.Connection) -> None:+ await connection.execute(+ "INSERT INTO users(id,username,hashed_password,role,created_by) VALUES(?,?,?,?,?)",+ (_uuid(1), "closure-admin", "fixed-hash", "admin", "fixed"),+ )+ await connection.execute(+ "INSERT INTO campaigns(id,name) VALUES(?,?)",+ (_uuid(2), "closure-campaign"),+ )+ await connection.execute(+ "INSERT INTO execution_actor_authority_revisions("+ "user_id,revision,latest_operation_id,latest_operation_base_revision,"+ "latest_operation_code,updated_at) VALUES(?,0,?,0,'ensure',1)",+ (_uuid(1), _uuid(3)),+ )+ await connection.execute(+ "INSERT INTO campaign_execution_authority_revisions("+ "campaign_id,revision,latest_operation_id,latest_operation_base_revision,"+ "latest_operation_code,updated_at) VALUES(?,0,?,0,'ensure',1)",+ (_uuid(2), _uuid(30)),+ )+ await connection.execute(+ "INSERT INTO logical_executions("+ "id,submission_id,campaign_id,actor_subject_ref,actor_user_id,module_id,"+ "ingress_code,admission_operation_id,submission_binding_contract_version,"+ "submission_request_binding_digest,submission_result_code,"+ "submission_exact_replay_code,submission_result_binding_digest,"+ "highest_attempt_ordinal,revision,created_at) "+ "VALUES(?,?,?,?,?,'test.module','sdk',?,2,?,'applied','replayed',?,0,0,1)",+ (+ _uuid(4),+ _uuid(5),+ _uuid(2),+ _uuid(1),+ _uuid(1),+ _uuid(31),+ "a" * 64,+ "b" * 64,+ ),+ )+ columns = (+ "id",+ "logical_execution_id",+ "campaign_id",+ "ordinal",+ "revision",+ "state",+ "closes_logical",+ "actor_subject_ref",+ "actor_user_id",+ "actor_authority_revision",+ "campaign_authority_revision",+ "destination_authority_revision",+ "credential_authority_revision",+ "request_contract_version",+ "evaluation_mode",+ "request_structure_valid",+ "canonicalization_complete",+ "unknown_fields_absent",+ "alternate_transport_absent",+ "bounded_shape_valid",+ "request_shape_units",+ "descriptor_contract_version",+ "descriptor_semantic_digest",+ "catalog_digest",+ "trusted_first_party_binding",+ "descriptor_binding_current",+ "descriptor_complete",+ "static_policy_evaluable",+ "minimum_role",+ "noise_class",+ "approval_policy",+ "capability_mask_version",+ "required_capability_mask",+ "descriptor_blocker_mask_version",+ "descriptor_blocker_mask",+ "preview_ready",+ "lifecycle_ready",+ "result_authority_ready",+ "transport_ready",+ "future_gateway_eligible",+ "authority_snapshots_complete",+ "authority_revisions_current",+ "actor_authenticated",+ "actor_active",+ "actor_role",+ "campaign_active",+ "actor_campaign_authorized",+ "approval_present",+ "approval_current",+ "approval_exactly_bound",+ "granted_capability_mask",+ "destination_extraction_complete",+ "destinations_in_scope",+ "credential_authority_resolved",+ "credential_authority_current",+ "opaque_handles_only",+ "permitted_handle_kinds_only",+ "raw_credentials_absent",+ "ambient_credentials_absent",+ "budget_authority_resolved",+ "budget_authority_current",+ "budget_capacity_available",+ "gateway_mode_snapshot",+ "gateway_decision_code",+ "policy_evaluation_state",+ "policy_contract_version",+ "policy_verdict",+ "policy_reason_mask_version",+ "policy_reason_mask",+ "external_effect_class",+ "idempotency_class",+ "retry_policy",+ "retry_disposition",+ "cancellation_ownership",+ "compensation_class",+ "timeout_origin",+ "timeout_limit_ms",+ "timeout_settlement",+ "outcome_code",+ "error_action_code",+ "settlement_state",+ "settlement_proof_code",+ "termination_confirmed",+ "lease_generation",+ "terminal_operation_id",+ "created_at",+ "finished_at",+ "settled_at",+ )+ values = (+ _uuid(6),+ _uuid(4),+ _uuid(2),+ 0,+ 0,+ "failed",+ 0,+ _uuid(1),+ _uuid(1),+ 0,+ 0,+ 0,+ 0,+ 1,+ "live",+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ "ares.module-descriptor.v2",+ "a" * 64,+ "b" * 64,+ 1,+ 1,+ 1,+ 1,+ "operator",+ "low",+ "none",+ 1,+ 0,+ 1,+ 0,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ "admin",+ 1,+ 1,+ 0,+ 0,+ 0,+ 0,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ 1,+ "enforced",+ "none",+ "evaluated",+ 1,+ "live_candidate",+ 1,+ 0,+ "read_only",+ "proven_idempotent",+ "after_revalidation",+ "eligible",+ "owned",+ "not_applicable",+ "module_defined_bounded",+ 1_000,+ "proven",+ "confirmed_failure_no_dispatch",+ "none",+ "not_applicable",+ "no_dispatch",+ 0,+ 0,+ _uuid(7),+ 1,+ 1,+ 1,+ )+ await connection.execute(+ "INSERT INTO execution_attempts("+ + ",".join(columns)+ + ") VALUES("+ + ",".join("?" for _ in columns)+ + ")",+ values,+ )+ await connection.commit()+++async def test_authority_ensure_and_invalidate_are_exactly_replayable() -> None:+ connection = await _new_connection()+ try:+ await connection.execute(+ "INSERT INTO users(id,username,hashed_password,role,created_by) VALUES(?,?,?,?,?)",+ (_UUIDS[0], "fixed-user", "fixed-hash", "admin", "fixed"),+ )+ await connection.commit()+ store = ExecutionLifecycleStore(connection, "sqlite")+ created = await store.ensure_actor_authority(_UUIDS[0], _UUIDS[1])+ replay = await store.ensure_actor_authority(_UUIDS[0], _UUIDS[1])+ invalidated = await store.invalidate_actor_authority(_UUIDS[0], 0, _UUIDS[2])+ stale = await store.invalidate_actor_authority(_UUIDS[0], 0, _UUIDS[3])+ finally:+ await connection.close()+ assert (created.result, replay.result, invalidated.result, stale.result) == (+ FixedResult.APPLIED,+ FixedResult.REPLAYED,+ FixedResult.APPLIED,+ FixedResult.CONFLICT_REVISION,+ ), "authority CAS result changed"+++ ("snapshot", "reason"),+ [+ (_blocked_snapshot(), PolicyReasonBit.INSUFFICIENT_ROLE.value),+ (+ replace(+ _blocked_snapshot(),+ actor_role="operator",+ required_capability_mask=3,+ granted_capability_mask=1,+ policy_reason_mask=PolicyReasonBit.CAPABILITY_REQUIRED.value,+ ),+ PolicyReasonBit.CAPABILITY_REQUIRED.value,+ ),+ (+ replace(+ _blocked_snapshot(),+ actor_role="operator",+ policy_verdict="preview_ready",+ policy_reason_mask=PolicyReasonBit.PREVIEW_NOT_READY.value,+ ),+ PolicyReasonBit.PREVIEW_NOT_READY.value,+ ),+ ],+ ids=("reporter-role", "capability", "preview-live"),+)+async def test_durable_block_creates_zero_budget_terminal_snapshot(+ snapshot: AttemptPolicySnapshot, reason: int+) -> None:+ connection = await _new_connection()+ try:+ await connection.execute(+ "INSERT INTO users(id,username,hashed_password,role,created_by) VALUES(?,?,?,?,?)",+ (_uuid(40), "blocked-user", "fixed-hash", snapshot.actor_role, "fixed"),+ )+ await connection.execute(+ "INSERT INTO campaigns(id,name) VALUES(?,?)",+ (_uuid(41), "blocked-campaign"),+ )+ await connection.commit()+ store = ExecutionLifecycleStore(connection, "sqlite")+ await store.ensure_actor_authority(_uuid(40), _uuid(42))+ await store.ensure_campaign_authority(_uuid(41), _uuid(43))+ request = AdmissionRequest(+ _uuid(44),+ _uuid(45),+ _uuid(46),+ _uuid(47),+ _uuid(48),+ _uuid(41),+ _uuid(40),+ _uuid(40),+ "test.module",+ "sdk",+ AttemptState.BLOCKED,+ _uuid(49),+ snapshot,+ )+ created = await store._create_initial_execution_v2_for_migration_fixture(request)+ replayed = await store._create_initial_execution_v2_for_migration_fixture(request)+ attempt = await (+ await connection.execute(+ "SELECT state,policy_reason_mask,closes_logical,outcome_code "+ "FROM execution_attempts"+ )+ ).fetchone()+ observed_counts = []+ for table in (+ "execution_attempt_approvals",+ "campaign_execution_budget_ledger",+ "campaign_execution_budgets",+ ):+ cursor = await connection.execute(+ "SELECT count(*) FROM " + table # noqa: S608+ )+ row = await cursor.fetchone()+ observed_counts.append(int(row[0]))+ counts = tuple(observed_counts)+ finally:+ await connection.close()+ assert (created.result, replayed.result) == (+ FixedResult.APPLIED,+ FixedResult.REPLAYED,+ ), "durable block replay changed"+ assert tuple(attempt) == ("blocked", reason, 1, "policy_blocked"), "blocked snapshot changed"+ assert counts == (0, 0, 0), "blocked decision reserved budget"+++async def test_accepted_creation_reserves_all_budgets_in_one_transaction() -> None:+ connection = await _new_connection()+ try:+ await connection.execute(+ "INSERT INTO users(id,username,hashed_password,role,created_by) VALUES(?,?,?,?,?)",+ (_uuid(60), "accept-admin", "fixed-hash", "admin", "fixed"),+ )+ await connection.execute(+ "INSERT INTO campaigns(id,name) VALUES(?,?)", (_uuid(61), "accept")+ )+ await connection.execute(+ "UPDATE execution_gateway_state SET mode='enforced',catalog_digest=?,"+ "activation_revision=1,activation_at=1,revision=1 WHERE singleton_id=1",+ ("c" * 64,),+ )+ await connection.commit()+ store = ExecutionLifecycleStore(connection, "sqlite")+ await store.ensure_actor_authority(_uuid(60), _uuid(62))+ await store.ensure_campaign_authority(_uuid(61), _uuid(63))+ await store.configure_campaign_budgets(+ BudgetConfiguration(+ _uuid(61),+ _uuid(64),+ 10,+ _uuid(65),+ 10,+ _uuid(66),+ 1,+ _uuid(67),+ )+ )+ snapshot = replace(+ _blocked_snapshot(),+ actor_role="admin",+ required_capability_mask=1,+ granted_capability_mask=1,+ preview_ready=True,+ lifecycle_ready=True,+ result_authority_ready=True,+ transport_ready=True,+ future_gateway_eligible=True,+ budget_capacity_available=True,+ gateway_mode_snapshot="enforced",+ policy_verdict="live_candidate",+ policy_reason_mask=0,+ )+ budgets = BudgetReservation(+ _uuid(61),+ _uuid(70),+ _uuid(64),+ _uuid(71),+ 2,+ 0,+ _uuid(65),+ _uuid(72),+ 3,+ 0,+ _uuid(66),+ _uuid(73),+ 0,+ _uuid(74),+ )+ request = AdmissionRequest(+ _uuid(68),+ _uuid(69),+ _uuid(70),+ None,+ None,+ _uuid(61),+ _uuid(60),+ _uuid(60),+ "test.module",+ "sdk",+ AttemptState.ACCEPTED,+ _uuid(75),+ snapshot,+ budgets=budgets,+ )+ created = await store._create_initial_execution_v2_for_migration_fixture(request)+ attempt = await (+ await connection.execute(+ "SELECT state,settlement_state,closes_logical FROM execution_attempts"+ )+ ).fetchone()+ ledgers = await (+ await connection.execute(+ "SELECT budget_kind,reservation_units,disposition "+ "FROM campaign_execution_budget_ledger ORDER BY budget_kind"+ )+ ).fetchall()+ outbox_count = await (+ await connection.execute("SELECT count(*) FROM execution_publication_outbox")+ ).fetchone()+ dispatched = await store.transition_attempt(+ TransitionRequest(+ _uuid(70),+ 0,+ AttemptState.DISPATCHING,+ _uuid(76),+ owner_ref=_uuid(77),+ lease_generation=1,+ lease_duration_ms=1_000,+ campaign_id=_uuid(61),+ )+ )+ running = await store.transition_attempt(+ TransitionRequest(+ _uuid(70),+ 1,+ AttemptState.RUNNING,+ _uuid(78),+ owner_ref=_uuid(77),+ lease_generation=1,+ campaign_id=_uuid(61),+ )+ )+ terminal_request = TerminalCommitRequest(+ _uuid(68),+ _uuid(61),+ _uuid(79),+ _uuid(80),+ TransitionRequest(+ _uuid(70),+ 2,+ AttemptState.SUCCEEDED,+ _uuid(81),+ owner_ref=_uuid(77),+ lease_generation=1,+ outcome_code=OutcomeCode.CONFIRMED_SUCCESS,+ authoritative_proof="worker_terminal_ack",+ campaign_id=_uuid(61),+ ),+ BudgetSettlement(+ _uuid(61),+ _uuid(70),+ _uuid(64),+ 2,+ 1,+ 1,+ _uuid(65),+ 3,+ 2,+ 1,+ _uuid(66),+ 1,+ _uuid(82),+ ),+ )+ terminal = await store.commit_terminal_attempt(terminal_request)+ terminal_replay = await store.commit_terminal_attempt(terminal_request)+ finished = await (+ await connection.execute(+ "SELECT state,closes_logical,settlement_state,outcome_code FROM execution_attempts"+ )+ ).fetchone()+ finally:+ await connection.close()+ assert created.result is FixedResult.APPLIED, "acceptance failed"+ assert tuple(attempt) == ("accepted", "reserved", 0), "attempt changed"+ assert tuple(tuple(row) for row in ledgers) == (+ ("concurrency", 1, "held"),+ ("exfiltration", 3, "held"),+ ("noise", 2, "held"),+ ), "acceptance reservations changed"+ assert int(outbox_count[0]) == 0, "acceptance published an event"+ assert (dispatched.result, running.result, terminal.result, terminal_replay.result) == (+ FixedResult.APPLIED,+ FixedResult.APPLIED,+ FixedResult.APPLIED,+ FixedResult.REPLAYED,+ ), "terminal transaction changed"+ assert tuple(finished) == ("succeeded", 1, "settled", "confirmed_success"), (+ "terminal state changed"+ )+++async def test_outbox_claim_renew_retry_reclaim_and_poison_are_cas_bound() -> None:+ connection = await _new_connection()+ try:+ await connection.execute("PRAGMA foreign_keys=OFF")+ await connection.execute(+ "INSERT INTO execution_publication_outbox("+ "id,publication_key,attempt_id,campaign_id,event_code,is_attempt_terminal,"+ "publication_state,delivery_attempt_count,available_at,lease_generation,"+ "claim_revision,latest_operation_id,latest_operation_code,"+ "latest_operation_base_revision,created_at) "+ "VALUES(?,?,?,?,?,0,'pending',0,1,0,0,?,'insert',0,1)",+ (_UUIDS[0], _UUIDS[1], _UUIDS[2], _UUIDS[3], "recovery_required", _UUIDS[1]),+ )+ await connection.commit()+ store = ExecutionLifecycleStore(connection, "sqlite")+ claimed = await store.claim_outbox(+ OutboxMutation(+ _UUIDS[0],+ 0,+ _UUIDS[4],+ _UUIDS[5],+ 0,+ _UUIDS[3],+ _UUIDS[2],+ _UUIDS[1],+ "recovery_required",+ )+ )+ renewed = await store.renew_outbox(+ OutboxMutation(+ _UUIDS[0],+ 1,+ _UUIDS[6],+ _UUIDS[5],+ 1,+ _UUIDS[3],+ _UUIDS[2],+ _UUIDS[1],+ "recovery_required",+ )+ )+ retried = await store.fail_outbox(+ OutboxMutation(+ _UUIDS[0],+ 2,+ _UUIDS[7],+ _UUIDS[5],+ 1,+ _UUIDS[3],+ _UUIDS[2],+ _UUIDS[1],+ "recovery_required",+ ),+ retryable=True,+ )+ row = await (+ await connection.execute(+ "SELECT publication_state,delivery_attempt_count,claim_revision,"+ "latest_operation_code FROM execution_publication_outbox"+ )+ ).fetchone()+ finally:+ await connection.close()+ assert (claimed.result, renewed.result, retried.result) == (+ FixedResult.APPLIED,+ FixedResult.APPLIED,+ FixedResult.APPLIED,+ ), "outbox CAS result changed"+ assert tuple(row) == ("pending", 1, 3, "retryable_failure"), "outbox state changed"+++async def test_expired_twentieth_claim_is_poisoned_without_owner_cooperation() -> None:+ connection = await _new_connection()+ try:+ await connection.execute("PRAGMA foreign_keys=OFF")+ await connection.execute(+ "INSERT INTO execution_publication_outbox("+ "id,publication_key,attempt_id,campaign_id,event_code,is_attempt_terminal,"+ "publication_state,delivery_attempt_count,available_at,claim_owner_ref,"+ "lease_generation,claimed_at,lease_expires_at,failure_code,claim_revision,"+ "latest_operation_id,latest_operation_code,latest_operation_base_revision,"+ "created_at) VALUES(?,?,?,?,?,0,'claimed',20,NULL,?,20,1,1,NULL,20,?,"+ "'reclaim',19,1)",+ (+ _uuid(100),+ _uuid(101),+ _uuid(102),+ _uuid(103),+ "recovery_required",+ _uuid(104),+ _uuid(105),+ ),+ )+ await connection.commit()+ store = ExecutionLifecycleStore(connection, "sqlite")+ request = OutboxMutation(+ _uuid(100),+ 20,+ _uuid(106),+ campaign_id=_uuid(103),+ attempt_id=_uuid(102),+ publication_key=_uuid(101),+ event_code="recovery_required",+ )+ applied = await store.poison_expired_attempt_twenty(request)+ replayed = await store.poison_expired_attempt_twenty(request)+ row = await (+ await connection.execute(+ "SELECT publication_state,claim_owner_ref,lease_generation,"+ "delivery_attempt_count,failure_code,claim_revision,latest_operation_id,"+ "latest_operation_code,latest_operation_base_revision "+ "FROM execution_publication_outbox"+ )+ ).fetchone()+ finally:+ await connection.close()+ assert (applied.result, replayed.result) == (+ FixedResult.APPLIED,+ FixedResult.REPLAYED,+ ), "attempt-limit poison replay changed"+ assert tuple(row) == (+ "poisoned",+ None,+ 20,+ 20,+ "delivery_attempt_limit",+ 21,+ _uuid(106),+ "poison",+ 20,+ ), "attempt-limit poison state changed"+++async def test_budget_reserve_and_settle_use_post_cas_revisions() -> None:+ connection = await _new_connection()+ try:+ await _insert_retryable_attempt(connection)+ store = ExecutionLifecycleStore(connection, "sqlite")+ configured = await store.configure_campaign_budgets(+ BudgetConfiguration(+ _uuid(2),+ _uuid(110),+ 10,+ _uuid(111),+ 10,+ _uuid(112),+ 2,+ _uuid(113),+ )+ )+ reserved = await store.reserve_budgets(+ BudgetReservation(+ _uuid(2),+ _uuid(6),+ _uuid(110),+ _uuid(114),+ 4,+ 0,+ _uuid(111),+ _uuid(115),+ 5,+ 0,+ _uuid(112),+ _uuid(116),+ 0,+ _uuid(117),+ )+ )+ settled = await store.settle_budgets(+ BudgetSettlement(+ _uuid(2),+ _uuid(6),+ _uuid(110),+ 4,+ 3,+ 1,+ _uuid(111),+ 5,+ 0,+ 1,+ _uuid(112),+ 1,+ _uuid(118),+ )+ )+ budget_rows = await (+ await connection.execute(+ "SELECT budget_kind,reserved_units,consumed_units,revision "+ "FROM campaign_execution_budgets ORDER BY CASE budget_kind "+ "WHEN 'noise' THEN 1 WHEN 'exfiltration' THEN 2 ELSE 3 END"+ )+ ).fetchall()+ ledger_rows = await (+ await connection.execute(+ "SELECT budget_kind,disposition,consumed_units,"+ "budget_revision_reserved,budget_revision_settled "+ "FROM campaign_execution_budget_ledger ORDER BY CASE budget_kind "+ "WHEN 'noise' THEN 1 WHEN 'exfiltration' THEN 2 ELSE 3 END"+ )+ ).fetchall()+ finally:+ await connection.close()+ assert (configured.result, reserved.result, settled.result) == (+ FixedResult.APPLIED,+ FixedResult.APPLIED,+ FixedResult.APPLIED,+ ), "budget CAS result changed"+ assert tuple(tuple(row) for row in budget_rows) == (+ ("noise", 0, 3, 2),+ ("exfiltration", 0, 0, 2),+ ("concurrency", 0, 0, 2),+ ), "budget arithmetic changed"+ assert tuple(tuple(row) for row in ledger_rows) == (+ ("noise", "consumed", 3, 1, 2),+ ("exfiltration", "released", 0, 1, 2),+ ("concurrency", "released", 0, 1, 2),+ ), "ledger post-CAS revisions changed"+++async def test_budget_reservation_conflict_rolls_back_all_three_kinds() -> None:+ connection = await _new_connection()+ try:+ await _insert_retryable_attempt(connection)+ store = ExecutionLifecycleStore(connection, "sqlite")+ await store.configure_campaign_budgets(+ BudgetConfiguration(+ _uuid(2),+ _uuid(21),+ 10,+ _uuid(22),+ 10,+ _uuid(23),+ 1,+ _uuid(24),+ )+ )+ result = await store.reserve_budgets(+ BudgetReservation(+ _uuid(2),+ _uuid(6),+ _uuid(21),+ _uuid(26),+ 4,+ 0,+ _uuid(22),+ _uuid(27),+ 4,+ 1,+ _uuid(23),+ _uuid(28),+ 0,+ _uuid(29),+ )+ )+ rows = await (+ await connection.execute(+ "SELECT reserved_units,revision FROM campaign_execution_budgets "+ "ORDER BY budget_kind"+ )+ ).fetchall()+ ledgers = await (+ await connection.execute("SELECT count(*) FROM campaign_execution_budget_ledger")+ ).fetchone()+ finally:+ await connection.close()+ assert result.result is FixedResult.CONFLICT_REVISION, "conflict changed"+ assert tuple(tuple(row) for row in rows) == ((0, 0), (0, 0), (0, 0)), (+ "reservation conflict committed a partial mutation"+ )+ assert int(ledgers[0]) == 0, "reservation conflict created a ledger"+++async def test_close_without_retry_is_permanent_after_outbox_purge() -> None:+ connection = await _new_connection()+ try:+ await _insert_retryable_attempt(connection)+ store = ExecutionLifecycleStore(connection, "sqlite")+ request = ClosureRequest(+ _uuid(4),+ _uuid(6),+ _uuid(8),+ 0,+ _uuid(9),+ _uuid(1),+ _uuid(1),+ 0,+ _uuid(2),+ )+ applied = await store.close_without_retry(request)+ await connection.execute("DELETE FROM execution_publication_outbox WHERE id=?", (_uuid(8),))+ await connection.commit()+ replayed = await store.close_without_retry(request)+ conflicting = await store.close_without_retry(+ ClosureRequest(+ _uuid(4),+ _uuid(6),+ _uuid(10),+ 1,+ _uuid(11),+ _uuid(1),+ _uuid(1),+ 0,+ _uuid(2),+ )+ )+ logical = await (+ await connection.execute(+ "SELECT closure_operation_id,closing_attempt_id FROM logical_executions"+ )+ ).fetchone()+ finally:+ await connection.close()+ assert (applied.result, replayed.result, conflicting.result) == (+ FixedResult.APPLIED,+ FixedResult.REPLAYED_CLOSED,+ FixedResult.ALREADY_CLOSED,+ ), "closure replay changed"+ assert tuple(logical) == (_uuid(9), _uuid(6)), "permanent closure changed"+++async def test_retry_denial_child_uuid_replays_and_excludes_closure() -> None:+ connection = await _new_connection()+ try:+ await _insert_retryable_attempt(connection)+ store = ExecutionLifecycleStore(connection, "sqlite")+ child = AdmissionRequest(+ _uuid(4),+ _uuid(80),+ _uuid(81),+ _uuid(82),+ _uuid(83),+ _uuid(2),+ _uuid(1),+ _uuid(1),+ "test.module",+ "sdk",+ AttemptState.BLOCKED,+ _uuid(84),+ replace(+ _blocked_snapshot(),+ actor_role="admin",+ required_capability_mask=1,+ granted_capability_mask=0,+ policy_reason_mask=PolicyReasonBit.CAPABILITY_REQUIRED.value,+ ),+ )+ retry = RetryRequest(_uuid(4), _uuid(6), child, 0)+ applied = await store._create_retry_attempt_v2_for_migration_fixture(retry)+ replayed = await store._create_retry_attempt_v2_for_migration_fixture(retry)+ closure_loser = await store.close_without_retry(+ ClosureRequest(+ _uuid(4),+ _uuid(6),+ _uuid(85),+ 1,+ _uuid(86),+ _uuid(1),+ _uuid(1),+ 0,+ _uuid(2),+ )+ )+ attempts = await (+ await connection.execute(+ "SELECT id,parent_attempt_id,ordinal,state FROM execution_attempts ORDER BY ordinal"+ )+ ).fetchall()+ finally:+ await connection.close()+ assert (applied.result, replayed.result, closure_loser.result) == (+ FixedResult.APPLIED,+ FixedResult.REPLAYED_BOUND_CHILD,+ FixedResult.ALREADY_CLOSED,+ ), "retry/closure race changed"+ assert tuple(tuple(row) for row in attempts) == (+ (_uuid(6), None, 0, "failed"),+ (_uuid(81), _uuid(6), 1, "blocked"),+ ), "linear retry chain changed"+++async def test_closure_winner_excludes_retry_child() -> None:+ connection = await _new_connection()+ try:+ await _insert_retryable_attempt(connection)+ store = ExecutionLifecycleStore(connection, "sqlite")+ closed = await store.close_without_retry(+ ClosureRequest(+ _uuid(4),+ _uuid(6),+ _uuid(87),+ 0,+ _uuid(88),+ _uuid(1),+ _uuid(1),+ 0,+ _uuid(2),+ )+ )+ child = AdmissionRequest(+ _uuid(4),+ _uuid(89),+ _uuid(90),+ _uuid(91),+ _uuid(92),+ _uuid(2),+ _uuid(1),+ _uuid(1),+ "test.module",+ "sdk",+ AttemptState.BLOCKED,+ _uuid(93),+ _blocked_snapshot(),+ )+ retry = await store._create_retry_attempt_v2_for_migration_fixture(+ RetryRequest(_uuid(4), _uuid(6), child, 1)+ )+ attempt_count = await (+ await connection.execute("SELECT count(*) FROM execution_attempts")+ ).fetchone()+ finally:+ await connection.close()+ assert (closed.result, retry.result) == (+ FixedResult.APPLIED,+ FixedResult.ALREADY_CLOSED,+ ), "closure/retry race changed"+ assert int(attempt_count[0]) == 1, "closure loser created a child"+++def test_only_exact_receipt_immutability_triggers_are_created() -> None:+ connection = sqlite3.connect(":memory:")+ try:+ connection.executescript(CREATE_TABLES)+ rows = connection.execute(+ "SELECT name,tbl_name FROM sqlite_schema WHERE type='trigger' "+ "AND tbl_name IN (?,?,?,?,?,?,?,?,?,?,?)",+ LIFECYCLE_TABLES,+ ).fetchall()+ finally:+ connection.close()+ assert tuple(sorted(rows)) == (+ ("trg_eor_immutable_delete", "execution_operation_receipts"),+ ("trg_eor_immutable_update", "execution_operation_receipts"),+ ), "lifecycle trigger inventory changed"+++def test_exact_sqlite_catalog_validator_rejects_extra_lifecycle_index() -> None:+ connection = sqlite3.connect(":memory:")+ try:+ connection.executescript(CREATE_TABLES)+ connection.execute("CREATE INDEX unexpected_lifecycle_index ON execution_attempts(state)")+ rejected = False+ try:+ validate_sqlite_lifecycle_catalog(connection)+ except RuntimeError:+ rejected = True+ finally:+ connection.close()+ assert rejected is True, "unexpected lifecycle index passed validation"+++def test_i53_boundary_is_exact() -> None:+ assert MAX_I53 == 9_007_199_254_740_991, "I53 boundary changed"+++class _SQLiteZeroRowTraceStore(ExecutionLifecycleStore):+ """Record the real connection and transaction used after a zero-row write."""++ def __init__(self, connection: aiosqlite.Connection) -> None:+ super().__init__(connection, "sqlite")+ self.zero_connection_id: int | None = None+ self.zero_in_transaction = False+ self.classifier_connection_ids: list[int] = []+ self.classifier_in_transaction: list[bool] = []+ self._awaiting_classifier = False++ async def _returning_rows(+ self, connection: Any, sql: str, params: tuple[Any, ...]+ ) -> tuple[Any, ...]:+ rows = await super()._returning_rows(connection, sql, params)+ if not rows and "UPDATE execution_attempts SET" in sql:+ self.zero_connection_id = id(connection)+ self.zero_in_transaction = bool(connection.in_transaction)+ self._awaiting_classifier = True+ return rows++ async def _fetchrow(self, connection: Any, sql: str, params: tuple[Any, ...]) -> Any:+ if self._awaiting_classifier:+ self.classifier_connection_ids.append(id(connection))+ self.classifier_in_transaction.append(bool(connection.in_transaction))+ return await super()._fetchrow(connection, sql, params)+++class _SQLiteWinnerBarrierStore(ExecutionLifecycleStore):+ def __init__(+ self,+ connection: aiosqlite.Connection,+ winner_entered: asyncio.Event,+ contender_attempted: asyncio.Event,+ ) -> None:+ super().__init__(connection, "sqlite")+ self._winner_entered = winner_entered+ self._contender_attempted = contender_attempted++ @asynccontextmanager+ async def _transaction(self) -> AsyncIterator[Any]:+ async with super()._transaction() as connection:+ self._winner_entered.set()+ await self._contender_attempted.wait()+ yield connection+++class _SQLiteContenderBarrierStore(ExecutionLifecycleStore):+ def __init__(+ self,+ connection: aiosqlite.Connection,+ contender_attempted: asyncio.Event,+ ) -> None:+ super().__init__(connection, "sqlite")+ self._contender_attempted = contender_attempted++ @asynccontextmanager+ async def _transaction(self) -> AsyncIterator[Any]:+ self._contender_attempted.set()+ async with super()._transaction() as connection:+ yield connection+++class _SQLiteCancellationGateStore(ExecutionLifecycleStore):+ def __init__(+ self,+ connection: aiosqlite.Connection,+ receipt_entered: asyncio.Event,+ receipt_release: asyncio.Event,+ ) -> None:+ super().__init__(connection, "sqlite")+ self.receipt_entered = receipt_entered+ self.receipt_release = receipt_release+ self.armed = True++ async def _insert_receipt(self, *args: Any, **kwargs: Any) -> None:+ if self.armed:+ self.receipt_entered.set()+ await self.receipt_release.wait()+ await super()._insert_receipt(*args, **kwargs)+++class _SQLiteCleanupFailureStore(ExecutionLifecycleStore):+ def __init__(+ self,+ connection: aiosqlite.Connection,+ stage: str,+ cleanup_faults: list[str],+ ) -> None:+ super().__init__(connection, "sqlite")+ self.stage = stage+ self.cleanup_faults = cleanup_faults+ self.armed = True++ async def _returning_rows(+ self, connection: Any, sql: str, params: tuple[Any, ...]+ ) -> tuple[Any, ...]:+ rows = await super()._returning_rows(connection, sql, params)+ if self.armed and rows and "UPDATE execution_attempts SET" in sql:+ return rows + rows+ return rows++ async def _execute(self, connection: Any, sql: str, params: tuple[Any, ...]) -> None:+ await super()._execute(connection, sql, params)+ expected = {+ "savepoint-rollback": "ROLLBACK TO SAVEPOINT lifecycle_compound",+ "savepoint-release": "RELEASE SAVEPOINT lifecycle_compound",+ }.get(self.stage)+ if self.armed and expected == sql:+ self.cleanup_faults.append(self.stage)+ raise RuntimeError("fixed-sqlite-cleanup-failure")+++_SQLITE_P1A_ZERO_ROW_TRIGGERS = {+ "missing": (+ "CREATE TEMP TRIGGER p1a_zero_missing BEFORE UPDATE OF state "+ "ON execution_attempts "+ "WHEN OLD.id='00000000-0000-4000-8000-0000000000d2' BEGIN "+ "DELETE FROM campaign_execution_budget_ledger "+ "WHERE attempt_id='00000000-0000-4000-8000-0000000000d2'; "+ "DELETE FROM execution_attempts "+ "WHERE id='00000000-0000-4000-8000-0000000000d2'; "+ "SELECT RAISE(IGNORE); END;"+ ),+ "stale-revision": (+ "CREATE TEMP TRIGGER p1a_zero_stale_revision BEFORE UPDATE OF state "+ "ON execution_attempts "+ "WHEN OLD.id='00000000-0000-4000-8000-0000000000d2' BEGIN "+ "UPDATE execution_attempts SET revision=revision+1 "+ "WHERE id='00000000-0000-4000-8000-0000000000d2'; "+ "SELECT RAISE(IGNORE); END;"+ ),+ "stale-state": (+ "CREATE TEMP TRIGGER p1a_zero_stale_state BEFORE UPDATE OF state "+ "ON execution_attempts "+ "WHEN OLD.id='00000000-0000-4000-8000-0000000000d2' BEGIN "+ "UPDATE execution_attempts SET state='queued',"+ "queue_operation_id='00000000-0000-4000-8000-0000000003d5',"+ "queued_at=accepted_at "+ "WHERE id='00000000-0000-4000-8000-0000000000d2'; "+ "SELECT RAISE(IGNORE); END;"+ ),+ "stale-authority": (+ "CREATE TEMP TRIGGER p1a_zero_stale_authority BEFORE UPDATE OF state "+ "ON execution_attempts "+ "WHEN OLD.id='00000000-0000-4000-8000-0000000000d2' BEGIN "+ "UPDATE execution_actor_authority_revisions SET revision=revision+1,"+ "latest_operation_id='00000000-0000-4000-8000-0000000003d6',"+ "latest_operation_base_revision=revision,latest_operation_code='invalidate' "+ "WHERE user_id='00000000-0000-4000-8000-0000000000c8'; "+ "SELECT RAISE(IGNORE); END;"+ ),+ "stale-owner": (+ "CREATE TEMP TRIGGER p1a_zero_stale_owner BEFORE UPDATE OF state "+ "ON execution_attempts "+ "WHEN OLD.id='00000000-0000-4000-8000-0000000000d2' BEGIN "+ "UPDATE execution_attempts "+ "SET dispatch_owner_ref='00000000-0000-4000-8000-0000000003d7' "+ "WHERE id='00000000-0000-4000-8000-0000000000d2'; "+ "SELECT RAISE(IGNORE); END;"+ ),+ "stale-generation": (+ "CREATE TEMP TRIGGER p1a_zero_stale_generation BEFORE UPDATE OF state "+ "ON execution_attempts "+ "WHEN OLD.id='00000000-0000-4000-8000-0000000000d2' BEGIN "+ "UPDATE execution_attempts SET lease_generation=lease_generation+1 "+ "WHERE id='00000000-0000-4000-8000-0000000000d2'; "+ "SELECT RAISE(IGNORE); END;"+ ),+ "stale-lease": (+ "CREATE TEMP TRIGGER p1a_zero_stale_lease BEFORE UPDATE OF state "+ "ON execution_attempts "+ "WHEN OLD.id='00000000-0000-4000-8000-0000000000d2' BEGIN "+ "UPDATE execution_attempts SET lease_expires_at=created_at "+ "WHERE id='00000000-0000-4000-8000-0000000000d2'; "+ "SELECT RAISE(IGNORE); END;"+ ),+ "stale-cancellation": (+ "CREATE TEMP TRIGGER p1a_zero_stale_cancellation BEFORE UPDATE OF state "+ "ON execution_attempts "+ "WHEN OLD.id='00000000-0000-4000-8000-0000000000d2' BEGIN "+ "UPDATE execution_attempts SET cancellation_request_revision="+ "cancellation_request_revision+1 "+ "WHERE id='00000000-0000-4000-8000-0000000000d2'; "+ "SELECT RAISE(IGNORE); END;"+ ),+ "operation-conflict": (+ "CREATE TEMP TRIGGER p1a_zero_operation_conflict BEFORE UPDATE OF state "+ "ON execution_attempts "+ "WHEN OLD.id='00000000-0000-4000-8000-0000000000d2' BEGIN "+ "INSERT INTO execution_operation_receipts("+ "operation_id,operation_code,campaign_id,primary_target_id,secondary_target_id,"+ "principal_kind,principal_subject_ref,principal_user_id,"+ "principal_authority_revision_present,principal_authority_revision,"+ "binding_contract_version,request_binding_digest,"+ "expected_revision_present,expected_revision,"+ "secondary_expected_revision_present,secondary_expected_revision,"+ "owner_ref,lease_generation,result_code,exact_replay_code,result_binding_digest,"+ "result_identity,result_revision_present,result_revision,"+ "secondary_result_identity,secondary_result_revision_present,"+ "secondary_result_revision) VALUES("+ "'00000000-0000-4000-8000-0000000003d4','queue',"+ "'00000000-0000-4000-8000-0000000000c9',"+ "'00000000-0000-4000-8000-0000000003d8',NULL,"+ "'system','004cb934-3a47-4cd0-b0cb-a5b18df76a48',NULL,0,NULL,2,"+ "'dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd',"+ "1,0,0,NULL,NULL,NULL,'conflict_operation','replayed',"+ "'eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee',"+ "'00000000-0000-4000-8000-0000000003d8',1,0,NULL,0,NULL); "+ "SELECT RAISE(IGNORE); END;"+ ),+}+++async def _install_zero_row_trigger(connection: aiosqlite.Connection, case: str) -> None:+ await connection.execute("PRAGMA recursive_triggers=OFF")+ await connection.executescript(_SQLITE_P1A_ZERO_ROW_TRIGGERS[case])+ await connection.commit()+++async def _p1a_transition_request(+ connection: aiosqlite.Connection,+ case: str,+) -> tuple[TransitionRequest, bool]:+ setup_store = ExecutionLifecycleStore(connection, "sqlite")+ if case in {"stale-owner", "stale-generation", "stale-lease", "stale-cancellation"}:+ dispatched = await _nonterminal_transition(+ setup_store, connection, AttemptState.DISPATCHING, 970+ )+ assert dispatched.result is FixedResult.APPLIED, "P1-A dispatch setup failed"+ if case == "stale-cancellation":+ running = await _nonterminal_transition(setup_store, connection, AttemptState.RUNNING, 971)+ assert running.result is FixedResult.APPLIED, "P1-A running setup failed"+ cancelling = await _nonterminal_transition(+ setup_store, connection, AttemptState.CANCELLING, 972+ )+ assert cancelling.result is FixedResult.APPLIED, "P1-A cancellation setup failed"+ row = await _attempt_row(connection)+ return (+ TransitionRequest(+ _uuid(210),+ int(row[1]),+ AttemptState.SETTLEMENT_PENDING,+ _uuid(980),+ owner_ref=_uuid(220),+ lease_generation=int(row[3]),+ cancellation_request_revision=int(row[4]),+ outbox_id=_uuid(985),+ publication_key=_uuid(986),+ campaign_id=_uuid(201),+ ),+ True,+ )+ row = await _attempt_row(connection)+ values: dict[str, object] = {}+ target = AttemptState.QUEUED+ if case in {"stale-owner", "stale-generation", "stale-lease"}:+ target = AttemptState.RUNNING+ values = {"owner_ref": _uuid(220), "lease_generation": int(row[3])}+ else:+ values = {+ "actor_subject_ref": _uuid(200),+ "actor_user_id": _uuid(200),+ "actor_authority_revision": 0,+ }+ return (+ TransitionRequest(+ _uuid(210),+ int(row[1]),+ target,+ _uuid(980),+ campaign_id=_uuid(201),+ **values,+ ),+ False,+ )+++async def test_sqlite_truth_write_exactly_one_row_is_applied() -> None:+ connection = await _new_connection()+ try:+ await connection.execute(+ "INSERT INTO users(id,username,hashed_password,role,created_by) VALUES(?,?,?,?,?)",+ (_uuid(960), "p1a-exact-one", "fixed-hash", "admin", "fixed"),+ )+ await connection.commit()+ store = ExecutionLifecycleStore(connection, "sqlite")+ ensured = await store.ensure_actor_authority(_uuid(960), _uuid(961))+ updated = await store.invalidate_actor_authority(_uuid(960), 0, _uuid(962))+ row = await (+ await connection.execute(+ "SELECT revision,latest_operation_id FROM execution_actor_authority_revisions "+ "WHERE user_id=?",+ (_uuid(960),),+ )+ ).fetchone()+ receipt_count = await (+ await connection.execute(+ "SELECT count(*) FROM execution_operation_receipts WHERE operation_id=?",+ (_uuid(962),),+ )+ ).fetchone()+ finally:+ await connection.close()+ assert (ensured.result, updated.result, updated.revision) == (+ FixedResult.APPLIED,+ FixedResult.APPLIED,+ 1,+ ), "exactly-one truth write was not applied"+ assert tuple(row) == (1, _uuid(962)), "exactly-one truth write returned the wrong row"+ assert int(receipt_count[0]) == 1, "exactly-one truth write lost its receipt"+++async def test_sqlite_returning_row_disagrees_with_changes_is_invariant_failure() -> None:+ connection = await _new_connection()+ try:+ await connection.executescript(+ "CREATE TABLE p1a_changes_backing(id TEXT PRIMARY KEY,revision INTEGER NOT NULL);"+ "INSERT INTO p1a_changes_backing "+ "VALUES('00000000-0000-4000-8000-0000000003c3',0);"+ "CREATE VIEW p1a_changes_view AS SELECT id,revision FROM p1a_changes_backing;"+ "CREATE TRIGGER p1a_changes_view_update INSTEAD OF UPDATE ON p1a_changes_view "+ "BEGIN UPDATE p1a_changes_backing SET revision=NEW.revision WHERE id=OLD.id; END;"+ )+ await connection.commit()+ store = ExecutionLifecycleStore(connection, "sqlite")+ with pytest.raises(_AbortOperationError) as raised:+ async with store._transaction() as transaction:+ await store.cas_update_one(+ transaction,+ "UPDATE p1a_changes_view SET revision=revision+1 "+ "WHERE id=? AND revision=? RETURNING id,revision",+ (_uuid(963), 0),+ identity=_uuid(963),+ post_revision=1,+ zero_classifier=None,+ )+ row = await (+ await connection.execute(+ "SELECT revision FROM p1a_changes_backing WHERE id=?", (_uuid(963),)+ )+ ).fetchone()+ finally:+ await connection.close()+ assert raised.value.result.result is FixedResult.INVARIANT_FAILURE, (+ "RETURNING/changes disagreement was not fixed invariant failure"+ )+ assert int(row[0]) == 0, "RETURNING/changes invariant failure was not rolled back"+++ ("case", "expected_result", "expected_revision"),+ [+ ("missing", FixedResult.NOT_FOUND_OR_PURGED, None),+ ("stale-revision", FixedResult.CONFLICT_REVISION, 1),+ ("stale-state", FixedResult.CONFLICT_STATE, 0),+ ("stale-authority", FixedResult.AUTHORITY_STALE, 0),+ ("stale-owner", FixedResult.CONFLICT_OWNER, 1),+ ("stale-generation", FixedResult.CONFLICT_GENERATION, 1),+ ("stale-lease", FixedResult.CONFLICT_STATE, 1),+ ("stale-cancellation", FixedResult.CONFLICT_REVISION, 3),+ ("operation-conflict", FixedResult.CONFLICT_OPERATION, 0),+ ],+ ids=(+ "missing",+ "stale-revision",+ "stale-state",+ "stale-authority",+ "stale-owner",+ "stale-generation",+ "stale-lease",+ "stale-cancellation",+ "operation-conflict",+ ),+)+async def test_sqlite_zero_row_truth_write_is_reclassified_in_same_transaction(+ tmp_path,+ case: str,+ expected_result: FixedResult,+ expected_revision: int | None,+) -> None:+ connection, _setup_store = await _new_transition_case(+ (tmp_path / f"p1a-zero-{case}.db").as_posix(), AttemptState.ACCEPTED+ )+ try:+ request, settlement = await _p1a_transition_request(connection, case)+ await _install_zero_row_trigger(connection, case)+ store = _SQLiteZeroRowTraceStore(connection)+ result = (+ await store.enter_settlement_pending(request)+ if settlement+ else await store.transition_attempt(request)+ )+ assert store.zero_connection_id == id(connection), "zero-row write used another connection"+ assert store.zero_in_transaction is True, "zero-row write escaped its transaction"+ assert store.classifier_connection_ids, "zero-row write was not reread"+ assert set(store.classifier_connection_ids) == {id(connection)}, (+ "zero-row classifier changed connection"+ )+ assert all(store.classifier_in_transaction), (+ "zero-row classifier ran after transaction exit"+ )+ finally:+ await connection.close()+ assert (result.result, result.revision) == (expected_result, expected_revision), (+ "zero-row write received the wrong fixed classification"+ )+++async def test_sqlite_concurrent_cas_has_one_winner_and_fixed_loser(tmp_path) -> None:+ path = tmp_path / "p1a-concurrent-cas.db"+ winner_connection, _setup_store = await _new_transition_case(+ path.as_posix(), AttemptState.ACCEPTED+ )+ contender_connection = await aiosqlite.connect(path.as_posix())+ contender_connection.row_factory = aiosqlite.Row+ await contender_connection.execute("PRAGMA foreign_keys=ON")+ await contender_connection.execute("PRAGMA busy_timeout=5000")+ await contender_connection.commit()+ winner_entered = asyncio.Event()+ contender_attempted = asyncio.Event()+ winner_store = _SQLiteWinnerBarrierStore(winner_connection, winner_entered, contender_attempted)+ contender_store = _SQLiteContenderBarrierStore(contender_connection, contender_attempted)+ winner_task: asyncio.Task[Any] | None = None+ contender_task: asyncio.Task[Any] | None = None+ observer: aiosqlite.Connection | None = None+ try:+ winner_task = asyncio.create_task(+ winner_store.transition_attempt(+ TransitionRequest(+ _uuid(210),+ 0,+ AttemptState.QUEUED,+ _uuid(987),+ campaign_id=_uuid(201),+ actor_subject_ref=_uuid(200),+ actor_user_id=_uuid(200),+ actor_authority_revision=0,+ )+ )+ )+ await asyncio.wait_for(winner_entered.wait(), timeout=2)+ contender_task = asyncio.create_task(+ contender_store.transition_attempt(+ TransitionRequest(+ _uuid(210),+ 0,+ AttemptState.CANCELLING,+ _uuid(988),+ campaign_id=_uuid(201),+ actor_subject_ref=_uuid(200),+ actor_user_id=_uuid(200),+ actor_authority_revision=0,+ )+ )+ )+ await asyncio.wait_for(contender_attempted.wait(), timeout=2)+ winner, contender = await asyncio.wait_for(+ asyncio.gather(winner_task, contender_task), timeout=10+ )+ observer = await aiosqlite.connect(path.as_posix())+ row = await (+ await observer.execute(+ "SELECT state,revision FROM execution_attempts WHERE id=?", (_uuid(210),)+ )+ ).fetchone()+ receipt_count = await (+ await observer.execute(+ "SELECT count(*) FROM execution_operation_receipts WHERE operation_id IN (?,?)",+ (_uuid(987), _uuid(988)),+ )+ ).fetchone()+ finally:+ for task in (winner_task, contender_task):+ if task is not None and not task.done():+ task.cancel()+ pending = tuple(+ task for task in (winner_task, contender_task) if task is not None and not task.done()+ )+ if pending:+ await asyncio.gather(*pending, return_exceptions=True)+ if observer is not None:+ await observer.close()+ await contender_connection.close()+ await winner_connection.close()+ assert (winner.result, contender.result) == (+ FixedResult.APPLIED,+ FixedResult.CONFLICT_REVISION,+ ), "concurrent SQLite CAS winner/loser changed"+ assert tuple(row) == (AttemptState.QUEUED.value, 1), "concurrent CAS changed more than once"+ assert int(receipt_count[0]) == 1, "concurrent CAS wrote a loser receipt"+++async def test_sqlite_cancelled_truth_write_rolls_back_and_connection_reuses(tmp_path) -> None:+ path = tmp_path / "p1a-cancelled-write.db"+ connection = await _new_connection(path.as_posix())+ receipt_entered = asyncio.Event()+ receipt_release = asyncio.Event()+ store = _SQLiteCancellationGateStore(connection, receipt_entered, receipt_release)+ task: asyncio.Task[Any] | None = None+ observer: aiosqlite.Connection | None = None+ try:+ await connection.execute(+ "INSERT INTO users(id,username,hashed_password,role,created_by) VALUES(?,?,?,?,?)",+ (_uuid(964), "p1a-cancelled", "fixed-hash", "admin", "fixed"),+ )+ await connection.commit()+ task = asyncio.create_task(store.ensure_actor_authority(_uuid(964), _uuid(965)))+ await asyncio.wait_for(receipt_entered.wait(), timeout=2)+ assert connection.in_transaction is True, "cancellation gate was outside the transaction"+ task.cancel()+ with pytest.raises(asyncio.CancelledError):+ await asyncio.wait_for(task, timeout=2)+ assert connection.in_transaction is False, "cancelled write retained a transaction"+ observer = await aiosqlite.connect(path.as_posix())+ counts = await (+ await observer.execute(+ "SELECT (SELECT count(*) FROM execution_actor_authority_revisions),"+ "(SELECT count(*) FROM execution_operation_receipts)"+ )+ ).fetchone()+ await observer.close()+ observer = None+ store.armed = False+ reused = await store.ensure_actor_authority(_uuid(964), _uuid(965))+ finally:+ receipt_release.set()+ if task is not None and not task.done():+ task.cancel()+ await asyncio.gather(task, return_exceptions=True)+ if observer is not None:+ await observer.close()+ await connection.close()+ assert tuple(counts) == (0, 0), "cancelled truth write leaked partial state"+ assert reused.result is FixedResult.APPLIED, "cancelled SQLite connection was not reusable"+++ "stage",+ ["transaction-rollback", "savepoint-rollback", "savepoint-release"],+ ids=("transaction-rollback", "savepoint-rollback", "savepoint-release"),+)+async def test_sqlite_primary_fixed_failure_survives_cleanup_failure(+ monkeypatch, stage: str+) -> None:+ cleanup_faults: list[str] = []+ if stage == "transaction-rollback":+ connection = await _new_connection()+ try:+ await connection.execute(+ "INSERT INTO users(id,username,hashed_password,role,created_by) VALUES(?,?,?,?,?)",+ (_uuid(966), "p1a-cleanup", "fixed-hash", "admin", "fixed"),+ )+ await connection.commit()+ original_rollback = connection.rollback++ async def rollback_then_fail() -> None:+ await original_rollback()+ cleanup_faults.append(stage)+ raise RuntimeError("fixed-sqlite-cleanup-failure")++ monkeypatch.setattr(connection, "rollback", rollback_then_fail)+ store = _SQLiteCleanupFailureStore(connection, stage, cleanup_faults)+ original_returning = store._returning_rows++ async def duplicate_insert_rows(+ fault_connection: Any, sql: str, params: tuple[Any, ...]+ ) -> tuple[Any, ...]:+ rows = await original_returning(fault_connection, sql, params)+ if store.armed and rows and "execution_actor_authority_revisions" in sql:+ return rows + rows+ return rows++ monkeypatch.setattr(store, "_returning_rows", duplicate_insert_rows)+ failed = await store.ensure_actor_authority(_uuid(966), _uuid(967))+ store.armed = False+ reused = await store.ensure_actor_authority(_uuid(966), _uuid(967))+ finally:+ await connection.close()+ else:+ connection, _setup_store = await _new_transition_case(":memory:", AttemptState.ACCEPTED)+ try:+ store = _SQLiteCleanupFailureStore(connection, stage, cleanup_faults)+ request = TransitionRequest(+ _uuid(210),+ 0,+ AttemptState.QUEUED,+ _uuid(968),+ campaign_id=_uuid(201),+ actor_subject_ref=_uuid(200),+ actor_user_id=_uuid(200),+ actor_authority_revision=0,+ )+ failed = await store.transition_attempt(request)+ store.armed = False+ reused = await store.transition_attempt(request)+ finally:+ await connection.close()+ assert failed.result is FixedResult.INVARIANT_FAILURE, (+ "cleanup failure replaced the primary fixed failure"+ )+ assert cleanup_faults == [stage], "cleanup failure stage was not deterministic"+ assert reused.result is FixedResult.APPLIED, "cleanup failure left SQLite unusable"+++_SQLITE_P1C_TERMINAL_V3_ALIASES = (+ "invalid-contract-before-receipt",+ "v3-binding-vector-and-operation-codes",+ "receipt-replay-after-target-deletion",+ "receipt-replay-zero-mutable-reads",+ "changed-intent-conflict-operation",+ "known-success-atomic",+ "known-failure-atomic",+ "acknowledged-cancellation-atomic",+ "acknowledged-timeout-atomic",+ "uncertain-outcome-invalid-contract",+ "single-transaction-zero-nested-acquire",+ "derive-exact-three-held-ledgers",+ "missing-ledger-inconsistent-set-rollback",+ "duplicate-extra-ledger-inconsistent-set-rollback",+ "wrong-kind-ledger-inconsistent-set-rollback",+ "wrong-campaign-attempt-ledger-inconsistent-set-rollback",+ "non-held-ledger-conflict-operation-rollback",+ "current-budget-lock-no-toctou",+ "budget-capacity-inconsistent-set-rollback",+ "budget-write-failure-rollback",+ "output-write-failure-rollback",+ "terminal-write-failure-rollback",+ "logical-closure-write-failure-rollback",+ "outbox-write-failure-rollback",+ "receipt-write-failure-rollback",+ "public-intent-excludes-derived-fields",+ "missing-attempt-not-found-or-purged",+ "non-running-attempt-conflict-state",+ "stale-attempt-revision-conflict",+ "invariant-failure-rollback",+ "cancellation-rollback-and-reuse",+ "exception-rollback-and-reuse",+ "legacy-terminal-apply-replay-bytes-unchanged",+ "legacy-v3-crossing-conflict-operation",+ "changed-outcome-conflict-operation",+ "changed-result-digest-conflict-operation",+ "cancellation-caller-result-digest-invalid-contract",+ "timeout-caller-result-digest-invalid-contract",+ "canonical-output-order-exact-replay",+ "terminal-operation-and-system-principal-namespace",+ "derived-revision-overflow-invariant-failure-rollback",+)++_SQLITE_P1C_TERMINAL_NODE_COUNT = 41+_SQLITE_P1C_TERMINAL_NODE_ID_SHA256 = (+ "5d7df72980bd3e7fdc4bf809965568b127a19f5a080a95b116b221cafb347e4e"+)+++def _sqlite_p1c_terminal_inventory_digest() -> str:+ encoded = bytearray(b"ares.p1c-terminal-v3-sqlite-test-inventory.v1\x00")+ for alias in _SQLITE_P1C_TERMINAL_V3_ALIASES:+ node_id = (+ "tests/unit/test_execution_lifecycle_persistence.py::"+ f"test_sqlite_p1c_terminal_v3_seam[{alias}]"+ ).encode()+ encoded.extend(struct.pack(">I", len(node_id)))+ encoded.extend(node_id)+ return hashlib.sha256(encoded).hexdigest()+++assert len(_SQLITE_P1C_TERMINAL_V3_ALIASES) == _SQLITE_P1C_TERMINAL_NODE_COUNT+assert len(set(_SQLITE_P1C_TERMINAL_V3_ALIASES)) == _SQLITE_P1C_TERMINAL_NODE_COUNT+assert _sqlite_p1c_terminal_inventory_digest() == _SQLITE_P1C_TERMINAL_NODE_ID_SHA256++_SQLITE_P1C_TERMINAL_RESULT_DIGEST = hashlib.sha256(+ b"sqlite-p1c-terminal-v3-known-result"+).hexdigest()+++def _sqlite_p1c_binding_digest(+ domain: str,+ values: tuple[tuple[str, str | int | bool | None], ...],+) -> str:+ """Independent literal oracle for the protected v2 typed framing."""+ encoded = bytearray(b"ares.execution-operation-binding.v2\x00")++ def frame(value: bytes) -> None:+ encoded.extend(struct.pack(">I", len(value)))+ encoded.extend(value)++ frame(domain.encode("ascii"))+ seen: set[str] = set()+ for name, value in values:+ assert name not in seen, "SQLite terminal oracle contains a duplicate field"+ seen.add(name)+ frame(name.encode("ascii"))+ if value is None:+ encoded.extend(b"n")+ elif type(value) is bool:+ encoded.extend(b"b\x01" if value else b"b\x00")+ elif type(value) is int:+ encoded.extend(b"i")+ frame(value.to_bytes(8, "big", signed=False))+ elif type(value) is str:+ encoded.extend(b"s")+ frame(value.encode("utf-8"))+ else: # pragma: no cover - a broken test oracle must be loud.+ raise AssertionError("unsupported SQLite terminal oracle value")+ return hashlib.sha256(encoded).hexdigest()+++def _sqlite_p1c_terminal_operation_id(attempt_id: str) -> str:+ digest = _sqlite_p1c_binding_digest(+ "terminal-commit-operation-id.v3",+ (("attempt_id", attempt_id), ("action", "commit-known-settled")),+ )+ return (+ digest[:8]+ + "-"+ + digest[8:12]+ + "-4"+ + digest[13:16]+ + "-8"+ + digest[17:20]+ + "-"+ + digest[20:32]+ )+++def _sqlite_p1c_terminal_operation_code(outcome: OutcomeCode) -> str:+ return {+ OutcomeCode.CONFIRMED_SUCCESS: "terminal_succeeded",+ OutcomeCode.CONFIRMED_FAILURE: "terminal_failed",+ OutcomeCode.CONFIRMED_CANCELLED_NO_RESULT: "cancellation_acknowledgement",+ OutcomeCode.CONFIRMED_TIMEOUT_TERMINATED: "timeout",+ }[outcome]+++def _sqlite_p1c_terminal_request_digest(intent: TerminalCommitIntentV3) -> str:+ operation_id = _sqlite_p1c_terminal_operation_id(intent.attempt_id)+ operation_code = _sqlite_p1c_terminal_operation_code(intent.outcome_code)+ canonical_outputs = tuple(+ sorted(+ intent.outputs,+ key=lambda item: (item.kind.value, item.target_id, item.link_id),+ )+ )+ output_fields = tuple(+ field+ for index, output in enumerate(canonical_outputs)+ for field in (+ (f"output_{index}_link_id", output.link_id),+ (f"output_{index}_kind", output.kind.value),+ (f"output_{index}_target_id", output.target_id),+ )+ )+ return _sqlite_p1c_binding_digest(+ "execution-terminal-commit.v3.request",+ (+ ("terminal_commit_contract_version", 3),+ ("logical_execution_id", intent.logical_execution_id),+ ("campaign_id", intent.campaign_id),+ ("attempt_id", intent.attempt_id),+ ("operation_id", operation_id),+ ("expected_attempt_revision", intent.expected_attempt_revision),+ ("operation_code", operation_code),+ ("outcome_code", intent.outcome_code.value),+ ("noise_actual", intent.noise_actual),+ ("exfiltration_actual", intent.exfiltration_actual),+ ("concurrency_actual", intent.concurrency_actual),+ (+ "execution_result_digest_present",+ intent.execution_result_digest is not None,+ ),+ ("execution_result_digest", intent.execution_result_digest),+ ("output_count", len(canonical_outputs)),+ )+ + output_fields,+ )+++def _sqlite_p1c_terminal_derived_uuid(operation_id: str, label: str) -> str:+ digest = hashlib.sha256((operation_id + "\x00" + label).encode("ascii")).hexdigest()+ return (+ digest[:8]+ + "-"+ + digest[8:12]+ + "-4"+ + digest[13:16]+ + "-8"+ + digest[17:20]+ + "-"+ + digest[20:32]+ )+++def _sqlite_p1c_terminal_result_digest(intent: TerminalCommitIntentV3) -> str:+ operation_id = _sqlite_p1c_terminal_operation_id(intent.attempt_id)+ operation_code = _sqlite_p1c_terminal_operation_code(intent.outcome_code)+ target, proof = {+ OutcomeCode.CONFIRMED_SUCCESS: (AttemptState.SUCCEEDED, "local_completion"),+ OutcomeCode.CONFIRMED_FAILURE: (AttemptState.FAILED, "local_completion"),+ OutcomeCode.CONFIRMED_CANCELLED_NO_RESULT: (+ AttemptState.CANCELLED,+ "cancellation_no_result_ack",+ ),+ OutcomeCode.CONFIRMED_TIMEOUT_TERMINATED: (+ AttemptState.TIMED_OUT,+ "timeout_termination_ack",+ ),+ }[intent.outcome_code]+ post_revision = intent.expected_attempt_revision + 1+ outbox_id = _sqlite_p1c_terminal_derived_uuid(operation_id, "terminal-outbox")+ publication_key = _sqlite_p1c_terminal_derived_uuid(+ operation_id,+ "terminal-publication",+ )+ counts = tuple(+ sum(output.kind is kind for output in intent.outputs)+ for kind in (+ OutputKind.FINDING,+ OutputKind.CREDENTIAL,+ OutputKind.HOST,+ OutputKind.ARTIFACT,+ )+ )+ return _sqlite_p1c_binding_digest(+ "execution-terminal-commit.v3.result",+ (+ ("result_code", FixedResult.APPLIED.value),+ ("exact_replay_code", FixedResult.REPLAYED.value),+ ("result_identity_present", True),+ ("result_identity", intent.attempt_id),+ ("result_revision_present", True),+ ("result_revision", post_revision),+ ("secondary_result_identity_present", True),+ ("secondary_result_identity", intent.logical_execution_id),+ ("secondary_result_revision_present", True),+ ("secondary_result_revision", 1),+ ("state", target.value),+ ("revision", post_revision),+ ("closes_logical", True),+ ("finding_count", counts[0]),+ ("credential_count", counts[1]),+ ("host_count", counts[2]),+ ("artifact_count", counts[3]),+ ("outbox_id", outbox_id),+ ("terminal_commit_contract_version", 3),+ ("operation_id", operation_id),+ ("operation_code", operation_code),+ ("campaign_id", intent.campaign_id),+ ("logical_execution_id", intent.logical_execution_id),+ ("attempt_id", intent.attempt_id),+ ("outcome_code", intent.outcome_code.value),+ ("authoritative_proof", proof),+ ("retry_eligible", False),+ (+ "execution_result_digest_present",+ intent.execution_result_digest is not None,+ ),+ ("execution_result_digest", intent.execution_result_digest),+ ("publication_key", publication_key),+ ),+ )+++async def _sqlite_p1c_terminal_case(+ path: Any,+ *,+ predecessor: AttemptState = AttemptState.RUNNING,+) -> tuple[aiosqlite.Connection, ExecutionLifecycleStore, int]:+ connection, store = await _new_transition_case(path.as_posix(), AttemptState.ACCEPTED)+ if predecessor is AttemptState.ACCEPTED:+ return connection, store, 0+ dispatched = await _nonterminal_transition(store, connection, AttemptState.DISPATCHING, 20_100)+ assert dispatched.result is FixedResult.APPLIED, "terminal fixture dispatch failed"+ running = await _nonterminal_transition(store, connection, AttemptState.RUNNING, 20_101)+ assert running.result is FixedResult.APPLIED, "terminal fixture start failed"+ if predecessor is AttemptState.CANCELLING:+ cancelling = await _nonterminal_transition(+ store, connection, AttemptState.CANCELLING, 20_102+ )+ assert cancelling.result is FixedResult.APPLIED, "terminal fixture cancel failed"+ return connection, store, 3+ assert predecessor is AttemptState.RUNNING, "unsupported terminal fixture predecessor"+ return connection, store, 2+++def _sqlite_p1c_terminal_intent(+ expected_revision: int,+ *,+ outcome: OutcomeCode = OutcomeCode.CONFIRMED_SUCCESS,+ execution_result_digest: str | None | object = ...,+ outputs: tuple[OutputObservation, ...] = (),+ noise_actual: int = 1,+ exfiltration_actual: int = 2,+ concurrency_actual: int = 0,+) -> TerminalCommitIntentV3:+ if execution_result_digest is ...:+ execution_result_digest = (+ None+ if outcome+ in {+ OutcomeCode.CONFIRMED_CANCELLED_NO_RESULT,+ OutcomeCode.CONFIRMED_TIMEOUT_TERMINATED,+ }+ else _SQLITE_P1C_TERMINAL_RESULT_DIGEST+ )+ return TerminalCommitIntentV3(+ logical_execution_id=_uuid(208),+ campaign_id=_uuid(201),+ attempt_id=_uuid(210),+ expected_attempt_revision=expected_revision,+ outcome_code=outcome,+ noise_actual=noise_actual,+ exfiltration_actual=exfiltration_actual,+ concurrency_actual=concurrency_actual,+ execution_result_digest=execution_result_digest, # type: ignore[arg-type]+ outputs=outputs,+ )+++async def _sqlite_p1c_terminal_receipt(+ connection: aiosqlite.Connection, attempt_id: str = _uuid(210)+) -> Any:+ return await (+ await connection.execute(+ "SELECT operation_id,operation_code,campaign_id,primary_target_id,"+ "secondary_target_id,principal_kind,principal_subject_ref,principal_user_id,"+ "principal_authority_revision_present,principal_authority_revision,"+ "binding_contract_version,request_binding_digest,result_code,exact_replay_code,"+ "result_binding_digest,result_identity,result_revision,secondary_result_identity,"+ "secondary_result_revision FROM execution_operation_receipts "+ "WHERE operation_id=?",+ (_sqlite_p1c_terminal_operation_id(attempt_id),),+ )+ ).fetchone()+++async def _sqlite_p1c_terminal_state(connection: aiosqlite.Connection) -> Any:+ return await (+ await connection.execute(+ "SELECT state,revision,outcome_code,settlement_state,settlement_proof_code,"+ "termination_confirmed,closes_logical,retry_disposition,terminal_operation_id,"+ "cancellation_ack_operation_id,timeout_operation_id "+ "FROM execution_attempts WHERE id=?",+ (_uuid(210),),+ )+ ).fetchone()+++def _sqlite_p1c_legacy_terminal_request(+ operation_id: str,+ expected_revision: int,+) -> TerminalCommitRequest:+ return TerminalCommitRequest(+ _uuid(208),+ _uuid(201),+ _uuid(20_200),+ _uuid(20_201),+ TransitionRequest(+ _uuid(210),+ expected_revision,+ AttemptState.SUCCEEDED,+ operation_id,+ owner_ref=_uuid(220),+ lease_generation=1,+ outcome_code=OutcomeCode.CONFIRMED_SUCCESS,+ authoritative_proof="local_completion",+ campaign_id=_uuid(201),+ ),+ BudgetSettlement(+ _uuid(201),+ _uuid(210),+ _uuid(204),+ 2,+ 1,+ 1,+ _uuid(205),+ 3,+ 2,+ 1,+ _uuid(206),+ 1,+ _uuid(20_202),+ ),+ )+++_SQLITE_P1C_LEGACY_TERMINAL_RECEIPT_VECTORS = (+ (+ _uuid(20_200),+ "outbox_insert",+ 2,+ "5dccdba355c4feef9cd6df03d5d6b3c8af06feee7ee618108615a35a545425e7",+ "7a50d0b26f31239a9fba139b28affd32750988bb7d6dc360c0a570ea8856a0d3",+ ),+ (+ _uuid(20_202),+ "budget_settle",+ 2,+ "e0d4a8b6ca4ea2e38967e3158283cd1fa175279a41b1c55490cebbf76b48a9a1",+ "04f8900897528d734dd7f4fd030af712b34e2cd18ddf929f247b20494f5ddcad",+ ),+ (+ _uuid(20_400),+ "terminal_succeeded",+ 2,+ "da5caf4a079873de9cdea7f31a284bcac45bdd3526c602038aaeb66147fc5cb8",+ "0b15cef8a5886d92669f712e36c80a91e4e10d00a1e0d92d6a479ad1bde08278",+ ),+)+++class _SQLiteP1CTerminalTraceStore(ExecutionLifecycleStore):+ def __init__(+ self,+ backend: Any,+ *,+ receipt_only: bool = False,+ duplicate_ledger_row: bool = False,+ ledger_mutation: str | None = None,+ fail_at: str | None = None,+ cancel_at: str | None = None,+ duplicate_terminal_returning: bool = False,+ ) -> None:+ super().__init__(backend, "sqlite")+ self.receipt_only = receipt_only+ self.duplicate_ledger_row = duplicate_ledger_row+ self.ledger_mutation = ledger_mutation+ self.fail_at = fail_at+ self.cancel_at = cancel_at+ self.duplicate_terminal_returning = duplicate_terminal_returning+ self.transaction_entries = 0+ self.connection_identities: set[int] = set()+ self.read_events: list[str] = []+ self.budget_writes = 0+ self.output_insert_order: list[str] = []++ @asynccontextmanager+ async def _transaction(self) -> AsyncIterator[Any]:+ self.transaction_entries += 1+ async with super()._transaction() as connection:+ self.connection_identities.add(id(connection))+ yield connection++ async def _fetchrow(self, connection: Any, sql: str, params: Any) -> Any:+ self.connection_identities.add(id(connection))+ self.read_events.append("receipt" if "execution_operation_receipts" in sql else "mutable")+ if self.receipt_only and "execution_operation_receipts" not in sql:+ raise AssertionError("exact terminal replay read a mutable target")+ return await super()._fetchrow(connection, sql, params)++ async def _fetchall(self, connection: Any, sql: str, params: Any) -> Any:+ self.connection_identities.add(id(connection))+ self.read_events.append("mutable")+ if self.receipt_only:+ raise AssertionError("exact terminal receipt classification read a mutable set")+ rows = tuple(await super()._fetchall(connection, sql, params))+ if self.duplicate_ledger_row and "FROM campaign_execution_budget_ledger" in sql and rows:+ return rows + (rows[0],)+ if (+ self.ledger_mutation is not None+ and "FROM campaign_execution_budget_ledger" in sql+ and rows+ ):+ mutable = [list(row) for row in rows]+ if self.ledger_mutation == "kind":+ mutable[0][4] = "exfiltration"+ elif self.ledger_mutation == "campaign":+ mutable[0][2] = _uuid(20_300)+ elif self.ledger_mutation == "attempt":+ mutable[0][1] = _uuid(20_301)+ else: # pragma: no cover - invalid fault label is a broken test.+ raise AssertionError("unknown terminal ledger mutation")+ return tuple(tuple(row) for row in mutable)+ return rows++ async def _returning_rows(self, connection: Any, sql: str, params: Any) -> Any:+ self.connection_identities.add(id(connection))+ rows = await super()._returning_rows(connection, sql, params)+ if (+ self.duplicate_terminal_returning+ and "UPDATE execution_attempts SET state=" in sql+ and rows+ ):+ return rows + rows+ return rows++ async def cas_update_one(self, connection: Any, sql: str, params: Any, **kwargs: Any) -> Any:+ row = await super().cas_update_one(connection, sql, params, **kwargs)+ if "UPDATE campaign_execution_budgets" in sql:+ self.budget_writes += 1+ if self.fail_at == "budget" and self.budget_writes == 2:+ raise RuntimeError("fixed-terminal-budget-write-failure")+ if self.fail_at == "terminal" and "UPDATE execution_attempts SET state=" in sql:+ raise RuntimeError("fixed-terminal-attempt-write-failure")+ if self.fail_at == "logical" and "UPDATE logical_executions SET closure" in sql:+ raise RuntimeError("fixed-terminal-logical-write-failure")+ return row++ async def _insert_output_links(self, *args: Any, **kwargs: Any) -> Any:+ counts = await super()._insert_output_links(*args, **kwargs)+ if self.fail_at == "output":+ raise RuntimeError("fixed-terminal-output-write-failure")+ if self.fail_at == "exception":+ raise RuntimeError("fixed-terminal-exception")+ if self.cancel_at == "output":+ raise asyncio.CancelledError+ return counts++ async def update_exact_set(+ self,+ connection: Any,+ sql: str,+ params: Any,+ **kwargs: Any,+ ) -> Any:+ result = await super().update_exact_set(connection, sql, params, **kwargs)+ if "INSERT INTO execution_output_links" in sql:+ self.output_insert_order.append(str(params[0]))+ return result++ async def _insert_terminal_outbox(self, *args: Any, **kwargs: Any) -> Any:+ result = await super()._insert_terminal_outbox(*args, **kwargs)+ if self.fail_at == "outbox":+ raise RuntimeError("fixed-terminal-outbox-write-failure")+ return result++ async def _insert_receipt(self, connection: Any, spec: Any, **kwargs: Any) -> Any:+ result = await super()._insert_receipt(connection, spec, **kwargs)+ if self.fail_at == "receipt" and spec.operation_code in {+ "terminal_succeeded",+ "terminal_failed",+ "cancellation_acknowledgement",+ "timeout",+ }:+ raise RuntimeError("fixed-terminal-receipt-write-failure")+ return result++ async def _insert_terminal_v3_receipt(self, *args: Any, **kwargs: Any) -> Any:+ result = await super()._insert_terminal_v3_receipt(*args, **kwargs)+ if self.fail_at == "receipt":+ raise RuntimeError("fixed-terminal-v3-receipt-write-failure")+ return result+++async def _sqlite_p1c_assert_rollback(+ connection: aiosqlite.Connection,+ store: ExecutionLifecycleStore,+ intent: TerminalCommitIntentV3,+ *,+ expected_result: FixedResult | None = None,+ expected_exception: type[BaseException] | None = None,+) -> OperationResult | None:+ before = await _snapshot_case(connection)+ if expected_exception is None:+ result = await store.commit_terminal_attempt_v3(intent)+ assert result.result is expected_result, "terminal rollback result changed"+ else:+ with pytest.raises(expected_exception):+ await store.commit_terminal_attempt_v3(intent)+ result = None+ after = await _snapshot_case(connection)+ assert after == before, "terminal failure committed partial state"+ return result+++ "case_alias",+ _SQLITE_P1C_TERMINAL_V3_ALIASES,+ ids=_SQLITE_P1C_TERMINAL_V3_ALIASES,+)+async def test_sqlite_p1c_terminal_v3_seam(tmp_path, case_alias: str) -> None: # noqa: C901, PLR0912, PLR0915+ if case_alias == "public-intent-excludes-derived-fields":+ public_dataclass_fields = fields(TerminalCommitIntentV3)+ public_fields = tuple(item.name for item in public_dataclass_fields)+ assert public_fields == (+ "logical_execution_id",+ "campaign_id",+ "attempt_id",+ "expected_attempt_revision",+ "outcome_code",+ "noise_actual",+ "exfiltration_actual",+ "concurrency_actual",+ "execution_result_digest",+ "outputs",+ ), "terminal public authority surface changed"+ assert get_type_hints(TerminalCommitIntentV3) == {+ "logical_execution_id": str,+ "campaign_id": str,+ "attempt_id": str,+ "expected_attempt_revision": int,+ "outcome_code": OutcomeCode,+ "noise_actual": int,+ "exfiltration_actual": int,+ "concurrency_actual": int,+ "execution_result_digest": str | None,+ "outputs": tuple[OutputObservation, ...],+ }, "terminal public field types changed"+ assert all(item.default is MISSING for item in public_dataclass_fields[:-1])+ assert public_dataclass_fields[-1].default == (), "terminal output default changed"+ dataclass_parameters = TerminalCommitIntentV3.__dataclass_params__+ assert is_dataclass(TerminalCommitIntentV3)+ assert (+ dataclass_parameters.init,+ dataclass_parameters.repr,+ dataclass_parameters.eq,+ dataclass_parameters.order,+ dataclass_parameters.unsafe_hash,+ dataclass_parameters.frozen,+ ) == (True, False, False, False, False, True)+ assert TerminalCommitIntentV3.__slots__ == public_fields+ assert TerminalCommitIntentV3.__hash__ is None+ forbidden = {+ "operation_id",+ "principal_kind",+ "principal_subject_ref",+ "principal_user_id",+ "principal_authority_revision",+ "actor_subject_ref",+ "actor_user_id",+ "actor_authority_revision",+ "campaign_authority_revision",+ "budget_id",+ "budget_ids",+ "ledger_id",+ "ledger_ids",+ "reserved_units",+ "budget_revision",+ "current_budget_revision",+ "retry_eligibility",+ "retry_eligible",+ "policy_result",+ "closure_disposition",+ "receipt_classification",+ }+ assert not forbidden.intersection(public_fields), (+ "caller authority leaked into terminal intent"+ )+ baseline = _sqlite_p1c_terminal_intent(2)+ assert not hasattr(baseline, "__dict__"), "terminal intent lost its slot boundary"+ with pytest.raises(FrozenInstanceError):+ baseline.campaign_id = _uuid(20_299)+ values = {item.name: getattr(baseline, item.name) for item in fields(baseline)}+ for name in sorted(forbidden):+ with pytest.raises(TypeError):+ TerminalCommitIntentV3(**values, **{name: "caller-controlled"})+ return++ if case_alias == "missing-attempt-not-found-or-purged":+ connection = await _new_connection()+ try:+ result = await ExecutionLifecycleStore(connection, "sqlite").commit_terminal_attempt_v3(+ _sqlite_p1c_terminal_intent(0)+ )+ receipt = await _sqlite_p1c_terminal_receipt(connection)+ finally:+ await connection.close()+ assert (result.result, result.revision) == (+ FixedResult.NOT_FOUND_OR_PURGED,+ None,+ )+ assert receipt is None, "missing attempt created a receipt"+ return++ if case_alias == "v3-binding-vector-and-operation-codes":+ cases = (+ (OutcomeCode.CONFIRMED_SUCCESS, AttemptState.RUNNING, "terminal_succeeded"),+ (OutcomeCode.CONFIRMED_FAILURE, AttemptState.RUNNING, "terminal_failed"),+ (+ OutcomeCode.CONFIRMED_CANCELLED_NO_RESULT,+ AttemptState.CANCELLING,+ "cancellation_acknowledgement",+ ),+ (OutcomeCode.CONFIRMED_TIMEOUT_TERMINATED, AttemptState.RUNNING, "timeout"),+ )+ for index, (outcome, predecessor, operation_code) in enumerate(cases):+ connection, store, revision = await _sqlite_p1c_terminal_case(+ tmp_path / f"binding-{index}.db", predecessor=predecessor+ )+ try:+ intent = _sqlite_p1c_terminal_intent(revision, outcome=outcome)+ result = await store.commit_terminal_attempt_v3(intent)+ receipt = await _sqlite_p1c_terminal_receipt(connection)+ finally:+ await connection.close()+ assert result.result is FixedResult.APPLIED, "terminal binding case failed"+ assert receipt[0] == _sqlite_p1c_terminal_operation_id(intent.attempt_id)+ assert receipt[1] == operation_code, "terminal operation code changed"+ assert receipt[10] == 2, "receipt storage contract version changed"+ assert receipt[11] == _sqlite_p1c_terminal_request_digest(intent), (+ "terminal request binding vector changed"+ )+ assert receipt[14] == _sqlite_p1c_terminal_result_digest(intent), (+ "terminal result binding vector changed"+ )+ assert receipt[14] != intent.execution_result_digest, (+ "terminal receipt result binding conflated the execution-result digest"+ )+ return++ predecessor = (+ AttemptState.CANCELLING+ if case_alias+ in {+ "acknowledged-cancellation-atomic",+ "cancellation-caller-result-digest-invalid-contract",+ }+ else AttemptState.ACCEPTED+ if case_alias == "non-running-attempt-conflict-state"+ else AttemptState.RUNNING+ )+ connection, base_store, revision = await _sqlite_p1c_terminal_case(+ tmp_path / "terminal.db", predecessor=predecessor+ )+ store: ExecutionLifecycleStore = base_store+ intent = _sqlite_p1c_terminal_intent(revision)+ try:+ if case_alias == "invalid-contract-before-receipt":+ trace = _SQLiteP1CTerminalTraceStore(connection)+ duplicate_output = OutputObservation(_uuid(20_610), OutputKind.HOST, _uuid(260))+ same_link_other_target = OutputObservation(+ duplicate_output.link_id,+ OutputKind.HOST,+ _uuid(261),+ )+ same_target_other_link = OutputObservation(+ _uuid(20_611),+ OutputKind.HOST,+ duplicate_output.target_id,+ )+ oversized_outputs = tuple(+ OutputObservation(_uuid(21_000 + index), OutputKind.HOST, _uuid(22_000 + index))+ for index in range(257)+ )+ invalids = (+ replace(intent, expected_attempt_revision=MAX_I53),+ replace(intent, expected_attempt_revision=True),+ replace(intent, expected_attempt_revision=-1),+ replace(intent, attempt_id="not-a-canonical-uuid"),+ replace(intent, noise_actual=True),+ replace(intent, exfiltration_actual=True),+ replace(intent, concurrency_actual=True),+ replace(intent, noise_actual=-1),+ replace(intent, noise_actual=MAX_I53 + 1),+ replace(intent, concurrency_actual=1),+ replace(intent, execution_result_digest=None),+ replace(+ intent,+ execution_result_digest=_SQLITE_P1C_TERMINAL_RESULT_DIGEST.upper(),+ ),+ replace(intent, execution_result_digest="a" * 63),+ replace(intent, outputs=(duplicate_output, duplicate_output)),+ replace(intent, outputs=(duplicate_output, same_link_other_target)),+ replace(intent, outputs=(duplicate_output, same_target_other_link)),+ replace(intent, outputs=[duplicate_output]), # type: ignore[arg-type]+ replace(intent, outputs=oversized_outputs),+ replace(+ intent,+ outcome_code=OutcomeCode.CONFIRMED_FAILURE,+ outputs=(duplicate_output,),+ ),+ )+ before = await _snapshot_case(connection)+ results = tuple([await trace.commit_terminal_attempt_v3(item) for item in invalids])+ assert all(item.result is FixedResult.INVALID_CONTRACT for item in results)+ assert trace.transaction_entries == 0, "invalid intent entered a transaction"+ assert await _snapshot_case(connection) == before+ elif case_alias == "receipt-replay-after-target-deletion":+ applied = await store.commit_terminal_attempt_v3(intent)+ receipt_before = await _sqlite_p1c_terminal_receipt(connection)+ await connection.execute("PRAGMA foreign_keys=OFF")+ await connection.execute("DELETE FROM campaigns WHERE id=?", (_uuid(201),))+ await connection.execute("DELETE FROM logical_executions WHERE id=?", (_uuid(208),))+ await connection.execute("DELETE FROM execution_attempts WHERE id=?", (_uuid(210),))+ await connection.execute("DELETE FROM campaign_execution_budgets")+ await connection.execute("DELETE FROM campaign_execution_budget_ledger")+ await connection.execute("DELETE FROM execution_publication_outbox")+ await connection.commit()+ mutable_counts = []+ for table, predicate, parameters in (+ ("campaigns", "id=?", (_uuid(201),)),+ ("logical_executions", "id=?", (_uuid(208),)),+ ("execution_attempts", "id=?", (_uuid(210),)),+ ("campaign_execution_budgets", "campaign_id=?", (_uuid(201),)),+ ("campaign_execution_budget_ledger", "campaign_id=?", (_uuid(201),)),+ ("execution_publication_outbox", "campaign_id=?", (_uuid(201),)),+ ):+ row = await (+ await connection.execute(+ f"SELECT COUNT(*) FROM {table} WHERE {predicate}", # noqa: S608+ parameters,+ )+ ).fetchone()+ mutable_counts.append(int(row[0]))+ assert mutable_counts == [0] * 6, "terminal replay targets were not deleted"+ replayed = await store.commit_terminal_attempt_v3(intent)+ receipt_after = await _sqlite_p1c_terminal_receipt(connection)+ assert (applied.result, replayed.result, replayed.revision) == (+ FixedResult.APPLIED,+ FixedResult.REPLAYED,+ revision + 1,+ )+ assert tuple(receipt_before) == tuple(receipt_after), (+ "terminal replay changed its immutable result identities"+ )+ elif case_alias == "receipt-replay-zero-mutable-reads":+ applied = await store.commit_terminal_attempt_v3(intent)+ trace = _SQLiteP1CTerminalTraceStore(connection, receipt_only=True)+ replayed = await trace.commit_terminal_attempt_v3(intent)+ assert (applied.result, replayed.result) == (+ FixedResult.APPLIED,+ FixedResult.REPLAYED,+ )+ assert trace.transaction_entries == 1+ elif case_alias == "changed-intent-conflict-operation":+ applied = await store.commit_terminal_attempt_v3(intent)+ receipt_only = _SQLiteP1CTerminalTraceStore(connection, receipt_only=True)+ changed = tuple(+ [+ await receipt_only.commit_terminal_attempt_v3(changed_intent)+ for changed_intent in (+ replace(intent, noise_actual=0),+ replace(+ intent,+ outputs=(+ OutputObservation(+ _uuid(20_612),+ OutputKind.HOST,+ _uuid(260),+ ),+ ),+ ),+ )+ ]+ )+ assert applied.result is FixedResult.APPLIED+ assert all(item.result is FixedResult.CONFLICT_OPERATION for item in changed)+ assert receipt_only.transaction_entries == 2+ elif case_alias in {+ "known-success-atomic",+ "known-failure-atomic",+ "acknowledged-cancellation-atomic",+ "acknowledged-timeout-atomic",+ }:+ outcome, state, proof, event_code, operation_columns = {+ "known-success-atomic": (+ OutcomeCode.CONFIRMED_SUCCESS,+ AttemptState.SUCCEEDED,+ "local_completion",+ "execution_succeeded",+ "terminal",+ ),+ "known-failure-atomic": (+ OutcomeCode.CONFIRMED_FAILURE,+ AttemptState.FAILED,+ "local_completion",+ "execution_failed",+ "terminal",+ ),+ "acknowledged-cancellation-atomic": (+ OutcomeCode.CONFIRMED_CANCELLED_NO_RESULT,+ AttemptState.CANCELLED,+ "cancellation_no_result_ack",+ "execution_cancelled",+ "cancellation",+ ),+ "acknowledged-timeout-atomic": (+ OutcomeCode.CONFIRMED_TIMEOUT_TERMINATED,+ AttemptState.TIMED_OUT,+ "timeout_termination_ack",+ "execution_timed_out",+ "timeout",+ ),+ }[case_alias]+ intent = _sqlite_p1c_terminal_intent(revision, outcome=outcome)+ result = await store.commit_terminal_attempt_v3(intent)+ attempt = await _sqlite_p1c_terminal_state(connection)+ receipt = await _sqlite_p1c_terminal_receipt(connection)+ logical = await (+ await connection.execute(+ "SELECT closure_operation_id,closing_attempt_id,revision "+ "FROM logical_executions WHERE id=?",+ (_uuid(208),),+ )+ ).fetchone()+ outbox = await (+ await connection.execute(+ "SELECT event_code,is_attempt_terminal FROM execution_publication_outbox "+ "WHERE attempt_id=?",+ (_uuid(210),),+ )+ ).fetchone()+ settled_ledgers = await (+ await connection.execute(+ "SELECT COUNT(*) FROM campaign_execution_budget_ledger "+ "WHERE attempt_id=? AND disposition IN ('consumed','released') "+ "AND budget_revision_settled IS NOT NULL",+ (_uuid(210),),+ )+ ).fetchone()+ operation_id = _sqlite_p1c_terminal_operation_id(intent.attempt_id)+ expected_operation_columns = {+ "terminal": (operation_id, None, None),+ "cancellation": (None, operation_id, None),+ "timeout": (None, None, operation_id),+ }[operation_columns]+ assert (result.result, result.revision) == (+ FixedResult.APPLIED,+ revision + 1,+ )+ assert tuple(attempt[:6]) == (+ state.value,+ revision + 1,+ outcome.value,+ "settled",+ proof,+ 1,+ ), "known terminal settlement changed"+ assert tuple(attempt[6:]) == (+ 1,+ "closed_without_retry",+ *expected_operation_columns,+ ), "known terminal closure facts changed"+ assert tuple(logical) == (operation_id, _uuid(210), 1), (+ "known terminal logical closure changed"+ )+ assert (receipt[12], receipt[13], receipt[15], receipt[16]) == (+ FixedResult.APPLIED.value,+ FixedResult.REPLAYED.value,+ _uuid(210),+ revision + 1,+ ), "known terminal receipt result changed"+ assert tuple(outbox) == (event_code, 1), "known terminal outbox binding changed"+ assert int(settled_ledgers[0]) == 3, "known terminal budget settlement was incomplete"+ elif case_alias == "uncertain-outcome-invalid-contract":+ uncertain = replace(+ intent,+ outcome_code=OutcomeCode.UNKNOWN_AFTER_RECOVERY,+ execution_result_digest=None,+ )+ trace = _SQLiteP1CTerminalTraceStore(connection)+ await _sqlite_p1c_assert_rollback(+ connection,+ trace,+ uncertain,+ expected_result=FixedResult.INVALID_CONTRACT,+ )+ assert trace.transaction_entries == 0, "uncertain outcome reached persistence"+ elif case_alias == "single-transaction-zero-nested-acquire":+ trace = _SQLiteP1CTerminalTraceStore(connection)+ applied = await trace.commit_terminal_attempt_v3(intent)+ assert applied.result is FixedResult.APPLIED+ assert trace.transaction_entries == 1, "terminal seam nested a transaction"+ assert trace.connection_identities == {id(connection)}, (+ "terminal seam acquired another connection"+ )+ assert trace.read_events[0] == "receipt", (+ "terminal apply read mutable state before receipt classification"+ )+ elif case_alias == "derive-exact-three-held-ledgers":+ applied = await store.commit_terminal_attempt_v3(intent)+ ledgers = await (+ await connection.execute(+ "SELECT budget_kind,disposition,consumed_units "+ "FROM campaign_execution_budget_ledger WHERE attempt_id=? "+ "ORDER BY CASE budget_kind WHEN 'noise' THEN 1 "+ "WHEN 'exfiltration' THEN 2 ELSE 3 END",+ (_uuid(210),),+ )+ ).fetchall()+ assert applied.result is FixedResult.APPLIED+ assert tuple(tuple(row) for row in ledgers) == (+ ("noise", "consumed", 1),+ ("exfiltration", "consumed", 2),+ ("concurrency", "released", 0),+ )+ elif case_alias == "missing-ledger-inconsistent-set-rollback":+ await connection.execute(+ "DELETE FROM campaign_execution_budget_ledger "+ "WHERE attempt_id=? AND budget_kind='noise'",+ (_uuid(210),),+ )+ await connection.commit()+ await _sqlite_p1c_assert_rollback(+ connection,+ store,+ intent,+ expected_result=FixedResult.INCONSISTENT_BUDGET_SET,+ )+ elif case_alias == "duplicate-extra-ledger-inconsistent-set-rollback":+ trace = _SQLiteP1CTerminalTraceStore(connection, duplicate_ledger_row=True)+ await _sqlite_p1c_assert_rollback(+ connection,+ trace,+ intent,+ expected_result=FixedResult.INCONSISTENT_BUDGET_SET,+ )+ elif case_alias == "wrong-kind-ledger-inconsistent-set-rollback":+ trace = _SQLiteP1CTerminalTraceStore(connection, ledger_mutation="kind")+ await _sqlite_p1c_assert_rollback(+ connection,+ trace,+ intent,+ expected_result=FixedResult.INCONSISTENT_BUDGET_SET,+ )+ elif case_alias == "wrong-campaign-attempt-ledger-inconsistent-set-rollback":+ for mutation in ("campaign", "attempt"):+ trace = _SQLiteP1CTerminalTraceStore(connection, ledger_mutation=mutation)+ await _sqlite_p1c_assert_rollback(+ connection,+ trace,+ intent,+ expected_result=FixedResult.INCONSISTENT_BUDGET_SET,+ )+ elif case_alias == "non-held-ledger-conflict-operation-rollback":+ await connection.execute(+ "UPDATE campaign_execution_budget_ledger SET disposition='released',"+ "consumed_units=0,budget_revision_settled=1,settled_at=reserved_at "+ "WHERE attempt_id=? AND budget_kind='noise'",+ (_uuid(210),),+ )+ await connection.commit()+ await _sqlite_p1c_assert_rollback(+ connection,+ store,+ intent,+ expected_result=FixedResult.CONFLICT_OPERATION,+ )+ elif case_alias == "current-budget-lock-no-toctou":+ await connection.execute(+ "UPDATE campaign_execution_budgets SET revision=2,latest_operation_id=?,"+ "latest_operation_base_revision=1,latest_operation_code='configure' "+ "WHERE campaign_id=?",+ (_uuid(20_310), _uuid(201)),+ )+ await connection.commit()+ applied = await store.commit_terminal_attempt_v3(intent)+ revisions = await (+ await connection.execute(+ "SELECT revision FROM campaign_execution_budgets WHERE campaign_id=? "+ "ORDER BY CASE budget_kind WHEN 'noise' THEN 1 "+ "WHEN 'exfiltration' THEN 2 ELSE 3 END",+ (_uuid(201),),+ )+ ).fetchall()+ assert applied.result is FixedResult.APPLIED+ assert tuple(int(row[0]) for row in revisions) == (3, 3, 3)+ elif case_alias == "budget-capacity-inconsistent-set-rollback":+ await connection.execute(+ "UPDATE campaign_execution_budgets SET reserved_units=0 "+ "WHERE campaign_id=? AND budget_kind='noise'",+ (_uuid(201),),+ )+ await connection.commit()+ await _sqlite_p1c_assert_rollback(+ connection,+ store,+ intent,+ expected_result=FixedResult.INCONSISTENT_BUDGET_SET,+ )+ elif case_alias in {+ "budget-write-failure-rollback",+ "output-write-failure-rollback",+ "terminal-write-failure-rollback",+ "logical-closure-write-failure-rollback",+ "outbox-write-failure-rollback",+ "receipt-write-failure-rollback",+ }:+ fail_at = {+ "budget-write-failure-rollback": "budget",+ "output-write-failure-rollback": "output",+ "terminal-write-failure-rollback": "terminal",+ "logical-closure-write-failure-rollback": "logical",+ "outbox-write-failure-rollback": "outbox",+ "receipt-write-failure-rollback": "receipt",+ }[case_alias]+ if fail_at == "output":+ intent = replace(+ intent,+ outputs=(OutputObservation(_uuid(20_320), OutputKind.HOST, _uuid(260)),),+ )+ trace = _SQLiteP1CTerminalTraceStore(connection, fail_at=fail_at)+ await _sqlite_p1c_assert_rollback(+ connection,+ trace,+ intent,+ expected_exception=RuntimeError,+ )+ elif case_alias == "non-running-attempt-conflict-state":+ result = await _sqlite_p1c_assert_rollback(+ connection,+ store,+ replace(intent, expected_attempt_revision=revision + 1),+ expected_result=FixedResult.CONFLICT_STATE,+ )+ assert result is not None+ assert result.revision == revision, (+ "attempt-state precedence did not dominate stale revision"+ )+ elif case_alias == "stale-attempt-revision-conflict":+ await _sqlite_p1c_assert_rollback(+ connection,+ store,+ replace(intent, expected_attempt_revision=revision - 1),+ expected_result=FixedResult.CONFLICT_REVISION,+ )+ elif case_alias == "invariant-failure-rollback":+ trace = _SQLiteP1CTerminalTraceStore(connection, duplicate_terminal_returning=True)+ await _sqlite_p1c_assert_rollback(+ connection,+ trace,+ intent,+ expected_result=FixedResult.INVARIANT_FAILURE,+ )+ elif case_alias == "cancellation-rollback-and-reuse":+ trace = _SQLiteP1CTerminalTraceStore(connection, cancel_at="output")+ await _sqlite_p1c_assert_rollback(+ connection,+ trace,+ intent,+ expected_exception=asyncio.CancelledError,+ )+ reused = await base_store.commit_terminal_attempt_v3(intent)+ assert reused.result is FixedResult.APPLIED, "cancelled connection was not reusable"+ elif case_alias == "exception-rollback-and-reuse":+ trace = _SQLiteP1CTerminalTraceStore(connection, fail_at="exception")+ await _sqlite_p1c_assert_rollback(+ connection,+ trace,+ intent,+ expected_exception=RuntimeError,+ )+ reused = await base_store.commit_terminal_attempt_v3(intent)+ assert reused.result is FixedResult.APPLIED, "failed connection was not reusable"+ elif case_alias == "legacy-terminal-apply-replay-bytes-unchanged":+ operation_id = _uuid(20_400)+ legacy = _sqlite_p1c_legacy_terminal_request(operation_id, revision)+ applied = await store.commit_terminal_attempt(legacy)+ vector_rows = await (+ await connection.execute(+ "SELECT operation_id,operation_code,binding_contract_version,"+ "request_binding_digest,result_binding_digest "+ "FROM execution_operation_receipts WHERE operation_id IN (?,?,?) "+ "ORDER BY operation_id",+ (_uuid(20_200), _uuid(20_202), operation_id),+ )+ ).fetchall()+ all_receipts_before = await (+ await connection.execute(+ "SELECT * FROM execution_operation_receipts ORDER BY operation_id"+ )+ ).fetchall()+ replayed = await store.commit_terminal_attempt(legacy)+ all_receipts_after = await (+ await connection.execute(+ "SELECT * FROM execution_operation_receipts ORDER BY operation_id"+ )+ ).fetchall()+ assert (applied.result, replayed.result) == (+ FixedResult.APPLIED,+ FixedResult.REPLAYED,+ )+ assert tuple(tuple(row) for row in vector_rows) == (+ _SQLITE_P1C_LEGACY_TERMINAL_RECEIPT_VECTORS+ ), "legacy terminal receipt vectors drifted"+ assert tuple(tuple(row) for row in all_receipts_before) == tuple(+ tuple(row) for row in all_receipts_after+ ), "legacy replay changed a receipt row"+ elif case_alias == "legacy-v3-crossing-conflict-operation":+ operation_id = _sqlite_p1c_terminal_operation_id(intent.attempt_id)+ legacy = _sqlite_p1c_legacy_terminal_request(operation_id, revision)+ applied = await store.commit_terminal_attempt(legacy)+ receipt_only = _SQLiteP1CTerminalTraceStore(connection, receipt_only=True)+ crossed = await receipt_only.commit_terminal_attempt_v3(intent)+ assert (applied.result, crossed.result) == (+ FixedResult.APPLIED,+ FixedResult.CONFLICT_OPERATION,+ )+ assert receipt_only.transaction_entries == 1+ second_connection, second_store, second_revision = await _sqlite_p1c_terminal_case(+ tmp_path / "cross-v3-first.db"+ )+ try:+ second_intent = _sqlite_p1c_terminal_intent(second_revision)+ v3_applied = await second_store.commit_terminal_attempt_v3(second_intent)+ second_receipt_only = _SQLiteP1CTerminalTraceStore(+ second_connection, receipt_only=True+ )+ legacy_crossed = await second_receipt_only.commit_terminal_attempt(+ _sqlite_p1c_legacy_terminal_request(+ _sqlite_p1c_terminal_operation_id(second_intent.attempt_id),+ second_revision,+ )+ )+ finally:+ await second_connection.close()+ assert (v3_applied.result, legacy_crossed.result) == (+ FixedResult.APPLIED,+ FixedResult.CONFLICT_OPERATION,+ )+ assert second_receipt_only.transaction_entries == 1+ elif case_alias == "changed-outcome-conflict-operation":+ applied = await store.commit_terminal_attempt_v3(intent)+ receipt_only = _SQLiteP1CTerminalTraceStore(connection, receipt_only=True)+ changed = await receipt_only.commit_terminal_attempt_v3(+ replace(+ intent,+ outcome_code=OutcomeCode.CONFIRMED_FAILURE,+ outputs=(),+ execution_result_digest=hashlib.sha256(b"changed-outcome").hexdigest(),+ )+ )+ assert (applied.result, changed.result) == (+ FixedResult.APPLIED,+ FixedResult.CONFLICT_OPERATION,+ )+ assert receipt_only.transaction_entries == 1+ elif case_alias == "changed-result-digest-conflict-operation":+ applied = await store.commit_terminal_attempt_v3(intent)+ receipt_only = _SQLiteP1CTerminalTraceStore(connection, receipt_only=True)+ changed = await receipt_only.commit_terminal_attempt_v3(+ replace(intent, execution_result_digest=hashlib.sha256(b"changed").hexdigest())+ )+ assert (applied.result, changed.result) == (+ FixedResult.APPLIED,+ FixedResult.CONFLICT_OPERATION,+ )+ assert receipt_only.transaction_entries == 1+ elif case_alias in {+ "cancellation-caller-result-digest-invalid-contract",+ "timeout-caller-result-digest-invalid-contract",+ }:+ outcome = (+ OutcomeCode.CONFIRMED_CANCELLED_NO_RESULT+ if case_alias.startswith("cancellation")+ else OutcomeCode.CONFIRMED_TIMEOUT_TERMINATED+ )+ invalid = _sqlite_p1c_terminal_intent(+ revision,+ outcome=outcome,+ execution_result_digest=_SQLITE_P1C_TERMINAL_RESULT_DIGEST,+ )+ trace = _SQLiteP1CTerminalTraceStore(connection)+ await _sqlite_p1c_assert_rollback(+ connection,+ trace,+ invalid,+ expected_result=FixedResult.INVALID_CONTRACT,+ )+ assert trace.transaction_entries == 0, "no-result digest reached persistence"+ elif case_alias == "canonical-output-order-exact-replay":+ await connection.execute(+ "INSERT INTO hosts(id,campaign_id,ip_address) VALUES(?,?,?)",+ (_uuid(20_500), _uuid(201), "192.0.2.2"),+ )+ await connection.execute(+ "INSERT INTO loot(id,campaign_id,host_id,loot_type,name) VALUES(?,?,?,?,?)",+ (_uuid(20_503), _uuid(201), _uuid(260), "artifact", "fixed-output"),+ )+ await connection.commit()+ outputs = (+ OutputObservation(_uuid(20_502), OutputKind.HOST, _uuid(20_500)),+ OutputObservation(_uuid(20_503), OutputKind.ARTIFACT, _uuid(20_503)),+ OutputObservation(_uuid(20_501), OutputKind.HOST, _uuid(260)),+ )+ forward = replace(intent, outputs=outputs)+ reversed_intent = replace(intent, outputs=tuple(reversed(outputs)))+ trace = _SQLiteP1CTerminalTraceStore(connection)+ applied = await trace.commit_terminal_attempt_v3(forward)+ replayed = await trace.commit_terminal_attempt_v3(reversed_intent)+ rows = await (+ await connection.execute(+ "SELECT id,host_id,loot_id FROM execution_output_links "+ "WHERE attempt_id=? ORDER BY id",+ (_uuid(210),),+ )+ ).fetchall()+ assert (applied.result, replayed.result) == (+ FixedResult.APPLIED,+ FixedResult.REPLAYED,+ )+ assert _sqlite_p1c_terminal_request_digest(+ forward+ ) == _sqlite_p1c_terminal_request_digest(reversed_intent)+ assert tuple(tuple(row) for row in rows) == (+ (_uuid(20_501), _uuid(260), None),+ (_uuid(20_502), _uuid(20_500), None),+ (_uuid(20_503), None, _uuid(20_503)),+ )+ assert trace.output_insert_order == [+ _uuid(20_503),+ _uuid(20_501),+ _uuid(20_502),+ ], "persisted output insertion order was not canonical"+ elif case_alias == "terminal-operation-and-system-principal-namespace":+ applied = await store.commit_terminal_attempt_v3(intent)+ receipt = await _sqlite_p1c_terminal_receipt(connection)+ actor = await (+ await connection.execute(+ "SELECT actor_subject_ref,actor_user_id FROM execution_attempts WHERE id=?",+ (_uuid(210),),+ )+ ).fetchone()+ assert applied.result is FixedResult.APPLIED+ assert tuple(receipt[:11]) == (+ _sqlite_p1c_terminal_operation_id(_uuid(210)),+ "terminal_succeeded",+ _uuid(201),+ _uuid(210),+ _uuid(208),+ "system",+ SYSTEM_PRINCIPAL_SUBJECT_REF,+ None,+ 0,+ None,+ 2,+ )+ assert tuple(actor) == (_uuid(200), _uuid(200))+ assert SYSTEM_PRINCIPAL_SUBJECT_REF != str(actor[0]), (+ "reserved system subject collided with the persisted actor"+ )+ assert ("system", SYSTEM_PRINCIPAL_SUBJECT_REF) != (+ "actor",+ str(actor[0]),+ ), "typed system namespace collided with the user-principal namespace"+ elif case_alias == "derived-revision-overflow-invariant-failure-rollback":+ await connection.execute(+ "UPDATE campaign_execution_budgets SET revision=?,"+ "latest_operation_base_revision=? "+ "WHERE campaign_id=? AND budget_kind='noise'",+ (MAX_I53, MAX_I53 - 1, _uuid(201)),+ )+ await connection.commit()+ await _sqlite_p1c_assert_rollback(+ connection,+ store,+ intent,+ expected_result=FixedResult.INVARIANT_FAILURE,+ )+ await connection.close()+ connection, store, revision = await _sqlite_p1c_terminal_case(+ tmp_path / "logical-overflow.db"+ )+ intent = _sqlite_p1c_terminal_intent(revision)+ await connection.execute(+ "UPDATE logical_executions SET revision=? WHERE id=?",+ (MAX_I53, _uuid(208)),+ )+ await connection.commit()+ await _sqlite_p1c_assert_rollback(+ connection,+ store,+ intent,+ expected_result=FixedResult.INVARIANT_FAILURE,+ )+ await connection.close()+ connection, store, revision = await _sqlite_p1c_terminal_case(+ tmp_path / "actual-max.db"+ )+ await connection.execute(+ "UPDATE campaign_execution_budgets SET capacity_units=?,reserved_units=? "+ "WHERE campaign_id=? AND budget_kind='noise'",+ (MAX_I53, MAX_I53, _uuid(201)),+ )+ await connection.execute(+ "UPDATE campaign_execution_budget_ledger SET reservation_units=? "+ "WHERE attempt_id=? AND budget_kind='noise'",+ (MAX_I53, _uuid(210)),+ )+ await connection.commit()+ max_actual = await store.commit_terminal_attempt_v3(+ _sqlite_p1c_terminal_intent(revision, noise_actual=MAX_I53)+ )+ max_rows = await (+ await connection.execute(+ "SELECT b.reserved_units,b.consumed_units,l.consumed_units "+ "FROM campaign_execution_budgets b "+ "JOIN campaign_execution_budget_ledger l ON l.budget_id=b.id "+ "WHERE b.campaign_id=? AND b.budget_kind='noise' AND l.attempt_id=?",+ (_uuid(201), _uuid(210)),+ )+ ).fetchone()+ assert max_actual.result is FixedResult.APPLIED, "MAX_I53 actual usage was rejected"+ assert tuple(max_rows) == (0, MAX_I53, MAX_I53), (+ "MAX_I53 actual usage was not settled with checked arithmetic"+ )+ else: # pragma: no cover - tuple/dispatcher drift must be loud.+ raise AssertionError(f"unhandled SQLite terminal alias: {case_alias}")+ finally:+ await connection.close()diff --git a/tests/unit/test_migration_portability.py b/tests/unit/test_migration_portability.pyindex ff6f364..de0679c 100644--- a/tests/unit/test_migration_portability.py+++ b/tests/unit/test_migration_portability.py@@ -18,6 +18,7 @@ from tempfile import TemporaryDirectoryimport pytestfrom alembic import commandfrom alembic.config import Config+from alembic.script import ScriptDirectoryfrom sqlalchemy.engine import URL_REPO_ROOT = Path(__file__).resolve().parents[2]@@ -5903,3 +5904,34 @@ def test_revision_0006_exact_column_state_machine(rejected_atomically,"revision 0006 changed an incompatible catalog",)+++def test_revision_0011_is_the_only_linear_head_with_protected_parent() -> None:+ migration = importlib.import_module(+ "migrations.versions.0011_execution_admission_authority"+ )+ protected_parent = importlib.import_module(+ "migrations.versions.0010_execution_lifecycle"+ )+ config = _config(configured_url="sqlite://")+ script = ScriptDirectory.from_config(config)+ revisions = tuple(+ item.revision+ for item in reversed(+ tuple(script.walk_revisions(base="base", head="heads"))+ )+ )+ _require_fixed(script.get_heads() == ["0011"], "revision head changed")+ _require_fixed(+ revisions == tuple(f"{value:04d}" for value in range(1, 12)),+ "revision graph is not linear",+ )+ _require_fixed(+ migration.down_revision == "0010"+ and protected_parent.down_revision == "0009",+ "revision 0010 parent changed",+ )+ with pytest.raises(+ RuntimeError, match="revision-0010 downgrade is not supported"+ ):+ protected_parent.downgrade()diff --git a/tests/unit/test_phase1_runtime_durability.py b/tests/unit/test_phase1_runtime_durability.pyindex 060d6f4..de5816d 100644--- a/tests/unit/test_phase1_runtime_durability.py+++ b/tests/unit/test_phase1_runtime_durability.py@@ -1,7 +1,10 @@"""Phase 1 regressions for the durable API -> engine -> DB -> graph path."""+from __future__ import annotations+import asyncioimport json+from dataclasses import fields, replacefrom types import SimpleNamespacefrom typing import Anyfrom unittest.mock import AsyncMock@@ -12,9 +15,37 @@ from ares.api import serverfrom ares.core.campaign import Campaign, Finding, NoiseProfile, ScopeEntry, Severityfrom ares.core.config import AresSettingsfrom ares.core.engine import AresEngine, ExecutionPlan, ModuleStatus+from ares.core.execution_admission import (+ C_LIVE_PLAN_CHILD_DOMAIN,+ C_LIVE_RETRY_CHILD_DOMAIN,+ C_LIVE_STRATEGY_CHILD_DOMAIN,+ DispatchDispositionV1,+ DispatchRequestV1,+ ExecutionAdmissionCoordinatorV1,+ RevalidatedPrincipalV1,+ _identity,+ _mark_test_settlement_proof,+ _mint_test_dispatch_context,+ _mint_test_plan_context,+ canonical_intent_digest,+ derive_attempt_id,+ derive_child_submission_id,+ derive_logical_execution_id,+ derive_operation_id,+ derive_submission_id,+ mark_terminal_committed,+)from ares.core.plugin.loader import ModuleRegistryfrom ares.credential.vault import Credential, CredentialType, CredentialVaultfrom ares.db.database import AresDatabase, DBCredential, Host+from ares.db.execution_lifecycle import (+ AttemptState,+ CampaignActorGrantMutation,+ FixedResult,+ OperationResult,+ OutcomeCode,+ TrustedPrincipal,+)from ares.modules.base import BaseModule, ModuleResultfrom ares.strategy.engine import StrategyEngine@@ -49,6 +80,27 @@ class PhaseOneProbeModule(BaseModule):)+class SQLiteLifecycleProbeModule(BaseModule):+ """Descriptor-backed no-network probe for real SQLite lifecycle wiring."""++ MODULE_ID = "ad.phase1_sqlite_probe"+ MODULE_NAME = "SQLite lifecycle probe"+ MODULE_CATEGORY = "ad"+ MODULE_DESCRIPTION = "Test-only real-store lifecycle probe"+ contexts: list[Any] = []++ async def validate(self, ctx: Any) -> None:+ return None++ async def execute(self, ctx: Any) -> ModuleResult:+ type(self).contexts.append(ctx)+ return ModuleResult(+ status="success",+ module_id=self.MODULE_ID,+ raw={"source": "sqlite-lifecycle-probe"},+ )++def _settings() -> AresSettings:return AresSettings(ares_secret_key="phase1-test-secret-key-min-32-chars!!",@@ -76,6 +128,628 @@ def _engine(settings: AresSettings, db: AresDatabase) -> AresEngine:return engine+async def _run_committed(+ engine: AresEngine,+ campaign: Campaign,+ module_id: str,+ params: dict[str, Any],+):+ context = _mint_test_dispatch_context(engine, campaign.id, module_id)+ result = await engine.run_module(+ module_id,+ campaign,+ params,+ actor_role="team_lead",+ dispatch_context=context,+ )+ mark_terminal_committed(context)+ return await engine._finalize_committed_module_result(campaign, module_id, result, context)+++class _LifecycleStoreStub:+ def __init__(self) -> None:+ self.initial = OperationResult(FixedResult.APPLIED, 0)+ self.replay_after_first = False+ self.admission_calls = 0+ self.transition_failure_target = None+ self.terminal: OperationResult | None = None+ self.terminal_exception: BaseException | None = None+ self.transitions: list[Any] = []+ self.terminal_intents: list[Any] = []+ self.settlement_requests: list[Any] = []++ async def create_initial_execution_v3(self, principal: Any, intent: Any):+ self.admission_calls += 1+ self.principal = principal+ self.admission_intent = intent+ if self.replay_after_first and self.admission_calls > 1:+ return OperationResult(FixedResult.REPLAYED, 0)+ return self.initial++ async def create_retry_attempt_v3(self, principal: Any, intent: Any):+ self.principal = principal+ self.retry_intent = intent+ return self.initial++ async def transition_attempt(self, request: Any):+ self.transitions.append(request)+ if request.target_state is self.transition_failure_target:+ return OperationResult(FixedResult.CONFLICT_STATE, request.expected_revision)+ return OperationResult(FixedResult.APPLIED, request.expected_revision + 1)++ async def commit_terminal_attempt_v3(self, intent: Any):+ self.terminal_intents.append(intent)+ if self.terminal_exception is not None:+ raise self.terminal_exception+ return self.terminal or OperationResult(+ FixedResult.APPLIED, intent.expected_attempt_revision + 1+ )++ async def enter_settlement_pending(self, request: Any):+ self.settlement_requests.append(request)+ return OperationResult(FixedResult.APPLIED, request.expected_revision + 1)+++class _RecordingLifecycleStore:+ """Transparent recorder around a real lifecycle store used by C-LIVE tests."""++ def __init__(self, store: Any) -> None:+ self._store = store+ self.transitions: list[Any] = []+ self.terminal_intents: list[Any] = []++ def __getattr__(self, name: str) -> Any:+ return getattr(self._store, name)++ async def transition_attempt(self, request: Any):+ self.transitions.append(request)+ return await self._store.transition_attempt(request)++ async def commit_terminal_attempt_v3(self, intent: Any):+ self.terminal_intents.append(intent)+ return await self._store.commit_terminal_attempt_v3(intent)+++def _live_fixture():+ campaign = _campaign("11111111-1111-4111-8111-111111111111")+ engine = AresEngine(settings=_settings())+ registry = ModuleRegistry()+ registry.register(PhaseOneProbeModule)+ engine._registry = registry+ store = _LifecycleStoreStub()+ principal = TrustedPrincipal(+ "33333333-3333-4333-8333-333333333333",+ "33333333-3333-4333-8333-333333333333",+ )++ async def revalidate(candidate: Any, campaign_id: str, module_id: str):+ assert candidate.subject_ref == principal.subject_ref+ assert campaign_id == campaign.id+ assert module_id == PhaseOneProbeModule.MODULE_ID+ return RevalidatedPrincipalV1(principal, 0, "team_lead")++ coordinator = ExecutionAdmissionCoordinatorV1(store, engine, revalidate)+ request = DispatchRequestV1(+ campaign_id=campaign.id,+ module_id=PhaseOneProbeModule.MODULE_ID,+ ingress_code="api_module",+ idempotency_key="22222222-2222-4222-8222-222222222222",+ raw_parameters={"target": "10.10.10.5"},+ whole_intent_digest=canonical_intent_digest(+ {"module_id": PhaseOneProbeModule.MODULE_ID, "target": "10.10.10.5"}+ ),+ )+ return campaign, engine, store, principal, coordinator, request+++async def _sqlite_live_fixture(tmp_path: Any, monkeypatch: pytest.MonkeyPatch):+ """Build one descriptor-authorized C-LIVE coordinator on the real SQLite store."""+ from tests.unit.test_execution_lifecycle_persistence import (+ _p1c_eligible_descriptor,+ _p1c_enable_acceptance,+ _p1c_sqlite_authority_store,+ )++ from ares.modules import descriptors as descriptor_module+ from ares.modules.descriptors import ModuleCategory, ModuleDescriptor++ source = _p1c_eligible_descriptor(monkeypatch)+ descriptor_values = {+ field.name: getattr(source, field.name)+ for field in fields(ModuleDescriptor)+ if field.init+ }+ descriptor_values.update(+ module_id=SQLiteLifecycleProbeModule.MODULE_ID,+ category=ModuleCategory.AD,+ )+ descriptor = ModuleDescriptor(**descriptor_values)+ descriptors = dict(descriptor_module.FIRST_PARTY_DESCRIPTORS)+ descriptors[descriptor.module_id] = descriptor+ monkeypatch.setattr(descriptor_module, "FIRST_PARTY_DESCRIPTORS", descriptors)+ database, _setup_store, admin, actor_id, campaign_id, _credential_id = (+ await _p1c_sqlite_authority_store(tmp_path)+ )+ actual_store = database.execution_lifecycle_store()+ principal = TrustedPrincipal(actor_id, actor_id)+ grant = await actual_store.put_campaign_actor_grant(+ admin,+ CampaignActorGrantMutation(+ "77777777-7777-4777-8777-777777777777",+ campaign_id,+ principal.user_id,+ None,+ ),+ )+ assert grant.result is FixedResult.APPLIED+ await _p1c_enable_acceptance(actual_store, admin, campaign_id)+ store = _RecordingLifecycleStore(actual_store)++ campaign = _campaign(campaign_id)+ engine = AresEngine(settings=_settings())+ registry = ModuleRegistry()+ registry.register(SQLiteLifecycleProbeModule)+ engine._registry = registry++ async def revalidate(candidate: Any, candidate_campaign: str, module_id: str):+ assert candidate == principal+ assert candidate_campaign == campaign_id+ assert module_id == SQLiteLifecycleProbeModule.MODULE_ID+ return RevalidatedPrincipalV1(principal, 0, "operator")++ coordinator = ExecutionAdmissionCoordinatorV1(store, engine, revalidate)+ request = DispatchRequestV1(+ campaign_id=campaign_id,+ module_id=SQLiteLifecycleProbeModule.MODULE_ID,+ ingress_code="api_module",+ idempotency_key="88888888-8888-4888-8888-888888888888",+ raw_parameters={"noise_profile": "stealth"},+ whole_intent_digest=canonical_intent_digest(+ {+ "module_id": SQLiteLifecycleProbeModule.MODULE_ID,+ "noise_profile": "stealth",+ }+ ),+ )+ return database, campaign, engine, store, principal, coordinator, request+++def _assert_c_live_typed_length_uuid_vectors_are_literal() -> None:+ campaign_id = "11111111-1111-4111-8111-111111111111"+ key = "22222222-2222-4222-8222-222222222222"+ submission = derive_submission_id(campaign_id, "api_module", key)+ logical = derive_logical_execution_id(campaign_id, submission)+ attempt = derive_attempt_id(logical, "test.safe_probe")+ assert submission == "b6dc6c66-d862-4e37-83b7-88060726d0f5"+ assert logical == "90f8daee-8ac7-48d0-8e3a-4293580cf2bf"+ assert attempt == "f8c45915-a12d-409e-8552-8a0d25586a9f"+ assert (+ derive_operation_id(attempt, "admission")+ == "cca963e4-fd56-4246-8cbb-c775f68e715b"+ )+ assert derive_operation_id(attempt, "queue") == "5a190d69-5318-4f30-8213-8881319448da"+ assert (+ derive_child_submission_id(+ submission,+ "test.safe_probe",+ occurrence=1,+ stage_ordinal=2,+ decision_ordinal=0,+ module_ordinal=3,+ domain=C_LIVE_PLAN_CHILD_DOMAIN,+ )+ == "f506c525-b0db-492c-8133-e4d280b00e49"+ )+ assert (+ derive_child_submission_id(+ submission,+ "test.safe_probe",+ occurrence=1,+ stage_ordinal=2,+ decision_ordinal=4,+ module_ordinal=3,+ domain=C_LIVE_STRATEGY_CHILD_DOMAIN,+ )+ == "92dd04fa-f59f-4439-86a4-50fab7529867"+ )+ assert (+ derive_child_submission_id(+ submission,+ "test.safe_probe",+ occurrence=1,+ stage_ordinal=0,+ decision_ordinal=0,+ module_ordinal=0,+ domain=C_LIVE_RETRY_CHILD_DOMAIN,+ )+ == "cd8b9bfd-6e95-4149-8a23-89edf120e1d2"+ )+++async def test_c_live_concurrent_duplicate_dispatches_exactly_once(+ tmp_path: Any, monkeypatch: pytest.MonkeyPatch+) -> None:+ _assert_c_live_typed_length_uuid_vectors_are_literal()+ database, campaign, _engine_value, store, principal, coordinator, request = (+ await _sqlite_live_fixture(tmp_path, monkeypatch)+ )+ peer_database = AresDatabase(tmp_path / "p1c-authority.db")+ await peer_database.connect()+ peer_store = _RecordingLifecycleStore(peer_database.execution_lifecycle_store())+ peer_engine = AresEngine(settings=_settings())+ peer_registry = ModuleRegistry()+ peer_registry.register(SQLiteLifecycleProbeModule)+ peer_engine._registry = peer_registry++ async def peer_revalidate(candidate: Any, campaign_id: str, module_id: str):+ assert candidate == principal+ assert campaign_id == campaign.id+ assert module_id == SQLiteLifecycleProbeModule.MODULE_ID+ return RevalidatedPrincipalV1(principal, 0, "operator")++ peer = ExecutionAdmissionCoordinatorV1(peer_store, peer_engine, peer_revalidate)+ SQLiteLifecycleProbeModule.contexts.clear()+ try:+ results = await asyncio.gather(+ coordinator.execute_module(principal, request, campaign),+ peer.execute_module(principal, request, campaign),+ )+ assert {result.disposition for result in results} == {+ DispatchDispositionV1.TERMINAL,+ DispatchDispositionV1.REPLAYED,+ }+ assert sum(result.terminal_committed for result in results) == 1+ assert len(SQLiteLifecycleProbeModule.contexts) == 1+ transitions = store.transitions + peer_store.transitions+ assert [item.target_state for item in transitions] == [+ AttemptState.QUEUED,+ AttemptState.DISPATCHING,+ AttemptState.RUNNING,+ ]+ assert [item.expected_revision for item in transitions] == [0, 1, 2]+ terminal_intents = store.terminal_intents + peer_store.terminal_intents+ assert len(terminal_intents) == 1+ assert terminal_intents[0].expected_attempt_revision == 3+ assert terminal_intents[0].concurrency_actual == 0+ attempt = await (+ await database.conn.execute(+ "SELECT state,revision FROM execution_attempts WHERE id=?",+ (results[0].identity.attempt_id,),+ )+ ).fetchone()+ assert tuple(attempt) == ("succeeded", 4)+ finally:+ await peer_database.close()+ await database.close()+++async def test_c_live_terminal_commit_then_response_loss_replays_stable_ids_without_effect() -> None:+ campaign, _engine_value, store, principal, coordinator, request = _live_fixture()+ PhaseOneProbeModule.contexts.clear()+ applied = await coordinator.execute_module(principal, request, campaign)+ store.initial = OperationResult(FixedResult.REPLAYED, 0)+ transition_count = len(store.transitions)+ terminal_count = len(store.terminal_intents)+ replay = await coordinator.execute_module(principal, request, campaign)+ assert applied.disposition is DispatchDispositionV1.TERMINAL+ assert replay.disposition is DispatchDispositionV1.REPLAYED+ assert replay.identity == applied.identity+ assert len(PhaseOneProbeModule.contexts) == 1+ assert len(store.transitions) == transition_count+ assert len(store.terminal_intents) == terminal_count+++ "failed_target",+ [AttemptState.QUEUED, AttemptState.DISPATCHING, AttemptState.RUNNING],+ ids=["queued", "dispatching", "running"],+)+async def test_c_live_failed_pre_effect_state_cas_has_zero_effect(+ failed_target: AttemptState,+) -> None:+ campaign, _engine_value, store, principal, coordinator, request = _live_fixture()+ store.transition_failure_target = failed_target+ PhaseOneProbeModule.contexts.clear()+ result = await coordinator.execute_module(principal, request, campaign)+ assert result.lifecycle_result is FixedResult.CONFLICT_STATE+ assert result.effect_started is False+ assert PhaseOneProbeModule.contexts == []+ assert store.terminal_intents == []+++async def test_c_live_uncertainty_after_running_is_settlement_pending_without_retry(+ monkeypatch: Any,+) -> None:+ campaign, _engine_value, store, principal, coordinator, request = _live_fixture()++ async def timeout_execute(self: Any, ctx: Any):+ raise TimeoutError("executor quiescence is not proven")++ monkeypatch.setattr(PhaseOneProbeModule, "execute", timeout_execute)+ result = await coordinator.execute_module(principal, request, campaign)+ assert result.disposition is DispatchDispositionV1.INDETERMINATE+ assert result.terminal_committed is False+ assert store.terminal_intents == []+ assert len(store.settlement_requests) == 1+ assert store.settlement_requests[0].target_state is AttemptState.SETTLEMENT_PENDING++ # External task cancellation is process control, not an HTTP outcome. The+ # coordinator must shield one bounded safety write and then re-raise it.+ campaign, _engine_value, cancelled_store, principal, coordinator, request = (+ _live_fixture()+ )+ entered_effect = asyncio.Event()++ async def cancelled_execute(self: Any, ctx: Any):+ entered_effect.set()+ await asyncio.Future()++ monkeypatch.setattr(PhaseOneProbeModule, "execute", cancelled_execute)+ task = asyncio.create_task(coordinator.execute_module(principal, request, campaign))+ await entered_effect.wait()+ task.cancel()+ with pytest.raises(asyncio.CancelledError):+ await task+ assert len(cancelled_store.settlement_requests) == 1+ assert cancelled_store.settlement_requests[0].target_state is AttemptState.SETTLEMENT_PENDING+++async def test_c_live_terminal_persistence_failure_has_no_success_response_or_broadcast() -> None:+ campaign, _engine_value, store, principal, coordinator, request = _live_fixture()+ store.terminal_exception = RuntimeError("injected terminal persistence failure")+ PhaseOneProbeModule.contexts.clear()+ result = await coordinator.execute_module(principal, request, campaign)+ assert result.disposition is DispatchDispositionV1.INDETERMINATE+ assert result.lifecycle_result is FixedResult.APPLIED+ assert result.terminal_committed is False+ assert len(store.settlement_requests) == 1+ assert campaign.findings == []++ campaign, _engine_value, cancelled_store, principal, coordinator, request = (+ _live_fixture()+ )+ cancelled_store.terminal_exception = asyncio.CancelledError()+ with pytest.raises(asyncio.CancelledError):+ await coordinator.execute_module(principal, request, campaign)+ assert len(cancelled_store.settlement_requests) == 1+ assert campaign.findings == []++ campaign, _engine_value, wrong_revision_store, principal, coordinator, request = (+ _live_fixture()+ )+ wrong_revision_store.terminal = OperationResult(FixedResult.APPLIED, 99)+ result = await coordinator.execute_module(principal, request, campaign)+ assert result.disposition is DispatchDispositionV1.INDETERMINATE+ assert result.lifecycle_result is FixedResult.INVARIANT_FAILURE+ assert result.terminal_committed is False+ assert campaign.findings == []+++async def test_c_live_crash_after_admission_before_queue_is_stranded_without_effect() -> None:+ campaign, engine, store, principal, _coordinator, request = _live_fixture()++ async def unavailable_revalidation(*_args: Any):+ return None++ coordinator = ExecutionAdmissionCoordinatorV1(store, engine, unavailable_revalidation)+ PhaseOneProbeModule.contexts.clear()+ result = await coordinator.execute_module(principal, request, campaign)+ assert result.lifecycle_result is FixedResult.AUTHORITY_STALE+ assert result.revision == 0+ assert store.transitions == []+ assert PhaseOneProbeModule.contexts == []+++ ("created_result", "expected_effects"),+ [+ pytest.param(OperationResult(FixedResult.APPLIED, 0), 1, id="applied-child-dispatches"),+ pytest.param(+ OperationResult(FixedResult.REPLAYED_BOUND_CHILD, 0),+ 0,+ id="replayed-child-does-not-dispatch",+ ),+ ],+)+async def test_c_live_retry_dispatch_ownership(+ created_result: OperationResult,+ expected_effects: int,+) -> None:+ campaign, _engine_value, store, principal, coordinator, request = _live_fixture()+ store.initial = created_result+ PhaseOneProbeModule.contexts.clear()+ result = await coordinator.retry_module(+ principal,+ request,+ campaign,+ logical_execution_id="44444444-4444-4444-8444-444444444444",+ parent_attempt_id="55555555-5555-4555-8555-555555555555",+ expected_parent_revision=4,+ )+ assert len(PhaseOneProbeModule.contexts) == expected_effects+ assert result.effect_started is bool(expected_effects)+++def test_c_live_repeated_plan_modules_have_deterministic_child_identities() -> None:+ _assert_c_live_typed_length_uuid_vectors_are_literal()+ campaign, _engine_value, _store, _principal, _coordinator, base = _live_fixture()+ digest = canonical_intent_digest(["ad.phase1_probe", "ad.phase1_probe"])+ first_request = replace(+ base,+ ingress_code="api_campaign_plan",+ whole_intent_digest=digest,+ module_ordinal=0,+ )+ second_request = replace(+ base,+ ingress_code="api_campaign_plan",+ whole_intent_digest=digest,+ module_ordinal=1,+ )+ first = _identity(first_request)+ second = _identity(second_request)+ assert first == _identity(first_request)+ assert second == _identity(second_request)+ assert first.submission_id != second.submission_id+ assert first.logical_execution_id != second.logical_execution_id+ assert first.attempt_id != second.attempt_id+ assert campaign.id == base.campaign_id+++async def test_c_live_changed_whole_plan_conflicts_before_child_redispatch(+ tmp_path: Any, monkeypatch: pytest.MonkeyPatch+) -> None:+ database, campaign, _engine_value, store, principal, coordinator, base = (+ await _sqlite_live_fixture(tmp_path, monkeypatch)+ )+ original = replace(+ base,+ ingress_code="api_campaign_plan",+ module_ordinal=0,+ whole_intent_digest=canonical_intent_digest(["ad.phase1_probe"]),+ )+ changed = replace(+ base,+ ingress_code="api_campaign_plan",+ module_ordinal=0,+ whole_intent_digest=canonical_intent_digest(+ ["ad.phase1_probe", "ad.phase1_probe"]+ ),+ )+ first_identity = _identity(original)+ changed_identity = _identity(changed)+ assert first_identity.submission_id == changed_identity.submission_id+ assert first_identity.logical_execution_id != changed_identity.logical_execution_id+ SQLiteLifecycleProbeModule.contexts.clear()+ try:+ applied = await coordinator.execute_module(principal, original, campaign)+ conflict = await coordinator.execute_module(principal, changed, campaign)+ assert applied.terminal_committed is True+ assert conflict.lifecycle_result is FixedResult.CONFLICT_OPERATION+ assert len(SQLiteLifecycleProbeModule.contexts) == 1+ attempts = await (+ await database.conn.execute(+ "SELECT state,revision FROM execution_attempts ORDER BY id"+ )+ ).fetchall()+ assert [tuple(row) for row in attempts] == [("succeeded", 4)]+ finally:+ await database.close()+++ ("case", "expected_outcome"),+ [+ pytest.param("success", OutcomeCode.CONFIRMED_SUCCESS, id="confirmed-success"),+ pytest.param("failure", OutcomeCode.CONFIRMED_FAILURE, id="confirmed-failure"),+ pytest.param(+ "cancelled",+ OutcomeCode.CONFIRMED_CANCELLED_NO_RESULT,+ id="confirmed-cancelled-no-result",+ ),+ pytest.param(+ "timeout",+ OutcomeCode.CONFIRMED_TIMEOUT_TERMINATED,+ id="confirmed-timeout-terminated",+ ),+ ],+)+async def test_c_live_known_settled_outcome_commits_before_result(+ case: str,+ expected_outcome: OutcomeCode,+ monkeypatch: Any,+) -> None:+ campaign, engine, store, principal, coordinator, request = _live_fixture()+ if case == "failure":+ async def failed_execute(self: Any, ctx: Any):+ raise RuntimeError("known settled failure")++ monkeypatch.setattr(PhaseOneProbeModule, "execute", failed_execute)+ elif case in {"cancelled", "timeout"}:+ original_run = engine.run_module++ async def settled_run(*args: Any, **kwargs: Any):+ result = await original_run(*args, **kwargs)+ context = kwargs["dispatch_context"]+ proof = (+ "cancellation_no_result_ack"+ if case == "cancelled"+ else "timeout_termination_ack"+ )+ _mark_test_settlement_proof(context, proof)+ result.status = (+ ModuleStatus.CANCELLED if case == "cancelled" else ModuleStatus.TIMEOUT+ )+ result.findings = []+ result.raw_output = {}+ return result++ monkeypatch.setattr(engine, "run_module", settled_run)++ result = await coordinator.execute_module(principal, request, campaign)+ assert result.terminal_committed is True+ assert store.terminal_intents[-1].outcome_code is expected_outcome+ if case == "success":+ assert campaign.findings, "result publication must occur after terminal commit"+ if case in {"cancelled", "timeout"}:+ assert store.terminal_intents[-1].execution_result_digest is None+++ "case",+ [+ "principal-and-mutable-input-not-in-namespace",+ "changed-principal-conflicts",+ "changed-immutable-intent-conflicts",+ ],+)+async def test_c_live_submission_namespace_and_binding(+ case: str, tmp_path: Any, monkeypatch: pytest.MonkeyPatch+) -> None:+ campaign, _engine_value, _store, principal, _coordinator, request = _live_fixture()+ changed = replace(request, raw_parameters={"target": "10.10.10.6"})+ assert _identity(request).submission_id == _identity(changed).submission_id+ if case == "principal-and-mutable-input-not-in-namespace":+ assert derive_submission_id(+ campaign.id, request.ingress_code, request.idempotency_key+ ) == _identity(request).submission_id+ return++ database, campaign, _engine_value, _store, principal, coordinator, request = (+ await _sqlite_live_fixture(tmp_path, monkeypatch)+ )+ changed = replace(request, raw_parameters={"noise_profile": "normal"})+ candidate = principal+ if case == "changed-principal-conflicts":+ candidate = TrustedPrincipal(+ "66666666-6666-4666-8666-666666666666",+ "66666666-6666-4666-8666-666666666666",+ )+ SQLiteLifecycleProbeModule.contexts.clear()+ try:+ applied = await coordinator.execute_module(principal, request, campaign)+ result = await coordinator.execute_module(+ candidate,+ changed if case == "changed-immutable-intent-conflicts" else request,+ campaign,+ )+ assert applied.terminal_committed is True+ assert result.lifecycle_result is FixedResult.CONFLICT_OPERATION+ assert len(SQLiteLifecycleProbeModule.contexts) == 1+ finally:+ await database.close()++@pytest.mark.asyncioasync def test_db_bound_engine_persists_each_execution_once(tmp_path: Any) -> None:settings = _settings()@@ -85,11 +759,11 @@ async def test_db_bound_engine_persists_each_execution_once(tmp_path: Any) -> Noengine = _engine(settings, db)PhaseOneProbeModule.contexts.clear()try:- result = await engine.run_module(- PhaseOneProbeModule.MODULE_ID,+ result = await _run_committed(+ engine,campaign,+ PhaseOneProbeModule.MODULE_ID,{"target": "10.10.10.5"},- actor_role="team_lead",)findings, total = await db.list_findings(campaign.id, per_page=20)async with db.conn.execute(@@ -100,7 +774,10 @@ async def test_db_bound_engine_persists_each_execution_once(tmp_path: Any) -> Noassert result.status is ModuleStatus.DONEassert total == len(findings) == 1assert module_runs == 1- assert PhaseOneProbeModule.contexts[-1].artifact_store is campaign._runtime_state.artifact_store+ assert (+ PhaseOneProbeModule.contexts[-1].artifact_store+ is campaign._runtime_state.artifact_store+ )assert PhaseOneProbeModule.contexts[-1].vault is campaign._runtime_state.vaultfinally:await db.close()@@ -120,24 +797,26 @@ async def test_restored_vault_is_reused_by_the_next_campaign_run(tmp_path: Any)cred_type=CredentialType.CLEARTEXT,)source_vault.store(credential, "never-return-this-secret")- await db.save_credential_preencrypted(DBCredential(- id=credential.id,- campaign_id=campaign.id,- username=credential.username,- cred_type=credential.cred_type.value,- secret=credential.secret_enc.decode(),- domain=credential.domain,- source_module="phase1.fixture",- ))+ await db.save_credential_preencrypted(+ DBCredential(+ id=credential.id,+ campaign_id=campaign.id,+ username=credential.username,+ cred_type=credential.cred_type.value,+ secret=credential.secret_enc.decode(),+ domain=credential.domain,+ source_module="phase1.fixture",+ )+ )engine = _engine(settings, db)PhaseOneProbeModule.contexts.clear()try:restored = await engine.restore_campaign_vault(campaign)- result = await engine.run_module(- PhaseOneProbeModule.MODULE_ID,+ result = await _run_committed(+ engine,campaign,+ PhaseOneProbeModule.MODULE_ID,{"target": "10.10.10.5"},- actor_role="team_lead",)assert restored == 1@@ -158,36 +837,65 @@ async def test_plan_and_strategy_rehydrate_durable_state_and_done_is_success(tmpengine = _engine(settings, db)try:plan = ExecutionPlan().add_stage(- "probe", [PhaseOneProbeModule.MODULE_ID],+ "probe",+ [PhaseOneProbeModule.MODULE_ID],{PhaseOneProbeModule.MODULE_ID: {"target": "10.10.10.5"}},)- plan_results = await engine.run_plan(plan, campaign, actor_role="team_lead")+ plan_context = _mint_test_plan_context(engine, campaign.id, tuple(plan.all_module_ids()))+ plan_results = await engine.run_plan(+ plan,+ campaign,+ actor_role="team_lead",+ dispatch_context=plan_context,+ )+ for child_context in plan_context.children:+ module_result = plan_results[child_context.module_id]+ mark_terminal_committed(child_context)+ await engine._finalize_committed_module_result(+ campaign,+ child_context.module_id,+ module_result,+ child_context,+ )assert plan_results[PhaseOneProbeModule.MODULE_ID].status is ModuleStatus.DONEstrategy = StrategyEngine(ares_engine=engine, settings=settings)- strategy._run_coverage_predictor = AsyncMock(return_value={- "detection_score": 0.0,- "wait_recommendation": {"hours": 0},- })- strategy._get_edr_context = AsyncMock(return_value={- "edr_vendor": "test", "viable_techniques": [], "recommended_approach": None,- })- strategy._run_ai_planner = AsyncMock(return_value={- "confidence_score": 1.0,- "execution_plan": [{- "name": "probe",- "modules": [PhaseOneProbeModule.MODULE_ID],- "params": {PhaseOneProbeModule.MODULE_ID: {"target": "10.10.10.5"}},- }],- "warnings": [],- })+ strategy._run_coverage_predictor = AsyncMock(+ return_value={+ "detection_score": 0.0,+ "wait_recommendation": {"hours": 0},+ }+ )+ strategy._get_edr_context = AsyncMock(+ return_value={+ "edr_vendor": "test",+ "viable_techniques": [],+ "recommended_approach": None,+ }+ )+ strategy._run_ai_planner = AsyncMock(+ return_value={+ "confidence_score": 1.0,+ "execution_plan": [+ {+ "name": "probe",+ "modules": [PhaseOneProbeModule.MODULE_ID],+ "params": {PhaseOneProbeModule.MODULE_ID: {"target": "10.10.10.5"}},+ }+ ],+ "warnings": [],+ }+ )strategy_result = await strategy.run_autonomous_engagement(campaign=campaign,max_rounds=1,llm_backend="local",actor_role="team_lead",)- assert PhaseOneProbeModule.MODULE_ID in strategy_result.modules_succeeded+ assert PhaseOneProbeModule.MODULE_ID not in strategy_result.modules_succeeded+ strategy._run_coverage_predictor.assert_not_awaited()+ strategy._get_edr_context.assert_not_awaited()+ strategy._run_ai_planner.assert_not_awaited()engine.discard_campaign_runtime(campaign.id)rehydrated_campaign = _campaign(campaign.id)@@ -195,7 +903,7 @@ async def test_plan_and_strategy_rehydrate_durable_state_and_done_is_success(tmprestarted_state = await restarted_engine.ensure_campaign_runtime(rehydrated_campaign)findings, total = await db.list_findings(campaign.id, per_page=20)- assert total == len(findings) >= 2+ assert total == len(findings) == 1assert restarted_state.session.get_host("10.10.10.5") is not Noneassert (await db.get_campaign_graph(campaign.id)) is not Nonefinally:@@ -203,23 +911,84 @@ async def test_plan_and_strategy_rehydrate_durable_state_and_done_is_success(tmp@pytest.mark.asyncio-async def test_strategy_preflight_does_not_reserve_a_slot_for_unknown_campaign(monkeypatch: Any) -> None:- original_db, original_engine = server._db, server._engine+async def test_strategy_preflight_does_not_reserve_a_slot_for_unknown_campaign(+ monkeypatch: Any,+) -> None:+ from datetime import datetime, timedelta, timezone+ from unittest.mock import MagicMock++ from ares.api.rbac import AuthenticatedUser+ from ares.db.websocket_tickets import BearerTicketSource+server._active_engagements.clear()- try:- server._db = SimpleNamespace(get_campaign=AsyncMock(return_value=None))- server._engine = object() # preflight exits before engine use- body = server.AutonomousEngagementRequest(campaign_id="missing", llm_backend="local")- with pytest.raises(server.HTTPException) as exc_info:- await server.start_autonomous_engagement(- body,- actor=SimpleNamespace(username="owner", role="team_lead"),- )- assert exc_info.value.status_code == 404- assert server._active_engagements == {}- finally:- server._db, server._engine = original_db, original_engine- server._active_engagements.clear()+ database = SimpleNamespace(get_campaign=AsyncMock(return_value=None))+ engine = MagicMock()+ engine.run_module = AsyncMock()+ engine.run_plan = AsyncMock()+ runtime = MagicMock()+ planning_seam = MagicMock()+ broadcast = AsyncMock()+ monkeypatch.setattr(server, "_strategy_test_plan", planning_seam)+ monkeypatch.setattr(server, "_broadcast_event", broadcast)+ request = server.Request(+ {+ "type": "http",+ "http_version": "1.1",+ "method": "POST",+ "scheme": "http",+ "path": "/strategy/engage",+ "raw_path": b"/strategy/engage",+ "query_string": b"",+ "headers": [+ (b"authorization", b"Bearer test-only-preflight"),+ (+ b"idempotency-key",+ b"11111111-1111-4111-8111-111111111111",+ ),+ ],+ "client": ("127.0.0.1", 40123),+ "server": ("testserver", 80),+ "app": server.app,+ }+ )+ response = server.Response()+ actor = AuthenticatedUser(+ username="owner",+ role="team_lead",+ websocket_ticket_source=BearerTicketSource(+ user_id="11111111-1111-4111-8111-111111111111",+ subject="owner",+ jti="preflight-jti",+ expires_at=datetime.now(timezone.utc) + timedelta(minutes=5),+ family_id="A" * 43,+ auth_epoch=1,+ ),+ )+ body = server.AutonomousEngagementRequest(+ campaign_id="missing",+ llm_backend="local",+ )++ with pytest.raises(server.HTTPException) as exc_info:+ await server.start_autonomous_engagement(+ body,+ request,+ response,+ actor=actor,+ engine=engine,+ db=database,+ c_live_runtime=runtime,+ )++ assert exc_info.value.status_code == 404+ assert exc_info.value.detail == "Campaign 'missing' not found"+ database.get_campaign.assert_awaited_once_with("missing")+ planning_seam.assert_not_called()+ runtime.bind.assert_not_called()+ engine.run_module.assert_not_awaited()+ engine.run_plan.assert_not_awaited()+ broadcast.assert_not_awaited()+ assert server._active_engagements == {}@pytest.mark.asyncio@@ -228,27 +997,34 @@ async def test_persisted_graph_and_attack_paths_use_safe_durable_rows(tmp_path:db = await AresDatabase.create(tmp_path / "phase1-graph.db", settings.encryption_key_value)campaign = _campaign("phase1-graph")await db.save_campaign(campaign)- await db.upsert_host(Host(- campaign_id=campaign.id,- ip_address="10.10.10.5",- hostname="dc01",- is_dc=True,- ))- await db.save_finding(campaign.id, Finding(- title="Persisted graph finding",- description="Verified durable graph fixture.",- severity=Severity.CRITICAL,- host="10.10.10.5",- module_id="ad.phase1_probe",- validated=True,- ))- await db.save_credential(DBCredential(- campaign_id=campaign.id,- username="svc_graph",- cred_type="cleartext",- secret="graph-secret-must-not-leak",- domain="LAB.LOCAL",- ))+ await db.upsert_host(+ Host(+ campaign_id=campaign.id,+ ip_address="10.10.10.5",+ hostname="dc01",+ is_dc=True,+ )+ )+ await db.save_finding(+ campaign.id,+ Finding(+ title="Persisted graph finding",+ description="Verified durable graph fixture.",+ severity=Severity.CRITICAL,+ host="10.10.10.5",+ module_id="ad.phase1_probe",+ validated=True,+ ),+ )+ await db.save_credential(+ DBCredential(+ campaign_id=campaign.id,+ username="svc_graph",+ cred_type="cleartext",+ secret="graph-secret-must-not-leak",+ domain="LAB.LOCAL",+ )+ )engine = _engine(settings, db)actor = SimpleNamespace(username="owner", role="team_lead")try:diff --git a/tests/unit/test_sdk_public_api.py b/tests/unit/test_sdk_public_api.pyindex f3dd06a..3eb8a8d 100644--- a/tests/unit/test_sdk_public_api.py+++ b/tests/unit/test_sdk_public_api.py@@ -7,6 +7,7 @@ import pytestimport ares.sdk as sdkfrom ares.core.context import ExecutionContextfrom ares.core.engine import AresEngine+from ares.core.execution_admission import _mint_test_dispatch_contextfrom ares.modules.base import BaseModule, ModuleResult, OpsecLevel, validate_module_class@@ -158,6 +159,7 @@ async def test_runtime_uses_module_timeout_contract(monkeypatch) -> None:params={"target": "127.0.0.1"},timeout_seconds=120,actor_role="team_lead",+ dispatch_context=_mint_test_dispatch_context(engine, helper.campaign.id, "demo.timeout"),)assert result.status.value == "done"@@ -216,11 +218,14 @@ async def test_runtime_retries_use_module_timeout_contract(monkeypatch) -> None:params={"target": "127.0.0.1"},timeout_seconds=120,actor_role="team_lead",+ dispatch_context=_mint_test_dispatch_context(+ engine, helper.campaign.id, "demo.retry_timeout"+ ),)- assert result.status.value == "done"- assert result.error is None- assert observed_timeouts == [10, 7, 7]+ assert result.status.value == "timeout"+ assert DemoModule.execute_calls == 1+ assert observed_timeouts == [10, 7]@pytest.mark.asyncio@@ -232,7 +237,10 @@ async def test_module_test_helper_available_from_public_sdk() -> None:description="SDK helper smoke test",)class DemoModule(sdk.BaseModule):+ execute_calls = 0+async def execute(self, ctx: sdk.ExecutionContext) -> sdk.ModuleResult:+ type(self).execute_calls += 1return sdk.ModuleResult(status="dry_run" if ctx.dry_run else "success",module_id=self.MODULE_ID,@@ -245,6 +253,36 @@ async def test_module_test_helper_available_from_public_sdk() -> None:helper = sdk.ModuleTestHelper(DemoModule, scope_cidrs=["127.0.0.1/32"])result = await helper.run_full(target="127.0.0.1", dry_run=True)- assert result.status == "dry_run"+ assert result.status == "preview_only"assert result.module_id == "demo.helper"- assert result.raw == {"target": "127.0.0.1"}+ assert result.raw["target"] == "127.0.0.1"+ assert result.raw["would_execute"] is False+ assert DemoModule.execute_calls == 0++[email protected]("entrypoint", ["run", "run-full"])+async def test_module_test_helper_is_preview_only(entrypoint: str) -> None:+ class PreviewProbe(sdk.BaseModule):+ MODULE_ID = "test.sdk_preview"+ MODULE_NAME = "SDK preview probe"+ MODULE_CATEGORY = "test"+ MODULE_DESCRIPTION = "Proves the public SDK cannot dispatch"+ execute_calls = 0++ async def execute(self, ctx: sdk.ExecutionContext) -> sdk.ModuleResult:+ type(self).execute_calls += 1+ return sdk.ModuleResult(status="success", module_id=self.MODULE_ID)++ async def run(self, **kwargs):+ type(self).execute_calls += 1+ return [], {}++ helper = sdk.ModuleTestHelper(PreviewProbe)+ if entrypoint == "run":+ result = await helper.run(helper.make_context())+ else:+ result = await helper.run_full()+ assert result.status == "preview_only"+ assert result.raw["would_execute"] is False+ assert PreviewProbe.execute_calls == 0diff --git a/tests/unit/test_security_critical.py b/tests/unit/test_security_critical.pyindex 0cf108b..ac311b9 100644--- a/tests/unit/test_security_critical.py+++ b/tests/unit/test_security_critical.py@@ -14,6 +14,7 @@ Coverage:Pattern: httpx.ASGITransport + dependency_overrides (no lifespan needed).All tests are self-contained — no shared mutable state between classes."""+from __future__ import annotationsimport asyncio@@ -23,8 +24,8 @@ from unittest.mock import AsyncMock, MagicMockimport pytest# ── env bootstrap (before any ares import) ────────────────────────────────────-os.environ.setdefault("ARES_SECRET_KEY", "test-sec-critical-min32-chars!!!!")-os.environ.setdefault("ARES_ENCRYPTION_KEY", "test-enc-critical-min32-chars!!!!")+os.environ.setdefault("ARES_SECRET_KEY", "test-sec-critical-min32-chars!!!!")+os.environ.setdefault("ARES_ENCRYPTION_KEY", "test-enc-critical-min32-chars!!!!")os.environ.setdefault("ARES_DEFAULT_ADMIN_PASSWORD", "TestCriticalPass1!")os.environ.setdefault("ARES_DEBUG", "true")os.environ.setdefault("ARES_BROWSER_ORIGIN", "http://localhost:5173")@@ -46,6 +47,7 @@ def _isolate_server_dependencies():def _settings():from ares.core.config import get_settings+get_settings.cache_clear()return get_settings()@@ -69,17 +71,18 @@ def _auth(username: str, role: str) -> dict:def _make_mock_db():db = MagicMock()- db.verify_user = AsyncMock(return_value=None)- db.get_user = AsyncMock(return_value=None)- db.user_exists = AsyncMock(return_value=False)- db.create_user = AsyncMock()- db.create_refresh_token = AsyncMock(return_value="raw-mock-refresh-token")- db.rotate_refresh_token = AsyncMock(return_value=(None, None))+ db.verify_user = AsyncMock(return_value=None)+ db.get_user = AsyncMock(return_value=None)+ db.user_exists = AsyncMock(return_value=False)+ db.create_user = AsyncMock()+ db.create_refresh_token = AsyncMock(return_value="raw-mock-refresh-token")+ db.rotate_refresh_token = AsyncMock(return_value=(None, None))db.revoke_all_refresh_tokens = AsyncMock()from ares.core.token_sessions import (SessionRevocationResult,SessionRevocationStatus,)+db.revoke_current_session = AsyncMock(return_value=SessionRevocationResult(SessionRevocationStatus.REVOKED))@@ -89,8 +92,8 @@ def _make_mock_db():db.revoke_all_sessions = AsyncMock(return_value=SessionRevocationResult(SessionRevocationStatus.REVOKED))- db.revoke_access_token = AsyncMock()- db.is_access_token_revoked = AsyncMock(return_value=False)+ db.revoke_access_token = AsyncMock()+ db.is_access_token_revoked = AsyncMock(return_value=False)async def resolve_access_token_principal(subject: str,@@ -110,20 +113,19 @@ def _make_mock_db():"auth_epoch": auth_epoch,}- db.resolve_access_token_principal = AsyncMock(- side_effect=resolve_access_token_principal- )- db.audit = AsyncMock()- db.purge_expired_tokens = AsyncMock(return_value=0)- db.list_campaigns = AsyncMock(return_value=([], 0))- db.get_campaign = AsyncMock(return_value=None)- db.verify_api_key = AsyncMock(return_value=None)- db.load_credentials_raw = AsyncMock(return_value=[])+ db.resolve_access_token_principal = AsyncMock(side_effect=resolve_access_token_principal)+ db.audit = AsyncMock()+ db.purge_expired_tokens = AsyncMock(return_value=0)+ db.list_campaigns = AsyncMock(return_value=([], 0))+ db.get_campaign = AsyncMock(return_value=None)+ db.verify_api_key = AsyncMock(return_value=None)+ db.load_credentials_raw = AsyncMock(return_value=[])return dbdef _reset_limiter() -> None:from ares.api.rbac import _limiter+_limiter._windows.clear()@@ -158,12 +160,8 @@ def _browser_client(app):base_url="http://localhost:5173",event_hooks={"request": [_headers]},)- client.cookies.set(- "ares-dev-csrf", "A" * 43, domain="localhost.local", path="/"- )- client.cookies.set(- "ares-dev-refresh", "r" * 64, domain="localhost.local", path="/"- )+ client.cookies.set("ares-dev-csrf", "A" * 43, domain="localhost.local", path="/")+ client.cookies.set("ares-dev-refresh", "r" * 64, domain="localhost.local", path="/")return client@@ -206,6 +204,7 @@ def test_main_websocket_scrubs_query_before_actual_uvicorn_logging():from ares.api.server import campaign_events, _take_campaign_websocket_ticketfrom uvicorn.config import UvicornDeprecationWarning+with warnings.catch_warnings():warnings.simplefilter("ignore", DeprecationWarning)warnings.simplefilter("ignore", UvicornDeprecationWarning)@@ -242,9 +241,9 @@ def test_main_websocket_scrubs_query_before_actual_uvicorn_logging():call_count, marker_absent = _run(exercise())route_body = ast.parse(textwrap.dedent(inspect.getsource(campaign_events))).body[0].body- helper_body = ast.parse(- textwrap.dedent(inspect.getsource(_take_campaign_websocket_ticket))- ).body[0].body+ helper_body = (+ ast.parse(textwrap.dedent(inspect.getsource(_take_campaign_websocket_ticket))).body[0].body+ )route_first_operation_is_scrub = (isinstance(route_body[1], ast.Assign)and isinstance(route_body[1].value, ast.Call)@@ -275,6 +274,7 @@ def test_main_websocket_scrubs_query_before_actual_uvicorn_logging():# TEST CLASS 1 — TOKEN REVOCATION# ══════════════════════════════════════════════════════════════════════+class TestTokenRevocation:"""After logout, a still-valid (not-expired) access token must be rejected.@@ -286,8 +286,9 @@ class TestTokenRevocation:def _client(self, mock_db):from ares.api.server import app, get_db, get_settings+app.state.db = mock_db- app.dependency_overrides[get_db] = lambda: mock_db+ app.dependency_overrides[get_db] = lambda: mock_dbapp.dependency_overrides[get_settings] = lambda: _settings()return _browser_client(app)@@ -303,22 +304,20 @@ class TestTokenRevocation:f"Revoked token must return 401, got {r.status_code}. ""Logout is ineffective — token still works after revocation!")+_run(_run_test())def test_valid_token_accepted(self):"""Token not in blacklist must work normally."""db = _make_mock_db()db.is_access_token_revoked = AsyncMock(return_value=False)- db.get_user = AsyncMock(return_value={- "id": "u1", "username": "alice", "role": "operator"- })+ db.get_user = AsyncMock(return_value={"id": "u1", "username": "alice", "role": "operator"})async def _run_test():async with self._client(db) as c:r = await c.get("/auth/me", headers=_auth("alice", "operator"))- assert r.status_code == 200, (- f"Valid token must return 200, got {r.status_code}"- )+ assert r.status_code == 200, f"Valid token must return 200, got {r.status_code}"+_run(_run_test())def test_expired_token_rejected(self):@@ -328,20 +327,16 @@ class TestTokenRevocation:async def _run_test():async with self._client(db) as c:- r = await c.get("/auth/me",- headers={"Authorization": f"Bearer {token}"})- assert r.status_code == 401, (- f"Expired token must return 401, got {r.status_code}"- )+ r = await c.get("/auth/me", headers={"Authorization": f"Bearer {token}"})+ assert r.status_code == 401, f"Expired token must return 401, got {r.status_code}"+_run(_run_test())def test_logout_triggers_cookie_family_revocation(self):"""POST /auth/logout must use refresh-cookie family authority."""db = _make_mock_db()db.is_access_token_revoked = AsyncMock(return_value=False)- db.get_user = AsyncMock(return_value={- "id": "u1", "username": "alice", "role": "operator"- })+ db.get_user = AsyncMock(return_value={"id": "u1", "username": "alice", "role": "operator"})async def _run_test():async with self._client(db) as c:@@ -349,6 +344,7 @@ class TestTokenRevocation:assert r.status_code == 204db.revoke_refresh_cookie_session.assert_awaited_once()db.revoke_current_session.assert_not_awaited()+_run(_run_test())@@ -356,6 +352,7 @@ class TestTokenRevocation:# TEST CLASS 2 — DASHBOARD AUTHENTICATION# ══════════════════════════════════════════════════════════════════════+class TestDashboardAuthentication:"""Every dashboard /api/* endpoint must return 401 without a valid token.@@ -363,17 +360,18 @@ class TestDashboardAuthentication:"""PROTECTED = [- ("GET", "/api/status"),- ("GET", "/api/campaigns"),- ("GET", "/api/campaigns/test-id/findings"),- ("GET", "/api/campaigns/test-id/hosts"),- ("GET", "/api/campaigns/test-id/summary"),- ("GET", "/api/workers"),+ ("GET", "/api/status"),+ ("GET", "/api/campaigns"),+ ("GET", "/api/campaigns/test-id/findings"),+ ("GET", "/api/campaigns/test-id/hosts"),+ ("GET", "/api/campaigns/test-id/summary"),+ ("GET", "/api/workers"),]def _client(self):import httpxfrom ares.api.dashboard.app import dashboard_app+dashboard_app.state.db = _make_mock_db()return httpx.AsyncClient(transport=httpx.ASGITransport(app=dashboard_app),@@ -383,6 +381,7 @@ class TestDashboardAuthentication:@pytest.mark.parametrize("method,path", PROTECTED)def test_endpoint_requires_auth(self, method, path):"""Each protected endpoint must return 401 with no token."""+async def _run_test():async with self._client() as c:r = await c.request(method, path)@@ -390,14 +389,17 @@ class TestDashboardAuthentication:f"Dashboard [{method}] {path} returned {r.status_code} without auth. ""This endpoint exposes campaign data without authentication!")+_run(_run_test())def test_root_accessible_without_auth(self):"""GET / (HTML shell) is intentionally public."""+async def _run_test():async with self._client() as c:r = await c.get("/")assert r.status_code == 200+_run(_run_test())def test_valid_token_grants_access(self):@@ -408,15 +410,16 @@ class TestDashboardAuthentication:async def _run_test():import httpxfrom ares.api.dashboard.app import dashboard_app+db.is_access_token_revoked = AsyncMock(return_value=False)dashboard_app.state.db = dbasync with httpx.AsyncClient(transport=httpx.ASGITransport(app=dashboard_app),base_url="http://localhost",) as c:- r = await c.get("/api/campaigns",- headers=_auth("alice", "operator"))+ r = await c.get("/api/campaigns", headers=_auth("alice", "operator"))assert r.status_code == 200+_run(_run_test())@@ -424,6 +427,7 @@ class TestDashboardAuthentication:# TEST CLASS 3 — RBAC ENFORCEMENT PER ROLE# ══════════════════════════════════════════════════════════════════════+def test_legacy_dashboard_escapes_api_fields_before_innerhtml():"""API-derived strings must be escaped before legacy dashboard innerHTML use."""from ares.api.dashboard.app import _DASHBOARD_HTML@@ -458,7 +462,7 @@ def test_legacy_dashboard_escapes_api_fields_before_innerhtml():"${c.name}</div>","${c.client}","${f.mitre_technique}</span>",- "<span class=\"ip\">${h.ip_address}</span>",+ '<span class="ip">${h.ip_address}</span>',">(${h.hostname})</span>","${h.os || 'Unknown OS'}","' ' + h.os_version",@@ -488,20 +492,21 @@ class TestRBACEnforcement:def _client(self, mock_db=None):from ares.api.server import app, get_db, get_settings+db = mock_db or _make_mock_db()app.state.db = db- app.dependency_overrides[get_db] = lambda: db+ app.dependency_overrides[get_db] = lambda: dbapp.dependency_overrides[get_settings] = lambda: _settings()return _browser_client(app)def test_no_token_returns_401(self):"""Unauthenticated request must return 401, not 403."""+async def _run_test():async with self._client() as c:r = await c.get("/campaigns")- assert r.status_code == 401, (- f"No token must return 401, not {r.status_code}"- )+ assert r.status_code == 401, f"No token must return 401, not {r.status_code}"+_run(_run_test())def test_reporter_blocked_from_creating_campaign(self):@@ -518,6 +523,7 @@ class TestRBACEnforcement:assert r.status_code == 403, (f"Reporter must get 403 on POST /campaigns, got {r.status_code}")+_run(_run_test())def test_reporter_can_read_campaigns(self):@@ -526,11 +532,11 @@ class TestRBACEnforcement:async def _run_test():async with self._client(db) as c:- r = await c.get("/campaigns",- headers=_auth("reporter1", "reporter"))+ r = await c.get("/campaigns", headers=_auth("reporter1", "reporter"))assert r.status_code == 200, (f"Reporter must be able to read campaigns, got {r.status_code}")+_run(_run_test())def test_operator_blocked_from_registering_users(self):@@ -541,13 +547,13 @@ class TestRBACEnforcement:async with self._client(db) as c:r = await c.post("/auth/register",- json={"username": "newuser", "password": "Password1!",- "role": "operator"},+ json={"username": "newuser", "password": "Password1!", "role": "operator"},headers=_auth("op1", "operator"),)assert r.status_code == 403, (f"Operator must be blocked from /auth/register, got {r.status_code}")+_run(_run_test())def test_team_lead_can_register_users(self):@@ -560,18 +566,19 @@ class TestRBACEnforcement:async with self._client(db) as c:r = await c.post("/auth/register",- json={"username": "newuser", "password": "StrongPass1!",- "role": "operator"},+ json={"username": "newuser", "password": "StrongPass1!", "role": "operator"},headers=_auth("lead1", "team_lead"),)assert r.status_code in (200, 201, 422), (f"team_lead must reach /auth/register (200/201), got {r.status_code}")+_run(_run_test())def test_can_run_module_rbac_operator(self):"""operator may run ad.* and lateral.* modules."""from ares.api.rbac import AuthenticatedUser+user = AuthenticatedUser(username="op1", role="operator")assert user.can_run_module("ad.kerberoast")assert user.can_run_module("lateral.psexec")@@ -580,6 +587,7 @@ class TestRBACEnforcement:def test_can_run_module_rbac_recon(self):"""recon may only run enumeration modules."""from ares.api.rbac import AuthenticatedUser+user = AuthenticatedUser(username="recon1", role="recon")assert user.can_run_module("ad.enum_users")assert user.can_run_module("network.port_scan")@@ -590,6 +598,7 @@ class TestRBACEnforcement:def test_can_run_module_rbac_reporter(self):"""reporter may not run any module."""from ares.api.rbac import AuthenticatedUser+user = AuthenticatedUser(username="rep1", role="reporter")assert not user.can_run_module("ad.enum_users")assert not user.can_run_module("reporting.report_gen")@@ -598,6 +607,7 @@ class TestRBACEnforcement:"""Unknown role string must default to most restrictive (reporter)."""from ares.api.rbac import AuthenticatedUserfrom ares.collab.manager import OperatorRole+user = AuthenticatedUser(username="mystery", role="god_mode")assert user.operator_role == OperatorRole.REPORTERassert not user.can_run_module("ad.kerberoast")@@ -607,6 +617,7 @@ class TestRBACEnforcement:# TEST CLASS 4 — REFRESH TOKEN RATE LIMITING# ══════════════════════════════════════════════════════════════════════+class TestRefreshTokenRateLimit:"""POST /auth/refresh must be rate-limited to prevent token flooding."""@@ -615,15 +626,17 @@ class TestRefreshTokenRateLimit:def _client(self, mock_db=None):from ares.api.server import app, get_db, get_settings+db = mock_db or _make_mock_db()app.state.db = db- app.dependency_overrides[get_db] = lambda: db+ app.dependency_overrides[get_db] = lambda: dbapp.dependency_overrides[get_settings] = lambda: _settings()return _browser_client(app)def test_rate_limited_after_many_attempts(self):"""After N refresh calls from same IP, 429 must be returned."""from ares.api.rbac import RATE_LIMITS+limit = RATE_LIMITS["auth"]async def _run_test():@@ -632,14 +645,14 @@ class TestRefreshTokenRateLimit:for _ in range(limit + 2):r = await c.post("/auth/refresh")statuses.append(r.status_code)- assert 429 in statuses, (- f"Expected 429 after {limit} attempts, got statuses: {statuses}"- )+ assert 429 in statuses, f"Expected 429 after {limit} attempts, got statuses: {statuses}"+_run(_run_test())def test_429_has_retry_after_header(self):"""Rate-limit 429 response must include Retry-After header."""from ares.api.rbac import RATE_LIMITS+limit = RATE_LIMITS["auth"]async def _run_test():@@ -653,6 +666,7 @@ class TestRefreshTokenRateLimit:)returnpytest.fail("Never received 429 — rate limiting not working")+_run(_run_test())@@ -660,6 +674,7 @@ class TestRefreshTokenRateLimit:# TEST CLASS 5 — CREDENTIAL VAULT PERSISTENCE# ══════════════════════════════════════════════════════════════════════+class TestCredentialVaultPersistence:"""Credentials found during a module run must persist to DB and be restorable."""@@ -673,12 +688,13 @@ class TestCredentialVaultPersistence:db.save_credential_preencrypted = AsyncMock()campaign = Campaign(- name="persist-test", client="test",+ name="persist-test",+ client="test",scope=[ScopeEntry(cidr="10.0.0.0/8")],noise_profile=NoiseProfile.NORMAL,)vault = CredentialVault(encryption_key="test-vault-key-32-chars-ok!!!!")- cred = Credential(+ cred = Credential(campaign_id=campaign.id,username="administrator",domain="CORP",@@ -696,8 +712,9 @@ class TestCredentialVaultPersistence:db.save_credential_preencrypted.assert_called_once()call = db.save_credential_preencrypted.call_args[0][0]assert call.username == "administrator"- assert call.domain == "CORP"+ assert call.domain == "CORP"assert "ntlm" in call.cred_type.lower()+_run(_run_test())def test_restore_from_db_records(self):@@ -708,36 +725,40 @@ class TestCredentialVaultPersistence:# Vault A: store a credentialvault_a = CredentialVault(encryption_key=enc_key)- cred = Credential(- id="cred-restore-001", campaign_id="camp-001",- username="svc_sql", domain="CORP",+ cred = Credential(+ id="cred-restore-001",+ campaign_id="camp-001",+ username="svc_sql",+ domain="CORP",cred_type=CredentialType.CLEARTEXT,source_module="test",)vault_a.store(cred, "SuperSecret99!")- stored = vault_a._store["cred-restore-001"]- secret_enc = stored.secret_enc- secret_str = secret_enc.decode() if isinstance(secret_enc, bytes) else secret_enc+ stored = vault_a._store["cred-restore-001"]+ secret_enc = stored.secret_enc+ secret_str = secret_enc.decode() if isinstance(secret_enc, bytes) else secret_enc# Simulate what DB returns- db_records = [{- "id": "cred-restore-001",- "campaign_id": "camp-001",- "username": "svc_sql",- "domain": "CORP",- "cred_type": "cleartext",- "secret_enc": secret_str,- "source_module": "test",- "host_id": None,- "notes": "",- }]+ db_records = [+ {+ "id": "cred-restore-001",+ "campaign_id": "camp-001",+ "username": "svc_sql",+ "domain": "CORP",+ "cred_type": "cleartext",+ "secret_enc": secret_str,+ "source_module": "test",+ "host_id": None,+ "notes": "",+ }+ ]# Vault B: restore from DB — share salt/fernet for compatibilityvault_b = CredentialVault(encryption_key=enc_key)- vault_b._salt = vault_a._salt+ vault_b._salt = vault_a._saltvault_b._salt_hex = vault_a._salt_hex- vault_b._fernet = vault_a._fernet+ vault_b._fernet = vault_a._fernetcount = vault_b.restore_from_db_records(db_records)@@ -759,7 +780,8 @@ class TestCredentialVaultPersistence:db.save_credential_preencrypted = AsyncMock()campaign = Campaign(- name="empty-vault-test", client="test",+ name="empty-vault-test",+ client="test",scope=[ScopeEntry(cidr="10.0.0.0/8")],noise_profile=NoiseProfile.NORMAL,)@@ -771,6 +793,7 @@ class TestCredentialVaultPersistence:saved = await engine._persist_vault_credentials(campaign)assert saved == 0db.save_credential_preencrypted.assert_not_called()+_run(_run_test())def test_no_vault_on_campaign_is_safe(self):@@ -778,10 +801,11 @@ class TestCredentialVaultPersistence:from ares.core.campaign import Campaign, ScopeEntry, NoiseProfilefrom ares.core.engine import AresEngine- db = MagicMock()+ db = MagicMock()db.save_credential_preencrypted = AsyncMock()campaign = Campaign(- name="no-vault", client="test",+ name="no-vault",+ client="test",scope=[ScopeEntry(cidr="10.0.0.0/8")],noise_profile=NoiseProfile.NORMAL,)@@ -791,6 +815,7 @@ class TestCredentialVaultPersistence:async def _run_test():saved = await engine._persist_vault_credentials(campaign)assert saved == 0+_run(_run_test())@@ -798,6 +823,7 @@ class TestCredentialVaultPersistence:# TEST CLASS 6 — validate() ENFORCEMENT# ══════════════════════════════════════════════════════════════════════+class TestValidateEnforcement:"""Engine must call validate() before execute() on every module run."""@@ -807,19 +833,20 @@ class TestValidateEnforcement:from ares.core.errors import ModuleValidationErrorfrom ares.core.campaign import Campaign, ScopeEntry, NoiseProfilefrom ares.core.engine import AresEngine+ from ares.core.execution_admission import _mint_test_dispatch_contextvalidate_calls: list[bool] = []- execute_calls: list[bool] = []+ execute_calls: list[bool] = []class _StrictModule(BaseModule):- MODULE_ID = "test.strict_validate"- MODULE_NAME = "Strict Test"- MODULE_CATEGORY = "test"+ MODULE_ID = "test.strict_validate"+ MODULE_NAME = "Strict Test"+ MODULE_CATEGORY = "test"MODULE_DESCRIPTION = "Validation test module"- OPSEC_LEVEL = OpsecLevel.SILENT- MITRE_TECHNIQUES = []- REQUIRES = ["target"]- OUTPUTS = []+ OPSEC_LEVEL = OpsecLevel.SILENT+ MITRE_TECHNIQUES = []+ REQUIRES = ["target"]+ OUTPUTS = []async def validate(self, ctx):validate_calls.append(True)@@ -832,16 +859,17 @@ class TestValidateEnforcement:async def execute(self, ctx):execute_calls.append(True)- return ModuleResult(status="success", findings=[], raw={},- module_id=self.MODULE_ID)+ return ModuleResult(status="success", findings=[], raw={}, module_id=self.MODULE_ID)campaign = Campaign(- name="validate-test", client="test",+ name="validate-test",+ client="test",scope=[ScopeEntry(cidr="10.0.0.0/8")],noise_profile=NoiseProfile.NORMAL,)from ares.core.engine import ModuleRegistry as _Reg+registry = _Reg()registry._registry = {"test.strict_validate": _StrictModule}@@ -850,21 +878,25 @@ class TestValidateEnforcement:async def _run_test():from ares.core.config import get_settings+get_settings.cache_clear()result = await engine.run_module("test.strict_validate",campaign,params={"target": "10.0.0.1"},actor_role="team_lead",+ dispatch_context=_mint_test_dispatch_context(+ engine, campaign.id, "test.strict_validate"+ ),# No required_param — validate() must fail)assert len(validate_calls) == 1, "validate() must be called exactly once"- assert len(execute_calls) == 0, (- "execute() must NOT run when validate() raises"- )+ assert len(execute_calls) == 0, "execute() must NOT run when validate() raises"from ares.core.engine import ModuleStatus+assert result.status == ModuleStatus.FAILEDassert "required_param" in (result.error or "")+_run(_run_test())def test_skip_validation_bypasses_validate(self):@@ -873,38 +905,38 @@ class TestValidateEnforcement:from ares.core.errors import ModuleValidationErrorfrom ares.core.campaign import Campaign, ScopeEntry, NoiseProfilefrom ares.core.engine import AresEngine+ from ares.core.execution_admission import _mint_test_dispatch_contextvalidate_calls: list[bool] = []- execute_calls: list[bool] = []+ execute_calls: list[bool] = []class _AlwaysFailValidate(BaseModule):- MODULE_ID = "test.always_fail_validate"- MODULE_NAME = "Always Fail Validate"- MODULE_CATEGORY = "test"+ MODULE_ID = "test.always_fail_validate"+ MODULE_NAME = "Always Fail Validate"+ MODULE_CATEGORY = "test"MODULE_DESCRIPTION = "Skip validation test"- OPSEC_LEVEL = OpsecLevel.SILENT- MITRE_TECHNIQUES = []- REQUIRES = []- OUTPUTS = []+ OPSEC_LEVEL = OpsecLevel.SILENT+ MITRE_TECHNIQUES = []+ REQUIRES = []+ OUTPUTS = []async def validate(self, ctx):validate_calls.append(True)- raise ModuleValidationError(- "always fails", module_id=self.MODULE_ID- )+ raise ModuleValidationError("always fails", module_id=self.MODULE_ID)async def execute(self, ctx):execute_calls.append(True)- return ModuleResult(status="success", findings=[], raw={},- module_id=self.MODULE_ID)+ return ModuleResult(status="success", findings=[], raw={}, module_id=self.MODULE_ID)campaign = Campaign(- name="skip-validate-test", client="test",+ name="skip-validate-test",+ client="test",scope=[ScopeEntry(cidr="10.0.0.0/8")],noise_profile=NoiseProfile.NORMAL,)from ares.core.engine import ModuleRegistry as _Reg+registry = _Reg()registry._registry = {"test.always_fail_validate": _AlwaysFailValidate}@@ -913,6 +945,7 @@ class TestValidateEnforcement:async def _run_test():from ares.core.config import get_settings+get_settings.cache_clear()result = await engine.run_module("test.always_fail_validate",@@ -920,15 +953,18 @@ class TestValidateEnforcement:params={"target": "10.0.0.1"},skip_validation=True,actor_role="team_lead",+ dispatch_context=_mint_test_dispatch_context(+ engine, campaign.id, "test.always_fail_validate"+ ),)assert len(validate_calls) == 0, ("validate() must NOT be called when skip_validation=True")- assert len(execute_calls) == 1, (- "execute() must run when validation is skipped"- )+ assert len(execute_calls) == 1, "execute() must run when validation is skipped"from ares.core.engine import ModuleStatus+assert result.status == ModuleStatus.DONE+_run(_run_test())def test_targets_validation_rejects_path_traversal(self):diff --git a/tests/unit/test_sqlite_auth_token_lifecycle.py b/tests/unit/test_sqlite_auth_token_lifecycle.pyindex 7d4e8e1..29914a4 100644--- a/tests/unit/test_sqlite_auth_token_lifecycle.py+++ b/tests/unit/test_sqlite_auth_token_lifecycle.py@@ -150,6 +150,63 @@ async def db_and_user(tmp_path: Path) -> AsyncIterator[tuple[AresDatabase, str]]await db.close()+async def test_sqlite_c_live_trusted_store_factory_is_coordinator_only(+ db_and_user: tuple[AresDatabase, str],+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ from ares.api.rbac import AuthenticatedUser+ from ares.api.server import _CLiveRuntime+ from ares.db.websocket_tickets import BearerTicketSource++ database, user_id = db_and_user+ original_factory = database.execution_lifecycle_store+ stores: list[object] = []++ def tracked_factory() -> object:+ store = original_factory()+ stores.append(store)+ return store++ class SealedEngine:+ def __init__(self) -> None:+ self.store_ids: list[int] = []++ def _bind_admission_store(self, store: object) -> None:+ store_id = id(store)+ if self.store_ids and self.store_ids[-1] != store_id:+ raise PermissionError("cross-store binding")+ self.store_ids.append(store_id)++ monkeypatch.setattr(database, "execution_lifecycle_store", tracked_factory)+ engine = SealedEngine()+ runtime = _CLiveRuntime(database, engine)+ family_id = __import__("base64").urlsafe_b64encode(+ hashlib.sha256(b"sqlite-c-live-family").digest()+ ).rstrip(b"=").decode("ascii")+ actor = AuthenticatedUser(+ username="sqlite-lifecycle-user",+ role="operator",+ websocket_ticket_source=BearerTicketSource(+ user_id=user_id,+ subject="sqlite-lifecycle-user",+ jti="10000000-0000-4000-8000-000000000001",+ expires_at=datetime.now(timezone.utc) + timedelta(minutes=5),+ family_id=family_id,+ auth_epoch=1,+ ),+ )++ first_principal, first = runtime.bind(actor)+ second_principal, second = runtime.bind(actor)++ assert len(stores) == 1+ assert runtime.store is stores[0]+ assert first is not second+ assert first_principal is not second_principal+ assert engine.store_ids == [id(stores[0]), id(stores[0])]++@pytest.mark.asyncioasync def test_rotation_before_connect_fails_without_creating_database(tmp_path: Path,diff --git a/tests/unit/test_strategy_engine.py b/tests/unit/test_strategy_engine.pyindex 118c363..308eb17 100644--- a/tests/unit/test_strategy_engine.py+++ b/tests/unit/test_strategy_engine.py@@ -14,12 +14,12 @@ Run: pytest tests/unit/test_strategy_engine.py -v"""from __future__ import annotations-import asyncioimport sys-import time-from pathlib import Path-from unittest.mock import MagicMock, AsyncMock, patchfrom dataclasses import dataclass+from pathlib import Path+from types import SimpleNamespace+from typing import Any+from unittest.mock import AsyncMock, MagicMockimport pytest@@ -28,6 +28,179 @@ if str(_ROOT) not in sys.path:sys.path.insert(0, str(_ROOT))+def _c_live_strategy_engine_with(+ coordinator: Any,+ plan: tuple[dict[str, Any], ...],+):+ from ares.db.execution_lifecycle import TrustedPrincipal+ from ares.strategy.engine import StrategyEngine++ engine = StrategyEngine(ares_engine=MagicMock(), settings=MagicMock())+ engine._configure_c_live_test_plan(+ coordinator=coordinator,+ principal=TrustedPrincipal(+ "00000000-0000-4000-8000-000000000021",+ "00000000-0000-4000-8000-000000000021",+ ),+ idempotency_key="00000000-0000-4000-8000-000000000048",+ plan=plan,+ )+ return engine+++def _c_live_strategy_outcome(disposition: Any, *, status: str = "success") -> Any:+ from ares.db.execution_lifecycle import FixedResult++ return SimpleNamespace(+ disposition=disposition,+ identity=None,+ lifecycle_result=FixedResult.APPLIED,+ module_result=SimpleNamespace(status=status, findings=[]),+ terminal_committed=disposition.value == "terminal",+ )+++async def test_c_live_strategy_single_module_uses_coordinator():+ from ares.core.execution_admission import DispatchDispositionV1++ coordinator = SimpleNamespace(+ execute_module=AsyncMock(+ return_value=_c_live_strategy_outcome(DispatchDispositionV1.TERMINAL)+ )+ )+ engine = _c_live_strategy_engine_with(+ coordinator,+ ({"module_id": "ad.test", "params": {"target": "10.0.0.1"}},),+ )++ result = await engine.run_autonomous_engagement(SimpleNamespace(id="campaign-21"))++ assert result.final_status == "terminal"+ assert result.modules_succeeded == ["ad.test"]+ coordinator.execute_module.assert_awaited_once()+ request = coordinator.execute_module.await_args.args[1]+ assert request.ingress_code == "strategy"+ assert request.module_id == "ad.test"+++async def test_c_live_strategy_child_revalidates_after_principal_revocation():+ from ares.core.execution_admission import DispatchDispositionV1++ coordinator = SimpleNamespace(+ execute_module=AsyncMock(+ side_effect=[+ _c_live_strategy_outcome(DispatchDispositionV1.TERMINAL),+ _c_live_strategy_outcome(DispatchDispositionV1.NON_DISPATCHABLE),+ ]+ )+ )+ engine = _c_live_strategy_engine_with(+ coordinator,+ (+ {"module_id": "ad.first", "params": {}},+ {"module_id": "ad.revoked", "params": {}},+ ),+ )++ result = await engine.run_autonomous_engagement(SimpleNamespace(id="campaign-48"))++ assert result.final_status == "non_dispatchable"+ assert coordinator.execute_module.await_count == 2+++ "helper_name",+ ["coverage-predictor", "edr-context", "ai-planner"],+ ids=["coverage-predictor", "edr-context", "ai-planner"],+)+async def test_c_live_strategy_helper_is_disabled_without_network(helper_name):+ from ares.strategy.engine import StrategyEngine++ engine = StrategyEngine(ares_engine=MagicMock(), settings=MagicMock())+ campaign = MagicMock()+ if helper_name == "coverage-predictor":+ value = await engine._run_coverage_predictor(campaign)+ assert value["detection_score"] == 0.0+ elif helper_name == "edr-context":+ value = await engine._get_edr_context(campaign)+ assert value["viable_techniques"] == []+ else:+ value = await engine._run_ai_planner(campaign, "goal", "local", "", False, {})+ assert value["execution_plan"] == []+ engine._engine.run_module.assert_not_called()+++async def test_c_live_strategy_parent_child_partial_completion_is_durable_and_not_redispatched():+ from ares.core.execution_admission import DispatchDispositionV1++ effects: dict[str, int] = {}+ calls = 0++ async def execute_module(principal, request, campaign):+ nonlocal calls+ del principal, campaign+ calls += 1+ if calls == 2:+ return _c_live_strategy_outcome(DispatchDispositionV1.NON_DISPATCHABLE)+ if effects.get(request.module_id):+ return _c_live_strategy_outcome(DispatchDispositionV1.REPLAYED)+ effects[request.module_id] = 1+ return _c_live_strategy_outcome(DispatchDispositionV1.TERMINAL)++ coordinator = SimpleNamespace(execute_module=execute_module)+ engine = _c_live_strategy_engine_with(+ coordinator,+ (+ {"module_id": "ad.first", "params": {}},+ {"module_id": "ad.second", "params": {}},+ ),+ )+ campaign = SimpleNamespace(id="campaign-74")++ first = await engine.run_autonomous_engagement(campaign)+ second = await engine.run_autonomous_engagement(campaign)++ assert first.final_status == "non_dispatchable"+ assert second.final_status == "terminal"+ assert effects == {"ad.first": 1, "ad.second": 1}+++async def test_c_live_test_plan_is_complete_before_first_module_effect():+ from ares.core.execution_admission import DispatchDispositionV1++ original_params = {"target": "10.0.0.75"}+ engine_holder: dict[str, Any] = {}++ async def execute_module(principal, request, campaign):+ del principal, campaign+ frozen = engine_holder["engine"]._c_live_test_plan_json+ assert frozen is not None+ assert '"ad.first"' in frozen+ assert '"ad.second"' in frozen+ if request.module_id == "ad.first":+ assert request.raw_parameters == {"target": "10.0.0.75"}+ return _c_live_strategy_outcome(DispatchDispositionV1.TERMINAL)++ engine = _c_live_strategy_engine_with(+ SimpleNamespace(execute_module=execute_module),+ (+ {"module_id": "ad.first", "params": original_params},+ {"module_id": "ad.second", "params": {}},+ ),+ )+ engine_holder["engine"] = engine+ original_params["target"] = "mutated-after-freeze"++ result = await engine.run_autonomous_engagement(SimpleNamespace(id="campaign-75"))++ assert result.final_status == "terminal"++# ═══════════════════════════════════════════════════════════════════════════════# 1. Data Models# ═══════════════════════════════════════════════════════════════════════════════diff --git a/tests/unit/test_unversioned_database_adoption.py b/tests/unit/test_unversioned_database_adoption.pyindex 816d370..ea6fa88 100644--- a/tests/unit/test_unversioned_database_adoption.py+++ b/tests/unit/test_unversioned_database_adoption.py@@ -14,6 +14,7 @@ from alembic import commandimport ares.db.migrations.adoption as adoption_modulefrom ares.db.database import AresDatabase+from ares.db.execution_lifecycle import sqlite_admission_authority_runtime_scriptfrom ares.db.migrations.adoption import (SUPPORTED_GENERATIONS,AdoptionExit,@@ -26,6 +27,7 @@ from ares.db.migrations.adoption import (sqlite_catalog_and_row_digest,verify_managed_connection_from_path,)+from ares.db.schema import CREATE_TABLESasync def _create_runtime(path: Path, *, generation: int = 7) -> None:@@ -64,6 +66,8 @@ def test_supported_generation_contract_is_frozen() -> None:("sqlite", 7, "0007", True),("postgresql", 6, "0006", False),("postgresql", 7, "0007", True),+ ("sqlite", 10, "runtime-0010", True),+ ("sqlite", 11, "runtime-0011", True),)@@ -114,6 +118,39 @@ async def test_sqlite_runtime_generation_is_classified(assert version_count == 0+async def test_runtime_generation_ten_adopts_by_exact_catalog_then_removes_marker(+ tmp_path: Path,+) -> None:+ path = tmp_path / "runtime-ten.db"+ backup = tmp_path / "runtime-ten.backup"+ connection = sqlite3.connect(path)+ try:+ generation_11_script = sqlite_admission_authority_runtime_script()+ assert CREATE_TABLES.endswith(generation_11_script)+ connection.executescript(CREATE_TABLES[: -len(generation_11_script)])+ finally:+ connection.close()+ classified = inspect_sqlite_database(path)+ adopted = await asyncio.to_thread(adopt_sqlite, path, backup)+ connection = sqlite3.connect(path)+ try:+ revision = connection.execute(+ "SELECT version_num FROM alembic_version"+ ).fetchone()[0]+ legacy_marker = connection.execute(+ "SELECT count(*) FROM sqlite_schema WHERE name='schema_version'"+ ).fetchone()[0]+ finally:+ connection.close()+ assert (classified.predecessor, adopted.exit_code, revision, legacy_marker) == (+ "runtime-0010",+ AdoptionExit.OK,+ "0011",+ 0,+ ), "runtime generation ten adoption changed"++@pytest.mark.asyncioasync def test_unknown_sqlite_catalog_is_rejected_without_mutation(tmp_path: Path,@@ -151,7 +188,7 @@ async def test_sqlite_adoption_uses_backup_and_normal_history(assert backup.is_file()assert _catalog_digest(backup) == beforemanaged = verify_managed_connection_from_path(path)- assert managed.diagnostic == "ARES-M2B-ALREADY-MANAGED:0009"+ assert managed.diagnostic == "ARES-M2B-ALREADY-MANAGED:0011"connection = sqlite3.connect(path)try:revision = connection.execute(@@ -159,7 +196,7 @@ async def test_sqlite_adoption_uses_backup_and_normal_history().fetchone()[0]finally:connection.close()- assert revision == "0009"+ assert revision == "0011"@pytest.mark.asyncio@@ -178,7 +215,7 @@ async def test_sqlite_adoption_rerun_is_verified_noop(tmp_path: Path) -> None:second_backup.exists(),) == (AdoptionExit.OK,- "ARES-M2B-ALREADY-MANAGED:0009",+ "ARES-M2B-ALREADY-MANAGED:0011",True,False,)@@ -278,7 +315,7 @@ async def test_startup_rejects_unversioned_without_alembic_side_effect(@pytest.mark.asyncio-async def test_startup_rejects_noncanonical_fake_0009(tmp_path: Path) -> None:+async def test_startup_requires_migration_for_managed_0009(tmp_path: Path) -> None:path = tmp_path / "runtime.db"await _create_runtime(path)connection = sqlite3.connect(path)@@ -294,7 +331,7 @@ async def test_startup_rejects_noncanonical_fake_0009(tmp_path: Path) -> None:connection.close()before = _catalog_digest(path)database = AresDatabase(path)- with pytest.raises(RuntimeError, match="Invalid managed"):+ with pytest.raises(RuntimeError, match="migration is required"):await database.connect()assert _catalog_digest(path) == beforediff --git a/tests/unit/test_websocket_ticket_migration.py b/tests/unit/test_websocket_ticket_migration.pyindex 4835f48..3a1a48a 100644--- a/tests/unit/test_websocket_ticket_migration.py+++ b/tests/unit/test_websocket_ticket_migration.py@@ -1589,12 +1589,12 @@ async def _runtime_bootstrap(path: Path) -> bool:await database.close()-def test_migration_head_is_real_empty_base_to_0009() -> None:+def test_migration_head_is_real_empty_base_to_0011() -> None:with _temporary_database("empty-head") as path:initially_empty = _application_tables(path) == ()initial_revision_absent = _version(path) is None_upgrade(path, "head")- revision_is_current = _version(path) == "0009"+ revision_is_current = _version(path) == "0011"exact_contract = _ticket_contract(path) == _EXPECTED_TICKET_CONTRACTenforcement_holds = _exercise_ticket_enforcement(path)@@ -1602,15 +1602,15 @@ def test_migration_head_is_real_empty_base_to_0009() -> None:initially_empty and initial_revision_absent,"fresh migration database was not empty",)- _require_fixed(SCHEMA_VERSION == 8, "SQLite schema version is not eight")- _require_fixed(revision_is_current, "Alembic head is not revision 0009")+ _require_fixed(SCHEMA_VERSION == 9, "SQLite schema version is not nine")+ _require_fixed(revision_is_current, "Alembic head is not revision 0011")_require_fixed(exact_contract,- "fresh revision 0009 ticket fingerprint diverged",+ "fresh revision 0011 ticket fingerprint diverged",)_require_fixed(enforcement_holds,- "fresh revision 0009 enforcement diverged",+ "fresh revision 0011 enforcement diverged",)@@ -1724,7 +1724,7 @@ def test_runtime_bootstrap_and_alembic_have_exact_ticket_parity() -> None:migration_contract = _ticket_contract(migration_path)runtime_contract = _ticket_contract(runtime_path)both_exact = (- _version(migration_path) == "0009"+ _version(migration_path) == "0011"and migration_contract == _EXPECTED_TICKET_CONTRACTand runtime_contract == _EXPECTED_TICKET_CONTRACTand migration_contract == runtime_contractdiff --git a/tests/unit/test_worker_execution_admission.py b/tests/unit/test_worker_execution_admission.pynew file mode 100644index 0000000..394ac04--- /dev/null+++ b/tests/unit/test_worker_execution_admission.py@@ -0,0 +1,111 @@+"""C-LIVE worker boundary: serialized stdin is never dispatch authority."""++from __future__ import annotations++import pickle++import pytest++from ares.core.execution_admission import _mint_test_dispatch_context+from ares.worker._subprocess_worker import (+ _PRIVATE_WORKER_CONSUMER,+ _run_module_in_process,+ run_module,+)+++CAMPAIGN_ID = "11111111-1111-4111-8111-111111111111"+MODULE_ID = "test.worker_probe"+++async def _assert_serialized_worker_payload_is_always_rejected() -> None:+ result = await run_module(+ {+ "campaign_id": CAMPAIGN_ID,+ "module_id": MODULE_ID,+ "params": {"target": "127.0.0.1"},+ "capabilities": ["cap_unsafe"],+ }+ )+ assert result == {+ "success": False,+ "error": "subprocess stdin execution requires a non-serializable coordinator capability",+ "code": "EXECUTION_ADMISSION_REQUIRED",+ "findings": [],+ "raw": {},+ }+++def _assert_worker_capability_cannot_be_serialized() -> None:+ context = _mint_test_dispatch_context(+ _PRIVATE_WORKER_CONSUMER,+ CAMPAIGN_ID,+ MODULE_ID,+ )+ with pytest.raises(TypeError, match="not serializable"):+ pickle.dumps(context)+++async def _assert_private_in_process_worker_capability_is_single_use() -> None:+ effects: list[str] = []++ async def executor(payload):+ effects.append(payload["module_id"])+ return {"success": True, "findings": [], "raw": {"ok": True}}++ payload = {"campaign_id": CAMPAIGN_ID, "module_id": MODULE_ID, "params": {}}+ context = _mint_test_dispatch_context(+ _PRIVATE_WORKER_CONSUMER,+ CAMPAIGN_ID,+ MODULE_ID,+ ordinal=1,+ )+ result = await _run_module_in_process(payload, context, executor)+ assert result["success"] is True+ assert effects == [MODULE_ID]++ with pytest.raises(PermissionError, match="already used"):+ await _run_module_in_process(payload, context, executor)+ assert effects == [MODULE_ID]+++async def _assert_private_worker_rejects_cross_module_context_before_effect() -> None:+ effects = 0++ async def executor(payload):+ nonlocal effects+ effects += 1+ return {"success": True}++ context = _mint_test_dispatch_context(+ _PRIVATE_WORKER_CONSUMER,+ CAMPAIGN_ID,+ MODULE_ID,+ ordinal=2,+ )+ with pytest.raises(PermissionError):+ await _run_module_in_process(+ {"campaign_id": CAMPAIGN_ID, "module_id": "test.other", "params": {}},+ context,+ executor,+ )+ assert effects == 0+++ "case",+ [+ "missing-capability",+ "fabricated-serialized-capability",+ "valid-coordinator-capability-single-use",+ ],+)+async def test_subprocess_worker_sealed_admission(case: str) -> None:+ if case == "missing-capability":+ await _assert_serialized_worker_payload_is_always_rejected()+ elif case == "fabricated-serialized-capability":+ _assert_worker_capability_cannot_be_serialized()+ await _assert_private_worker_rejects_cross_module_context_before_effect()+ else:+ await _assert_private_in_process_worker_capability_is_single_use()