You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
1309 lines
62 KiB
Python
1309 lines
62 KiB
Python
"""Durable mutation admission shared by engine workers.
|
|
|
|
Only the small admission record is changed under a database CAS. No database
|
|
transaction remains open during host work. Claims have no lease expiry: an
|
|
absent worker, cancelled request or old timestamp cannot prove that remote work
|
|
has stopped. Uncertain claims require explicit reconciliation.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from contextlib import contextmanager
|
|
from contextvars import ContextVar
|
|
from dataclasses import dataclass, field
|
|
import hashlib
|
|
import json
|
|
import re
|
|
import secrets
|
|
import threading
|
|
import time
|
|
from typing import Any, Mapping
|
|
|
|
|
|
RECORD_KIND = "coordination"
|
|
RECORD_KEY = "admission-v1"
|
|
_IDENTIFIER = re.compile(r"[A-Za-z0-9_.:-]{1,191}\Z")
|
|
_TOKEN = re.compile(r"[A-Za-z0-9_-]{16,128}\Z")
|
|
_KIND = re.compile(r"[a-z][a-z0-9_-]{0,63}\Z")
|
|
_EXPLICIT_VPC_RECONCILE_METADATA = {"explicit_vpc_reconcile": True}
|
|
_RESOLVE_AND_BIND_RECEIPT_KIND = "resolve_and_bind_v1"
|
|
_RESOLVE_FAMILY_AND_BIND_RECEIPT_KIND = "resolve_family_and_bind_v1"
|
|
_UNKNOWN_CODES = frozenset({
|
|
"libvirt_execution_uncertain", "libvirt_execution_blocked",
|
|
"coordination_uncertain", "operation_uncertain",
|
|
})
|
|
_SAFE_EXECUTION_CODES = frozenset({
|
|
"libvirt_execution_timeout", "libvirt_execution_stopped",
|
|
})
|
|
|
|
|
|
class CoordinationError(Exception):
|
|
def __init__(self, error_code: str, status: int = 409):
|
|
messages = {
|
|
"coordination_busy": "资源正由其他任务占用,请稍后查询原操作",
|
|
"coordination_uncertain": "已有执行结果未确认的任务,请先核对原操作",
|
|
"coordination_unavailable": "无法确认持久执行占用,已拒绝新的修改",
|
|
}
|
|
super().__init__(messages.get(error_code, messages["coordination_unavailable"]))
|
|
self.error_code = error_code
|
|
self.status = status
|
|
|
|
|
|
class CoordinationAdmissionRejected(CoordinationError):
|
|
"""A confirmed admission conflict before this claim can dispatch work.
|
|
|
|
The old blocking claim remains authoritative; this exception only proves
|
|
that the rejected execution did not start its own remote mutation.
|
|
"""
|
|
|
|
|
|
class CoordinationClaimRejected(CoordinationAdmissionRejected):
|
|
"""A conflicting claim was observed without committing a new claim."""
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class Claim:
|
|
token: str
|
|
execution_id: str
|
|
owner_id: str
|
|
operation_id: str | None = None
|
|
resources: tuple[str, ...] = ()
|
|
kind: str = "request"
|
|
metadata: dict = field(default_factory=dict, compare=False, repr=False)
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class ExecutionContext:
|
|
coordinator: DurableCoordinator
|
|
claim: Claim
|
|
# Shared by nested claims and copied thread contexts for this execution.
|
|
# A later connection failure cannot erase an earlier session's writes.
|
|
remote_write_started: threading.Event = field(default_factory=threading.Event,
|
|
compare=False, repr=False)
|
|
connection_failure_safe: bool = False
|
|
# Opt in only where every remote mutation passes the RPC write hook.
|
|
# In particular, this is not implied by read-only SSH connection probes.
|
|
tracked_mutations: bool = False
|
|
admission_rejected: threading.Event = field(default_factory=threading.Event,
|
|
compare=False, repr=False)
|
|
execution_unknown: threading.Event = field(default_factory=threading.Event,
|
|
compare=False, repr=False)
|
|
|
|
|
|
_CURRENT_EXECUTION: ContextVar[ExecutionContext | None] = ContextVar(
|
|
"cloud_durable_execution", default=None)
|
|
_default_coordinator: DurableCoordinator | None = None
|
|
_default_lock = threading.Lock()
|
|
|
|
|
|
def _encode(value: Any) -> str:
|
|
return json.dumps(value, ensure_ascii=True, allow_nan=False,
|
|
separators=(",", ":"), sort_keys=True)
|
|
|
|
|
|
def _identity(claim: Claim | Mapping[str, Any]) -> tuple[str, str, str]:
|
|
values = ((claim.token, claim.execution_id, claim.owner_id)
|
|
if isinstance(claim, Claim) else
|
|
(claim.get("token"), claim.get("execution_id"), claim.get("owner_id")))
|
|
if any(not isinstance(value, str) or not _TOKEN.fullmatch(value) for value in values):
|
|
raise ValueError("Invalid coordination claim identity")
|
|
return values
|
|
|
|
|
|
def _resources(values) -> tuple[str, ...]:
|
|
if isinstance(values, (str, bytes)):
|
|
raise ValueError("Coordination resources must be a sequence")
|
|
result = tuple(sorted(set(values)))
|
|
if any(not isinstance(value, str) or not 1 <= len(value) <= 512
|
|
or any(ord(char) < 33 or ord(char) > 126 for char in value)
|
|
for value in result):
|
|
raise ValueError("Invalid coordination resource")
|
|
return result
|
|
|
|
|
|
def _digest(value: Any) -> str:
|
|
return hashlib.sha256(_encode(value).encode("ascii")).hexdigest()
|
|
|
|
|
|
def _claim_envelope(record: Mapping[str, Any]) -> dict[str, Any]:
|
|
"""Return the immutable admission identity used by handoff receipts."""
|
|
return {key: record.get(key) for key in (
|
|
"token", "execution_id", "owner_id", "operation_id", "resources",
|
|
"maintenance", "kind", "metadata",
|
|
)}
|
|
|
|
|
|
class DurableCoordinator:
|
|
def __init__(self, store, *, owner_id: str | None = None, cas_attempts: int = 32,
|
|
max_claims: int = 1024):
|
|
if not all(callable(getattr(store, method, None)) for method in
|
|
("get", "insert", "compare_and_set")):
|
|
raise ValueError("Durable coordination requires atomic database CAS")
|
|
self.store = store
|
|
self.owner_id = owner_id or secrets.token_hex(32)
|
|
if not isinstance(self.owner_id, str) or not _TOKEN.fullmatch(self.owner_id):
|
|
raise ValueError("Invalid coordination owner")
|
|
if isinstance(cas_attempts, bool) or not isinstance(cas_attempts, int) or cas_attempts < 1:
|
|
raise ValueError("Invalid coordination retry bound")
|
|
self.cas_attempts = cas_attempts
|
|
if isinstance(max_claims, bool) or not isinstance(max_claims, int) or max_claims < 1:
|
|
raise ValueError("Invalid coordination capacity")
|
|
self.max_claims = max_claims
|
|
|
|
@staticmethod
|
|
def _decode(raw: str) -> dict:
|
|
try:
|
|
document = json.loads(raw)
|
|
if (not isinstance(document, dict) or document.get("version") != 1
|
|
or isinstance(document.get("version"), bool)
|
|
or isinstance(document.get("revision"), bool)
|
|
or not isinstance(document.get("revision"), int)
|
|
or document["revision"] < 0
|
|
or not isinstance(document.get("claims"), dict)
|
|
or not isinstance(document.get("resolutions", []), list)):
|
|
raise ValueError("Invalid coordination document")
|
|
for token, record in document["claims"].items():
|
|
if (not isinstance(record, dict) or _identity(record)[0] != token
|
|
or record.get("state") not in {"active", "uncertain"}
|
|
or not isinstance(record.get("maintenance"), bool)
|
|
or not isinstance(record.get("kind"), str)
|
|
or not _KIND.fullmatch(record["kind"])
|
|
or not isinstance(record.get("metadata"), dict)
|
|
or record.get("operation_id") is not None and (
|
|
not isinstance(record["operation_id"], str)
|
|
or not _IDENTIFIER.fullmatch(record["operation_id"]))
|
|
or list(_resources(record.get("resources", ()))) != record.get("resources")
|
|
or any(isinstance(record.get(field), bool)
|
|
or not isinstance(record.get(field), int)
|
|
or record[field] < 0
|
|
for field in ("created_at", "updated_at"))):
|
|
raise ValueError("Invalid coordination claim")
|
|
return document
|
|
except (TypeError, ValueError, AttributeError, KeyError):
|
|
raise CoordinationError("coordination_unavailable", 503) from None
|
|
|
|
def _read(self) -> tuple[str, dict]:
|
|
try:
|
|
raw = self.store.get(RECORD_KIND, RECORD_KEY)
|
|
if raw is None:
|
|
empty = _encode({"version": 1, "revision": 0, "claims": {}, "resolutions": []})
|
|
# Insert first so competing CAS transactions lock a real row,
|
|
# rather than racing inserts beneath missing-key gap locks.
|
|
self.store.insert(RECORD_KIND, RECORD_KEY, empty)
|
|
raw = self.store.get(RECORD_KIND, RECORD_KEY)
|
|
if raw is None:
|
|
raise CoordinationError("coordination_unavailable", 503)
|
|
return raw, self._decode(raw)
|
|
except CoordinationError:
|
|
mark_execution_unknown()
|
|
raise
|
|
except Exception:
|
|
mark_execution_unknown()
|
|
raise CoordinationError("coordination_unavailable", 503) from None
|
|
|
|
def _change(self, mutate):
|
|
for _attempt in range(self.cas_attempts):
|
|
raw, document = self._read()
|
|
try:
|
|
changed, result = mutate(document)
|
|
except CoordinationAdmissionRejected:
|
|
mark_admission_rejected()
|
|
raise
|
|
except CoordinationError:
|
|
mark_execution_unknown()
|
|
raise
|
|
if not changed:
|
|
return result
|
|
document["revision"] += 1
|
|
try:
|
|
if self.store.compare_and_set(RECORD_KIND, RECORD_KEY, raw, _encode(document)):
|
|
return result
|
|
except Exception:
|
|
# A lost commit response may still have installed this claim.
|
|
# Do not fall back to an in-memory lock or assume rollback.
|
|
mark_execution_unknown()
|
|
raise CoordinationError("coordination_unavailable", 503) from None
|
|
mark_execution_unknown()
|
|
raise CoordinationError("coordination_unavailable", 503)
|
|
|
|
def claim(self, operation_id: str | None = None, resources=(), maintenance: bool = False,
|
|
execution_id: str | None = None, kind: str = "request", metadata=None) -> Claim:
|
|
resources = _resources(resources)
|
|
if operation_id is not None and (
|
|
not isinstance(operation_id, str) or not _IDENTIFIER.fullmatch(operation_id)):
|
|
raise ValueError("Invalid coordination operation")
|
|
execution_id = execution_id or secrets.token_hex(32)
|
|
if (not isinstance(execution_id, str) or not _TOKEN.fullmatch(execution_id)
|
|
or execution_id in {operation_id, self.owner_id}):
|
|
raise ValueError("Execution identity must be an independent random token")
|
|
if not isinstance(maintenance, bool) or not isinstance(kind, str) or not _KIND.fullmatch(kind):
|
|
raise ValueError("Invalid coordination claim kind")
|
|
if metadata is None:
|
|
metadata = {}
|
|
if not isinstance(metadata, Mapping):
|
|
raise ValueError("Invalid coordination metadata")
|
|
metadata = json.loads(_encode(dict(metadata)))
|
|
if len(_encode(metadata)) > 8192:
|
|
raise ValueError("Coordination metadata is too large")
|
|
token = secrets.token_hex(32)
|
|
now = int(time.time())
|
|
record = {
|
|
"token": token, "execution_id": execution_id, "owner_id": self.owner_id,
|
|
"operation_id": operation_id, "resources": list(resources),
|
|
"maintenance": maintenance, "kind": kind, "metadata": metadata,
|
|
"state": "active", "created_at": now, "updated_at": now,
|
|
}
|
|
claim = Claim(token, execution_id, self.owner_id, operation_id, resources,
|
|
kind, json.loads(_encode(metadata)))
|
|
|
|
def mutate(document):
|
|
if len(document["claims"]) >= self.max_claims:
|
|
raise CoordinationClaimRejected("coordination_busy", 409)
|
|
conflicts = []
|
|
for existing in document["claims"].values():
|
|
conflict = (
|
|
maintenance or existing["maintenance"]
|
|
or (existing["state"] == "uncertain"
|
|
or existing["execution_id"] != execution_id)
|
|
and (operation_id is not None and existing["operation_id"] == operation_id
|
|
or bool(set(resources).intersection(existing["resources"])))
|
|
)
|
|
if conflict:
|
|
conflicts.append(existing)
|
|
if conflicts:
|
|
unknown = any(existing["state"] == "uncertain" for existing in conflicts)
|
|
raise CoordinationClaimRejected(
|
|
"coordination_uncertain" if unknown else "coordination_busy",
|
|
503 if unknown else 409)
|
|
document["claims"][token] = record
|
|
return True, claim
|
|
|
|
return self._change(mutate)
|
|
|
|
@staticmethod
|
|
def _owned(document, claim):
|
|
token, execution_id, owner_id = _identity(claim)
|
|
current = document["claims"].get(token)
|
|
if current is None or (current["execution_id"], current["owner_id"]) != (execution_id, owner_id):
|
|
return None
|
|
return current
|
|
|
|
def release(self, claim: Claim | Mapping[str, Any]) -> bool:
|
|
def mutate(document):
|
|
current = self._owned(document, claim)
|
|
if current is None or current["state"] != "active":
|
|
return False, False
|
|
del document["claims"][current["token"]]
|
|
return True, True
|
|
return self._change(mutate)
|
|
|
|
def release_exact(self, claim: Mapping[str, Any]) -> bool:
|
|
"""Release only an unchanged active durable snapshot."""
|
|
if not isinstance(claim, Mapping):
|
|
raise ValueError("Exact coordination release snapshot is required")
|
|
expected = dict(claim)
|
|
_identity(expected)
|
|
|
|
def mutate(document):
|
|
current = document["claims"].get(expected["token"])
|
|
if current is None or current != expected or current["state"] != "active":
|
|
return False, False
|
|
del document["claims"][current["token"]]
|
|
return True, True
|
|
|
|
return self._change(mutate)
|
|
|
|
def retain(self, claim: Claim | Mapping[str, Any], reason_code: str = "operation_uncertain") -> bool:
|
|
if not isinstance(reason_code, str) or not _IDENTIFIER.fullmatch(reason_code):
|
|
raise ValueError("Invalid coordination reason code")
|
|
|
|
def mutate(document):
|
|
current = self._owned(document, claim)
|
|
if current is None:
|
|
return False, False
|
|
if current["state"] == "uncertain":
|
|
return False, True
|
|
current.update(state="uncertain", reason_code=reason_code, updated_at=int(time.time()))
|
|
return True, True
|
|
return self._change(mutate)
|
|
|
|
def refresh(self, claim: Claim | Mapping[str, Any]) -> bool:
|
|
def mutate(document):
|
|
current = self._owned(document, claim)
|
|
if current is None:
|
|
return False, False
|
|
now = int(time.time())
|
|
if current["updated_at"] == now:
|
|
return False, True
|
|
current["updated_at"] = now
|
|
return True, True
|
|
return self._change(mutate)
|
|
|
|
def update_metadata(self, claim: Claim | Mapping[str, Any], metadata: Mapping) -> bool:
|
|
if not isinstance(metadata, Mapping):
|
|
raise ValueError("Invalid coordination metadata")
|
|
additions = json.loads(_encode(dict(metadata)))
|
|
|
|
def mutate(document):
|
|
current = self._owned(document, claim)
|
|
if current is None:
|
|
return False, False
|
|
updated = {**current["metadata"], **additions}
|
|
if len(_encode(updated)) > 8192:
|
|
raise ValueError("Coordination metadata is too large")
|
|
current.update(metadata=updated, updated_at=int(time.time()))
|
|
return True, True
|
|
return self._change(mutate)
|
|
|
|
def add_resources(self, claim: Claim | Mapping[str, Any], resources) -> Claim:
|
|
additions = _resources(resources)
|
|
|
|
def mutate(document):
|
|
current = self._owned(document, claim)
|
|
if current is None:
|
|
raise CoordinationError("coordination_unavailable", 503)
|
|
if current["state"] != "active":
|
|
raise CoordinationError("coordination_uncertain", 503)
|
|
combined = _resources((*current["resources"], *additions))
|
|
for existing in document["claims"].values():
|
|
if existing["token"] == current["token"]:
|
|
continue
|
|
if existing["maintenance"] or (
|
|
(existing["state"] == "uncertain"
|
|
or existing["execution_id"] != current["execution_id"])
|
|
and bool(set(combined).intersection(existing["resources"]))
|
|
):
|
|
unknown = existing["state"] == "uncertain"
|
|
raise CoordinationClaimRejected(
|
|
"coordination_uncertain" if unknown else "coordination_busy",
|
|
503 if unknown else 409)
|
|
changed = list(combined) != current["resources"]
|
|
current.update(resources=list(combined), updated_at=int(time.time()))
|
|
return changed, Claim(current["token"], current["execution_id"],
|
|
current["owner_id"], current["operation_id"],
|
|
combined, current["kind"],
|
|
json.loads(_encode(current["metadata"])))
|
|
return self._change(mutate)
|
|
|
|
def snapshot(self) -> dict[str, dict]:
|
|
return self._read()[1]["claims"]
|
|
|
|
def bind_operation(self, claim: Claim, operation_id: str,
|
|
metadata: Mapping[str, Any]) -> Claim:
|
|
"""Bind a validated operation envelope before its first resource claim.
|
|
|
|
Identity, ownership and execution evidence stay unchanged. An existing
|
|
binding is immutable, and another execution's same operation remains
|
|
fenced even when its resource set is empty.
|
|
"""
|
|
if not isinstance(operation_id, str) or not _IDENTIFIER.fullmatch(operation_id):
|
|
raise ValueError("Invalid coordination operation")
|
|
if not isinstance(metadata, Mapping):
|
|
raise ValueError("Invalid coordination metadata")
|
|
additions = json.loads(_encode(dict(metadata)))
|
|
|
|
def mutate(document):
|
|
current = self._owned(document, claim)
|
|
if current is None:
|
|
raise CoordinationError("coordination_unavailable", 503)
|
|
if current["state"] != "active":
|
|
raise CoordinationClaimRejected("coordination_uncertain", 503)
|
|
if (current["operation_id"] not in {None, operation_id}
|
|
or any(key in current["metadata"] and current["metadata"][key] != value
|
|
for key, value in additions.items())):
|
|
raise CoordinationClaimRejected("coordination_busy", 409)
|
|
for existing in document["claims"].values():
|
|
if existing["token"] == current["token"]:
|
|
continue
|
|
if existing["maintenance"] or (
|
|
(existing["state"] == "uncertain"
|
|
or existing["execution_id"] != current["execution_id"])
|
|
and existing["operation_id"] == operation_id
|
|
):
|
|
unknown = existing["state"] == "uncertain"
|
|
raise CoordinationClaimRejected(
|
|
"coordination_uncertain" if unknown else "coordination_busy",
|
|
503 if unknown else 409)
|
|
combined = {**current["metadata"], **additions}
|
|
if len(_encode(combined)) > 8192:
|
|
raise ValueError("Coordination metadata is too large")
|
|
changed = current["operation_id"] != operation_id or combined != current["metadata"]
|
|
current.update(operation_id=operation_id, metadata=combined,
|
|
updated_at=int(time.time()))
|
|
return changed, Claim(current["token"], current["execution_id"], current["owner_id"],
|
|
operation_id, tuple(current["resources"]), current["kind"],
|
|
json.loads(_encode(combined)))
|
|
|
|
return self._change(mutate)
|
|
|
|
def bind_explicit_operation(self, claim: Claim | Mapping[str, Any],
|
|
operation_id: str,
|
|
metadata: Mapping[str, Any]) -> Claim:
|
|
"""Consume the one-shot VPC reconcile capability while binding.
|
|
|
|
This stricter sibling of :meth:`bind_operation` is used only by an
|
|
explicitly authorized VPC request. The marker is replaced by the
|
|
signed target identity in the same CAS, so nested resource claims
|
|
cannot inherit a capability that was meant only for the HTTP root.
|
|
"""
|
|
replacement_identity = _identity(claim)
|
|
if not isinstance(operation_id, str) or not _IDENTIFIER.fullmatch(operation_id):
|
|
raise ValueError("Invalid coordination operation")
|
|
if not isinstance(metadata, Mapping):
|
|
raise ValueError("Invalid coordination metadata")
|
|
target_metadata = json.loads(_encode(dict(metadata)))
|
|
if len(_encode(target_metadata)) > 8192:
|
|
raise ValueError("Coordination metadata is too large")
|
|
|
|
def claim_value(name, default=None):
|
|
if isinstance(claim, Mapping):
|
|
return claim.get(name, default)
|
|
return getattr(claim, name, default)
|
|
|
|
if (replacement_identity[2] != self.owner_id
|
|
or claim_value("operation_id") is not None
|
|
or tuple(claim_value("resources", ())) != ()
|
|
or claim_value("kind") != "request"
|
|
or claim_value("metadata", {}) != _EXPLICIT_VPC_RECONCILE_METADATA):
|
|
raise ValueError("Invalid explicit reconciliation root")
|
|
|
|
def mutate(document):
|
|
current = self._owned(document, claim)
|
|
if (current is None
|
|
or current["state"] != "active"
|
|
or current["maintenance"]
|
|
or current["operation_id"] is not None
|
|
or current["resources"] != []
|
|
or current["kind"] != "request"
|
|
or current["metadata"] != _EXPLICIT_VPC_RECONCILE_METADATA):
|
|
raise CoordinationClaimRejected("coordination_uncertain", 503)
|
|
conflicts = [
|
|
existing for existing in document["claims"].values()
|
|
if existing["token"] != current["token"]
|
|
and (existing["execution_id"] == current["execution_id"]
|
|
or existing["operation_id"] == operation_id)
|
|
]
|
|
if conflicts:
|
|
unknown = any(existing["state"] == "uncertain"
|
|
for existing in conflicts)
|
|
raise CoordinationClaimRejected(
|
|
"coordination_uncertain" if unknown else "coordination_busy",
|
|
503 if unknown else 409)
|
|
current.update(
|
|
operation_id=operation_id,
|
|
metadata=json.loads(_encode(target_metadata)),
|
|
updated_at=int(time.time()),
|
|
)
|
|
return True, Claim(
|
|
current["token"], current["execution_id"], current["owner_id"],
|
|
operation_id, (), "request",
|
|
json.loads(_encode(target_metadata)))
|
|
|
|
return self._change(mutate)
|
|
|
|
def operation_claim(self, operation_id: str) -> dict | None:
|
|
matches = [claim for claim in self.snapshot().values()
|
|
if claim["operation_id"] == operation_id]
|
|
return next((claim for claim in matches if claim["state"] == "uncertain"),
|
|
matches[0] if matches else None)
|
|
|
|
def has_work(self) -> bool:
|
|
return bool(self.snapshot())
|
|
|
|
def resolve(self, claim: Claim | Mapping[str, Any], evidence: str) -> bool:
|
|
"""Explicit operator reconciliation; never call on expiry or restart.
|
|
|
|
Evidence should reference the recorded host verification, not contain
|
|
credentials or raw host output. Keep a bounded reconciliation receipt
|
|
in the same atomic update that removes the claim.
|
|
"""
|
|
if not isinstance(evidence, str) or not evidence.strip() or len(evidence) > 1024:
|
|
raise ValueError("Explicit reconciliation evidence is required")
|
|
|
|
def mutate(document):
|
|
current = self._owned(document, claim)
|
|
if current is None:
|
|
return False, False
|
|
receipts = document.setdefault("resolutions", [])
|
|
receipts.append({
|
|
"token": current["token"], "operation_id": current["operation_id"],
|
|
"resolved_by": self.owner_id, "resolved_at": int(time.time()),
|
|
"evidence": evidence.strip(),
|
|
})
|
|
document["resolutions"] = receipts[-100:]
|
|
del document["claims"][current["token"]]
|
|
return True, True
|
|
return self._change(mutate)
|
|
|
|
def resolve_and_claim(self, claim: Mapping[str, Any], evidence: str, *,
|
|
execution_id: str) -> Claim:
|
|
"""Explicitly replace one proven stopped owner without an admission gap.
|
|
|
|
The supplied snapshot must still match in full. The replacement keeps
|
|
its exact resource fence while the caller persists the old operation's
|
|
terminal receipt and transfers ownership to a new background job.
|
|
"""
|
|
if not isinstance(evidence, str) or not evidence.strip() or len(evidence) > 1024:
|
|
raise ValueError("Explicit reconciliation evidence is required")
|
|
_identity(claim)
|
|
if (not isinstance(execution_id, str) or not _TOKEN.fullmatch(execution_id)
|
|
or execution_id in {claim.get("operation_id"), self.owner_id,
|
|
claim.get("execution_id")}):
|
|
raise ValueError("Reconciliation requires a new execution identity")
|
|
token = secrets.token_hex(32)
|
|
|
|
def mutate(document):
|
|
current = self._owned(document, claim)
|
|
if (current is None or current != dict(claim)
|
|
or current["state"] != "uncertain"):
|
|
raise CoordinationClaimRejected("coordination_uncertain", 503)
|
|
for existing in document["claims"].values():
|
|
if existing["token"] == current["token"]:
|
|
continue
|
|
if existing["maintenance"] or (
|
|
(existing["state"] == "uncertain"
|
|
or existing["execution_id"] != execution_id)
|
|
and (existing["operation_id"] == current["operation_id"]
|
|
or bool(set(current["resources"]).intersection(existing["resources"])))
|
|
):
|
|
unknown = existing["state"] == "uncertain"
|
|
raise CoordinationClaimRejected(
|
|
"coordination_uncertain" if unknown else "coordination_busy",
|
|
503 if unknown else 409)
|
|
now = int(time.time())
|
|
replacement = {
|
|
**current, "token": token, "execution_id": execution_id,
|
|
"owner_id": self.owner_id, "state": "active", "kind": "resource",
|
|
"metadata": {"reconciled_operation_id": current["operation_id"]},
|
|
"created_at": now, "updated_at": now,
|
|
}
|
|
replacement.pop("reason_code", None)
|
|
receipts = document.setdefault("resolutions", [])
|
|
receipts.append({
|
|
"token": current["token"], "operation_id": current["operation_id"],
|
|
"resolved_by": self.owner_id, "resolved_at": now,
|
|
"evidence": evidence.strip(), "replacement_token": token,
|
|
})
|
|
document["resolutions"] = receipts[-100:]
|
|
del document["claims"][current["token"]]
|
|
document["claims"][token] = replacement
|
|
return True, Claim(token, execution_id, self.owner_id,
|
|
replacement["operation_id"], tuple(replacement["resources"]),
|
|
"resource", dict(replacement["metadata"]))
|
|
|
|
return self._change(mutate)
|
|
|
|
def resolve_and_bind(self, claim: Mapping[str, Any], replacement: Claim | Mapping[str, Any],
|
|
evidence: str, *, operation_id: str,
|
|
metadata: Mapping[str, Any]) -> Claim:
|
|
"""Atomically retire an exact uncertain owner into an active request.
|
|
|
|
The replacement must already be an active request owned by this
|
|
coordinator. Its token is preserved, so an HTTP request can take over
|
|
an explicitly reconciled operation without a release/admission gap.
|
|
"""
|
|
if not isinstance(evidence, str) or not evidence.strip() or len(evidence) > 1024:
|
|
raise ValueError("Explicit reconciliation evidence is required")
|
|
_identity(claim)
|
|
replacement_identity = _identity(replacement)
|
|
if not isinstance(operation_id, str) or not _IDENTIFIER.fullmatch(operation_id):
|
|
raise ValueError("Invalid coordination operation")
|
|
if not isinstance(metadata, Mapping):
|
|
raise ValueError("Invalid coordination metadata")
|
|
target_metadata = json.loads(_encode(dict(metadata)))
|
|
if len(_encode(target_metadata)) > 8192:
|
|
raise ValueError("Coordination metadata is too large")
|
|
source_resources = _resources(claim.get("resources", ()))
|
|
if list(source_resources) != claim.get("resources"):
|
|
raise ValueError("Invalid retained reconciliation resources")
|
|
|
|
def replacement_value(name, default=None):
|
|
if isinstance(replacement, Mapping):
|
|
return replacement.get(name, default)
|
|
return getattr(replacement, name, default)
|
|
|
|
if (replacement_identity[2] != self.owner_id
|
|
or replacement_value("operation_id") is not None
|
|
or tuple(replacement_value("resources", ())) != ()
|
|
or replacement_value("kind") != "request"
|
|
or replacement_value("metadata", {})
|
|
!= _EXPLICIT_VPC_RECONCILE_METADATA):
|
|
raise ValueError("Invalid explicit reconciliation root")
|
|
|
|
def mutate(document):
|
|
original = self._owned(document, claim)
|
|
current = document["claims"].get(replacement_identity[0])
|
|
if (original is None or original != dict(claim)
|
|
or original["state"] != "uncertain"
|
|
or original["operation_id"] != operation_id
|
|
or original["maintenance"]
|
|
or original["kind"] not in {"background", "request"}
|
|
or original["metadata"] != target_metadata
|
|
or current is None
|
|
or (current["execution_id"], current["owner_id"])
|
|
!= replacement_identity[1:]
|
|
or current["owner_id"] != self.owner_id
|
|
or current["token"] == original["token"]
|
|
or current["state"] != "active"
|
|
or current["maintenance"]
|
|
or current["kind"] != "request"
|
|
or current["operation_id"] is not None
|
|
or current["resources"] != []
|
|
or current["metadata"]
|
|
!= _EXPLICIT_VPC_RECONCILE_METADATA):
|
|
raise CoordinationClaimRejected("coordination_uncertain", 503)
|
|
conflicts = [
|
|
existing for existing in document["claims"].values()
|
|
if existing["token"] not in {original["token"], current["token"]}
|
|
and (existing["maintenance"]
|
|
or existing["execution_id"] in {
|
|
original["execution_id"], current["execution_id"]}
|
|
or existing["operation_id"] == operation_id
|
|
or bool(set(source_resources).intersection(
|
|
existing["resources"])))
|
|
]
|
|
if conflicts:
|
|
unknown = any(existing["state"] == "uncertain"
|
|
for existing in conflicts)
|
|
raise CoordinationClaimRejected(
|
|
"coordination_uncertain" if unknown else "coordination_busy",
|
|
503 if unknown else 409)
|
|
now = int(time.time())
|
|
current.update(
|
|
operation_id=operation_id, resources=list(source_resources),
|
|
metadata=json.loads(_encode(target_metadata)), updated_at=now)
|
|
receipt = {
|
|
"kind": _RESOLVE_AND_BIND_RECEIPT_KIND,
|
|
"token": original["token"],
|
|
"operation_id": operation_id,
|
|
"resolved_by": self.owner_id,
|
|
"resolved_at": now,
|
|
"evidence": evidence.strip(),
|
|
"source_claim_sha256": _digest(original),
|
|
"replacement_token": current["token"],
|
|
"replacement_identity_sha256": _digest(
|
|
_claim_envelope(current)),
|
|
}
|
|
receipts = document.setdefault("resolutions", [])
|
|
receipts.append(receipt)
|
|
document["resolutions"] = receipts[-100:]
|
|
del document["claims"][original["token"]]
|
|
return True, Claim(
|
|
current["token"], current["execution_id"], current["owner_id"],
|
|
operation_id, source_resources, "request",
|
|
json.loads(_encode(target_metadata)))
|
|
|
|
return self._change(mutate)
|
|
|
|
@staticmethod
|
|
def _reconciliation_family(
|
|
claims, *, operation_id: str,
|
|
metadata: Mapping[str, Any]) -> tuple[dict[str, Any], ...]:
|
|
"""Validate one exact retained execution family.
|
|
|
|
A family contains one request/background root plus only resource
|
|
children created beneath that root. A root may already carry the
|
|
aggregate resource fence transferred by an earlier handoff. Every row
|
|
must carry the same immutable VPC target and already be uncertain.
|
|
Callers must still prove from durable host readback that the next pass
|
|
is observation-only before using this family handoff.
|
|
"""
|
|
if isinstance(claims, (str, bytes, Mapping)):
|
|
raise ValueError("Reconciliation family must be a sequence")
|
|
target_metadata = json.loads(_encode(dict(metadata)))
|
|
rows = tuple(dict(claim) for claim in claims)
|
|
if not rows:
|
|
raise ValueError("Reconciliation family is required")
|
|
for row in rows:
|
|
_identity(row)
|
|
tokens = [row["token"] for row in rows]
|
|
if len(tokens) != len(set(tokens)):
|
|
raise ValueError("Reconciliation family contains duplicate claims")
|
|
execution_ids = {row.get("execution_id") for row in rows}
|
|
owner_ids = {row.get("owner_id") for row in rows}
|
|
if len(execution_ids) != 1 or len(owner_ids) != 1:
|
|
raise ValueError("Reconciliation family identity is inconsistent")
|
|
roots = [
|
|
row for row in rows
|
|
if row.get("kind") in {"background", "request"}
|
|
]
|
|
if (len(roots) != 1
|
|
or any(row.get("state") != "uncertain"
|
|
or row.get("operation_id") != operation_id
|
|
or row.get("maintenance") is not False
|
|
or row.get("metadata") != target_metadata
|
|
or not isinstance(row.get("resources"), list)
|
|
for row in rows)
|
|
or any(row is not roots[0]
|
|
and (row.get("kind") != "resource"
|
|
or not isinstance(row.get("resources"), list)
|
|
or not row["resources"])
|
|
for row in rows)):
|
|
raise ValueError("Invalid retained reconciliation family")
|
|
return tuple(sorted(rows, key=lambda row: row["token"]))
|
|
|
|
def resolve_family_and_bind(
|
|
self, claims, replacement: Claim | Mapping[str, Any],
|
|
evidence: str, *, operation_id: str,
|
|
metadata: Mapping[str, Any]) -> Claim:
|
|
"""Atomically retire an exact uncertain execution family.
|
|
|
|
This method does not itself authorize a retry. The VPC coordinator
|
|
calls it only after durable same-target evidence proves that the
|
|
immediate host pass can perform read-only observation. Exact family
|
|
matching prevents a partial or foreign claim set from being erased.
|
|
"""
|
|
if not isinstance(evidence, str) or not evidence.strip() or len(evidence) > 1024:
|
|
raise ValueError("Explicit reconciliation evidence is required")
|
|
if not isinstance(operation_id, str) or not _IDENTIFIER.fullmatch(operation_id):
|
|
raise ValueError("Invalid coordination operation")
|
|
if not isinstance(metadata, Mapping):
|
|
raise ValueError("Invalid coordination metadata")
|
|
target_metadata = json.loads(_encode(dict(metadata)))
|
|
if len(_encode(target_metadata)) > 8192:
|
|
raise ValueError("Coordination metadata is too large")
|
|
family = self._reconciliation_family(
|
|
claims, operation_id=operation_id, metadata=target_metadata)
|
|
replacement_identity = _identity(replacement)
|
|
|
|
def replacement_value(name, default=None):
|
|
if isinstance(replacement, Mapping):
|
|
return replacement.get(name, default)
|
|
return getattr(replacement, name, default)
|
|
|
|
if (replacement_identity[2] != self.owner_id
|
|
or replacement_value("operation_id") is not None
|
|
or tuple(replacement_value("resources", ())) != ()
|
|
or replacement_value("kind") != "request"
|
|
or replacement_value("metadata", {})
|
|
!= _EXPLICIT_VPC_RECONCILE_METADATA):
|
|
raise ValueError("Invalid explicit reconciliation root")
|
|
|
|
family_tokens = {row["token"] for row in family}
|
|
source_execution_id = family[0]["execution_id"]
|
|
source_family_sha256 = _digest(list(family))
|
|
family_resources = _resources(
|
|
resource
|
|
for row in family
|
|
for resource in row["resources"]
|
|
)
|
|
root = next(row for row in family
|
|
if row["kind"] in {"background", "request"})
|
|
|
|
def mutate(document):
|
|
current = document["claims"].get(replacement_identity[0])
|
|
if (current is None
|
|
or (current["execution_id"], current["owner_id"])
|
|
!= replacement_identity[1:]
|
|
or current["owner_id"] != self.owner_id
|
|
or current["state"] != "active"
|
|
or current["maintenance"]
|
|
or current["kind"] != "request"
|
|
or current["operation_id"] is not None
|
|
or current["resources"] != []
|
|
or current["metadata"]
|
|
!= _EXPLICIT_VPC_RECONCILE_METADATA):
|
|
raise CoordinationClaimRejected("coordination_uncertain", 503)
|
|
if any(document["claims"].get(row["token"]) != row
|
|
for row in family):
|
|
raise CoordinationClaimRejected("coordination_uncertain", 503)
|
|
conflicts = [
|
|
existing for existing in document["claims"].values()
|
|
if existing["token"] not in family_tokens | {current["token"]}
|
|
and (existing["maintenance"]
|
|
or existing["execution_id"] in {
|
|
source_execution_id, current["execution_id"]}
|
|
or existing["operation_id"] == operation_id
|
|
or bool(set(family_resources).intersection(
|
|
existing["resources"])))
|
|
]
|
|
if conflicts:
|
|
unknown = any(existing["state"] == "uncertain"
|
|
for existing in conflicts)
|
|
raise CoordinationClaimRejected(
|
|
"coordination_uncertain" if unknown else "coordination_busy",
|
|
503 if unknown else 409)
|
|
now = int(time.time())
|
|
current.update(
|
|
operation_id=operation_id, resources=list(family_resources),
|
|
metadata=json.loads(_encode(target_metadata)), updated_at=now)
|
|
receipt = {
|
|
"kind": _RESOLVE_FAMILY_AND_BIND_RECEIPT_KIND,
|
|
"token": root["token"],
|
|
"operation_id": operation_id,
|
|
"resolved_by": self.owner_id,
|
|
"resolved_at": now,
|
|
"evidence": evidence.strip(),
|
|
"source_execution_id": source_execution_id,
|
|
"source_family_size": len(family),
|
|
"source_family_sha256": source_family_sha256,
|
|
"replacement_token": current["token"],
|
|
"replacement_identity_sha256": _digest(
|
|
_claim_envelope(current)),
|
|
}
|
|
receipts = document.setdefault("resolutions", [])
|
|
receipts.append(receipt)
|
|
document["resolutions"] = receipts[-100:]
|
|
for token in family_tokens:
|
|
del document["claims"][token]
|
|
return True, Claim(
|
|
current["token"], current["execution_id"], current["owner_id"],
|
|
operation_id, family_resources, "request",
|
|
json.loads(_encode(target_metadata)))
|
|
|
|
return self._change(mutate)
|
|
|
|
def classify_resolve_family_and_bind(
|
|
self, claims, replacement: Claim | Mapping[str, Any],
|
|
evidence: str, *, operation_id: str,
|
|
metadata: Mapping[str, Any]) -> tuple[str, dict[str, Any] | None]:
|
|
"""Classify a lost exact-family handoff response."""
|
|
if not isinstance(evidence, str) or not evidence.strip() or len(evidence) > 1024:
|
|
raise ValueError("Explicit reconciliation evidence is required")
|
|
if not isinstance(operation_id, str) or not _IDENTIFIER.fullmatch(operation_id):
|
|
raise ValueError("Invalid coordination operation")
|
|
if not isinstance(metadata, Mapping):
|
|
raise ValueError("Invalid coordination metadata")
|
|
target_metadata = json.loads(_encode(dict(metadata)))
|
|
if len(_encode(target_metadata)) > 8192:
|
|
raise ValueError("Coordination metadata is too large")
|
|
family = self._reconciliation_family(
|
|
claims, operation_id=operation_id, metadata=target_metadata)
|
|
replacement_identity = _identity(replacement)
|
|
family_tokens = {row["token"] for row in family}
|
|
source_execution_id = family[0]["execution_id"]
|
|
source_family_sha256 = _digest(list(family))
|
|
family_resources = _resources(
|
|
resource
|
|
for row in family
|
|
for resource in row["resources"]
|
|
)
|
|
root = next(row for row in family
|
|
if row["kind"] in {"background", "request"})
|
|
_raw, document = self._read()
|
|
current = document["claims"].get(replacement_identity[0])
|
|
source_rows = {
|
|
token: document["claims"].get(token) for token in family_tokens}
|
|
anonymous = bool(
|
|
current is not None
|
|
and (current["execution_id"], current["owner_id"])
|
|
== replacement_identity[1:]
|
|
and current["state"] == "active"
|
|
and current["maintenance"] is False
|
|
and current["operation_id"] is None
|
|
and current["resources"] == []
|
|
and current["kind"] == "request"
|
|
and current["metadata"] == _EXPLICIT_VPC_RECONCILE_METADATA)
|
|
bound = bool(
|
|
current is not None
|
|
and (current["execution_id"], current["owner_id"])
|
|
== replacement_identity[1:]
|
|
and current["state"] in {"active", "uncertain"}
|
|
and current["maintenance"] is False
|
|
and current["operation_id"] == operation_id
|
|
and current["resources"] == list(family_resources)
|
|
and current["kind"] == "request"
|
|
and current["metadata"] == target_metadata)
|
|
other_conflict = any(
|
|
existing["token"] not in family_tokens | {replacement_identity[0]}
|
|
and (existing["maintenance"]
|
|
or existing["execution_id"] in {
|
|
source_execution_id, replacement_identity[1]}
|
|
or existing["operation_id"] == operation_id
|
|
or bool(set(family_resources).intersection(
|
|
existing["resources"])))
|
|
for existing in document["claims"].values())
|
|
expected_receipt = {
|
|
"kind": _RESOLVE_FAMILY_AND_BIND_RECEIPT_KIND,
|
|
"token": root["token"],
|
|
"operation_id": operation_id,
|
|
"resolved_by": self.owner_id,
|
|
"evidence": evidence.strip(),
|
|
"source_execution_id": source_execution_id,
|
|
"source_family_size": len(family),
|
|
"source_family_sha256": source_family_sha256,
|
|
"replacement_token": replacement_identity[0],
|
|
"replacement_identity_sha256": (
|
|
_digest(_claim_envelope(current)) if bound else None),
|
|
}
|
|
|
|
def receipt_matches(receipt) -> bool:
|
|
return bool(
|
|
isinstance(receipt, dict)
|
|
and set(receipt) == {*expected_receipt, "resolved_at"}
|
|
and isinstance(receipt.get("resolved_at"), int)
|
|
and not isinstance(receipt.get("resolved_at"), bool)
|
|
and receipt["resolved_at"] > 0
|
|
and all(receipt.get(key) == value
|
|
for key, value in expected_receipt.items()))
|
|
|
|
related_receipts = [
|
|
receipt for receipt in document.get("resolutions", [])
|
|
if (isinstance(receipt, dict)
|
|
and (receipt.get("source_execution_id") == source_execution_id
|
|
or receipt.get("replacement_token")
|
|
== replacement_identity[0]))
|
|
]
|
|
matching_receipts = [receipt for receipt in related_receipts
|
|
if receipt_matches(receipt)]
|
|
if (all(row is None for row in source_rows.values())
|
|
and bound and not other_conflict
|
|
and len(matching_receipts) == len(related_receipts) == 1):
|
|
return "committed", current
|
|
if (all(source_rows[row["token"]] == row for row in family)
|
|
and anonymous and not other_conflict and not related_receipts):
|
|
return "uncommitted", current
|
|
return "mixed", current
|
|
|
|
def classify_resolve_and_bind(
|
|
self, claim: Mapping[str, Any], replacement: Claim | Mapping[str, Any],
|
|
evidence: str, *, operation_id: str,
|
|
metadata: Mapping[str, Any]) -> tuple[str, dict[str, Any] | None]:
|
|
"""Classify a lost handoff response from one exact durable snapshot.
|
|
|
|
``committed`` requires the source to be gone, the request to carry the
|
|
exact bound VPC identity, and one exact receipt written by the same CAS.
|
|
``uncommitted`` requires both original rows to remain unchanged and no
|
|
matching receipt. Every mixed state is deliberately unclassifiable.
|
|
"""
|
|
if not isinstance(evidence, str) or not evidence.strip() or len(evidence) > 1024:
|
|
raise ValueError("Explicit reconciliation evidence is required")
|
|
_identity(claim)
|
|
replacement_identity = _identity(replacement)
|
|
if not isinstance(operation_id, str) or not _IDENTIFIER.fullmatch(operation_id):
|
|
raise ValueError("Invalid coordination operation")
|
|
if not isinstance(metadata, Mapping):
|
|
raise ValueError("Invalid coordination metadata")
|
|
target_metadata = json.loads(_encode(dict(metadata)))
|
|
if len(_encode(target_metadata)) > 8192:
|
|
raise ValueError("Coordination metadata is too large")
|
|
source_resources = _resources(claim.get("resources", ()))
|
|
if list(source_resources) != claim.get("resources"):
|
|
raise ValueError("Invalid retained reconciliation resources")
|
|
|
|
def replacement_value(name, default=None):
|
|
if isinstance(replacement, Mapping):
|
|
return replacement.get(name, default)
|
|
return getattr(replacement, name, default)
|
|
|
|
if (replacement_identity[2] != self.owner_id
|
|
or replacement_value("operation_id") is not None
|
|
or tuple(replacement_value("resources", ())) != ()
|
|
or replacement_value("kind") != "request"
|
|
or replacement_value("metadata", {})
|
|
!= _EXPLICIT_VPC_RECONCILE_METADATA):
|
|
raise ValueError("Invalid explicit reconciliation root")
|
|
|
|
_raw, document = self._read()
|
|
original = document["claims"].get(claim["token"])
|
|
current = document["claims"].get(replacement_identity[0])
|
|
other_conflict = any(
|
|
existing["token"] not in {claim["token"], replacement_identity[0]}
|
|
and (existing["maintenance"]
|
|
or existing["execution_id"] in {
|
|
claim["execution_id"], replacement_identity[1]}
|
|
or existing["operation_id"] == operation_id
|
|
or bool(set(source_resources).intersection(
|
|
existing["resources"])))
|
|
for existing in document["claims"].values()
|
|
)
|
|
anonymous = bool(
|
|
current is not None
|
|
and (current["execution_id"], current["owner_id"])
|
|
== replacement_identity[1:]
|
|
and current["state"] == "active"
|
|
and current["maintenance"] is False
|
|
and current["operation_id"] is None
|
|
and current["resources"] == []
|
|
and current["kind"] == "request"
|
|
and current["metadata"] == _EXPLICIT_VPC_RECONCILE_METADATA)
|
|
bound = bool(
|
|
current is not None
|
|
and (current["execution_id"], current["owner_id"])
|
|
== replacement_identity[1:]
|
|
and current["state"] in {"active", "uncertain"}
|
|
and current["maintenance"] is False
|
|
and current["operation_id"] == operation_id
|
|
and current["resources"] == list(source_resources)
|
|
and current["kind"] == "request"
|
|
and current["metadata"] == target_metadata)
|
|
expected_receipt = {
|
|
"kind": _RESOLVE_AND_BIND_RECEIPT_KIND,
|
|
"token": claim["token"],
|
|
"operation_id": operation_id,
|
|
"resolved_by": self.owner_id,
|
|
"evidence": evidence.strip(),
|
|
"source_claim_sha256": _digest(dict(claim)),
|
|
"replacement_token": replacement_identity[0],
|
|
"replacement_identity_sha256": (
|
|
_digest(_claim_envelope(current)) if bound else None),
|
|
}
|
|
|
|
def receipt_matches(receipt) -> bool:
|
|
return bool(
|
|
isinstance(receipt, dict)
|
|
and set(receipt) == {*expected_receipt, "resolved_at"}
|
|
and isinstance(receipt.get("resolved_at"), int)
|
|
and not isinstance(receipt.get("resolved_at"), bool)
|
|
and receipt["resolved_at"] > 0
|
|
and all(receipt.get(key) == value
|
|
for key, value in expected_receipt.items()))
|
|
|
|
related_receipts = [
|
|
receipt for receipt in document.get("resolutions", [])
|
|
if (isinstance(receipt, dict)
|
|
and (receipt.get("token") == claim["token"]
|
|
or receipt.get("replacement_token")
|
|
== replacement_identity[0]))
|
|
]
|
|
matching_receipts = [receipt for receipt in related_receipts
|
|
if receipt_matches(receipt)]
|
|
if (original is None and bound and not other_conflict
|
|
and len(matching_receipts) == len(related_receipts) == 1):
|
|
return "committed", current
|
|
if (original == dict(claim) and anonymous and not other_conflict
|
|
and not related_receipts):
|
|
return "uncommitted", current
|
|
return "mixed", current
|
|
|
|
def classify_release(
|
|
self, claim: Mapping[str, Any]) -> tuple[str, dict[str, Any] | None]:
|
|
"""Classify a lost exact release response without weakening identity.
|
|
|
|
This helper intentionally accepts a complete durable snapshot rather
|
|
than a :class:`Claim`: only byte-for-byte survival proves that a failed
|
|
release did not commit. Absence proves the idempotent release result;
|
|
every changed row is mixed and must remain fenced.
|
|
"""
|
|
if not isinstance(claim, Mapping):
|
|
raise ValueError("Exact coordination release snapshot is required")
|
|
expected = dict(claim)
|
|
_identity(expected)
|
|
_raw, document = self._read()
|
|
current = document["claims"].get(expected["token"])
|
|
if current is None:
|
|
return "committed", None
|
|
if current == expected and current.get("state") == "active":
|
|
return "uncommitted", current
|
|
return "mixed", current
|
|
|
|
|
|
def configure_default_coordinator(coordinator: DurableCoordinator | None) -> None:
|
|
global _default_coordinator
|
|
if coordinator is not None and not isinstance(coordinator, DurableCoordinator):
|
|
raise ValueError("Invalid default coordinator")
|
|
with _default_lock:
|
|
_default_coordinator = coordinator
|
|
|
|
|
|
def get_default_coordinator() -> DurableCoordinator | None:
|
|
with _default_lock:
|
|
return _default_coordinator
|
|
|
|
|
|
def current_execution() -> ExecutionContext | None:
|
|
return _CURRENT_EXECUTION.get()
|
|
|
|
|
|
def update_current_claim(claim: Claim) -> None:
|
|
context = current_execution()
|
|
if context is None or _identity(context.claim) != _identity(claim):
|
|
raise ValueError("Only the current execution claim may be updated")
|
|
_CURRENT_EXECUTION.set(ExecutionContext(
|
|
context.coordinator, claim, context.remote_write_started,
|
|
context.connection_failure_safe, context.tracked_mutations,
|
|
context.admission_rejected, context.execution_unknown))
|
|
|
|
|
|
def mark_remote_write_started() -> None:
|
|
"""Record conservative in-process proof before an RPC write is sent."""
|
|
context = current_execution()
|
|
if context is not None:
|
|
context.remote_write_started.set()
|
|
|
|
|
|
def mark_remote_write_confirmed() -> None:
|
|
"""Retire confirmed write evidence at a quiescent mutation boundary.
|
|
|
|
Callers may use this only after the remote write returned a strict receipt
|
|
or equivalent readback and no sibling mutation is still in flight. An
|
|
unknown execution remains sticky and can never be made retryable here.
|
|
"""
|
|
context = current_execution()
|
|
if context is not None and not context.execution_unknown.is_set():
|
|
context.remote_write_started.clear()
|
|
|
|
|
|
def mark_execution_unknown() -> None:
|
|
"""Never allow later no-write evidence to erase an ambiguous execution."""
|
|
context = current_execution()
|
|
if context is not None:
|
|
context.execution_unknown.set()
|
|
|
|
|
|
def mark_admission_rejected() -> None:
|
|
"""Called only by a confirmed local admission boundary before dispatch."""
|
|
context = current_execution()
|
|
if context is not None:
|
|
context.admission_rejected.set()
|
|
|
|
|
|
def execution_failure_before_write(error_code: str | None) -> bool:
|
|
"""Live no-dispatch evidence for explicitly tracked VM execution only.
|
|
|
|
This never reconciles a stored claim. A pending background owner must also
|
|
be checked by callers deciding whether the whole request has completed.
|
|
An error code cannot itself prove that someone else's fence rejected us.
|
|
"""
|
|
context = current_execution()
|
|
if (context is None or not context.tracked_mutations
|
|
or context.remote_write_started.is_set()
|
|
or context.execution_unknown.is_set()
|
|
or error_code == "coordination_unavailable"):
|
|
return False
|
|
if error_code in {"coordination_uncertain", "libvirt_execution_blocked"}:
|
|
return context.admission_rejected.is_set()
|
|
if (error_code in _UNKNOWN_CODES
|
|
or isinstance(error_code, str) and error_code.endswith("_uncertain")):
|
|
return False
|
|
return True
|
|
|
|
|
|
def connection_failure_before_write(error_code: str) -> bool:
|
|
"""Allow only explicitly libvirt-only scopes to use connection evidence.
|
|
|
|
Other workflows can mutate hosts over SSH before their first libvirt call.
|
|
An absent RPC write marker never proves those workflows were side-effect
|
|
free. Persisted unknown claims are not released through this local proof.
|
|
"""
|
|
context = current_execution()
|
|
return bool(error_code == "libvirt_connection_failed"
|
|
and context is not None and context.connection_failure_safe
|
|
and not context.execution_unknown.is_set()
|
|
and not context.remote_write_started.is_set())
|
|
|
|
|
|
@contextmanager
|
|
def execution_context(coordinator: DurableCoordinator, claim: Claim, *,
|
|
connection_failure_safe: bool | None = None,
|
|
tracked_mutations: bool | None = None):
|
|
parent = current_execution()
|
|
same_execution = (parent is not None and parent.coordinator is coordinator
|
|
and parent.claim.execution_id == claim.execution_id)
|
|
evidence = parent.remote_write_started if same_execution else threading.Event()
|
|
safe = (parent.connection_failure_safe if same_execution else False)
|
|
if connection_failure_safe is not None:
|
|
safe = connection_failure_safe
|
|
tracked = parent.tracked_mutations if same_execution else False
|
|
if tracked_mutations is not None:
|
|
tracked = tracked_mutations
|
|
rejected = parent.admission_rejected if same_execution else threading.Event()
|
|
unknown = parent.execution_unknown if same_execution else threading.Event()
|
|
token = _CURRENT_EXECUTION.set(ExecutionContext(
|
|
coordinator, claim, evidence, safe, tracked, rejected, unknown))
|
|
try:
|
|
yield
|
|
finally:
|
|
_CURRENT_EXECUTION.reset(token)
|
|
|
|
|
|
def _uncertain_exception(exc: BaseException) -> bool:
|
|
if isinstance(exc, CoordinationAdmissionRejected):
|
|
mark_admission_rejected()
|
|
context = current_execution()
|
|
if (isinstance(exc, CoordinationClaimRejected) and exc.status >= 500
|
|
and not execution_failure_before_write(exc.error_code)):
|
|
return True
|
|
return bool(context is not None and (context.remote_write_started.is_set()
|
|
or context.execution_unknown.is_set()))
|
|
context = current_execution()
|
|
if context is not None and context.execution_unknown.is_set():
|
|
return True
|
|
code = getattr(exc, "error_code", None)
|
|
# Cancellation may race another thread which has not published its write
|
|
# marker yet. A disconnected caller is not evidence of no dispatch.
|
|
if not isinstance(exc, Exception):
|
|
mark_execution_unknown()
|
|
return True
|
|
if isinstance(exc, CoordinationError) and exc.status >= 500:
|
|
mark_execution_unknown()
|
|
return True
|
|
if (code == "coordination_unavailable"
|
|
or code in _UNKNOWN_CODES
|
|
or isinstance(code, str) and code.endswith("_uncertain")):
|
|
if execution_failure_before_write(code):
|
|
return False
|
|
mark_execution_unknown()
|
|
return True
|
|
if execution_failure_before_write(code):
|
|
return False
|
|
if code in _SAFE_EXECUTION_CODES:
|
|
context = current_execution()
|
|
return bool(context is not None and context.remote_write_started.is_set())
|
|
if connection_failure_before_write(code):
|
|
return False
|
|
status = getattr(exc, "status", None)
|
|
return not isinstance(status, int) or status >= 500
|
|
|
|
|
|
@contextmanager
|
|
def resource_guard(resources, timeout: float = 5.0, *,
|
|
connection_failure_safe: bool | None = None,
|
|
tracked_mutations: bool | None = None):
|
|
import math
|
|
|
|
if (isinstance(timeout, bool) or not isinstance(timeout, (int, float))
|
|
or not math.isfinite(timeout) or timeout < 0):
|
|
raise ValueError("Invalid coordination wait bound")
|
|
resources = _resources(resources)
|
|
context = current_execution()
|
|
coordinator = context.coordinator if context is not None else get_default_coordinator()
|
|
if coordinator is None:
|
|
raise CoordinationError("coordination_unavailable", 503)
|
|
execution_id = context.claim.execution_id if context is not None else None
|
|
deadline = time.monotonic() + timeout
|
|
while True:
|
|
try:
|
|
claim = coordinator.claim(
|
|
operation_id=context.claim.operation_id if context is not None else None,
|
|
resources=resources, execution_id=execution_id, kind="resource",
|
|
metadata=context.claim.metadata if context is not None else None)
|
|
break
|
|
except CoordinationError as exc:
|
|
remaining = deadline - time.monotonic()
|
|
if exc.error_code != "coordination_busy" or remaining <= 0:
|
|
if isinstance(exc, CoordinationAdmissionRejected):
|
|
mark_admission_rejected()
|
|
else:
|
|
mark_execution_unknown()
|
|
raise
|
|
time.sleep(min(0.02, remaining))
|
|
with execution_context(coordinator, claim,
|
|
connection_failure_safe=connection_failure_safe,
|
|
tracked_mutations=tracked_mutations):
|
|
try:
|
|
yield claim
|
|
except BaseException as exc:
|
|
if _uncertain_exception(exc):
|
|
reason = getattr(exc, "error_code", None)
|
|
settled = coordinator.retain(
|
|
claim, reason if isinstance(reason, str)
|
|
and _IDENTIFIER.fullmatch(reason) else "operation_uncertain")
|
|
else:
|
|
settled = coordinator.release(claim)
|
|
if not settled:
|
|
mark_execution_unknown()
|
|
raise CoordinationError("coordination_uncertain", 503) from exc
|
|
raise
|
|
else:
|
|
context = current_execution()
|
|
settled = (
|
|
coordinator.retain(claim, "operation_uncertain")
|
|
if context is not None
|
|
and context.execution_unknown.is_set()
|
|
else coordinator.release(claim)
|
|
)
|
|
if not settled:
|
|
mark_execution_unknown()
|
|
raise CoordinationError("coordination_uncertain", 503)
|