diff --git a/integration/vllm/README.md b/integration/vllm/README.md index 9098264d..5d9b5768 100644 --- a/integration/vllm/README.md +++ b/integration/vllm/README.md @@ -157,6 +157,85 @@ LMCache connector access logs, so one setting covers every integration. Format: | `share_across_dp_sizes` | `false` | Leave the data-parallel size out of the object identity, so deployments of different DP sizes share objects (every DP replica writes the same bytes). Changes every key: objects stored so far are not found once after turning it on. | | `lookup_rpc_port` | (ipc auto) | port for the rank-0 scheduler-side prefix-lookup RPC; set only if the default IPC socket name collides. | +### CycleStore shadow (default off) + +`cyclestore_shadow` is a separate, observation-only namespace. Missing config or +`{"mode":"off"}` constructs no CycleStore client, starts no executor, emits no +RPC, and leaves RETAIN usage and physical LOAD/SAVE behavior unchanged. Shadow +mode requires explicit transport, audit and complete-layout configuration: + +```json +"cyclestore_shadow": { + "mode": "shadow", + "controller_binary": "/path/to/dfkv_cycle_controller", + "address": "127.0.0.1:60200", + "request_dir": "/path/to/audit/requests", + "queue_capacity": 256, + "rpc_timeout_ms": 15000, + "required_contributors": ["worker:0"], + "layout": {"layout_digest": "<64-hex-stable-engine-layout-digest>"} +} +``` + +Requests must independently carry `kv_transfer_params.dfkv_cyclestore` with +`schema_version=1`, stable `operation_id`, authenticated `scope_id`, +`cache_domain_id`, and `requested_ttl`. `request_id` remains only `attempt_id`; +there is no silent request-id fallback. The adapter forms versioned +operation/receipt envelopes beside `dfkv_cache_usage`; it never puts logical +C'/W'/U' into RETAIN accounting, customer billing, or physical RETAIN fields. + +Admission runs on every eligible reuse level, including all-local hits with no +LOAD. A commit needs **both** finalized prefill execution and every configured +full-rank/PP/KDA evidence contributor. `request_finished` and SAVE completion do +not replace either term. Production prefill notification requires the companion +`cyclestore/s4-vllm-hook` patch against the explicitly selected vLLM baseline; +unpatched upstream vLLM does not already provide this event. + +MultiConnector forwards the finalized prefill event to every child **only where +that optional companion hook actually exists**, including non-preferred dfkv +children whose physical hit requires no LOAD or SAVE. Upstream MultiConnector +versions without `on_prefill_executed` are an explicitly **unsupported** +environment: the optional `DfkvMultiConnector` wrapper propagates the actual +outer parent's hook capability to its real inner `DfkvStoreConnector` (which +keeps its own name), then admission fixes `unsupported_prefill_hook` after +physical lookup, never a prefill fallback/new operation/Commit. Choosing plain +MultiConnector without such parent-boundary compatibility does not make it +supported. Direct connector behavior and unrelated +RETAIN traffic are unchanged. Tests that +exercise a positive Multi fan-out must use the real companion or an equivalently +reviewed test-only forwarder; injected support does not imply upstream support. +`physical.write_tokens` and `committed_complete_pages` come from terminal +physical completion evidence, never `candidate_pages * page_size`; a full +physical hit with zero SAVE writes zero tokens. Logical cached must not exceed +physical cached, and positive FINAL receipts require logicalCommitApplied plus +an allowlisted outcome, aligned path identity, digest, apply and accepted data. + +Finished journals bind scope/domain/root, the complete lookup request digest, +canonical/full-page evidence digests, original prefill and immutable publication. +A reused attempt id with another operation is rejected before any new RPC. Commit +transport loss replays exactly the original token/path/prefill for at most three +attempts; pending retry evidence can be recovered by a fresh coordinator, while +close never reopens it. Response audit-write errors are separate degradation +markers and cannot erase a received response. A monotonic worker enforces the +publication deadline without another admission poll. PD consumers emit only a +reference with `publication_emitted=false`; this does not claim producer envelope +transport or Msh streaming support. + +The current client always sends complete `PathEvidence` for server validation; +it does not claim `EvidenceCapability` reuse, invented digest-cache verification, +or capability-client support. Full-evidence remains its required fallback path. +`LookupTokenPayload.requestedTtl` must match the requested enum before lookup +projection is accepted; unknown/clock/leader failures stay transport-unknown. + +Each RPC currently invokes the same S3 C++ protobuf-JSON CLI in a fresh process; +no Python brpc binding is claimed. This favors wire fidelity over scheduler +startup latency; resident-client optimization and a performance/latency gate +were **not** implemented or measured. Lookup/transport failure degrades shadow +state to unknown without changing physical behavior. Late receipts are reconcile +records only and never rewrite the first publication. Chat streaming's existing +final usage chunk has no `kv_transfer_params`; this adapter does **not** claim +Msh headers or the Chat-streaming Router/Nexus path is connected. + Transfer threads are shut down through vLLM's connector `shutdown()` lifecycle hook. Shutdown stops admission, cancels queued transfers with the same visible save/load outcomes described above, waits for active native operations, joins diff --git a/integration/vllm/src/dfkv_vllm/connector.py b/integration/vllm/src/dfkv_vllm/connector.py index b79c7c08..47493e38 100644 --- a/integration/vllm/src/dfkv_vllm/connector.py +++ b/integration/vllm/src/dfkv_vllm/connector.py @@ -280,6 +280,30 @@ def build_connector_meta( finally: self._finish_call() + def on_prefill_executed(self, request: Request, prefill_stats: Any) -> None: + """Companion vLLM core hook; not present in unpatched upstream cores.""" + self._begin_call() + try: + assert self.connector_scheduler is not None + self.connector_scheduler.on_prefill_executed(request, prefill_stats) + finally: + self._finish_call() + + def mark_cyclestore_evidence_ready( + self, request_id: str, contributor: str, complete_pages: int, + physical_evidence_digest: bytes, put_completed_tokens: int | None = None, + committed_complete_pages: int | None = None, put_failed_tokens: int = 0, + ) -> None: + """Ingress for the operation-level full-rank/PP/KDA evidence aggregator.""" + self._begin_call() + try: + assert self.connector_scheduler is not None + self.connector_scheduler.mark_cyclestore_evidence_ready( + request_id, contributor, complete_pages, physical_evidence_digest, + put_completed_tokens, committed_complete_pages, put_failed_tokens) + finally: + self._finish_call() + def request_finished( self, request: Request, diff --git a/integration/vllm/src/dfkv_vllm/cyclestore_multi_connector.py b/integration/vllm/src/dfkv_vllm/cyclestore_multi_connector.py new file mode 100644 index 00000000..aae9c1d2 --- /dev/null +++ b/integration/vllm/src/dfkv_vllm/cyclestore_multi_connector.py @@ -0,0 +1,38 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Optional parent-boundary capability propagation for CycleStore shadow. + +This wrapper changes no upstream vLLM method signatures. It preserves the +existing child configuration ``kv_connector="DfkvStoreConnector"`` and merely +provides an explicit opt-in outer type for deployments that need shadow support +in both legacy and companion environments. +""" + +from vllm.distributed.kv_transfer.kv_connector.factory import KVConnectorFactory +from vllm.distributed.kv_transfer.kv_connector.v1.multi_connector import MultiConnector + + +def apply_prefill_hook_support(parent: MultiConnector) -> None: + """Apply the actual outer MultiConnector's hook availability to dfkv only.""" + unavailable = not callable(getattr(parent, "on_prefill_executed", None)) + for child in parent._connectors: + scheduler = getattr(child, "connector_scheduler", None) + if scheduler is not None and hasattr(scheduler, "_prefill_hook_unavailable"): + scheduler._prefill_hook_unavailable = unavailable + + +class DfkvMultiConnector(MultiConnector): + """Opt-in outer wrapper with an actual parent/child capability boundary.""" + + def __init__(self, *args, **kwargs) -> None: + super().__init__(*args, **kwargs) + apply_prefill_hook_support(self) + + +try: + KVConnectorFactory.register_connector( + "DfkvMultiConnector", __name__, DfkvMultiConnector.__name__) +except ValueError: + # Same module may be reloaded by vLLM's factory discovery. A different class + # registered for this unique name would indicate an integration error. + if KVConnectorFactory.get_connector_class_by_name("DfkvMultiConnector") is not DfkvMultiConnector: + raise diff --git a/integration/vllm/src/dfkv_vllm/cyclestore_shadow.py b/integration/vllm/src/dfkv_vllm/cyclestore_shadow.py new file mode 100644 index 00000000..c19126a0 --- /dev/null +++ b/integration/vllm/src/dfkv_vllm/cyclestore_shadow.py @@ -0,0 +1,1390 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Default-off CycleStore shadow admission, commit and publication sidecar. + +The real transport is the S3 ``dfkv_cycle_controller`` protobuf-JSON client. +There is deliberately no second Python RPC wire implementation here. All +semantic commit decisions remain in the replicated CycleStore service; this +module only fixes engine evidence, preserves the original token/time inputs, +and freezes the first shadow publication. +""" + +from __future__ import annotations + +import base64 +from collections import OrderedDict +import copy +from dataclasses import dataclass, field +import hashlib +import json +import os +from pathlib import Path +import queue +import struct +import subprocess +import threading +import time +from typing import Any, Callable, Mapping + + +CYCLE_PARAM = "dfkv_cyclestore" +SHADOW_USAGE_PARAM = "dfkv_cyclestore_shadow" +SHADOW_REFERENCE_PARAM = "dfkv_cyclestore_shadow_reference" +POSITIVE_OUTCOMES = frozenset({ + "ROOT_CYCLE_CREATED", "PATH_COVERAGE_CREATED", "RENEWED", +}) +NEGATIVE_OUTCOMES = frozenset({ + "CONFLICT", "EXPIRED", "STALE_LOOKUP_TOKEN", "OPERATION_ID_CONFLICT", + "EVIDENCE_CONFLICT", "TTL_CONFLICT", "INVALID_EVIDENCE", "STALE_EPOCH_FENCE", +}) +MAX_COMMIT_ATTEMPTS = 3 +def _b64(value: bytes) -> str: + return base64.b64encode(value).decode("ascii") + + +def _lp(value: bytes) -> bytes: + if len(value) > 0xFFFFFFFF: + raise ValueError("CycleStore canonical field is too large") + return struct.pack(">I", len(value)) + value + + +def _domain_digest(domain: str, body: bytes) -> bytes: + return hashlib.sha256(_lp(domain.encode("utf-8")) + _lp(body)).digest() + + +def _path_bytes(pages: list[Mapping[str, Any]], complete: bool) -> bytes: + encoded = bytearray(struct.pack(">I", len(pages))) + for expected_depth, page in enumerate(pages): + page_hash = page["hash"] + physical_digest = page["physical_digest"] + if not isinstance(page_hash, bytes) or not page_hash: + raise ValueError("CycleStore page hash must be nonempty bytes") + if page["depth"] != expected_depth: + raise ValueError("CycleStore path depths must be contiguous") + if not isinstance(physical_digest, bytes) or len(physical_digest) != 32: + raise ValueError("physical page evidence must be a SHA-256 digest") + encoded += _lp(page_hash) + struct.pack(">I", page["depth"]) + if complete: + encoded += _lp(physical_digest) + encoded.append(0) # has_expected_tip=false in S2 record schema v1. + return bytes(encoded) + + +def canonical_path_digests(pages: list[Mapping[str, Any]]) -> tuple[bytes, bytes]: + """Match S2 ``EncodeCanonical/CompletePageEvidence`` byte for byte.""" + canonical = struct.pack(">I", 1) + _path_bytes(pages, False) + complete = struct.pack(">I", 1) + _path_bytes(pages, True) + return ( + _domain_digest("cyclestore.canonical_path.v1", canonical), + _domain_digest("cyclestore.complete_page_evidence.v1", complete), + ) + + +def forward_prefill_executed(connector: Any, request: Any, prefill_stats: Any) -> bool: + """Invoke an existing prefill hook, or explicitly reject unsupported Multi. + + Upstream vLLM ``MultiConnector`` inherits ``KVConnectorBase_V1`` but does not + forward this optional hook. Absence is an explicit unsupported environment, + not completed prefill evidence. Direct connectors retain their normal call. + No token, operation, timing evidence or fallback commit is fabricated. + """ + callback = getattr(connector, "on_prefill_executed", None) + if callback is not None: + callback(request, prefill_stats) + return True + for child in getattr(connector, "_connectors", ()): + scheduler = getattr(child, "connector_scheduler", None) + shadow = getattr(scheduler, "cyclestore_shadow", None) + if shadow is not None: + shadow.degrade_attempt(request.request_id, "unsupported_prefill_hook") + return False + + +def _page_hash(value: Any) -> bytes: + if not isinstance(value, bytes) or not value: + raise ValueError("vLLM block hashes must be nonempty bytes") + return value + + +def build_operation( + request: Any, + *, + token_len: int, + alignment_tokens: int, + layout: Mapping[str, Any], +) -> dict[str, Any]: + """Build the immutable FamilyKey + operation + complete-page candidate.""" + params = getattr(request, "kv_transfer_params", None) + cycle = params.get(CYCLE_PARAM) if isinstance(params, dict) else None + if not isinstance(cycle, dict) or cycle.get("schema_version") != 1: + raise ValueError("missing dfkv_cyclestore schema_version=1") + operation_id = cycle.get("operation_id") + scope_id = cycle.get("scope_id") + domain_id = cycle.get("cache_domain_id") + ttl = cycle.get("requested_ttl") + for name, value in (("operation_id", operation_id), ("scope_id", scope_id), + ("cache_domain_id", domain_id)): + if not isinstance(value, str) or not value: + raise ValueError(f"CycleStore {name} must be a nonempty string") + if ttl not in ("TTL_5M", "TTL_1H"): + raise ValueError("CycleStore requested_ttl must be TTL_5M or TTL_1H") + if token_len <= 0 or token_len % alignment_tokens: + raise ValueError("CycleStore candidate is not complete-page aligned") + hashes = list(getattr(request, "block_hashes", ())) + page_count = token_len // alignment_tokens + if page_count == 0 or len(hashes) < page_count: + raise ValueError("CycleStore candidate has no complete page evidence") + layout_digest = layout.get("layout_digest") + if not isinstance(layout_digest, str) or len(layout_digest) != 64: + raise ValueError("CycleStore layout_digest must be 64 hexadecimal characters") + try: + layout_bytes = bytes.fromhex(layout_digest) + except ValueError as error: + raise ValueError("CycleStore layout_digest is not hexadecimal") from error + pages = [] + for depth, value in enumerate(hashes[:page_count]): + page_hash = _page_hash(value) + physical = _domain_digest( + "dfkv.cyclestore.engine_physical_page.v1", + layout_bytes + struct.pack(">I", depth) + _lp(page_hash), + ) + pages.append({"hash": page_hash, "depth": depth, + "physical_digest": physical}) + canonical, complete = canonical_path_digests(pages) + path = { + "pages": [ + {"pageHash": _b64(page["hash"]), "depth": page["depth"], + "physicalEvidenceDigest": _b64(page["physical_digest"])} + for page in pages + ], + "canonicalPathDigest": _b64(canonical), + "completePageEvidenceDigest": _b64(complete), + } + return { + "schema_version": 1, + "operation_id": operation_id, + "attempt_id": request.request_id, + "scope_id": scope_id, + "cache_domain_id": domain_id, + "family_root_hash": pages[0]["hash"], + "page_tokens": alignment_tokens, + "complete_pages": len(pages), + "lookup_request": { + "family": { + "scopeId": scope_id, + "cacheDomainId": domain_id, + "familyRootHash": _b64(pages[0]["hash"]), + }, + "operationId": operation_id, + "path": path, + "requestedTtl": ttl, + }, + "canonical_path_digest": canonical, + "complete_page_evidence_digest": complete, + } + + +def _journal_identity(operation: Mapping[str, Any], prefill_ms: int | None, + *, include_prefill: bool = True) -> dict[str, Any]: + request = operation["lookup_request"] + identity = { + "operation_id": operation["operation_id"], + "scope_id": operation["scope_id"], + "cache_domain_id": operation["cache_domain_id"], + "family_root_hash": _b64(operation["family_root_hash"]), + "lookup_request_digest": hashlib.sha256( + json.dumps(request, sort_keys=True).encode("utf-8")).hexdigest(), + "canonical_path_digest": request["path"]["canonicalPathDigest"], + "complete_page_evidence_digest": request["path"]["completePageEvidenceDigest"], + } + if include_prefill: + identity["prefill_completed_at_ms"] = prefill_ms + return identity + + +def _journal_record_identity(record: Mapping[str, Any]) -> dict[str, Any] | None: + identity = record.get("operation_identity") + return identity if isinstance(identity, dict) else None + + +class SubprocessCycleStoreClient: + """Reuse the actual S3 C++ CycleStore_Stub CLI; do not invent brpc bindings.""" + + def __init__(self, settings: "CycleShadowSettings") -> None: + self.settings = settings + self._commit_calls = 0 + settings.request_dir.mkdir(parents=True, exist_ok=True) + + def call(self, operation: str, request: Mapping[str, Any]) -> dict[str, Any]: + if operation not in ("lookup", "commit"): + raise ValueError("unsupported CycleStore operation") + serial = f"{time.time_ns()}-{threading.get_ident()}-{os.getpid()}" + path = self.settings.request_dir / f"{operation}-{serial}.json" + # Unique request/response files are audit evidence, not temporary wire + # files to be silently discarded after a subprocess returns. + path.write_text(json.dumps(request, sort_keys=True), encoding="utf-8") + address = self.settings.address + if operation == "commit" and self.settings.replica_addresses: + addresses = self.settings.replica_addresses + address = addresses[self._commit_calls % len(addresses)] + self._commit_calls += 1 + command = [ + str(self.settings.controller_binary), f"--mode={operation}", + f"--address={address}", f"--request_file={path}", + f"--rpc_timeout_ms={self.settings.rpc_timeout_ms}", + ] + try: + completed = subprocess.run( + command, text=True, capture_output=True, + timeout=self.settings.rpc_timeout_ms / 1000 + 2, + env={**os.environ, "HISTFILE": "/dev/null"}, check=False, + ) + if completed.returncode != 0: + response = {"transportError": "UNAVAILABLE", + "clientReturncode": completed.returncode, + "clientStderr": completed.stderr} + else: + response = json.loads(completed.stdout) + except (OSError, subprocess.TimeoutExpired, json.JSONDecodeError) as error: + response = {"transportError": "UNAVAILABLE", + "clientError": f"{type(error).__name__}: {error}"} + try: + path.with_suffix(".response.json").write_text( + json.dumps(response, sort_keys=True), encoding="utf-8") + except OSError as error: + # Audit failure is independent evidence, never a new transport + # outcome: the already-received RPC response remains authoritative. + response = dict(response) + response["auditError"] = f"{type(error).__name__}: {error}" + return response + + +@dataclass(frozen=True) +class CycleShadowSettings: + controller_binary: Path + address: str + request_dir: Path + queue_capacity: int = 256 + rpc_timeout_ms: int = 15000 + required_contributors: frozenset[str] = frozenset({"worker:0"}) + publication_budget_ms: int | None = None + retry_backoff_ms: int = 100 + replica_addresses: tuple[str, ...] = () + + @classmethod + def from_extra_config(cls, extra: Mapping[str, Any]) -> "CycleShadowSettings | None": + raw = extra.get("cyclestore_shadow") + if raw is None: + return None + if not isinstance(raw, dict): + raise ValueError("cyclestore_shadow must be an object") + mode = raw.get("mode", "off") + if mode == "off": + return None + if mode != "shadow": + raise ValueError("cyclestore_shadow.mode must be off or shadow") + for key in ("controller_binary", "address", "request_dir", "layout"): + if key not in raw: + raise ValueError(f"cyclestore_shadow.{key} is required in shadow mode") + capacity = raw.get("queue_capacity", 256) + timeout = raw.get("rpc_timeout_ms", 15000) + budget = raw.get("publication_budget_ms") + retry_backoff = raw.get("retry_backoff_ms", 100) + replicas = raw.get("replica_addresses", []) + if (isinstance(retry_backoff, bool) or not isinstance(retry_backoff, int) or + retry_backoff <= 0): + raise ValueError("cyclestore_shadow.retry_backoff_ms must be positive") + if (not isinstance(replicas, list) or + any(not isinstance(item, str) or not item for item in replicas)): + raise ValueError("cyclestore_shadow.replica_addresses must be strings") + if isinstance(capacity, bool) or not isinstance(capacity, int) or capacity <= 0: + raise ValueError("cyclestore_shadow.queue_capacity must be positive") + if isinstance(timeout, bool) or not isinstance(timeout, int) or timeout <= 0: + raise ValueError("cyclestore_shadow.rpc_timeout_ms must be positive") + if budget is not None and (isinstance(budget, bool) or + not isinstance(budget, int) or budget <= 0): + raise ValueError("cyclestore_shadow.publication_budget_ms must be positive") + contributors = raw.get("required_contributors", ["worker:0"]) + if (not isinstance(contributors, list) or not contributors or + any(not isinstance(item, str) or not item for item in contributors)): + raise ValueError("required_contributors must be nonempty strings") + return cls( + controller_binary=Path(raw["controller_binary"]), + address=str(raw["address"]), request_dir=Path(raw["request_dir"]), + queue_capacity=capacity, rpc_timeout_ms=timeout, + required_contributors=frozenset(contributors), + publication_budget_ms=budget, retry_backoff_ms=retry_backoff, + replica_addresses=tuple(replicas), + ) + + +@dataclass +class _Operation: + operation: dict[str, Any] + attempts: set[str] = field(default_factory=set) + lookup_started: bool = False + admission_started_monotonic: float = 0.0 + lookup_done: bool = False + lookup_response: dict[str, Any] | None = None + token: dict[str, Any] | None = None + payload: dict[str, Any] | None = None + prefill_completed_at_ms: int | None = None + physical_stats: dict[str, int] | None = None + evidence: dict[str, dict[str, Any]] = field(default_factory=dict) + evidence_ready: bool = False + put_completed_tokens: int | None = None + committed_complete_pages: int | None = None + put_failed_tokens: int = 0 + commit_started: bool = False + commit_done: bool = False + commit_attempts: int = 0 + retry_due_monotonic: float | None = None + pending_state: str = "none" + commit_response: dict[str, Any] | None = None + publication: dict[str, Any] | None = None + reconciles: list[dict[str, Any]] = field(default_factory=list) + late_applied: bool = False + + @property + def dedupe_key(self) -> tuple[str, str, bytes, str]: + operation = self.operation + return (operation["scope_id"], operation["cache_domain_id"], + operation["family_root_hash"], operation["operation_id"]) + + +def _integer(value: Any) -> int | None: + if isinstance(value, bool): + return None + if isinstance(value, int): + return value + if isinstance(value, str): + try: + return int(value) + except ValueError: + return None + return None + + +def _authoritative_receipt(response: Mapping[str, Any]) -> Mapping[str, Any] | None: + """Accept only a replicated, shadow response with one definite receipt.""" + if response.get("shadowOnly") is not True or response.get("noReplication") is not False: + return None + if response.get("transportError") not in (None, "", "RESULT_UNSPECIFIED"): + return None + receipt = response.get("receipt") + if not isinstance(receipt, dict): + return None + outcome = receipt.get("outcome") + if outcome not in POSITIVE_OUTCOMES and outcome not in NEGATIVE_OUTCOMES: + return None + if outcome in POSITIVE_OUTCOMES and receipt.get("logicalCommitApplied") is not True: + return None + if outcome in NEGATIVE_OUTCOMES and receipt.get("logicalCommitApplied") is not False: + return None + return receipt + + +def _allowlisted_final(response: Mapping[str, Any], operation: Mapping[str, Any], + prefill_completed_at_ms: int | None): + def invalid(reason): + return None, reason + + receipt = _authoritative_receipt(response) + if receipt is None: + return invalid("invalid_commit_envelope") + outcome = receipt["outcome"] + if outcome in POSITIVE_OUTCOMES: + accepted = _integer(receipt.get("acceptedAtMs")) + if accepted is None: + return invalid("invalid_commit_envelope") + if (prefill_completed_at_ms is not None and + accepted < prefill_completed_at_ms): + # The RPC completed: contradictory evidence is a terminal invalid + # envelope, not a transport unknown to hide behind another Commit. + return invalid("invalid_commit_envelope") + if (_integer(receipt.get("applyIndex")) is None or + receipt.get("lockedTtl") not in ("TTL_5M", "TTL_1H")): + return invalid("invalid_commit_envelope") + if not isinstance(receipt.get("receiptDigest"), str) or not receipt["receiptDigest"]: + return invalid("invalid_commit_envelope") + if (outcome == "OPERATION_ID_CONFLICT" and receipt.get("pathDigest") in ( + None, "", "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=")): + return receipt, None + if receipt.get("pathDigest") != operation["lookup_request"]["path"]["canonicalPathDigest"]: + return invalid("commit_path_identity_conflict") + return receipt, None + + +def validate_publication(envelope: Mapping[str, Any], + baseline: Mapping[str, Any] | None = None) -> None: + """Fail closed on mixed pages/tokens/time or negative arithmetic.""" + required_identity = ("schema_version", "operation_id", "attempt_id") + if baseline is not None: + required_identity += ("scope_id", "cache_domain_id", "family_root_hash") + for key in required_identity: + if envelope.get(key) is None: + raise ValueError(f"shadow publication missing {key}") + if baseline is not None and envelope.get(key) != baseline.get(key): + raise ValueError(f"shadow publication changed immutable {key}") + physical = envelope.get("physical") + if not isinstance(physical, dict): + raise ValueError("shadow publication lacks physical arithmetic") + for key in ("prompt_tokens", "cached_tokens", "computed_tokens"): + value = physical.get(key) + if isinstance(value, bool) or not isinstance(value, int) or value < 0: + raise ValueError(f"invalid physical.{key}") + if physical["cached_tokens"] > physical["prompt_tokens"]: + raise ValueError("physical cached tokens exceed prompt tokens") + if physical["cached_tokens"] + physical["computed_tokens"] != physical["prompt_tokens"]: + raise ValueError("physical P != C + computed_tokens") + shadow = envelope.get("shadow_usage") + if not isinstance(shadow, dict): + raise ValueError("shadow publication lacks logical arithmetic") + cached = _integer(shadow.get("cached_tokens")) + uncached = _integer(shadow.get("uncached_tokens")) + if (cached is None) != (uncached is None): + raise ValueError("logical cached/uncached must be jointly known or null") + if cached is not None: + if cached < 0 or uncached < 0 or cached > physical["prompt_tokens"]: + raise ValueError("invalid logical cache token arithmetic") + if cached > physical["cached_tokens"]: + raise ValueError("logical cached exceeds physical cached") + if cached + uncached != physical["prompt_tokens"]: + raise ValueError("logical P != C' + U'") + for key in ("cache_write_tokens", "effective_ttl_ms"): + value = _integer(shadow.get(key)) + if value is not None and value < 0: + raise ValueError(f"negative shadow_usage.{key}") + if baseline is not None and envelope.get("physical") != baseline.get("physical"): + raise ValueError("physical evidence changed within one operation") + if envelope.get("commit_projection") is not None: + commit = envelope["commit_projection"] + accepted = _integer(commit.get("accepted_at_ms")) + prefill = _integer(envelope.get("prefill_completed_at_ms")) + negative_final = (commit.get("outcome") in NEGATIVE_OUTCOMES and + commit.get("logical_commit_applied") is False) + if (commit.get("envelope_valid") is True and accepted is not None and + prefill is not None and accepted < prefill and not negative_final): + raise ValueError("replicated accepted_at precedes engine prefill completion") + + +class CycleShadowCoordinator: + """Single-writer executor plus immutable first-publication records.""" + + def __init__(self, settings: CycleShadowSettings, layout: Mapping[str, Any], + *, client: Any | None = None, + wall_clock_ms: Callable[[], int] | None = None) -> None: + self.settings = settings + self.layout = copy.deepcopy(dict(layout)) + self.client = client or SubprocessCycleStoreClient(settings) + self._wall_clock_ms = wall_clock_ms or (lambda: time.time_ns() // 1_000_000) + self._operations: dict[tuple[str, str, bytes, str], _Operation] = {} + self._attempts: dict[str, tuple[str, str, bytes, str]] = {} + self._orphan_publications: dict[str, dict[str, Any]] = {} + self._finished: OrderedDict[str, dict[str, Any]] = OrderedDict() + self._finished_attempts: set[str] = set() + self._journal_conflicts: set[str] = set() + self._replayed_attempts: set[str] = set() + self._finished_durable_failures: set[str] = set() + self._journal_errors: set[str] = set() + self._finished_cache_capacity = max(16, settings.queue_capacity * 2) + self._publication_dir = settings.request_dir / "publications" + self._publication_dir.mkdir(parents=True, exist_ok=True) + self._queue: queue.Queue[tuple[str, Any] | None] = queue.Queue( + maxsize=settings.queue_capacity) + self._condition = threading.Condition() + self._closed = False + self._restore_pending_operations() + self._worker = threading.Thread(target=self._run, name="cyclestore-shadow", + daemon=True) + self._publication_worker = threading.Thread( + target=self._publication_deadline_loop, + name="cyclestore-publication-deadline", daemon=True) + self._worker.start() + self._publication_worker.start() + + @property + def layout_config(self) -> Mapping[str, Any]: + return self.layout + + def build_operation(self, request: Any, token_len: int, + alignment_tokens: int) -> dict[str, Any]: + return build_operation(request, token_len=token_len, + alignment_tokens=alignment_tokens, layout=self.layout) + + def begin_or_replay(self, attempt_id: str, + operation: dict[str, Any]) -> bool: + """Return ready once the original token or degraded admission is fixed.""" + with self._condition: + self._reject_closed() + existing_key = self._attempts.get(attempt_id) + candidate = _Operation(operation=copy.deepcopy(operation), + attempts={attempt_id}) + key = candidate.dedupe_key + if existing_key is not None and existing_key != key: + raise ValueError("one attempt cannot change CycleStore family/operation") + finished = self._finished_record_locked(attempt_id) + if finished is not None: + journal_identity = _journal_identity( + operation, + finished["operation_identity"].get("prefill_completed_at_ms")) + if finished["operation_identity"] != journal_identity: + self._journal_conflicts.add(attempt_id) + envelope = self._orphan_envelope( + attempt_id, "journal_operation_identity_conflict") + envelope.update({ + "operation_id": operation["operation_id"], + "scope_id": operation["scope_id"], + "cache_domain_id": operation["cache_domain_id"], + "family_root_hash": _b64(operation["family_root_hash"]), + "lookup_projection": { + "canonical_path_digest": operation["lookup_request"]["path"]["canonicalPathDigest"], + "complete_page_evidence_digest": operation["lookup_request"]["path"]["completePageEvidenceDigest"], + }, + }) + self._orphan_publications[attempt_id] = envelope + return True # Do not let old evidence or new RPC escape. + self._replayed_attempts.add(attempt_id) + return True + op = self._operations.get(key) + if op is None: + op = candidate + op.admission_started_monotonic = time.monotonic() + self._operations[key] = op + else: + if op.operation["lookup_request"] != operation["lookup_request"]: + raise ValueError("same family/operation cannot change candidate path") + op.attempts.add(attempt_id) + self._attempts[attempt_id] = key + if not op.lookup_started: + op.lookup_started = True + self._enqueue_locked("lookup", op) + budget = self.settings.publication_budget_ms + if (budget is not None and op.publication is None and + (time.monotonic() - op.admission_started_monotonic) * 1000 >= budget): + self._publish_locked(op, "degraded", "publication_budget_exceeded") + return self._admission_ready_locked(op) + + def degrade_attempt(self, attempt_id: str, reason: str, + operation: dict[str, Any] | None = None) -> None: + with self._condition: + key = self._attempts.get(attempt_id) + op = self._operations.get(key) + if op is None and operation is not None: + candidate = _Operation(operation=copy.deepcopy(operation), + attempts={attempt_id}) + key = candidate.dedupe_key + op = self._operations.setdefault(key, candidate) + self._attempts[attempt_id] = key + if op is not None: + self._publish_locked(op, "degraded", reason) + elif attempt_id not in self._orphan_publications: + self._orphan_publications[attempt_id] = self._orphan_envelope( + attempt_id, reason) + + @staticmethod + def _admission_ready_locked(op: _Operation) -> bool: + if op.token is not None or op.publication is not None: + return True + response = op.lookup_response or {} + return bool(op.lookup_done and response.get("result") != "OK") + + def on_prefill_executed(self, attempt_id: str, stats: Any, + prefill_completed_at_ms: int | None = None) -> None: + prompt = _integer(getattr(stats, "num_prompt_tokens", None)) + cached = _integer(getattr(stats, "num_cached_tokens", None)) + computed = _integer(getattr(stats, "num_computed_tokens", None)) + if (prompt is None or cached is None or computed is None or + min(prompt, cached, computed) < 0 or cached + computed != prompt): + raise ValueError("invalid core PrefillStats P/C/computed evidence") + with self._condition: + op = self._operation_for_attempt_locked(attempt_id) + now = self._wall_clock_ms() if prefill_completed_at_ms is None else prefill_completed_at_ms + if isinstance(now, bool) or not isinstance(now, int) or now < 0: + raise ValueError("prefill_completed_at_ms must be nonnegative integer time") + if op.prefill_completed_at_ms is not None: + if op.physical_stats == {"prompt_tokens": prompt, "cached_tokens": cached, + "computed_tokens": computed}: + # The first engine timestamp is authoritative for retry; + # a repeated hook must not sample a new local wall time. + return + raise ValueError("one operation cannot rewrite original prefill evidence") + op.prefill_completed_at_ms = now + op.physical_stats = {"prompt_tokens": prompt, "cached_tokens": cached, + "computed_tokens": computed} + self._maybe_commit_locked(op) + self._condition.notify_all() + + def mark_evidence_ready(self, attempt_id: str, contributor: str, + complete_pages: int, + physical_evidence_digest: bytes, + put_completed_tokens: int | None = None, + committed_complete_pages: int | None = None, + put_failed_tokens: int = 0) -> None: + with self._condition: + op = self._operation_for_attempt_locked(attempt_id) + for name, value in (("put_completed_tokens", put_completed_tokens), + ("committed_complete_pages", committed_complete_pages)): + if isinstance(value, bool) or not isinstance(value, int) or value < 0: + raise ValueError(f"missing/invalid physical {name}") + if (put_completed_tokens % op.operation["page_tokens"] or + committed_complete_pages != + put_completed_tokens // op.operation["page_tokens"] or + committed_complete_pages > complete_pages): + raise ValueError("physical completion is not complete-page aligned") + if op.physical_stats is not None and put_completed_tokens > op.physical_stats["computed_tokens"]: + raise ValueError("physical PUT completion exceeds actual computed tokens") + if isinstance(put_failed_tokens, bool) or not isinstance(put_failed_tokens, int) or put_failed_tokens < 0: + raise ValueError("invalid physical failed PUT count") + evidence = { + "complete_pages": complete_pages, + "physical_evidence_digest": _b64(physical_evidence_digest), + "put_completed_tokens": put_completed_tokens, + "committed_complete_pages": committed_complete_pages, + "put_failed_tokens": put_failed_tokens, + } + if contributor in op.evidence: + if op.evidence[contributor] == evidence: + return + raise ValueError("conflicting duplicate Cycle evidence contributor") + if op.commit_started: + raise ValueError("Cycle evidence is frozen once Commit starts") + if complete_pages != op.operation["complete_pages"]: + raise ValueError("Cycle evidence does not cover every candidate page") + if physical_evidence_digest != op.operation["complete_page_evidence_digest"]: + raise ValueError("Cycle evidence digest changed candidate path") + if any(existing["put_completed_tokens"] != put_completed_tokens or + existing["committed_complete_pages"] != committed_complete_pages + for existing in op.evidence.values()): + raise ValueError("rank/PP evidence disagrees on physical completion") + op.evidence[contributor] = evidence + op.put_completed_tokens = put_completed_tokens + op.committed_complete_pages = committed_complete_pages + op.put_failed_tokens = max(op.put_failed_tokens, put_failed_tokens) + op.evidence_ready = self.settings.required_contributors.issubset(op.evidence) + self._maybe_commit_locked(op) + self._condition.notify_all() + + def _maybe_commit_locked(self, op: _Operation) -> None: + if (op.commit_started or op.publication is not None or + not op.evidence_ready or op.token is None): + return + if op.prefill_completed_at_ms is None or op.physical_stats is None: + return + if op.put_failed_tokens: + self._publish_locked(op, "degraded", "physical_persistence_failure") + return + if (op.put_completed_tokens is None or + op.put_completed_tokens > op.physical_stats["computed_tokens"]): + self._publish_locked(op, "degraded", "physical_evidence_conflict") + return + payload = op.payload or {} + issued = _integer(payload.get("issuedAtMs")) + prefill_deadline = _integer(payload.get("prefillNotAfterMs")) + if issued is None or issued > op.prefill_completed_at_ms: + self._publish_locked(op, "degraded", "clock_unavailable") + return + if prefill_deadline is not None and op.prefill_completed_at_ms > prefill_deadline: + self._publish_locked(op, "degraded", "expired_prefill_window") + return + op.commit_started = True + self._enqueue_locked("commit", op) + + def _pending_path_for_operation(self, operation: Mapping[str, Any]) -> Path: + identity = _journal_identity(operation, None, include_prefill=False) + suffix = hashlib.sha256(json.dumps(identity, sort_keys=True).encode("utf-8")).hexdigest() + return self.settings.request_dir / "pending" / f"{suffix}.json" + + @staticmethod + def _operation_for_json(operation: Mapping[str, Any]) -> dict[str, Any]: + value = copy.deepcopy(dict(operation)) + for key in ("family_root_hash", "canonical_path_digest", + "complete_page_evidence_digest"): + value[key] = _b64(value[key]) + return value + + @staticmethod + def _operation_from_json(value: Mapping[str, Any]) -> dict[str, Any]: + operation = copy.deepcopy(dict(value)) + for key in ("family_root_hash", "canonical_path_digest", + "complete_page_evidence_digest"): + operation[key] = base64.b64decode(operation[key]) + return operation + + def _persist_pending(self, op: _Operation, state: str) -> None: + if not op.commit_started: + return + op.pending_state = state + payload = { + "schema_version": 1, "pending_state": state, + "operation": self._operation_for_json(op.operation), + "operation_identity": _journal_identity( + op.operation, op.prefill_completed_at_ms), + "attempts": sorted(op.attempts), "lookup_response": op.lookup_response, + "token": op.token, "payload": op.payload, "evidence": op.evidence, + "physical_stats": op.physical_stats, + "put_completed_tokens": op.put_completed_tokens, + "committed_complete_pages": op.committed_complete_pages, + "put_failed_tokens": op.put_failed_tokens, + "commit_attempts": op.commit_attempts, + } + try: + path = self._pending_path_for_operation(op.operation) + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_name(f"{path.name}.{os.getpid()}.tmp") + temporary.write_text(json.dumps(payload, sort_keys=True), encoding="utf-8") + os.replace(temporary, path) + except OSError as error: + # Active restart recovery may be unavailable, but never erase a + # valid already-received response or turn it into transport failure. + op.lookup_response = {**(op.lookup_response or {}), + "recoveryAuditError": str(error)} + + def _restore_pending_operations(self) -> None: + pending_dir = self.settings.request_dir / "pending" + if not pending_dir.is_dir(): + return + for path in sorted(pending_dir.glob("*.json")): + try: + record = json.loads(path.read_text(encoding="utf-8")) + if record.get("pending_state") not in ( + "pending", "retry_scheduled", "transport_unknown_exhausted"): + continue + operation = self._operation_from_json(record["operation"]) + expected = _journal_identity(operation, record["physical_stats"] is not None and + int(record["operation_identity"]["prefill_completed_at_ms"])) + if record.get("operation_identity") != expected: + continue + response = record["lookup_response"] + payload = response.get("payload") if isinstance(response, dict) else None + if (not isinstance(response, dict) or response.get("result") != "OK" or + response.get("transportError") not in (None, "", "RESULT_UNSPECIFIED") or + response.get("shadowOnly") is not True or + response.get("noReplication") is not False or + not isinstance(payload, dict) or + payload.get("requestedTtl") != operation["lookup_request"]["requestedTtl"] or + payload.get("issuedAtMs") != response.get("authoritativeNowMs") or + payload.get("canonicalPathDigest") != + operation["lookup_request"]["path"]["canonicalPathDigest"] or + payload.get("completePageEvidenceDigest") != + operation["lookup_request"]["path"]["completePageEvidenceDigest"]): + continue + op = _Operation(operation=operation) + op.attempts = set(record["attempts"]) + op.lookup_started = op.lookup_done = True + op.lookup_response = response + op.token = record["token"] + op.payload = record["payload"] + op.evidence = record["evidence"] + op.evidence_ready = self.settings.required_contributors.issubset(op.evidence) + op.physical_stats = record["physical_stats"] + op.prefill_completed_at_ms = record["operation_identity"]["prefill_completed_at_ms"] + op.put_completed_tokens = record["put_completed_tokens"] + op.committed_complete_pages = record["committed_complete_pages"] + op.put_failed_tokens = record["put_failed_tokens"] + op.commit_started = op.commit_done = True + attempts = int(record["commit_attempts"]) + if attempts < 1 or attempts > MAX_COMMIT_ATTEMPTS: + continue + op.commit_attempts = attempts + op.retry_due_monotonic = ( + time.monotonic() if attempts < MAX_COMMIT_ATTEMPTS else None) + op.pending_state = ("retry_scheduled" if op.retry_due_monotonic is not None + else "transport_unknown_exhausted") + key = op.dedupe_key + if key in self._operations: + continue + self._operations[key] = op + for attempt_id in op.attempts: + self._attempts[attempt_id] = key + finished = self._finished_record_locked(attempt_id) + if finished is not None: + if finished.get("operation_identity") != expected: + self._journal_errors.add(attempt_id) + continue + op.publication = copy.deepcopy(finished["publication"]) + op.reconciles = copy.deepcopy(finished["reconcile"]["reconciles"]) + op.late_applied = finished["reconcile"]["late_applied"] + except (OSError, ValueError, KeyError, TypeError): + continue + + def _publication_path(self, attempt_id: str) -> Path: + # Request ids never become paths; a stable digest avoids traversal and + # preserves the operation/attempt identity inside the JSON envelope. + return self._publication_dir / ( + hashlib.sha256(attempt_id.encode("utf-8")).hexdigest() + ".json") + + def _cache_finished_locked(self, attempt_id: str, + record: dict[str, Any]) -> None: + self._finished.pop(attempt_id, None) + self._finished[attempt_id] = copy.deepcopy(record) + while len(self._finished) > self._finished_cache_capacity: + for oldest in self._finished: + if oldest not in self._finished_durable_failures: + self._finished.pop(oldest) + break + else: + break # Never evict the only immutable copy after an I/O failure. + + def _finished_record_locked(self, attempt_id: str) -> dict[str, Any] | None: + cached = self._finished.get(attempt_id) + if cached is not None: + self._finished.move_to_end(attempt_id) + return copy.deepcopy(cached) + path = self._publication_path(attempt_id) + try: + if not path.is_file(): + return None + record = json.loads(path.read_text(encoding="utf-8")) + publication = record["publication"] + if (record.get("schema_version") != 1 or + record.get("attempt_id") != attempt_id or + not isinstance(record.get("reconcile"), dict)): + raise ValueError("durable shadow publication identity mismatch") + identity = record["operation_identity"] + request = record["lookup_request"] + encoded_request = json.dumps(request, sort_keys=True).encode("utf-8") + if (identity.get("lookup_request_digest") != + hashlib.sha256(encoded_request).hexdigest()): + raise ValueError("journal operation request digest mismatch") + if (publication.get("operation_id") != identity.get("operation_id") or + publication.get("scope_id") != identity.get("scope_id") or + publication.get("cache_domain_id") != identity.get("cache_domain_id") or + publication.get("family_root_hash") != identity.get("family_root_hash") or + publication.get("prefill_completed_at_ms") != + identity.get("prefill_completed_at_ms")): + raise ValueError("journal publication identity mismatch") + projection = publication.get("lookup_projection") + if (projection is not None and + (projection.get("canonical_path_digest") != + identity.get("canonical_path_digest") or + projection.get("complete_page_evidence_digest") != + identity.get("complete_page_evidence_digest"))): + raise ValueError("journal candidate evidence identity mismatch") + physical = publication.get("physical") + if isinstance(physical, dict) and all( + physical.get(key) is not None for key in + ("prompt_tokens", "cached_tokens", "computed_tokens")): + validate_publication(publication, publication) + self._cache_finished_locked(attempt_id, record) + return copy.deepcopy(record) + except (OSError, ValueError, KeyError, TypeError): + # A damaged audit sidecar must not throw into inference or rewrite a + # valid Commit as transport failure. The owning op is not reclaimed. + self._journal_errors.add(attempt_id) + return None + + def _write_finished_record_locked( + self, attempt_id: str, publication: dict[str, Any], + reconcile: dict[str, Any], operation_identity: dict[str, Any] | None = None, + lookup_request: dict[str, Any] | None = None, + ) -> None: + if operation_identity is None or lookup_request is None: + existing = self._finished_record_locked(attempt_id) + if existing is None: + raise ValueError("finished publication lacks immutable operation identity") + operation_identity = existing["operation_identity"] + lookup_request = existing["lookup_request"] + record = {"schema_version": 1, "attempt_id": attempt_id, + "operation_identity": copy.deepcopy(operation_identity), + "lookup_request": copy.deepcopy(lookup_request), + "publication": copy.deepcopy(publication), + "reconcile": copy.deepcopy(reconcile)} + path = self._publication_path(attempt_id) + temporary = path.with_name(f"{path.name}.{os.getpid()}.tmp") + self._cache_finished_locked(attempt_id, record) + try: + temporary.write_text(json.dumps(record, sort_keys=True), encoding="utf-8") + os.replace(temporary, path) + self._finished_durable_failures.discard(attempt_id) + except OSError: + # Publication remains frozen in memory even when its audit journal + # is unavailable; never surface an I/O error into physical inference. + self._finished_durable_failures.add(attempt_id) + self._cache_finished_locked(attempt_id, record) + + def _finish_attempt_locked( + self, attempt_id: str, publication: dict[str, Any], + reconcile: dict[str, Any] | None = None, + operation: dict[str, Any] | None = None, + ) -> None: + if operation is not None: + identity = _journal_identity(operation, publication["prefill_completed_at_ms"]) + lookup_request = operation["lookup_request"] + else: + projection = publication.get("lookup_projection") or {} + lookup_request = { + "adapterOnly": True, + "operationId": publication["operation_id"], + "attemptId": attempt_id, + } + identity = { + "operation_id": publication["operation_id"], + "scope_id": publication.get("scope_id"), + "cache_domain_id": publication.get("cache_domain_id"), + "family_root_hash": publication.get("family_root_hash"), + "lookup_request_digest": hashlib.sha256( + json.dumps(lookup_request, sort_keys=True).encode("utf-8")).hexdigest(), + "canonical_path_digest": projection.get("canonical_path_digest"), + "complete_page_evidence_digest": projection.get("complete_page_evidence_digest"), + "prefill_completed_at_ms": publication.get("prefill_completed_at_ms"), + } + existing = self._finished_record_locked(attempt_id) + if existing is not None and existing["operation_identity"] != identity: + self._journal_errors.add(attempt_id) + return + if existing is not None and existing["publication"] != publication: + self._journal_errors.add(attempt_id) + return + reconcile = (existing["reconcile"] if existing is not None else + copy.deepcopy(reconcile) if reconcile is not None else + {"late_applied": False, "reconciles": []}) + if attempt_id in self._journal_errors: + self._finished_durable_failures.add(attempt_id) + self._cache_finished_locked(attempt_id, { + "schema_version": 1, "attempt_id": attempt_id, + "operation_identity": identity, "lookup_request": lookup_request, + "publication": publication, "reconcile": reconcile, + }) + else: + self._write_finished_record_locked( + attempt_id, publication, reconcile, identity, lookup_request) + self._finished_attempts.add(attempt_id) + self._orphan_publications.pop(attempt_id, None) + + def _reclaim_quiescent_locked(self) -> None: + # Large token/path/evidence records have a bounded process lifetime; + # only compact, bounded-memory + durable publication records remain. + for key, op in list(self._operations.items()): + if not op.attempts.issubset(self._finished_attempts): + continue + if op.attempts.intersection(self._journal_errors): + continue + if (not op.lookup_done or + (op.commit_started and + (not op.commit_done or op.retry_due_monotonic is not None))): + continue + for attempt_id in op.attempts: + self._attempts.pop(attempt_id, None) + self._finished_attempts.discard(attempt_id) + del self._operations[key] + + def consumer_reference(self, attempt_id: str) -> dict[str, Any]: + """Consumer output is explicitly not an independent publication.""" + with self._condition: + op = self._operations.get(self._attempts.get(attempt_id)) + return { + "schema_version": 1, "operation_id": ( + op.operation["operation_id"] if op is not None else None), + "attempt_id": attempt_id, + "role": "kv_consumer", "publication_emitted": False, + "publication_authority": "producer", + "producer_publication_transported": False, + "shadow_only": True, + } + + def request_finished(self, attempt_id: str) -> dict[str, Any]: + """Read/freeze publication only; never substitutes for prefill completion.""" + with self._condition: + if attempt_id in self._journal_conflicts: + return copy.deepcopy(self._orphan_publications[attempt_id]) + finished = self._finished_record_locked(attempt_id) + op = self._operations.get(self._attempts.get(attempt_id)) + if op is not None and finished is not None: + expected_identity = _journal_identity( + op.operation, op.prefill_completed_at_ms) + if finished["operation_identity"] != expected_identity: + self._journal_conflicts.add(attempt_id) + return copy.deepcopy(self._orphan_publications.setdefault( + attempt_id, self._orphan_envelope( + attempt_id, "journal_prefill_identity_conflict"))) + if finished is not None: + return copy.deepcopy(finished["publication"]) + if op is None: + publication = self._orphan_publications.setdefault( + attempt_id, self._orphan_envelope(attempt_id, "operation_not_admitted")) + else: + if op.publication is None: + response = op.commit_response or {} + receipt, invalid_reason = _allowlisted_final( + response, op.operation, op.prefill_completed_at_ms) + if receipt and receipt.get("outcome") in POSITIVE_OUTCOMES: + self._publish_locked(op, "shadow_success", "replicated_receipt") + elif response.get("receipt") is not None: + reason = (str(receipt.get("outcome")) if receipt is not None + else invalid_reason) + self._publish_locked(op, "degraded", reason) + else: + terminal = (op.commit_response is not None and op.commit_done and + op.retry_due_monotonic is None) + transport_error = response.get("transportError") + if terminal and response.get("evidenceFallbackRequired") is True: + reason = str(transport_error or "evidence_fallback_required") + elif terminal and transport_error not in ( + None, "", "RESULT_UNSPECIFIED"): + reason = str(transport_error) + elif terminal: + reason = invalid_reason + else: + reason = ("commit_in_flight" if op.commit_started else + "lookup_in_flight" if not op.lookup_done else + "commit_pending_or_unavailable") + self._publish_locked(op, "degraded", reason) + publication = op.publication + self._finish_attempt_locked( + attempt_id, publication, + {"late_applied": op.late_applied, + "reconciles": copy.deepcopy(op.reconciles)} if op is not None else None, + op.operation if op is not None else None) + self._reclaim_quiescent_locked() + return copy.deepcopy(publication) + + def reconcile_snapshot(self, attempt_id: str) -> dict[str, Any] | None: + with self._condition: + finished = self._finished_record_locked(attempt_id) + if finished is not None: + return copy.deepcopy(finished["reconcile"]) + op = self._operations.get(self._attempts.get(attempt_id)) + if op is None: + return None + return {"late_applied": op.late_applied, + "reconciles": copy.deepcopy(op.reconciles)} + + def wait_for_idle(self, timeout: float = 10.0) -> bool: + deadline = time.monotonic() + timeout + with self._condition: + while time.monotonic() < deadline: + if all((op.lookup_done or op.publication is not None) and + (not op.commit_started or + (op.commit_done and op.retry_due_monotonic is None)) + for op in self._operations.values()): + return True + self._condition.wait(deadline - time.monotonic()) + return False + + def _publication_deadline_loop(self) -> None: + budget_ms = self.settings.publication_budget_ms + if budget_ms is None: + return + with self._condition: + while not self._closed: + now = time.monotonic() + deadlines = [] + for op in self._operations.values(): + if op.publication is not None: + continue + deadline = op.admission_started_monotonic + budget_ms / 1000 + if deadline <= now: + self._publish_locked(op, "degraded", "publication_budget_exceeded") + else: + deadlines.append(deadline) + self._condition.notify_all() + next_deadline = min(deadlines, default=now + 0.05) + self._condition.wait(timeout=max(0.001, min(0.05, next_deadline - now))) + + def _operation_for_attempt_locked(self, attempt_id: str) -> _Operation: + key = self._attempts.get(attempt_id) + op = self._operations.get(key) + if op is None: + raise ValueError("CycleStore Lookup admission is required before prefill evidence") + return op + + def _enqueue_locked(self, kind: str, op: _Operation) -> None: + try: + self._queue.put_nowait((kind, op.dedupe_key)) + except queue.Full: + op.lookup_done = True + op.commit_done = op.commit_started + self._publish_locked(op, "degraded", "queue_full") + + def _schedule_retry_locked(self, op: _Operation) -> None: + if self._closed or op.commit_attempts >= MAX_COMMIT_ATTEMPTS: + op.retry_due_monotonic = None + self._persist_pending(op, "closed" if self._closed + else "transport_unknown_exhausted") + return + delay = self.settings.retry_backoff_ms * (2 ** max(0, op.commit_attempts - 1)) / 1000 + op.retry_due_monotonic = time.monotonic() + delay + self._persist_pending(op, "retry_scheduled") + self._condition.notify_all() + + def _run(self) -> None: + while True: + try: + item = self._queue.get(timeout=0.025) + except queue.Empty: + with self._condition: + if self._closed: + continue + now = time.monotonic() + for key, op in list(self._operations.items()): + if (op.retry_due_monotonic is not None and + op.retry_due_monotonic <= now): + try: + self._queue.put_nowait(("commit_retry", key)) + op.retry_due_monotonic = None + except queue.Full: + op.retry_due_monotonic = now + 0.01 + continue + try: + if item is None: + return + kind, key = item + with self._condition: + op = self._operations[key] + if self._closed: + continue + request = (op.operation["lookup_request"] if kind == "lookup" else { + "token": op.token, "path": op.operation["lookup_request"]["path"], + "prefillCompletedAtMs": str(op.prefill_completed_at_ms), + }) + if kind != "lookup": + op.commit_attempts += 1 + op.commit_done = False + self._persist_pending(op, "retry_scheduled") + response = self.client.call( + "lookup" if kind == "lookup" else "commit", copy.deepcopy(request)) + with self._condition: + op = self._operations[key] + if kind == "lookup": + self._store_lookup_locked(op, response) + else: + self._store_commit_locked(op, response) + self._condition.notify_all() + except Exception as error: + with self._condition: + if item is not None: + kind, key = item + op = self._operations.get(key) + if op is not None: + if kind == "lookup": + self._store_lookup_locked(op, {"result": "UNAVAILABLE", + "clientError": str(error)}) + else: + self._store_commit_locked(op, {"transportError": "UNAVAILABLE", + "clientError": str(error)}) + self._condition.notify_all() + finally: + self._queue.task_done() + + def _store_lookup_locked(self, op: _Operation, + response: dict[str, Any]) -> None: + op.lookup_done = True + op.lookup_response = copy.deepcopy(response) + if response.get("result") != "OK": + reason = str(response.get("result") or "UNAVAILABLE") + self._publish_locked(op, "degraded", reason) + self._reclaim_quiescent_locked() + return + if response.get("transportError") not in (None, "", "RESULT_UNSPECIFIED"): + self._publish_locked(op, "degraded", "invalid_lookup_envelope") + self._reclaim_quiescent_locked() + return + if response.get("shadowOnly") is not True or response.get("noReplication") is not False: + self._publish_locked(op, "degraded", "invalid_replication_evidence") + self._reclaim_quiescent_locked() + return + token = response.get("token") + payload = response.get("payload") + issued = _integer((payload or {}).get("issuedAtMs")) + authoritative = _integer(response.get("authoritativeNowMs")) + if (not isinstance(token, dict) or not isinstance(payload, dict) or + payload.get("requestedTtl") != op.operation["lookup_request"]["requestedTtl"] or + payload.get("canonicalPathDigest") != + op.operation["lookup_request"]["path"]["canonicalPathDigest"] or + payload.get("completePageEvidenceDigest") != + op.operation["lookup_request"]["path"]["completePageEvidenceDigest"] or + issued is None or authoritative != issued): + self._publish_locked(op, "degraded", "invalid_lookup_snapshot") + self._reclaim_quiescent_locked() + return + op.token = copy.deepcopy(token) + op.payload = copy.deepcopy(payload) + self._maybe_commit_locked(op) + self._reclaim_quiescent_locked() + + def _store_commit_locked(self, op: _Operation, + response: dict[str, Any]) -> None: + op.commit_done = True + op.commit_response = copy.deepcopy(response) + raw_receipt = response.get("receipt") + receipt = _allowlisted_final( + response, op.operation, op.prefill_completed_at_ms)[0] + if op.publication is not None and raw_receipt is not None: + logical_applied = bool(receipt and receipt.get("logicalCommitApplied")) + op.late_applied = logical_applied + op.reconciles.append({ + "logical_commit_applied": logical_applied, + "accepted_at_ms": _integer(receipt.get("acceptedAtMs")) if receipt else None, + "apply_index": _integer(receipt.get("applyIndex")) if receipt else None, + "receipt_digest": receipt.get("receiptDigest") if receipt else None, + "envelope_valid": receipt is not None, + }) + reconcile = {"late_applied": op.late_applied, + "reconciles": copy.deepcopy(op.reconciles)} + for attempt_id in op.attempts: + finished = self._finished_record_locked(attempt_id) + if finished is not None: + self._write_finished_record_locked( + attempt_id, finished["publication"], reconcile) + elif raw_receipt is not None and receipt is None: + self._publish_locked(op, "degraded", "invalid_commit_envelope") + elif receipt and receipt.get("outcome") in POSITIVE_OUTCOMES: + self._publish_locked(op, "shadow_success", "replicated_receipt") + elif receipt: + self._publish_locked(op, "degraded", str(receipt.get("outcome"))) + # Transport-unavailable deliberately remains unpublished/unknown until + # request_finished or another explicit first-publication point. + if raw_receipt is None and response.get("transportError") in ( + "UNAVAILABLE", "CLOCK_UNAVAILABLE"): + self._schedule_retry_locked(op) + else: + op.retry_due_monotonic = None + self._persist_pending(op, "final_receipt" if receipt is not None + else "invalid_commit_envelope") + self._reclaim_quiescent_locked() + + def _orphan_envelope(self, attempt_id: str, reason: str) -> dict[str, Any]: + return { + "schema_version": 1, "operation_id": None, "attempt_id": attempt_id, + "result": "degraded", "reason": reason, "cycle_state": "unknown", + "published_at_ms": self._wall_clock_ms(), + "publication_source": "adapter", + "physical": None, "shadow_usage": { + "cached_tokens": None, "cache_write_tokens": None, + "uncached_tokens": None, "effective_ttl_ms": None, + "bucket_5m": None, "bucket_1h": None, + }, + "lookup_projection": None, "commit_projection": None, + "prefill_completed_at_ms": None, + "shadow_only": True, "no_replication": None, + } + + def _publish_locked(self, op: _Operation, result: str, reason: str) -> None: + if op.publication is not None: + return # First publication is one-way frozen, including late success. + operation = op.operation + payload = op.payload or {} + response = op.commit_response or {} + receipt = response.get("receipt") or {} + authoritative_receipt = ( + _allowlisted_final(response, operation, op.prefill_completed_at_ms)[0] + if response else None) + physical = copy.deepcopy(op.physical_stats) if op.physical_stats is not None else { + "prompt_tokens": None, "cached_tokens": None, "computed_tokens": None, + } + physical.update({ + "write_tokens": op.put_completed_tokens, + "complete_pages": op.operation["complete_pages"], + "committed_complete_pages": op.committed_complete_pages, + }) + alive_depth = _integer(payload.get("aliveDepth")) + cached = (min(physical["prompt_tokens"], (alive_depth + 1) * op.operation["page_tokens"]) + if alive_depth is not None and alive_depth >= -1 and + physical["prompt_tokens"] is not None else None) + new_nodes = _integer(receipt.get("newNodeCount")) + accepted = _integer(receipt.get("acceptedAtMs")) + lease_expire = _integer(receipt.get("leaseExpireAtMs")) + locked_ttl = receipt.get("lockedTtl") + success = result == "shadow_success" + cache_write = (new_nodes * op.operation["page_tokens"] + if success and new_nodes is not None else None) + envelope = { + "schema_version": 1, + "operation_id": operation["operation_id"], + "attempt_id": operation["attempt_id"], + "scope_id": operation["scope_id"], + "cache_domain_id": operation["cache_domain_id"], + "family_root_hash": _b64(operation["family_root_hash"]), + "result": result, "reason": reason, + "cycle_state": ("applied" if success else + "deterministic_negative" if authoritative_receipt else "unknown"), + "published_at_ms": self._wall_clock_ms(), + "publication_source": "replicated_receipt" if success else "adapter", + "physical": physical, + "shadow_usage": { + "cached_tokens": cached, + "cache_write_tokens": cache_write, + "uncached_tokens": (physical["prompt_tokens"] - cached + if cached is not None else None), + "effective_ttl_ms": (max(0, lease_expire - accepted) + if accepted is not None and lease_expire is not None else None), + "bucket_5m": locked_ttl == "TTL_5M" if locked_ttl else None, + "bucket_1h": locked_ttl == "TTL_1H" if locked_ttl else None, + }, + "lookup_projection": ({ + "read_at_ms": _integer(payload.get("issuedAtMs")), + "authoritative_now_ms": _integer((op.lookup_response or {}).get("authoritativeNowMs")), + "read_apply_index": _integer(payload.get("readApplyIndex")), + "generation": _integer(payload.get("readRootGeneration")), + "family_incarnation": _integer(payload.get("familyIncarnation")), + "data_epoch": _integer(payload.get("dataEpoch")), + "intent": payload.get("intent"), + "requested_ttl": payload.get("requestedTtl"), + "alive_depth": alive_depth, + "prefill_not_after_ms": _integer(payload.get("prefillNotAfterMs")), + "commit_not_after_ms": _integer(payload.get("commitNotAfterMs")), + "canonical_path_digest": _b64(operation["canonical_path_digest"]), + "complete_page_evidence_digest": _b64(operation["complete_page_evidence_digest"]), + } if op.payload is not None else None), + "prefill_completed_at_ms": op.prefill_completed_at_ms, + "commit_projection": ({ + "outcome": receipt.get("outcome"), + "transport_error": response.get("transportError"), + "evidence_fallback_required": bool(response.get("evidenceFallbackRequired")), + "accepted_at_ms": accepted, + "apply_index": _integer(receipt.get("applyIndex")), + "root_generation": _integer(receipt.get("rootGeneration")), + "observed_current_generation": _integer(receipt.get("observedCurrentGeneration")), + "locked_ttl": locked_ttl, + "lease_expire_at_ms": lease_expire, + "new_node_count": new_nodes, + "logical_commit_applied": bool( + authoritative_receipt and receipt.get("logicalCommitApplied")), + "billing_eligible_for_new_cycle": bool( + authoritative_receipt and receipt.get("billingEligibleForNewCycle")), + "receipt_replayed": bool(response.get("receiptReplayed")), + "envelope_valid": authoritative_receipt is not None, + "receipt_digest": receipt.get("receiptDigest"), + } if op.commit_response is not None else None), + "shadow_only": True, + "evidence_mode": "full_evidence", + "no_replication": (op.commit_response if op.commit_response is not None + else op.lookup_response or {}).get("noReplication"), + } + if (cached is not None and physical["cached_tokens"] is not None and + cached > physical["cached_tokens"]): + # Never hide an impossible logical prefix behind min(C', C). + if success: + envelope["result"] = "degraded" + envelope["reason"] = "logical_cached_exceeds_physical" + envelope["cycle_state"] = "physical_evidence_conflict" + for key in ("cached_tokens", "uncached_tokens", "cache_write_tokens"): + envelope["shadow_usage"][key] = None + # Before core stats exist, the envelope is explicitly partial and does + # not pass the arithmetic gate; it is still truthful degraded metadata. + if all(physical.get(key) is not None + for key in ("prompt_tokens", "cached_tokens", "computed_tokens")): + validate_publication(envelope) + op.publication = copy.deepcopy(envelope) + + def _reject_closed(self) -> None: + if self._closed: + raise RuntimeError("CycleStore shadow coordinator is closed") + + def close(self) -> None: + with self._condition: + if self._closed: + return + self._closed = True + for op in self._operations.values(): + if op.commit_started: + self._persist_pending(op, "closed") + self._condition.notify_all() + # Do not leave a daemon worker unsignalled when capacity is exhausted. + # _run skips queued work after _closed; one owned CLI call is bounded by + # rpc_timeout_ms plus the client's two-second subprocess allowance. + self._queue.put(None) + self._worker.join(timeout=self.settings.rpc_timeout_ms / 1000 + 4) + self._publication_worker.join(timeout=1.0) + if self._worker.is_alive() or self._publication_worker.is_alive(): + raise RuntimeError("CycleStore shadow executor exceeded RPC shutdown bound") diff --git a/integration/vllm/src/dfkv_vllm/scheduler.py b/integration/vllm/src/dfkv_vllm/scheduler.py index 630708f8..ffc2038e 100644 --- a/integration/vllm/src/dfkv_vllm/scheduler.py +++ b/integration/vllm/src/dfkv_vllm/scheduler.py @@ -36,6 +36,12 @@ from .worker import ( LookupKeyClient, ) +from .cyclestore_shadow import ( + CycleShadowCoordinator, + CycleShadowSettings, + SHADOW_REFERENCE_PARAM, + SHADOW_USAGE_PARAM, +) logger = init_logger(__name__) @@ -99,6 +105,15 @@ def __init__( extra_config = ( vllm_config.kv_transfer_config.kv_connector_extra_config ) + self._prefill_hook_unavailable = False + if getattr( + vllm_config.kv_transfer_config, "kv_connector", None + ) == "MultiConnector": + from vllm.distributed.kv_transfer.kv_connector.v1.multi_connector import ( + MultiConnector, + ) + self._prefill_hook_unavailable = not callable( + getattr(MultiConnector, "on_prefill_executed", None)) self.load_async = extra_config.get("load_async", True) if not isinstance(self.load_async, bool): raise ValueError("dfkv connector: load_async must be a boolean") @@ -112,6 +127,13 @@ def __init__( ) self.client = LookupKeyClient(vllm_config) self._closed = False + shadow_settings = CycleShadowSettings.from_extra_config(extra_config) + self.cyclestore_shadow = None + if shadow_settings is not None: + self.cyclestore_shadow = CycleShadowCoordinator( + shadow_settings, + extra_config["cyclestore_shadow"]["layout"], + ) # Align with the engine's own scheduler_block_size and hash_block_size. self._block_size, self._hash_block_size = resolve_kv_cache_block_sizes( @@ -149,6 +171,29 @@ def __init__( # requests; the applied TTL comes back from the worker's lookup. self._retention: dict[str, tuple[int, int, int]] = {} + def _cycle_admission( + self, request: Request, token_len: int, alignment_tokens: int + ) -> bool: + shadow = getattr(self, "cyclestore_shadow", None) + if shadow is None: + return True + try: + operation = shadow.build_operation( + request, token_len, alignment_tokens) + if getattr(self, "_prefill_hook_unavailable", False): + # Freeze reason at first admission, before any async physical + # lookup or finish-time publication can mask it with a generic + # pending/transport state. It never grants a logical Commit. + shadow.degrade_attempt(request.request_id, "unsupported_prefill_hook") + return shadow.begin_or_replay(request.request_id, operation) + except Exception as error: + logger.warning( + "CycleStore shadow admission degraded req=%s error=%s", + request.request_id, error, + ) + shadow.degrade_attempt(request.request_id, "invalid_engine_evidence") + return True # Physical RETAIN/LOAD admission is unchanged. + def get_num_new_matched_tokens( self, request: Request, @@ -194,6 +239,10 @@ def get_num_new_matched_tokens( requested_ttl, 0, num_computed_tokens) return 0, False + # Launch logical admission before physical lookup. In particular this + # remains live when local L1/L2 covers the whole candidate and no LOAD + # spec will ever be created. Polls replay one operation/token only. + cycle_ready = self._cycle_admission(request, token_len, align) _lk0 = time.perf_counter() lookup = self.client.lookup( request.request_id, @@ -204,6 +253,13 @@ def get_num_new_matched_tokens( ) if lookup is None: return None, False + if not cycle_ready and not self._cycle_admission(request, token_len, align): + return None, False + shadow = getattr(self, "cyclestore_shadow", None) + if shadow is not None and getattr(self, "_prefill_hook_unavailable", False): + # A real admission with no prefill notification is not logical + # success: there can be no Commit, but physical lookup/RETAIN continues. + shadow.degrade_attempt(request.request_id, "unsupported_prefill_hook") num_external_hit_tokens, applied_ttl = lookup if requested_ttl: self._retention[request.request_id] = ( @@ -788,6 +844,44 @@ def register_finished_partial_tail( self._finished_partial_tail_metas[request.request_id] = req_meta return True + def on_prefill_executed(self, request: Request, prefill_stats: Any) -> None: + """Receive the companion core hook after PrefillStats.finalize(). + + request_finished is intentionally not a substitute: it is end of the + whole decode lifecycle. Evidence readiness is a separate AND term. + """ + shadow = getattr(self, "cyclestore_shadow", None) + if shadow is None or self.kv_role == "kv_consumer": + return + try: + shadow.on_prefill_executed(request.request_id, prefill_stats) + except Exception as error: + logger.warning( + "CycleStore shadow prefill degraded req=%s error=%s", + request.request_id, error, + ) + shadow.degrade_attempt(request.request_id, "invalid_prefill_evidence") + + def mark_cyclestore_evidence_ready( + self, request_id: str, contributor: str, complete_pages: int, + physical_evidence_digest: bytes, put_completed_tokens: int | None = None, + committed_complete_pages: int | None = None, put_failed_tokens: int = 0, + ) -> None: + """Aggregate full-rank/PP/KDA evidence without using SAVE as Commit.""" + shadow = getattr(self, "cyclestore_shadow", None) + if shadow is None or self.kv_role == "kv_consumer": + return + try: + shadow.mark_evidence_ready( + request_id, contributor, complete_pages, physical_evidence_digest, + put_completed_tokens, committed_complete_pages, put_failed_tokens) + except Exception as error: + logger.warning( + "CycleStore shadow evidence degraded req=%s error=%s", + request_id, error, + ) + shadow.degrade_attempt(request_id, "invalid_engine_evidence") + def request_finished( self, request: Request, @@ -799,6 +893,17 @@ def request_finished( self._failed_load_req_ids.discard(request.request_id) self.load_specs.pop(request.request_id, None) usage = self._retention_usage(request) + shadow = getattr(self, "cyclestore_shadow", None) + if shadow is not None: + if usage is None: + usage = {} + # Parallel namespace: legacy RETAIN keys/values are untouched. + if self.kv_role == "kv_consumer": + usage[SHADOW_REFERENCE_PARAM] = shadow.consumer_reference( + request.request_id) + else: + usage[SHADOW_USAGE_PARAM] = shadow.request_finished( + request.request_id) if self.kv_role == "kv_consumer": return False, usage tracker = self._request_trackers.get(request.request_id) @@ -847,6 +952,9 @@ def close(self) -> None: return self._closed = True self.client.close() + shadow = getattr(self, "cyclestore_shadow", None) + if shadow is not None: + shadow.close() def reset_store(self) -> bool: """Request a global store reset via worker rank 0. diff --git a/integration/vllm/tests/cyclestore_shadow_e2e.py b/integration/vllm/tests/cyclestore_shadow_e2e.py new file mode 100755 index 00000000..8be9c477 --- /dev/null +++ b/integration/vllm/tests/cyclestore_shadow_e2e.py @@ -0,0 +1,273 @@ +#!/usr/bin/env python3 +"""Real three-replica CycleStore shadow adapter smoke; no GPU/model/mock RPC. + +Run with an S3-compatible ``dfkv_cycle_controller`` built from e4274728. The +three controller processes, data directories, ports and protobuf-JSON audit +requests are exclusive to this invocation's fresh evidence root. +""" + +import argparse +import copy +import hashlib +import json +from pathlib import Path +import subprocess +import sys + +REPO = Path(__file__).resolve().parents[3] +sys.path.insert(0, str(REPO / "src/cyclestore/test")) +sys.path.insert(0, str(REPO / "integration/vllm/src")) +sys.path.insert(0, str(REPO / "integration/common/src")) + +from raft_business_integration_test import BusinessCluster, integer # noqa: E402 +from dfkv_vllm.cyclestore_shadow import ( # noqa: E402 + CycleShadowCoordinator, CycleShadowSettings, SubprocessCycleStoreClient, + build_operation, validate_publication, +) + + +LAYOUT = {"layout_digest": hashlib.sha256(b"s4-e2e-single-full-attention").hexdigest()} + + +def request(attempt, operation, *, wrong_path=False): + pages = [b"root-hash", b"wrong-page-hash" if wrong_path else b"child-page-hash"] + return type("Request", (), { + "request_id": attempt, + "num_prompt_tokens": 128, + "num_tokens": 128, + "block_hashes": pages, + "kv_transfer_params": {"dfkv_cyclestore": { + "schema_version": 1, "operation_id": operation, + "scope_id": "s3-test", "cache_domain_id": "s3-test-domain", + "requested_ttl": "TTL_5M", + }}, + })() + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--binary", required=True, type=Path) + parser.add_argument("--root", required=True, type=Path) + args = parser.parse_args() + binary = str(args.binary.resolve()) + root = args.root.resolve() + if root.exists(): + print(f"FAIL: evidence root already exists: {root}") + return 2 + root.parent.mkdir(parents=True, exist_ok=True) + cluster = BusinessCluster(binary, root) + settings = CycleShadowSettings( + controller_binary=Path(binary), address="", + request_dir=root / "adapter-requests", + ) + coordinator = None + try: + leader, _ = cluster.start_all() + settings = CycleShadowSettings( + controller_binary=Path(binary), address=cluster.addrs[leader], + request_dir=root / "adapter-requests", + ) + coordinator = CycleShadowCoordinator(settings, LAYOUT) + client = coordinator.client + assert isinstance(client, SubprocessCycleStoreClient) + cluster.set_clocks(1_000_000) + + def run_operation(attempt, operation_id, now_ms, expected_outcome, + physical_cached=64, put_tokens=64): + req = request(attempt, operation_id) + operation = coordinator.build_operation(req, 128, 64) + assert coordinator.begin_or_replay(attempt, operation) in (True, False) + assert coordinator.wait_for_idle(20) + op = coordinator._operations[ # direct test inspection of original token + (operation["scope_id"], operation["cache_domain_id"], + operation["family_root_hash"], operation["operation_id"])] + assert op.token is not None and op.payload is not None + assert op.payload["requestedTtl"] == "TTL_5M" + # The service may issue a capability reference even on full-evidence + # Lookup. This client never sends it back to bypass PathEvidence. + assert "evidenceCapability" not in operation["lookup_request"] + assert (op.lookup_response or {}).get("evidenceFallbackRequired") is False + assert (op.lookup_response or {}).get("noReplication") is False + coordinator.mark_evidence_ready( + attempt, "worker:0", operation["complete_pages"], + operation["complete_page_evidence_digest"], + put_completed_tokens=put_tokens, + committed_complete_pages=put_tokens // 64) + coordinator.on_prefill_executed( + attempt, type("Stats", (), { + "num_prompt_tokens": 128, "num_cached_tokens": physical_cached, + "num_computed_tokens": 128 - physical_cached, + })(), prefill_completed_at_ms=now_ms) + assert coordinator.wait_for_idle(20) + envelope = coordinator.request_finished(attempt) + assert envelope["commit_projection"]["outcome"] == expected_outcome + assert envelope["commit_projection"]["accepted_at_ms"] == now_ms + assert envelope["result"] == "shadow_success" + assert envelope["no_replication"] is False + validate_publication(envelope) + return req, operation, op, envelope + + cold_req, cold_op, cold_state, cold = run_operation( + "s4-cold-attempt", "s4-cold", 1_000_000, "ROOT_CYCLE_CREATED") + assert cold["commit_projection"]["root_generation"] == 1 + assert cold["commit_projection"]["new_node_count"] == 2 + assert cold["shadow_usage"]["cache_write_tokens"] == 128 + + # Same operation Lookup is the service READ_BARRIER and returns the + # exact original token, not a new deadline or operation. + replay_lookup = client.call("lookup", cold_op["lookup_request"]) + assert replay_lookup["token"] == cold_state.token + assert replay_lookup["payload"] == cold_state.payload + + cluster.set_clocks(1_001_000) + _renew_req, _renew_op, _renew_state, renew = run_operation( + "s4-renew-attempt", "s4-renew", 1_001_000, "RENEWED", + physical_cached=128, put_tokens=0) + assert renew["commit_projection"]["root_generation"] == 1 + assert renew["commit_projection"]["new_node_count"] == 0 + assert renew["commit_projection"]["billing_eligible_for_new_cycle"] is False + + # Illegal prefill creates a persistent negative FINAL. Correcting the + # prefill timestamp is a different Commit input and cannot overwrite it. + bad_operation = build_operation( + request("s4-bad-prefill-attempt", "s4-bad-prefill"), + token_len=128, alignment_tokens=64, layout=LAYOUT) + bad_lookup = client.call("lookup", bad_operation["lookup_request"]) + bad_commit_request = { + "token": copy.deepcopy(bad_lookup["token"]), + "path": bad_operation["lookup_request"]["path"], + "prefillCompletedAtMs": "2000000", + } + bad_prefill = client.call("commit", bad_commit_request) + assert bad_prefill["receipt"]["outcome"] == "INVALID_EVIDENCE" + assert bad_prefill["receipt"]["logicalCommitApplied"] is False + corrected = client.call("commit", { + "token": copy.deepcopy(bad_lookup["token"]), + "path": bad_operation["lookup_request"]["path"], + "prefillCompletedAtMs": "1001000", + }) + assert corrected["receipt"]["outcome"] == "OPERATION_ID_CONFLICT" + bad_replay = client.call("commit", bad_commit_request) + assert bad_replay["receipt"] == bad_prefill["receipt"] + assert bad_replay["receiptReplayed"] is True + + # A wrong, but canonically valid, PathEvidence for the finalized + # operation is rejected and cannot poison the original receipt. + wrong_operation = build_operation( + request("s4-wrong-attempt", "s4-cold", wrong_path=True), + token_len=128, alignment_tokens=64, layout=LAYOUT) + wrong = client.call("commit", { + "token": copy.deepcopy(cold_state.token), + "path": wrong_operation["lookup_request"]["path"], + "prefillCompletedAtMs": "1000000", + }) + assert wrong["receipt"]["outcome"] == "OPERATION_ID_CONFLICT" + original = client.call("commit", { + "token": copy.deepcopy(cold_state.token), + "path": cold_op["lookup_request"]["path"], + "prefillCompletedAtMs": "1000000", + }) + assert original["receipt"] == cold_state.commit_response["receipt"] + assert original["receiptReplayed"] is True + + cluster.set_clocks(1_400_000) + _expiry_req, _expiry_op, _expiry_state, expiry = run_operation( + "s4-expiry-attempt", "s4-expiry", 1_400_000, "ROOT_CYCLE_CREATED") + assert expiry["lookup_projection"]["intent"] == "CREATE_NEXT_ROOT" + assert expiry["commit_projection"]["root_generation"] == 2 + assert expiry["commit_projection"]["new_node_count"] == 0 + assert expiry["shadow_usage"]["cache_write_tokens"] == 0 + + unknown_operation = build_operation( + request("s4-unknown-attempt", "s4-unknown"), + token_len=128, alignment_tokens=64, layout=LAYOUT) + unknown_lookup = client.call("lookup", unknown_operation["lookup_request"]) + unknown_commit_request = { + "token": copy.deepcopy(unknown_lookup["token"]), + "path": unknown_operation["lookup_request"]["path"], + "prefillCompletedAtMs": "1400000", + } + cluster.set_clocks(1_300_000) + unknown = client.call("commit", unknown_commit_request) + assert unknown["transportError"] == "UNAVAILABLE" + assert "receipt" not in unknown + cluster.set_clocks(1_400_000) + resolved = client.call("commit", unknown_commit_request) + assert resolved["receipt"]["logicalCommitApplied"] is True + assert integer(resolved["receipt"]["rootGeneration"]) == 2 + + # Reusing a page hash below a different parent must fail closed rather + # than borrowing the old tip's Alive lease or silently merging a DAG. + lineage_req = request("s4-lineage-attempt", "s4-lineage") + lineage_req.block_hashes = [b"root-hash", b"intermediate-page-hash", + b"child-page-hash"] + lineage_req.num_prompt_tokens = lineage_req.num_tokens = 192 + lineage_operation = build_operation( + lineage_req, token_len=192, alignment_tokens=64, layout=LAYOUT) + lineage_lookup = client.call("lookup", lineage_operation["lookup_request"]) + assert lineage_lookup["result"] == "EVIDENCE_CONFLICT" + assert "token" not in lineage_lookup and "payload" not in lineage_lookup + lineage_commit = None + + gc = cluster.admin(leader, "gc", now_ms=2_500_000, drop_fence=True) + assert gc["ok"], gc + cluster.set_clocks(2_500_000) + incarnation_req = request("s4-incarnation-attempt", "s4-incarnation") + incarnation_op = build_operation( + incarnation_req, token_len=128, alignment_tokens=64, layout=LAYOUT) + incarnation = client.call("lookup", incarnation_op["lookup_request"]) + assert integer(incarnation["payload"]["familyIncarnation"]) == 2 + stale = client.call("commit", { + "token": copy.deepcopy(cold_state.token), + "path": cold_op["lookup_request"]["path"], + "prefillCompletedAtMs": "1000000", + }) + assert stale["receipt"]["outcome"] == "STALE_LOOKUP_TOKEN" + assert stale["receipt"]["logicalCommitApplied"] is False + stale_relookup = client.call("lookup", cold_op["lookup_request"]) + assert stale_relookup["result"] != "OK" + assert "token" not in stale_relookup + assert "payload" not in stale_relookup + + evidence = { + "binary": binary, + "controller_sha256": hashlib.sha256(Path(binary).read_bytes()).hexdigest(), + "source_head": subprocess.check_output( + ["git", "-C", str(REPO), "rev-parse", "HEAD"], text=True).strip(), + "leader": leader, + "cold": cold, "renew": renew, "expiry": expiry, + "wrong_path": wrong, "original_after_wrong": original, + "bad_prefill": bad_prefill, "corrected_prefill": corrected, + "bad_prefill_replay": bad_replay, + "clock_unknown": unknown, "clock_resolved": resolved, + "lineage_lookup": lineage_lookup, "lineage_commit": lineage_commit, + "incarnation_lookup": incarnation, "stale_token": stale, + "stale_relookup": stale_relookup, + "capability_client_adapted": False, + "full_evidence_service_validated": True, + "adapter_request_files": sorted( + str(path) for path in settings.request_dir.glob("*.json")), + "controller_commands": str(root / "commands.jsonl"), + "replica_logs": sorted(str(path) for path in (root / "logs").glob("*.log")), + "chat_streaming_msh_kv_transfer_params_connected": False, + "gpu_model_weights_used": False, + } + (root / "adapter-e2e-result.json").write_text( + json.dumps(evidence, sort_keys=True, indent=2) + "\n") + print("PASS case=adapter_real_cold_renew_expiry generations=1,1,2 new_nodes=2,0,0") + print("PASS case=adapter_read_barrier_and_operation_id_conflict token_equal=True original_replayed=True") + print("PASS case=adapter_real_invalid_prefill_final correction=OPERATION_ID_CONFLICT replayed=True") + print("PASS case=adapter_real_clock_unknown transport=UNAVAILABLE receipt=False resolved=True") + print("PASS case=adapter_real_parent_path_lineage outcome=EVIDENCE_CONFLICT borrowed_alive=False") + print("PASS case=adapter_real_incarnation_stale_token family_incarnation=2 outcome=STALE_LOOKUP_TOKEN receipt_only_lookup=False") + print("PASS case=adapter_real_brpc_receipts no_replication=False adapter_mock_rpc=False full_evidence=True capability_client=False") + print("SUMMARY PASS=7 SKIP=0 FAIL=0 TOTAL=7") + return 0 + finally: + if coordinator is not None: + coordinator.close() + cluster.cleanup() + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/integration/vllm/tests/cyclestore_shadow_review_e2e.py b/integration/vllm/tests/cyclestore_shadow_review_e2e.py new file mode 100755 index 00000000..31ced37a --- /dev/null +++ b/integration/vllm/tests/cyclestore_shadow_review_e2e.py @@ -0,0 +1,283 @@ +#!/usr/bin/env python3 +"""Real-controller M3/M4 response-audit, retry and process-restart evidence.""" + +import argparse +import copy +from dataclasses import replace +import hashlib +import json +import os +from pathlib import Path +import subprocess +import sys +import time +from types import SimpleNamespace +from unittest.mock import patch + +REPO = Path(__file__).resolve().parents[3] +sys.path.insert(0, str(REPO / "src/cyclestore/test")) +sys.path.insert(0, str(REPO / "integration/vllm/src")) +sys.path.insert(0, str(REPO / "integration/common/src")) + +from raft_business_integration_test import BusinessCluster # noqa: E402 +from dfkv_vllm.cyclestore_shadow import ( # noqa: E402 + CycleShadowCoordinator, CycleShadowSettings, build_operation) + + +LAYOUT = {"layout_digest": hashlib.sha256(b"s4-review-real-full-evidence").hexdigest()} +PAGE = 64 + + +def input_request(attempt, operation): + return SimpleNamespace( + request_id=attempt, num_prompt_tokens=128, num_tokens=128, + block_hashes=[b"root-hash", b"child-page-hash"], + kv_transfer_params={"dfkv_cyclestore": { + "schema_version": 1, "operation_id": operation, + "scope_id": "s3-test", "cache_domain_id": "s3-test-domain", + "requested_ttl": "TTL_5M", + }}) + + +def settings(binary, root, addresses, request_dir=None): + return CycleShadowSettings( + controller_binary=Path(binary), address=addresses[0], + request_dir=Path(request_dir or Path(root) / "adapter-requests"), + retry_backoff_ms=30, replica_addresses=tuple(addresses)) + + +def fail_only_response_audit_files(): + original = Path.write_text + + def fail(path, data, *args, **kwargs): + if path.name.endswith(".response.json"): + raise OSError("injected response audit OSError") + return original(path, data, *args, **kwargs) + + return patch.object(Path, "write_text", autospec=True, side_effect=fail) + + +def make_operation(coordinator, operation_id, before_commit=None, now_ms=1_600_000): + req = input_request(f"{operation_id}-attempt", operation_id) + operation = coordinator.build_operation(req, 128, PAGE) + ready = coordinator.begin_or_replay(req.request_id, operation) + assert ready in (True, False) + assert coordinator.wait_for_idle(20) + coordinator.mark_evidence_ready( + req.request_id, "worker:0", operation["complete_pages"], + operation["complete_page_evidence_digest"], + put_completed_tokens=0, committed_complete_pages=0) + coordinator.on_prefill_executed( + req.request_id, SimpleNamespace( + num_prompt_tokens=128, num_cached_tokens=128, num_computed_tokens=0), + prefill_completed_at_ms=now_ms) + if before_commit is not None: + before_commit() + return req, operation + + +def drive_full_hit(coordinator, operation_id): + req, operation = make_operation(coordinator, operation_id) + assert coordinator.wait_for_idle(20) + op = coordinator._operations[coordinator._attempts[req.request_id]] + audit = {"lookup": op.lookup_response, "commit": op.commit_response} + return coordinator.request_finished(req.request_id), audit + + +def write_result(path, result): + path.write_text(json.dumps(result, sort_keys=True, indent=2) + "\n") + + +def restart_worker(binary, root, addresses, phase, request_dir): + coordinator = CycleShadowCoordinator( + settings(binary, root, addresses, request_dir), LAYOUT) + evidence_dir = Path(request_dir) + if phase == "recover": + first = json.loads((evidence_dir / "first-publication.json").read_text()) + frozen = coordinator.request_finished("restart-operation-attempt") + assert coordinator.wait_for_idle(20) + reconcile = coordinator.reconcile_snapshot("restart-operation-attempt") + assert frozen == first["publication"] + assert reconcile["late_applied"] is True + coordinator.close() + write_result(evidence_dir / "recovered.json", { + "publication": frozen, "reconcile": reconcile, + "original_operation_reopened": False, + }) + return + + client = coordinator.client + real_call = client.call + timeout_used = {"done": False} + + def timeout_first_commit(operation, request): + if operation == "commit" and not timeout_used["done"]: + timeout_used["done"] = True + client.settings = replace(client.settings, rpc_timeout_ms=1) + try: + # This remains an actual CycleStore_Stub invocation. Expiration + # kills only the owned CLI child; the raft command may still apply. + return real_call(operation, request) + finally: + client.settings = replace(client.settings, rpc_timeout_ms=15000) + return real_call(operation, request) + + client.call = timeout_first_commit + make_operation(coordinator, "restart-operation", now_ms=2_000_000) + deadline = time.monotonic() + 10 + while not timeout_used["done"]: + assert time.monotonic() < deadline, "lost-response injection was not exercised" + time.sleep(0.005) + # Wait until that first real attempt has returned transport unknown. + while True: + op = coordinator._operations[coordinator._attempts["restart-operation-attempt"]] + if op.commit_done: + break + frozen = coordinator.request_finished("restart-operation-attempt") + assert frozen["result"] == "degraded" + write_result(evidence_dir / "first-publication.json", {"publication": frozen}) + # Real process exit without close(): pending state and immutable original + # token/path/prefill survive for a fresh coordinator in phase=recover. + os._exit(0) + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--binary", required=True) + parser.add_argument("--root", required=True, type=Path) + parser.add_argument("--stage", choices=("main", "crash", "recover"), default="main") + parser.add_argument("--addresses", default="") + parser.add_argument("--request-dir", default="") + args = parser.parse_args() + binary = str(Path(args.binary).resolve()) + root = args.root.resolve() + if args.stage != "main": + restart_worker(binary, root, args.addresses.split(","), args.stage, + args.request_dir) + return 0 + if root.exists(): + print(f"FAIL: evidence root exists: {root}") + return 2 + root.parent.mkdir(parents=True, exist_ok=True) + cluster = BusinessCluster(binary, root) + try: + leader, _ = cluster.start_all() + addresses = list(cluster.addrs) + addresses.insert(0, addresses.pop(leader)) + cluster.set_clocks(1_600_000) + coordinator = CycleShadowCoordinator(settings(binary, root, addresses), LAYOUT) + observed = {} + with fail_only_response_audit_files(): + observed["positive"], positive_audit = drive_full_hit( + coordinator, "positive-audit") + assert observed["positive"]["result"] == "shadow_success" + assert positive_audit["lookup"].get("auditError") + assert positive_audit["commit"].get("auditError") + observed["negative"], _ = drive_full_hit(coordinator, "negative-audit") + assert observed["negative"]["result"] == "shadow_success" + negative_real_call = coordinator.client.call + advance_once = {"done": False} + + def advance_before_real_expire(operation, request): + if operation == "commit" and not advance_once["done"]: + advance_once["done"] = True + cluster.set_clocks(2_000_000) + return negative_real_call(operation, request) + + coordinator.client.call = advance_before_real_expire + expiring = make_operation(coordinator, "negative-final-audit") + del expiring + # The prefill occurred in a valid read window; accept now exceeds + # commit_not_after, making EXPIRED a genuine negative FINAL. + assert coordinator.wait_for_idle(20) + coordinator.client.call = negative_real_call + negative_op = coordinator._operations[ + coordinator._attempts["negative-final-audit-attempt"]] + negative = coordinator.request_finished("negative-final-audit-attempt") + assert negative["commit_projection"]["outcome"] == "EXPIRED" + assert negative["cycle_state"] == "deterministic_negative" + op = negative_op + assert op.commit_response.get("auditError") + observed["negative_final"] = negative + coordinator.client.settings = replace( + coordinator.client.settings, replica_addresses=()) + conflict = coordinator.client.call("commit", { + "token": copy.deepcopy(negative_op.token), + "path": copy.deepcopy(negative_op.operation["lookup_request"]["path"]), + "prefillCompletedAtMs": "2000000", + }) + assert conflict["receipt"]["outcome"] == "OPERATION_ID_CONFLICT" + with coordinator._condition: + coordinator._store_commit_locked(negative_op, conflict) + assert negative_op.reconciles[-1]["envelope_valid"] is True + observed["operation_id_conflict"] = conflict + + cluster.set_clocks(2_000_000) + client = coordinator.client + real_call = client.call + once = {"done": False} + + def timeout_first_late_commit(operation, request): + if operation == "commit" and not once["done"]: + once["done"] = True + client.settings = replace(client.settings, rpc_timeout_ms=1) + try: + return real_call(operation, request) + finally: + client.settings = replace(client.settings, rpc_timeout_ms=15000) + return real_call(operation, request) + + client.call = timeout_first_late_commit + make_operation(coordinator, "late-audit-success", now_ms=2_000_000) + late_op = coordinator._operations[ + coordinator._attempts["late-audit-success-attempt"]] + first = coordinator.request_finished("late-audit-success-attempt") + assert first["result"] == "degraded" + assert coordinator.wait_for_idle(20) + assert coordinator.request_finished("late-audit-success-attempt") == first + reconcile = coordinator.reconcile_snapshot("late-audit-success-attempt") + assert reconcile["late_applied"] is True + observed["late"] = {"first": first, "reconcile": reconcile} + assert late_op.commit_response.get("auditError") + coordinator.close() + + restart_dir = root / "restart-sidecar" + phase = subprocess.run([ + sys.executable, __file__, "--stage=crash", "--binary", binary, + "--root", str(root), "--addresses", ",".join(addresses), + "--request-dir", str(restart_dir), + ], text=True, capture_output=True, timeout=45) + (root / "restart-crash.stdout.log").write_text(phase.stdout + phase.stderr) + if phase.returncode != 0: + raise AssertionError(f"restart crash phase failed: {phase.stdout}{phase.stderr}") + phase = subprocess.run([ + sys.executable, __file__, "--stage=recover", "--binary", binary, + "--root", str(root), "--addresses", ",".join(addresses), + "--request-dir", str(restart_dir), + ], text=True, capture_output=True, timeout=45) + (root / "restart-recover.stdout.log").write_text(phase.stdout + phase.stderr) + if phase.returncode != 0: + raise AssertionError(f"restart recover phase failed: {phase.stdout}{phase.stderr}") + + result = { + "source_head": subprocess.check_output( + ["git", "-C", str(REPO), "rev-parse", "HEAD"], text=True).strip(), + "controller_sha256": hashlib.sha256(Path(binary).read_bytes()).hexdigest(), + "observed": observed, "restart": json.loads( + (restart_dir / "recovered.json").read_text()), + "real_cli_rpc": True, "mock_rpc": False, + } + write_result(root / "review-e2e-result.json", result) + print("PASS case=M3_lookup_positive_and_negative_FINAL_response_OSError preserved=True") + print("PASS case=M3_late_success_response_OSError original_reconcile=True") + print("PASS case=M4_real_timeout_then_success original_input_replay=True first_degraded_unchanged=True") + print("PASS case=M4_fresh_process_retry original_token_path_prefill=True late_applied=True") + print("PASS case=S2_real_operation_id_conflict zero_path_digest=accepted definite_negative=True") + print("SUMMARY PASS=5 SKIP=0 FAIL=0 TOTAL=5") + return 0 + finally: + cluster.cleanup() + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/integration/vllm/tests/test_cyclestore_shadow.py b/integration/vllm/tests/test_cyclestore_shadow.py new file mode 100644 index 00000000..b87ffe71 --- /dev/null +++ b/integration/vllm/tests/test_cyclestore_shadow.py @@ -0,0 +1,690 @@ +"""Synthetic, GPU-free CycleStore shadow adapter acceptance tests. + +The fake client below tests only adapter barriers/publication. It is never +used as evidence for the real brpc/braft scenarios; those live in +``cyclestore_shadow_e2e.py`` and invoke the S3 C++ ``CycleStore_Stub`` CLI. +""" + +from contextlib import contextmanager +import copy +import hashlib +import multiprocessing +from pathlib import Path +import shutil +import tempfile +import threading +import time +from types import SimpleNamespace +from unittest.mock import MagicMock + +import pytest + +from dfkv_vllm.cyclestore_shadow import ( + CycleShadowCoordinator, + CycleShadowSettings, + build_operation, + validate_publication, +) + + +LAYOUT = {"layout_digest": hashlib.sha256(b"single-full-attention-layout").hexdigest()} + + +class FakeCycleClient: + def __init__(self, *, lookup_gate=None, commit_gate=None): + self.lookup_gate = lookup_gate + self.commit_gate = commit_gate + self.lookup_calls = [] + self.commit_calls = [] + self.lookup_result = "OK" + self.commit_outcome = "ROOT_CYCLE_CREATED" + self.issued_at = 299_000 + self.accepted_at = 320_000 + self.generation = 1 + self.intent = "RENEW_OR_EXTEND" + self.alive_depth = 0 + self.new_nodes = 0 + self.receipt_logical = True + self.no_replication = False + self.transport_error = "RESULT_UNSPECIFIED" + self.commit_transport_results = [] + + def call(self, operation, request): + request = copy.deepcopy(request) + calls = self.lookup_calls if operation == "lookup" else self.commit_calls + calls.append(request) + if operation == "lookup": + if self.lookup_gate is not None: + assert self.lookup_gate.wait(5) + if self.lookup_result != "OK": + return {"result": self.lookup_result, "shadowOnly": True, + "noReplication": self.no_replication} + return { + "result": "OK", "token": {"canonicalPayload": "dG9rZW4=", + "tokenAuth": "YXV0aA==", "authKeyId": 1}, + "payload": {"issuedAtMs": str(self.issued_at), + "prefillNotAfterMs": str(self.issued_at + 1_000), + "commitNotAfterMs": str(self.issued_at + 121_000), + "readApplyIndex": "7", "readRootGeneration": "1", + "readRootExpireAtMs": "300000", + "readRootLockedTtl": "TTL_5M", + "canonicalPathDigest": request["path"]["canonicalPathDigest"], + "completePageEvidenceDigest": request["path"]["completePageEvidenceDigest"], + "familyIncarnation": "1", "dataEpoch": "1", + "intent": self.intent, "aliveDepth": self.alive_depth, + "requestedTtl": request["requestedTtl"]}, + "authoritativeNowMs": str(self.issued_at), + "shadowOnly": True, "noReplication": self.no_replication, + "transportError": self.transport_error, + } + if self.commit_gate is not None: + assert self.commit_gate.wait(5) + if self.commit_transport_results: + outcome = self.commit_transport_results.pop(0) + if outcome is not None: + return {"transportError": outcome, "shadowOnly": True, + "noReplication": False} + receipt = { + "outcome": self.commit_outcome, + "logicalCommitApplied": self.receipt_logical, + "billingEligibleForNewCycle": self.commit_outcome == "ROOT_CYCLE_CREATED", + "rootGeneration": str(self.generation), + "observedCurrentGeneration": "1", + "acceptedAtMs": str(self.accepted_at), + "applyIndex": "13", "lockedTtl": "TTL_5M", + "leaseExpireAtMs": str(self.accepted_at + 300_000) if self.receipt_logical else "0", + "newNodeCount": self.new_nodes, + "pathDigest": request["path"]["canonicalPathDigest"], + "receiptDigest": "cmVjZWlwdA==", + } + return {"receipt": receipt, "shadowOnly": True, + "noReplication": self.no_replication, + "transportError": self.transport_error, "receiptReplayed": False} + + +def _settings(client, contributors=("worker:0",), request_dir=None, **overrides): + return CycleShadowSettings( + controller_binary=Path("/unused/dfkv_cycle_controller"), + address="127.0.0.1:1", + request_dir=request_dir or Path(tempfile.mkdtemp(prefix="cyclestore-shadow-test-")), + required_contributors=frozenset(contributors), **overrides, + ) + + +@contextmanager +def _coordinator(client=None, contributors=("worker:0",), **overrides): + client = client or FakeCycleClient() + settings = _settings(client, contributors, **overrides) + coordinator = CycleShadowCoordinator( + settings, LAYOUT, client=client, wall_clock_ms=lambda: 321_000, + ) + try: + yield coordinator, client + finally: + try: + coordinator.close() + finally: + shutil.rmtree(settings.request_dir) + + +def _request(request_id="attempt-1", operation_id="operation-1", pages=2): + return SimpleNamespace( + request_id=request_id, num_prompt_tokens=pages * 64, + num_tokens=pages * 64, + block_hashes=[hashlib.sha256(f"page-{i}".encode()).digest() + for i in range(pages)], + kv_transfer_params={"dfkv_retention_ttl_s": 300, "dfkv_cyclestore": { + "schema_version": 1, "operation_id": operation_id, + "scope_id": "scope-a", "cache_domain_id": "domain-a", + "requested_ttl": "TTL_5M", + }}, + ) + + +def _admit(coordinator, request=None): + request = request or _request() + operation = coordinator.build_operation(request, 128, 64) + coordinator.begin_or_replay(request.request_id, operation) + assert coordinator.wait_for_idle() + return request, operation + + +def _ready(coordinator, request, operation, *, put_tokens=64, put_failed_tokens=0): + coordinator.mark_evidence_ready( + request.request_id, "worker:0", operation["complete_pages"], + operation["complete_page_evidence_digest"], + put_completed_tokens=put_tokens, + committed_complete_pages=put_tokens // 64, + put_failed_tokens=put_failed_tokens) + + +def _stats(prompt=128, cached=64): + return SimpleNamespace(num_prompt_tokens=prompt, num_cached_tokens=cached, + num_computed_tokens=prompt - cached, + num_local_cached_tokens=cached, + num_external_cached_tokens=0) + + +def test_off_is_default_and_never_constructs_a_client(): + assert CycleShadowSettings.from_extra_config({}) is None + assert CycleShadowSettings.from_extra_config( + {"cyclestore_shadow": {"mode": "off"}}) is None + + +def test_scheduler_full_l1_hit_still_looks_up_and_replays_one_operation(): + from dfkv_vllm.scheduler import DfkvStoreScheduler + + gate = threading.Event() + client = FakeCycleClient(lookup_gate=gate) + with _coordinator(client) as (coordinator, _): + scheduler = object.__new__(DfkvStoreScheduler) + scheduler._kv_events = False + scheduler._retention = {} + scheduler._failed_load_req_ids = set() + scheduler._request_trackers = {} + scheduler.load_specs = {} + scheduler.lookup_async = False + scheduler.load_async = False + scheduler.request_level_loads = False + scheduler.kv_role = "kv_both" + scheduler._block_size = 64 + scheduler._hash_block_size = 64 + scheduler._partial_hash_hits = False + scheduler.cyclestore_shadow = coordinator + physical_calls = [] + + def physical_lookup(request_id, token_len, hashes, non_block=False, + retain_ttl_s=0): + physical_calls.append((token_len, retain_ttl_s)) + return token_len, 300 + + scheduler.client = SimpleNamespace( + lookup=physical_lookup, discard=lambda _request_id: None) + request = _request() + + assert scheduler.get_num_new_matched_tokens(request, 64) == (None, False) + # A repeated poll while the first RPC is pending cannot issue a new op. + assert scheduler.get_num_new_matched_tokens(request, 64) == (None, False) + gate.set() + assert coordinator.wait_for_idle() + assert scheduler.get_num_new_matched_tokens(request, 64) == (0, False) + assert scheduler.get_num_new_matched_tokens(request, 64) == (0, False) + assert len(client.lookup_calls) == 1 + assert scheduler.load_specs == {} + assert scheduler._retention["attempt-1"] == (300, 300, 64) + + _delay, params = scheduler.request_finished(request, ([],)) + assert params["dfkv_cache_usage"] == { + "cached_tokens": 64, "cache_write_tokens": 64, "applied_ttl_s": 300} + assert params["dfkv_cyclestore_shadow"]["cycle_state"] == "unknown" + + +def test_commit_waits_for_prefill_and_full_evidence_then_runs_once(): + with _coordinator() as (coordinator, client): + request, operation = _admit(coordinator) + _ready(coordinator, request, operation) + assert client.commit_calls == [] + coordinator.on_prefill_executed( + request.request_id, _stats(), prefill_completed_at_ms=299_500) + assert coordinator.wait_for_idle() + assert len(client.commit_calls) == 1 + # Duplicate core notification with identical fixed evidence is idempotent. + coordinator.on_prefill_executed( + request.request_id, _stats(), prefill_completed_at_ms=299_500) + first = coordinator.request_finished(request.request_id) + second = coordinator.request_finished(request.request_id) + assert first == second + assert first["result"] == "shadow_success" + assert first["lookup_projection"]["read_at_ms"] == 299_000 + assert first["prefill_completed_at_ms"] == 299_500 + assert first["commit_projection"]["accepted_at_ms"] == 320_000 + assert len(client.commit_calls) == 1 + + +def test_request_finished_never_substitutes_for_missing_prefill_barrier(): + with _coordinator() as (coordinator, client): + request, operation = _admit(coordinator) + _ready(coordinator, request, operation) + envelope = coordinator.request_finished(request.request_id) + assert envelope["result"] == "degraded" + assert envelope["cycle_state"] == "unknown" + assert client.commit_calls == [] + + +def test_late_legal_renewal_uses_299_read_320_apply_not_local_clock(): + with _coordinator() as (coordinator, client): + client.commit_outcome = "RENEWED" + request, operation = _admit(coordinator) + _ready(coordinator, request, operation) + coordinator.on_prefill_executed( + request.request_id, _stats(), prefill_completed_at_ms=299_500) + assert coordinator.wait_for_idle() + envelope = coordinator.request_finished(request.request_id) + assert envelope["result"] == "shadow_success" + assert envelope["commit_projection"]["outcome"] == "RENEWED" + assert envelope["commit_projection"]["billing_eligible_for_new_cycle"] is False + assert client.commit_calls[0]["prefillCompletedAtMs"] == "299500" + assert client.commit_calls[0]["token"]["canonicalPayload"] == "dG9rZW4=" + validate_publication(envelope) + + +def test_expired_root_creates_next_root_without_changing_physical_hit(): + with _coordinator() as (coordinator, client): + client.issued_at = 1_400_000 + client.accepted_at = 1_400_100 + client.generation = 2 + client.intent = "CREATE_NEXT_ROOT" + client.alive_depth = -1 + client.new_nodes = 0 + request, operation = _admit(coordinator) + _ready(coordinator, request, operation) + coordinator.on_prefill_executed( + request.request_id, _stats(), prefill_completed_at_ms=1_400_050) + assert coordinator.wait_for_idle() + envelope = coordinator.request_finished(request.request_id) + assert envelope["commit_projection"]["outcome"] == "ROOT_CYCLE_CREATED" + assert envelope["commit_projection"]["root_generation"] == 2 + assert envelope["physical"]["cached_tokens"] == 64 + assert envelope["shadow_usage"]["cached_tokens"] == 0 + assert envelope["shadow_usage"]["cache_write_tokens"] == 0 + validate_publication(envelope) + + +def test_degraded_transport_preserves_physical_result_and_unknown_state(): + from dfkv_vllm.scheduler import DfkvStoreScheduler + + client = FakeCycleClient() + client.lookup_result = "UNAVAILABLE" + with _coordinator(client) as (coordinator, _): + scheduler = object.__new__(DfkvStoreScheduler) + scheduler._kv_events = False + scheduler._retention = {} + scheduler._failed_load_req_ids = set() + scheduler._request_trackers = {} + scheduler.load_specs = {} + scheduler.lookup_async = False + scheduler.load_async = False + scheduler.request_level_loads = False + scheduler.kv_role = "kv_both" + scheduler._block_size = 64 + scheduler._hash_block_size = 64 + scheduler._partial_hash_hits = False + scheduler.cyclestore_shadow = coordinator + scheduler.client = SimpleNamespace( + lookup=lambda *args, **kwargs: (64, 300), discard=lambda _r: None) + request = _request() + assert scheduler.get_num_new_matched_tokens(request, 0) in ( + (None, False), (64, False)) + assert coordinator.wait_for_idle() + # A transport-unavailable publication permits the unchanged physical + # result on the next replay; it never turns into logical expiry. + assert scheduler.get_num_new_matched_tokens(request, 0) == (64, False) + assert scheduler._retention["attempt-1"] == (300, 300, 64) + envelope = coordinator.request_finished(request.request_id) + assert envelope["result"] == "degraded" + assert envelope["reason"] == "UNAVAILABLE" + assert envelope["cycle_state"] == "unknown" + assert envelope["shadow_usage"]["cached_tokens"] is None + + +def test_late_applied_never_rewrites_first_degraded_publication(): + commit_gate = threading.Event() + client = FakeCycleClient(commit_gate=commit_gate) + with _coordinator(client) as (coordinator, _): + request, operation = _admit(coordinator) + _ready(coordinator, request, operation) + coordinator.on_prefill_executed( + request.request_id, _stats(), prefill_completed_at_ms=299_500) + deadline = threading.Event() + # Wait until the real executor entered its original Commit. + while not client.commit_calls: + deadline.wait(0.005) + frozen = coordinator.request_finished(request.request_id) + assert frozen["result"] == "degraded" + assert frozen["reason"] == "commit_in_flight" + original = copy.deepcopy(frozen) + commit_gate.set() + assert coordinator.wait_for_idle() + assert coordinator.request_finished(request.request_id) == original + reconcile = coordinator.reconcile_snapshot(request.request_id) + assert reconcile["late_applied"] is True + assert reconcile["reconciles"][0]["accepted_at_ms"] == 320_000 + + +def test_stale_incarnation_token_is_deterministic_negative_not_expired_unknown(): + with _coordinator() as (coordinator, client): + client.commit_outcome = "STALE_LOOKUP_TOKEN" + client.receipt_logical = False + request, operation = _admit(coordinator) + _ready(coordinator, request, operation) + coordinator.on_prefill_executed( + request.request_id, _stats(), prefill_completed_at_ms=299_500) + assert coordinator.wait_for_idle() + envelope = coordinator.request_finished(request.request_id) + assert envelope["result"] == "degraded" + assert envelope["cycle_state"] == "deterministic_negative" + assert envelope["reason"] == "STALE_LOOKUP_TOKEN" + assert envelope["commit_projection"]["logical_commit_applied"] is False + + +def test_missing_rank_or_kda_contributor_cannot_commit_or_become_expired(): + with _coordinator(contributors=("tp:0", "kda:0")) as (coordinator, client): + request, operation = _admit(coordinator) + coordinator.mark_evidence_ready( + request.request_id, "tp:0", operation["complete_pages"], + operation["complete_page_evidence_digest"], + put_completed_tokens=64, committed_complete_pages=1) + coordinator.on_prefill_executed( + request.request_id, _stats(), prefill_completed_at_ms=299_500) + assert client.commit_calls == [] + envelope = coordinator.request_finished(request.request_id) + assert envelope["cycle_state"] == "unknown" + assert envelope["reason"] != "EXPIRED" + + +def test_expired_prefill_deadline_never_starts_commit_or_substitutes_operation(): + with _coordinator() as (coordinator, client): + request, operation = _admit(coordinator) + _ready(coordinator, request, operation) + coordinator.on_prefill_executed( + request.request_id, _stats(), prefill_completed_at_ms=300_001) + assert client.commit_calls == [] + envelope = coordinator.request_finished(request.request_id) + assert envelope["reason"] == "expired_prefill_window" + assert envelope["operation_id"] == "operation-1" + + +def test_usage_integrity_rejects_page_token_mix_and_arithmetic_regression(): + with _coordinator() as (coordinator, _): + request, operation = _admit(coordinator) + _ready(coordinator, request, operation) + coordinator.on_prefill_executed( + request.request_id, _stats(), prefill_completed_at_ms=299_500) + assert coordinator.wait_for_idle() + envelope = coordinator.request_finished(request.request_id) + boundary = copy.deepcopy(envelope) + validate_publication(envelope, boundary) + bad = copy.deepcopy(envelope) + bad["shadow_usage"]["uncached_tokens"] += 64 + with pytest.raises(ValueError, match="P != C'"): + validate_publication(bad) + bad = copy.deepcopy(envelope) + bad["physical"]["computed_tokens"] = -1 + with pytest.raises(ValueError, match="computed_tokens"): + validate_publication(bad) + bad = copy.deepcopy(envelope) + bad["physical"]["cached_tokens"] += 64 + with pytest.raises(ValueError, match="P != C"): + validate_publication(bad, boundary) + + +def test_operation_envelope_has_no_token_or_local_accepted_time_substitute(): + request = _request() + operation = build_operation(request, token_len=128, alignment_tokens=64, + layout=LAYOUT) + encoded = str(operation) + assert "canonicalPayload" not in encoded + assert operation["lookup_request"]["operationId"] == "operation-1" + assert operation["lookup_request"]["path"]["canonicalPathDigest"] + assert operation["lookup_request"]["path"]["completePageEvidenceDigest"] + + +def test_nonreplicated_lookup_and_commit_cannot_publish_applied(): + client = FakeCycleClient() + client.no_replication = True + with _coordinator(client) as (coordinator, _): + request, _operation = _admit(coordinator) + envelope = coordinator.request_finished(request.request_id) + assert envelope["result"] == "degraded" + assert envelope["reason"] == "invalid_replication_evidence" + assert envelope["cycle_state"] == "unknown" + + client = FakeCycleClient() + with _coordinator(client) as (coordinator, _): + request, operation = _admit(coordinator) + client.no_replication = True + _ready(coordinator, request, operation) + coordinator.on_prefill_executed( + request.request_id, _stats(), prefill_completed_at_ms=299_500) + assert coordinator.wait_for_idle() + envelope = coordinator.request_finished(request.request_id) + assert envelope["result"] == "degraded" + assert envelope["reason"] == "invalid_commit_envelope" + assert envelope["cycle_state"] == "unknown" + assert envelope["commit_projection"]["logical_commit_applied"] is False + assert envelope["commit_projection"]["envelope_valid"] is False + + +def test_contradictory_transport_and_receipt_is_unknown(): + client = FakeCycleClient() + with _coordinator(client) as (coordinator, _): + request, operation = _admit(coordinator) + client.transport_error = "UNAVAILABLE" + _ready(coordinator, request, operation) + coordinator.on_prefill_executed( + request.request_id, _stats(), prefill_completed_at_ms=299_500) + assert coordinator.wait_for_idle() + op = coordinator._operations[coordinator._attempts[request.request_id]] + assert op.commit_response["transportError"] == "UNAVAILABLE" + assert "clientError" not in op.commit_response + envelope = coordinator.request_finished(request.request_id) + assert envelope["result"] == "degraded" + assert envelope["reason"] == "invalid_commit_envelope" + assert envelope["cycle_state"] == "unknown" + assert envelope["commit_projection"]["transport_error"] == "UNAVAILABLE" + assert envelope["commit_projection"]["logical_commit_applied"] is False + assert len(client.commit_calls) == 1 + + +def test_duplicate_scheduler_prefill_keeps_first_timestamp_without_degrading(): + from dfkv_vllm.scheduler import DfkvStoreScheduler + + with _coordinator() as (coordinator, client): + request, operation = _admit(coordinator) + times = iter((299_500, 299_800)) + coordinator._wall_clock_ms = lambda: next(times, 300_000) + scheduler = object.__new__(DfkvStoreScheduler) + scheduler.cyclestore_shadow = coordinator + scheduler.kv_role = "kv_both" + scheduler.on_prefill_executed(request, _stats()) + scheduler.on_prefill_executed(request, _stats()) + op_key = (operation["scope_id"], operation["cache_domain_id"], + operation["family_root_hash"], operation["operation_id"]) + assert coordinator._operations[op_key].prefill_completed_at_ms == 299_500 + _ready(coordinator, request, operation) + assert coordinator.wait_for_idle() + assert len(client.commit_calls) == 1 + assert client.commit_calls[0]["prefillCompletedAtMs"] == "299500" + assert coordinator.request_finished(request.request_id)["result"] == "shadow_success" + + +def test_identical_evidence_replay_after_commit_is_a_noop(): + with _coordinator() as (coordinator, client): + request, operation = _admit(coordinator) + _ready(coordinator, request, operation) + coordinator.on_prefill_executed( + request.request_id, _stats(), prefill_completed_at_ms=299_500) + assert coordinator.wait_for_idle() + _ready(coordinator, request, operation) + assert len(client.commit_calls) == 1 + assert coordinator.request_finished(request.request_id)["result"] == "shadow_success" + + +def test_finished_operations_reclaim_large_state_and_replay_durable_publications(): + publications = {} + with _coordinator(queue_capacity=1) as (coordinator, _): + for index in range(18): + req = _request(f"attempt-{index}", f"operation-{index}") + request, operation = _admit(coordinator, req) + _ready(coordinator, request, operation) + coordinator.on_prefill_executed( + request.request_id, _stats(), prefill_completed_at_ms=299_500) + assert coordinator.wait_for_idle() + publications[request.request_id] = coordinator.request_finished(request.request_id) + assert coordinator._operations == {} + assert coordinator._attempts == {} + assert len(coordinator._finished) <= 16 + assert len(list(coordinator._publication_dir.glob("*.json"))) == 18 + for attempt_id, expected in publications.items(): + assert coordinator.request_finished(attempt_id) == expected + + +def test_close_with_full_queue_signals_and_joins_worker(): + gate = threading.Event() + client = FakeCycleClient(lookup_gate=gate) + with _coordinator(client, queue_capacity=1) as (coordinator, _): + first = _request("close-0", "close-op-0") + first_op = coordinator.build_operation(first, 128, 64) + coordinator.begin_or_replay(first.request_id, first_op) + second = _request("close-1", "close-op-1") + second_op = coordinator.build_operation(second, 128, 64) + coordinator.begin_or_replay(second.request_id, second_op) + while not client.lookup_calls: + time.sleep(0.001) + closer = threading.Thread(target=coordinator.close) + closer.start() + assert closer.is_alive() + gate.set() + closer.join(5) + assert not closer.is_alive() + assert len(client.lookup_calls) == 1 + + +def test_publication_budget_freezes_unknown_without_a_new_operation(): + gate = threading.Event() + client = FakeCycleClient(lookup_gate=gate) + with _coordinator(client, publication_budget_ms=1) as (coordinator, _): + request = _request() + operation = coordinator.build_operation(request, 128, 64) + coordinator.begin_or_replay(request.request_id, operation) + time.sleep(0.005) + assert coordinator.begin_or_replay(request.request_id, operation) is True + gate.set() + assert coordinator.wait_for_idle() + envelope = coordinator.request_finished(request.request_id) + assert envelope["reason"] == "publication_budget_exceeded" + assert envelope["operation_id"] == "operation-1" + assert len(client.lookup_calls) == 1 + + +def test_late_reconcile_before_first_finish_survives_reclaim(): + with _coordinator() as (coordinator, _): + request, operation = _admit(coordinator) + _ready(coordinator, request, operation) + coordinator.on_prefill_executed( + request.request_id, _stats(), prefill_completed_at_ms=299_500) + assert coordinator.wait_for_idle() + # Simulate an externally reconciled late receipt arriving before the + # first finish/publication snapshot, then reclaim that operation. + op = coordinator._operations[(operation["scope_id"], operation["cache_domain_id"], + operation["family_root_hash"], operation["operation_id"])] + op.late_applied = True + op.reconciles.append({"logical_commit_applied": True, "accepted_at_ms": 320_000}) + envelope = coordinator.request_finished(request.request_id) + assert envelope["result"] == "shadow_success" + assert coordinator._operations == {} + reconcile = coordinator.reconcile_snapshot(request.request_id) + assert reconcile["late_applied"] is True + assert reconcile["reconciles"][0]["accepted_at_ms"] == 320_000 + + +def test_shared_attempt_journal_reload_keeps_original_publication_identity(): + with _coordinator() as (coordinator, _): + first = _request("shared-a", "operation-1") + request, operation = _admit(coordinator, first) + second = _request("shared-b", "operation-1") + second_operation = coordinator.build_operation(second, 128, 64) + coordinator.begin_or_replay(second.request_id, second_operation) + _ready(coordinator, request, operation) + coordinator.on_prefill_executed( + request.request_id, _stats(), prefill_completed_at_ms=299_500) + assert coordinator.wait_for_idle() + expected = coordinator.request_finished(first.request_id) + assert coordinator.request_finished(second.request_id) == expected + assert coordinator._operations == {} + coordinator._finished.clear() # force both per-handle journal reloads + assert coordinator.request_finished(first.request_id) == expected + assert coordinator.request_finished(second.request_id) == expected + assert coordinator._finished_attempts == set() + + +def test_corrupt_journal_does_not_rewrite_commit_or_late_reconcile(): + gate = threading.Event() + client = FakeCycleClient(commit_gate=gate) + with _coordinator(client) as (coordinator, _): + request, operation = _admit(coordinator) + _ready(coordinator, request, operation) + coordinator.on_prefill_executed( + request.request_id, _stats(), prefill_completed_at_ms=299_500) + while not client.commit_calls: + time.sleep(0.001) + envelope = coordinator.request_finished(request.request_id) + assert envelope["reason"] == "commit_in_flight" + coordinator._publication_path(request.request_id).write_text("not-json") + coordinator._finished.clear() + gate.set() + assert coordinator.wait_for_idle() + # Valid committed response is not overwritten by journal decode errors. + assert coordinator.reconcile_snapshot(request.request_id)["late_applied"] is True + assert coordinator.request_finished(request.request_id) == envelope + + +def test_contradictory_lookup_transport_and_token_is_unknown(): + client = FakeCycleClient() + client.transport_error = "UNAVAILABLE" + with _coordinator(client) as (coordinator, _): + request, _operation = _admit(coordinator) + envelope = coordinator.request_finished(request.request_id) + assert envelope["reason"] == "invalid_lookup_envelope" + assert envelope["cycle_state"] == "unknown" + assert envelope["lookup_projection"] is None + assert client.commit_calls == [] + + +def test_pr1_requested_ttl_is_validated_and_projected_not_defaulted(): + with _coordinator() as (coordinator, _): + request, operation = _admit(coordinator) + _ready(coordinator, request, operation) + coordinator.on_prefill_executed( + request.request_id, _stats(), prefill_completed_at_ms=299_500) + assert coordinator.wait_for_idle() + envelope = coordinator.request_finished(request.request_id) + assert envelope["lookup_projection"]["requested_ttl"] == "TTL_5M" + assert envelope["lookup_projection"]["requested_ttl"] != "TTL_UNSPECIFIED" + assert envelope["evidence_mode"] == "full_evidence" + + +def test_pr1_requested_ttl_mismatch_cannot_be_reissued_as_valid_token(): + client = FakeCycleClient() + + def wrong_ttl(operation, request): + response = FakeCycleClient.call(client, operation, request) + if operation == "lookup": + response["payload"]["requestedTtl"] = "TTL_UNSPECIFIED" + return response + + client.call = wrong_ttl + with _coordinator(client) as (coordinator, _): + request, _operation = _admit(coordinator) + envelope = coordinator.request_finished(request.request_id) + assert envelope["reason"] == "invalid_lookup_snapshot" + assert envelope["cycle_state"] == "unknown" + assert envelope["lookup_projection"] is None + + +def test_clock_outcome_inside_receipt_is_unknown_not_definite_expired(): + client = FakeCycleClient() + with _coordinator(client) as (coordinator, _): + request, operation = _admit(coordinator) + client.commit_outcome = "CLOCK_UNAVAILABLE" + client.receipt_logical = False + _ready(coordinator, request, operation) + coordinator.on_prefill_executed( + request.request_id, _stats(), prefill_completed_at_ms=299_500) + assert coordinator.wait_for_idle() + envelope = coordinator.request_finished(request.request_id) + assert envelope["result"] == "degraded" + assert envelope["reason"] != "EXPIRED" + assert envelope["cycle_state"] == "unknown" + assert envelope["commit_projection"]["logical_commit_applied"] is False + assert envelope["commit_projection"]["envelope_valid"] is False diff --git a/integration/vllm/tests/test_cyclestore_shadow_reviewfix.py b/integration/vllm/tests/test_cyclestore_shadow_reviewfix.py new file mode 100644 index 00000000..077ba460 --- /dev/null +++ b/integration/vllm/tests/test_cyclestore_shadow_reviewfix.py @@ -0,0 +1,841 @@ +"""Independent adapter M1–M6 and review-should S1/S2/S3/S6 regressions.""" + +import copy +import multiprocessing +from pathlib import Path +import shutil +import tempfile +import threading +import types +from types import SimpleNamespace +import time +from unittest.mock import MagicMock + +import pytest + +from dfkv_vllm.cyclestore_shadow import ( + CycleShadowCoordinator, build_operation, forward_prefill_executed, + validate_publication) +from test_cyclestore_shadow import ( + FakeCycleClient, LAYOUT, _admit, _coordinator, _ready, _request, + _settings, _stats) + + +def _with_actual_companion_hook(multi): + """Mark native support or inject the exact, already-reviewed forwarder. + + The second branch is a test-only optional compatible wrapper, not an + upstream-feature assertion: 09accb543's hook is a three-line fan-out over + existing ``_connectors`` children. Its presence and injection source are + made explicit in the case metadata/checks rather than hidden by a mock core. + """ + if getattr(multi, "on_prefill_executed", None) is not None: + return "native-companion-hook" + def forward(self, request, prefill_stats): + for connector in self._connectors: + connector.on_prefill_executed(request, prefill_stats) + multi.on_prefill_executed = types.MethodType(forward, multi) + return "test-injected-companion-09accb543" + + +def test_m1_multi_forwards_prefill_to_nonpreferred_dfkv_without_save(): + from dfkv_vllm.connector import DfkvStoreConnector + from dfkv_vllm.scheduler import DfkvStoreScheduler + from vllm.distributed.kv_transfer.kv_connector.v1.multi_connector import MultiConnector + + client = FakeCycleClient() + client.commit_outcome = "RENEWED" + with _coordinator(client) as (coordinator, _): + scheduler = object.__new__(DfkvStoreScheduler) + scheduler.kv_role = "kv_both" + scheduler._failed_load_req_ids = set() + scheduler.load_specs = {} + scheduler._retention = {} + scheduler._partial_hash_hits = False + scheduler._manager_groups = False + scheduler._block_size = scheduler._hash_block_size = 64 + scheduler.lookup_async = scheduler.load_async = False + scheduler.request_level_loads = False + scheduler.cyclestore_shadow = coordinator + scheduler.client = SimpleNamespace( + lookup=lambda *args, **kwargs: (0, 0), discard=lambda _r: None) + connector = object.__new__(DfkvStoreConnector) + connector._shutdown_condition = threading.Condition() + connector._inflight_calls = 0 + connector._shutdown = False + connector.connector_scheduler = scheduler + preferred = MagicMock() + multi = object.__new__(MultiConnector) + multi._connectors = [preferred, connector] + request = _request() + assert scheduler.get_num_new_matched_tokens(request, 64) in ((0, False), (None, False)) + assert coordinator.wait_for_idle() + assert scheduler.get_num_new_matched_tokens(request, 64) == (0, False) + assert scheduler.load_specs == {} + assert preferred.on_prefill_executed.call_count == 0 + + coordinator._wall_clock_ms = lambda: 299_500 + support_environment = _with_actual_companion_hook(multi) + assert support_environment in ( + "native-companion-hook", "test-injected-companion-09accb543") + assert forward_prefill_executed(multi, request, _stats()) is True + preferred.on_prefill_executed.assert_called_once() + op = coordinator._operations[coordinator._attempts[request.request_id]] + scheduler.mark_cyclestore_evidence_ready( + request.request_id, "worker:0", op.operation["complete_pages"], + op.operation["complete_page_evidence_digest"], + put_completed_tokens=0, committed_complete_pages=0) + assert coordinator.wait_for_idle() + assert len(client.commit_calls) == 1 + assert coordinator.request_finished(request.request_id)["result"] == "shadow_success" + + +def test_upstream_missing_multi_hook_is_explicitly_unsupported_not_commit(monkeypatch): + from _cache_api import cache_group, full_attention_spec + from dfkv_vllm import scheduler as scheduler_module + import torch + from vllm.config import CacheConfig + from vllm.v1.kv_cache_interface import KVCacheConfig + + # Exercise real DfkvStoreScheduler construction and admission, rather than + # merely calling the guard helper directly. Legacy has no method; an explicit + # None-valued override produces the same shape on a companion-equipped core. + from vllm.distributed.kv_transfer.kv_connector.v1.multi_connector import MultiConnector + if getattr(MultiConnector, "on_prefill_executed", None) is not None: + monkeypatch.setattr(MultiConnector, "on_prefill_executed", None) + monkeypatch.setattr( + scheduler_module, "LookupKeyClient", + lambda _config: SimpleNamespace( + lookup=lambda *args, **kwargs: (0, 0), + discard=lambda _request_id: None, + ), + ) + monkeypatch.setenv("PYTHONHASHSEED", "0") + vllm_config = SimpleNamespace( + parallel_config=SimpleNamespace(decode_context_parallel_size=1), + cache_config=CacheConfig( + block_size=64, prefix_caching_hash_algo="sha256"), + kv_transfer_config=SimpleNamespace( + kv_connector="MultiConnector", kv_role="kv_both", + kv_connector_extra_config={"load_async": False}, + ), + kv_events_config=None, num_hash_lookahead_tokens=0, + ) + spec = full_attention_spec( + block_size=64, num_kv_heads=1, head_size=8, dtype=torch.bfloat16) + kv_cache_config = KVCacheConfig( + num_blocks=8, kv_cache_tensors=[], + kv_cache_groups=[cache_group(["layer"], spec)], + ) + with _coordinator() as (coordinator, client): + scheduler = scheduler_module.DfkvStoreScheduler(vllm_config, kv_cache_config) + scheduler.cyclestore_shadow = coordinator + request = _request() + first = scheduler.get_num_new_matched_tokens(request, 64) + assert first in ((0, False), (None, False)) + assert coordinator.wait_for_idle() + if first[0] is None: + assert scheduler.get_num_new_matched_tokens(request, 64) == (0, False) + envelope = coordinator.request_finished(request.request_id) + assert scheduler._prefill_hook_unavailable is True + assert envelope["reason"] == "unsupported_prefill_hook" + assert envelope["cycle_state"] == "unknown" + assert client.commit_calls == [] + assert envelope["commit_projection"] is None + + +def _build_actual_multi_parent(monkeypatch): + from _cache_api import cache_group, full_attention_spec + from dfkv_vllm import scheduler as scheduler_module + from dfkv_vllm.cyclestore_multi_connector import DfkvMultiConnector + import torch + from vllm.distributed.kv_transfer.kv_connector.v1 import KVConnectorRole + from vllm.config import CacheConfig + from vllm.v1.kv_cache_interface import KVCacheConfig + + # Do not hand-set either parent or child method: use actual factory/wrapper + # config. The dfkv child still receives its own connector name. + monkeypatch.setattr( + scheduler_module, "LookupKeyClient", + lambda _config: SimpleNamespace( + lookup=lambda *args, **kwargs: (0, 0), + discard=lambda _request_id: None, + ), + ) + monkeypatch.setenv("PYTHONHASHSEED", "0") + nested = [{"kv_connector": "MockConnector", "kv_role": "kv_both"}, + {"kv_connector": "DfkvStoreConnector", "kv_role": "kv_both", + "kv_connector_module_path": "dfkv_vllm.connector"}] + outer_config = { + "kv_connector": "MultiConnector", + "kv_role": "kv_both", + "kv_connector_extra_config": {"connectors": nested}, + } + from vllm.config import KVTransferConfig + outer = KVTransferConfig(**outer_config) + from vllm.distributed.kv_transfer.kv_connector.factory import KVConnectorFactory + from tests.v1.kv_connector.unit import test_multi_connector as mock_module + del mock_module # register built-in MockConnector through this import + from dfkv_vllm.cyclestore_multi_connector import apply_prefill_hook_support + del apply_prefill_hook_support + from dfkv_vllm.connector import DfkvStoreConnector + del DfkvStoreConnector + config = SimpleNamespace( + cache_config=CacheConfig(block_size=64, prefix_caching_hash_algo="sha256"), + parallel_config=SimpleNamespace(decode_context_parallel_size=1), + scheduler_config=SimpleNamespace(disable_hybrid_kv_cache_manager=True), + kv_transfer_config=outer, kv_events_config=None, + num_hash_lookahead_tokens=0, + ) + spec = full_attention_spec( + block_size=64, num_kv_heads=1, head_size=8, dtype=torch.bfloat16) + kv_cache_config = KVCacheConfig( + num_blocks=8, kv_cache_tensors=[], + kv_cache_groups=[cache_group(["layer"], spec)], + ) + return DfkvMultiConnector(config, KVConnectorRole.SCHEDULER, kv_cache_config) + + +@pytest.mark.parametrize("missing", [True, False]) +def test_actual_parent_wrapper_propagates_prefill_support(monkeypatch, missing): + from vllm.distributed.kv_transfer.kv_connector.v1.multi_connector import MultiConnector + if missing: + monkeypatch.setattr(MultiConnector, "on_prefill_executed", None, + raising=False) + parent = _build_actual_multi_parent(monkeypatch) + if not missing: + # A documented, real forwarder—not an upstream presence assumption. + support_environment = _with_actual_companion_hook(parent) + from dfkv_vllm.cyclestore_multi_connector import apply_prefill_hook_support + apply_prefill_hook_support(parent) + assert support_environment in ( + "native-companion-hook", "test-injected-companion-09accb543") + dfkv_child = parent._connectors[-1] + assert dfkv_child._kv_transfer_config.kv_connector == "DfkvStoreConnector" + scheduler = dfkv_child.connector_scheduler + assert scheduler._prefill_hook_unavailable is missing + coordinator = scheduler.cyclestore_shadow + if missing: + # No real class/socket/model: actual coordinator hook evidence only. + with _coordinator() as (shadow, client): + scheduler.cyclestore_shadow = shadow + first = scheduler.get_num_new_matched_tokens(_request(), 64) + assert first in ((0, False), (None, False)) + if first[0] is None: + early = shadow.request_finished("attempt-1") + assert early["reason"] == "unsupported_prefill_hook" + assert shadow.wait_for_idle() + if first[0] is None: + assert scheduler.get_num_new_matched_tokens(_request(), 64) == (0, False) + assert shadow.request_finished("attempt-1")["reason"] == "unsupported_prefill_hook" + assert client.commit_calls == [] + else: + assert coordinator is None + + +def test_direct_connector_prefill_hook_stays_noop_not_missing(): + class DirectNoop: + calls = 0 + def on_prefill_executed(self, _request, _stats): + self.calls += 1 + + direct = DirectNoop() + request = _request() + assert forward_prefill_executed(direct, request, _stats()) is True + assert direct.calls == 1 + + +def test_legacy_absent_connector_name_preserves_existing_retain(monkeypatch): + from _cache_api import cache_group, full_attention_spec + from dfkv_vllm import scheduler as scheduler_module + import torch + from vllm.config import CacheConfig + from vllm.v1.kv_cache_interface import KVCacheConfig + + monkeypatch.setattr( + scheduler_module, "LookupKeyClient", + lambda _config: SimpleNamespace( + lookup=lambda *args, **kwargs: (64, 300), + discard=lambda _request_id: None, + ), + ) + monkeypatch.setenv("PYTHONHASHSEED", "0") + vllm_config = SimpleNamespace( + parallel_config=SimpleNamespace(decode_context_parallel_size=1), + cache_config=CacheConfig(block_size=64, prefix_caching_hash_algo="sha256"), + # Legacy fixtures carry roles and extras, not kv_connector by name. + kv_transfer_config=SimpleNamespace( + kv_role="kv_both", kv_connector_extra_config={"load_async": False}), + kv_events_config=None, num_hash_lookahead_tokens=0, + ) + spec = full_attention_spec( + block_size=64, num_kv_heads=1, head_size=8, dtype=torch.bfloat16) + groups = [cache_group(["layer"], spec)] + kv_cache_config = KVCacheConfig( + num_blocks=8, kv_cache_tensors=[], kv_cache_groups=groups) + with _coordinator() as (shadow, _): + scheduler = scheduler_module.DfkvStoreScheduler(vllm_config, kv_cache_config) + scheduler.cyclestore_shadow = shadow + assert scheduler._prefill_hook_unavailable is False + request = _request() + first = scheduler.get_num_new_matched_tokens(request, 0) + assert first in ((None, False), (64, False)) + assert shadow.wait_for_idle() + if first[0] is None: + assert scheduler.get_num_new_matched_tokens(request, 0) == (64, False) + assert scheduler._retention["attempt-1"] == (300, 300, 64) + assert len(scheduler.load_specs) == 1 + + +def test_m2_restart_id_reuse_rejects_before_rpc_and_same_operation_replays(): + with tempfile.TemporaryDirectory(prefix="cyclestore-m2-restart-") as root: + root_path = Path(root) + client = FakeCycleClient() + coordinator = CycleShadowCoordinator( + _settings(client, request_dir=root_path), LAYOUT, client=client) + request, operation = _admit(coordinator) + _ready(coordinator, request, operation) + coordinator.on_prefill_executed(request.request_id, _stats(), prefill_completed_at_ms=299_500) + assert coordinator.wait_for_idle() + expected = coordinator.request_finished(request.request_id) + coordinator.close() + + other = _request(request.request_id, "different-operation") + other_operation = build_operation(other, token_len=128, alignment_tokens=64, layout=LAYOUT) + restarted_client = FakeCycleClient() + restarted = CycleShadowCoordinator( + _settings(restarted_client, request_dir=root_path), LAYOUT, client=restarted_client) + try: + assert restarted.begin_or_replay(request.request_id, other_operation) is True + conflict = restarted.request_finished(request.request_id) + assert conflict["reason"] == "journal_operation_identity_conflict" + assert conflict["operation_id"] == "different-operation" + assert conflict["operation_id"] != expected["operation_id"] + assert restarted_client.lookup_calls == [] and restarted_client.commit_calls == [] + finally: + restarted.close() + + same_client = FakeCycleClient() + same = CycleShadowCoordinator( + _settings(same_client, request_dir=root_path), LAYOUT, client=same_client) + try: + assert same.begin_or_replay(request.request_id, operation) is True + assert same.request_finished(request.request_id) == expected + assert same_client.lookup_calls == [] and same_client.commit_calls == [] + finally: + same.close() + + +def test_m4_timeout_then_success_replays_original_and_freezes_degraded(): + client = FakeCycleClient() + client.commit_transport_results = ["UNAVAILABLE", None] + with _coordinator(client, retry_backoff_ms=50) as (coordinator, _): + request, operation = _admit(coordinator) + _ready(coordinator, request, operation) + coordinator.on_prefill_executed(request.request_id, _stats(), prefill_completed_at_ms=299_500) + while not client.commit_calls: + time.sleep(0.001) + frozen = coordinator.request_finished(request.request_id) + assert frozen["result"] == "degraded" + assert coordinator.wait_for_idle() + assert len(client.commit_calls) == 2 + assert client.commit_calls[0] == client.commit_calls[1] + assert coordinator.request_finished(request.request_id) == frozen + assert coordinator.reconcile_snapshot(request.request_id)["late_applied"] is True + + +def test_m4_transport_retries_are_bounded_and_close_does_not_reopen(): + with tempfile.TemporaryDirectory(prefix="cyclestore-m4-close-") as root: + client = FakeCycleClient() + client.commit_transport_results = ["UNAVAILABLE", "UNAVAILABLE", "UNAVAILABLE", None] + coordinator = CycleShadowCoordinator( + _settings(client, request_dir=Path(root), retry_backoff_ms=5), + LAYOUT, client=client) + request, operation = _admit(coordinator) + _ready(coordinator, request, operation) + coordinator.on_prefill_executed(request.request_id, _stats(), prefill_completed_at_ms=299_500) + assert coordinator.wait_for_idle() + assert len(client.commit_calls) == 3 + assert all(call == client.commit_calls[0] for call in client.commit_calls) + coordinator.close() + before = len(client.commit_calls) + restarted = CycleShadowCoordinator( + _settings(FakeCycleClient(), request_dir=Path(root)), LAYOUT, + client=FakeCycleClient()) + try: + time.sleep(0.05) + assert len(client.commit_calls) == before + assert restarted._operations == {} + finally: + restarted.close() + + +def test_m5_full_hit_zero_save_partial_put_and_failure_are_independent(): + client = FakeCycleClient() + client.commit_outcome = "RENEWED" + client.alive_depth = 1 + with _coordinator(client) as (coordinator, _): + request, operation = _admit(coordinator) + _ready(coordinator, request, operation, put_tokens=0) + coordinator.on_prefill_executed( + request.request_id, _stats(128, 128), prefill_completed_at_ms=299_500) + assert coordinator.wait_for_idle() + envelope = coordinator.request_finished(request.request_id) + assert envelope["physical"]["write_tokens"] == 0 + assert envelope["physical"]["committed_complete_pages"] == 0 + assert envelope["physical"]["computed_tokens"] == 0 + assert envelope["shadow_usage"]["cached_tokens"] == 128 + + with _coordinator() as (coordinator, _): + request, operation = _admit(coordinator) + _ready(coordinator, request, operation, put_tokens=64) + coordinator.on_prefill_executed(request.request_id, _stats(), prefill_completed_at_ms=299_500) + assert coordinator.wait_for_idle() + envelope = coordinator.request_finished(request.request_id) + assert envelope["physical"]["write_tokens"] == 64 + assert envelope["physical"]["committed_complete_pages"] == 1 + + with _coordinator() as (coordinator, client): + request, operation = _admit(coordinator) + _ready(coordinator, request, operation, put_tokens=64, put_failed_tokens=64) + coordinator.on_prefill_executed( + request.request_id, _stats(128, 0), prefill_completed_at_ms=299_500) + assert client.commit_calls == [] + assert coordinator.request_finished(request.request_id)["reason"] == "physical_persistence_failure" + + +def test_m6_logical_cached_above_physical_is_rejected_not_clamped(): + client = FakeCycleClient() + client.alive_depth = 1 + client.commit_outcome = "RENEWED" + with _coordinator(client) as (coordinator, _): + request, operation = _admit(coordinator) + _ready(coordinator, request, operation) + coordinator.on_prefill_executed(request.request_id, _stats(), prefill_completed_at_ms=299_500) + assert coordinator.wait_for_idle() + envelope = coordinator.request_finished(request.request_id) + assert envelope["result"] == "degraded" + assert envelope["reason"] == "logical_cached_exceeds_physical" + assert envelope["shadow_usage"]["cached_tokens"] is None + invalid = copy.deepcopy(envelope) + invalid["shadow_usage"]["cached_tokens"] = 128 + invalid["shadow_usage"]["uncached_tokens"] = 0 + with pytest.raises(ValueError, match="exceeds physical cached"): + validate_publication(invalid) + + +@pytest.mark.parametrize("outcome", ["E110", "E111", "E112", "110", "", "expired"]) +def test_s1_non_allowlisted_outcomes_are_unknown(outcome): + client = FakeCycleClient() + client.commit_outcome = outcome + client.receipt_logical = False + with _coordinator(client) as (coordinator, _): + request, operation = _admit(coordinator) + _ready(coordinator, request, operation) + coordinator.on_prefill_executed(request.request_id, _stats(), prefill_completed_at_ms=299_500) + assert coordinator.wait_for_idle() + envelope = coordinator.request_finished(request.request_id) + assert envelope["reason"] == "invalid_commit_envelope" + assert envelope["cycle_state"] == "unknown" + + +def test_s2_positive_logical_false_is_not_applied(): + client = FakeCycleClient() + client.receipt_logical = False + with _coordinator(client) as (coordinator, _): + request, operation = _admit(coordinator) + _ready(coordinator, request, operation) + coordinator.on_prefill_executed(request.request_id, _stats(), prefill_completed_at_ms=299_500) + assert coordinator.wait_for_idle() + envelope = coordinator.request_finished(request.request_id) + assert envelope["result"] != "shadow_success" + assert envelope["cycle_state"] == "unknown" + assert envelope["commit_projection"]["envelope_valid"] is False + + +def test_s6_deadline_freezes_without_another_admission_poll(): + client = FakeCycleClient(commit_gate=threading.Event()) + gate = client.commit_gate + with _coordinator(client, publication_budget_ms=30) as (coordinator, _): + request, operation = _admit(coordinator) + _ready(coordinator, request, operation) + coordinator.on_prefill_executed(request.request_id, _stats(), prefill_completed_at_ms=299_500) + time.sleep(0.15) + envelope = coordinator.request_finished(request.request_id) + assert envelope["reason"] == "publication_budget_exceeded" + gate.set() + assert coordinator.wait_for_idle() + assert coordinator.request_finished(request.request_id) == envelope + + +def _producer(root, queue): + client = FakeCycleClient() + client.commit_outcome = "RENEWED" + client.alive_depth = 1 + coordinator = CycleShadowCoordinator( + _settings(client, request_dir=Path(root)), LAYOUT, client=client) + request, operation = _admit(coordinator) + _ready(coordinator, request, operation, put_tokens=0) + coordinator.on_prefill_executed(request.request_id, _stats(128, 128), prefill_completed_at_ms=299_500) + assert coordinator.wait_for_idle() + queue.put(coordinator.request_finished(request.request_id)) + coordinator.close() + + +def _consumer(root, queue): + from dfkv_vllm.scheduler import DfkvStoreScheduler + + coordinator = CycleShadowCoordinator( + _settings(FakeCycleClient(), request_dir=Path(root)), LAYOUT, + client=FakeCycleClient()) + scheduler = object.__new__(DfkvStoreScheduler) + scheduler.kv_role = "kv_consumer" + scheduler._retention = {} + scheduler._request_trackers = {} + scheduler._finished_lookahead_metas = {} + scheduler._finished_partial_tail_metas = {} + scheduler._preempted_req_ids = set() + scheduler._unfinished_requests = {} + scheduler._unfinished_request_ids = set() + scheduler._allocated_req_ids = set() + scheduler._failed_load_req_ids = set() + scheduler._block_size = 64 + scheduler.load_specs = {} + scheduler._finished_lookahead_metas = {} + scheduler.client = SimpleNamespace(discard=lambda _r: None) + scheduler.cyclestore_shadow = coordinator + request = _request() + operation = coordinator.build_operation(request, 128, 64) + coordinator.begin_or_replay(request.request_id, operation) + scheduler.register_finished_lookahead_save(request, ([],)) + queue.put((multiprocessing.current_process().pid, + scheduler.request_finished(request, ([],)))) + coordinator.close() + + +def test_s3_two_process_consumer_does_not_publish_second_degraded(): + root = tempfile.mkdtemp(prefix="cyclestore-pd-role-") + try: + context = multiprocessing.get_context("fork") + queue = context.Queue() + producer = context.Process(target=_producer, args=(root, queue)) + producer.start() + published = queue.get(timeout=10) + producer.join(10) + assert producer.exitcode == 0 and published["result"] == "shadow_success" + consumer = context.Process(target=_consumer, args=(root, queue)) + consumer.start() + _pid, (_delay, params) = queue.get(timeout=10) + consumer.join(10) + assert consumer.exitcode == 0 + assert "dfkv_cyclestore_shadow" not in params + reference = params["dfkv_cyclestore_shadow_reference"] + assert reference["publication_emitted"] is False + assert reference["publication_authority"] == "producer" + assert reference["producer_publication_transported"] is False + finally: + shutil.rmtree(root) + + +@pytest.mark.parametrize("failure_sequence", [(64, 0), (0, 64)]) +def test_m5_put_failure_is_conjunctive_across_contributors(failure_sequence): + client = FakeCycleClient() + with _coordinator(client, contributors=("tp:0", "tp:1")) as (coordinator, _): + request, operation = _admit(coordinator) + for contributor, failed in zip(("tp:0", "tp:1"), failure_sequence): + coordinator.mark_evidence_ready( + request.request_id, contributor, operation["complete_pages"], + operation["complete_page_evidence_digest"], + put_completed_tokens=64, committed_complete_pages=1, + put_failed_tokens=failed) + coordinator.on_prefill_executed( + request.request_id, _stats(128, 0), prefill_completed_at_ms=299_500) + assert client.commit_calls == [] + assert coordinator.request_finished(request.request_id)["reason"] == "physical_persistence_failure" + + +def test_m4_restore_cannot_reset_global_attempt_ceiling(): + with tempfile.TemporaryDirectory(prefix="cyclestore-retry-ceiling-") as root: + client = FakeCycleClient() + client.commit_transport_results = ["UNAVAILABLE"] * 4 + coordinator = CycleShadowCoordinator( + _settings(client, request_dir=Path(root), retry_backoff_ms=5), + LAYOUT, client=client) + request, operation = _admit(coordinator) + _ready(coordinator, request, operation) + coordinator.on_prefill_executed(request.request_id, _stats(), prefill_completed_at_ms=299_500) + assert coordinator.wait_for_idle() + coordinator.request_finished(request.request_id) + assert len(client.commit_calls) == 3 + coordinator._closed = True # crash-style quiescence without closed-state journal + + for _ in range(2): + recovered_client = FakeCycleClient() + recovered = CycleShadowCoordinator( + _settings(recovered_client, request_dir=Path(root)), LAYOUT, + client=recovered_client) + try: + op = recovered._operations[recovered._attempts[request.request_id]] + assert op.commit_attempts == 3 + assert op.retry_due_monotonic is None + assert len(recovered_client.commit_calls) == 0 + finally: + # Crash recovery (not graceful close) must preserve exhausted + # retry state; graceful close after that remains non-reopening. + recovered._closed = True + assert len(client.commit_calls) == 3 + + +def test_operation_id_conflict_zero_digest_is_definite_negative_final(): + client = FakeCycleClient() + client.commit_outcome = "OPERATION_ID_CONFLICT" + client.receipt_logical = False + real_call = client.call + + def zero_digest(operation, request): + response = real_call(operation, request) + if operation == "commit": + response["receipt"]["pathDigest"] = "" + return response + + client.call = zero_digest + with _coordinator(client) as (coordinator, _): + request, operation = _admit(coordinator) + _ready(coordinator, request, operation) + coordinator.on_prefill_executed(request.request_id, _stats(), prefill_completed_at_ms=299_500) + assert coordinator.wait_for_idle() + envelope = coordinator.request_finished(request.request_id) + assert envelope["result"] == "degraded" + assert envelope["reason"] == "OPERATION_ID_CONFLICT" + assert envelope["cycle_state"] == "deterministic_negative" + assert envelope["commit_projection"]["envelope_valid"] is True + + +@pytest.mark.parametrize( + ("digest_field", "bad_value"), + [ + ("canonicalPathDigest", None), + ("canonicalPathDigest", "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="), + ("completePageEvidenceDigest", None), + ("completePageEvidenceDigest", "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="), + ], +) +def test_live_lookup_rejects_absent_or_changed_operation_digests(digest_field, bad_value): + client = FakeCycleClient() + real_call = client.call + + def contradictory_lookup(operation_name, request): + response = real_call(operation_name, request) + if operation_name == "lookup": + if bad_value is None: + response["payload"].pop(digest_field) + else: + response["payload"][digest_field] = bad_value + return response + + client.call = contradictory_lookup + with _coordinator(client) as (coordinator, _): + request, operation = _admit(coordinator) + expected_digest = operation["lookup_request"]["path"][digest_field] + assert bad_value != expected_digest + op = coordinator._operations[coordinator._attempts[request.request_id]] + assert op.token is None and op.payload is None + envelope = coordinator.request_finished(request.request_id) + assert envelope["result"] == "degraded" + assert envelope["reason"] == "invalid_lookup_snapshot" + assert envelope["cycle_state"] == "unknown" + assert envelope["lookup_projection"] is None + assert client.commit_calls == [] + + +def test_full_evidence_fallback_with_original_digests_can_commit(): + client = FakeCycleClient() + real_call = client.call + fallback_paths = [] + + def full_evidence_fallback(operation_name, request): + if operation_name in ("lookup", "commit"): + path = request["path"] + assert path["pages"] + fallback_paths.append(copy.deepcopy(path)) + response = real_call(operation_name, request) + if operation_name == "lookup": + assert (response["payload"]["canonicalPathDigest"] == + request["path"]["canonicalPathDigest"]) + assert (response["payload"]["completePageEvidenceDigest"] == + request["path"]["completePageEvidenceDigest"]) + return response + + client.call = full_evidence_fallback + with _coordinator(client) as (coordinator, _): + request, operation = _admit(coordinator) + _ready(coordinator, request, operation) + coordinator.on_prefill_executed( + request.request_id, _stats(), prefill_completed_at_ms=299_500) + assert coordinator.wait_for_idle() + envelope = coordinator.request_finished(request.request_id) + assert envelope["result"] == "shadow_success" + assert envelope["evidence_mode"] == "full_evidence" + assert envelope["lookup_projection"]["canonical_path_digest"] == ( + operation["lookup_request"]["path"]["canonicalPathDigest"]) + assert envelope["lookup_projection"]["complete_page_evidence_digest"] == ( + operation["lookup_request"]["path"]["completePageEvidenceDigest"]) + assert fallback_paths == [operation["lookup_request"]["path"]] * 2 + + +def test_terminal_evidence_fallback_preserves_fault_identity_not_in_flight(): + client = FakeCycleClient() + real_call = client.call + commit_requests = [] + + def terminal_fallback(operation_name, request): + if operation_name == "commit": + commit_requests.append(copy.deepcopy(request)) + return {"transportError": "INVALID_EVIDENCE", + "evidenceFallbackRequired": True, + "shadowOnly": True, "noReplication": False} + return real_call(operation_name, request) + + client.call = terminal_fallback + with _coordinator(client) as (coordinator, _): + request, operation = _admit(coordinator) + _ready(coordinator, request, operation) + coordinator.on_prefill_executed( + request.request_id, _stats(), prefill_completed_at_ms=299_500) + assert coordinator.wait_for_idle() + op = coordinator._operations[coordinator._attempts[request.request_id]] + assert op.commit_done is True and op.retry_due_monotonic is None + envelope = coordinator.request_finished(request.request_id) + assert envelope["result"] == "degraded" + assert envelope["reason"] == "INVALID_EVIDENCE" + assert envelope["cycle_state"] == "unknown" + assert envelope["commit_projection"]["transport_error"] == "INVALID_EVIDENCE" + assert envelope["commit_projection"]["evidence_fallback_required"] is True + assert envelope["commit_projection"]["envelope_valid"] is False + assert len(commit_requests) == 1 + + +def test_exhausted_transport_retry_publishes_terminal_error_not_in_flight(): + client = FakeCycleClient() + client.commit_transport_results = ["UNAVAILABLE"] * 3 + with _coordinator(client, retry_backoff_ms=1) as (coordinator, _): + request, operation = _admit(coordinator) + _ready(coordinator, request, operation) + coordinator.on_prefill_executed( + request.request_id, _stats(), prefill_completed_at_ms=299_500) + assert coordinator.wait_for_idle() + assert len(client.commit_calls) == 3 + op = coordinator._operations[coordinator._attempts[request.request_id]] + assert op.commit_done is True and op.retry_due_monotonic is None + envelope = coordinator.request_finished(request.request_id) + assert envelope["result"] == "degraded" + assert envelope["reason"] == "UNAVAILABLE" + assert envelope["reason"] != "commit_in_flight" + assert envelope["cycle_state"] == "unknown" + assert envelope["commit_projection"]["transport_error"] == "UNAVAILABLE" + assert envelope["commit_projection"]["evidence_fallback_required"] is False + assert envelope["commit_projection"]["envelope_valid"] is False + assert len(client.commit_calls) == 3 + + +def test_receipt_before_prefill_is_terminal_invalid_not_transport_loss(): + client = FakeCycleClient() + client.accepted_at = 299_499 + real_call = client.call + commit_responses = [] + + def record_commit_response(operation_name, request): + response = real_call(operation_name, request) + if operation_name == "commit": + commit_responses.append(copy.deepcopy(response)) + return response + + client.call = record_commit_response + with _coordinator(client) as (coordinator, _): + request, operation = _admit(coordinator) + _ready(coordinator, request, operation) + coordinator.on_prefill_executed( + request.request_id, _stats(), prefill_completed_at_ms=299_500) + assert coordinator.wait_for_idle() + op = coordinator._operations[coordinator._attempts[request.request_id]] + assert op.commit_done is True and op.retry_due_monotonic is None + assert op.commit_attempts == 1 + assert op.commit_response == commit_responses[0] + assert "clientError" not in op.commit_response + + envelope = coordinator.request_finished(request.request_id) + assert envelope["result"] == "degraded" + assert envelope["reason"] == "invalid_commit_envelope" + assert envelope["cycle_state"] == "unknown" + assert envelope["shadow_usage"]["cache_write_tokens"] is None + projection = envelope["commit_projection"] + assert projection["outcome"] == "ROOT_CYCLE_CREATED" + assert projection["accepted_at_ms"] == 299_499 + assert projection["transport_error"] == "RESULT_UNSPECIFIED" + assert projection["receipt_digest"] == "cmVjZWlwdA==" + assert projection["envelope_valid"] is False + assert projection["logical_commit_applied"] is False + assert projection["billing_eligible_for_new_cycle"] is False + assert coordinator.request_finished(request.request_id) == envelope + assert len(client.commit_calls) == 1 + validate_publication(envelope) + + # A genuinely authoritative projection still fails closed; only the + # invalid raw response is retained as diagnostic degraded evidence. + authoritative = copy.deepcopy(envelope) + authoritative["commit_projection"]["envelope_valid"] = True + with pytest.raises(ValueError, match="accepted_at precedes"): + validate_publication(authoritative) + + +def test_authoritative_negative_before_prefill_is_definite_terminal(): + client = FakeCycleClient() + client.commit_outcome = "INVALID_EVIDENCE" + client.receipt_logical = False + client.accepted_at = 299_499 + real_call = client.call + commit_responses = [] + + def record_negative_response(operation_name, request): + response = real_call(operation_name, request) + if operation_name == "commit": + response["evidenceFallbackRequired"] = True + commit_responses.append(copy.deepcopy(response)) + return response + + client.call = record_negative_response + with _coordinator(client, retry_backoff_ms=1) as (coordinator, _): + request, operation = _admit(coordinator) + _ready(coordinator, request, operation) + coordinator.on_prefill_executed( + request.request_id, _stats(), prefill_completed_at_ms=299_500) + assert coordinator.wait_for_idle() + op = coordinator._operations[coordinator._attempts[request.request_id]] + assert op.commit_done is True and op.retry_due_monotonic is None + assert op.commit_attempts == 1 + assert op.commit_response == commit_responses[0] + assert "clientError" not in op.commit_response + + envelope = coordinator.request_finished(request.request_id) + assert envelope["result"] == "degraded" + assert envelope["reason"] == "INVALID_EVIDENCE" + assert envelope["cycle_state"] == "deterministic_negative" + assert envelope["prefill_completed_at_ms"] == 299_500 + assert envelope["shadow_usage"]["cache_write_tokens"] is None + projection = envelope["commit_projection"] + assert projection["outcome"] == "INVALID_EVIDENCE" + assert projection["accepted_at_ms"] == 299_499 + assert projection["transport_error"] == "RESULT_UNSPECIFIED" + assert projection["receipt_digest"] == "cmVjZWlwdA==" + assert projection["evidence_fallback_required"] is True + assert projection["envelope_valid"] is True + assert projection["logical_commit_applied"] is False + assert projection["billing_eligible_for_new_cycle"] is False + validate_publication(envelope) + assert coordinator.request_finished(request.request_id) == envelope + assert len(client.commit_calls) == len(commit_responses) == 1 + + contradictory_negative = copy.deepcopy(envelope) + contradictory_negative["commit_projection"]["logical_commit_applied"] = True + with pytest.raises(ValueError, match="accepted_at precedes"): + validate_publication(contradictory_negative) diff --git a/src/cyclestore/CMakeLists.txt b/src/cyclestore/CMakeLists.txt index 47e7b051..612f7055 100644 --- a/src/cyclestore/CMakeLists.txt +++ b/src/cyclestore/CMakeLists.txt @@ -71,6 +71,15 @@ add_executable(dfkv_cycle_controller src/controller_main.cc) target_compile_options(dfkv_cycle_controller PRIVATE -Wall -Wextra -Wpedantic) target_link_libraries(dfkv_cycle_controller PRIVATE dfkv_cyclestore_raft) +# S4 evidence-reuse measurement helpers. These are never registered as CTest +# workloads: the Python driver owns a bounded three-replica scenario and emits +# its complete raw distribution instead of a performance-gate verdict. +add_executable(cyclestore_persistent_client test/persistent_cycle_client.cc) +target_include_directories(cyclestore_persistent_client PRIVATE ${CMAKE_CURRENT_BINARY_DIR}) +target_link_libraries(cyclestore_persistent_client PRIVATE dfkv_cyclestore_raft) +add_executable(cyclestore_store_perf_audit test/store_perf_audit_main.cc) +target_link_libraries(cyclestore_store_perf_audit PRIVATE dfkv_cyclestore_core) + if(DFKV_BUILD_TESTS) add_executable(cyclestore_coverage_index_test test/coverage_index_test.cc) target_link_libraries(cyclestore_coverage_index_test @@ -127,6 +136,14 @@ if(DFKV_BUILD_TESTS) set_tests_properties(CycleStoreS2.FullDifferential PROPERTIES LABELS cyclestore_s2 TIMEOUT 600) + add_test(NAME CycleStoreS2.CapabilityDifferential + COMMAND ${DFKV_CYCLESTORE_PYTHON3} + ${CYCLESTORE_TEST_DIR}/capability_diff.py + --binary $ + --artifacts ${CMAKE_CURRENT_BINARY_DIR}/capability-diff-artifacts) + set_tests_properties(CycleStoreS2.CapabilityDifferential PROPERTIES + LABELS cyclestore_s2 TIMEOUT 180) + add_executable(cyclestore_snapshot_binding_test test/raft_snapshot_binding_test.cc) target_link_libraries(cyclestore_snapshot_binding_test PRIVATE dfkv_cyclestore_raft) add_test(NAME CycleStoreS3.SnapshotIdentity diff --git a/src/cyclestore/include/cyclestore/fsm.h b/src/cyclestore/include/cyclestore/fsm.h index 96ebfac9..354bdd2b 100644 --- a/src/cyclestore/include/cyclestore/fsm.h +++ b/src/cyclestore/include/cyclestore/fsm.h @@ -66,6 +66,7 @@ struct LookupCommand { FamilyKey family; std::string operation_id; PathEvidenceRecord path; + std::optional evidence_capability; TtlClass requested_ttl = TtlClass::kUnspecified; std::uint64_t apply_index = 0; std::uint64_t term = 0; @@ -82,11 +83,14 @@ struct LookupResult { std::string detail; bool shadow_only = true; bool no_replication = true; + std::optional evidence_capability; + bool evidence_fallback_required = false; }; struct CommitCommand { Bytes canonical_lookup_token; PathEvidenceRecord path; + std::optional evidence_capability; std::uint64_t prefill_completed_at_ms = 0; std::uint64_t apply_index = 0; std::uint64_t term = 0; @@ -100,6 +104,8 @@ struct CommitResult { bool shadow_only = true; bool no_replication = true; std::string detail; + std::optional evidence_capability; + bool evidence_fallback_required = false; }; struct EpochCommand { @@ -160,11 +166,11 @@ class CycleStateMachine { static StoreStatus Open(std::unique_ptr store, FsmConfig config, std::unique_ptr* output); - LookupResult IssueLookup(const LookupCommand& command); + LookupResult IssueLookup(LookupCommand command); // Duplicate-only read path. The caller must supply a verified applied read // point; no deadlines or records are written and first issuance never uses it. - LookupResult ReadLookup(const LookupCommand& command); - CommitResult ApplyCommit(const CommitCommand& command); + LookupResult ReadLookup(LookupCommand command); + CommitResult ApplyCommit(CommitCommand command); FsmResult AdvanceDataEpoch(const EpochCommand& command); FsmResult Collect(const GcCommand& command); @@ -173,6 +179,9 @@ class CycleStateMachine { const std::string& operation_id, bool* found) const; ShardMeta MetaForTest() const; + const std::map& CapabilitiesForTest() const { + return capabilities_; + } const std::string& LastErrorForTest() const; FsmProjection ProjectionForTest(const FamilyKey& family) const; StoreStatus ReadExpiryForTest(std::int64_t now_ms, std::size_t limit, @@ -224,6 +233,17 @@ class CycleStateMachine { bool ValidateEvidence(const FamilyKey& family, const PathEvidenceRecord& path, Digest* path_digest, Digest* evidence_digest, LookupResult* failure) const; + bool ResolveEvidence(const FamilyKey& family, + const std::optional& capability, + std::int64_t authoritative_now_ms, PathEvidenceRecord* path, + Digest* path_digest, Digest* evidence_digest, bool* reused, + LookupResult* failure); + static bool HasOperationCapabilityEncoding(const OperationRecord& operation, + const Bytes& capability_encoding); + void TrackCapability(const EvidenceCapabilityRecord& capability); + void EraseCapabilitiesForTip(const FamilyKey& family, const Id128& tip, + std::vector* mutations, + bool update_memory); bool NodeMatchesPath(const FamilyState& family, const NodeState& node, const PathEvidenceRecord& path, std::size_t depth) const; int32_t AliveDepth(FamilyState* family, const PathEvidenceRecord& path, @@ -253,6 +273,8 @@ class CycleStateMachine { std::string last_error_; std::map families_; std::map operations_; + std::map capabilities_; + std::map> capability_keys_by_tip_; }; const char* FsmResultName(FsmResult result); diff --git a/src/cyclestore/include/cyclestore/records.h b/src/cyclestore/include/cyclestore/records.h index fcfee7f7..250520d6 100644 --- a/src/cyclestore/include/cyclestore/records.h +++ b/src/cyclestore/include/cyclestore/records.h @@ -30,6 +30,7 @@ enum class RecordKind : std::uint8_t { kLease = 6, kOperation = 7, kExpiryIndex = 8, + kEvidenceCapability = 9, }; enum class RecoveryState : std::uint8_t { @@ -197,6 +198,14 @@ struct OperationRecord { std::uint32_t auth_key_id = 0; Digest lookup_input_digest{}; Digest commit_input_digest{}; + // Absent in legacy values (false). New FINAL records bind the compact digest + // independently of transport form, preserving genuine mutation conflicts. + bool commit_input_semantic_v2 = false; + // Canonical values issued with this operation's token or returned/persisted + // with its FINAL. They retain historical replay identity independently of + // the mutable latest-value capability slot. Empty means absent. + Bytes issued_capability_encoding; + Bytes final_capability_encoding; bool has_final_receipt = false; CommitReceiptRecord final_receipt; std::int64_t receipt_final_state_at_ms = 0; @@ -238,6 +247,27 @@ struct PathEvidenceRecord { NodeRefRecord expected_tip; }; +struct EvidenceCapabilityKey { + FamilyKey family; + Digest canonical_path_digest{}; +}; + +// Durable proof that this server validated one complete, still materialized +// path. The client may echo it, but it is never itself validation authority. +struct EvidenceCapabilityRecord { + std::uint32_t schema_version = 1; + FamilyKey family; + std::uint64_t data_epoch = 0; + std::uint64_t family_incarnation = 0; + std::uint64_t root_generation = 0; + TtlClass root_locked_ttl = TtlClass::kUnspecified; + NodeRefRecord expected_tip; + Digest canonical_path_digest{}; + Digest complete_page_evidence_digest{}; + std::uint64_t validated_apply_index = 0; + std::uint32_t page_count = 0; +}; + struct FinalFenceResetGuard { std::int64_t authoritative_now_ms = 0; bool no_leases = false; @@ -267,6 +297,7 @@ Bytes EncodeNodeUniqueKey(const NodeUniqueKey& key); Bytes EncodeLeaseRecordKey(const LeaseRecordKey& key); Bytes EncodeOperationRecordKey(const OperationRecordKey& key); Bytes EncodeExpiryIndexKey(const ExpiryIndexKey& key); +Bytes EncodeEvidenceCapabilityKey(const EvidenceCapabilityKey& key); bool DecodeCheckpointKey(const Bytes& encoded, std::uint64_t* snapshot_index, std::string* error); @@ -282,6 +313,8 @@ bool DecodeOperationRecordKey(const Bytes& encoded, OperationRecordKey* key, std::string* error); bool DecodeExpiryIndexKey(const Bytes& encoded, ExpiryIndexKey* key, std::string* error); +bool DecodeEvidenceCapabilityKey(const Bytes& encoded, EvidenceCapabilityKey* key, + std::string* error); Bytes EncodeShardMeta(const ShardMeta& record); Bytes EncodeCheckpoint(const Checkpoint& record); @@ -291,6 +324,9 @@ Bytes EncodeNodeUniqueIndex(const NodeUniqueIndex& record); Bytes EncodeLeaseRecord(const LeaseRecord& record); Bytes EncodeOperationRecord(const OperationRecord& record); Bytes EncodeExpiryIndex(const ExpiryIndex& record); +Bytes EncodeEvidenceCapability(const EvidenceCapabilityRecord& record); +bool SameEvidenceCapability(const EvidenceCapabilityRecord& left, + const EvidenceCapabilityRecord& right); bool DecodeShardMeta(const Bytes& encoded, ShardMeta* record, std::string* error); bool DecodeCheckpoint(const Bytes& encoded, Checkpoint* record, std::string* error); @@ -302,6 +338,8 @@ bool DecodeLeaseRecord(const Bytes& encoded, LeaseRecord* record, std::string* e bool DecodeOperationRecord(const Bytes& encoded, OperationRecord* record, std::string* error); bool DecodeExpiryIndex(const Bytes& encoded, ExpiryIndex* record, std::string* error); +bool DecodeEvidenceCapability(const Bytes& encoded, EvidenceCapabilityRecord* record, + std::string* error); Bytes EncodeCanonicalPathEvidence(const PathEvidenceRecord& path); Bytes EncodeCompletePageEvidence(const PathEvidenceRecord& path); @@ -314,6 +352,16 @@ std::optional ComputeLookupInputDigest(const FamilyKey& family, std::optional ComputeCommitInputDigest(const Bytes& canonical_lookup_token_payload, const PathEvidenceRecord& path, std::uint64_t prefill_completed_at_ms); +// Versioned semantic input identities avoid re-encoding and re-hashing an +// already validated page vector. Full and capability transport forms share +// these identities; legacy v1 records retain their original fallback codec. +std::optional ComputeLookupInputDigest( + const FamilyKey& family, const std::string& operation_id, + const Digest& canonical_path_digest, const Digest& complete_page_evidence_digest, + TtlClass requested_ttl); +std::optional ComputeCommitInputDigest( + const Bytes& canonical_lookup_token_payload, const Digest& canonical_path_digest, + const Digest& complete_page_evidence_digest, std::uint64_t prefill_completed_at_ms); std::optional DeriveNodeId(const FamilyKey& family, const BirthIdentity& birth, const Bytes& page_hash); diff --git a/src/cyclestore/proto/cycle_store.proto b/src/cyclestore/proto/cycle_store.proto index bd709422..598737d1 100644 --- a/src/cyclestore/proto/cycle_store.proto +++ b/src/cyclestore/proto/cycle_store.proto @@ -60,11 +60,28 @@ message PathEvidence { NodeRef expected_tip = 4; } +// An echoed server-issued reference, never client-side proof. If pages is +// non-empty it is ignored and the complete evidence path is always validated. +message EvidenceCapability { + uint32 schema_version = 1; + FamilyKey family = 2; + uint64 data_epoch = 3; + uint64 family_incarnation = 4; + uint64 root_generation = 5; + TtlClass root_locked_ttl = 6; + NodeRef expected_tip = 7; + bytes canonical_path_digest = 8; + bytes complete_page_evidence_digest = 9; + uint64 validated_apply_index = 10; + uint32 page_count = 11; +} + message LookupRequest { FamilyKey family = 1; string operation_id = 2; PathEvidence path = 3; TtlClass requested_ttl = 4; + EvidenceCapability evidence_capability = 5; } message LookupTokenPayload { @@ -101,12 +118,15 @@ message LookupResponse { uint64 authoritative_now_ms = 4; bool shadow_only = 5; bool no_replication = 6; + EvidenceCapability evidence_capability = 7; + bool evidence_fallback_required = 8; } message CommitRequest { LookupToken token = 1; PathEvidence path = 2; uint64 prefill_completed_at_ms = 3; + EvidenceCapability evidence_capability = 4; } message CommitReceipt { @@ -131,6 +151,8 @@ message CommitResponse { bool receipt_replayed = 3; bool shadow_only = 4; bool no_replication = 5; + EvidenceCapability evidence_capability = 6; + bool evidence_fallback_required = 7; } service CycleStore { diff --git a/src/cyclestore/src/cycle_service.cc b/src/cyclestore/src/cycle_service.cc index e8a3a0d5..de359d2a 100644 --- a/src/cyclestore/src/cycle_service.cc +++ b/src/cyclestore/src/cycle_service.cc @@ -79,6 +79,43 @@ PathEvidenceRecord PathFromProto(const v1::PathEvidence& source) { return destination; } +EvidenceCapabilityRecord CapabilityFromProto(const v1::EvidenceCapability& source) { + EvidenceCapabilityRecord destination; + destination.schema_version = source.schema_version(); + destination.family = FamilyFromProto(source.family()); + destination.data_epoch = source.data_epoch(); + destination.family_incarnation = source.family_incarnation(); + destination.root_generation = source.root_generation(); + destination.root_locked_ttl = TtlFromProto(source.root_locked_ttl()); + destination.expected_tip = NodeRefFromProto(source.expected_tip()); + const auto copy_digest = [](const std::string& input, Digest* output) { + if (input.size() == output->size()) + std::copy(input.begin(), input.end(), output->begin()); + }; + copy_digest(source.canonical_path_digest(), &destination.canonical_path_digest); + copy_digest(source.complete_page_evidence_digest(), + &destination.complete_page_evidence_digest); + destination.validated_apply_index = source.validated_apply_index(); + destination.page_count = source.page_count(); + return destination; +} + +void CapabilityToProto(const EvidenceCapabilityRecord& source, + v1::EvidenceCapability* destination) { + destination->set_schema_version(source.schema_version); + FamilyToProto(source.family, destination->mutable_family()); + destination->set_data_epoch(source.data_epoch); + destination->set_family_incarnation(source.family_incarnation); + destination->set_root_generation(source.root_generation); + destination->set_root_locked_ttl(TtlToProto(source.root_locked_ttl)); + NodeRefToProto(source.expected_tip, destination->mutable_expected_tip()); + destination->set_canonical_path_digest(RawBytes(source.canonical_path_digest)); + destination->set_complete_page_evidence_digest( + RawBytes(source.complete_page_evidence_digest)); + destination->set_validated_apply_index(source.validated_apply_index); + destination->set_page_count(source.page_count); +} + void TokenToProto(const LookupToken& source, TtlClass requested_ttl, v1::LookupResponse* response) { const Bytes canonical = EncodeLookupToken(source); @@ -143,6 +180,8 @@ LookupCommand LookupCommandFromProto(const v1::LookupRequest& request, command.family = FamilyFromProto(request.family()); command.operation_id = request.operation_id(); command.path = PathFromProto(request.path()); + if (request.has_evidence_capability()) + command.evidence_capability = CapabilityFromProto(request.evidence_capability()); command.requested_ttl = TtlFromProto(request.requested_ttl()); command.apply_index = apply_index; command.term = term; @@ -159,6 +198,8 @@ CommitCommand CommitCommandFromProto(const v1::CommitRequest& request, CommitCommand command; command.canonical_lookup_token = BytesFromString(request.token().canonical_payload()); command.path = PathFromProto(request.path()); + if (request.has_evidence_capability()) + command.evidence_capability = CapabilityFromProto(request.evidence_capability()); command.prefill_completed_at_ms = request.prefill_completed_at_ms(); command.apply_index = apply_index; command.term = term; @@ -171,6 +212,9 @@ v1::LookupResponse LookupResponseFromFsm(const LookupResult& result, v1::LookupResponse response; response.set_result(static_cast(static_cast(result.result))); if (result.has_token) TokenToProto(result.token, requested_ttl, &response); + if (result.evidence_capability.has_value()) + CapabilityToProto(*result.evidence_capability, response.mutable_evidence_capability()); + response.set_evidence_fallback_required(result.evidence_fallback_required); response.set_shadow_only(true); response.set_no_replication(false); return response; @@ -179,6 +223,14 @@ v1::LookupResponse LookupResponseFromFsm(const LookupResult& result, v1::CommitResponse CommitResponseFromFsm(const CommitResult& result, bool has_final_receipt) { v1::CommitResponse response; + if (result.evidence_fallback_required || + (result.result == FsmResult::kInvalidEvidence && !has_final_receipt)) { + response.set_transport_error(v1::INVALID_EVIDENCE); + response.set_evidence_fallback_required(result.evidence_fallback_required); + response.set_shadow_only(true); + response.set_no_replication(false); + return response; // Never manufacture a receipt shadowing a durable FINAL. + } response.set_transport_error(has_final_receipt ? v1::RESULT_UNSPECIFIED : v1::UNAVAILABLE); if (has_final_receipt) { @@ -201,6 +253,9 @@ v1::CommitResponse CommitResponseFromFsm(const CommitResult& result, output->set_receipt_digest(RawBytes(receipt.receipt_digest)); } response.set_receipt_replayed(has_final_receipt && result.receipt_replayed); + if (result.evidence_capability.has_value()) + CapabilityToProto(*result.evidence_capability, response.mutable_evidence_capability()); + response.set_evidence_fallback_required(result.evidence_fallback_required); response.set_shadow_only(true); response.set_no_replication(false); return response; diff --git a/src/cyclestore/src/fsm.cc b/src/cyclestore/src/fsm.cc index d80c7519..f1ab74e0 100644 --- a/src/cyclestore/src/fsm.cc +++ b/src/cyclestore/src/fsm.cc @@ -308,6 +308,8 @@ StoreStatus CycleStateMachine::Recover() { if (!status.ok()) return status; families_.clear(); operations_.clear(); + capabilities_.clear(); + capability_keys_by_tip_.clear(); operation_counts_by_family_.clear(); gc_cursor_.clear(); recovery_required_ = false; @@ -474,6 +476,26 @@ StoreStatus CycleStateMachine::Recover() { OperationStateValue{key.family, operation, token}; ++operation_counts_by_family_[FamilyMapKey(key.family)]; } + records.clear(); + status = store_->ScanRecords(RecordKind::kEvidenceCapability, &records); + if (!status.ok()) return status; + for (const auto& stored : records) { + EvidenceCapabilityKey key; + EvidenceCapabilityRecord capability; + std::string error; + if (!DecodeEvidenceCapabilityKey(stored.key, &key, &error) || + !DecodeEvidenceCapability(stored.value, &capability, &error)) + return StoreStatus{StoreError::kCorruption, error}; + if (EncodeFamilyKey(key.family) != EncodeFamilyKey(capability.family) || + key.canonical_path_digest != capability.canonical_path_digest) + return StoreStatus{StoreError::kCorruption, "capability key and value identities diverge"}; + // A snapshot/log tail that cannot prove this validation point must not make + // the capability usable. It remains harmless durable audit data and every + // short request falls back to complete evidence. + if (capability.validated_apply_index <= meta_.last_applied_index) + TrackCapability(capability); + } + records.clear(); status = store_->ScanRecords(RecordKind::kExpiryIndex, &records); if (!status.ok()) return status; @@ -502,6 +524,12 @@ const CycleStateMachine::FamilyState* CycleStateMachine::FindFamily(const Family const auto iterator = families_.find(FamilyMapKey(family)); return iterator == families_.end() ? nullptr : &iterator->second; } +bool CycleStateMachine::HasOperationCapabilityEncoding( + const OperationRecord& operation, const Bytes& capability_encoding) { + return !capability_encoding.empty() && + (operation.issued_capability_encoding == capability_encoding || + operation.final_capability_encoding == capability_encoding); +} std::map::iterator CycleStateMachine::RequireFamily(const FamilyKey& family) { return families_.try_emplace(FamilyMapKey(family), family).first; @@ -571,6 +599,124 @@ bool CycleStateMachine::ValidateEvidence(const FamilyKey& family, return true; } +bool CycleStateMachine::ResolveEvidence( + const FamilyKey& family_key, + const std::optional& capability, + std::int64_t authoritative_now_ms, PathEvidenceRecord* path, + Digest* path_digest, Digest* evidence_digest, bool* reused, + LookupResult* failure) { + *reused = false; + // A complete request always takes the legacy validation path, even if a + // client also echoes a stale capability. This is the explicit wire fallback. + if (!capability.has_value() || !path->pages.empty()) + return ValidateEvidence(family_key, *path, path_digest, evidence_digest, failure); + + auto fallback = [&](const char* reason) { + failure->result = FsmResult::kInvalidEvidence; + failure->evidence_fallback_required = true; + const std::string prior = std::move(failure->detail); + failure->detail = std::string("evidence capability rejected (") + reason + ")" + + (prior.empty() ? "" : "; " + prior) + "; retry with complete page evidence"; + return false; + }; + if (capability->schema_version != 1 || + EncodeFamilyKey(capability->family) != EncodeFamilyKey(family_key)) + return fallback("schema_or_family"); + const Bytes capability_key = EncodeEvidenceCapabilityKey( + EvidenceCapabilityKey{family_key, capability->canonical_path_digest}); + const auto known = capabilities_.find(capability_key); + if (known == capabilities_.end()) return fallback("missing_persisted_key"); + if (capability->validated_apply_index == 0 || + capability->validated_apply_index > meta_.last_applied_index) + return fallback("unrecovered_validation_point"); + if (!SameEvidenceCapability(known->second, *capability)) { + failure->detail = "capability_value_mismatch request_validated=" + + std::to_string(capability->validated_apply_index) + + " persisted_validated=" + + std::to_string(known->second.validated_apply_index) + + " request_tip=" + HexDigest(Sha256(capability->expected_tip.page_hash)) + + " request_generation=" + std::to_string(capability->root_generation) + + " persisted_generation=" + std::to_string(known->second.root_generation); + return fallback("changed_persisted_value"); + } + + const FamilyState* family = FindFamily(family_key); + if (family == nullptr || family->fence.data_epoch != meta_.data_epoch || + family->fence.data_epoch != capability->data_epoch || + family->fence.family_incarnation != capability->family_incarnation || + family->fence.current_root_generation != capability->root_generation || + family->fence.current_root_locked_ttl != capability->root_locked_ttl) + return fallback("fence_epoch_generation_or_ttl"); + const NodeState* tip = FindNode(*family, capability->expected_tip.node_id); + if (tip == nullptr || tip->incarnation != capability->expected_tip.node_incarnation || + tip->page_hash != capability->expected_tip.page_hash || + tip->depth != capability->expected_tip.depth || + tip->depth + 1 != capability->page_count || + (capability->expected_tip.page_hash != family_key.family_root_hash && + capability->page_count == 1)) + return fallback("tip_identity_or_depth"); + const Cover cover = family->index.PointQuery(tip->online_id); + if (!cover.alive(authoritative_now_ms) || cover.root_generation != capability->root_generation) + return fallback("expired_or_old_coverage"); + + path->pages.clear(); + path->pages.reserve(capability->page_count); + const NodeState* current = tip; + while (current != nullptr) { + if (current->depth >= capability->page_count) + return fallback("depth_overflow"); + path->pages.push_back(PageEvidenceRecord{current->page_hash, current->depth, {}}); + if (current->depth == 0) break; + const NodeState* parent = FindNode(*family, current->parent_id); + if (parent == nullptr || parent->depth + 1 != current->depth) + return fallback("missing_or_invalid_parent"); + current = parent; + } + if (current == nullptr || current->depth != 0 || + current->page_hash != family_key.family_root_hash || + path->pages.size() != capability->page_count) + return fallback("root_lineage"); + std::reverse(path->pages.begin(), path->pages.end()); + path->has_expected_tip = true; + path->expected_tip = capability->expected_tip; + *path_digest = capability->canonical_path_digest; + *evidence_digest = capability->complete_page_evidence_digest; + *reused = true; + return true; +} + +void CycleStateMachine::TrackCapability(const EvidenceCapabilityRecord& capability) { + const Bytes key = EncodeEvidenceCapabilityKey( + EvidenceCapabilityKey{capability.family, capability.canonical_path_digest}); + const auto previous = capabilities_.find(key); + if (previous != capabilities_.end()) { + const Bytes previous_tip = EncodeNodeRecordKey( + NodeRecordKey{previous->second.family, previous->second.expected_tip.node_id}); + auto tips = capability_keys_by_tip_.find(previous_tip); + if (tips != capability_keys_by_tip_.end()) { + tips->second.erase(key); + if (tips->second.empty()) capability_keys_by_tip_.erase(tips); + } + } + capabilities_[key] = capability; + capability_keys_by_tip_[EncodeNodeRecordKey( + NodeRecordKey{capability.family, capability.expected_tip.node_id})].insert(key); +} + +void CycleStateMachine::EraseCapabilitiesForTip( + const FamilyKey& family, const Id128& tip, + std::vector* mutations, bool update_memory) { + const Bytes tip_key = EncodeNodeRecordKey(NodeRecordKey{family, tip}); + const auto indexed = capability_keys_by_tip_.find(tip_key); + if (indexed == capability_keys_by_tip_.end()) return; + for (const Bytes& key : indexed->second) { + if (mutations != nullptr) + mutations->push_back({RecordKind::kEvidenceCapability, key, true, {}}); + if (update_memory) capabilities_.erase(key); + } + if (update_memory) capability_keys_by_tip_.erase(indexed); +} + NodeId CycleStateMachine::FindOnlineNode(const FamilyState& family, const Bytes& page_hash) const { const auto iterator = family.live_nodes.find(page_hash); return iterator == family.live_nodes.end() ? kInvalidNodeId : iterator->second.online_id; @@ -664,7 +810,7 @@ StoreStatus CycleStateMachine::Persist(JournalEntry entry) { return status; } -LookupResult CycleStateMachine::IssueLookup(const LookupCommand& command) { +LookupResult CycleStateMachine::IssueLookup(LookupCommand command) { LookupResult result; if (recovery_required_) { result.result = FsmResult::kUnavailable; @@ -700,8 +846,11 @@ LookupResult CycleStateMachine::IssueLookup(const LookupCommand& command) { } Digest path_digest{}, evidence_digest{}; + bool evidence_reused = false; if (command.operation_id.empty() || - !ValidateEvidence(command.family, command.path, &path_digest, &evidence_digest, &result)) { + !ResolveEvidence(command.family, command.evidence_capability, command.issued_at_ms, + &command.path, &path_digest, &evidence_digest, &evidence_reused, + &result)) { if (command.operation_id.empty()) result.result = FsmResult::kInvalidEvidence; return result; } @@ -790,8 +939,9 @@ LookupResult CycleStateMachine::IssueLookup(const LookupCommand& command) { token.anchor = RootRef(command.family, fence); } - const auto lookup_digest = ComputeLookupInputDigest(command.family, command.operation_id, - command.path, command.requested_ttl); + const auto lookup_digest = ComputeLookupInputDigest( + command.family, command.operation_id, path_digest, evidence_digest, + command.requested_ttl); if (!lookup_digest) { result.result = FsmResult::kInvalidEvidence; result.detail = "lookup input encoding failed"; @@ -824,6 +974,25 @@ LookupResult CycleStateMachine::IssueLookup(const LookupCommand& command) { result.detail = "lookup token encoding failed"; return result; } + std::optional issued_capability; + if (evidence_reused) { + issued_capability = command.evidence_capability; + } else if (token.has_expected_tip) { + EvidenceCapabilityRecord capability; + capability.family = command.family; + capability.data_epoch = token.data_epoch; + capability.family_incarnation = token.family_incarnation; + capability.root_generation = fence.current_root_generation; + capability.root_locked_ttl = fence.current_root_locked_ttl; + capability.expected_tip = token.expected_tip; + capability.canonical_path_digest = path_digest; + capability.complete_page_evidence_digest = evidence_digest; + capability.validated_apply_index = command.apply_index; + capability.page_count = static_cast(command.path.pages.size()); + issued_capability = std::move(capability); + } + if (issued_capability.has_value()) + operation.issued_capability_encoding = EncodeEvidenceCapability(*issued_capability); JournalEntry entry; entry.apply_index = command.apply_index; entry.term = command.term; @@ -833,6 +1002,12 @@ LookupResult CycleStateMachine::IssueLookup(const LookupCommand& command) { entry.mutations.push_back({RecordKind::kOperation, EncodeOperationRecordKey(OperationRecordKey{command.family, command.operation_id}), false, EncodeOperationRecord(operation)}); + if (issued_capability.has_value() && !evidence_reused) { + entry.mutations.push_back({RecordKind::kEvidenceCapability, + EncodeEvidenceCapabilityKey(EvidenceCapabilityKey{ + command.family, issued_capability->canonical_path_digest}), false, + EncodeEvidenceCapability(*issued_capability)}); + } ExpiryIndexKey expiry_key; expiry_key.gc_at_ms = prune_barrier; expiry_key.type = ExpiryType::kOperation; @@ -859,14 +1034,16 @@ LookupResult CycleStateMachine::IssueLookup(const LookupCommand& command) { operations_[OperationMapKey(command.family, command.operation_id)] = OperationStateValue{command.family, operation, token}; ++operation_counts_by_family_[FamilyMapKey(command.family)]; + if (issued_capability.has_value()) TrackCapability(*issued_capability); result.result = FsmResult::kOk; result.has_token = true; result.token = token; result.alive_depth = token.alive_depth; + result.evidence_capability = std::move(issued_capability); return result; } -LookupResult CycleStateMachine::ReadLookup(const LookupCommand& command) { +LookupResult CycleStateMachine::ReadLookup(LookupCommand command) { LookupResult result; if (recovery_required_) { result.result = FsmResult::kUnavailable; @@ -902,9 +1079,77 @@ LookupResult CycleStateMachine::ReadLookup(const LookupCommand& command) { result.detail = "read barrier is behind token issuance"; return result; } - const auto input = ComputeLookupInputDigest(command.family, command.operation_id, - command.path, command.requested_ttl); - if (!input || existing->second.record.lookup_input_digest != *input) { + Digest path_digest{}, evidence_digest{}; + bool evidence_reused = false; + bool capability_history_required = false; + bool operation_bound_capability = false; + if (command.evidence_capability.has_value() && command.path.pages.empty() && + existing->second.record.canonical_lookup_token_payload == + EncodeLookupToken(existing->second.token)) { + capability_history_required = true; + const EvidenceCapabilityRecord& capability = *command.evidence_capability; + operation_bound_capability = HasOperationCapabilityEncoding( + existing->second.record, EncodeEvidenceCapability(capability)); + const LookupToken& token = existing->second.token; + const NodeRefRecord& tip = token.expected_tip; + const bool matches_token = + capability.schema_version == 1 && + EncodeFamilyKey(capability.family) == EncodeFamilyKey(token.family) && + capability.data_epoch == token.data_epoch && + capability.family_incarnation == token.family_incarnation && + capability.root_generation == token.read_root_generation && + capability.root_locked_ttl == token.read_root_locked_ttl && + capability.validated_apply_index != 0 && + capability.validated_apply_index <= token.read_apply_index && + token.has_expected_tip && capability.expected_tip.node_id == tip.node_id && + capability.expected_tip.node_incarnation == tip.node_incarnation && + capability.expected_tip.page_hash == tip.page_hash && + capability.expected_tip.depth == tip.depth && + capability.page_count == tip.depth + 1 && + (tip.depth != 0 || tip.page_hash == token.family.family_root_hash) && + capability.canonical_path_digest == token.canonical_path_digest && + capability.complete_page_evidence_digest == token.complete_page_evidence_digest; + const auto replay_digest = matches_token ? ComputeLookupInputDigest( + command.family, command.operation_id, capability.canonical_path_digest, + capability.complete_page_evidence_digest, command.requested_ttl) : std::nullopt; + // Read replay is authorized by this operation's exact persisted + // capability history, not its mutable latest-value capability slot. + if (replay_digest && *replay_digest == existing->second.record.lookup_input_digest && + existing->second.record.requested_ttl == command.requested_ttl && + operation_bound_capability) { + path_digest = capability.canonical_path_digest; + evidence_digest = capability.complete_page_evidence_digest; + evidence_reused = true; + } + } + if (!evidence_reused && + !ResolveEvidence(command.family, command.evidence_capability, command.issued_at_ms, + &command.path, &path_digest, &evidence_digest, &evidence_reused, + &result)) + return result; + const auto input = ComputeLookupInputDigest( + command.family, command.operation_id, path_digest, evidence_digest, + command.requested_ttl); + bool same_input = input && existing->second.record.lookup_input_digest == *input; + if (!same_input && !evidence_reused) { + const auto legacy = ComputeLookupInputDigest(command.family, command.operation_id, + command.path, command.requested_ttl); + same_input = legacy && existing->second.record.lookup_input_digest == *legacy; + } + const bool same_token_evidence = + existing->second.token.canonical_path_digest == path_digest && + existing->second.token.complete_page_evidence_digest == evidence_digest && + existing->second.record.requested_ttl == command.requested_ttl; + if (capability_history_required && evidence_reused && same_token_evidence && + !operation_bound_capability) { + result.result = FsmResult::kInvalidEvidence; + result.evidence_fallback_required = true; + result.has_token = false; + result.detail = "evidence capability rejected (operation_capability_origin); " + "retry with complete page evidence"; + return result; + } + if ((!same_input && !(evidence_reused && same_token_evidence)) || !same_token_evidence) { result.result = FsmResult::kOperationIdConflict; result.detail = "lookup retry has different input"; return result; @@ -913,6 +1158,7 @@ LookupResult CycleStateMachine::ReadLookup(const LookupCommand& command) { result.has_token = true; result.token = existing->second.token; result.alive_depth = result.token.alive_depth; + if (evidence_reused) result.evidence_capability = command.evidence_capability; return result; } diff --git a/src/cyclestore/src/fsm_commit.cc b/src/cyclestore/src/fsm_commit.cc index 962b1c3c..adbaa8f6 100644 --- a/src/cyclestore/src/fsm_commit.cc +++ b/src/cyclestore/src/fsm_commit.cc @@ -34,7 +34,7 @@ bool AddRetention(std::int64_t time, std::uint64_t retention, std::int64_t* resu } // namespace -CommitResult CycleStateMachine::ApplyCommit(const CommitCommand& command) { +CommitResult CycleStateMachine::ApplyCommit(CommitCommand command) { CommitResult result; if (recovery_required_) { result.result = FsmResult::kUnavailable; @@ -57,18 +57,80 @@ CommitResult CycleStateMachine::ApplyCommit(const CommitCommand& command) { const auto existing_operation = operations_.find(operation_key); FamilyState* family = FindFamily(token.family); const std::uint64_t observed_generation = family == nullptr ? 0 : family->fence.current_root_generation; - const std::optional commit_digest = ComputeCommitInputDigest( - command.canonical_lookup_token, command.path, command.prefill_completed_at_ms); - if (!commit_digest) { - result.result = FsmResult::kInvalidEvidence; - result.detail = "commit input encoding failed"; - result.receipt.outcome = static_cast(result.result); - return result; + Digest path_digest{}, evidence_digest{}; + bool evidence_reused = false; + const bool capability_only_request = + command.evidence_capability.has_value() && command.path.pages.empty(); + if (capability_only_request && + existing_operation != operations_.end() && + existing_operation->second.record.has_final_receipt && + existing_operation->second.record.commit_input_semantic_v2 && + existing_operation->second.record.canonical_lookup_token_payload == + command.canonical_lookup_token) { + const EvidenceCapabilityRecord& capability = *command.evidence_capability; + const NodeRefRecord& tip = token.expected_tip; + const Bytes capability_encoding = EncodeEvidenceCapability(capability); + const bool operation_bound_capability = HasOperationCapabilityEncoding( + existing_operation->second.record, capability_encoding); + const bool matches_token = + operation_bound_capability && capability.schema_version == 1 && + EncodeFamilyKey(capability.family) == EncodeFamilyKey(token.family) && + capability.data_epoch == token.data_epoch && + capability.family_incarnation == token.family_incarnation && + capability.root_generation == token.read_root_generation && + capability.root_locked_ttl == token.read_root_locked_ttl && + capability.validated_apply_index != 0 && + capability.validated_apply_index <= token.read_apply_index && + token.has_expected_tip && capability.expected_tip.node_id == tip.node_id && + capability.expected_tip.node_incarnation == tip.node_incarnation && + capability.expected_tip.page_hash == tip.page_hash && + capability.expected_tip.depth == tip.depth && + capability.page_count == tip.depth + 1 && + (tip.depth != 0 || tip.page_hash == token.family.family_root_hash) && + capability.canonical_path_digest == token.canonical_path_digest && + capability.complete_page_evidence_digest == token.complete_page_evidence_digest; + // A retained capability with the exact token/path identity proves the + // transport form. The FINAL comparison below decides replay versus a real + // prefill conflict; mutable latest coverage must not turn that conflict + // into a fallback or a replacement receipt. + if (matches_token) { + path_digest = capability.canonical_path_digest; + evidence_digest = capability.complete_page_evidence_digest; + evidence_reused = true; + } } - if (existing_operation != operations_.end() && existing_operation->second.record.has_final_receipt) { + const bool operation_history_validated = evidence_reused; + auto finish_final_replay = [&](const std::optional& candidate) { FsmResult replay_result = static_cast(existing_operation->second.record.final_receipt.outcome); CommitReceiptRecord replay_receipt = existing_operation->second.record.final_receipt; - const bool identical_input = existing_operation->second.record.commit_input_digest == *commit_digest; + bool identical_input = candidate && + existing_operation->second.record.commit_input_digest == *candidate; + if (!identical_input && !evidence_reused) { + const auto legacy = ComputeCommitInputDigest( + command.canonical_lookup_token, command.path, command.prefill_completed_at_ms); + identical_input = legacy && existing_operation->second.record.commit_input_digest == *legacy; + } + CommitResult replay; + if (!identical_input && evidence_reused && + !existing_operation->second.record.commit_input_semantic_v2) { + // Legacy v1 records commit prefill only inside a hash of the complete + // page vector. Without that vector we cannot prove identical replay; + // require the caller's full evidence instead of a false terminal conflict. + replay.result = FsmResult::kInvalidEvidence; + replay.evidence_fallback_required = true; + replay.detail = "legacy FINAL replay requires complete page evidence"; + return replay; + } + if (capability_only_request && !operation_history_validated && identical_input && + replay_result != FsmResult::kEvidenceConflict) { + // Generic live coverage proves neither this operation's capability + // history nor its token read watermark. Never let it authorize replay + // of an existing FINAL receipt or echo an unbound capability. + replay.result = FsmResult::kInvalidEvidence; + replay.evidence_fallback_required = true; + replay.detail = "FINAL replay requires operation-bound evidence capability"; + return replay; + } if (!identical_input || replay_result == FsmResult::kEvidenceConflict) { replay_result = FsmResult::kOperationIdConflict; replay_receipt = CommitReceiptRecord{}; @@ -83,16 +145,60 @@ CommitResult CycleStateMachine::ApplyCommit(const CommitCommand& command) { entry.term = command.term; const StoreStatus status = Persist(std::move(entry)); if (!status.ok()) { - result.result = FsmResult::kUnavailable; - result.receipt.outcome = static_cast(result.result); - result.detail = status.detail; - return result; + replay.result = FsmResult::kUnavailable; + replay.receipt.outcome = static_cast(replay.result); + replay.detail = status.detail; + return replay; } - result.receipt = replay_receipt; - result.result = replay_result; - result.receipt_replayed = replay_result != FsmResult::kOperationIdConflict; + replay.receipt = replay_receipt; + replay.result = replay_result; + replay.receipt_replayed = replay_result != FsmResult::kOperationIdConflict; if (replay_result == FsmResult::kOperationIdConflict) - result.detail = "final receipt exists with different full commit input"; + replay.detail = "final receipt exists with different full commit input"; + else if (evidence_reused) + replay.evidence_capability = command.evidence_capability; + return replay; + }; + const bool replay_full_final = existing_operation != operations_.end() && + existing_operation->second.record.has_final_receipt && + (!command.evidence_capability.has_value() || !command.path.pages.empty()); + if (replay_full_final) { + // Complete-evidence retries retain the original idempotent conflict + // semantics: token/path binding is compared before current live coverage. + // Malformed or cross-generation full input cannot fabricate a replacement + // receipt for a durable FINAL operation. + const auto canonical = ComputeCanonicalPathDigest(command.path); + const auto complete = ComputeCompletePageEvidenceDigest(command.path); + std::optional full_digest; + if (canonical && complete) { + path_digest = *canonical; + evidence_digest = *complete; + full_digest = ComputeCommitInputDigest(command.canonical_lookup_token, + path_digest, evidence_digest, command.prefill_completed_at_ms); + } + return finish_final_replay(full_digest); + } + LookupResult evidence_failure; + if (!evidence_reused && + !ResolveEvidence(token.family, command.evidence_capability, command.accepted_at_ms, + &command.path, &path_digest, &evidence_digest, &evidence_reused, + &evidence_failure)) { + result.result = FsmResult::kInvalidEvidence; + result.detail = evidence_failure.detail; + result.evidence_fallback_required = evidence_failure.evidence_fallback_required; + result.receipt.outcome = static_cast(result.result); + result.receipt.apply_index = command.apply_index; + return result; + } + const std::optional commit_digest = ComputeCommitInputDigest( + command.canonical_lookup_token, path_digest, evidence_digest, + command.prefill_completed_at_ms); + if (existing_operation != operations_.end() && existing_operation->second.record.has_final_receipt) + return finish_final_replay(commit_digest); + if (!commit_digest) { + result.result = FsmResult::kInvalidEvidence; + result.detail = "commit input encoding failed"; + result.receipt.outcome = static_cast(result.result); return result; } result.receipt.outcome = static_cast(FsmResult::kUnavailable); @@ -115,8 +221,9 @@ CommitResult CycleStateMachine::ApplyCommit(const CommitCommand& command) { if (existing_operation != operations_.end()) { negative_record = existing_operation->second.record; } else { - const auto lookup_digest = ComputeLookupInputDigest(token.family, token.operation_id, - command.path, token.requested_ttl); + const auto lookup_digest = ComputeLookupInputDigest( + token.family, token.operation_id, path_digest, evidence_digest, + token.requested_ttl); if (!lookup_digest) { result.result = FsmResult::kInvalidEvidence; result.receipt.outcome = static_cast(result.result); @@ -133,6 +240,10 @@ CommitResult CycleStateMachine::ApplyCommit(const CommitCommand& command) { negative_record.state = OperationState::kFinal; negative_record.has_final_receipt = true; negative_record.commit_input_digest = *commit_digest; + negative_record.commit_input_semantic_v2 = true; + if (command.evidence_capability.has_value() && evidence_reused) + negative_record.final_capability_encoding = + EncodeEvidenceCapability(*command.evidence_capability); negative_record.final_receipt = result.receipt; negative_record.receipt_final_state_at_ms = command.accepted_at_ms; std::int64_t receipt_gc = 0; @@ -220,16 +331,22 @@ CommitResult CycleStateMachine::ApplyCommit(const CommitCommand& command) { negative(FsmResult::kStaleLookupToken); return result; } - const auto key_lookup_input = ComputeLookupInputDigest(token.family, token.operation_id, command.path, - existing_operation->second.record.requested_ttl); - if (!key_lookup_input || existing_operation->second.record.lookup_input_digest != *key_lookup_input) { - negative(FsmResult::kEvidenceConflict); - return result; + const auto key_lookup_input = ComputeLookupInputDigest( + token.family, token.operation_id, path_digest, evidence_digest, + existing_operation->second.record.requested_ttl); + bool same_lookup_input = key_lookup_input && + existing_operation->second.record.lookup_input_digest == *key_lookup_input; + if (!same_lookup_input && !evidence_reused) { + const auto legacy = ComputeLookupInputDigest(token.family, token.operation_id, command.path, + existing_operation->second.record.requested_ttl); + same_lookup_input = legacy && existing_operation->second.record.lookup_input_digest == *legacy; } - Digest path_digest{}, evidence_digest{}; - LookupResult invalid; - if (!ValidateEvidence(token.family, command.path, &path_digest, &evidence_digest, &invalid)) { - negative(FsmResult::kInvalidEvidence); + if (!same_lookup_input && evidence_reused && + path_digest == token.canonical_path_digest && + evidence_digest == token.complete_page_evidence_digest) + same_lookup_input = true; + if (!same_lookup_input) { + negative(FsmResult::kEvidenceConflict); return result; } if (path_digest != token.canonical_path_digest || evidence_digest != token.complete_page_evidence_digest) { @@ -456,6 +573,7 @@ CommitResult CycleStateMachine::ApplyCommit(const CommitCommand& command) { final_operation.state = OperationState::kFinal; final_operation.has_final_receipt = true; final_operation.commit_input_digest = *commit_digest; + final_operation.commit_input_semantic_v2 = true; final_operation.final_receipt = receipt; final_operation.receipt_final_state_at_ms = command.accepted_at_ms; if (!AddRetention(command.accepted_at_ms, config_.retry_window_ms, @@ -468,6 +586,29 @@ CommitResult CycleStateMachine::ApplyCommit(const CommitCommand& command) { changed_fence.receipt_barrier_highwater_ms = std::max( changed_fence.receipt_barrier_highwater_ms, final_operation.receipt_gc_at_ms); + EvidenceCapabilityRecord committed_capability; + committed_capability.family = token.family; + committed_capability.data_epoch = changed_fence.data_epoch; + committed_capability.family_incarnation = changed_fence.family_incarnation; + committed_capability.root_generation = next_generation; + committed_capability.root_locked_ttl = locked_ttl; + committed_capability.expected_tip.node_id = tip_id; + committed_capability.expected_tip.node_incarnation = tip_incarnation; + committed_capability.expected_tip.page_hash = command.path.pages.back().page_hash; + committed_capability.expected_tip.depth = static_cast(command.path.pages.size() - 1); + committed_capability.canonical_path_digest = path_digest; + committed_capability.complete_page_evidence_digest = evidence_digest; + committed_capability.validated_apply_index = command.apply_index; + committed_capability.page_count = static_cast(command.path.pages.size()); + if (evidence_reused) { + // A reused Δ=0 commit did not validate a new client page vector. Preserve + // the existing proof so a lostresponse retry with the exact same request + // reaches FINAL replay instead of being rejected as an old watermark. + committed_capability = *command.evidence_capability; + } + final_operation.final_capability_encoding = + EncodeEvidenceCapability(committed_capability); + JournalEntry entry; entry.apply_index = command.apply_index; entry.term = command.term; @@ -534,6 +675,9 @@ CommitResult CycleStateMachine::ApplyCommit(const CommitCommand& command) { entry.mutations.push_back({RecordKind::kOperation, EncodeOperationRecordKey(OperationRecordKey{token.family, token.operation_id}), false, EncodeOperationRecord(final_operation)}); + entry.mutations.push_back({RecordKind::kEvidenceCapability, + EncodeEvidenceCapabilityKey(EvidenceCapabilityKey{token.family, path_digest}), false, + EncodeEvidenceCapability(committed_capability)}); ExpiryIndexKey expiry_key; expiry_key.gc_at_ms = lease.lease_gc_at_ms; expiry_key.type = ExpiryType::kLease; @@ -618,8 +762,10 @@ CommitResult CycleStateMachine::ApplyCommit(const CommitCommand& command) { family->leases.emplace(*lease_id, lease); family->fence = changed_fence; existing_operation->second.record = final_operation; + TrackCapability(committed_capability); result.result = positive; result.receipt = receipt; + result.evidence_capability = std::move(committed_capability); return result; } diff --git a/src/cyclestore/src/fsm_gc.cc b/src/cyclestore/src/fsm_gc.cc index f2062b1c..6c6b5cf4 100644 --- a/src/cyclestore/src/fsm_gc.cc +++ b/src/cyclestore/src/fsm_gc.cc @@ -259,6 +259,7 @@ FsmResult CycleStateMachine::Collect(const GcCommand& command) { entry.mutations.push_back({RecordKind::kNodeUniqueIndex, EncodeNodeUniqueKey(NodeUniqueKey{key.family, state.page_hash}), true, {}}); drop_index(stored.key); + EraseCapabilitiesForTip(key.family, state.id, &entry.mutations, false); pruned_nodes.emplace(state.id, key.family); pruned_children[state.parent_id].first = key.family; ++pruned_children[state.parent_id].second; @@ -341,6 +342,7 @@ FsmResult CycleStateMachine::Collect(const GcCommand& command) { EncodeNodeRecordKey(NodeRecordKey{key.family, root_node.second.id}), true, {}}); entry.mutations.push_back({RecordKind::kNodeUniqueIndex, EncodeNodeUniqueKey(NodeUniqueKey{key.family, root_node.second.page_hash}), true, {}}); + EraseCapabilitiesForTip(key.family, root_node.second.id, &entry.mutations, false); } drop_index(stored.key); fence_dropped = true; @@ -429,6 +431,7 @@ FsmResult CycleStateMachine::Collect(const GcCommand& command) { recovery_required_ = true; return FsmResult::kUnavailable; } + EraseCapabilitiesForTip(family->key, id, nullptr, true); family->live_nodes.erase(hash); family->hash_by_id.erase(id); family->online_by_id.erase(id); @@ -477,6 +480,8 @@ FsmResult CycleStateMachine::Collect(const GcCommand& command) { operations_.at(ExpiryOperationKey(operation_key)).record = retired; } if (fence_dropped) { + EraseCapabilitiesForTip(target->key, RootRef(target->key, target->fence).node_id, + nullptr, true); target->live_nodes.clear(); target->hash_by_id.clear(); target->online_by_id.clear(); diff --git a/src/cyclestore/src/journal.cc b/src/cyclestore/src/journal.cc index fbf34ae3..095b6534 100644 --- a/src/cyclestore/src/journal.cc +++ b/src/cyclestore/src/journal.cc @@ -78,7 +78,10 @@ std::uint32_t Load32(const std::uint8_t bytes[4]) { return value; } -bool ValidKind(std::uint8_t kind) { return kind >= 1 && kind <= 8; } +bool ValidKind(std::uint8_t kind) { + return kind >= static_cast(RecordKind::kShardMeta) && + kind <= static_cast(RecordKind::kEvidenceCapability); +} Bytes MutationMapKey(const RecordMutation& mutation) { Bytes key; diff --git a/src/cyclestore/src/records.cc b/src/cyclestore/src/records.cc index f8c4a767..3eac624d 100644 --- a/src/cyclestore/src/records.cc +++ b/src/cyclestore/src/records.cc @@ -419,6 +419,10 @@ Bytes EncodeExpiryIndexKey(const ExpiryIndexKey& key) { Writer w; w.U8('X'); w.I64(key.gc_at_ms); w.U8(static_cast(key.type)); WriteFamily(&w, key.family); w.LP(key.object_key); w.Id(key.incarnation); return w.Finish(); } +Bytes EncodeEvidenceCapabilityKey(const EvidenceCapabilityKey& key) { + Writer w; w.U8('V'); WriteFamily(&w, key.family); + w.DigestValue(key.canonical_path_digest); return w.Finish(); +} bool DecodeCheckpointKey(const Bytes& encoded, std::uint64_t* snapshot_index, std::string* error) { if (!HasPrefix(encoded, 'C') || encoded.size() != 9) return Fail(error, "invalid checkpoint key"); @@ -469,6 +473,15 @@ bool DecodeExpiryIndexKey(const Bytes& encoded, ExpiryIndexKey* key, std::string key->type = static_cast(type); return true; } +bool DecodeEvidenceCapabilityKey(const Bytes& encoded, EvidenceCapabilityKey* key, + std::string* error) { + if (!HasPrefix(encoded, 'V')) return Fail(error, "invalid capability key prefix"); + Reader r(encoded); std::uint8_t prefix = 0; + if (!r.U8(&prefix) || !ReadFamily(&r, &key->family) || + !r.DigestValue(&key->canonical_path_digest) || !r.End()) + return Fail(error, "malformed evidence capability key"); + return true; +} Bytes EncodeShardMeta(const ShardMeta& r) { Writer w; w.U32(kRecordSchemaVersion); w.U64(r.last_applied_index); w.U64(r.last_applied_term); @@ -578,7 +591,8 @@ Bytes EncodeOperationRecord(const OperationRecord& r) { w.DigestValue(r.lookup_input_digest); w.DigestValue(r.commit_input_digest); w.Bool(r.has_final_receipt); if (r.has_final_receipt) WriteReceipt(&w, r.final_receipt); w.I64(r.receipt_final_state_at_ms); w.I64(r.receipt_gc_at_ms); w.U64(r.token_apply_index); - w.Bool(r.token_expired); return w.Finish(); + w.Bool(r.token_expired); w.Bool(r.commit_input_semantic_v2); + w.LP(r.issued_capability_encoding); w.LP(r.final_capability_encoding); return w.Finish(); } bool DecodeOperationRecord(const Bytes& encoded, OperationRecord* out, std::string* error) { Reader r(encoded); if (!BeginValue(&r, error)) return false; std::uint8_t state = 0; @@ -587,6 +601,9 @@ bool DecodeOperationRecord(const Bytes& encoded, OperationRecord* out, std::stri !r.LP(&out->token_auth) || !r.U32(&out->auth_key_id) || !r.DigestValue(&out->lookup_input_digest) || !r.DigestValue(&out->commit_input_digest) || !r.Bool(&out->has_final_receipt)) return Fail(error, "malformed operation record"); + out->commit_input_semantic_v2 = false; + out->issued_capability_encoding.clear(); + out->final_capability_encoding.clear(); out->state = static_cast(state); if (out->has_final_receipt && !ReadReceipt(&r, &out->final_receipt)) return Fail(error, "malformed final receipt"); @@ -597,6 +614,17 @@ bool DecodeOperationRecord(const Bytes& encoded, OperationRecord* out, std::stri return Fail(error, "final operation missing receipt"); if (out->state == OperationState::kTokenIssued && out->has_final_receipt) return Fail(error, "token operation has premature receipt"); + if (!r.End() && !r.Bool(&out->commit_input_semantic_v2)) + return Fail(error, "malformed operation input version"); + if (!r.End() && (!r.LP(&out->issued_capability_encoding) || + !r.LP(&out->final_capability_encoding))) + return Fail(error, "malformed operation capability history"); + EvidenceCapabilityRecord capability; + if ((!out->issued_capability_encoding.empty() && + !DecodeEvidenceCapability(out->issued_capability_encoding, &capability, error)) || + (!out->final_capability_encoding.empty() && + !DecodeEvidenceCapability(out->final_capability_encoding, &capability, error))) + return Fail(error, "malformed operation capability history"); return EndValue(r, error); } @@ -612,6 +640,52 @@ bool DecodeExpiryIndex(const Bytes& encoded, ExpiryIndex* out, std::string* erro return EndValue(r, error); } +Bytes EncodeEvidenceCapability(const EvidenceCapabilityRecord& c) { + Writer w; w.U32(kRecordSchemaVersion); w.U32(c.schema_version); + WriteFamily(&w, c.family); w.U64(c.data_epoch); w.U64(c.family_incarnation); + w.U64(c.root_generation); w.Ttl(c.root_locked_ttl); WriteNodeRef(&w, c.expected_tip); + w.DigestValue(c.canonical_path_digest); w.DigestValue(c.complete_page_evidence_digest); + w.U64(c.validated_apply_index); w.U32(c.page_count); return w.Finish(); +} +bool SameEvidenceCapability(const EvidenceCapabilityRecord& left, + const EvidenceCapabilityRecord& right) { + return left.schema_version == right.schema_version && + left.family.scope_id == right.family.scope_id && + left.family.cache_domain_id == right.family.cache_domain_id && + left.family.family_root_hash == right.family.family_root_hash && + left.data_epoch == right.data_epoch && + left.family_incarnation == right.family_incarnation && + left.root_generation == right.root_generation && + left.root_locked_ttl == right.root_locked_ttl && + left.expected_tip.node_id == right.expected_tip.node_id && + left.expected_tip.node_incarnation == right.expected_tip.node_incarnation && + left.expected_tip.page_hash == right.expected_tip.page_hash && + left.expected_tip.depth == right.expected_tip.depth && + left.canonical_path_digest == right.canonical_path_digest && + left.complete_page_evidence_digest == right.complete_page_evidence_digest && + left.validated_apply_index == right.validated_apply_index && + left.page_count == right.page_count; +} + +bool DecodeEvidenceCapability(const Bytes& encoded, EvidenceCapabilityRecord* out, + std::string* error) { + Reader r(encoded); if (!BeginValue(&r, error)) return false; + if (!r.U32(&out->schema_version) || out->schema_version != 1 || + !ReadFamily(&r, &out->family) || !r.U64(&out->data_epoch) || + !r.U64(&out->family_incarnation) || !r.U64(&out->root_generation) || + !r.Ttl(&out->root_locked_ttl)) return Fail(error, "malformed evidence capability"); + out->expected_tip = NodeRefRecord{}; + if (!r.Id(&out->expected_tip.node_id) || !r.Id(&out->expected_tip.node_incarnation) || + !r.LP(&out->expected_tip.page_hash) || !r.U32(&out->expected_tip.depth) || + !r.DigestValue(&out->canonical_path_digest) || + !r.DigestValue(&out->complete_page_evidence_digest) || + !r.U64(&out->validated_apply_index) || !r.U32(&out->page_count) || + out->validated_apply_index == 0 || out->page_count == 0 || + out->expected_tip.depth + 1 != out->page_count) + return Fail(error, "malformed evidence capability payload"); + return EndValue(r, error); +} + Bytes EncodeCanonicalPathEvidence(const PathEvidenceRecord& path) { Writer w; w.U32(kRecordSchemaVersion); WritePath(&w, path, false); return w.Finish(); } @@ -645,6 +719,23 @@ std::optional ComputeCommitInputDigest(const Bytes& canonical_lookup_tok w.LP(complete_evidence); w.U64(prefill_completed_at_ms); return DomainDigest("cyclestore.commit_input.v1", w.Finish()); } +std::optional ComputeLookupInputDigest( + const FamilyKey& family, const std::string& operation_id, + const Digest& canonical_path_digest, const Digest& complete_page_evidence_digest, + TtlClass requested_ttl) { + Writer w; WriteFamily(&w, family); w.LP(operation_id); + w.DigestValue(canonical_path_digest); w.DigestValue(complete_page_evidence_digest); + w.Ttl(requested_ttl); + return DomainDigest("cyclestore.lookup_input.v2", w.Finish()); +} +std::optional ComputeCommitInputDigest( + const Bytes& canonical_lookup_token_payload, const Digest& canonical_path_digest, + const Digest& complete_page_evidence_digest, std::uint64_t prefill_completed_at_ms) { + Writer w; w.LP(canonical_lookup_token_payload); + w.DigestValue(canonical_path_digest); w.DigestValue(complete_page_evidence_digest); + w.U64(prefill_completed_at_ms); + return DomainDigest("cyclestore.commit_input.v2", w.Finish()); +} std::optional DeriveNodeId(const FamilyKey& family, const BirthIdentity& birth, const Bytes& page_hash) { diff --git a/src/cyclestore/src/store_rocksdb.cc b/src/cyclestore/src/store_rocksdb.cc index a75a597d..bbccf6ec 100644 --- a/src/cyclestore/src/store_rocksdb.cc +++ b/src/cyclestore/src/store_rocksdb.cc @@ -37,7 +37,8 @@ std::size_t ColumnFamilyIndex(RecordKind kind) { case RecordKind::kNode: case RecordKind::kNodeUniqueIndex: return 2; case RecordKind::kLease: return 3; - case RecordKind::kOperation: return 4; + case RecordKind::kOperation: + case RecordKind::kEvidenceCapability: return 4; case RecordKind::kExpiryIndex: return 5; } return kColumnFamilyCount; @@ -109,6 +110,10 @@ bool DecodeRecordKey(RecordKind kind, const Bytes& key, std::string* error) { ExpiryIndexKey decoded; return DecodeExpiryIndexKey(key, &decoded, error); } + case RecordKind::kEvidenceCapability: { + EvidenceCapabilityKey decoded; + return DecodeEvidenceCapabilityKey(key, &decoded, error); + } } *error = "unknown record kind"; return false; @@ -124,6 +129,9 @@ bool DecodeRecordValue(RecordKind kind, const Bytes& value, std::string* error) case RecordKind::kLease: { LeaseRecord v; return DecodeLeaseRecord(value, &v, error); } case RecordKind::kOperation: { OperationRecord v; return DecodeOperationRecord(value, &v, error); } case RecordKind::kExpiryIndex: { ExpiryIndex v; return DecodeExpiryIndex(value, &v, error); } + case RecordKind::kEvidenceCapability: { + EvidenceCapabilityRecord v; return DecodeEvidenceCapability(value, &v, error); + } } *error = "unknown record kind"; return false; @@ -347,7 +355,9 @@ StoreStatus Store::ScanRecords(RecordKind kind, std::vector* recor } if (kind == RecordKind::kCheckpoint && record.key == EncodeShardMetaKey()) continue; if ((kind == RecordKind::kNode && record.key.front() != 'N') || - (kind == RecordKind::kNodeUniqueIndex && record.key.front() != 'U')) continue; + (kind == RecordKind::kNodeUniqueIndex && record.key.front() != 'U') || + (kind == RecordKind::kOperation && record.key.front() != 'O') || + (kind == RecordKind::kEvidenceCapability && record.key.front() != 'V')) continue; std::string decode_error; if (!DecodeRecordKey(kind, record.key, &decode_error) || !DecodeRecordValue(kind, record.value, &decode_error)) diff --git a/src/cyclestore/test/capability_helper_manifest.json b/src/cyclestore/test/capability_helper_manifest.json new file mode 100644 index 00000000..f9fc7ff8 --- /dev/null +++ b/src/cyclestore/test/capability_helper_manifest.json @@ -0,0 +1,21 @@ +{ + "schema": "cyclestore-capability-helper-closure-v1", + "origin": { + "worktree": "cyclestore-pr634-main-reviewfix-GxAsgC", + "source_head": "384106e52cae51a4f2902b2d0b7cda75cdfaa9b1", + "integration_preview": "92032bb957e68c5a9e368508107b2d563481398d", + "actual_merged_main": "1df1493f145ff5ddf408a60a7aa067d7fc865a4f", + "base_path": "src/cyclestore/test", + "prepared_only": false + }, + "runtime_verified_files": { + "raft_integration_test.py": "c689404406df25fbac16292b4aebbf27d8b5bef67cbaf62dbb41617bc9153ff9", + "raft_business_integration_test.py": "8cfb82f2461aacb2b5795c2b49c0812ddc908c0b68a528b54dd134505f6f7cb5", + "raft_business_perf_test.py": "55fc4d493a8626fe8dcafc9a5cbff64e8fa9d904b80059ebd79caf87ee7ef322" + }, + "compiled_helper_origins": { + "persistent_cycle_client.cc": "2d9d3e60a5fbcd96dd1410edca47b09f44bab29658d446f2efd591ba66ecd36d", + "store_perf_audit_main.cc": "7579eae0fa889f72202e839a5f2adca98d885dca83f4b0fcc75b4c198182644f" + }, + "notes": "Main-connected candidate provenance only, not a production-readiness claim. source_head is the validated source parent before the actual-main connection and this provenance update. actual_merged_main is the observed upstream PR631 merge; integration_preview has exactly the same tree as that merge. The runtime hashes identify the actual recomposed helpers, including the restored PR631/main evidence assertions, deterministic malformed-RPC coverage, and the adapter append-depth repair; they are not claimed to be byte-identical to the old S4 origin. Both C++ hashes likewise identify the exact helper sources in this candidate." +} diff --git a/src/cyclestore/test/persistent_cycle_client.cc b/src/cyclestore/test/persistent_cycle_client.cc new file mode 100644 index 00000000..7ed09b66 --- /dev/null +++ b/src/cyclestore/test/persistent_cycle_client.cc @@ -0,0 +1,323 @@ +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include "cycle_store.pb.h" +#include "raft_control.pb.h" +#include "cyclestore/fsm_raft.h" + +DEFINE_string(address, "", "leader 127.0.0.1:port"); +DEFINE_int32(rpc_timeout_ms, 30000, "per-RPC timeout"); +DEFINE_bool(single_status, false, "execute one status RPC and exit"); +DEFINE_bool(instrument_payload, false, "measure JSON/proto/business-frame sizes and serialization outside Stub RTT"); + +namespace dfkv::cyclestore { +namespace { + +using Clock = std::chrono::steady_clock; +namespace control = dfkv::cyclestore::raft::test; + +std::int64_t Nanos(Clock::time_point start, Clock::time_point end) { + return std::chrono::duration_cast(end - start).count(); +} + +std::string JsonEscape(const std::string& input) { + std::string output; + output.reserve(input.size() + 8); + for (const unsigned char value : input) { + switch (value) { + case '\\': output += "\\\\"; break; + case '"': output += "\\\""; break; + case '\n': output += "\\n"; break; + case '\r': output += "\\r"; break; + case '\t': output += "\\t"; break; + default: + if (value < 0x20) { + constexpr char kHex[] = "0123456789abcdef"; + output += "\\u00"; + output.push_back(kHex[value >> 4]); + output.push_back(kHex[value & 0xf]); + } else { + output.push_back(static_cast(value)); + } + } + } + return output; +} + +void PrintFailure(std::uint64_t sequence, const std::string& operation, + std::int64_t prepare_ns, const std::string& error) { + std::cout << "{\"sequence\":" << sequence << ",\"operation\":\"" + << operation << "\",\"prepare_latency_ns\":" << prepare_ns + << ",\"latency_ns\":0,\"ok\":false,\"error\":\"" + << JsonEscape(error) << "\"}\n"; + std::cout.flush(); +} + +template +std::string ResponseJson(const Response& response) { + google::protobuf::util::JsonPrintOptions options; + options.add_whitespace = false; + options.always_print_primitive_fields = true; + std::string output; + const auto status = google::protobuf::util::MessageToJsonString(response, &output, options); + return status.ok() ? output : std::string(); +} + +class PersistentClient { + public: + PersistentClient(std::string address, int timeout_ms) + : address_(std::move(address)), timeout_ms_(timeout_ms), + cycle_stub_(&channel_), control_stub_(&channel_) {} + + int Init() { + const auto started = Clock::now(); + if (channel_.Init(address_.c_str(), nullptr) != 0) return -1; + channel_init_ns_ = Nanos(started, Clock::now()); + return 0; + } + + std::int64_t channel_init_ns() const { return channel_init_ns_; } + + bool Status(std::uint64_t sequence) { + control::ControlRequest request; + request.set_operation("status"); + control::ControlResponse response; + brpc::Controller controller; + controller.set_timeout_ms(timeout_ms_); + const auto started = Clock::now(); + control_stub_.Control(&controller, &request, &response, nullptr); + const auto elapsed = Nanos(started, Clock::now()); + if (controller.Failed()) { + PrintFailure(sequence, "status", 0, controller.ErrorText()); + return false; + } + const std::string json = ResponseJson(response); + if (json.empty()) { + PrintFailure(sequence, "status", 0, "status response JSON serialization failed"); + return false; + } + PrintSuccess(sequence, "status", 0, elapsed, json); + return true; + } + + bool Lookup(std::uint64_t sequence, const std::string& path) { + const auto prepare_started = Clock::now(); + std::ifstream input(path); + if (!input) { + PrintFailure(sequence, "lookup", 0, "cannot open request JSON " + path); + return false; + } + const std::string source((std::istreambuf_iterator(input)), + std::istreambuf_iterator()); + v1::LookupRequest request; + const auto parse = google::protobuf::util::JsonStringToMessage(source, &request); + const auto prepare_ns = Nanos(prepare_started, Clock::now()); + if (!parse.ok()) { + PrintFailure(sequence, "lookup", prepare_ns, std::string(parse.ToString())); + return false; + } + std::string instrumentation; + if (FLAGS_instrument_payload) { + const auto serialize_started = Clock::now(); + std::string wire; + if (!request.SerializeToString(&wire)) { + PrintFailure(sequence, "lookup", prepare_ns, "lookup request protobuf serialization failed"); + return false; + } + const auto serialize_ns = Nanos(serialize_started, Clock::now()); + instrumentation = ",\"request_json_bytes\":" + std::to_string(source.size()) + + ",\"request_proto_bytes\":" + std::to_string(wire.size()) + + ",\"protobuf_serialize_ns\":" + std::to_string(serialize_ns); + } + v1::LookupResponse response; + brpc::Controller controller; + controller.set_timeout_ms(timeout_ms_); + const auto started = Clock::now(); + cycle_stub_.Lookup(&controller, &request, &response, nullptr); + const auto elapsed = Nanos(started, Clock::now()); + if (controller.Failed()) { + PrintFailure(sequence, "lookup", prepare_ns, controller.ErrorText()); + return false; + } + if (FLAGS_instrument_payload) { + const auto entry_started = Clock::now(); + const std::string entry = CycleRaftFsm::EncodeLookup(request, response.authoritative_now_ms()); + const auto entry_ns = Nanos(entry_started, Clock::now()); + if (entry.empty()) { + PrintFailure(sequence, "lookup", prepare_ns, "lookup business frame serialization failed"); + return false; + } + instrumentation += ",\"response_proto_bytes\":" + std::to_string(response.ByteSizeLong()) + + ",\"raft_business_command_bytes\":" + std::to_string(entry.size()) + + ",\"braft_task_payload_bytes\":" + std::to_string(entry.size() + 1) + + ",\"business_frame_encode_ns\":" + std::to_string(entry_ns); + } + const auto response_json_started = Clock::now(); + const std::string json = ResponseJson(response); + const auto response_json_ns = Nanos(response_json_started, Clock::now()); + if (json.empty()) { + PrintFailure(sequence, "lookup", prepare_ns, "lookup response JSON serialization failed"); + return false; + } + if (FLAGS_instrument_payload) + instrumentation += ",\"response_json_serialize_ns\":" + std::to_string(response_json_ns); + PrintSuccess(sequence, "lookup", prepare_ns, elapsed, json, instrumentation); + return true; + } + + bool Commit(std::uint64_t sequence, const std::string& path) { + const auto prepare_started = Clock::now(); + std::ifstream input(path); + if (!input) { + PrintFailure(sequence, "commit", 0, "cannot open request JSON " + path); + return false; + } + const std::string source((std::istreambuf_iterator(input)), + std::istreambuf_iterator()); + v1::CommitRequest request; + const auto parse = google::protobuf::util::JsonStringToMessage(source, &request); + const auto prepare_ns = Nanos(prepare_started, Clock::now()); + if (!parse.ok()) { + PrintFailure(sequence, "commit", prepare_ns, std::string(parse.ToString())); + return false; + } + std::string instrumentation; + if (FLAGS_instrument_payload) { + const auto serialize_started = Clock::now(); + std::string wire; + if (!request.SerializeToString(&wire)) { + PrintFailure(sequence, "commit", prepare_ns, "commit request protobuf serialization failed"); + return false; + } + const auto serialize_ns = Nanos(serialize_started, Clock::now()); + instrumentation = ",\"request_json_bytes\":" + std::to_string(source.size()) + + ",\"request_proto_bytes\":" + std::to_string(wire.size()) + + ",\"protobuf_serialize_ns\":" + std::to_string(serialize_ns); + } + v1::CommitResponse response; + brpc::Controller controller; + controller.set_timeout_ms(timeout_ms_); + const auto started = Clock::now(); + cycle_stub_.Commit(&controller, &request, &response, nullptr); + const auto elapsed = Nanos(started, Clock::now()); + if (controller.Failed()) { + PrintFailure(sequence, "commit", prepare_ns, controller.ErrorText()); + return false; + } + if (FLAGS_instrument_payload) { + if (!response.has_receipt() && !response.evidence_fallback_required()) { + PrintFailure(sequence, "commit", prepare_ns, "commit receipt missing; cannot reproduce accepted_at frame"); + return false; + } + instrumentation += ",\"response_proto_bytes\":" + std::to_string(response.ByteSizeLong()); + if (response.has_receipt()) { + const auto entry_started = Clock::now(); + const std::string entry = CycleRaftFsm::EncodeCommit( + request, static_cast(response.receipt().accepted_at_ms())); + const auto entry_ns = Nanos(entry_started, Clock::now()); + if (entry.empty()) { + PrintFailure(sequence, "commit", prepare_ns, "commit business frame serialization failed"); + return false; + } + instrumentation += ",\"raft_business_command_bytes\":" + std::to_string(entry.size()) + + ",\"braft_task_payload_bytes\":" + std::to_string(entry.size() + 1) + + ",\"business_frame_encode_ns\":" + std::to_string(entry_ns); + } + } + const auto response_json_started = Clock::now(); + const std::string json = ResponseJson(response); + const auto response_json_ns = Nanos(response_json_started, Clock::now()); + if (json.empty()) { + PrintFailure(sequence, "commit", prepare_ns, "commit response JSON serialization failed"); + return false; + } + if (FLAGS_instrument_payload) + instrumentation += ",\"response_json_serialize_ns\":" + std::to_string(response_json_ns); + PrintSuccess(sequence, "commit", prepare_ns, elapsed, json, instrumentation); + return true; + } + + private: + static void PrintSuccess(std::uint64_t sequence, const std::string& operation, + std::int64_t prepare_ns, std::int64_t latency_ns, + const std::string& response_json, + const std::string& instrumentation = {}) { + std::cout << "{\"sequence\":" << sequence << ",\"operation\":\"" << operation + << "\",\"prepare_latency_ns\":" << prepare_ns + << ",\"latency_ns\":" << latency_ns << ",\"ok\":true" + << instrumentation << ",\"response\":" << response_json << "}\n"; + std::cout.flush(); + } + + std::string address_; + int timeout_ms_; + brpc::Channel channel_; + v1::CycleStore_Stub cycle_stub_; + control::RaftControl_Stub control_stub_; + std::int64_t channel_init_ns_ = 0; +}; + +int Run(int argc, char** argv) { + google::ParseCommandLineFlags(&argc, &argv, true); + if (FLAGS_address.empty()) { + LOG(ERROR) << "--address is required"; + return 2; + } + PersistentClient client(FLAGS_address, FLAGS_rpc_timeout_ms); + if (client.Init() != 0) { + LOG(ERROR) << "cannot initialize brpc channel"; + return 1; + } + if (FLAGS_single_status) return client.Status(1) ? 0 : 1; + + std::cout << "{\"ready\":true,\"pid\":" << getpid() + << ",\"channel_init_ns\":" << client.channel_init_ns() << "}\n"; + std::cout.flush(); + std::string line; + std::uint64_t sequence = 0; + while (std::getline(std::cin, line)) { + const std::size_t split = line.find('\t'); + if (split == std::string::npos) { + PrintFailure(++sequence, "invalid", 0, "input must be operationrequest_path"); + continue; + } + const std::string operation = line.substr(0, split); + const std::string path = line.substr(split + 1); + if (operation == "quit") { + std::cout << "{\"done\":true,\"sequence\":" << sequence << "}\n"; + std::cout.flush(); + return 0; + } + ++sequence; + if (operation == "status") { + client.Status(sequence); + } else if (operation == "lookup") { + client.Lookup(sequence, path); + } else if (operation == "commit") { + client.Commit(sequence, path); + } else { + PrintFailure(sequence, operation, 0, "unknown operation " + operation); + } + } + return 0; +} + +} // namespace +} // namespace dfkv::cyclestore + +int main(int argc, char** argv) { + butil::AtExitManager exit_manager; + return dfkv::cyclestore::Run(argc, argv); +} diff --git a/src/cyclestore/test/raft_business_integration_test.py b/src/cyclestore/test/raft_business_integration_test.py index 7187e272..245f1035 100644 --- a/src/cyclestore/test/raft_business_integration_test.py +++ b/src/cyclestore/test/raft_business_integration_test.py @@ -293,6 +293,22 @@ def commit_request(lookup, now_ms, request_path=None): accepted_at_ms=t0, receipt_barrier=positive_only_fence["receipt_barrier_highwater_ms"]) + malformed_lookup = cluster.business( + leader, "lookup", lookup_request("malformed-full-no-final"), + "malformed-full-no-final-lookup") + malformed_request = commit_request(malformed_lookup, t0) + malformed_request["path"]["pages"] = [] + for attempt in ("initial", "retry"): + invalid = cluster.business( + leader, "commit", malformed_request, + f"malformed-full-no-final-{attempt}") + assert invalid["transportError"] == "INVALID_EVIDENCE" + assert not invalid.get("evidenceFallbackRequired", False) + assert "receipt" not in invalid + cluster.observe("CHECK", case="malformed_full_commit_is_deterministic", + initial="INVALID_EVIDENCE", retry="INVALID_EVIDENCE", + fabricated_receipts=0) + cluster.set_clocks(t0 + 1000) renew_lookup = cluster.business(leader, "lookup", lookup_request("renew"), "renew-lookup") assert renew_lookup["payload"]["intent"] == "RENEW_OR_EXTEND" diff --git a/src/cyclestore/test/raft_business_perf_test.py b/src/cyclestore/test/raft_business_perf_test.py new file mode 100644 index 00000000..06a18038 --- /dev/null +++ b/src/cyclestore/test/raft_business_perf_test.py @@ -0,0 +1,1315 @@ +#!/usr/bin/env python3 +"""S4 shadow-only B1/B2/B3 measurements using the real CycleStore brpc client. + +No result in this harness is a performance-gate verdict. Every measured RPC is +an actual generated CycleStore Lookup or Commit call against a three-process +braft group. Admin operations are used only for test clock, status, GC and +checkpoint control, never as substitutes for measured business requests. +""" + +import argparse +import base64 +import concurrent.futures +import copy +import hashlib +import json +import math +import os +from pathlib import Path +import select +import subprocess +import sys +import threading +import time +import traceback + +from raft_business_integration_test import BusinessCluster, b64 +from raft_integration_test import integer + + +COMMIT_FIELDS = { + "outcome", "logicalCommitApplied", "billingEligibleForNewCycle", + "rootGeneration", "observedCurrentGeneration", "acceptedAtMs", + "applyIndex", "lockedTtl", "leaseId", "leaseExpireAtMs", + "newNodeCount", "pathDigest", "receiptDigest", +} +LOOKUP_PAYLOAD_FIELDS = { + "family", "operationId", "familyIncarnation", "dataEpoch", + "canonicalPathDigest", "completePageEvidenceDigest", "readRootGeneration", + "readRootExpireAtMs", "readRootLocked_ttl", "intent", "anchor", + "readApplyIndex", "issuedAtMs", "prefillNotAfterMs", "commitNotAfterMs", + "aliveDepth", +} +# Protobuf JSON uses the original proto field name readRootLockedTtl. +LOOKUP_PAYLOAD_FIELDS.discard("readRootLocked_ttl") +LOOKUP_PAYLOAD_FIELDS.add("readRootLockedTtl") +CONFLICT_RESULTS = { + "CONFLICT", "EXPIRED", "STALE_LOOKUP_TOKEN", "OPERATION_ID_CONFLICT", + "EVIDENCE_CONFLICT", "TTL_CONFLICT", "STALE_EPOCH_FENCE", +} + + +def percentile(sorted_values, numerator, denominator=100): + if not sorted_values: + return None + rank = max(1, math.ceil((numerator / denominator) * len(sorted_values))) + return sorted_values[min(rank, len(sorted_values)) - 1] + + +def distribution(values): + ordered = sorted(int(value) for value in values) + result = { + "samples": len(ordered), + "latencies_ns": ordered, + "min_ns": ordered[0] if ordered else None, + "max_ns": ordered[-1] if ordered else None, + } + for name, numerator, denominator in ( + ("p50", 50, 100), ("p95", 95, 100), ("p99", 99, 100), + ("p99.9", 999, 1000), + ): + value = percentile(ordered, numerator, denominator) + result[f"{name}_ns"] = value + result[f"{name}_ms"] = value / 1_000_000 if value is not None else None + return result + + +def counter_distribution(values): + ordered = sorted(int(value) for value in values) + result = {"samples": len(ordered), "raw_values": ordered, + "min": ordered[0] if ordered else None, + "max": ordered[-1] if ordered else None} + for name, numerator, denominator in ( + ("p50", 50, 100), ("p95", 95, 100), ("p99", 99, 100), + ("p99.9", 999, 1000), + ): + result[name] = percentile(ordered, numerator, denominator) + return result + + +def family_for(root, scope="s4-shadow", domain="cyclestore-perf"): + return {"scopeId": scope, "cacheDomainId": domain, + "familyRootHash": b64(root)} + + +def path_for(root, family_tag, pages=16000, branch=None, start=0): + entries = [] + for depth in range(start, start + pages): + if depth == 0: + page = root + else: + suffix = "" if branch is None else f":{branch}" + page = hashlib.sha256(f"{family_tag}{suffix}:{depth}".encode()).digest() + evidence = hashlib.sha256(b"physical:" + page).digest() + entries.append({"pageHash": b64(page), "depth": depth, + "physicalEvidenceDigest": b64(evidence)}) + return {"pages": entries} + + +def branch_path(main_path, root, family_tag, branch): + pages = copy.deepcopy(main_path["pages"][:-1]) + tip = path_for(root, family_tag, pages=1, branch=branch, start=len(pages)) + pages.extend(tip["pages"]) + return {"pages": pages} + + +def appended_path(path, root, family_tag, count, tag): + base_depth = len(path["pages"]) + addition = path_for(root, family_tag, pages=count, branch=tag, start=base_depth) + return {"pages": path["pages"] + addition["pages"]} + + +class Monitor: + def __init__(self, cluster, interval_s): + self.cluster = cluster + self.interval_s = interval_s + self.samples = [] + self.started_ns = None + self.stopped_ns = None + self._stop = threading.Event() + self._thread = threading.Thread(target=self._run, name=f"{cluster.name}-monitor") + + def start(self): + self.started_ns = time.perf_counter_ns() + self._thread.start() + + def stop(self): + self._stop.set() + if self._thread.is_alive(): + self._thread.join(timeout=20) + self.stopped_ns = time.perf_counter_ns() + destination = self.cluster.root / "monitor.json" + destination.write_text(json.dumps({ + "started_unix_ms": int(self.cluster.monitor_wall_started * 1000) + if hasattr(self.cluster, "monitor_wall_started") else None, + "samples": self.samples, + }, sort_keys=True, indent=2)) + return self.summary() + + def _process_sample(self): + values = [] + for index, process in enumerate(self.cluster.processes): + if process is None or process.poll() is not None: + values.append({"replica": index, "alive": False}) + continue + try: + stat = Path(f"/proc/{process.pid}/stat").read_text() + fields = stat.rsplit(") ", 1)[1].split() + clk = os.sysconf(os.sysconf_names["SC_CLK_TCK"]) + status_text = Path(f"/proc/{process.pid}/status").read_text().splitlines() + status = {line.split(":", 1)[0]: line.split(":", 1)[1].strip() + for line in status_text if ":" in line} + values.append({ + "replica": index, "alive": True, "pid": process.pid, + "cpu_seconds": (int(fields[11]) + int(fields[12])) / clk, + "rss_bytes": int(status["VmRSS"].split()[0]) * 1024, + "threads": int(status["Threads"]), + }) + except (OSError, KeyError, ValueError) as error: + self.cluster.record_exception("monitor_process", error) + values.append({"replica": index, "alive": False, "error": str(error)}) + return values + + def _run(self): + self.cluster.monitor_wall_started = time.time() + while not self._stop.is_set(): + sample = { + "monotonic_ns": time.perf_counter_ns(), + "processes": self._process_sample(), + "client_visible_queue": self.cluster.inflight_snapshot(), + "raft_status": {}, + } + for index in range(3): + if self.cluster.processes[index] is None or self.cluster.processes[index].poll() is not None: + continue + try: + response = self.cluster.admin(index, "status", sample_class="control") + committed = integer(response.get("committedIndex")) + applied = integer(response.get("knownAppliedIndex")) + last = integer(response.get("lastIndex")) + sample["raft_status"][str(index)] = response + sample.setdefault("server_queue", {})[str(index)] = { + "apply_backlog": max(0, committed - applied), + "uncommitted_log": max(0, last - committed), + "last_minus_applied": max(0, last - applied), + } + except Exception as error: # Preserve every unhandled monitor observation error. + self.cluster.record_exception("monitor_status", error, replica=index) + self.samples.append(sample) + self._stop.wait(self.interval_s) + + def summary(self): + live = [p for sample in self.samples for p in sample["processes"] if p.get("alive")] + process = {} + for index in range(3): + points = [(s["monotonic_ns"], p) for s in self.samples + for p in s["processes"] if p["replica"] == index and p.get("alive")] + if len(points) >= 2: + elapsed = points[-1][0] - points[0][0] + cpu = points[-1][1]["cpu_seconds"] - points[0][1]["cpu_seconds"] + process[str(index)] = { + "samples": len(points), "cpu_seconds_delta": cpu, + "elapsed_seconds": elapsed / 1e9, + "average_cpu_percent_one_core": 100 * cpu / (elapsed / 1e9) if elapsed > 0 else None, + "max_rss_bytes": max(p["rss_bytes"] for _, p in points), + "max_threads": max(p["threads"] for _, p in points), + } + read_queue = [s["client_visible_queue"]["lookup"] for s in self.samples] + write_queue = [s["client_visible_queue"]["commit"] for s in self.samples] + apply_backlog = [q["apply_backlog"] for s in self.samples + for q in s.get("server_queue", {}).values()] + return { + "sample_count": len(self.samples), "samples_per_replica_cpu": process, + "max_observed_rss_bytes": max((p["rss_bytes"] for p in live), default=0), + "client_visible_read_queue": counter_distribution(read_queue), + "client_visible_write_queue": counter_distribution(write_queue), + "server_apply_backlog_including_read_barriers": counter_distribution(apply_backlog), + "note": "Read queue is client-visible in-flight Lookup RPCs; server_apply_backlog is braft committedIndex-knownAppliedIndex and includes read barriers, not a private braft read-queue gauge.", + } + + +class ResidentClientProcess: + """One stdin/stdout-driven C++ process owning one persistent brpc Channel.""" + + def __init__(self, cluster, key, leader): + self.cluster = cluster + self.key = key + self.leader = leader + self.sequence = 0 + self._rpc_lock = threading.Lock() + self._closed = False + self.command = [cluster.persistent_binary, + f"--address={cluster.addrs[leader]}", "--rpc_timeout_ms=30000"] + if cluster.instrument_payload: + self.command.append("--instrument_payload=true") + self.driver_log_path = cluster.root / "logs" / f"resident-{key}-driver.log" + self.driver_log = self.driver_log_path.open("ab", buffering=0) + started = time.perf_counter_ns() + self.process = subprocess.Popen( + self.command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, + stderr=self.driver_log, text=True, bufsize=1, + env={**os.environ, "HISTFILE": "/dev/null"}) + self.started_monotonic_ns = started + try: + ready = self._read_response(20, "ready") + if not ready.get("ready"): + raise AssertionError(f"resident driver did not become ready: {ready}") + self.ready_monotonic_ns = time.perf_counter_ns() + self.channel_init_ns = integer(ready.get("channel_init_ns"), -1) + self.cluster.observe("resident_client_ready", client=key, + pid=self.process.pid, command=self.command, + channel_init_ns=self.channel_init_ns, + log=self.driver_log_path) + except Exception: + self.close() + raise + + def _read_response(self, timeout_s, operation): + if self.process.stdout is None: + raise AssertionError("resident stdout is closed") + readable, _, _ = select.select([self.process.stdout], [], [], timeout_s) + if not readable: + raise subprocess.TimeoutExpired(self.command, timeout_s, + output=f"resident {operation} response timeout") + line = self.process.stdout.readline() + if not line: + raise AssertionError(f"resident driver exited during {operation}: " + f"rc={self.process.poll()} log={self.driver_log_path}") + try: + return json.loads(line) + except json.JSONDecodeError as error: + raise AssertionError(f"invalid resident JSON during {operation}: {line!r}") from error + + def call(self, operation, request_path): + with self._rpc_lock: + if self._closed or self.process.poll() is not None or self.process.stdin is None: + raise AssertionError(f"resident client {self.key} is unavailable") + first = self.sequence == 0 + started_wall = time.time() + started = time.perf_counter_ns() + self.process.stdin.write(operation + "\t" + str(request_path) + "\n") + self.process.stdin.flush() + result = self._read_response(45, operation) + harness_rtt = time.perf_counter_ns() - started + self.sequence += 1 + result["first_rpc_for_channel"] = first + result["resident_client_key"] = self.key + result["resident_pid"] = self.process.pid + result["harness_round_trip_ns"] = harness_rtt + record = { + "time_unix_ms": int(started_wall * 1000), "scenario": self.cluster.root.name, + "mode": "persistent_client", "resident_command": self.command, + "resident_pid": self.process.pid, "resident_client_key": self.key, + "operation": operation, "request_file": str(request_path), + "returncode": 0 if result.get("ok") else 1, + "stdout": json.dumps(result, sort_keys=True), "stderr": "", + } + with self.cluster._io_lock: + with self.cluster.command_log.open("a") as output: + output.write(json.dumps(record, sort_keys=True) + "\n") + if not result.get("ok"): + raise AssertionError(f"resident RPC failed: {result}") + return result + + def close(self): + with self._rpc_lock: + if self._closed: + return + self._closed = True + try: + if self.process.poll() is None: + if self.process.stdin is not None: + self.process.stdin.write("quit\t-\n") + self.process.stdin.flush() + self.process.stdin.close() + self.process.wait(timeout=10) + if self.process.stdout is not None: + self.process.stdout.close() + except Exception as error: + self.cluster.record_exception("resident_close", error, client=self.key) + if self.process.poll() is None: + self.process.kill() + self.process.wait(timeout=5) + finally: + self.driver_log.close() + + def summary(self): + return {"pid": self.process.pid, "command": self.command, + "driver_log": str(self.driver_log_path), + "channel_init_ns": self.channel_init_ns, + "python_start_to_ready_ns": self.ready_monotonic_ns - self.started_monotonic_ns, + "driver_rpc_records": self.sequence} + + +class PerfCluster(BusinessCluster): + def __init__(self, binary, audit_binary, scenario, name, + persistent_binary=None, client_mode="cold_cli", instrument_payload=False): + self._io_lock = threading.Lock() + super().__init__(binary, scenario) + self.audit_binary = str(audit_binary) + self.persistent_binary = str(persistent_binary) if persistent_binary is not None else None + self.client_mode = client_mode + self.instrument_payload = instrument_payload + self._residents = {} + self.name = name + self.events = [] + self.pair_events = [] + self.correctness = {"assertions": 0, "replayed_lookups": 0, + "replayed_commits": 0, "intentional_conflicts": 0} + self.exceptions = [] + self.audits = [] + self.control_events = [] + self._inflight_lock = threading.Lock() + self._inflight = {"lookup": 0, "commit": 0} + self._event_sequence = 0 + self.monitor = None + self.current_ms = 0 + self.storage_measurements = {} + + def resident_client(self, leader, lane): + key = "B2_cold" if lane == "B2_cold" else "main" + if key not in self._residents: + if self.client_mode != "persistent" or not self.persistent_binary: + raise AssertionError("persistent client binary/mode is not configured") + self._residents[key] = ResidentClientProcess(self, key, leader) + return self._residents[key] + + def cleanup(self): + for resident in list(self._residents.values()): + resident.close() + super().cleanup() + + def observe(self, event, **values): + record = {"scenario": self.root.name, "event": event, **values} + with self._io_lock: + with (self.root / "observations.jsonl").open("a") as output: + output.write(json.dumps(record, sort_keys=True, default=str) + "\n") + try: + print(f"OBSERVE scenario={self.root.name} event={event} " + + " ".join(f"{key}={value}" for key, value in values.items()), flush=True) + except BrokenPipeError: + # The durable JSONL observation above is authoritative. A timed-out + # tsh display pipe must not abort business measurement or cleanup. + pass + + def start(self, index): + data = self.root / f"replica-{index}" + data.mkdir(parents=True, exist_ok=True) + self.start_counts[index] += 1 + log_path = self.root / "logs" / f"replica-{index}-start-{self.start_counts[index]}.log" + command = [ + "nice", "-n", "10", self.binary, "--mode=serve", "--business=true", + f"--port={self.ports[index]}", f"--peer={self.peers[index]}", + f"--conf={self.conf}", f"--data_path={data}", + "--group=CycleStoreS4Perf", "--enable_test_clock=true", + "--initial_test_now_ms=0", "--election_timeout_ms=500", + "--catchup_timeout_ms=3000", "--prefill_window_ms=60000", + "--commit_window_ms=120000", "--retry_window_ms=300000", + ] + with log_path.open("ab", buffering=0) as log: + process = subprocess.Popen(command, stdin=subprocess.DEVNULL, stdout=log, + stderr=log, env={**os.environ, "HISTFILE": "/dev/null"}) + self.processes[index] = process + self.observe("s4_process_start", replica=index, pid=process.pid, log=log_path) + + def check(self, condition, name, **details): + self.correctness["assertions"] += 1 + if not condition: + raise AssertionError(f"{self.name}:{name}: {details}") + + def record_exception(self, phase, error, **details): + item = {"phase": phase, "type": type(error).__name__, "message": str(error), + "traceback": traceback.format_exc(), **details} + with self._io_lock: + self.exceptions.append(item) + with (self.root / "exceptions.jsonl").open("a") as output: + output.write(json.dumps(item, sort_keys=True) + "\n") + + def inflight_snapshot(self): + with self._inflight_lock: + return dict(self._inflight) + + def record_call(self, command, started, completed, **extra): + record = {"time_unix_ms": int(started * 1000), "scenario": self.root.name, + "command": command, "returncode": completed.returncode, + "stdout": completed.stdout, "stderr": completed.stderr, **extra} + with self._io_lock: + with self.command_log.open("a") as output: + output.write(json.dumps(record, sort_keys=True) + "\n") + if completed.returncode != 0: + raise AssertionError(f"client command failed: {record}") + try: + return json.loads(completed.stdout) + except json.JSONDecodeError as error: + raise AssertionError(f"invalid client JSON: {record}") from error + + def admin(self, index, operation, operation_id="", now_ms=0, drop_fence=False, + family=None, sample_class="control", lane="admin"): + family = family or family_for(b"root-hash", scope="s3-test", domain="s3-test-domain") + command = [ + self.binary, "--mode=client", f"--address={self.addrs[index]}", + f"--operation={operation}", f"--payload={operation_id}", + f"--now_ms={now_ms}", f"--drop_fence={'true' if drop_fence else 'false'}", + f"--scope={family['scopeId']}", f"--domain={family['cacheDomainId']}", + "--timeout_ms=30000", "--rpc_timeout_ms=45000", + ] + # The admin protocol accepts family_root_hash as a command-line string. + # All harness roots are deliberately printable ASCII; business RPC path + # hashes remain arbitrary 32-byte values and never use this channel. + root_bytes = base64.b64decode(family["familyRootHash"]) + try: + root_argument = root_bytes.decode("ascii") + except UnicodeDecodeError as error: + raise AssertionError("admin family root must be printable ASCII") from error + if not root_argument or any(ord(character) < 32 or ord(character) > 126 + for character in root_argument): + raise AssertionError("admin family root must be printable ASCII") + command.append("--family_root_hash=" + root_argument) + started_wall = time.time() + started = time.perf_counter_ns() + completed = subprocess.run(command, text=True, capture_output=True, timeout=55) + elapsed = time.perf_counter_ns() - started + response = self.record_call(command, started_wall, completed, + operation=operation, sample_class=sample_class) + event = {"scenario": self.name, "lane": lane, "kind": f"admin_{operation}", + "sample_class": sample_class, "latency_ns": elapsed, + "started_monotonic_ns": started, "response": response} + with self._io_lock: + self.control_events.append(event) + return response + + def set_clocks(self, now_ms, indexes=(0, 1, 2)): + for index in indexes: + if self.processes[index] is not None and self.processes[index].poll() is None: + response = self.admin(index, "clock", now_ms=now_ms) + self.check(response.get("ok") is True, "set_clock", replica=index, + now_ms=now_ms, response=response) + self.current_ms = now_ms + + def business(self, index, operation, request, name, scenario=None, lane="main", + sample_class="measurement", kind=None): + request_dir = self.root / "requests" + request_dir.mkdir(exist_ok=True) + request_path = request_dir / f"{name}.json" + request_path.write_text(json.dumps(request, sort_keys=True)) + command = [self.binary, f"--mode={operation}", f"--address={self.addrs[index]}", + f"--request_file={request_path}", "--rpc_timeout_ms=30000"] + with self._inflight_lock: + self._inflight[operation] += 1 + self._event_sequence += 1 + sequence = self._event_sequence + started_wall = time.time() + started = time.perf_counter_ns() + try: + extra = {} + if self.client_mode == "persistent": + driver = self.resident_client(index, lane).call(operation, request_path) + elapsed = integer(driver["latency_ns"]) + response = driver["response"] + extra = { + "prepare_latency_ns": integer(driver["prepare_latency_ns"], -1), + "harness_round_trip_ns": integer(driver["harness_round_trip_ns"]), + "resident_client_key": driver["resident_client_key"], + "resident_pid": integer(driver["resident_pid"]), + "first_rpc_for_channel": driver["first_rpc_for_channel"], + "driver_sequence": integer(driver["sequence"]), + } + for key in ("request_json_bytes", "request_proto_bytes", "response_proto_bytes", + "raft_business_command_bytes", "braft_task_payload_bytes", + "protobuf_serialize_ns", "business_frame_encode_ns", + "response_json_serialize_ns"): + if key in driver: + extra[key] = integer(driver[key]) + else: + completed = subprocess.run(command, text=True, capture_output=True, timeout=40) + elapsed = time.perf_counter_ns() - started + response = self.record_call(command, started_wall, completed, + operation=operation, sample_class=sample_class) + event = {"scenario": scenario or self.name, "lane": lane, + "kind": kind or operation, "sample_class": sample_class, + "sequence": sequence, "request_name": name, + "request_file": str(request_path), "latency_ns": elapsed, + "started_monotonic_ns": started, + "completed_monotonic_ns": time.perf_counter_ns(), + "time_unix_ms": int(started_wall * 1000), "response": response, + "client_mode": self.client_mode, **extra} + with self._io_lock: + self.events.append(event) + with (self.root / "events.jsonl").open("a") as output: + output.write(json.dumps(event, sort_keys=True) + "\n") + return event + finally: + with self._inflight_lock: + self._inflight[operation] -= 1 + + def pair(self, lookup_event, commit_event, kind, lane, new_nodes, scenario=None, + sample_class="measurement"): + event = {"scenario": scenario or self.name, "lane": lane, "kind": kind, + "sample_class": sample_class, + "latency_ns": lookup_event["latency_ns"] + commit_event["latency_ns"], + "lookup_sequence": lookup_event["sequence"], + "commit_sequence": commit_event["sequence"], + "first_rpc_for_channel": lookup_event.get("first_rpc_for_channel", False), + "new_node_count": new_nodes} + self.pair_events.append(event) + return event + + def validate_lookup(self, event, intent=None): + response = event["response"] + self.check(response.get("result") == "OK", "lookup_result", response=response) + self.check(response.get("shadowOnly") is True and response.get("noReplication") is False, + "lookup_shadow_replication_flags", response=response) + self.check("token" in response and response["token"].get("canonicalPayload"), + "lookup_token_complete", response=response) + payload = response.get("payload", {}) + self.check(LOOKUP_PAYLOAD_FIELDS <= set(payload), "lookup_payload_fields", + missing=sorted(LOOKUP_PAYLOAD_FIELDS - set(payload))) + if intent is not None: + self.check(payload.get("intent") == intent, "lookup_intent", + expected=intent, actual=payload.get("intent")) + return response + + def validate_commit(self, event, outcome, new_nodes, generation=1): + response = event["response"] + self.check(response.get("transportError") == "RESULT_UNSPECIFIED", + "commit_transport", response=response) + self.check(response.get("shadowOnly") is True and response.get("noReplication") is False, + "commit_shadow_replication_flags", response=response) + receipt = response.get("receipt", {}) + self.check(COMMIT_FIELDS <= set(receipt), "commit_receipt_fields", + missing=sorted(COMMIT_FIELDS - set(receipt))) + self.check(receipt.get("outcome") == outcome, "commit_outcome", + expected=outcome, actual=receipt.get("outcome")) + self.check(receipt.get("logicalCommitApplied") is True, "commit_logical_applied") + self.check(integer(receipt.get("newNodeCount"), -1) == new_nodes, + "commit_new_nodes", expected=new_nodes, actual=receipt.get("newNodeCount")) + self.check(integer(receipt.get("rootGeneration"), -1) == generation, + "commit_generation", expected=generation, actual=receipt.get("rootGeneration")) + self.check(receipt.get("leaseId") and receipt.get("receiptDigest"), + "commit_lease_and_digest_present") + return receipt + + def cycle(self, leader, family, path, operation_id, name, now_ms, outcome, + new_nodes, scenario=None, lane="main", kind="cycle", prefill_ms=None, + lookup_intent=None, ttl="TTL_5M", sample_class="measurement"): + lookup_request = {"family": family, "operationId": operation_id, + "path": path, "requestedTtl": ttl} + lookup = self.business(leader, "lookup", lookup_request, name + "-lookup", + scenario=scenario, lane=lane, kind=kind + "_lookup", + sample_class=sample_class) + self.validate_lookup(lookup, intent=lookup_intent) + commit_request = {"token": copy.deepcopy(lookup["response"]["token"]), + "path": path, "prefillCompletedAtMs": str(now_ms if prefill_ms is None else prefill_ms)} + commit = self.business(leader, "commit", commit_request, name + "-commit", + scenario=scenario, lane=lane, kind=kind + "_commit", + sample_class=sample_class) + receipt = self.validate_commit(commit, outcome, new_nodes) + self.check(receipt.get("lockedTtl") == ttl, "locked_ttl", expected=ttl, actual=receipt) + if ttl == "TTL_1H" and new_nodes == 16000: + self.check(receipt.get("billingEligibleForNewCycle") is True, "cold_1h_billing") + pair = self.pair(lookup, commit, kind + "_pair_sum", lane, new_nodes, scenario, + sample_class=sample_class) + return lookup, commit, pair + + def replay(self, leader, family, path, lookup_event, commit_event, name): + operation_id = lookup_event["request_name"] + lookup_request = {"family": family, "operationId": lookup_event["response"]["payload"]["operationId"], + "path": path, "requestedTtl": lookup_event["response"]["payload"]["readRootLockedTtl"]} + lookup = self.business(leader, "lookup", lookup_request, name + "-lookup-replay", + kind="correctness_lookup_replay", sample_class="correctness") + self.validate_lookup(lookup) + self.check(lookup["response"] == lookup_event["response"], "lookup_replay_exact", + note="original issued time and both deadlines must not change") + self.correctness["replayed_lookups"] += 1 + request = {"token": copy.deepcopy(lookup_event["response"]["token"]), "path": path, + "prefillCompletedAtMs": lookup_event["response"]["payload"]["issuedAtMs"]} + # Use the original commit's exact prefill input recovered from the request file. + original_commit_request = json.loads(Path(commit_event["request_file"]).read_text()) + request["prefillCompletedAtMs"] = original_commit_request["prefillCompletedAtMs"] + replay = self.business(leader, "commit", request, name + "-commit-replay", + kind="correctness_commit_replay", sample_class="correctness") + self.check(replay["response"]["receipt"] == commit_event["response"]["receipt"], + "commit_replay_original_receipt") + self.check(replay["response"].get("receiptReplayed") is True, "commit_replay_flag") + self.correctness["replayed_commits"] += 1 + return lookup, replay + + def wait_all_debug(self, family, operation_id, timeout=45): + deadline = time.monotonic() + timeout + latest = None + retries = 0 + while time.monotonic() < deadline: + latest = {} + try: + for index in range(3): + response = self.admin(index, "debug", operation_id, family=family) + self.check(response.get("ok") is True, "debug_admin", response=response) + latest[index] = json.loads(response["debugState"]) + canonical = {json.dumps({"token": state["token"], "receipt": state["receipt"], + "meta": state["meta"]}, sort_keys=True) + for state in latest.values()} + if len(canonical) == 1 and all(state.get("invariants") is True and + state["token"].get("found") is True and + state["receipt"].get("found") is True + for state in latest.values()): + return latest + except (AssertionError, subprocess.TimeoutExpired): + retries += 1 + time.sleep(0.1) + raise AssertionError(f"debug mismatch after retries={retries}: {latest}") + + def storage(self, label): + result = {"label": label, "replicas": {}} + for index in range(3): + data = self.root / f"replica-{index}" + rocks_wal = 0 + braft_log = 0 + snapshots = 0 + for path in data.rglob("*"): + if not path.is_file(): + continue + relative = path.relative_to(data) + size = path.stat().st_size + if relative.parts[0] == "business_rocksdb" and path.suffix == ".log": + rocks_wal += size + if relative.parts[0] == "log": + braft_log += size + if relative.parts[0] == "snapshot": + snapshots += size + result["replicas"][str(index)] = { + "rocksdb_business_wal_bytes": rocks_wal, + "braft_log_bytes": braft_log, + "snapshot_bytes": snapshots, + } + self.storage_measurements[label] = result + return result + + @staticmethod + def storage_delta(before, after): + result = {} + for index in before["replicas"]: + result[index] = {key: after["replicas"][index][key] - value + for key, value in before["replicas"][index].items()} + return result + + def start_monitor(self, interval_s): + self.monitor = Monitor(self, interval_s) + self.monitor.start() + + def stop_monitor(self): + return self.monitor.stop() if self.monitor is not None else None + + def audit_stores(self, now_ms, expected_graph=None, expected_leases=None, + require_no_pruning=False): + for index in range(3): + path = self.root / f"replica-{index}" / "business_rocksdb" + command = [self.audit_binary, f"--db={path}", f"--now_ms={now_ms}"] + started = time.time() + completed = subprocess.run(command, text=True, capture_output=True, timeout=90) + response = self.record_call(command, started, completed, operation="store_audit") + (self.root / f"audit-replica-{index}.json").write_text(json.dumps(response, indent=2, sort_keys=True)) + self.audits.append(response) + self.check(response.get("ok") is True, "store_audit_ok", replica=index) + self.check(response["node_records"] == response["node_unique_records"], + "node_unique_index_count", replica=index) + if expected_graph is not None: + self.check(response["graph_highwater"] == expected_graph, + "persisted_graph_highwater", expected=expected_graph, actual=response) + if expected_leases is not None: + self.check(response["lease_highwater"] == expected_leases, + "persisted_lease_highwater", expected=expected_leases, actual=response) + if require_no_pruning and expected_graph is not None: + self.check(response["node_records"] == expected_graph, + "persisted_physical_graph", expected=expected_graph, actual=response) + self.check(response["lease_records"] == expected_leases, + "persisted_physical_leases", expected=expected_leases, actual=response) + self.check(len({json.dumps({key: audit[key] for key in ( + "graph_highwater", "lease_highwater", "node_records", "lease_records", + "operation_records")}, sort_keys=True) for audit in self.audits}) == 1, + "three_replica_store_counts_equal") + return self.audits + + def summarize(self, measured_started=None, measured_completed=None, monitor_summary=None, + extra=None): + measurement = [event for event in self.events if event["sample_class"] == "measurement"] + measured_pairs = [event for event in self.pair_events + if event["sample_class"] == "measurement"] + groups = {} + for event in measurement + measured_pairs: + key = f"{event['scenario']}/{event['lane']}/{event['kind']}" + groups.setdefault(key, []).append(event["latency_ns"]) + response_counts = {} + conflicts = 0 + degraded = 0 + for event in measurement: + response = event["response"] + if "receipt" in response: + outcome = response["receipt"].get("outcome", "MISSING") + response_counts[outcome] = response_counts.get(outcome, 0) + 1 + if outcome in CONFLICT_RESULTS: + conflicts += 1 + if response.get("transportError") != "RESULT_UNSPECIFIED" or "receipt" not in response: + degraded += 1 + else: + outcome = response.get("result", "MISSING") + response_counts[outcome] = response_counts.get(outcome, 0) + 1 + if outcome in CONFLICT_RESULTS: + conflicts += 1 + if outcome == "UNAVAILABLE" or not response.get("token", {}).get("canonicalPayload"): + degraded += 1 + elapsed_ns = None if measured_started is None or measured_completed is None else measured_completed - measured_started + measurements = {key: distribution(values) for key, values in sorted(groups.items())} + steady_groups = {} + prepare_groups = {} + for event in measurement + measured_pairs: + key = f"{event['scenario']}/{event['lane']}/{event['kind']}" + if not event.get("first_rpc_for_channel", False): + steady_groups.setdefault(key, []).append(event["latency_ns"]) + if event.get("prepare_latency_ns") is not None: + prepare_groups.setdefault(key, []).append(event["prepare_latency_ns"]) + first_rpc = [{key: event.get(key) for key in ( + "scenario", "lane", "kind", "sample_class", "latency_ns", + "prepare_latency_ns", "harness_round_trip_ns", "resident_client_key", + "resident_pid", "driver_sequence", "request_file")} + for event in self.events if event.get("first_rpc_for_channel", False)] + per_node = {} + for event in measured_pairs: + if event["new_node_count"] > 0: + key = f"{event['scenario']}/{event['lane']}/{event['kind']}/per_new_node" + per_node.setdefault(key, []).append(event["latency_ns"] / event["new_node_count"]) + for key, values in per_node.items(): + measurements[key] = distribution(values) + measurements[key]["unit"] = "ns_per_actual_new_node_pair_sum" + if self.storage_measurements.get("after_setup") and self.storage_measurements.get("measurement_end"): + measured_wal = self.storage_delta(self.storage_measurements["after_setup"], + self.storage_measurements["measurement_end"]) + else: + measured_wal = None + return { + "scenario": self.name, "load": {"measured_requests": len(measurement), + "measured_pair_count": len(measured_pairs), + "wall_elapsed_ns": elapsed_ns, + "achieved_request_rate_per_s": len(measurement) / (elapsed_ns / 1e9) + if elapsed_ns and elapsed_ns > 0 else None}, + "client_mode": self.client_mode, + "latency_nearest_rank": measurements, + "steady_state_latency_nearest_rank": { + key: distribution(values) for key, values in sorted(steady_groups.items())}, + "request_prepare_latency_nearest_rank": { + key: distribution(values) for key, values in sorted(prepare_groups.items())}, + "first_rpc_per_channel": first_rpc, + "resident_clients": {key: resident.summary() + for key, resident in self._residents.items()}, + "response_outcome_counts": response_counts, + "measured_conflict_count": conflicts, "measured_degraded_count": degraded, + "correctness": self.correctness, "exceptions": self.exceptions, + "storage": self.storage_measurements, "measured_storage_delta": measured_wal, + "controller": monitor_summary, "store_audits": self.audits, + "extra": extra or {}, + "evidence": {"root": str(self.root), "events": str(self.root / "events.jsonl"), + "commands": str(self.root / "commands.jsonl"), + "replica_logs": str(self.root / "logs")}, + } + + +def run_status_baseline(cluster, leader, calls): + if calls < 1: + return {"status": "NOT_REQUESTED"} + cold_path = cluster.root / "status-baseline-cold-cli.jsonl" + persistent_path = cluster.root / "status-baseline-persistent.jsonl" + cold_events = [] + persistent_events = [] + for index in range(calls): + command = [cluster.binary, "--mode=client", f"--address={cluster.addrs[leader]}", + "--operation=status", "--rpc_timeout_ms=30000"] + started_wall = time.time() + started = time.perf_counter_ns() + completed = subprocess.run(command, text=True, capture_output=True, timeout=40) + elapsed = time.perf_counter_ns() - started + response = cluster.record_call(command, started_wall, completed, + operation="status_baseline_cold_cli") + event = {"index": index, "client_mode": "cold_cli", "latency_ns": elapsed, + "cold_cli_process_wall": True, "response": response} + cold_events.append(event) + with cold_path.open("a") as output: + output.write(json.dumps(event, sort_keys=True) + "\n") + resident = cluster.resident_client(leader, "main") + for index in range(calls): + result = resident.call("status", "-") + event = {"index": index, "client_mode": "persistent_client", + "latency_ns": integer(result["latency_ns"]), + "prepare_latency_ns": integer(result["prepare_latency_ns"]), + "harness_round_trip_ns": integer(result["harness_round_trip_ns"]), + "response": result["response"]} + persistent_events.append(event) + with persistent_path.open("a") as output: + output.write(json.dumps(event, sort_keys=True) + "\n") + cold_distribution = distribution([event["latency_ns"] for event in cold_events]) + persistent_distribution = distribution([event["latency_ns"] for event in persistent_events]) + return { + "rpc": "RaftControl/status on the same leader and same business servers", + "samples_each": calls, "cold_cli_process_wall": cold_distribution, + "persistent_in_process_rtt": persistent_distribution, + "cold_first_latency_ns": cold_events[0]["latency_ns"] if cold_events else None, + "persistent_first_latency_ns": persistent_events[0]["latency_ns"] if persistent_events else None, + "cold_median_minus_persistent_median_ns": + cold_distribution["p50_ns"] - persistent_distribution["p50_ns"], + "evidence": {"cold_cli": str(cold_path), "persistent_client": str(persistent_path)}, + } + + +def cold_cycle(cluster, leader, family, path, operation_id, name, now_ms, ttl="TTL_5M", + scenario=None, lane="cold", kind="cold", sample_class="measurement"): + requested = {"family": family, "operationId": operation_id, "path": path, + "requestedTtl": ttl} + lookup = cluster.business(leader, "lookup", requested, name + "-lookup", + scenario=scenario, lane=lane, kind=kind + "_lookup", + sample_class=sample_class) + cluster.validate_lookup(lookup, intent="CREATE_NEXT_ROOT") + commit_request = {"token": copy.deepcopy(lookup["response"]["token"]), "path": path, + "prefillCompletedAtMs": str(now_ms)} + commit = cluster.business(leader, "commit", commit_request, name + "-commit", + scenario=scenario, lane=lane, kind=kind + "_commit", + sample_class=sample_class) + expected = "ROOT_CYCLE_CREATED" + receipt = cluster.validate_commit(commit, expected, 16000 if len(path["pages"]) == 16000 else len(path["pages"])) + cluster.check(receipt["lockedTtl"] == ttl, "cold_locked_ttl", expected=ttl, actual=receipt) + pair = cluster.pair(lookup, commit, kind + "_pair_sum", lane, + integer(receipt["newNodeCount"]), scenario, + sample_class=sample_class) + return lookup, commit, pair + + +def abort_cluster(cluster, phase, error): + cluster.record_exception(phase, error) + if cluster.monitor is not None: + try: + cluster.stop_monitor() + except Exception as monitor_error: + cluster.record_exception("abort_monitor", monitor_error) + try: + cluster.cleanup() + except Exception as cleanup_error: + cluster.record_exception("abort_cleanup", cleanup_error) + + +def run_b1(binary, audit_binary, root, persistent_binary=None, client_mode="cold_cli"): + cluster = PerfCluster(binary, audit_binary, root / "B1-hot-16k", "B1", + persistent_binary, client_mode) + measured_started = measured_completed = monitor_summary = None + try: + leader, _ = cluster.start_all() + cluster.storage("scenario_start") + cluster.set_clocks(1000) + root_hash = b"b1-root-00000000000000000000000000" + family = family_for(root_hash) + main_path = path_for(root_hash, "b1-main") + cold_cycle(cluster, leader, family, main_path, "b1-cold-main", "b1-setup-cold-main", + 1000, scenario="B1_SETUP", sample_class="setup") + branches = {} + for branch_number in range(4): + path = branch_path(main_path, root_hash, f"b1-branch-{branch_number}", f"tip-{branch_number}") + branches[branch_number] = path + # The 15999-node prefix exists; exactly one explicitly marked new tip is allowed. + cluster.cycle(leader, family, path, f"b1-cold-branch-{branch_number}", + f"b1-setup-cold-branch-{branch_number}", 1000, + "PATH_COVERAGE_CREATED", 1, scenario="B1_SETUP", + kind="setup_branch", lookup_intent="RENEW_OR_EXTEND", + sample_class="setup") + cluster.storage("after_setup") + schedule = ["late", "late", "local", "late", "late", "local", + "late", "late", "local", "late", "late", "late"] + schedule += (["main"] * 8 + ["sibling"]) * 12 + cluster.check(len(schedule) == 120, "b1_config_event_count", actual=len(schedule)) + cluster.check(schedule.count("late") == 9 and schedule.count("local") == 3 and + schedule.count("main") == 96 and schedule.count("sibling") == 12, + "b1_config_event_ratio") + measured_started = time.perf_counter_ns() + cluster.start_monitor(0.5) + next_late_lookup = 299000 + late_number = 0 + local_number = 0 + main_number = 0 + sibling_number = 0 + retained = None + for index, event_kind in enumerate(schedule): + if event_kind == "late": + lookup_now = next_late_lookup + cluster.set_clocks(lookup_now) + operation_id = f"b1-late-{late_number}" + request = {"family": family, "operationId": operation_id, "path": main_path, + "requestedTtl": "TTL_5M"} + lookup = cluster.business(leader, "lookup", request, operation_id + "-lookup", + lane="late_299_320", kind="late_lookup") + cluster.validate_lookup(lookup, intent="RENEW_OR_EXTEND") + commit_now = lookup_now + 21000 + cluster.set_clocks(commit_now) + commit_request = {"token": copy.deepcopy(lookup["response"]["token"]), + "path": main_path, "prefillCompletedAtMs": str(commit_now)} + commit = cluster.business(leader, "commit", commit_request, operation_id + "-commit", + lane="late_299_320", kind="late_commit") + cluster.validate_commit(commit, "RENEWED", 0) + cluster.pair(lookup, commit, "late_pair_sum", "late_299_320", 0) + if retained is None: + retained = (lookup, commit) + late_number += 1 + next_late_lookup = commit_now + 20000 + elif event_kind == "local": + now = cluster.current_ms + path = branches[local_number] + operation_id = f"b1-local-expired-{local_number}" + lookup, commit, _ = cluster.cycle( + leader, family, path, operation_id, operation_id, now, + "PATH_COVERAGE_CREATED", 0, lane="local_branch_expired", + kind="local_expiry", lookup_intent="RENEW_OR_EXTEND") + cluster.check(integer(lookup["response"]["payload"]["aliveDepth"], -1) == 15998, + "local_branch_prefix_expired", payload=lookup["response"]["payload"]) + local_number += 1 + elif event_kind == "sibling": + now = max(700000, cluster.current_ms) + cluster.set_clocks(now) + operation_id = f"b1-sibling-hot-{sibling_number}" + lookup, commit, _ = cluster.cycle( + leader, family, branches[3], operation_id, operation_id, now, + "PATH_COVERAGE_CREATED" if sibling_number == 0 else "RENEWED", 0, + lane="same_generation_sibling", kind="sibling_hot", + lookup_intent="RENEW_OR_EXTEND") + if sibling_number == 0: + cluster.check(integer(lookup["response"]["payload"]["aliveDepth"], -1) == 15998, + "first_hot_sibling_was_locally_expired") + sibling_number += 1 + else: + now = max(700000, cluster.current_ms) + cluster.set_clocks(now) + operation_id = f"b1-main-hot-{main_number}" + cluster.cycle(leader, family, main_path, operation_id, operation_id, now, + "RENEWED", 0, lane="same_family_hot", kind="main_hot", + lookup_intent="RENEW_OR_EXTEND") + main_number += 1 + measured_completed = time.perf_counter_ns() + monitor_summary = cluster.stop_monitor() + cluster.storage("measurement_end") + # Correctness samples are deliberately excluded from all latency distributions. + cluster.replay(leader, family, main_path, retained[0], retained[1], "b1-correctness-replay") + wrong_path = copy.deepcopy(main_path) + wrong_path["pages"][-1]["pageHash"] = b64(hashlib.sha256(b"b1-wrong-tip").digest()) + original_request = json.loads(Path(retained[1]["request_file"]).read_text()) + wrong_request = {"token": copy.deepcopy(original_request["token"]), "path": wrong_path, + "prefillCompletedAtMs": original_request["prefillCompletedAtMs"]} + wrong = cluster.business(leader, "commit", wrong_request, "b1-intentional-conflict", + sample_class="correctness", kind="correctness_conflict") + cluster.check(wrong["response"]["receipt"]["outcome"] == "OPERATION_ID_CONFLICT", + "intentional_full_input_conflict") + cluster.check(wrong["response"]["receipt"]["logicalCommitApplied"] is False, + "intentional_conflict_no_positive_effect") + cluster.correctness["intentional_conflicts"] += 1 + cluster.wait_all_debug(family, "b1-main-hot-95") + cluster.check(sum(integer(e["response"].get("receipt", {}).get("newNodeCount")) + for e in cluster.events if e["sample_class"] == "measurement" and + e["scenario"] == "B1" and e["kind"].endswith("commit")) == 0, + "b1_measured_zero_new_nodes") + return cluster, leader, family, 16000 + 4, 1 + 4 + 120, measured_started, measured_completed, monitor_summary, { + "events": {"same_family_hot": 96, "same_generation_sibling_hot": 12, + "locally_expired_sibling": 3, "late_lookup_commit": 9, + "first_late_lookup_ms": 299000, "first_late_prefill_and_accept_ms": 320000, + "inter_event_late_delay_ms": 21000}, + "full_path_pages": 16000, "explicit_setup_branch_nodes": 4, + "measurement_definition": "one lookup plus one prefill commit per measured event; no hot-cycle new nodes allowed", + } + except Exception as error: + abort_cluster(cluster, "B1_scenario", error) + raise + + +def run_b2(binary, audit_binary, root, cold_families, + persistent_binary=None, client_mode="cold_cli"): + cluster = PerfCluster(binary, audit_binary, root / "B2-cold-16k-tail", "B2", + persistent_binary, client_mode) + measured_started = measured_completed = monitor_summary = None + final_family = None + final_operation = None + try: + leader, _ = cluster.start_all() + cluster.storage("scenario_start") + cluster.set_clocks(1000000) + cluster.storage("after_setup") + measured_started = time.perf_counter_ns() + cluster.start_monitor(0.5) + retained = None + for cold_index in range(cold_families): + root_hash = f"b2-root-{cold_index:04d}-000000000000000000".encode()[:32] + family = family_for(root_hash, scope=f"s4-b2-{cold_index}") + path = path_for(root_hash, f"b2-family-{cold_index}") + cold_cycle(cluster, leader, family, path, f"b2-cold-{cold_index}", + f"b2-cold-{cold_index}", cluster.current_ms, ttl="TTL_1H", kind="cold_16k") + tail1 = appended_path(path, root_hash, f"b2-family-{cold_index}", 1, + f"b2-family-{cold_index}-tail1") + lookup1, commit1, _ = cluster.cycle( + leader, family, tail1, f"b2-tail1-{cold_index}", f"b2-tail1-{cold_index}", + cluster.current_ms, "PATH_COVERAGE_CREATED", 1, lane="tail_delta_1", + kind="tail_delta_1", lookup_intent="RENEW_OR_EXTEND", ttl="TTL_1H") + tail4 = appended_path(tail1, root_hash, f"b2-family-{cold_index}", 4, + f"b2-family-{cold_index}-tail4") + cluster.cycle(leader, family, tail4, f"b2-tail4-{cold_index}", f"b2-tail4-{cold_index}", + cluster.current_ms, "PATH_COVERAGE_CREATED", 4, lane="tail_delta_4", + kind="tail_delta_4", lookup_intent="RENEW_OR_EXTEND", ttl="TTL_1H") + if retained is None: + retained = (family, tail1, lookup1, commit1) + final_family, final_operation = family, f"b2-tail4-{cold_index}" + measured_completed = time.perf_counter_ns() + monitor_summary = cluster.stop_monitor() + cluster.storage("measurement_end") + cluster.replay(leader, retained[0], retained[1], retained[2], retained[3], "b2-correctness-replay") + cluster.wait_all_debug(final_family, final_operation) + expected_graph = cold_families * (16000 + 1 + 4) + expected_leases = cold_families * 3 + return cluster, leader, final_family, expected_graph, expected_leases, measured_started, measured_completed, monitor_summary, { + "cold_16k_families": cold_families, "tail_delta_1_requests": cold_families, + "tail_delta_4_requests": cold_families, "full_path_pages": 16000, + "request_ttl": "TTL_1H", + "measurement_definition": "cold and tail request and per-new-node distributions are independent of B1 hot renewal", + "per_node_latency": "lookup_latency_ns+commit_latency_ns divided by that commit's actual newNodeCount; not wall wall-clock including clock control", + } + except Exception as error: + abort_cluster(cluster, "B2_scenario", error) + raise + + +def run_b3(binary, audit_binary, root, hot_operations, cold_families, monitor_interval, + persistent_binary=None, client_mode="cold_cli", baseline_calls=0): + cluster = PerfCluster(binary, audit_binary, root / "B3-background-concurrency", "B3", + persistent_binary, client_mode) + measured_started = measured_completed = monitor_summary = None + main_family = None + try: + leader, _ = cluster.start_all() + cluster.storage("scenario_start") + cluster.set_clocks(1000000) + main_root = b"b3-main-root-00000000000000000000"[:32] + main_family = family_for(main_root, scope="s4-b3-main") + main_path = path_for(main_root, "b3-main") + cold_cycle(cluster, leader, main_family, main_path, "b3-setup-main", + "b3-setup-main", 1000000, ttl="TTL_1H", scenario="B3_SETUP", + sample_class="setup") + gc_root = b"b3-gc-root-000000000000000000000"[:32] + gc_family = family_for(gc_root, scope="s4-b3-gc") + gc_path = path_for(gc_root, "b3-gc", pages=2) + _, gc_commit, _ = cold_cycle(cluster, leader, gc_family, gc_path, "b3-setup-gc", + "b3-setup-gc", 1000000, ttl="TTL_5M", scenario="B3_SETUP", + sample_class="setup") + gc_due_ms = integer(gc_commit["response"]["receipt"]["leaseExpireAtMs"]) + 300000 + cluster.set_clocks(2000000) + cluster.check(cluster.current_ms - gc_due_ms == 400000, "b3_gc_lag_configuration") + cluster.storage("after_setup") + measured_started = time.perf_counter_ns() + cluster.start_monitor(monitor_interval) + gc_observations = [] + snapshot_observations = [] + + def hot_worker(): + retained = None + for index in range(hot_operations): + operation_id = f"b3-hot-{index}" + lookup, commit, _ = cluster.cycle( + leader, main_family, main_path, operation_id, operation_id, + 2000000, "RENEWED", 0, lane="B1_hot", kind="concurrent_hot", + lookup_intent="RENEW_OR_EXTEND", ttl="TTL_1H") + # Existing operation takes the real replicated READ_BARRIER path. + duplicate_lookup_request = {"family": main_family, "operationId": operation_id, + "path": main_path, "requestedTtl": "TTL_1H"} + duplicate = cluster.business(leader, "lookup", duplicate_lookup_request, + operation_id + "-read-barrier", lane="B1_hot", + kind="read_barrier_lookup") + cluster.validate_lookup(duplicate) + cluster.check(duplicate["response"] == lookup["response"], + "b3_read_barrier_original_token_deadlines") + replay_request = json.loads(Path(commit["request_file"]).read_text()) + replay = cluster.business(leader, "commit", replay_request, + operation_id + "-idempotent-commit", lane="B1_hot", + kind="idempotent_replay_commit", sample_class="correctness") + cluster.check(replay["response"]["receipt"] == commit["response"]["receipt"] and + replay["response"]["receiptReplayed"] is True, + "b3_idempotent_commit_original_receipt") + cluster.correctness["replayed_commits"] += 1 + if retained is None: + retained = (lookup, commit) + return retained + + def cold_worker(): + for cold_index in range(cold_families): + root_hash = f"b3-cold-{cold_index:04d}-0000000000000000".encode()[:32] + family = family_for(root_hash, scope=f"s4-b3-cold-{cold_index}") + path = path_for(root_hash, f"b3-cold-family-{cold_index}") + cold_cycle(cluster, leader, family, path, f"b3-cold-{cold_index}", + f"b3-cold-{cold_index}", 2000000, ttl="TTL_1H", lane="B2_cold", + kind="concurrent_cold_16k") + tail1 = appended_path(path, root_hash, f"b3-cold-family-{cold_index}", 1, "b3-tail1") + cluster.cycle(leader, family, tail1, f"b3-tail1-{cold_index}", + f"b3-tail1-{cold_index}", 2000000, "PATH_COVERAGE_CREATED", 1, + lane="B2_cold", kind="concurrent_tail_delta_1", + lookup_intent="RENEW_OR_EXTEND", ttl="TTL_1H") + tail4 = appended_path(tail1, root_hash, f"b3-cold-family-{cold_index}", 4, "b3-tail4") + cluster.cycle(leader, family, tail4, f"b3-tail4-{cold_index}", + f"b3-tail4-{cold_index}", 2000000, "PATH_COVERAGE_CREATED", 4, + lane="B2_cold", kind="concurrent_tail_delta_4", + lookup_intent="RENEW_OR_EXTEND", ttl="TTL_1H") + + def snapshot_worker(): + for index in range(2): + started = time.perf_counter_ns() + response = cluster.admin(leader, "snapshot", "b3-hot-0", lane="checkpoint") + snapshot_observations.append({"index": index, "latency_ns": time.perf_counter_ns() - started, + "response": response}) + cluster.check(response.get("ok") is True, "b3_checkpoint", response=response) + + def gc_worker(): + started = time.perf_counter_ns() + response = cluster.admin(leader, "gc", "b3-setup-gc", now_ms=2000000, + family=gc_family, lane="gc") + gc_observations.append({ + "configured_oldest_lease_gc_at_ms": gc_due_ms, + "gc_now_ms": 2000000, "gc_lag_before_ms": 2000000 - gc_due_ms, + "latency_ns": time.perf_counter_ns() - started, "response": response, + }) + cluster.check(response.get("ok") is True and "GC:" in response.get("responsePayload", ""), + "b3_gc_collected", response=response) + + with concurrent.futures.ThreadPoolExecutor(max_workers=4) as executor: + futures = [executor.submit(hot_worker), executor.submit(cold_worker), + executor.submit(snapshot_worker), executor.submit(gc_worker)] + for future in futures: + future.result() + measured_completed = time.perf_counter_ns() + monitor_summary = cluster.stop_monitor() + cluster.storage("measurement_end") + cluster.wait_all_debug(main_family, f"b3-hot-{hot_operations - 1}") + status_baseline = run_status_baseline(cluster, leader, baseline_calls) + expected_graph = 16000 + 2 + cold_families * 16005 + expected_leases = hot_operations + 2 + cold_families * 3 + return cluster, leader, main_family, expected_graph, expected_leases, measured_started, measured_completed, monitor_summary, { + "hot_operations": hot_operations, + "read_barrier_lookups": hot_operations, + "idempotent_replay_commits_excluded_from_latency": hot_operations, + "cold_16k_families": cold_families, "tail_delta_1_requests": cold_families, + "tail_delta_4_requests": cold_families, "checkpoints": 2, "gc_runs": 1, + "replication_fsync": "Enabled by Store sync_writes and braft three-replica apply; every measured business commit completes Node::apply", + "gc_observations": gc_observations, "checkpoint_observations": snapshot_observations, + "read_queue_definition": "client-visible in-flight Lookup plus server committedIndex-knownAppliedIndex combined apply backlog", + "status_rpc_baseline": status_baseline, + } + except Exception as error: + abort_cluster(cluster, "B3_scenario", error) + raise + + +def finish(label, outcome, args): + (cluster, leader, family, expected_graph, expected_leases, measured_started, + measured_completed, monitor_summary, extra) = outcome + cleanup_error = None + try: + cluster.cleanup() + except Exception as error: + cleanup_error = error + cluster.record_exception("cleanup", error) + try: + cluster.audit_stores(cluster.current_ms, expected_graph=expected_graph, + expected_leases=expected_leases, + require_no_pruning=(label in ("B1", "B2"))) + except Exception as error: + cluster.record_exception("store_audit_or_assertion", error) + raise + finally: + if cleanup_error is not None: + raise cleanup_error + summary = cluster.summarize(measured_started, measured_completed, monitor_summary, extra) + summary["status"] = ("MEASURED_WITH_CORRECTNESS_ASSERTIONS_PASS" if not cluster.exceptions + else "MEASURED_WITH_EXCEPTIONS") + (args.root / f"summary-{label}.json").write_text(json.dumps(summary, indent=2, sort_keys=True)) + return summary + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--binary", required=True, type=Path) + parser.add_argument("--audit-binary", required=True, type=Path) + parser.add_argument("--persistent-binary", type=Path) + parser.add_argument("--client-mode", choices=("cold_cli", "persistent"), default="persistent") + parser.add_argument("--status-baseline-calls", type=int, default=32) + parser.add_argument("--root", required=True, type=Path) + parser.add_argument("--b1-events", type=int, default=120, + help="Fixed B1 recipe is 120; other values are rejected, not silently substituted") + parser.add_argument("--b2-cold-families", type=int, default=8) + parser.add_argument("--b3-hot-operations", type=int, default=64) + parser.add_argument("--b3-cold-families", type=int, default=2) + parser.add_argument("--monitor-interval-s", type=float, default=0.5) + args = parser.parse_args() + args.root = args.root.resolve() + if args.root.exists(): + print(f"FAIL: evidence root already exists: {args.root}") + return 2 + if (args.b1_events != 120 or args.b2_cold_families < 1 or args.b3_hot_operations < 1 or + args.b3_cold_families < 1 or args.status_baseline_calls < 0 or + (args.client_mode == "persistent" and args.persistent_binary is None)): + print("FAIL: invalid workload/client configuration") + return 2 + args.root.mkdir(parents=True) + manifest = { + "suite": f"CycleStore S4 shadow-only {args.client_mode} measurement batch", + "performance_gate_verdict": None, + "gate_note": "§10 未给阈值,以上为测量,不称性能门通过", + "binary": str(args.binary.resolve()), "audit_binary": str(args.audit_binary.resolve()), + "persistent_binary": str(args.persistent_binary.resolve()) if args.persistent_binary else None, + "configuration": vars(args) | {"binary": str(args.binary), "audit_binary": str(args.audit_binary), + "persistent_binary": str(args.persistent_binary), + "root": str(args.root)}, + "percentile_method": "nearest rank on raw per-RPC end-to-end client latencies; p99.9 is sparse-tail descriptive only at small N", + "business_rpc": ("generated CycleStore Lookup/Commit on one persistent brpc Channel per producer lane" + if args.client_mode == "persistent" else + "generated CycleStore Lookup/Commit via a new dfkv_cycle_controller process per RPC"), + "cold_cli_evidence_do_not_mix": "../evidence-perf-attempt02", + "admin_not_measured_as_business": True, + } + (args.root / "run-manifest.json").write_text(json.dumps(manifest, indent=2, sort_keys=True, default=str)) + scenarios = [ + ("B1", lambda: run_b1(args.binary, args.audit_binary, args.root, + args.persistent_binary, args.client_mode)), + ("B2", lambda: run_b2(args.binary, args.audit_binary, args.root, args.b2_cold_families, + args.persistent_binary, args.client_mode)), + ("B3", lambda: run_b3(args.binary, args.audit_binary, args.root, + args.b3_hot_operations, args.b3_cold_families, args.monitor_interval_s, + args.persistent_binary, args.client_mode, args.status_baseline_calls)), + ] + results = {} + failed = 0 + for label, runner in scenarios: + started = time.time() + try: + outcome = runner() + result = finish(label, outcome, args) + results[label] = {"status": result["status"], "summary": str(args.root / f"summary-{label}.json"), + "measured_requests": result["load"]["measured_requests"], + "exceptions": len(result["exceptions"])} + if result["exceptions"]: + failed += 1 + print(f"MEASURED scenario={label} requests={result['load']['measured_requests']} " + f"exceptions={len(result['exceptions'])} summary={args.root / f'summary-{label}.json'}", flush=True) + except Exception as error: + failed += 1 + failure = {"status": "FAILED", "type": type(error).__name__, "message": str(error), + "traceback": traceback.format_exc()} + results[label] = failure + (args.root / f"failure-{label}.json").write_text(json.dumps(failure, indent=2, sort_keys=True)) + print(f"FAIL scenario={label} error={error}", flush=True) + results[label]["wall_seconds"] = time.time() - started + overall = {"manifest": str(args.root / "run-manifest.json"), "scenarios": results, + "failed_scenarios": failed, "B4": {"status": "NOT_RUN_OPTIONAL", + "reason": "B1-B3 first-batch delivery prioritized; no RTO claim"}, + "performance_gate_verdict": None, + "gate_note": "§10 未给阈值,以上为测量,不称性能门通过"} + (args.root / "summary.json").write_text(json.dumps(overall, indent=2, sort_keys=True)) + print(json.dumps(overall, sort_keys=True), flush=True) + return 0 if failed == 0 else 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/src/cyclestore/test/raft_capability_perf_test.py b/src/cyclestore/test/raft_capability_perf_test.py new file mode 100755 index 00000000..16be484a --- /dev/null +++ b/src/cyclestore/test/raft_capability_perf_test.py @@ -0,0 +1,365 @@ +#!/usr/bin/env python3 +"""Same-byte persistent-client comparison of full evidence and capabilities. + +All measured operations are real Lookup/Commit RPCs on a three-replica braft +cluster. Cold and appended paths always send complete evidence. Capability +requests are accepted only after a server-issued, durable proof; every negative +capability probe must request the complete-evidence fallback. This reports +measurements, not a performance-gate verdict. +""" + +import argparse +import copy +import hashlib +import json +import os +from pathlib import Path +import shutil +import signal +import subprocess +import sys +import time +import traceback + +from raft_business_perf_test import (PerfCluster, counter_distribution, + distribution, family_for, path_for, + appended_path, branch_path) + + +def verify_helper_closure(): + manifest_path = Path(__file__).with_name("capability_helper_manifest.json") + manifest = json.loads(manifest_path.read_text()) + actual = {} + for name, expected in manifest["runtime_verified_files"].items(): + digest = hashlib.sha256(Path(__file__).with_name(name).read_bytes()).hexdigest() + if digest != expected: + raise RuntimeError(f"capability helper identity mismatch: {name}: {digest} != {expected}") + actual[name] = digest + return {"manifest": manifest, "verified_sha256": actual} + + +def capability_cycle(cluster, leader, family, capability, operation_id, name, + now_ms, outcome="RENEWED", new_nodes=0, generation=1, + sample_class="measurement", kind="capability"): + lookup_request = { + "family": family, + "operationId": operation_id, + "requestedTtl": "TTL_5M", + "evidenceCapability": capability, + } + lookup = cluster.business(leader, "lookup", lookup_request, name + "-lookup", + kind=kind + "_lookup", sample_class=sample_class) + cluster.validate_lookup(lookup) + commit_request = { + "token": copy.deepcopy(lookup["response"]["token"]), + "prefillCompletedAtMs": str(now_ms), + "evidenceCapability": capability, + } + commit = cluster.business(leader, "commit", commit_request, name + "-commit", + kind=kind + "_commit", sample_class=sample_class) + receipt = cluster.validate_commit(commit, outcome, new_nodes, generation) + cluster.pair(lookup, commit, kind + "_pair_sum", "main", new_nodes, + sample_class=sample_class) + return lookup, commit, commit["response"]["evidenceCapability"] + + +def full_cycle(cluster, leader, family, path, operation_id, name, now_ms, + outcome="RENEWED", new_nodes=0, generation=1, + sample_class="measurement"): + lookup_request = {"family": family, "operationId": operation_id, + "path": path, "requestedTtl": "TTL_5M"} + lookup = cluster.business(leader, "lookup", lookup_request, name + "-lookup", + kind="full_lookup", sample_class=sample_class) + cluster.validate_lookup(lookup) + commit_request = {"token": copy.deepcopy(lookup["response"]["token"]), + "path": path, "prefillCompletedAtMs": str(now_ms)} + commit = cluster.business(leader, "commit", commit_request, name + "-commit", + kind="full_commit", sample_class=sample_class) + receipt = cluster.validate_commit(commit, outcome, new_nodes, generation) + cluster.pair(lookup, commit, "full_pair_sum", "main", new_nodes, + sample_class=sample_class) + return lookup, commit, cluster.pair_events[-1] + + +def summarize(cluster, root, source_head, profile, started_ns, completed_ns): + events = [event for event in cluster.events if event["sample_class"] == "measurement"] + groups = {} + for event in events: + row = groups.setdefault(event["kind"], {"lookup_commit": {}, "payload": {}}) + row["lookup_commit"]["latency"] = distribution( + [item["latency_ns"] for item in events if item["kind"] == event["kind"]]) + for key in ("request_proto_bytes", "request_json_bytes", + "raft_business_command_bytes", "prepare_latency_ns", + "protobuf_serialize_ns", "business_frame_encode_ns"): + if key in event: + row["payload"][key] = counter_distribution( + [item[key] for item in events + if item["kind"] == event["kind"] and key in item]) + pairs = [event for event in cluster.pair_events + if event["sample_class"] == "measurement"] + pair_groups = {} + for kind in sorted({event["kind"] for event in pairs}): + pair_groups[kind] = distribution( + [event["latency_ns"] for event in pairs if event["kind"] == kind]) + summary = { + "schema": "cyclestore-capability-perf-v1", + "source_head": source_head, + "capability_helper_closure": verify_helper_closure(), + "measurement": "NO_PERFORMANCE_GATE_VERDICT", + "elapsed_ns": completed_ns - started_ns, + "groups": groups, + "pairs": pair_groups, + "correctness": cluster.correctness, + "exceptions": cluster.exceptions, + "events": len(events), + "profile": profile, + "store_audits": cluster.audits, + } + (root / "summary.json").write_text(json.dumps(summary, indent=2, sort_keys=True)) + return summary + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--binary", required=True, type=Path) + parser.add_argument("--audit-binary", required=True, type=Path) + parser.add_argument("--persistent-binary", required=True, type=Path) + parser.add_argument("--root", required=True, type=Path) + parser.add_argument("--pages", type=int, default=16000) + parser.add_argument("--hot-pairs", type=int, default=16) + parser.add_argument("--source-head", required=True) + parser.add_argument("--profile", action="store_true") + args = parser.parse_args() + verify_helper_closure() + if args.root.exists() or args.pages < 2 or args.hot_pairs < 2: + print("FAIL: fresh root, D>=2 and at least two hot pairs are required") + return 2 + args.root.mkdir(parents=True) + cluster = PerfCluster(args.binary.resolve(), args.audit_binary.resolve(), + args.root / "cluster", "CAPABILITY", + args.persistent_binary.resolve(), "persistent", + instrument_payload=True) + profile = {"requested": args.profile, "status": "not_requested"} + profiler = None + started_ns = completed_ns = None + expected_graph = 0 + expected_leases = 0 + try: + leader, _ = cluster.start_all() + cluster.set_clocks(1000000) + roots = {} + paths = {} + for mode in ("full", "capability"): + root = f"cap-{mode}-root-0000000000000000".encode()[:32].ljust(32, b"0") + roots[mode] = root + paths[mode] = path_for(root, f"same-seed-{mode}".encode(), args.pages) + family = family_for(root, scope="s4-capability-perf") + cluster.cycle(leader, family, paths[mode], f"{mode}-cold", + f"{mode}-cold", 1000000, "ROOT_CYCLE_CREATED", args.pages, + kind="setup", sample_class="setup") + expected_graph += len(paths[mode]["pages"]) + expected_leases += 1 + # One warm-up is deliberately outside measurement. + lookup, commit, pair = cluster.cycle( + leader, family, paths[mode], f"{mode}-warm", f"{mode}-warm", + 1000000, "RENEWED", 0, kind="warmup", sample_class="setup") + expected_leases += 1 + if mode == "capability": + cluster.check("evidenceCapability" in commit["response"], + "warm_capability_issued") + + if args.profile: + if shutil.which("perf") is None: + profile = {"requested": True, "status": "perf_not_installed"} + else: + data = args.root / "leader.perf.data" + profiler = subprocess.Popen( + ["perf", "record", "-F", "997", "-g", "-p", + str(cluster.processes[leader].pid), "-o", str(data)], + stdout=(args.root / "perf-record.log").open("w"), + stderr=subprocess.STDOUT, + env={**os.environ, "HISTFILE": "/dev/null"}) + profile = {"requested": True, "status": "recording", + "leader_pid": cluster.processes[leader].pid, + "data": str(data)} + started_ns = time.perf_counter_ns() + for mode in ("full", "capability"): + family = family_for(roots[mode], scope="s4-capability-perf") + if mode == "capability": + # Re-establish the client-side reference from a durable full + # lookup, then use only short references for this hot sequence. + setup_lookup, setup_commit, _ = cluster.cycle( + leader, family, paths[mode], "capability-reference", + "capability-reference", 1000000, "RENEWED", 0, + kind="setup", sample_class="setup") + expected_leases += 1 + capability = setup_commit["response"]["evidenceCapability"] + for index in range(args.hot_pairs): + now_ms = 1000000 + name = f"{mode}-hot-{index}" + if mode == "full": + full_cycle(cluster, leader, family, paths[mode], name, name, + now_ms) + else: + _, _, capability = capability_cycle( + cluster, leader, family, capability, name, name, now_ms) + expected_leases += 1 + + # A side renewal uses its own path proof and cannot borrow the main + # chain's reference. + side_path = branch_path(paths[mode], roots[mode], + f"same-seed-{mode}".encode(), "side") + setup_lookup, setup_commit, _ = cluster.cycle( + leader, family, side_path, f"{mode}-side-cold", f"{mode}-side-cold", + 1000000, "PATH_COVERAGE_CREATED", 1, kind="setup", sample_class="setup") + expected_graph += len(side_path["pages"]) - (len(paths[mode]["pages"]) - 1) + expected_leases += 1 + if mode == "full": + full_cycle(cluster, leader, family, side_path, "full-side-hot", + "full-side-hot", 1000000, new_nodes=0) + else: + capability = setup_commit["response"]["evidenceCapability"] + side_lookup, _, capability = capability_cycle( + cluster, leader, family, capability, + "capability-side-hot", "capability-side-hot", 1000000) + invalid = copy.deepcopy(capability) + invalid["validatedApplyIndex"] = "1" + rejected = cluster.business( + leader, "commit", + {"token": copy.deepcopy(side_lookup["response"]["token"]), + "prefillCompletedAtMs": "1000000", + "evidenceCapability": invalid}, + "capability-final-fallback", kind="capability_fallback", + sample_class="correctness") + cluster.check(rejected["response"].get("transportError") == "INVALID_EVIDENCE", + "final_fallback_transport", response=rejected["response"]) + cluster.check(rejected["response"].get("evidenceFallbackRequired") is True, + "final_fallback_flag") + cluster.check("receipt" not in rejected["response"], + "final_fallback_never_shadows_receipt") + expected_leases += 1 + + # Delta=1 and create-next-root always use complete evidence. + appended = appended_path(paths[mode], roots[mode], b"delta", 1, "one") + appended_lookup, _, _ = full_cycle( + cluster, leader, family, appended, f"{mode}-delta-one", + f"{mode}-delta-one", 1000000, + outcome="PATH_COVERAGE_CREATED", new_nodes=1) + expected_graph += len(appended["pages"]) - len(paths[mode]["pages"]) + expected_leases += 1 + # Replaying the appended operation with the same tip but a changed + # non-root ancestor must conflict without another lease or node. + wrong_ancestor_path = copy.deepcopy(appended) + wrong_ancestor_path["pages"][-2] = path_for( + roots[mode], f"same-seed-{mode}".encode(), pages=1, + branch="wrong-ancestor", start=len(appended["pages"]) - 2)["pages"][0] + wrong_ancestor = cluster.business( + leader, "commit", + {"token": copy.deepcopy(appended_lookup["response"]["token"]), + "path": wrong_ancestor_path, "prefillCompletedAtMs": "1000000"}, + f"{mode}-wrong-appended-ancestor", kind="correctness_conflict", + sample_class="correctness") + cluster.check(wrong_ancestor["response"]["receipt"].get("outcome") == + "OPERATION_ID_CONFLICT", "wrong_side_ancestor_conflict") + cluster.check(wrong_ancestor["response"]["receipt"].get("logicalCommitApplied") is False, + "wrong_side_ancestor_no_positive_effect") + cluster.correctness["intentional_conflicts"] += 1 + if mode == "capability": + stale = copy.deepcopy(capability) + stale["validatedApplyIndex"] = "1" + rejected = cluster.business( + leader, "lookup", + {"family": family, "operationId": "unknown-capability", + "requestedTtl": "TTL_5M", "evidenceCapability": stale}, + "unknown-capability", kind="capability_fallback", + sample_class="correctness") + cluster.check(rejected["response"].get("result") == "INVALID_EVIDENCE", + "unknown_capability_rejected", response=rejected["response"]) + cluster.check(rejected["response"].get("evidenceFallbackRequired") is True, + "fallback_flag_present") + + # Restart the leader after the full and short-reference streams. The + # first request on the newly elected leader must resolve the recovered + # durable capability, not a process-local client assertion. + family = family_for(roots["capability"], scope="s4-capability-perf") + cluster.processes[leader].terminate() + cluster.processes[leader].wait(timeout=20) + cluster.start(leader) + deadline = time.monotonic() + 30 + recovered_leader = None + while time.monotonic() < deadline and recovered_leader is None: + statuses = [cluster.admin(index, "status") for index in range(3)] + if all(status.get("ok") for status in statuses): + recovered_leader = next( + (index for index, status in enumerate(statuses) + if status.get("nodeState") == "LEADER"), None) + if recovered_leader is None: + time.sleep(0.1) + cluster.check(recovered_leader is not None, "recovery_leader_elected") + leader = recovered_leader + cluster.set_clocks(1000000) + for resident in list(cluster._residents.values()): + resident.close() + cluster._residents.clear() + _, _, capability = capability_cycle( + cluster, leader, family, capability, "recovery-first-capability", + "recovery-first-capability", 1000000, kind="recovery_capability") + expected_leases += 1 + + cluster.set_clocks(1400000) + expired = cluster.business( + leader, "lookup", + {"family": family, "operationId": "expired-capability", + "requestedTtl": "TTL_5M", "evidenceCapability": capability}, + "expired-capability", kind="capability_fallback", + sample_class="correctness") + cluster.check(expired["response"].get("evidenceFallbackRequired") is True, + "expired_capability_requires_full") + full_cycle(cluster, leader, family, paths["capability"], "create-next-root", + "create-next-root", 1400000, outcome="ROOT_CYCLE_CREATED", + new_nodes=0, generation=2) + expected_leases += 1 + cluster.wait_all_debug(family, "create-next-root") + completed_ns = time.perf_counter_ns() + if profiler is not None: + profiler.send_signal(signal.SIGINT) + profile["record_exit"] = profiler.wait(timeout=30) + report = subprocess.run(["perf", "report", "--stdio", "-i", profile["data"]], + text=True, capture_output=True, timeout=60) + (args.root / "perf-report.txt").write_text(report.stdout + report.stderr) + profile["report_exit"] = report.returncode + profile["status"] = "captured" if report.returncode == 0 else "report_failed" + else: + completed_ns = time.perf_counter_ns() + cluster.cleanup() + # Counts are independently scanned from every replica's persisted CFs. + cluster.audit_stores(cluster.current_ms, expected_graph=expected_graph, + expected_leases=expected_leases, require_no_pruning=True) + summary = summarize(cluster, args.root, args.source_head, profile, + started_ns, completed_ns) + summary["store_audits"] = cluster.audits + summary["expected_graph_highwater"] = expected_graph + summary["expected_positive_leases"] = expected_leases + summary["status"] = ("MEASURED_WITH_CORRECTNESS_ASSERTIONS_PASS" + if not cluster.exceptions else "MEASURED_WITH_EXCEPTIONS") + (args.root / "summary.json").write_text(json.dumps(summary, indent=2, sort_keys=True)) + print(f"CAPABILITY_MEASUREMENT status={summary['status']} events={summary['events']} " + f"summary={args.root / 'summary.json'}") + return 0 if not cluster.exceptions else 1 + except Exception as error: + completed_ns = completed_ns or time.perf_counter_ns() + cluster.record_exception("capability_perf", error) + if profiler is not None and profiler.poll() is None: + profiler.send_signal(signal.SIGINT) + profiler.wait(timeout=30) + cluster.cleanup() + summary = summarize(cluster, args.root, args.source_head, profile, + started_ns or time.perf_counter_ns(), completed_ns) + summary["status"] = "MEASURED_WITH_EXCEPTIONS" + (args.root / "summary.json").write_text(json.dumps(summary, indent=2, sort_keys=True)) + traceback.print_exc() + return 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/src/cyclestore/test/store_perf_audit_main.cc b/src/cyclestore/test/store_perf_audit_main.cc new file mode 100644 index 00000000..61c93520 --- /dev/null +++ b/src/cyclestore/test/store_perf_audit_main.cc @@ -0,0 +1,109 @@ +#include +#include +#include +#include +#include + +#include "cyclestore/store.h" + +namespace dfkv::cyclestore { +namespace { + +int Fail(const std::string& stage, const StoreStatus& status) { + std::cerr << "{" << "\"ok\":false,\"stage\":\"" << stage + << "\",\"error\":\"" << status.detail << "\"}\n"; + return 1; +} + +} // namespace +} // namespace dfkv::cyclestore + +int main(int argc, char** argv) { + using namespace dfkv::cyclestore; + std::string path; + std::int64_t now_ms = 0; + for (int i = 1; i < argc; ++i) { + const std::string argument(argv[i]); + if (argument.rfind("--db=", 0) == 0) { + path = argument.substr(5); + } else if (argument.rfind("--now_ms=", 0) == 0) { + try { + now_ms = std::stoll(argument.substr(9)); + } catch (...) { + std::cerr << "invalid --now_ms\n"; + return 2; + } + } else { + std::cerr << "usage: store_perf_audit_main --db=PATH [--now_ms=MS]\n"; + return 2; + } + } + if (path.empty()) { + std::cerr << "missing --db\n"; + return 2; + } + + OpenStoreOptions options; + options.path = path; + options.read_only = true; + std::unique_ptr store; + StoreStatus status = Store::Open(options, &store); + if (!status.ok()) return Fail("open", status); + + ShardMeta meta; + status = store->ReadMeta(&meta); + if (!status.ok()) return Fail("read_meta", status); + std::vector nodes; + std::vector unique_nodes; + std::vector leases; + std::vector operations; + std::vector capabilities; + std::vector expiry; + status = store->ScanRecords(RecordKind::kNode, &nodes); + if (!status.ok()) return Fail("scan_nodes", status); + status = store->ScanRecords(RecordKind::kNodeUniqueIndex, &unique_nodes); + if (!status.ok()) return Fail("scan_unique_nodes", status); + status = store->ScanRecords(RecordKind::kLease, &leases); + if (!status.ok()) return Fail("scan_leases", status); + status = store->ScanRecords(RecordKind::kOperation, &operations); + if (!status.ok()) return Fail("scan_operations", status); + status = store->ScanRecords(RecordKind::kEvidenceCapability, &capabilities); + if (!status.ok()) return Fail("scan_capabilities", status); + status = store->ScanRecords(RecordKind::kExpiryIndex, &expiry); + if (!status.ok()) return Fail("scan_expiry", status); + + std::uint64_t due_leases = 0; + std::int64_t oldest_lease_gc_at = 0; + std::string decode_error; + for (const StoredRecord& stored : leases) { + LeaseRecord lease; + if (!DecodeLeaseRecord(stored.value, &lease, &decode_error)) { + std::cerr << "cannot decode lease: " << decode_error << "\n"; + return 1; + } + if (lease.lease_gc_at_ms < now_ms) { + ++due_leases; + if (oldest_lease_gc_at == 0 || lease.lease_gc_at_ms < oldest_lease_gc_at) + oldest_lease_gc_at = lease.lease_gc_at_ms; + } + } + const std::int64_t gc_lag_ms = oldest_lease_gc_at == 0 ? 0 : now_ms - oldest_lease_gc_at; + std::cout << "{\"ok\":true" + << ",\"last_applied_index\":" << meta.last_applied_index + << ",\"last_applied_term\":" << meta.last_applied_term + << ",\"data_epoch\":" << meta.data_epoch + << ",\"last_accepted_wall_time_ms\":" << meta.last_accepted_wall_time_ms + << ",\"graph_highwater\":" << (meta.next_node_ordinal - 1) + << ",\"lease_highwater\":" << (meta.next_lease_ordinal - 1) + << ",\"next_command_ordinal\":" << meta.next_command_ordinal + << ",\"node_records\":" << nodes.size() + << ",\"node_unique_records\":" << unique_nodes.size() + << ",\"lease_records\":" << leases.size() + << ",\"operation_records\":" << operations.size() + << ",\"evidence_capability_records\":" << capabilities.size() + << ",\"expiry_records\":" << expiry.size() + << ",\"now_ms\":" << now_ms + << ",\"due_lease_records\":" << due_leases + << ",\"gc_lag_ms\":" << gc_lag_ms << "}\n"; + return 0; +} diff --git a/test/cache/ram_tier_test.cc b/test/cache/ram_tier_test.cc index e5aea541..dc2002a4 100644 --- a/test/cache/ram_tier_test.cc +++ b/test/cache/ram_tier_test.cc @@ -530,7 +530,10 @@ TEST(RamTier, WriteBackFlushFailureIsPostAckAndUnhealthy) { const std::string value(500, 'f'); EXPECT_EQ(rt.PutWriteBack(K(104), value.data(), value.size()).status, Status::kOk); - ASSERT_TRUE(WaitFor([&] { return rt.FlushDropped() == 1u; })); + ASSERT_TRUE(WaitFor([&] { + return rt.FlushDropped() == 1u && !rt.healthy(); + })) << "timed out waiting for loss: flush_dropped=" << rt.FlushDropped() + << ", healthy=" << rt.healthy(); EXPECT_EQ(rt.PostAckFlushFailures(), 1u); EXPECT_EQ(rt.DirtyObjects(), 0u); EXPECT_FALSE(rt.healthy()); @@ -2328,7 +2331,10 @@ TEST(RamTierFlushFailure, AfterTheLastAttemptTheValueIsDroppedAndCounted) { const std::string value(500, 'd'); ASSERT_EQ(rt.PutWriteBack(K(1), value.data(), value.size()).status, Status::kOk); - ASSERT_TRUE(WaitFor([&] { return rt.FlushDropped() == 1u; })); + ASSERT_TRUE(WaitFor([&] { + return rt.FlushDropped() == 1u && !rt.healthy(); + })) << "timed out waiting for loss: flush_dropped=" << rt.FlushDropped() + << ", healthy=" << rt.healthy(); EXPECT_EQ(sink.count(), 4u); EXPECT_EQ(rt.FlushRetries(), 3u); EXPECT_EQ(rt.PostAckFlushFailures(), 1u); @@ -2365,7 +2371,10 @@ TEST(RamTierFlushFailure, FlushToAFailedTargetIsNotRetried) { const std::string value(500, 't'); ASSERT_EQ(rt.PutWriteBack(K(1), value.data(), value.size()).status, Status::kOk); - ASSERT_TRUE(WaitFor([&] { return rt.FlushDropped() == 1u; })); + ASSERT_TRUE(WaitFor([&] { + return rt.FlushDropped() == 1u && !rt.healthy(); + })) << "timed out waiting for loss: flush_dropped=" << rt.FlushDropped() + << ", healthy=" << rt.healthy(); EXPECT_EQ(sink.count(), 1u); EXPECT_EQ(rt.FlushRetries(), 0u); EXPECT_EQ(rt.PostAckFlushFailures(), 1u); @@ -2386,8 +2395,10 @@ TEST(RamTierFlushFailure, HealthRecoversWhenFlushesSucceedAgain) { return rt.PutWriteBack(K(id), value.data(), value.size()).status; }; ASSERT_EQ(put(1), Status::kOk); - ASSERT_TRUE(WaitFor([&] { return rt.FlushDropped() == 1u; })); - ASSERT_FALSE(rt.healthy()); + ASSERT_TRUE(WaitFor([&] { + return rt.FlushDropped() == 1u && !rt.healthy(); + })) << "timed out waiting for loss: flush_dropped=" << rt.FlushDropped() + << ", healthy=" << rt.healthy(); failing = false; for (uint64_t id = 10; id < 17; ++id) ASSERT_EQ(put(id), Status::kOk); @@ -2781,10 +2792,12 @@ TEST(RamTierFlushFailure, FailuresAfterRefusalsStillEndInALoss) { ASSERT_EQ(rt.PutWriteBack(K(1), value.data(), value.size()).status, Status::kOk); // DirtyObjects() acquire-read pairs with the post-NoteDrop() release - // decrement; admission added the only dirty object before this wait. + // decrement; flush_dropped_ is published before NoteDrop clears healthy_. + // Wait for every terminal effect rather than the legitimate interval between. ASSERT_TRUE(WaitFor([&] { - return rt.FlushDropped() == 1u && rt.DirtyObjects() == 0; - })); + return rt.FlushDropped() == 1u && rt.DirtyObjects() == 0 && !rt.healthy(); + })) << "timed out waiting for loss: flush_dropped=" << rt.FlushDropped() + << ", dirty=" << rt.DirtyObjects() << ", healthy=" << rt.healthy(); EXPECT_EQ(sink.calls.load(), 5); EXPECT_EQ(rt.FlushNoRoom(), 2u); EXPECT_EQ(rt.FlushRetries(), 2u); diff --git a/test/cyclestore/capability_diff.py b/test/cyclestore/capability_diff.py new file mode 100755 index 00000000..33c16164 --- /dev/null +++ b/test/cyclestore/capability_diff.py @@ -0,0 +1,492 @@ +#!/usr/bin/env python3 +"""Independent expected-value differential for evidence capabilities. + +The C++ provider outputs business results and durable projections. This runner +independently declares command traces and expected outcomes, validates rejection +and side-effect invariants, and compares complete semantic receipts between +full-evidence and capability forms. No expected value is copied from the +corresponding request or accepted merely because the provider echoed it. +""" + +import argparse +import json +import os +from pathlib import Path +import subprocess +import sys + +ROOT = "root/a" + + +def command(text): + return {"command": text} + + +class Oracle: + def __init__(self, binary, artifacts): + self.binary = str(binary) + self.artifacts = artifacts + self.artifacts.mkdir(parents=True) + self.trace = [] + self.expected = [] + self.replies = [] + self.checks = 0 + self.errors = [] + + def require(self, condition, label, reply, detail=None): + self.checks += 1 + if not condition: + self.errors.append({"assertion": label, "detail": detail, "reply": reply}) + + def value(self, reply, path, expected, label): + if path == "capability_count": + actual = len(reply["capabilities"]) + else: + actual = reply + for part in path.split("."): + actual = actual[part] + self.require(actual == expected, label, reply, + {"path": path, "expected": expected, "actual": actual}) + + def expect(self, text, **expected): + index = len(self.trace) + expected = {key: (True if value == "true" else False if value == "false" else value) + for key, value in expected.items()} + self.trace.append(text) + self.expected.append((index, expected)) + return index + + def case(self, name): + return self.expect(f"CASE {name}", result="case") + + def bootstrap(self, path=ROOT): + self.expect(f"LOOKUP cold {path} 300000 0 1 1 0", result="ok") + self.expect(f"COMMIT cold {path} 0 0", result="root_cycle_created", + **{"capability_count": 1}) + + def run_all(self): + completed = subprocess.run([self.binary], input="\n".join(self.trace) + "\n", + text=True, capture_output=True, timeout=180) + (self.artifacts / "trace.txt").write_text("\n".join(self.trace) + "\n") + (self.artifacts / "business-output.jsonl").write_text(completed.stdout) + (self.artifacts / "stderr.txt").write_text(completed.stderr) + if completed.returncode != 0: + raise RuntimeError(f"capability provider failed rc={completed.returncode}: {completed.stderr}") + replies = [json.loads(line) for line in completed.stdout.splitlines() if line] + if len(replies) != len(self.expected): + raise RuntimeError(f"reply count {len(replies)} != commands {len(self.expected)}") + self.replies = replies + for index, expected in self.expected: + reply = replies[index] + for path, value in expected.items(): + if path == "capability_count": + self.value(reply, path, value, "capability_count") + else: + self.value(reply, path, value, "independent_expected") + return replies + + def add_delta_zero_pair(self, name, capability): + self.case(name) + self.expect(f"LOOKUP cold {ROOT} 300000 0 1 1 0", result="ok") + self.expect(f"COMMIT cold {ROOT} 0 0", result="root_cycle_created", + **{"receipt.new_node_count": 2, "capability_count": 1}) + self.expect(f"LOOKUP known {ROOT} 300000 1000 1 1 0", result="ok") + self.expect(f"COMMIT known {ROOT} 1000 1000", result="renewed", + **{"receipt.new_node_count": 0, "capability_count": 1}) + self.expect(f"CAP_LOOKUP hot known 300000 1000 0", result="ok", + has_capability="true", capability_count=1) + if capability: + self.expect(f"CAP_COMMIT hot hot hot 1000 1000", result="renewed", + **{"receipt.new_node_count": 0, "capability_count": 1}) + else: + self.expect(f"COMMIT hot {ROOT} 1000 1000", result="renewed", + **{"receipt.new_node_count": 0, "capability_count": 1}) + return len(self.trace) - 1 + + def build(self): + full_hot = self.add_delta_zero_pair("full-semantic", capability=False) + short_hot = self.add_delta_zero_pair("short-semantic", capability=True) + self.semantic_pairs = [(full_hot, short_hot)] + + self.expect("CAP_COMMIT hot known hot 1000 2000", receipt_replayed="true") + self.expect("RECOVER", result="recovered", capability_count=1) + self.expect("CAP_COMMIT hot known hot 1000 2001", receipt_replayed="true") + self.expect("CAP_STATE", capability_count=1) + + for field in ("canonical_path_digest", "complete_page_evidence_digest", + "tip_incarnation", "root_generation", "data_epoch", + "family_incarnation", "root_locked_ttl", "validated_apply_index", + "future_apply_index", "page_count", "tip_page_hash", "family"): + self.case("invalid-" + field) + self.bootstrap() + self.expect(f"CAP_MUTATE cold {field}", result="capability_mutated") + self.expect("CAP_LOOKUP invalid cold 300000 1000 0", result="invalid_evidence", + fallback_required="true", has_capability="false") + self.expect("CAP_STATE", capability_count=1) + + self.case("side-lineage-parent-mismatch") + self.bootstrap("root/a/x") + self.expect("LOOKUP side root/b/y 300000 1000 1 1 0", result="ok") + self.expect("COMMIT side root/b/y 1000 1000", result="path_coverage_created") + self.expect("CAP_SWAP_TIP cold side", result="capability_tip_swapped") + self.expect("CAP_LOOKUP confused cold 300000 1000 0", result="invalid_evidence", + fallback_required="true") + self.expect("LOOKUP wrong root/b/x 300000 1000 1 1 0", result="evidence_conflict") + + self.case("expired-root-new-generation") + self.bootstrap() + self.expect("CAP_LOOKUP expired cold 300000 301000 0", result="invalid_evidence", + fallback_required="true") + self.expect(f"LOOKUP replay {ROOT} 300000 1000 1 1 0", result="ok") + self.expect(f"LOOKUP next {ROOT} 300000 301000 1 1 0", result="ok") + self.expect("CAP_ALIAS next_issued next", result="capability_aliased", + has_capability="true", capability_root_generation=1) + self.generation_commit_index = self.expect( + f"COMMIT next {ROOT} 301000 301000", result="root_cycle_created", + **{"receipt.root_generation": 2, "receipt.new_node_count": 0, + "capability_root_generation": 2}) + self.expect("CAP_LOOKUP stale cold 300000 302000 0", result="invalid_evidence", + fallback_required="true") + self.expect("CAP_LOOKUP fresh next 300000 302000 0", result="ok", + capability_root_generation=2) + self.generation_lookup_replay_index = self.expect( + "CAP_LOOKUP replay replay 300000 302000 1", result="ok", + capability_root_generation=1, capability_validated_apply_index=3) + self.generation_commit_replay_index = self.expect( + "CAP_COMMIT commit_replay next_issued next 301000 302000", receipt_replayed="true", + result="root_cycle_created", fallback_required="false", + **{"receipt.root_generation": 2, "receipt.accepted_at_ms": 301000}) + self.expect("RECOVER", result="recovered", capability_count=1) + self.expect("CAP_LOOKUP replay replay 300000 302000 1", result="ok", + capability_root_generation=1, capability_validated_apply_index=3) + self.expect("CAP_MUTATE replay validated_apply_index", result="capability_mutated") + self.generation_forged_lookup_replay_index = self.expect( + "CAP_LOOKUP replay replay 300000 302000 1", result="invalid_evidence", + fallback_required="true", has_capability="false") + + self.case("semantic-v2-replay-negative-controls") + self.bootstrap() + self.expect(f"LOOKUP next {ROOT} 300000 301000 1 1 0", result="ok") + self.expect(f"COMMIT next {ROOT} 301000 301000", result="root_cycle_created") + self.expect("CAP_MUTATE cold complete_page_evidence_digest", result="capability_mutated") + self.expect("CAP_COMMIT bad cold next 301000 302000", result="invalid_evidence", + fallback_required="true", receipt_replayed="false") + self.expect("CAP_LOOKUP next cold 300000 302000 1", result="invalid_evidence", + fallback_required="true", has_capability="false") + self.expect("LOOKUP other root/b 300000 302000 1 1 0", result="ok") + self.expect("COMMIT other root/b 302000 302000", result="path_coverage_created", + capability_count=2) + self.expect("CAP_COMMIT crossed other next 301000 302000", + result="operation_id_conflict", receipt_replayed="false") + self.expect("CAP_LOOKUP next other 300000 302000 1", result="operation_id_conflict", + has_capability="false") + + self.case("late-final-capability-watermark") + self.bootstrap() + self.expect(f"LOOKUP hot {ROOT} 300000 1000 1 1 0", result="ok") + self.late_original_issued_index = self.expect( + "CAP_ALIAS hot_issued hot", result="capability_aliased", + has_capability="true", capability_root_generation=1) + self.late_final_original_index = self.expect( + f"COMMIT hot {ROOT} 1000 1000", result="renewed", + **{"receipt.root_generation": 1, "receipt.accepted_at_ms": 1000}) + self.late_final_rejected_index = self.expect( + "CAP_COMMIT late hot hot 1000 2000", result="invalid_evidence", + fallback_required="true", receipt_replayed="false", has_capability="false") + self.authentic_hot_replay_index = self.expect( + "CAP_COMMIT authentic hot_issued hot 1000 2000", result="renewed", + fallback_required="false", receipt_replayed="true", has_capability="true", + **{"receipt.root_generation": 1, "receipt.accepted_at_ms": 1000}) + self.repeated_hot_replay_index = self.expect( + "CAP_COMMIT repeated hot_issued hot 1000 2001", result="renewed", + fallback_required="false", receipt_replayed="true", has_capability="true", + **{"receipt.root_generation": 1, "receipt.accepted_at_ms": 1000}) + + self.case("same-path-live-cross-operation-origin") + self.bootstrap() + self.expect(f"LOOKUP victim {ROOT} 300000 1000 1 1 0", result="ok") + self.live_victim_issued_index = self.expect( + "CAP_ALIAS victim_issued victim", result="capability_aliased", + has_capability="true", capability_root_generation=1) + self.live_victim_commit_index = self.expect( + f"COMMIT victim {ROOT} 1000 1000", result="renewed", + **{"receipt.root_generation": 1, "receipt.accepted_at_ms": 1000}) + self.expect(f"LOOKUP donor {ROOT} 300000 2000 1 1 0", result="ok") + self.live_donor_commit_index = self.expect( + f"COMMIT donor {ROOT} 1000 2000", result="renewed", + **{"receipt.root_generation": 1, "receipt.accepted_at_ms": 2000}) + self.expect("CAP_HISTORY victim donor", result="capability_not_in_history") + self.expect("CAP_HISTORY donor victim", result="capability_not_in_history") + self.live_borrowed_commit_index = self.expect( + "CAP_COMMIT borrowed donor victim 1000 3000", result="invalid_evidence", + fallback_required="true", receipt_replayed="false", has_capability="false") + self.live_authentic_replay_index = self.expect( + "CAP_COMMIT authentic victim_issued victim 1000 3001", result="renewed", + fallback_required="false", receipt_replayed="true", has_capability="true", + **{"receipt.root_generation": 1, "receipt.accepted_at_ms": 1000}) + self.live_repeated_replay_index = self.expect( + "CAP_COMMIT repeated victim_issued victim 1000 3002", result="renewed", + fallback_required="false", receipt_replayed="true", has_capability="true", + **{"receipt.root_generation": 1, "receipt.accepted_at_ms": 1000}) + + self.case("same-path-cross-operation-origin-after-recovery") + self.bootstrap() + self.expect(f"LOOKUP donor {ROOT} 300000 0 1 1 0", result="ok") + self.expect("CAP_ALIAS donor_issued donor", result="capability_aliased", + has_capability="true") + self.donor_commit_index = self.expect( + f"COMMIT donor {ROOT} 0 0", result="renewed", + **{"receipt.root_generation": 1, "capability_root_generation": 1}) + self.expect(f"LOOKUP victim {ROOT} 300000 1000 1 1 0", result="ok") + self.victim_issued_index = self.expect( + "CAP_ALIAS victim_issued victim", result="capability_aliased", + has_capability="true", capability_root_generation=1) + self.victim_commit_index = self.expect( + f"COMMIT victim {ROOT} 1000 1000", result="renewed", + **{"receipt.root_generation": 1, "capability_root_generation": 1}) + self.expect("CAP_HISTORY donor donor_issued", result="capability_in_history") + self.expect("CAP_HISTORY donor donor", result="capability_in_history") + self.expect("CAP_HISTORY victim victim_issued", result="capability_in_history") + self.expect("CAP_HISTORY victim victim", result="capability_in_history") + self.expect("CAP_HISTORY victim donor", result="capability_not_in_history") + self.expect("CAP_HISTORY donor victim", result="capability_not_in_history") + self.expect(f"LOOKUP replacement {ROOT} 300000 301000 1 1 0", result="ok") + self.expect(f"COMMIT replacement {ROOT} 301000 301000", + result="root_cycle_created", **{"receipt.root_generation": 2}) + self.expect("RECOVER", result="recovered", capability_count=1) + self.borrowed_commit_index = self.expect( + "CAP_COMMIT borrowed donor victim 1000 302000", result="invalid_evidence", + fallback_required="true", receipt_replayed="false", has_capability="false") + self.authentic_victim_replay_index = self.expect( + "CAP_COMMIT authentic victim_issued victim 1000 302001", result="renewed", + fallback_required="false", receipt_replayed="true", has_capability="true", + **{"receipt.root_generation": 1, "receipt.accepted_at_ms": 1000}) + self.reversed_commit_index = self.expect( + "CAP_COMMIT reversed victim donor 0 302002", result="invalid_evidence", + fallback_required="true", receipt_replayed="false", has_capability="false") + + self.case("prune-restart-snapshot-recreate") + self.bootstrap() + self.expect("LOOKUP by root/b/y 300000 1000 1 1 0", result="ok") + self.expect("COMMIT by root/b/y 1000 1000", result="path_coverage_created", + capability_count=2) + self.expect("COLLECT 1000000 0 64", result="collected", capability_count=0) + self.expect("CAP_LOOKUP pruned cold 300000 1000001 0", result="invalid_evidence", + fallback_required="true") + self.expect("RECOVER", result="recovered", capability_count=0) + self.expect("CAP_COMMIT prunedcold cold cold 1000 1000001", result="invalid_evidence", + fallback_required="true", receipt_replayed="false") + self.expect("CHECKPOINT", result="checkpoint") + self.expect("RESTORE", result="restored", capability_count=0) + self.expect("CAP_LOOKUP loaded cold 300000 1000001 0", result="invalid_evidence", + fallback_required="true", capability_count=0) + self.expect(f"COMMIT cold {ROOT} 0 1000001", result="stale_lookup_token", + receipt_replayed="false", **{"receipt.logical_commit_applied": "false"}) + self.expect(f"LOOKUP rebuilt {ROOT} 300000 1000001 1 1 0", result="ok") + rebuilt = len(self.trace) + self.expect(f"COMMIT rebuilt {ROOT} 1000001 1000001", result="root_cycle_created") + self.rebuilt_operation_index = rebuilt + self.expect("CAP_LOOKUP staleafter cold 300000 1000002 0", result="invalid_evidence", + fallback_required="true") + + self.case("legacy-final-and-optional-tail") + self.bootstrap() + self.expect(f"CAP_MARK_LEGACY cold {ROOT} 0", result="legacy_marked") + self.expect("RECOVER", result="recovered", capability_count=1) + self.expect("CAP_COMMIT coldshort cold cold 0 1000", result="invalid_evidence", + fallback_required="true", receipt_replayed="false") + # The original FINAL remains FINAL and retains its old receipt: the + # fallback is not materialized as a new FINAL or operation conflict. + self.expect(f"COMMIT cold {ROOT} 0 1000", receipt_replayed="true") + self.expect(f"LOOKUP next {ROOT} 300000 301000 1 1 0", result="ok") + self.expect(f"COMMIT next {ROOT} 301000 301000", result="root_cycle_created", + **{"receipt.root_generation": 2}) + self.expect("CAP_COMMIT stalelegacy cold cold 0 302000", result="invalid_evidence", + fallback_required="true", receipt_replayed="false") + + def compare_semantics(self): + late_original = self.replies[self.late_final_original_index] + late_rejected = self.replies[self.late_final_rejected_index] + hot_replay = self.replies[self.authentic_hot_replay_index] + repeated_hot_replay = self.replies[self.repeated_hot_replay_index] + hot_operation = next(op for op in late_original["state"]["operations"] + if op["operation_id"] == "hot") + self.require(late_original["capability_validated_apply_index"] > + hot_operation["read_apply_index"], + "late_final_capability_exceeds_token_read_watermark", + {"original": late_original, "token": hot_operation}) + self.require(late_original["state"] == late_rejected["state"] and + late_original["capabilities"] == late_rejected["capabilities"] and + late_rejected["receipt"] != late_original["receipt"], + "late_final_capability_cannot_replay_or_mutate_final", + {"original": late_original, "rejected": late_rejected}) + for replay in (hot_replay, repeated_hot_replay): + self.require(replay["receipt"] == late_original["receipt"] and + replay["capability_validated_apply_index"] == + hot_operation["read_apply_index"], + "original_lookup_capability_replays_original_receipt_repeatedly", + {"original": late_original, "replay": replay}) + + live_victim_commit = self.replies[self.live_victim_commit_index] + live_donor_commit = self.replies[self.live_donor_commit_index] + live_borrowed = self.replies[self.live_borrowed_commit_index] + live_authentic = self.replies[self.live_authentic_replay_index] + live_repeated = self.replies[self.live_repeated_replay_index] + live_victim_issued = self.replies[self.live_victim_issued_index] + self.require((live_donor_commit["capability_validated_apply_index"], + live_donor_commit["capability_root_generation"]) != + (live_victim_commit["capability_validated_apply_index"], + live_victim_commit["capability_root_generation"]), + "live_same_generation_donor_victim_capabilities_are_distinct", + {"donor": live_donor_commit, "victim": live_victim_commit}) + victim_before = next(op for op in live_donor_commit["state"]["operations"] + if op["operation_id"] == "victim") + victim_after = next(op for op in live_borrowed["state"]["operations"] + if op["operation_id"] == "victim") + self.require(live_donor_commit["state"] == live_borrowed["state"] and + live_donor_commit["capabilities"] == live_borrowed["capabilities"] and + victim_before == victim_after and + live_borrowed["receipt"] != live_victim_commit["receipt"], + "live_cross_operation_capability_cannot_replay_or_mutate_final", + {"original": live_victim_commit, "rejected": live_borrowed}) + for replay in (live_authentic, live_repeated): + self.require(replay["receipt"] == live_victim_commit["receipt"] and + replay["capability_validated_apply_index"] == + live_victim_issued["capability_validated_apply_index"], + "live_original_lookup_capability_replays_original_receipt_repeatedly", + {"original": live_victim_commit, "replay": replay}) + + donor_commit = self.replies[self.donor_commit_index] + victim_commit = self.replies[self.victim_commit_index] + victim_issued = self.replies[self.victim_issued_index] + borrowed_commit = self.replies[self.borrowed_commit_index] + authentic_replay = self.replies[self.authentic_victim_replay_index] + reversed_commit = self.replies[self.reversed_commit_index] + self.require((donor_commit["capability_validated_apply_index"], + donor_commit["capability_root_generation"]) != + (victim_commit["capability_validated_apply_index"], + victim_commit["capability_root_generation"]), + "same_path_donor_victim_capabilities_are_distinct", + {"donor": donor_commit, "victim": victim_commit}) + self.require(victim_commit["receipt"] == authentic_replay["receipt"], + "authentic_same_operation_history_replays_original_receipt", + {"original": victim_commit, "replay": authentic_replay}) + self.require(victim_issued["capability_validated_apply_index"] == + authentic_replay["capability_validated_apply_index"] and + victim_issued["capability_root_generation"] == + authentic_replay["capability_root_generation"], + "authentic_replay_echoes_only_victim_capability", + {"original": victim_issued, "replay": authentic_replay}) + for operation_id, original, rejected in ( + ("victim", victim_commit, borrowed_commit), + ("donor", donor_commit, reversed_commit)): + before = next(op for op in original["state"]["operations"] + if op["operation_id"] == operation_id) + after = next(op for op in rejected["state"]["operations"] + if op["operation_id"] == operation_id) + self.require(before == after and rejected["receipt"] != original["receipt"], + "cross_operation_capability_cannot_replay_or_mutate_final", + {"original": original, "rejected": rejected}, + {"operation_id": operation_id}) + + original_commit = self.replies[self.generation_commit_index] + replayed_commit = self.replies[self.generation_commit_replay_index] + self.require(original_commit["receipt"] == replayed_commit["receipt"], + "stale_root_replay_returns_original_receipt", + {"original": original_commit, "replay": replayed_commit}) + original_operation = next(op for op in original_commit["state"]["operations"] + if op["operation_id"] == "replay") + replayed_lookup = self.replies[self.generation_lookup_replay_index] + lookup_operation = next(op for op in replayed_lookup["state"]["operations"] + if op["operation_id"] == "replay") + self.require(original_operation == lookup_operation, + "stale_root_lookup_replays_original_operation", + {"original": original_operation, "replay": lookup_operation}) + forged_lookup = self.replies[self.generation_forged_lookup_replay_index] + forged_operation = next(op for op in forged_lookup["state"]["operations"] + if op["operation_id"] == "replay") + self.require(original_operation == forged_operation, + "unissued_capability_cannot_mutate_replayed_operation", + {"original": original_operation, "forged": forged_lookup}) + + for full_index, short_index in self.semantic_pairs: + full = self.replies[full_index] + short = self.replies[short_index] + for key in ("outcome", "logical_commit_applied", "billing", + "root_generation", "accepted_at_ms", "locked_ttl_ms", + "new_node_count", "path_digest", "receipt_digest"): + self.require(full["receipt"][key] == short["receipt"][key], + "full_short_receipt_semantics", + {"full": full, "short": short}, {"field": key}) + full_receipt = next(op for op in full["state"]["operations"] + if op["operation_id"] == "hot") + short_receipt = next(op for op in short["state"]["operations"] + if op["operation_id"] == "hot") + for key in ("canonical_path_digest", "complete_page_evidence_digest", + "read_root_generation", "read_root_locked_ttl_ms", "requested_ttl_ms"): + self.require(full_receipt[key] == short_receipt[key], + "full_short_token_semantics", + {"full": full_receipt, "short": short_receipt}, {"field": key}) + for key in ("root_generation", "data_epoch", "family_incarnation", "nodes"): + self.require(full["state"][key] == short["state"][key], + "full_short_side_effect_semantics", + {"full": full["state"], "short": short["state"]}, {"field": key}) + + for index, reply in enumerate(self.replies): + if reply["result"] == "invalid_evidence" and reply.get("fallback_required"): + for operation in reply["state"]["operations"]: + if operation["operation_id"] in ("invalid", "confused", "expired", "pruned", + "loaded", "stale", "coldshort"): + self.require(not operation["final"] or + operation["receipt"]["outcome"] != 16, + "fallback_has_no_counterfeit_final", reply) + rebuilt = next(op for op in self.replies[self.rebuilt_operation_index]["state"]["operations"] + if op["operation_id"] == "rebuilt") + self.require(rebuilt["receipt"]["outcome"] == 2, + "recreate_has_new_full_cycle", rebuilt) + + def summary(self): + return { + "schema": "cyclestore-capability-differential-v1", + "provider_binary": self.binary, + "events": len(self.replies), + "independent_assertions": self.checks, + "mismatches": len(self.errors), + "errors": self.errors, + "semantic_pair_comparisons": len(self.semantic_pairs), + "coverage": [ + "delta_zero_full_short_semantics", "exact_original_replay_restart", + "tip_incarnation_generation_epoch_ttl_page_family_bindings", + "side_lineage_parent_mismatch", "expired_root_new_generation", + "prune_gc_restart_snapshot_restore_recreate", "old_final_revocation", + "legacy_final_full_fallback_not_operation_conflict", + "optional_tail_recovery", "unknown_digest_fallback_without_counterfeit_final", + "duplicate_lookup_persisted_capability_origin_cached_and_recovered", + "late_final_capability_rejected_beyond_token_read_watermark", + "live_same_generation_cross_operation_origin_rejected_without_replacement", + "same_path_cross_operation_origin_rejected_after_generation_recovery", + ], + } + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--binary", required=True, type=Path) + parser.add_argument("--artifacts", required=True, type=Path) + args = parser.parse_args() + if args.artifacts.exists(): + print(f"artifact root already exists: {args.artifacts}", file=sys.stderr) + return 2 + oracle = Oracle(args.binary.resolve(), args.artifacts) + oracle.build() + oracle.run_all() + oracle.compare_semantics() + summary = oracle.summary() + summary["status"] = "PASS" if not oracle.errors else "FAIL" + (args.artifacts / "summary.json").write_text(json.dumps(summary, indent=2, sort_keys=True)) + print("CAPABILITY_DIFF_SUMMARY " + json.dumps(summary, sort_keys=True)) + return 0 if not oracle.errors else 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/test/cyclestore/fsm_diff_main.cc b/test/cyclestore/fsm_diff_main.cc index 5c9100f2..c2dc3abf 100644 --- a/test/cyclestore/fsm_diff_main.cc +++ b/test/cyclestore/fsm_diff_main.cc @@ -74,7 +74,8 @@ PathEvidenceRecord ParsePath(const std::string& input, const Bytes& root) { return path; } -std::unique_ptr OpenMachine(const fs::path& path, bool initialize) { +std::unique_ptr OpenMachine(const fs::path& path, bool initialize, + Store** raw_store = nullptr) { OpenStoreOptions options; options.path = path.string(); options.initialize_new = initialize; @@ -82,6 +83,7 @@ std::unique_ptr OpenMachine(const fs::path& path, bool initia std::unique_ptr store; StoreStatus status = Store::Open(options, &store); if (!status.ok()) throw std::runtime_error(status.detail); + if (raw_store != nullptr) *raw_store = store.get(); std::unique_ptr machine; status = CycleStateMachine::Open(std::move(store), FsmConfig{}, &machine); if (!status.ok()) throw std::runtime_error(status.detail); @@ -92,10 +94,14 @@ FamilyKey TestFamily() { return FamilyKey{"scope", "domain", {'r', 'o', 'o', 't' struct Case { Case(const fs::path& root, std::string name, std::size_t ordinal) - : path(root / (std::to_string(ordinal) + "-" + name)), machine(OpenMachine(path, true)) {} + : path(root / (std::to_string(ordinal) + "-" + name)), + machine(OpenMachine(path, true, &store)) {} fs::path path; + fs::path checkpoint_path; + Store* store = nullptr; std::unique_ptr machine; std::map tokens; + std::map capabilities; std::uint64_t next_apply_index = 1; }; @@ -154,6 +160,9 @@ std::string TokenJson(const FsmOperationProjection& operation) { std::ostringstream out; out << "{\"operation_id\":" << Quote(token.operation_id) << ",\"has_issued_token\":" << (operation.has_issued_token ? "true" : "false") + << ",\"canonical_path_digest\":" << Quote(HexArray(token.canonical_path_digest)) + << ",\"complete_page_evidence_digest\":" << Quote(HexArray(token.complete_page_evidence_digest)) + << ",\"commit_input_semantic_v2\":" << (operation.record.commit_input_semantic_v2 ? "true" : "false") << ",\"token_expired\":" << (operation.record.token_expired ? "true" : "false") << ",\"token_apply_index\":" << operation.record.token_apply_index << ",\"receipt_gc_at_ms\":" << operation.record.receipt_gc_at_ms @@ -235,6 +244,51 @@ std::string Reply(const std::string& result, std::int64_t alive, bool include_re return out.str(); } +std::string CapabilityListJson(const CycleStateMachine& machine) { + std::ostringstream out; + out << "["; + bool first = true; + for (const auto& [key, capability] : machine.CapabilitiesForTest()) { + if (!first) out << ","; + first = false; + out << "{\"root_generation\":" << capability.root_generation + << ",\"data_epoch\":" << capability.data_epoch + << ",\"family_incarnation\":" << capability.family_incarnation + << ",\"locked_ttl_ms\":" << TtlMs(capability.root_locked_ttl) + << ",\"tip_node_id\":" << Quote(HexArray(capability.expected_tip.node_id)) + << ",\"tip_incarnation\":" << Quote(HexArray(capability.expected_tip.node_incarnation)) + << ",\"tip_depth\":" << capability.expected_tip.depth + << ",\"canonical_path_digest\":" << Quote(HexArray(capability.canonical_path_digest)) + << ",\"complete_page_evidence_digest\":" << Quote(HexArray(capability.complete_page_evidence_digest)) + << ",\"validated_apply_index\":" << capability.validated_apply_index + << ",\"page_count\":" << capability.page_count << "}"; + } + out << "]"; + return out.str(); +} + +std::string CapabilityReply(const std::string& result, bool replayed, bool fallback, + const std::optional& capability, + const CommitReceiptRecord* receipt, + const CycleStateMachine& machine) { + std::ostringstream out; + out << "{\"result\":" << Quote(result) + << ",\"alive_depth\":-2" + << ",\"receipt_replayed\":" << (replayed ? "true" : "false") + << ",\"fallback_required\":" << (fallback ? "true" : "false") + << ",\"has_capability\":" << (capability.has_value() ? "true" : "false") + << ",\"capability_validated_apply_index\":" + << (capability.has_value() ? std::to_string(capability->validated_apply_index) : "0") + << ",\"capability_root_generation\":" + << (capability.has_value() ? std::to_string(capability->root_generation) : "0") + << ",\"receipt\":"; + if (receipt != nullptr) out << ReceiptJson(*receipt); + else out << "null"; + out << ",\"capabilities\":" << CapabilityListJson(machine) + << ",\"state\":" << StateJson(machine.ProjectionForTest(TestFamily())) << "}"; + return out.str(); +} + TtlClass ParseTtl(std::uint64_t ttl_ms) { if (ttl_ms == 300000) return TtlClass::k5m; if (ttl_ms == 3600000) return TtlClass::k1h; @@ -256,6 +310,9 @@ int Run() { input >> name; if (name.empty()) throw std::runtime_error("CASE requires a name"); current = std::make_unique(workspace.path, name, case_ordinal++); + current->tokens.clear(); + current->capabilities.clear(); + current->checkpoint_path.clear(); std::cout << Reply("case", -2, false, {}, current->machine->ProjectionForTest(TestFamily())) << std::endl; continue; } @@ -279,6 +336,8 @@ int Run() { LookupResult result = replay ? current->machine->ReadLookup(command) : current->machine->IssueLookup(command); if (result.result == FsmResult::kOk && result.has_token) current->tokens[operation] = result.token; + if (result.evidence_capability.has_value()) + current->capabilities[operation] = *result.evidence_capability; if (result.result == FsmResult::kOk && !replay) ++current->next_apply_index; const std::int64_t projected_alive = result.has_token || result.result == FsmResult::kOk ? result.alive_depth : -2; @@ -317,10 +376,176 @@ int Run() { command.term = 7; command.accepted_at_ms = accepted; const CommitResult result = current->machine->ApplyCommit(command); + if (result.result == FsmResult::kUnavailable) + throw std::runtime_error(result.detail + "; " + current->machine->LastErrorForTest()); + if (result.evidence_capability.has_value()) + current->capabilities[operation] = *result.evidence_capability; if (result.result != FsmResult::kClockUnavailable) ++current->next_apply_index; - std::cout << Reply(FsmResultName(result.result), -2, true, result.receipt, - current->machine->ProjectionForTest(token->second.family), - result.receipt_replayed) << std::endl; + std::cout << CapabilityReply(FsmResultName(result.result), result.receipt_replayed, + result.evidence_fallback_required, + result.evidence_capability, &result.receipt, + *current->machine) << std::endl; + continue; + } + if (verb == "CAP_LOOKUP") { + std::string operation, reference; + std::uint64_t ttl = 0, duplicate = 0; + std::int64_t now = 0; + input >> operation >> reference >> ttl >> now >> duplicate; + const auto capability = current->capabilities.find(reference); + if (capability == current->capabilities.end()) + throw std::runtime_error("unknown capability_ref: " + reference); + LookupCommand command; + command.family = TestFamily(); + command.operation_id = operation; + command.evidence_capability = capability->second; + command.requested_ttl = ParseTtl(ttl); + command.apply_index = current->next_apply_index; + command.term = 7; + command.issued_at_ms = now; + const bool replay = duplicate != 0 && current->tokens.count(operation) != 0; + const LookupResult result = replay ? current->machine->ReadLookup(command) + : current->machine->IssueLookup(command); + if (result.result == FsmResult::kOk && result.has_token) + current->tokens[operation] = result.token; + if (result.evidence_capability.has_value()) + current->capabilities[operation] = *result.evidence_capability; + if (result.result == FsmResult::kOk && !replay) ++current->next_apply_index; + std::cout << CapabilityReply(FsmResultName(result.result), false, + result.evidence_fallback_required, + result.evidence_capability, nullptr, + *current->machine) << std::endl; + continue; + } + if (verb == "CAP_COMMIT") { + std::string operation, reference, token_reference; + std::uint64_t prefill = 0; + std::int64_t accepted = 0; + input >> operation >> reference >> token_reference >> prefill >> accepted; + const auto capability = current->capabilities.find(reference); + const auto token = current->tokens.find(token_reference); + if (capability == current->capabilities.end() || token == current->tokens.end()) + throw std::runtime_error("unknown capability or token reference"); + CommitCommand command; + command.canonical_lookup_token = EncodeLookupToken(token->second); + command.evidence_capability = capability->second; + command.prefill_completed_at_ms = prefill; + command.apply_index = current->next_apply_index; + command.term = 7; + command.accepted_at_ms = accepted; + const CommitResult result = current->machine->ApplyCommit(command); + if (result.evidence_capability.has_value()) + current->capabilities[operation] = *result.evidence_capability; + if (result.result != FsmResult::kClockUnavailable) + current->next_apply_index = current->machine->MetaForTest().last_applied_index + 1; + std::cout << CapabilityReply(FsmResultName(result.result), result.receipt_replayed, + result.evidence_fallback_required, + result.evidence_capability, &result.receipt, + *current->machine) << std::endl; + continue; + } + if (verb == "CAP_MUTATE") { + std::string reference, field; + input >> reference >> field; + auto capability = current->capabilities.find(reference); + if (capability == current->capabilities.end()) + throw std::runtime_error("unknown capability mutation"); + auto& value = capability->second; + if (field == "canonical_path_digest") value.canonical_path_digest[0] ^= 1; + else if (field == "complete_page_evidence_digest") value.complete_page_evidence_digest[0] ^= 1; + else if (field == "tip_incarnation") value.expected_tip.node_incarnation[0] ^= 1; + else if (field == "root_generation") ++value.root_generation; + else if (field == "data_epoch") ++value.data_epoch; + else if (field == "family_incarnation") ++value.family_incarnation; + else if (field == "root_locked_ttl") value.root_locked_ttl = TtlClass::k1h; + else if (field == "validated_apply_index") --value.validated_apply_index; + else if (field == "future_apply_index") value.validated_apply_index = ~std::uint64_t{}; + else if (field == "page_count") ++value.page_count; + else if (field == "tip_page_hash") value.expected_tip.page_hash[0] ^= 1; + else if (field == "family") value.family.scope_id = "other"; + else throw std::runtime_error("unknown capability mutation field"); + std::cout << CapabilityReply("capability_mutated", false, false, std::nullopt, + nullptr, *current->machine) << std::endl; + continue; + } + if (verb == "CAP_SWAP_TIP") { + std::string reference, source; + input >> reference >> source; + auto& first = current->capabilities.at(reference); + first.expected_tip = current->capabilities.at(source).expected_tip; + std::cout << CapabilityReply("capability_tip_swapped", false, false, std::nullopt, + nullptr, *current->machine) << std::endl; + continue; + } + if (verb == "CAP_MARK_LEGACY") { + std::string operation, path; + std::uint64_t prefill = 0; + input >> operation >> path >> prefill; + auto projection = current->machine->ProjectionForTest(TestFamily()); + OperationRecord* operation_record = nullptr; + for (auto& candidate : projection.operations) { + if (candidate.has_issued_token && candidate.token.operation_id == operation) + operation_record = &candidate.record; + } + if (operation_record == nullptr) throw std::runtime_error("legacy operation not found"); + const auto legacy = ComputeCommitInputDigest( + operation_record->canonical_lookup_token_payload, + ParsePath(path, TestFamily().family_root_hash), prefill); + if (!legacy) throw std::runtime_error("legacy identity encoding failed"); + operation_record->commit_input_digest = *legacy; + operation_record->commit_input_semantic_v2 = false; + JournalEntry rewrite; + rewrite.apply_index = current->next_apply_index++; + rewrite.term = 7; + rewrite.command_ordinal = 1; + rewrite.mutations.push_back({RecordKind::kOperation, + EncodeOperationRecordKey(OperationRecordKey{TestFamily(), operation}), false, + EncodeOperationRecord(*operation_record)}); + const StoreStatus status = current->store->ApplyLocalBatch(rewrite); + if (!status.ok()) throw std::runtime_error(status.detail); + std::cout << CapabilityReply("legacy_marked", false, false, std::nullopt, + nullptr, *current->machine) << std::endl; + continue; + } + if (verb == "CAP_ALIAS") { + std::string alias, reference; + input >> alias >> reference; + const auto capability = current->capabilities.find(reference); + if (alias.empty() || capability == current->capabilities.end()) + throw std::runtime_error("unknown capability alias reference: " + reference); + current->capabilities[alias] = capability->second; + std::cout << CapabilityReply("capability_aliased", false, false, capability->second, + nullptr, *current->machine) << std::endl; + continue; + } + if (verb == "CAP_HISTORY") { + std::string operation, reference; + input >> operation >> reference; + const auto capability = current->capabilities.find(reference); + if (capability == current->capabilities.end()) + throw std::runtime_error("unknown capability_ref: " + reference); + const auto projection = current->machine->ProjectionForTest(TestFamily()); + const OperationRecord* operation_record = nullptr; + for (const auto& candidate : projection.operations) { + if (candidate.has_issued_token && candidate.token.operation_id == operation) { + operation_record = &candidate.record; + break; + } + } + if (operation_record == nullptr) + throw std::runtime_error("capability-history operation not found: " + operation); + const Bytes encoding = EncodeEvidenceCapability(capability->second); + const bool present = !encoding.empty() && + (operation_record->issued_capability_encoding == encoding || + operation_record->final_capability_encoding == encoding); + std::cout << CapabilityReply(present ? "capability_in_history" : "capability_not_in_history", + false, false, std::nullopt, nullptr, + *current->machine) << std::endl; + continue; + } + if (verb == "CAP_STATE") { + std::cout << CapabilityReply("capability_state", false, false, std::nullopt, + nullptr, *current->machine) << std::endl; continue; } if (verb == "EPOCH") { @@ -355,8 +580,8 @@ int Run() { const std::string detail = current->machine->LastErrorForTest(); throw std::runtime_error("GC failed: " + (detail.empty() ? std::string("record validation failed") : detail)); } - std::cout << Reply(FsmResultName(result), -2, false, {}, - current->machine->ProjectionForTest(TestFamily())) << std::endl; + std::cout << CapabilityReply(FsmResultName(result), false, false, std::nullopt, + nullptr, *current->machine) << std::endl; continue; } if (verb == "CLOCK") { @@ -381,15 +606,16 @@ int Run() { } if (verb == "RECOVER") { current->machine.reset(); - current->machine = OpenMachine(current->path, false); - std::cout << Reply("recovered", -2, false, {}, - current->machine->ProjectionForTest(TestFamily())) << std::endl; + current->machine = OpenMachine(current->path, false, ¤t->store); + std::cout << CapabilityReply("recovered", false, false, std::nullopt, nullptr, + *current->machine) << std::endl; continue; } if (verb == "CHECKPOINT") { CheckpointInfo info; const fs::path destination = current->path.parent_path() / (current->path.filename().string() + "-checkpoint-" + std::to_string(current->next_apply_index)); + current->checkpoint_path = destination; StoreStatus status = current->machine->CheckpointForTest(destination.string(), &info); if (!status.ok()) throw std::runtime_error(status.detail); auto checkpoint_machine = OpenMachine(destination, false); @@ -398,6 +624,20 @@ int Run() { std::cout << Reply("checkpoint", -2, false, {}, std::move(projection)) << std::endl; continue; } + if (verb == "RESTORE") { + if (current->checkpoint_path.empty()) throw std::runtime_error("RESTORE requires CHECKPOINT"); + const fs::path destination = current->path.parent_path() / + (current->path.filename().string() + "-restore-" + std::to_string(current->next_apply_index)); + fs::copy(current->checkpoint_path, destination, + fs::copy_options::recursive | fs::copy_options::overwrite_existing); + current->machine.reset(); + current->path = destination; + current->machine = OpenMachine(current->path, false, ¤t->store); + current->next_apply_index = current->machine->MetaForTest().last_applied_index + 1; + std::cout << CapabilityReply("restored", false, false, std::nullopt, nullptr, + *current->machine) << std::endl; + continue; + } throw std::runtime_error("unknown command: " + verb); } return 0; diff --git a/test/cyclestore/fsm_test.cc b/test/cyclestore/fsm_test.cc index 4ff40254..1b8eaf71 100644 --- a/test/cyclestore/fsm_test.cc +++ b/test/cyclestore/fsm_test.cc @@ -110,6 +110,50 @@ struct Fixture { next_index = machine->MetaForTest().last_applied_index + 1; return result; } + LookupResult LookupCapability(const std::string& operation, + const EvidenceCapabilityRecord& capability, + std::int64_t now, TtlClass ttl = TtlClass::k5m) { + LookupCommand command; + command.family = capability.family; + command.operation_id = operation; + command.evidence_capability = capability; + command.requested_ttl = ttl; + command.apply_index = next_index; + command.term = 7; + command.issued_at_ms = now; + LookupResult result = machine->IssueLookup(command); + next_index = machine->MetaForTest().last_applied_index + 1; + return result; + } + LookupResult ReadCapability(const std::string& operation, + const EvidenceCapabilityRecord& capability, + std::int64_t now, TtlClass ttl = TtlClass::k5m) { + LookupCommand command; + command.family = capability.family; + command.operation_id = operation; + command.evidence_capability = capability; + command.requested_ttl = ttl; + command.apply_index = next_index; + command.term = 7; + command.issued_at_ms = now; + command.linearizable = true; + command.leader_known = true; + return machine->ReadLookup(command); + } + CommitResult CommitCapability(const LookupToken& token, + const EvidenceCapabilityRecord& capability, + std::uint64_t prefill, std::int64_t accepted) { + CommitCommand command; + command.canonical_lookup_token = EncodeLookupToken(token); + command.evidence_capability = capability; + command.prefill_completed_at_ms = prefill; + command.apply_index = next_index; + command.term = 7; + command.accepted_at_ms = accepted; + CommitResult result = machine->ApplyCommit(command); + next_index = machine->MetaForTest().last_applied_index + 1; + return result; + } FsmResult Collect(std::int64_t now, bool drop = false) { GcCommand command; command.family = TestFamily(); @@ -277,6 +321,40 @@ void TestDeadlinesNegativeReceiptAndMutationFence() { CHECK(original.receipt.apply_index == 2); } +void TestMalformedFullReplayCannotReplaceFinalReceipt() { + Fixture fixture; + const auto path = Path({"root", "a"}); + const auto lookup = fixture.Lookup("full-final-conflict", path, 0); + REQUIRE(lookup.result == FsmResult::kOk); + const auto original = fixture.Commit(lookup.token, path, 0, 0); + REQUIRE(original.result == FsmResult::kRootCycleCreated); + + PathEvidenceRecord wrong_root = path; + wrong_root.pages.front().page_hash = Label("wrong-root"); + PathEvidenceRecord non_contiguous = path; + non_contiguous.pages.back().depth = 7; + const PathEvidenceRecord* malformed_inputs[] = {nullptr, &wrong_root, &non_contiguous}; + for (const PathEvidenceRecord* malformed : malformed_inputs) { + const PathEvidenceRecord empty; + const PathEvidenceRecord& input = malformed == nullptr ? empty : *malformed; + const auto conflict = fixture.Commit(lookup.token, input, 0, 700000); + CHECK(conflict.result == FsmResult::kOperationIdConflict); + CHECK(!conflict.receipt_replayed); + CHECK(!conflict.evidence_fallback_required); + bool found = false; + const auto durable = fixture.machine->ReceiptForTest( + TestFamily(), "full-final-conflict", &found); + REQUIRE(found); + CHECK(durable.receipt_digest == original.receipt.receipt_digest); + CHECK(durable.logical_commit_applied); + const auto replay = fixture.Commit(lookup.token, path, 0, 700001); + CHECK(replay.result == FsmResult::kRootCycleCreated); + CHECK(replay.receipt_replayed); + CHECK(replay.receipt.receipt_digest == original.receipt.receipt_digest); + } + CHECK(fixture.machine->ValidateInvariantsForTest()); +} + void TestIllegalPrefillProducesStableFinal() { Fixture fixture; const auto path = Path({"root", "a"}); @@ -785,6 +863,458 @@ void TestFamilyDropRejectsOldIncarnation() { CHECK(fixture.machine->ValidateInvariantsForTest()); } +void TestCapabilityHotReuseReplayAndRecovery() { + Fixture fixture; + const auto path = Path({"root", "a"}); + const auto cold = fixture.Lookup("cap-cold", path, 0); + REQUIRE(cold.result == FsmResult::kOk); + const auto cold_commit = fixture.Commit(cold.token, path, 0, 0); + REQUIRE(cold_commit.result == FsmResult::kRootCycleCreated); + REQUIRE(cold_commit.evidence_capability.has_value()); + const auto capability = *cold_commit.evidence_capability; + + const auto hot = fixture.LookupCapability("cap-hot", capability, 1000); + REQUIRE(hot.result == FsmResult::kOk); + CHECK(hot.token.canonical_path_digest == cold.token.canonical_path_digest); + CHECK(hot.token.complete_page_evidence_digest == + cold.token.complete_page_evidence_digest); + const auto renewed = fixture.CommitCapability(hot.token, capability, 1000, 1000); + REQUIRE(renewed.result == FsmResult::kRenewed); + CHECK(renewed.receipt.new_node_count == 0); + REQUIRE(renewed.evidence_capability.has_value()); + const auto duplicate = fixture.LookupCapability("cap-hot", capability, 1001); + REQUIRE(duplicate.result == FsmResult::kOk); + CHECK(EncodeLookupToken(duplicate.token) == EncodeLookupToken(hot.token)); + const auto replay = fixture.CommitCapability(hot.token, capability, 1000, 2000); + CHECK(replay.receipt_replayed); + CHECK(replay.receipt.receipt_digest == renewed.receipt.receipt_digest); + const auto repeated_replay = fixture.CommitCapability(hot.token, capability, 1000, 2001); + CHECK(repeated_replay.receipt_replayed); + CHECK(repeated_replay.receipt.receipt_digest == renewed.receipt.receipt_digest); + + fixture.Restart(); + const auto recovered_replay = fixture.CommitCapability(hot.token, capability, 1000, 2001); + REQUIRE(recovered_replay.receipt_replayed); + CHECK(recovered_replay.receipt.receipt_digest == renewed.receipt.receipt_digest); + const auto recovered = fixture.LookupCapability("cap-recovered", + *renewed.evidence_capability, 2000); + REQUIRE(recovered.result == FsmResult::kOk); + const auto recovered_commit = fixture.CommitCapability( + recovered.token, *renewed.evidence_capability, 2000, 2000); + CHECK(recovered_commit.result == FsmResult::kRenewed); + CheckpointInfo checkpoint; + REQUIRE(StoreOk(fixture.machine->CheckpointForTest( + (fixture.temp.path / "capability-checkpoint").string(), &checkpoint))); + REQUIRE(StoreOk(Store::VerifyCheckpoint( + (fixture.temp.path / "capability-checkpoint").string(), checkpoint))); + const auto refreshed_full = fixture.Lookup("cap-hot-later-full", path, 3000); + REQUIRE(refreshed_full.result == FsmResult::kOk); + const auto replay_after_refresh = fixture.CommitCapability( + hot.token, capability, 1000, 3000); + CHECK(replay_after_refresh.receipt_replayed); + CHECK(replay_after_refresh.receipt.receipt_digest == renewed.receipt.receipt_digest); + const auto changed_replay = fixture.CommitCapability( + hot.token, capability, 1001, 3001); + CHECK(changed_replay.result == FsmResult::kOperationIdConflict); + CHECK(fixture.machine->ValidateInvariantsForTest()); + +} + +void TestCapabilityLateFinalWatermarkOrigin() { + Fixture fixture; + const auto path = Path({"root", "a"}); + const auto late_cold = fixture.Lookup("late-cap-cold", path, 0); + REQUIRE(late_cold.result == FsmResult::kOk); + REQUIRE(fixture.Commit(late_cold.token, path, 0, 0).result == + FsmResult::kRootCycleCreated); + const auto late_hot = fixture.Lookup("late-cap-hot", path, 1000); + REQUIRE(late_hot.result == FsmResult::kOk); + REQUIRE(late_hot.evidence_capability.has_value()); + const auto original_hot_capability = *late_hot.evidence_capability; + const auto late_commit = fixture.Commit(late_hot.token, path, 1000, 1000); + REQUIRE(late_commit.result == FsmResult::kRenewed); + REQUIRE(late_commit.evidence_capability.has_value()); + REQUIRE(late_commit.evidence_capability->validated_apply_index > + late_hot.token.read_apply_index); + const auto late_replay = fixture.CommitCapability( + late_hot.token, *late_commit.evidence_capability, 1000, 2000); + CHECK(late_replay.result == FsmResult::kInvalidEvidence); + CHECK(late_replay.evidence_fallback_required); + CHECK(!late_replay.receipt_replayed); + CHECK(!late_replay.evidence_capability.has_value()); + CHECK(late_replay.receipt.receipt_digest != late_commit.receipt.receipt_digest); + const auto original_replay = fixture.CommitCapability( + late_hot.token, original_hot_capability, 1000, 2000); + REQUIRE(original_replay.receipt_replayed); + CHECK(original_replay.receipt.receipt_digest == late_commit.receipt.receipt_digest); + const auto repeated_original_replay = fixture.CommitCapability( + late_hot.token, original_hot_capability, 1000, 2001); + REQUIRE(repeated_original_replay.receipt_replayed); + CHECK(repeated_original_replay.receipt.receipt_digest == late_commit.receipt.receipt_digest); + CHECK(fixture.machine->ValidateInvariantsForTest()); +} + +void TestCapabilityRejectsForgeryAndStaleGeneration() { + Fixture fixture; + const auto path = Path({"root", "a"}); + const auto initial = fixture.Lookup("cap-forgery-cold", path, 0); + const auto initial_commit = fixture.Commit(initial.token, path, 0, 0); + REQUIRE(initial_commit.evidence_capability.has_value()); + const auto original = *initial_commit.evidence_capability; + + auto forged = original; + forged.validated_apply_index -= 1; + CHECK(fixture.LookupCapability("old-validation-point", forged, 1000) + .evidence_fallback_required); + forged = original; + forged.expected_tip.node_incarnation[0] ^= 1; + CHECK(fixture.LookupCapability("old-incarnation", forged, 1000) + .evidence_fallback_required); + forged = original; + forged.canonical_path_digest[0] ^= 1; + CHECK(fixture.LookupCapability("unknown-digest", forged, 1000) + .evidence_fallback_required); + forged = original; + forged.family.cache_domain_id = "other-domain"; + CHECK(fixture.LookupCapability("other-family", forged, 1000) + .evidence_fallback_required); + forged = original; + forged.root_locked_ttl = TtlClass::k1h; + CHECK(fixture.LookupCapability("wrong-ttl", forged, 1000) + .evidence_fallback_required); + + CHECK(fixture.LookupCapability("expired-capability", original, 301000) + .evidence_fallback_required); + const auto next = fixture.Lookup("cap-next-root", path, 301000); + REQUIRE(next.result == FsmResult::kOk); + REQUIRE(next.evidence_capability.has_value()); + const auto replay_capability = *next.evidence_capability; + const auto next_commit = fixture.Commit(next.token, path, 301000, 301000); + REQUIRE(next_commit.result == FsmResult::kRootCycleCreated); + CHECK(next_commit.receipt.new_node_count == 0); + REQUIRE(next_commit.evidence_capability.has_value()); + CHECK(next_commit.evidence_capability->root_generation == 2); + CHECK(fixture.LookupCapability("old-root-generation", original, 302000) + .evidence_fallback_required); + const auto old_commit = fixture.CommitCapability(next.token, replay_capability, 301000, 302000); + REQUIRE(old_commit.receipt_replayed); + CHECK(old_commit.result == next_commit.result); + CHECK(old_commit.receipt.receipt_digest == next_commit.receipt.receipt_digest); + CHECK(old_commit.receipt.accepted_at_ms == next_commit.receipt.accepted_at_ms); + CHECK(old_commit.receipt.apply_index == next_commit.receipt.apply_index); + CHECK(!old_commit.evidence_fallback_required); + const auto old_lookup = fixture.ReadCapability("cap-next-root", replay_capability, 302000); + REQUIRE(old_lookup.result == FsmResult::kOk); + CHECK(EncodeLookupToken(old_lookup.token) == EncodeLookupToken(next.token)); + REQUIRE(old_lookup.evidence_capability.has_value()); + CHECK(SameEvidenceCapability(*old_lookup.evidence_capability, replay_capability)); + CHECK(!old_lookup.evidence_fallback_required); + + auto changed_read = replay_capability; + --changed_read.validated_apply_index; + const auto forged_cached_lookup = fixture.ReadCapability( + "cap-next-root", changed_read, 302000); + CHECK(forged_cached_lookup.result == FsmResult::kInvalidEvidence); + CHECK(forged_cached_lookup.evidence_fallback_required); + CHECK(!forged_cached_lookup.has_token); + CHECK(!forged_cached_lookup.evidence_capability.has_value()); + + fixture.Restart(); + const auto recovered_old_lookup = fixture.ReadCapability( + "cap-next-root", replay_capability, 302000); + REQUIRE(recovered_old_lookup.result == FsmResult::kOk); + CHECK(EncodeLookupToken(recovered_old_lookup.token) == EncodeLookupToken(next.token)); + REQUIRE(recovered_old_lookup.evidence_capability.has_value()); + CHECK(SameEvidenceCapability(*recovered_old_lookup.evidence_capability, replay_capability)); + const auto forged_recovered_lookup = fixture.ReadCapability( + "cap-next-root", changed_read, 302000); + CHECK(forged_recovered_lookup.result == FsmResult::kInvalidEvidence); + CHECK(forged_recovered_lookup.evidence_fallback_required); + CHECK(!forged_recovered_lookup.has_token); + + auto changed_validation = original; + --changed_validation.validated_apply_index; + const auto bad_validation_replay = fixture.CommitCapability( + next.token, changed_validation, 301000, 302000); + CHECK(bad_validation_replay.result == FsmResult::kInvalidEvidence); + CHECK(bad_validation_replay.evidence_fallback_required); + CHECK(!bad_validation_replay.receipt_replayed); + const auto unchanged_validation_replay = fixture.CommitCapability( + next.token, replay_capability, 301000, 302001); + CHECK(unchanged_validation_replay.receipt_replayed); + CHECK(unchanged_validation_replay.receipt.receipt_digest == + next_commit.receipt.receipt_digest); + + auto wrong_digest = original; + wrong_digest.complete_page_evidence_digest[0] ^= 1; + const auto bad_replay = fixture.CommitCapability(next.token, wrong_digest, 301000, 302000); + CHECK(bad_replay.result == FsmResult::kInvalidEvidence); + CHECK(bad_replay.evidence_fallback_required); + CHECK(!bad_replay.receipt_replayed); + const auto bad_lookup = fixture.ReadCapability("cap-next-root", wrong_digest, 302000); + CHECK(bad_lookup.result == FsmResult::kInvalidEvidence); + CHECK(bad_lookup.evidence_fallback_required); + CHECK(!bad_lookup.has_token); + + const auto other_evidence = Path({"root", "b"}); + const auto other_path = fixture.Lookup("capability-other-path", other_evidence, 302000); + REQUIRE(other_path.result == FsmResult::kOk); + const auto other_commit = fixture.Commit(other_path.token, other_evidence, 302000, 302000); + REQUIRE(other_commit.evidence_capability.has_value()); + const auto crossed_replay = fixture.CommitCapability( + next.token, *other_commit.evidence_capability, 301000, 302000); + CHECK(crossed_replay.result == FsmResult::kOperationIdConflict); + CHECK(!crossed_replay.receipt_replayed); + const auto crossed_lookup = fixture.ReadCapability( + "cap-next-root", *other_commit.evidence_capability, 302000); + CHECK(crossed_lookup.result == FsmResult::kOperationIdConflict); + CHECK(!crossed_lookup.has_token); + + EpochCommand epoch; + epoch.expected_epoch = 1; + epoch.apply_index = fixture.next_index; + epoch.term = 7; + epoch.now_ms = 303000; + REQUIRE(fixture.machine->AdvanceDataEpoch(epoch) == FsmResult::kEpochAdvanced); + fixture.next_index = fixture.machine->MetaForTest().last_applied_index + 1; + CHECK(fixture.LookupCapability("old-data-epoch", *next_commit.evidence_capability, + 304000).evidence_fallback_required); +} + +void TestCapabilitySamePathCrossOperationOriginAfterRecovery() { + Fixture fixture; + const auto path = Path({"root", "a"}); + const auto bootstrap = fixture.Lookup("cap-origin-bootstrap", path, 0); + REQUIRE(bootstrap.result == FsmResult::kOk); + REQUIRE(fixture.Commit(bootstrap.token, path, 0, 0).result == FsmResult::kRootCycleCreated); + const auto victim = fixture.Lookup("cap-origin-victim", path, 1000); + REQUIRE(victim.result == FsmResult::kOk); + REQUIRE(victim.evidence_capability.has_value()); + const auto victim_capability = *victim.evidence_capability; + const auto victim_commit = fixture.Commit(victim.token, path, 1000, 1000); + REQUIRE(victim_commit.result == FsmResult::kRenewed); + REQUIRE(victim_commit.evidence_capability.has_value()); + + // Commit the donor last so its capability is the live persisted value; + // there is no replacement or stale-value rejection to mask FINAL origin. + const auto donor = fixture.Lookup("cap-origin-donor", path, 1000); + REQUIRE(donor.result == FsmResult::kOk); + const auto donor_commit = fixture.Commit(donor.token, path, 1000, 1000); + REQUIRE(donor_commit.result == FsmResult::kRenewed); + REQUIRE(donor_commit.evidence_capability.has_value()); + const auto donor_capability = *donor_commit.evidence_capability; + + const auto projection = fixture.machine->ProjectionForTest(TestFamily()); + const OperationRecord* donor_record = nullptr; + const OperationRecord* victim_record = nullptr; + for (const auto& candidate : projection.operations) { + if (!candidate.has_issued_token) continue; + if (candidate.token.operation_id == donor.token.operation_id) + donor_record = &candidate.record; + if (candidate.token.operation_id == victim.token.operation_id) + victim_record = &candidate.record; + } + REQUIRE(donor_record != nullptr); + REQUIRE(victim_record != nullptr); + REQUIRE(!donor_record->issued_capability_encoding.empty()); + REQUIRE(!donor_record->final_capability_encoding.empty()); + REQUIRE(!victim_record->issued_capability_encoding.empty()); + REQUIRE(!victim_record->final_capability_encoding.empty()); + const Bytes donor_encoding = EncodeEvidenceCapability(donor_capability); + const Bytes victim_encoding = EncodeEvidenceCapability(victim_capability); + REQUIRE(donor_encoding != victim_encoding); + REQUIRE(donor_record->issued_capability_encoding == donor_encoding || + donor_record->final_capability_encoding == donor_encoding); + REQUIRE(victim_record->issued_capability_encoding == victim_encoding || + victim_record->final_capability_encoding == victim_encoding); + REQUIRE(victim_record->issued_capability_encoding != donor_encoding && + victim_record->final_capability_encoding != donor_encoding); + REQUIRE(donor_record->issued_capability_encoding != victim_encoding && + donor_record->final_capability_encoding != victim_encoding); + + const auto live_borrowed = fixture.CommitCapability( + victim.token, donor_capability, 1000, 3000); + CHECK(live_borrowed.result == FsmResult::kInvalidEvidence); + CHECK(live_borrowed.evidence_fallback_required); + CHECK(!live_borrowed.receipt_replayed); + CHECK(!live_borrowed.evidence_capability.has_value()); + CHECK(live_borrowed.receipt.receipt_digest != victim_commit.receipt.receipt_digest); + const auto live_authentic = fixture.CommitCapability( + victim.token, victim_capability, 1000, 3001); + REQUIRE(live_authentic.receipt_replayed); + CHECK(live_authentic.receipt.receipt_digest == victim_commit.receipt.receipt_digest); + REQUIRE(live_authentic.evidence_capability.has_value()); + CHECK(SameEvidenceCapability(*live_authentic.evidence_capability, victim_capability)); + + const auto replacement = fixture.Lookup("cap-origin-replacement", path, 301000); + REQUIRE(replacement.result == FsmResult::kOk); + const auto replacement_commit = fixture.Commit(replacement.token, path, 301000, 301000); + REQUIRE(replacement_commit.result == FsmResult::kRootCycleCreated); + REQUIRE(replacement_commit.receipt.root_generation == 2); + fixture.Restart(); + + const auto borrowed = fixture.CommitCapability( + victim.token, donor_capability, 1000, 302000); + CHECK(borrowed.result == FsmResult::kInvalidEvidence); + CHECK(borrowed.evidence_fallback_required); + CHECK(!borrowed.receipt_replayed); + CHECK(!borrowed.evidence_capability.has_value()); + CHECK(borrowed.receipt.receipt_digest != victim_commit.receipt.receipt_digest); + + const auto authentic = fixture.CommitCapability( + victim.token, victim_capability, 1000, 302001); + REQUIRE(authentic.result == victim_commit.result); + CHECK(authentic.receipt_replayed); + CHECK(!authentic.evidence_fallback_required); + CHECK(authentic.receipt.receipt_digest == victim_commit.receipt.receipt_digest); + CHECK(authentic.receipt.accepted_at_ms == victim_commit.receipt.accepted_at_ms); + CHECK(authentic.receipt.apply_index == victim_commit.receipt.apply_index); + REQUIRE(authentic.evidence_capability.has_value()); + CHECK(SameEvidenceCapability(*authentic.evidence_capability, victim_capability)); + + const auto reversed = fixture.CommitCapability( + donor.token, victim_capability, 1000, 302002); + CHECK(reversed.result == FsmResult::kInvalidEvidence); + CHECK(reversed.evidence_fallback_required); + CHECK(!reversed.receipt_replayed); + CHECK(!reversed.evidence_capability.has_value()); + CHECK(reversed.receipt.receipt_digest != donor_commit.receipt.receipt_digest); + CHECK(fixture.machine->ValidateInvariantsForTest()); +} + +void TestCapabilityLegacyFinalRequiresFullReplay() { + Fixture fixture; + const auto path = Path({"root", "a"}); + const auto initial = fixture.Lookup("legacy-final", path, 0); + const auto initial_commit = fixture.Commit(initial.token, path, 0, 0); + REQUIRE(initial_commit.result == FsmResult::kRootCycleCreated); + REQUIRE(initial_commit.evidence_capability.has_value()); + const auto capability = *initial_commit.evidence_capability; + const auto legacy_digest = ComputeCommitInputDigest( + EncodeLookupToken(initial.token), path, 0); + REQUIRE(legacy_digest.has_value()); + auto projection = fixture.machine->ProjectionForTest(TestFamily()); + OperationRecord* operation = nullptr; + for (auto& candidate : projection.operations) { + if (candidate.has_issued_token && candidate.token.operation_id == "legacy-final") + operation = &candidate.record; + } + REQUIRE(operation != nullptr); + operation->commit_input_digest = *legacy_digest; + operation->commit_input_semantic_v2 = false; + operation->issued_capability_encoding.clear(); + operation->final_capability_encoding.clear(); + JournalEntry rewrite; + rewrite.apply_index = fixture.next_index; + rewrite.term = 7; + rewrite.command_ordinal = 1; + rewrite.mutations.push_back({RecordKind::kOperation, + EncodeOperationRecordKey(OperationRecordKey{TestFamily(), "legacy-final"}), + false, EncodeOperationRecord(*operation)}); + REQUIRE(StoreOk(fixture.fault_store->ApplyLocalBatch(rewrite))); + fixture.Restart(); + const auto legacy_short_read = fixture.ReadCapability("legacy-final", capability, 1000); + CHECK(legacy_short_read.result == FsmResult::kInvalidEvidence); + CHECK(legacy_short_read.evidence_fallback_required); + CHECK(!legacy_short_read.has_token); + const auto legacy_full_read = fixture.Read("legacy-final", path, 1000); + REQUIRE(legacy_full_read.result == FsmResult::kOk); + CHECK(EncodeLookupToken(legacy_full_read.token) == EncodeLookupToken(initial.token)); + const auto short_replay = fixture.CommitCapability(initial.token, capability, 0, 1000); + CHECK(short_replay.result == FsmResult::kInvalidEvidence); + CHECK(short_replay.evidence_fallback_required); + CHECK(!short_replay.receipt_replayed); + const auto full_replay = fixture.Commit(initial.token, path, 0, 1000); + REQUIRE(full_replay.receipt_replayed); + CHECK(full_replay.receipt.receipt_digest == initial_commit.receipt.receipt_digest); +} + +void TestCapabilityLineagePruneAndSideIsolation() { + Fixture fixture; + const auto ax = Path({"root", "a", "x"}); + const auto bx = Path({"root", "b", "x"}); + const auto by = Path({"root", "b", "y"}); + const auto first = fixture.Lookup("lineage-a", ax, 0); + REQUIRE(fixture.Commit(first.token, ax, 0, 0).result == FsmResult::kRootCycleCreated); + const auto a_cap_lookup = fixture.Lookup("lineage-a-known", ax, 1000); + const auto a_cap_commit = fixture.Commit(a_cap_lookup.token, ax, 1000, 1000); + REQUIRE(a_cap_commit.evidence_capability.has_value()); + const auto a_capability = *a_cap_commit.evidence_capability; + + const auto wrong_lineage = fixture.Lookup("lineage-b-same-x", bx, 1000); + CHECK(wrong_lineage.result == FsmResult::kEvidenceConflict); + CHECK(!wrong_lineage.evidence_capability.has_value()); + const auto side = fixture.Lookup("lineage-b-y", by, 1000); + const auto side_commit = fixture.Commit(side.token, by, 1000, 1000); + REQUIRE(side_commit.evidence_capability.has_value()); + auto confused = a_capability; + confused.expected_tip = side_commit.evidence_capability->expected_tip; + CHECK(fixture.LookupCapability("cross-side-tip", confused, 2000) + .evidence_fallback_required); + + REQUIRE(fixture.Collect(1000000) == FsmResult::kCollected); + std::vector stored_capabilities; + REQUIRE(StoreOk(fixture.fault_store->ScanRecords( + RecordKind::kEvidenceCapability, &stored_capabilities))); + CHECK(stored_capabilities.empty()); + CHECK(fixture.LookupCapability("pruned-a", a_capability, 1000001) + .evidence_fallback_required); + + // Restart before any same-hash rebuild: durable revocation, not merely the + // live map, must reject the old short path and prevent FINAL substitution. + fixture.Restart(); + stored_capabilities.clear(); + REQUIRE(StoreOk(fixture.fault_store->ScanRecords( + RecordKind::kEvidenceCapability, &stored_capabilities))); + CHECK(stored_capabilities.empty()); + CHECK(fixture.LookupCapability("pruned-a-after-restart", a_capability, 1000001) + .evidence_fallback_required); + CHECK(fixture.CommitCapability(a_cap_lookup.token, a_capability, 1000, 1000001) + .evidence_fallback_required); + bool old_final_found = true; + (void)fixture.machine->ReceiptForTest(TestFamily(), "lineage-a-known", &old_final_found); + CHECK(!old_final_found); + + CheckpointInfo pruned_checkpoint; + const fs::path checkpoint_path = fixture.temp.path / "pruned-capability-checkpoint"; + REQUIRE(StoreOk(fixture.machine->CheckpointForTest(checkpoint_path.string(), + &pruned_checkpoint))); + const fs::path loaded_path = fixture.temp.path / "pruned-capability-loaded"; + fs::copy(checkpoint_path, loaded_path, + fs::copy_options::recursive | fs::copy_options::overwrite_existing); + OpenStoreOptions loaded_options; + loaded_options.path = loaded_path.string(); + std::unique_ptr loaded_store; + REQUIRE(StoreOk(Store::Open(loaded_options, &loaded_store))); + std::unique_ptr loaded_machine; + REQUIRE(StoreOk(CycleStateMachine::Open(std::move(loaded_store), FsmConfig{}, + &loaded_machine))); + LookupCommand loaded_short; + loaded_short.family = TestFamily(); + loaded_short.operation_id = "pruned-a-after-snapshot-load"; + loaded_short.evidence_capability = a_capability; + loaded_short.requested_ttl = TtlClass::k5m; + loaded_short.issued_at_ms = 1000001; + loaded_short.apply_index = loaded_machine->MetaForTest().last_applied_index + 1; + loaded_short.term = 7; + CHECK(loaded_machine->IssueLookup(loaded_short).evidence_fallback_required); + old_final_found = true; + (void)loaded_machine->ReceiptForTest(TestFamily(), "lineage-a-known", &old_final_found); + CHECK(!old_final_found); + + const auto old_full_replay = fixture.Commit(a_cap_lookup.token, ax, 1000, 1000001); + CHECK(old_full_replay.result == FsmResult::kStaleLookupToken); + CHECK(!old_full_replay.receipt_replayed); + CHECK(old_full_replay.receipt.new_node_count == 0); + CHECK(!old_full_replay.receipt.logical_commit_applied); + const auto rebuilt = fixture.Lookup("rebuilt-a", ax, 1000001); + const auto rebuilt_commit = fixture.Commit(rebuilt.token, ax, 1000001, 1000001); + REQUIRE(rebuilt_commit.result == FsmResult::kRootCycleCreated); + CHECK(fixture.LookupCapability("late-old-capability", a_capability, 1000002) + .evidence_fallback_required); + CHECK(fixture.machine->ValidateInvariantsForTest()); +} + } // namespace } // namespace dfkv::cyclestore @@ -796,6 +1326,7 @@ int main() { test::suite.Case("BranchesLateRenewAndCreateRace", TestBranchesLateRenewAndCreateRace); test::suite.Case("TwoCreatorsOneWinner", TestTwoCreatorsOneWinner); test::suite.Case("DeadlinesNegativeReceiptAndMutationFence", TestDeadlinesNegativeReceiptAndMutationFence); + test::suite.Case("MalformedFullReplayCannotReplaceFinalReceipt", TestMalformedFullReplayCannotReplaceFinalReceipt); test::suite.Case("IllegalPrefillProducesStableFinal", TestIllegalPrefillProducesStableFinal); test::suite.Case("SameHashDifferentParentNeverBorrowsCoverage", TestSameHashDifferentParentNeverBorrowsCoverage); test::suite.Case("UnknownFamilyFinalRestartAndTokenState", TestUnknownFamilyFinalRestartAndTokenState); @@ -809,5 +1340,11 @@ int main() { test::suite.Case("WrongPathRequiresNewOperation", TestWrongPathRequiresNewOperation); test::suite.Case("PruneBarrierAndFenceIncarnationReset", TestPruneBarrierAndFenceIncarnationReset); test::suite.Case("FamilyDropRejectsOldIncarnation", TestFamilyDropRejectsOldIncarnation); + test::suite.Case("CapabilityHotReuseReplayAndRecovery", TestCapabilityHotReuseReplayAndRecovery); + test::suite.Case("CapabilityLateFinalWatermarkOrigin", TestCapabilityLateFinalWatermarkOrigin); + test::suite.Case("CapabilityRejectsForgeryAndStaleGeneration", TestCapabilityRejectsForgeryAndStaleGeneration); + test::suite.Case("CapabilitySamePathCrossOperationOriginAfterRecovery", TestCapabilitySamePathCrossOperationOriginAfterRecovery); + test::suite.Case("CapabilityLegacyFinalRequiresFullReplay", TestCapabilityLegacyFinalRequiresFullReplay); + test::suite.Case("CapabilityLineagePruneAndSideIsolation", TestCapabilityLineagePruneAndSideIsolation); return test::suite.Finish(); } diff --git a/test/cyclestore/journal_test.cc b/test/cyclestore/journal_test.cc index 7625f789..d0bea502 100644 --- a/test/cyclestore/journal_test.cc +++ b/test/cyclestore/journal_test.cc @@ -203,6 +203,51 @@ void TestAppendReadAndDeterministicReplay() { CHECK(CanonicalReplayDigest(without_duplicates) == digest); } +void TestCapabilityMutationRoundTripAndReplay() { + EvidenceCapabilityRecord capability; + capability.schema_version = 1; + capability.family = FamilyKey{"scope", "domain", {0, 0xff}}; + capability.canonical_path_digest.fill(0x5a); + capability.expected_tip.depth = 0; + capability.page_count = 1; + capability.validated_apply_index = 1; + RecordMutation put{RecordKind::kEvidenceCapability, + EncodeEvidenceCapabilityKey(EvidenceCapabilityKey{ + capability.family, capability.canonical_path_digest}), + false, EncodeEvidenceCapability(capability)}; + JournalEntry first = Entry(1, 7, 4); + first.mutations = {put, MetaMutation(1, 7)}; + JournalEntry second = Entry(2, 7, 5); + RecordMutation erase = put; + erase.erase = true; + erase.value.clear(); + second.mutations = {erase, MetaMutation(2, 7)}; + + TempJournal temp("capability-round-trip"); + JournalIssue issue; + REQUIRE(AppendJournalEntry(temp.path, first, &issue)); + REQUIRE(AppendJournalEntry(temp.path, second, &issue)); + const JournalReadResult read = ReadJournal(temp.path); + REQUIRE(read.ok()); + REQUIRE(read.entries.size() == 2); + CHECK(read.entries[0].mutations[0].kind == RecordKind::kEvidenceCapability); + EvidenceCapabilityRecord decoded; + std::string error; + REQUIRE(DecodeEvidenceCapability(read.entries[0].mutations[0].value, &decoded, &error)); + CHECK(decoded.canonical_path_digest == capability.canonical_path_digest); + CHECK(decoded.validated_apply_index == 1); + + Bytes record_key = put.key; + record_key.insert(record_key.begin(), static_cast(RecordKind::kEvidenceCapability)); + ReplayState before_erase; + REQUIRE(ReplayJournal({read.entries[0]}, &before_erase, &issue)); + CHECK(before_erase.records.find(record_key) != before_erase.records.end()); + ReplayState after_erase; + REQUIRE(ReplayJournal(read.entries, &after_erase, &issue)); + CHECK(after_erase.records.find(record_key) == after_erase.records.end()); + CHECK(after_erase.last_applied_index == 2); +} + void TestTruncatedHeaderAndPayloadPreserveValidPrefix() { JournalEntry first = Entry(1, 7, 4); first.mutations = {FamilyMutation(1), MetaMutation(1, 7)}; @@ -350,6 +395,7 @@ int main() { test::suite.Case("CrcVectorAndFrameRoundTrip", TestCrcVectorAndFrameRoundTrip); test::suite.Case("NewJournalSyncsParentDirectory", TestNewJournalSyncsParentDirectory); test::suite.Case("AppendReadAndDeterministicReplay", TestAppendReadAndDeterministicReplay); + test::suite.Case("CapabilityMutationRoundTripAndReplay", TestCapabilityMutationRoundTripAndReplay); test::suite.Case("TruncatedHeaderAndPayloadPreserveValidPrefix", TestTruncatedHeaderAndPayloadPreserveValidPrefix); test::suite.Case("CrcMismatchAndMalformedFrameAreNotRepaired", TestCrcMismatchAndMalformedFrameAreNotRepaired); test::suite.Case("ValueFieldMutationSurvivesFrameCrcButFailsRecordDecode", TestValueFieldMutationSurvivesFrameCrcButFailsRecordDecode); diff --git a/test/cyclestore/records_test.cc b/test/cyclestore/records_test.cc index 73f9c96f..61f8e8b2 100644 --- a/test/cyclestore/records_test.cc +++ b/test/cyclestore/records_test.cc @@ -284,6 +284,31 @@ void TestAllRecordRoundTrips() { expiry.expected_gc_at_ms = -1; expiry.object_apply_index = 13; ExpectRoundTrip(expiry, EncodeExpiryIndex, DecodeExpiryIndex); + + EvidenceCapabilityRecord capability; + capability.family = SampleFamily(); + capability.data_epoch = 11; + capability.family_incarnation = 2; + capability.root_generation = 3; + capability.root_locked_ttl = TtlClass::k1h; + capability.expected_tip.node_id = PatternId(20); + capability.expected_tip.node_incarnation = PatternId(21); + capability.expected_tip.page_hash = {0xaa, 0xbb}; + capability.expected_tip.depth = 1; + capability.canonical_path_digest = PatternDigest(22); + capability.complete_page_evidence_digest = PatternDigest(23); + capability.validated_apply_index = 13; + capability.page_count = 2; + const Bytes capability_key = EncodeEvidenceCapabilityKey( + EvidenceCapabilityKey{capability.family, capability.canonical_path_digest}); + EvidenceCapabilityKey decoded_capability_key; + std::string capability_error; + REQUIRE(DecodeEvidenceCapabilityKey(capability_key, &decoded_capability_key, + &capability_error)); + CHECK(EncodeFamilyKey(decoded_capability_key.family) == + EncodeFamilyKey(capability.family)); + CHECK(decoded_capability_key.canonical_path_digest == capability.canonical_path_digest); + ExpectRoundTrip(capability, EncodeEvidenceCapability, DecodeEvidenceCapability); } void TestMalformedAndVersionedDecoding() { @@ -399,8 +424,32 @@ void TestIndependentValueGoldenRecords() { "800000000000000d" // final_state_at "800000000000000e" // receipt_gc_at "0000000000000005" // token_apply_index - "01"; // token_expired - CHECK(EncodeOperationRecord(operation) == BytesFromHex(operation_golden)); + "01" // token_expired + "00" // legacy commit input digest semantics + "0000000000000000"; // empty issued and final capability history + const Bytes encoded_operation = EncodeOperationRecord(operation); + CHECK(encoded_operation == BytesFromHex(operation_golden)); + Bytes legacy_operation = encoded_operation; + legacy_operation.resize(legacy_operation.size() - 9); + OperationRecord decoded_legacy; + std::string legacy_error; + REQUIRE(DecodeOperationRecord(legacy_operation, &decoded_legacy, &legacy_error)); + CHECK(!decoded_legacy.commit_input_semantic_v2); + CHECK(decoded_legacy.issued_capability_encoding.empty()); + CHECK(decoded_legacy.final_capability_encoding.empty()); + operation.commit_input_semantic_v2 = true; + EvidenceCapabilityRecord capability; + capability.schema_version = 1; + capability.validated_apply_index = 15; + capability.expected_tip.depth = 0; + capability.page_count = 1; + operation.final_capability_encoding = EncodeEvidenceCapability(capability); + OperationRecord decoded_history; + REQUIRE(DecodeOperationRecord(EncodeOperationRecord(operation), + &decoded_history, &legacy_error)); + CHECK(decoded_history.commit_input_semantic_v2); + CHECK(decoded_history.final_capability_encoding == + operation.final_capability_encoding); } void TestFieldLevelEvidenceMutation() {