netherframe.testing 0.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- netherframe/testing/__init__.py +1 -0
- netherframe/testing/fakecloud.py +628 -0
- netherframe/testing/graph_memory.py +1484 -0
- netherframe/testing/graph_scenarios.py +377 -0
- netherframe/testing/log_capture.py +33 -0
- netherframe/testing/options.py +124 -0
- netherframe/testing/patching.py +17 -0
- netherframe/testing/provider_sources.py +53 -0
- netherframe/testing/provider_test_helpers.py +33 -0
- netherframe/testing/py.typed +0 -0
- netherframe/testing/pytest_fakecloud.py +75 -0
- netherframe/testing/pytest_workspace.py +122 -0
- netherframe/testing/schema_cache.py +54 -0
- netherframe/testing/state_backend_contract.py +775 -0
- netherframe/testing/terraform_cache.py +39 -0
- netherframe_testing-0.2.0.dist-info/METADATA +26 -0
- netherframe_testing-0.2.0.dist-info/RECORD +35 -0
- netherframe_testing-0.2.0.dist-info/WHEEL +4 -0
- netherframe_testing-0.2.0.dist-info/entry_points.txt +3 -0
- netherframe_testing-0.2.0.dist-info/licenses/LICENSE +21 -0
- nf/testing/__init__.py +21 -0
- nf/testing/fakecloud.py +21 -0
- nf/testing/graph_memory.py +21 -0
- nf/testing/graph_scenarios.py +21 -0
- nf/testing/log_capture.py +21 -0
- nf/testing/options.py +21 -0
- nf/testing/patching.py +21 -0
- nf/testing/provider_sources.py +21 -0
- nf/testing/provider_test_helpers.py +21 -0
- nf/testing/py.typed +0 -0
- nf/testing/pytest_fakecloud.py +21 -0
- nf/testing/pytest_workspace.py +21 -0
- nf/testing/schema_cache.py +21 -0
- nf/testing/state_backend_contract.py +21 -0
- nf/testing/terraform_cache.py +21 -0
|
@@ -0,0 +1,1484 @@
|
|
|
1
|
+
"""An in-memory graph state backend, for tests of the graph engine and of hybrid execution over it.
|
|
2
|
+
|
|
3
|
+
It implements ``GraphStateBackend`` with the same rules as the PostgreSQL graph backend (fencing
|
|
4
|
+
by epoch and expiry, pre-call validation, quarantine, the commit counter, compare-and-swap,
|
|
5
|
+
identity uniqueness), under one lock instead of transactions, with a clock tests can advance
|
|
6
|
+
(``advance``) and faults they can inject (``fail_next``).
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from netherframe.core.backends.graph_planning_context import bind_planning_context
|
|
12
|
+
|
|
13
|
+
import threading
|
|
14
|
+
import time
|
|
15
|
+
import uuid
|
|
16
|
+
from copy import deepcopy
|
|
17
|
+
from collections.abc import Mapping, Sequence
|
|
18
|
+
from dataclasses import dataclass, field, replace
|
|
19
|
+
from typing import Any
|
|
20
|
+
|
|
21
|
+
from netherframe.core.backends.graph_settings import GraphStateSettings
|
|
22
|
+
from netherframe.core.backends.graph_leases import X, LeaseKey, can_grant, missing_leases, normalized
|
|
23
|
+
from netherframe.core.backends.graph_plan_basis import GraphPlanBasis
|
|
24
|
+
from netherframe.core.backends.graph_edges import EdgeIndex, GraphEdge, targets_of
|
|
25
|
+
from netherframe.core.backends.graph_identity import GRAPH_OBJECT, locator_of
|
|
26
|
+
from netherframe.core.backends.graph_ownership import ObjectCheck, ObjectOwner, ownership_problems
|
|
27
|
+
from netherframe.core.backends.graph_object_guard import source_of
|
|
28
|
+
from netherframe.core.backends.graph_object_guard import bind_operation_request, object_problems, object_request
|
|
29
|
+
from netherframe.core.backends.graph_footprints import FOOTPRINT, combine_footprints, conflicting_owned_operations, footprint_problems, has_input_provenance, operation_footprint, recovery_footprint, retained_footprint, write_footprint
|
|
30
|
+
from netherframe.core.backends.graph_baseline import GraphBaseline, IntentRecord, intent_snapshot_digest, require_known_intents
|
|
31
|
+
from netherframe.core.backends.graph_planning import GraphEntrySummary, GraphPlanningOperation, GraphPlanningRow, GraphPlanningView, PlanningKey, planning_keys
|
|
32
|
+
from netherframe.core.backends.graph_retention import HistoryRetention, RetentionCount, retention_days
|
|
33
|
+
from netherframe.core.backends.graph_history import HistoryPage, HistoryQuery, position
|
|
34
|
+
from netherframe.core.backends.graph_plan_guard import ROLLBACK_DELETE, ROLLBACK_ENABLED, ROLLBACK_OF, GraphPlanAdmission, require_existing_identity, require_rollback_source
|
|
35
|
+
from netherframe.core.backends.graph_migration import StateTransfer, TransferRecord, storage_identity, transfer_writes
|
|
36
|
+
from netherframe.core.backends.graph_kept_return import KeptReturn
|
|
37
|
+
from netherframe.core.backends.graph_recovery import Probe, recovery_probe_result
|
|
38
|
+
from netherframe.core.backends.graph_checkpoint import (
|
|
39
|
+
CheckpointRestorePreview,
|
|
40
|
+
CheckpointTarget,
|
|
41
|
+
GraphCheckpoint,
|
|
42
|
+
before_image,
|
|
43
|
+
checked_targets,
|
|
44
|
+
checkpoint_id,
|
|
45
|
+
image_digest,
|
|
46
|
+
require_no_restore_blockers,
|
|
47
|
+
require_restore_identities,
|
|
48
|
+
restore_blockers,
|
|
49
|
+
restore_leases,
|
|
50
|
+
restore_writes,
|
|
51
|
+
)
|
|
52
|
+
from netherframe.core.backends.graph_inputs import STALE_INPUTS, changed_inputs, decode_inputs, effective_status, input_covers
|
|
53
|
+
from netherframe.core.backends.graph_inputs import stored_values_equal, value_fingerprint
|
|
54
|
+
from netherframe.core.backends.graph_state import (
|
|
55
|
+
ABORTED,
|
|
56
|
+
ACTIVE,
|
|
57
|
+
COMMITTED,
|
|
58
|
+
DISPATCHED,
|
|
59
|
+
ENDED,
|
|
60
|
+
EXPIRED,
|
|
61
|
+
FINAL_STAGES,
|
|
62
|
+
IN_FLIGHT_STAGES,
|
|
63
|
+
METADATA,
|
|
64
|
+
OBSERVATION,
|
|
65
|
+
OUTPUT,
|
|
66
|
+
RESERVED,
|
|
67
|
+
RESOURCE,
|
|
68
|
+
RETURNED,
|
|
69
|
+
UNCERTAIN,
|
|
70
|
+
UNCHECKED,
|
|
71
|
+
CommitResult,
|
|
72
|
+
GraphSnapshot,
|
|
73
|
+
GraphStateBackend,
|
|
74
|
+
HistoryRecord,
|
|
75
|
+
OperationRecord,
|
|
76
|
+
OperationSpec,
|
|
77
|
+
Ownership,
|
|
78
|
+
OwnershipLostError,
|
|
79
|
+
PreCallValidationError,
|
|
80
|
+
QuarantinedError,
|
|
81
|
+
RowVersion,
|
|
82
|
+
RowWrite,
|
|
83
|
+
StaleGraphPlanError,
|
|
84
|
+
SiblingOperationBusyError,
|
|
85
|
+
entry_status,
|
|
86
|
+
object_identity,
|
|
87
|
+
private_digest,
|
|
88
|
+
semantic_revisions,
|
|
89
|
+
validate_write_operations,
|
|
90
|
+
validate_recovery_writes,
|
|
91
|
+
validate_operation_resolution,
|
|
92
|
+
validate_operation_dispatch,
|
|
93
|
+
)
|
|
94
|
+
from netherframe.core.backends.state_models import ResourceState, State, StateVersion
|
|
95
|
+
from netherframe.core.exceptions import StateConflictError, StateError, StateLockError
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
@dataclass
|
|
99
|
+
class _Run:
|
|
100
|
+
run_id: str
|
|
101
|
+
epoch: int
|
|
102
|
+
operation: str
|
|
103
|
+
expires_at: float
|
|
104
|
+
status: str = ACTIVE
|
|
105
|
+
host: str = ""
|
|
106
|
+
pid: int | None = None
|
|
107
|
+
providers_killed: bool = False
|
|
108
|
+
info: dict[str, Any] = field(default_factory=dict)
|
|
109
|
+
lease_phase: str = "pending"
|
|
110
|
+
lease_set: dict[str, str] | None = None
|
|
111
|
+
mutation_started: bool = False
|
|
112
|
+
admission: GraphPlanAdmission | None = None
|
|
113
|
+
baseline: GraphBaseline | None = None
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
@dataclass
|
|
117
|
+
class _Row:
|
|
118
|
+
version: RowVersion
|
|
119
|
+
entry: Any
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
class InMemoryGraphBackend(GraphStateBackend):
|
|
123
|
+
"""A ``GraphStateBackend`` in memory (see the module's documentation)."""
|
|
124
|
+
|
|
125
|
+
supports_state_transfers = True
|
|
126
|
+
|
|
127
|
+
def state_identity(self) -> dict[str, Any]:
|
|
128
|
+
return {"backend": self.get_backend_type(), "state_id": self.state_id, "lineage": self.lineage}
|
|
129
|
+
|
|
130
|
+
def __init__(self, *, settings: GraphStateSettings | None = None, state_id: str = "memory-graph") -> None:
|
|
131
|
+
self.settings = settings or GraphStateSettings(lease_ttl=30.0, lease_renew_interval=0.5)
|
|
132
|
+
self.state_id = state_id
|
|
133
|
+
self.lineage = str(uuid.uuid4())
|
|
134
|
+
self.epoch = 0
|
|
135
|
+
self.frontier = 0
|
|
136
|
+
self.pruned_before = 0
|
|
137
|
+
self.history_epoch = 0
|
|
138
|
+
self.metadata: dict[str, Any] = {}
|
|
139
|
+
self.migrated_to: str | None = None
|
|
140
|
+
self.transfer_id: str | None = None
|
|
141
|
+
self.transfers: dict[str, TransferRecord] = {}
|
|
142
|
+
self.runs: dict[str, _Run] = {}
|
|
143
|
+
self.holder: str | None = None
|
|
144
|
+
self.leases: dict[str, dict[str, str]] = {}
|
|
145
|
+
self.lease_queue: dict[str, tuple[int, dict[str, str]]] = {}
|
|
146
|
+
self._ticket = 0
|
|
147
|
+
self.rows: dict[str, _Row] = {}
|
|
148
|
+
self.outputs: dict[str, _Row] = {}
|
|
149
|
+
self.observations: dict[str, ResourceState] = {}
|
|
150
|
+
self.ops: dict[str, OperationRecord] = {}
|
|
151
|
+
self.history_records: list[HistoryRecord] = []
|
|
152
|
+
self.edge_index = EdgeIndex()
|
|
153
|
+
self.baselines: dict[str, GraphBaseline] = {}
|
|
154
|
+
self._baseline_records: dict[str, list[IntentRecord]] = {}
|
|
155
|
+
self.checkpoints: dict[str, GraphCheckpoint] = {}
|
|
156
|
+
self.restore_receipts: dict[str, tuple[str, bool, int]] = {}
|
|
157
|
+
self._reservation = 0
|
|
158
|
+
self._checkpoint_keep = 5
|
|
159
|
+
#: Every commit: (sequence, run, time, the run's lease expiry then, its epoch), for the oracle "no commit without a live epoch"
|
|
160
|
+
self.commits: list[tuple[int, str, float, float, int]] = []
|
|
161
|
+
self._lock = threading.RLock()
|
|
162
|
+
self._offset = 0.0
|
|
163
|
+
self._faults: dict[str, list[BaseException]] = {}
|
|
164
|
+
#: Every fenced transition, for oracles: (method, run_id, epoch, authorised)
|
|
165
|
+
self.transitions: list[tuple[str, str, int, bool]] = []
|
|
166
|
+
|
|
167
|
+
# -- test controls -----------------------------------------------------------------
|
|
168
|
+
|
|
169
|
+
def now(self) -> float:
|
|
170
|
+
return time.time() + self._offset
|
|
171
|
+
|
|
172
|
+
def advance(self, seconds: float) -> None:
|
|
173
|
+
"""Move the backend's clock forward (expiry, quiescence)."""
|
|
174
|
+
with self._lock:
|
|
175
|
+
self._offset += seconds
|
|
176
|
+
|
|
177
|
+
def fail_next(self, method: str, error: BaseException | None = None) -> None:
|
|
178
|
+
"""Make the next call of ``method`` raise ``error`` (default: a dropped connection) before changing anything."""
|
|
179
|
+
self._faults.setdefault(method, []).append(error or ConnectionError(f"connection to the database lost during {method}"))
|
|
180
|
+
|
|
181
|
+
def _fault(self, method: str) -> None:
|
|
182
|
+
faults = self._faults.get(method)
|
|
183
|
+
if faults:
|
|
184
|
+
raise faults.pop(0)
|
|
185
|
+
|
|
186
|
+
# -- document interface ------------------------------------------------------------
|
|
187
|
+
|
|
188
|
+
def get_backend_type(self) -> str:
|
|
189
|
+
return "memory-graph"
|
|
190
|
+
|
|
191
|
+
def get_config(self) -> dict[str, Any]:
|
|
192
|
+
return {"type": "memory-graph", "state_id": self.state_id}
|
|
193
|
+
|
|
194
|
+
# -- ownership ---------------------------------------------------------------------
|
|
195
|
+
|
|
196
|
+
def _fence(self, ownership: Ownership, method: str, *, recovery: bool = False, restoring: bool = False, migrating: bool = False) -> _Run:
|
|
197
|
+
run = self.runs.get(ownership.run_id)
|
|
198
|
+
if migrating and (run is None or run.operation != "migrate" or run.admission is not None or ownership.claim is not None):
|
|
199
|
+
raise PreCallValidationError("State transfer requires its own whole-app migration run")
|
|
200
|
+
if self.migrated_to is not None and method not in {"mark_migrated", "migration"} and not migrating:
|
|
201
|
+
raise PreCallValidationError("This graph state is fenced by migration; ordinary mutations are refused")
|
|
202
|
+
if restoring and (run is None or run.operation != "restore-checkpoint" or run.admission is not None or ownership.claim is not None):
|
|
203
|
+
raise PreCallValidationError("A checkpoint restore needs its own state-only run")
|
|
204
|
+
if run is not None and run.operation == "restore-checkpoint" and (method in {"reserve", "dispatch", "mark_migrated"} or (method == "commit" and not restoring)):
|
|
205
|
+
raise PreCallValidationError("A checkpoint restore can only write its verified before-images")
|
|
206
|
+
live = run is not None and run.status == ACTIVE and run.epoch == ownership.epoch and run.expires_at > self.now()
|
|
207
|
+
if ownership.claim is not None and not recovery:
|
|
208
|
+
raise PreCallValidationError("An operation claim cannot authorize new calls or unrelated state administration")
|
|
209
|
+
if live:
|
|
210
|
+
self._queue_run(ownership)
|
|
211
|
+
authorised = live and (
|
|
212
|
+
(self.holder == ownership.run_id and self.leases.get(ownership.run_id, {}).get("app") == X)
|
|
213
|
+
or (not recovery and run is not None and run.admission is not None and run.lease_phase == "granted")
|
|
214
|
+
or (recovery and run is not None and run.operation == "recover")
|
|
215
|
+
or (restoring and run is not None and run.lease_phase == "granted")
|
|
216
|
+
)
|
|
217
|
+
if run is not None and run.admission is not None and method == "mark_migrated":
|
|
218
|
+
raise PreCallValidationError("An admitted resource plan cannot authorize app migration")
|
|
219
|
+
if run is not None and run.admission is not None and recovery:
|
|
220
|
+
raise PreCallValidationError("An admitted resource plan cannot authorize recovery; register a recoverer")
|
|
221
|
+
self.transitions.append((method, ownership.run_id, ownership.epoch, authorised))
|
|
222
|
+
if live and run is not None and not authorised and (run.lease_set or {}).get("app") != X:
|
|
223
|
+
raise PreCallValidationError("State mutations require a whole-app X lease or an admitted graph plan")
|
|
224
|
+
if not authorised or run is None:
|
|
225
|
+
raise OwnershipLostError(f"Run {ownership.run_id} no longer owns the app ({method} refused)")
|
|
226
|
+
return run
|
|
227
|
+
|
|
228
|
+
def _queue_run(self, ownership: Ownership) -> _Run:
|
|
229
|
+
run = self.runs.get(ownership.run_id)
|
|
230
|
+
if run is None or run.status != ACTIVE or run.epoch != ownership.epoch or run.expires_at <= self.now():
|
|
231
|
+
raise OwnershipLostError(f"Run {ownership.run_id} cannot use the lease queue: its ownership expired or was taken over")
|
|
232
|
+
if run.lease_phase == "granted" and (run.lease_set != self.leases.get(ownership.run_id) or ((run.lease_set or {}).get("app") == X and self.holder != run.run_id)):
|
|
233
|
+
raise OwnershipLostError("The run lost part of its granted lease set")
|
|
234
|
+
return run
|
|
235
|
+
|
|
236
|
+
def open_run(self, info: Mapping[str, Any], *, ttl: float, operation: str) -> Ownership:
|
|
237
|
+
with self._lock:
|
|
238
|
+
if ttl <= 0:
|
|
239
|
+
raise StateError("A run's lease TTL must be positive")
|
|
240
|
+
self.epoch += 1
|
|
241
|
+
run = _Run(uuid.uuid4().hex, self.epoch, operation, self.now() + ttl, host=str(info.get("host") or ""), pid=info.get("pid"), info=dict(info))
|
|
242
|
+
self.runs[run.run_id] = run
|
|
243
|
+
return Ownership(run.run_id, run.epoch, ttl, operation)
|
|
244
|
+
|
|
245
|
+
def request_leases(self, ownership: Ownership, request: Mapping[LeaseKey, str]) -> int:
|
|
246
|
+
with self._lock:
|
|
247
|
+
run = self._queue_run(ownership)
|
|
248
|
+
if run.operation == "recover":
|
|
249
|
+
raise PreCallValidationError("Recovery inherits operation footprints and cannot request a new run grant")
|
|
250
|
+
wanted = normalized(request)
|
|
251
|
+
previous = self.lease_queue.get(ownership.run_id)
|
|
252
|
+
if previous is not None:
|
|
253
|
+
if previous[1] != wanted:
|
|
254
|
+
raise StateLockError("A queued lease set is immutable; cancel it before requesting another")
|
|
255
|
+
return previous[0]
|
|
256
|
+
if run.lease_phase == "granted":
|
|
257
|
+
raise StateLockError("A granted lease set cannot grow; release it before requesting another")
|
|
258
|
+
if run.mutation_started:
|
|
259
|
+
raise StateLockError("A run cannot request another lease set after its first mutation; end the run before replanning")
|
|
260
|
+
self._ticket += 1
|
|
261
|
+
self.lease_queue[ownership.run_id] = (self._ticket, wanted)
|
|
262
|
+
return self._ticket
|
|
263
|
+
|
|
264
|
+
def try_grant_leases(self, ownership: Ownership) -> bool:
|
|
265
|
+
with self._lock:
|
|
266
|
+
for run in self.runs.values():
|
|
267
|
+
if run.status == ACTIVE and run.expires_at <= self.now():
|
|
268
|
+
self._quarantine(run)
|
|
269
|
+
run = self._queue_run(ownership)
|
|
270
|
+
if run.lease_phase == "granted":
|
|
271
|
+
return True
|
|
272
|
+
pending = self.lease_queue.get(ownership.run_id)
|
|
273
|
+
if pending is None:
|
|
274
|
+
raise StateLockError("The run has no queued lease request")
|
|
275
|
+
ticket, wanted = pending
|
|
276
|
+
older = [request for older_ticket, request in self.lease_queue.values() if older_ticket < ticket]
|
|
277
|
+
holders = [*self.leases.values(), *(retained_footprint(record) for record in self.ops.values() if not record.resolved)]
|
|
278
|
+
if not can_grant(wanted, holders, older):
|
|
279
|
+
return False
|
|
280
|
+
self.leases[ownership.run_id] = dict(wanted)
|
|
281
|
+
run.lease_set, run.lease_phase = dict(wanted), "granted"
|
|
282
|
+
self.lease_queue.pop(ownership.run_id)
|
|
283
|
+
if wanted.get("app") == X:
|
|
284
|
+
self.holder = ownership.run_id
|
|
285
|
+
return True
|
|
286
|
+
|
|
287
|
+
def release_leases(self, ownership: Ownership) -> None:
|
|
288
|
+
with self._lock:
|
|
289
|
+
run = self._queue_run(ownership)
|
|
290
|
+
pending = next((record for record in self.ops.values() if ownership.run_id in {record.run_id, record.recovered_by} and not record.resolved), None)
|
|
291
|
+
if pending is not None:
|
|
292
|
+
raise StateLockError(f"Operation {pending.op_id} still holds its footprint; resolve it before releasing the lease set")
|
|
293
|
+
if run.mutation_started:
|
|
294
|
+
raise StateLockError("A run cannot release its lease set after its first mutation; end the run before replanning")
|
|
295
|
+
self.leases.pop(ownership.run_id, None)
|
|
296
|
+
self.lease_queue.pop(ownership.run_id, None)
|
|
297
|
+
run.lease_set, run.lease_phase = None, "pending"
|
|
298
|
+
run.admission = None
|
|
299
|
+
if self.holder == ownership.run_id:
|
|
300
|
+
self.holder = None
|
|
301
|
+
|
|
302
|
+
def held_leases(self, ownership: Ownership) -> dict[str, str]:
|
|
303
|
+
with self._lock:
|
|
304
|
+
return dict(self.leases.get(ownership.run_id, {}))
|
|
305
|
+
|
|
306
|
+
def explain_lease_request(self, ownership, *, basis=None):
|
|
307
|
+
from netherframe.core.backends.graph_diagnostics import LeaseBlocker, lease_report
|
|
308
|
+
|
|
309
|
+
with self._lock:
|
|
310
|
+
self._queue_run(ownership)
|
|
311
|
+
pending = self.lease_queue.get(ownership.run_id)
|
|
312
|
+
if pending is None:
|
|
313
|
+
raise StateLockError("The run has no queued lease request to explain")
|
|
314
|
+
ticket, wanted = pending
|
|
315
|
+
live = {key for key, run in self.runs.items() if run.status == ACTIVE and run.expires_at > self.now()}
|
|
316
|
+
blockers = [LeaseBlocker(key, leases) for key, leases in self.leases.items() if key != ownership.run_id and key in live]
|
|
317
|
+
blockers.extend(LeaseBlocker(key, request, "older_waiter") for key, (older_ticket, request) in self.lease_queue.items() if older_ticket < ticket and key in live)
|
|
318
|
+
blockers.extend(LeaseBlocker(record.recovered_by or record.run_id, retained_footprint(record), "retained_operation", record.op_id) for record in self.ops.values() if not record.resolved)
|
|
319
|
+
return lease_report(wanted, blockers, run_id=ownership.run_id, ticket=ticket, frontier=self.frontier, basis=basis)
|
|
320
|
+
|
|
321
|
+
def validate_plan_basis(self, ownership: Ownership, basis: GraphPlanBasis) -> None:
|
|
322
|
+
with self._lock:
|
|
323
|
+
self._queue_run(ownership)
|
|
324
|
+
missing = missing_leases(self.leases.get(ownership.run_id, {}), basis.required_leases())
|
|
325
|
+
if missing:
|
|
326
|
+
raise PreCallValidationError("Plan is not covered by granted leases: " + ", ".join(sorted(missing)))
|
|
327
|
+
snapshot = self.snapshot()
|
|
328
|
+
if problems := basis.problems(snapshot, run_id=ownership.run_id):
|
|
329
|
+
from netherframe.core.backends.graph_diagnostics import validation_report
|
|
330
|
+
|
|
331
|
+
report = validation_report(basis, snapshot, problems, run_id=ownership.run_id)
|
|
332
|
+
raise StaleGraphPlanError("Plan preconditions changed; replan before applying:\n" + "\n".join(problems), graph_conflicts=report.to_dict())
|
|
333
|
+
|
|
334
|
+
def admit_plan(self, ownership: Ownership, basis: GraphPlanBasis, baseline: GraphBaseline | None) -> None:
|
|
335
|
+
with self._lock:
|
|
336
|
+
run = self._queue_run(ownership)
|
|
337
|
+
if ownership.claim is not None or run.operation == "recover":
|
|
338
|
+
raise PreCallValidationError("Recovery inherits operation coverage and cannot admit a new mutation plan")
|
|
339
|
+
admission = GraphPlanAdmission(basis, baseline, run.operation if baseline is None else None)
|
|
340
|
+
if run.admission is not None:
|
|
341
|
+
if run.admission != admission:
|
|
342
|
+
raise StateLockError("An admitted plan is immutable; release the entire grant before replanning")
|
|
343
|
+
return
|
|
344
|
+
if run.mutation_started or any(not record.resolved and ownership.run_id in {record.run_id, record.recovered_by} for record in self.ops.values()):
|
|
345
|
+
raise StateLockError("Admit a plan before reserving operations or mutating state")
|
|
346
|
+
if baseline is not None:
|
|
347
|
+
if run.baseline is not None and baseline != run.baseline:
|
|
348
|
+
raise StateLockError("The admitted plan and run baseline must agree")
|
|
349
|
+
self.baseline_intents(baseline)
|
|
350
|
+
self.validate_plan_basis(ownership, basis)
|
|
351
|
+
admission.check_existing_identities()
|
|
352
|
+
run.admission = deepcopy(admission)
|
|
353
|
+
|
|
354
|
+
def acquire(self, info: Mapping[str, Any], *, ttl: float, operation: str) -> Ownership | None:
|
|
355
|
+
with self._lock:
|
|
356
|
+
self._fault("acquire")
|
|
357
|
+
ownership = self.open_run(info, ttl=ttl, operation=operation)
|
|
358
|
+
granted = False
|
|
359
|
+
try:
|
|
360
|
+
self.request_leases(ownership, {LeaseKey(): X})
|
|
361
|
+
granted = self.try_grant_leases(ownership)
|
|
362
|
+
return ownership if granted else None
|
|
363
|
+
finally:
|
|
364
|
+
if not granted:
|
|
365
|
+
self.release(ownership)
|
|
366
|
+
|
|
367
|
+
def _quarantine(self, run: _Run) -> None:
|
|
368
|
+
if run.status == ACTIVE:
|
|
369
|
+
run.status = EXPIRED
|
|
370
|
+
for record in self.ops.values():
|
|
371
|
+
if record.run_id == run.run_id and not record.resolved and record.stage != RESERVED:
|
|
372
|
+
row = self.rows.get(record.address)
|
|
373
|
+
if row is not None and not row.version.tombstone:
|
|
374
|
+
row.version = replace(row.version, status=UNCERTAIN)
|
|
375
|
+
self.leases.pop(run.run_id, None)
|
|
376
|
+
self.lease_queue.pop(run.run_id, None)
|
|
377
|
+
if self.holder == run.run_id:
|
|
378
|
+
self.holder = None
|
|
379
|
+
|
|
380
|
+
def renew(self, ownership: Ownership) -> None:
|
|
381
|
+
with self._lock:
|
|
382
|
+
self._fault("renew")
|
|
383
|
+
run = self._queue_run(ownership)
|
|
384
|
+
run.expires_at = self.now() + ownership.ttl
|
|
385
|
+
|
|
386
|
+
def release(self, ownership: Ownership) -> None:
|
|
387
|
+
with self._lock:
|
|
388
|
+
run = self.runs.get(ownership.run_id)
|
|
389
|
+
if run is None or run.epoch != ownership.epoch:
|
|
390
|
+
return
|
|
391
|
+
if run is not None and run.status == ACTIVE and run.epoch == ownership.epoch:
|
|
392
|
+
run.status = ENDED
|
|
393
|
+
self.leases.pop(ownership.run_id, None)
|
|
394
|
+
self.lease_queue.pop(ownership.run_id, None)
|
|
395
|
+
if self.holder == ownership.run_id:
|
|
396
|
+
self.holder = None
|
|
397
|
+
self._prune_checkpoints()
|
|
398
|
+
|
|
399
|
+
def report_providers_killed(self, ownership: Ownership) -> None:
|
|
400
|
+
with self._lock:
|
|
401
|
+
run = self.runs.get(ownership.run_id)
|
|
402
|
+
if run is not None:
|
|
403
|
+
run.providers_killed = True
|
|
404
|
+
|
|
405
|
+
def current_owner(self) -> dict[str, Any] | None:
|
|
406
|
+
with self._lock:
|
|
407
|
+
if self.holder is None:
|
|
408
|
+
return None
|
|
409
|
+
run = self.runs[self.holder]
|
|
410
|
+
if run.expires_at <= self.now():
|
|
411
|
+
return None
|
|
412
|
+
return {"ID": run.run_id, "Operation": run.operation, "Who": f"{run.info.get('user', '')}@{run.host}", "epoch": run.epoch}
|
|
413
|
+
|
|
414
|
+
def end_run(self, run_id: str) -> None:
|
|
415
|
+
with self._lock:
|
|
416
|
+
run = self.runs.get(run_id)
|
|
417
|
+
if run is None or run.status != ACTIVE:
|
|
418
|
+
raise StateLockError(f"Run {run_id} has no active ownership of this state")
|
|
419
|
+
dispatched = [record.summary() for record in self.ops.values() if record.run_id == run_id and record.stage in IN_FLIGHT_STAGES]
|
|
420
|
+
if dispatched:
|
|
421
|
+
raise StateLockError(f"Run {run_id} holds dispatched operations, which force-unlock cannot clear; resolve them with `nf state recover`: {'; '.join(dispatched)}")
|
|
422
|
+
self._quarantine(run)
|
|
423
|
+
run.status = ENDED
|
|
424
|
+
|
|
425
|
+
# -- reading -----------------------------------------------------------------------
|
|
426
|
+
|
|
427
|
+
def _validate_edge_index(self) -> None:
|
|
428
|
+
self.edge_index.validate(
|
|
429
|
+
GraphEdge(target, kind, key)
|
|
430
|
+
for kind, table in ((RESOURCE, self.rows), (OUTPUT, self.outputs))
|
|
431
|
+
for key, row in table.items()
|
|
432
|
+
if not row.version.tombstone
|
|
433
|
+
for target in targets_of(row.version.inputs, row.entry.dependencies if kind == RESOURCE else ())
|
|
434
|
+
)
|
|
435
|
+
|
|
436
|
+
def snapshot_unchanged(self, frontier: int, lineage: str) -> bool:
|
|
437
|
+
with self._lock:
|
|
438
|
+
return self.frontier == frontier and self.lineage == lineage and not self.migrated_to and self.transfer_id is None and not any(not operation.resolved for operation in self.ops.values())
|
|
439
|
+
|
|
440
|
+
def snapshot(self) -> GraphSnapshot:
|
|
441
|
+
with self._lock:
|
|
442
|
+
self._fault("snapshot")
|
|
443
|
+
self._validate_edge_index()
|
|
444
|
+
state = State(serial=self.frontier, lineage=self.lineage, metadata=dict(self.metadata))
|
|
445
|
+
for key, row in self.rows.items():
|
|
446
|
+
if not row.version.tombstone:
|
|
447
|
+
entry = row.entry.copy()
|
|
448
|
+
entry.tainted = entry.tainted or row.version.status == "tainted"
|
|
449
|
+
state.resources[key] = entry
|
|
450
|
+
for key, entry in self.observations.items():
|
|
451
|
+
state.resources[key] = entry.copy()
|
|
452
|
+
for key, row in self.outputs.items():
|
|
453
|
+
if not row.version.tombstone:
|
|
454
|
+
state.outputs[key] = row.entry
|
|
455
|
+
return GraphSnapshot(
|
|
456
|
+
state=state,
|
|
457
|
+
versions={key: row.version for key, row in self.rows.items()},
|
|
458
|
+
output_versions={key: row.version for key, row in self.outputs.items()},
|
|
459
|
+
frontier=self.frontier,
|
|
460
|
+
lineage=self.lineage,
|
|
461
|
+
unresolved=[self._view(record) for record in self.ops.values() if not record.resolved],
|
|
462
|
+
migrated_to=self.migrated_to,
|
|
463
|
+
transfer_id=self.transfer_id,
|
|
464
|
+
edge_index=self.edge_index.copy(),
|
|
465
|
+
)
|
|
466
|
+
|
|
467
|
+
def planning_view(self, keys: Sequence[PlanningKey] = (), *, baseline: GraphBaseline | None = None, expected_capture: str | None = None) -> GraphPlanningView:
|
|
468
|
+
requested = planning_keys(keys)
|
|
469
|
+
with self._lock:
|
|
470
|
+
self._fault("planning_view")
|
|
471
|
+
self._validate_edge_index()
|
|
472
|
+
origin = tuple(self.baseline_intents(baseline)) if baseline is not None else ()
|
|
473
|
+
summaries = {(kind, key): GraphEntrySummary.from_version(kind, key, row.version) for kind, table in ((RESOURCE, self.rows), (OUTPUT, self.outputs)) for key, row in table.items()}
|
|
474
|
+
rows = {}
|
|
475
|
+
for kind, key in requested:
|
|
476
|
+
if (row := (self.outputs if kind == OUTPUT else self.rows).get(key)) is not None:
|
|
477
|
+
rows[kind, key] = GraphPlanningRow(row.version, None if row.version.tombstone else row.entry)
|
|
478
|
+
view = GraphPlanningView(
|
|
479
|
+
self.lineage,
|
|
480
|
+
self.frontier,
|
|
481
|
+
summaries,
|
|
482
|
+
requested,
|
|
483
|
+
rows,
|
|
484
|
+
backend_type=self.get_backend_type(),
|
|
485
|
+
state_id=self.state_id,
|
|
486
|
+
origin=origin,
|
|
487
|
+
baseline=baseline,
|
|
488
|
+
edge_index=self.edge_index,
|
|
489
|
+
unresolved=tuple(GraphPlanningOperation.of(self._view(record)) for record in self.ops.values() if not record.resolved),
|
|
490
|
+
migrated_to=self.migrated_to,
|
|
491
|
+
transfer_id=self.transfer_id,
|
|
492
|
+
cleanup_keys=frozenset({(OBSERVATION, key) for key in self.observations} | ({(METADATA, METADATA)} if "stack_outputs" in self.metadata else set())),
|
|
493
|
+
)
|
|
494
|
+
return view.require_capture(expected_capture)
|
|
495
|
+
|
|
496
|
+
def check_planning_ownership(self, view: GraphPlanningView, checks: Sequence[ObjectCheck]) -> GraphPlanningView:
|
|
497
|
+
with self._lock:
|
|
498
|
+
checked = self.planning_view(baseline=view.baseline, expected_capture=view.capture)
|
|
499
|
+
identities = {identity for check in checks for identity in check.identities}
|
|
500
|
+
addresses = {check.address for check in checks}
|
|
501
|
+
bound_types = {kind for check in checks for _source, kind in check.bound_sources}
|
|
502
|
+
unbound_types = {kind for check in checks for _source, kind in check.sources - check.bound_sources}
|
|
503
|
+
owners = []
|
|
504
|
+
for address, row in self.rows.items():
|
|
505
|
+
if row.version.tombstone:
|
|
506
|
+
continue
|
|
507
|
+
identity = row.version.object_identity
|
|
508
|
+
canonical = identity if identity and identity.startswith("nf-object-v1:") else None
|
|
509
|
+
bound = row.entry.metadata.get(GRAPH_OBJECT) is not None
|
|
510
|
+
if address in addresses or canonical in identities or (row.entry.type in bound_types and canonical is None) or (row.entry.type in unbound_types and bound):
|
|
511
|
+
owners.append(ObjectOwner(address, source_of(row.entry), row.entry.type, canonical, bound))
|
|
512
|
+
if problems := ownership_problems(checks, owners):
|
|
513
|
+
raise StateError("Planning cloud ownership validation failed:\n" + "\n".join(problems))
|
|
514
|
+
return checked
|
|
515
|
+
|
|
516
|
+
# -- operations --------------------------------------------------------------------
|
|
517
|
+
|
|
518
|
+
def _holding(self, key: str, *, other_than: str | None = None, run_id: str | None = None) -> OperationRecord | None:
|
|
519
|
+
"""The unresolved operation, of another run than ``run_id``, holding ``key``."""
|
|
520
|
+
for record in self.ops.values():
|
|
521
|
+
if not record.resolved and record.op_id != other_than and record.run_id != run_id and key in (record.address, *record.footprint):
|
|
522
|
+
return record
|
|
523
|
+
return None
|
|
524
|
+
|
|
525
|
+
supports_creation_arms = True
|
|
526
|
+
supports_creation_completions = True
|
|
527
|
+
supports_creation_return_batches = True
|
|
528
|
+
|
|
529
|
+
def arm_creations(self, ownership: Ownership, specs: Sequence[OperationSpec]) -> None:
|
|
530
|
+
from netherframe.core.backends.graph_authorization import creation_arm_cohort
|
|
531
|
+
|
|
532
|
+
prepared, _ = creation_arm_cohort(ownership, specs)
|
|
533
|
+
with self._lock:
|
|
534
|
+
self._fault("arm_creations")
|
|
535
|
+
run = self._fence(ownership, "arm creations")
|
|
536
|
+
if self.leases.get(ownership.run_id, {}).get("app") != X or run.admission is not None or run.operation != "apply":
|
|
537
|
+
raise PreCallValidationError("Creation authorization requires an unadmitted whole-app apply")
|
|
538
|
+
if any(spec.op_id in self.ops for spec in prepared):
|
|
539
|
+
raise StateError("Creation authorization cannot replace an existing operation")
|
|
540
|
+
reservation, mutated = self._reservation, run.mutation_started
|
|
541
|
+
try:
|
|
542
|
+
for spec in prepared:
|
|
543
|
+
self.reserve(ownership, spec)
|
|
544
|
+
self.dispatch(ownership, spec.op_id, provider_pid=spec.provider_pid)
|
|
545
|
+
self._fence(ownership, "arm creations")
|
|
546
|
+
except BaseException:
|
|
547
|
+
for spec in prepared:
|
|
548
|
+
self.ops.pop(spec.op_id, None)
|
|
549
|
+
self._reservation, run.mutation_started = reservation, mutated
|
|
550
|
+
raise
|
|
551
|
+
|
|
552
|
+
def reserve(self, ownership: Ownership, spec: OperationSpec) -> None:
|
|
553
|
+
from netherframe.core.backends.graph_moves import MOVE_GROUP, check_move_reservation, move_plan
|
|
554
|
+
|
|
555
|
+
with self._lock:
|
|
556
|
+
self._fault("reserve")
|
|
557
|
+
run = self._fence(ownership, "reserve")
|
|
558
|
+
if spec.op_id in self.ops:
|
|
559
|
+
raise StateError(f"Operation {spec.op_id} already exists; its facts cannot be replaced")
|
|
560
|
+
if run.admission is not None:
|
|
561
|
+
run.admission.check_operation(spec)
|
|
562
|
+
if group := move_plan(spec.request):
|
|
563
|
+
run.admission.check_targets(list(group.basis.writes | {(item.kind, item.key) for item in group.basis.auxiliary}))
|
|
564
|
+
if MOVE_GROUP in spec.request:
|
|
565
|
+
check_move_reservation(spec, self.snapshot(), ownership.run_id)
|
|
566
|
+
if spec.action == "create":
|
|
567
|
+
spec.request[ROLLBACK_ENABLED] = run.admission is None or ROLLBACK_DELETE in run.admission.basis.actions.get(spec.address, ())
|
|
568
|
+
else:
|
|
569
|
+
spec.request.pop(ROLLBACK_ENABLED, None)
|
|
570
|
+
for key in (spec.address, *spec.footprint):
|
|
571
|
+
holder = self._holding(key, run_id=ownership.run_id)
|
|
572
|
+
if holder is not None:
|
|
573
|
+
raise QuarantinedError(f"{key} is held by unresolved operation {holder.summary()}; resolve it with `nf state recover {holder.op_id}` first")
|
|
574
|
+
row = self.rows.get(spec.address)
|
|
575
|
+
actual = row.version if row is not None else None
|
|
576
|
+
if run.admission is not None:
|
|
577
|
+
require_existing_identity(actual, spec.address)
|
|
578
|
+
if not _same_row(actual, spec.expected):
|
|
579
|
+
raise PreCallValidationError(f"{spec.address} changed since this run read it (expected {_describe(spec.expected)}, found {_describe(actual)}); nothing was sent")
|
|
580
|
+
require_rollback_source(spec, ownership, self.ops.get(spec.request[ROLLBACK_OF]) if isinstance(spec.request.get(ROLLBACK_OF), str) else None, actual)
|
|
581
|
+
if actual is not None and actual.status == UNCERTAIN:
|
|
582
|
+
raise QuarantinedError(f"{spec.address} is uncertain (an earlier operation's outcome is unknown); resolve it with `nf state recover` first")
|
|
583
|
+
self._validate_inputs(spec.address, spec.request, ownership.run_id)
|
|
584
|
+
spec.request = bind_operation_request(spec)
|
|
585
|
+
spec.request[FOOTPRINT] = operation_footprint(spec, row.entry if row is not None and not row.version.tombstone else None, actual)
|
|
586
|
+
self._validate_footprint(spec.request[FOOTPRINT], ownership, allocation_scopes=tuple(object_request(spec.request, spec.action).allocation_scopes))
|
|
587
|
+
self._validate_objects(spec.address, spec.request, spec.action, run_id=ownership.run_id)
|
|
588
|
+
self._reservation += 1
|
|
589
|
+
self.ops[spec.op_id] = OperationRecord(
|
|
590
|
+
op_id=spec.op_id,
|
|
591
|
+
run_id=ownership.run_id,
|
|
592
|
+
epoch=ownership.epoch,
|
|
593
|
+
address=spec.address,
|
|
594
|
+
action=spec.action,
|
|
595
|
+
stage=RESERVED,
|
|
596
|
+
expected=spec.expected,
|
|
597
|
+
expected_provider=spec.provider,
|
|
598
|
+
object_identity=actual.object_identity if actual is not None else None,
|
|
599
|
+
request=deepcopy(spec.request),
|
|
600
|
+
request_digest=spec.request_digest,
|
|
601
|
+
footprint=list(spec.footprint),
|
|
602
|
+
owner_host=spec.owner_host,
|
|
603
|
+
owner_pid=spec.owner_pid,
|
|
604
|
+
provider_pid=spec.provider_pid,
|
|
605
|
+
created_at=self.now(),
|
|
606
|
+
reservation=self._reservation,
|
|
607
|
+
)
|
|
608
|
+
|
|
609
|
+
def _owned_op(self, ownership: Ownership, op_id: str, method: str) -> OperationRecord:
|
|
610
|
+
self._fence(ownership, method, recovery=ownership.claim is not None)
|
|
611
|
+
record = self.ops.get(op_id)
|
|
612
|
+
if record is None:
|
|
613
|
+
raise StateError(f"No operation {op_id}")
|
|
614
|
+
ownership.check_operation(record.op_id, record.run_id, record.epoch, record.attempt, record.recovered_by)
|
|
615
|
+
if record.resolved:
|
|
616
|
+
raise StateError(f"Operation {op_id} is already {record.stage}")
|
|
617
|
+
return record
|
|
618
|
+
|
|
619
|
+
def dispatch(self, ownership: Ownership, op_id: str, stage: str = DISPATCHED, *, provider_pid: int | None = None) -> None:
|
|
620
|
+
from netherframe.core.backends.graph_moves import MOVE_GROUP
|
|
621
|
+
|
|
622
|
+
with self._lock:
|
|
623
|
+
self._fault("dispatch")
|
|
624
|
+
record = self._owned_op(ownership, op_id, "dispatch")
|
|
625
|
+
if MOVE_GROUP in record.request:
|
|
626
|
+
raise PreCallValidationError("A state move conversion is read-only and cannot dispatch a provider mutation")
|
|
627
|
+
if ownership.claim is not None:
|
|
628
|
+
raise PreCallValidationError("Recovery resolves old operations; it cannot dispatch a new provider mutation")
|
|
629
|
+
validate_operation_dispatch(record.stage, stage)
|
|
630
|
+
run = self.runs[ownership.run_id]
|
|
631
|
+
if run.admission is not None:
|
|
632
|
+
run.admission.check_operation(OperationSpec(record.op_id, record.address, record.action, record.expected, record.expected_provider or "", record.request, record.footprint))
|
|
633
|
+
row = self.rows.get(record.address)
|
|
634
|
+
require_rollback_source(
|
|
635
|
+
OperationSpec(record.op_id, record.address, record.action, record.expected, record.expected_provider or "", record.request, record.footprint),
|
|
636
|
+
ownership,
|
|
637
|
+
self.ops.get(record.request[ROLLBACK_OF]) if isinstance(record.request.get(ROLLBACK_OF), str) else None,
|
|
638
|
+
row.version if row is not None else None,
|
|
639
|
+
)
|
|
640
|
+
self._validate_footprint(retained_footprint(record), ownership, exclude=(op_id,), allocation_scopes=tuple(object_request(record.request, record.action).allocation_scopes))
|
|
641
|
+
self._validate_inputs(record.address, record.request, ownership.run_id)
|
|
642
|
+
self._validate_objects(record.address, record.request, record.action, exclude_op=op_id, run_id=ownership.run_id)
|
|
643
|
+
self.runs[ownership.run_id].mutation_started = True
|
|
644
|
+
record.stage = stage
|
|
645
|
+
record.dispatched_at = self.now()
|
|
646
|
+
record.result = None
|
|
647
|
+
record.error = None
|
|
648
|
+
if provider_pid is not None:
|
|
649
|
+
record.provider_pid = provider_pid
|
|
650
|
+
|
|
651
|
+
def record_return(self, ownership: Ownership, op_id: str, result: dict[str, Any] | None, error: str | None = None) -> None:
|
|
652
|
+
with self._lock:
|
|
653
|
+
self._fault("record_return")
|
|
654
|
+
record = self._owned_op(ownership, op_id, "record_return")
|
|
655
|
+
if ownership.claim is not None:
|
|
656
|
+
raise PreCallValidationError("A recovery claim cannot replace the original call's returned result")
|
|
657
|
+
self.runs[ownership.run_id].mutation_started = True
|
|
658
|
+
record.result = {"stage": record.stage, "value": result}
|
|
659
|
+
record.error = error
|
|
660
|
+
record.returned_at = self.now()
|
|
661
|
+
record.stage = RETURNED
|
|
662
|
+
|
|
663
|
+
def complete_creations(self, ownership, completions):
|
|
664
|
+
from dataclasses import asdict
|
|
665
|
+
from netherframe.core.backends.graph_completion import CompletionResult, check_cohort, check_record, ready_writes
|
|
666
|
+
from netherframe.core.backends.graph_plan_guard import require_write_contracts
|
|
667
|
+
|
|
668
|
+
items = list(completions)
|
|
669
|
+
check_cohort(ownership, items)
|
|
670
|
+
with self._lock:
|
|
671
|
+
run = self._fence(ownership, "complete creations")
|
|
672
|
+
if run.admission is not None or run.operation != "apply":
|
|
673
|
+
raise PreCallValidationError("Completion requires unadmitted whole-app ownership")
|
|
674
|
+
for item in items:
|
|
675
|
+
record = self._owned_op(ownership, item.identity.op_id, "complete creations")
|
|
676
|
+
check_record(item, asdict(record), record.request)
|
|
677
|
+
fields = ("ops", "rows", "outputs", "observations", "metadata", "history_records", "edge_index", "frontier", "commits")
|
|
678
|
+
before = {name: deepcopy(getattr(self, name)) for name in fields}
|
|
679
|
+
mutation_started = run.mutation_started
|
|
680
|
+
try:
|
|
681
|
+
for item in items:
|
|
682
|
+
self.record_return(ownership, item.identity.op_id, item.result)
|
|
683
|
+
retained = {name: deepcopy(getattr(self, name)) for name in fields}
|
|
684
|
+
writes = []
|
|
685
|
+
try:
|
|
686
|
+
writes = ready_writes(items)
|
|
687
|
+
require_write_contracts(writes)
|
|
688
|
+
resolutions = {}
|
|
689
|
+
for write in writes:
|
|
690
|
+
op_id = write.op_id
|
|
691
|
+
if op_id is None:
|
|
692
|
+
raise PreCallValidationError("Completion publication requires operation-bound creates")
|
|
693
|
+
record = self._owned_op(ownership, op_id, "complete creations")
|
|
694
|
+
if record.stage != RETURNED or record.action != "create" or record.error is not None:
|
|
695
|
+
raise PreCallValidationError("Completion publication requires successful returned creates")
|
|
696
|
+
resolutions[op_id] = COMMITTED
|
|
697
|
+
publication = self.commit(ownership, writes, ops=resolutions) if writes else None
|
|
698
|
+
except Exception as exc:
|
|
699
|
+
for name, value in retained.items():
|
|
700
|
+
setattr(self, name, value)
|
|
701
|
+
result = CompletionResult(writes=tuple(writes), rejection=f"{type(exc).__name__}: {exc}")
|
|
702
|
+
else:
|
|
703
|
+
result = CompletionResult(publication, tuple(writes))
|
|
704
|
+
self._fence(ownership, "complete creations tail")
|
|
705
|
+
except BaseException:
|
|
706
|
+
for name, value in before.items():
|
|
707
|
+
setattr(self, name, value)
|
|
708
|
+
run.mutation_started = mutation_started
|
|
709
|
+
raise
|
|
710
|
+
return result
|
|
711
|
+
|
|
712
|
+
def restore_return(self, ownership: Ownership, kept: KeptReturn) -> None:
|
|
713
|
+
with self._lock:
|
|
714
|
+
self._fault("restore_return")
|
|
715
|
+
if ownership.claim is None:
|
|
716
|
+
raise PreCallValidationError("Restoring a kept response requires its explicit recovery claim")
|
|
717
|
+
record = self._owned_op(ownership, kept.identity.op_id, "restore_return")
|
|
718
|
+
if kept.check(record):
|
|
719
|
+
return
|
|
720
|
+
record.result = deepcopy(kept.envelope)
|
|
721
|
+
record.error = kept.error
|
|
722
|
+
record.returned_at = self.now()
|
|
723
|
+
record.stage = RETURNED
|
|
724
|
+
|
|
725
|
+
def record_recovery_probe(self, ownership: Ownership, op_id: str, probe: Probe, *, quiescence: float | None, confirm_terminated: bool) -> None:
|
|
726
|
+
with self._lock:
|
|
727
|
+
self._fault("record_recovery_probe")
|
|
728
|
+
if ownership.claim is None:
|
|
729
|
+
raise PreCallValidationError("A recovery observation requires its explicit operation claim")
|
|
730
|
+
record = self._owned_op(ownership, op_id, "record recovery probe")
|
|
731
|
+
[current] = self.operations(unresolved=False, op_id=op_id)
|
|
732
|
+
result = recovery_probe_result(current, probe, quiescence=quiescence, confirm_terminated=confirm_terminated)
|
|
733
|
+
record.result = deepcopy(result)
|
|
734
|
+
record.error = None
|
|
735
|
+
record.returned_at = self.now()
|
|
736
|
+
record.stage = RETURNED
|
|
737
|
+
|
|
738
|
+
def _validate_inputs(self, address: str, request: Mapping[str, Any], run_id: str) -> None:
|
|
739
|
+
inputs = decode_inputs(request.get("inputs"))
|
|
740
|
+
if not inputs:
|
|
741
|
+
return
|
|
742
|
+
resources = {key: row.version for key, row in self.rows.items()}
|
|
743
|
+
outputs = {key: row.version for key, row in self.outputs.items()}
|
|
744
|
+
changed = changed_inputs(inputs, resources, outputs, owner=(RESOURCE, address))
|
|
745
|
+
uncertain = [key for key, version in resources.items() if version.status == UNCERTAIN and key != address and any(input_covers(item, RESOURCE, key) for item in inputs)]
|
|
746
|
+
uncertain.extend(key for record in self.ops.values() if not record.resolved and record.run_id != run_id for key in (record.address, *record.footprint) if any(input_covers(item, RESOURCE, key) for item in inputs))
|
|
747
|
+
if changed or uncertain:
|
|
748
|
+
raise PreCallValidationError(f"{address}: consumed inputs changed or are unresolved before dispatch: {', '.join(sorted({item.key for item in changed} | set(uncertain)))}; replan before applying")
|
|
749
|
+
|
|
750
|
+
def _validate_objects(self, address: str, request: Mapping[str, Any], action: str, *, exclude_op: str | None = None, removed: Sequence[str] = (), allow_legacy_normalization: bool = False, run_id: str | None = None) -> None:
|
|
751
|
+
claims = object_request(request, action)
|
|
752
|
+
kinds = {kind for _source, kind in claims.sources}
|
|
753
|
+
candidates = [
|
|
754
|
+
row.entry
|
|
755
|
+
for key, row in self.rows.items()
|
|
756
|
+
if not row.version.tombstone
|
|
757
|
+
and key not in removed
|
|
758
|
+
and (
|
|
759
|
+
key == address
|
|
760
|
+
or row.version.object_identity in claims.identities
|
|
761
|
+
or (row.entry.type in kinds and ((not claims.bound_sources and row.entry.metadata.get(GRAPH_OBJECT) is not None) or (claims.bound_sources and not (row.version.object_identity or "").startswith("nf-object-v1:"))))
|
|
762
|
+
)
|
|
763
|
+
]
|
|
764
|
+
if problems := object_problems(address, request, action, candidates, list(self.ops.values()), exclude_op=exclude_op, allow_legacy_normalization=allow_legacy_normalization, run_id=run_id):
|
|
765
|
+
raise PreCallValidationError("Cloud ownership validation failed:\n" + "\n".join(problems))
|
|
766
|
+
|
|
767
|
+
def _validate_footprint(self, wanted: Mapping[str, str], ownership: Ownership, *, exclude: Sequence[str] = (), recovering: Sequence[str] = (), allocation_scopes: Sequence[str] = ()) -> None:
|
|
768
|
+
held = recovery_footprint(self._owned_op(ownership, ownership.claim.op_id, "validate recovery footprint").request) if ownership.claim is not None else self.leases.get(ownership.run_id, {})
|
|
769
|
+
if missing_leases(held, wanted):
|
|
770
|
+
raise PreCallValidationError("The mutation's full footprint is not covered by the run's granted leases")
|
|
771
|
+
if ownership.claim is None:
|
|
772
|
+
if blocked := conflicting_owned_operations(wanted, list(self.ops.values()), run_id=ownership.run_id, exclude=exclude, allocation_scopes=allocation_scopes):
|
|
773
|
+
raise SiblingOperationBusyError([(record.op_id, record.address) for record in self.ops.values() if record.op_id in blocked])
|
|
774
|
+
if problems := footprint_problems(wanted, list(self.ops.values()), run_id=ownership.run_id, exclude=exclude, recovering=recovering):
|
|
775
|
+
raise QuarantinedError("Mutation blocked by operation quarantine:\n" + "\n".join(problems))
|
|
776
|
+
|
|
777
|
+
def commit(self, ownership: Ownership, writes: Sequence[RowWrite], *, ops: Mapping[str, str] | None = None, outcome: str | None = None) -> CommitResult:
|
|
778
|
+
return self._commit(ownership, writes, ops=ops, outcome=outcome)
|
|
779
|
+
|
|
780
|
+
def _commit(self, ownership: Ownership, writes: Sequence[RowWrite], *, ops: Mapping[str, str] | None = None, outcome: str | None = None, restoring: bool = False, migrating: bool = False) -> CommitResult:
|
|
781
|
+
from netherframe.core.backends.graph_moves import MOVE_GROUP, check_move_commit, move_targets
|
|
782
|
+
|
|
783
|
+
with self._lock:
|
|
784
|
+
self._fault("commit")
|
|
785
|
+
run = self._fence(ownership, "commit", recovery=ownership.claim is not None, restoring=restoring, migrating=migrating)
|
|
786
|
+
if ownership.claim is None and run.admission is not None:
|
|
787
|
+
run.admission.check_writes(writes)
|
|
788
|
+
validate_recovery_writes(ownership, writes, ops or {})
|
|
789
|
+
records = {op_id: self._owned_op(ownership, op_id, "commit") for op_id in ops or {}}
|
|
790
|
+
for op_id, record in records.items():
|
|
791
|
+
validate_operation_resolution(record.stage, (ops or {})[op_id], action=record.action)
|
|
792
|
+
if any(MOVE_GROUP in record.request and (ops or {}).get(op_id) != COMMITTED for op_id, record in records.items()):
|
|
793
|
+
raise StateError("An atomic move must resolve as committed")
|
|
794
|
+
moving = check_move_commit(records, writes, self.snapshot()) if any(MOVE_GROUP in record.request for record in records.values()) else set()
|
|
795
|
+
validate_write_operations(writes, {op_id: [record.address, *record.footprint] for op_id, record in records.items()}, move_targets(records))
|
|
796
|
+
ordered = sorted(writes, key=lambda write: not write.removal)
|
|
797
|
+
demands = []
|
|
798
|
+
for write in ordered:
|
|
799
|
+
old = (self.outputs if write.kind == OUTPUT else self.rows).get(write.key)
|
|
800
|
+
if ownership.claim is None and run.admission is not None and write.kind == RESOURCE:
|
|
801
|
+
require_existing_identity(old.version if old is not None else None, write.key)
|
|
802
|
+
demands.append(
|
|
803
|
+
write_footprint(
|
|
804
|
+
write, old.entry if old is not None and write.kind == RESOURCE and not old.version.tombstone else None, old.version if old is not None else None, action=records[write.op_id].action if write.op_id in records else None
|
|
805
|
+
)
|
|
806
|
+
)
|
|
807
|
+
if demands:
|
|
808
|
+
self._validate_footprint(combine_footprints(demands), ownership, exclude=tuple(records), recovering=tuple(records))
|
|
809
|
+
# Check everything before writing anything
|
|
810
|
+
for write in ordered:
|
|
811
|
+
if write.kind in {RESOURCE, OUTPUT}:
|
|
812
|
+
prior = (self.outputs if write.kind == OUTPUT else self.rows).get(write.key)
|
|
813
|
+
intent = (prior.version.intent_fp if prior else None) if write.intent_fp is UNCHECKED else write.intent_fp
|
|
814
|
+
bind_planning_context(write.planning_context, (prior.version.revision if prior else 0) + 1, intent, removal=write.removal)
|
|
815
|
+
if write.kind == RESOURCE:
|
|
816
|
+
holder = self._holding(write.key, other_than=write.op_id, run_id=ownership.run_id)
|
|
817
|
+
if holder is not None and holder.op_id not in records:
|
|
818
|
+
raise QuarantinedError(f"{write.key} is held by unresolved operation {holder.summary()}")
|
|
819
|
+
if write.expected is UNCHECKED:
|
|
820
|
+
continue
|
|
821
|
+
table = self.outputs if write.kind == OUTPUT else self.rows
|
|
822
|
+
row = table.get(write.key)
|
|
823
|
+
if not _same_row(row.version if row else None, write.expected, statuses=False):
|
|
824
|
+
raise StateConflictError(f"{write.key} changed since this run read it (expected {_describe(write.expected)}, found {_describe(row.version if row else None)}); not written")
|
|
825
|
+
for write in ordered:
|
|
826
|
+
if write.kind != RESOURCE or write.removal or write.key in moving:
|
|
827
|
+
continue
|
|
828
|
+
old = self.rows.get(write.key)
|
|
829
|
+
normalizing = (
|
|
830
|
+
write.op_id is None
|
|
831
|
+
and old is not None
|
|
832
|
+
and old.entry is not None
|
|
833
|
+
and locator_of(old.entry.metadata, old.entry.type) is None
|
|
834
|
+
and stored_values_equal(old.entry.attributes, write.entry.attributes)
|
|
835
|
+
and stored_values_equal(old.entry.identity, write.entry.identity)
|
|
836
|
+
and old.entry.provider == write.entry.provider
|
|
837
|
+
and old.entry.private == write.entry.private
|
|
838
|
+
)
|
|
839
|
+
action = "import" if write.op_id is None and (old is None or old.version.tombstone) else "state"
|
|
840
|
+
self._validate_objects(
|
|
841
|
+
write.key,
|
|
842
|
+
{"template": write.entry.to_dict()},
|
|
843
|
+
action,
|
|
844
|
+
exclude_op=write.op_id,
|
|
845
|
+
removed=[item.key for item in ordered if item.kind == RESOURCE and item.removal],
|
|
846
|
+
allow_legacy_normalization=normalizing,
|
|
847
|
+
run_id=ownership.run_id,
|
|
848
|
+
)
|
|
849
|
+
identities: dict[str, str] = {key: row.version.object_identity for key, row in self.rows.items() if row.version.object_identity and not row.version.tombstone}
|
|
850
|
+
for key in moving:
|
|
851
|
+
identities.pop(key, None)
|
|
852
|
+
for write in ordered:
|
|
853
|
+
if write.kind != RESOURCE:
|
|
854
|
+
continue
|
|
855
|
+
identities.pop(write.key, None)
|
|
856
|
+
identity = object_identity(write.entry) if not write.removal else None
|
|
857
|
+
if identity is not None:
|
|
858
|
+
other = next((key for key, held in identities.items() if held == identity), None)
|
|
859
|
+
if other is not None:
|
|
860
|
+
raise StateConflictError(f"{write.key} and {other} would manage the same object ({identity}); two addresses can never manage one object")
|
|
861
|
+
identities[write.key] = identity
|
|
862
|
+
next_edges = self.edge_index
|
|
863
|
+
for write in ordered:
|
|
864
|
+
if write.kind not in {RESOURCE, OUTPUT}:
|
|
865
|
+
continue
|
|
866
|
+
row = (self.outputs if write.kind == OUTPUT else self.rows).get(write.key)
|
|
867
|
+
inputs = (row.version.inputs if row else None) if write.inputs is UNCHECKED else write.inputs
|
|
868
|
+
dependencies = write.entry.dependencies if write.kind == RESOURCE and write.entry is not None else ()
|
|
869
|
+
targets = targets_of(inputs, dependencies) if not write.removal else ()
|
|
870
|
+
next_edges = next_edges.replace(write.kind, write.key, targets)
|
|
871
|
+
self.frontier += 1
|
|
872
|
+
sequence = self.frontier
|
|
873
|
+
result = CommitResult(sequence)
|
|
874
|
+
for write in ordered:
|
|
875
|
+
if write.kind == METADATA:
|
|
876
|
+
self.metadata = dict(write.entry or {})
|
|
877
|
+
continue
|
|
878
|
+
if write.kind == OBSERVATION:
|
|
879
|
+
if write.removal:
|
|
880
|
+
self.observations.pop(write.key, None)
|
|
881
|
+
else:
|
|
882
|
+
self.observations[write.key] = write.entry.copy()
|
|
883
|
+
continue
|
|
884
|
+
table = self.outputs if write.kind == OUTPUT else self.rows
|
|
885
|
+
old = table.get(write.key)
|
|
886
|
+
revision = (old.version.revision if old else 0) + 1
|
|
887
|
+
incarnation = old.version.incarnation if old else 0
|
|
888
|
+
intent_fp = (old.version.intent_fp if old else None) if write.intent_fp is UNCHECKED else write.intent_fp
|
|
889
|
+
inputs = (old.version.inputs if old else None) if write.inputs is UNCHECKED else write.inputs
|
|
890
|
+
applied_fp = (old.version.applied_fp if old else None) if write.applied_fp is UNCHECKED else write.applied_fp
|
|
891
|
+
status = effective_status(
|
|
892
|
+
write.status, old.version if old else None, tainted=bool(write.kind == RESOURCE and write.entry is not None and write.entry.tainted), evaluated=write.inputs is not UNCHECKED and write.inputs is not None
|
|
893
|
+
)
|
|
894
|
+
if write.kind == OUTPUT:
|
|
895
|
+
version = RowVersion(revision, incarnation, status=status, tombstone=write.removal, intent_fp=intent_fp, inputs=inputs, applied_fp=applied_fp, value_fp=value_fingerprint(write.entry))
|
|
896
|
+
elif write.removal:
|
|
897
|
+
version = (
|
|
898
|
+
replace(old.version, revision=revision, tombstone=True, status="ready", object_identity=None, private_digest="", intent_fp=intent_fp, value_fp=value_fingerprint([None, old.version.provider, ""]))
|
|
899
|
+
if old
|
|
900
|
+
else RowVersion(revision, incarnation, tombstone=True, intent_fp=intent_fp, value_fp=value_fingerprint([None, "", ""]))
|
|
901
|
+
)
|
|
902
|
+
else:
|
|
903
|
+
entry: ResourceState = write.entry
|
|
904
|
+
if write.new_incarnation or old is None:
|
|
905
|
+
incarnation += 1
|
|
906
|
+
version = RowVersion(
|
|
907
|
+
revision,
|
|
908
|
+
incarnation,
|
|
909
|
+
status,
|
|
910
|
+
entry.provider,
|
|
911
|
+
private_digest(entry.private),
|
|
912
|
+
object_identity(entry),
|
|
913
|
+
intent_fp=intent_fp,
|
|
914
|
+
inputs=inputs,
|
|
915
|
+
applied_fp=applied_fp,
|
|
916
|
+
value_fp=value_fingerprint([entry.attributes, entry.provider, private_digest(entry.private)]),
|
|
917
|
+
)
|
|
918
|
+
stored = None if write.removal else (write.entry.copy() if write.kind == RESOURCE else write.entry)
|
|
919
|
+
version = replace(
|
|
920
|
+
version,
|
|
921
|
+
run_id=ownership.run_id,
|
|
922
|
+
mutation_revision=(revision if write.op_id is not None else old.version.mutation_revision if old else 0) if write.kind == RESOURCE else 0,
|
|
923
|
+
planning_context=bind_planning_context(write.planning_context, revision, intent_fp, removal=write.removal),
|
|
924
|
+
)
|
|
925
|
+
if write.kind == RESOURCE:
|
|
926
|
+
old_value = [old.entry.attributes if old and old.entry is not None else None, old.version.provider, old.version.private_digest, old.version.incarnation, old.version.tombstone] if old else None
|
|
927
|
+
new_value = [stored.attributes if stored is not None else None, version.provider, version.private_digest, version.incarnation, version.tombstone]
|
|
928
|
+
else:
|
|
929
|
+
old_value = [old.entry, old.version.tombstone] if old else None
|
|
930
|
+
new_value = [stored, version.tombstone]
|
|
931
|
+
version = semantic_revisions(old.version if old else None, version, value_changed=not stored_values_equal(old_value, new_value))
|
|
932
|
+
table[write.key] = _Row(version, stored)
|
|
933
|
+
result.versions[write.kind, write.key] = version
|
|
934
|
+
self.history_records.append(
|
|
935
|
+
HistoryRecord(
|
|
936
|
+
write.kind,
|
|
937
|
+
write.key,
|
|
938
|
+
revision,
|
|
939
|
+
sequence,
|
|
940
|
+
ownership.run_id,
|
|
941
|
+
write.op_id,
|
|
942
|
+
write.removal,
|
|
943
|
+
self.now(),
|
|
944
|
+
row=(stored.to_dict() if isinstance(stored, ResourceState) else stored),
|
|
945
|
+
intent_fp=version.intent_fp,
|
|
946
|
+
inputs=version.inputs,
|
|
947
|
+
applied_fp=version.applied_fp,
|
|
948
|
+
status=version.status,
|
|
949
|
+
mutation_revision=version.mutation_revision,
|
|
950
|
+
value_revision=version.value_revision,
|
|
951
|
+
membership_revision=version.membership_revision,
|
|
952
|
+
planning_context=version.planning_context,
|
|
953
|
+
sensitive_paths=tuple(tuple(path) for path in write.sensitive_paths),
|
|
954
|
+
),
|
|
955
|
+
)
|
|
956
|
+
excluded: set[tuple[str, str]] = set()
|
|
957
|
+
while result.versions:
|
|
958
|
+
resources = {key: row.version for key, row in self.rows.items()}
|
|
959
|
+
outputs = {key: row.version for key, row in self.outputs.items()}
|
|
960
|
+
stale = [
|
|
961
|
+
(kind, key, row)
|
|
962
|
+
for kind, table in ((RESOURCE, self.rows), (OUTPUT, self.outputs))
|
|
963
|
+
for key, row in table.items()
|
|
964
|
+
if (kind, key) not in excluded and row.version.live and row.version.status == "ready" and changed_inputs(row.version.inputs, resources, outputs, owner=(kind, key))
|
|
965
|
+
]
|
|
966
|
+
if not stale:
|
|
967
|
+
break
|
|
968
|
+
for kind, key, row in stale:
|
|
969
|
+
sensitive_paths = next((record.sensitive_paths for record in reversed(self.history_records) if (record.kind, record.key, record.revision) == (kind, key, row.version.revision)), ())
|
|
970
|
+
row.version = replace(row.version, revision=row.version.revision + 1, status=STALE_INPUTS, run_id=ownership.run_id, planning_context=None)
|
|
971
|
+
result.versions[kind, key] = row.version
|
|
972
|
+
excluded.add((kind, key))
|
|
973
|
+
value = row.entry.to_dict() if kind == RESOURCE else row.entry
|
|
974
|
+
self.history_records.append(
|
|
975
|
+
HistoryRecord(
|
|
976
|
+
kind,
|
|
977
|
+
key,
|
|
978
|
+
row.version.revision,
|
|
979
|
+
sequence,
|
|
980
|
+
ownership.run_id,
|
|
981
|
+
None,
|
|
982
|
+
False,
|
|
983
|
+
self.now(),
|
|
984
|
+
row=value,
|
|
985
|
+
intent_fp=row.version.intent_fp,
|
|
986
|
+
inputs=row.version.inputs,
|
|
987
|
+
applied_fp=row.version.applied_fp,
|
|
988
|
+
status=row.version.status,
|
|
989
|
+
sensitive_paths=sensitive_paths,
|
|
990
|
+
mutation_revision=row.version.mutation_revision,
|
|
991
|
+
value_revision=row.version.value_revision,
|
|
992
|
+
membership_revision=row.version.membership_revision,
|
|
993
|
+
)
|
|
994
|
+
)
|
|
995
|
+
for op_id, stage in (ops or {}).items():
|
|
996
|
+
record = records[op_id]
|
|
997
|
+
record.stage = stage
|
|
998
|
+
if stage in FINAL_STAGES:
|
|
999
|
+
record.resolved_at = self.now()
|
|
1000
|
+
record.outcome = outcome or f"committed at sequence {sequence}"
|
|
1001
|
+
self.commits.append((sequence, ownership.run_id, self.now(), run.expires_at, run.epoch))
|
|
1002
|
+
run.mutation_started = True
|
|
1003
|
+
result.edge_delta = self.edge_index.delta_to(next_edges)
|
|
1004
|
+
self.edge_index = next_edges
|
|
1005
|
+
return result
|
|
1006
|
+
|
|
1007
|
+
def abort(self, ownership: Ownership, op_id: str, reason: str) -> None:
|
|
1008
|
+
from netherframe.core.backends.graph_moves import move_original_status
|
|
1009
|
+
|
|
1010
|
+
with self._lock:
|
|
1011
|
+
self._fault("abort")
|
|
1012
|
+
record = self._owned_op(ownership, op_id, "abort")
|
|
1013
|
+
validate_operation_resolution(record.stage, ABORTED, action=record.action)
|
|
1014
|
+
original_status = move_original_status(record)
|
|
1015
|
+
if not has_input_provenance(record.request) and original_status in {None, "ready"}:
|
|
1016
|
+
original_status = "unconverged"
|
|
1017
|
+
record.stage = ABORTED
|
|
1018
|
+
record.outcome = reason
|
|
1019
|
+
record.resolved_at = self.now()
|
|
1020
|
+
row = self.rows.get(record.address)
|
|
1021
|
+
if row is not None and row.version.status == UNCERTAIN and self._holding(record.address) is None:
|
|
1022
|
+
row.version = replace(row.version, status="tainted" if row.entry is not None and row.entry.tainted else original_status or (entry_status(row.entry) if row.entry is not None else "ready"))
|
|
1023
|
+
|
|
1024
|
+
def mark_uncertain(self, ownership: Ownership, op_id: str, reason: str) -> None:
|
|
1025
|
+
with self._lock:
|
|
1026
|
+
self._fault("mark_uncertain")
|
|
1027
|
+
record = self._owned_op(ownership, op_id, "mark_uncertain")
|
|
1028
|
+
record.outcome = f"outcome unknown: {reason}"
|
|
1029
|
+
row = self.rows.get(record.address)
|
|
1030
|
+
if row is not None and not row.version.tombstone:
|
|
1031
|
+
row.version = replace(row.version, status=UNCERTAIN)
|
|
1032
|
+
|
|
1033
|
+
def operations(self, *, unresolved: bool = True, op_id: str | None = None) -> list[OperationRecord]:
|
|
1034
|
+
with self._lock:
|
|
1035
|
+
records = self.ops.values() if op_id is None else [self.ops[op_id]] if op_id in self.ops else []
|
|
1036
|
+
return [self._view(record) for record in records if not unresolved or not record.resolved]
|
|
1037
|
+
|
|
1038
|
+
def _view(self, record: OperationRecord) -> OperationRecord:
|
|
1039
|
+
run = self.runs.get(record.run_id)
|
|
1040
|
+
now = self.now()
|
|
1041
|
+
return replace(
|
|
1042
|
+
record,
|
|
1043
|
+
dispatched_for=(now - record.dispatched_at) if record.dispatched_at is not None else None,
|
|
1044
|
+
owner_status=run.status if run else None,
|
|
1045
|
+
owner_live=bool(run and run.status == ACTIVE and run.expires_at > now and self.holder == run.run_id),
|
|
1046
|
+
owner_providers_killed=bool(run and run.providers_killed),
|
|
1047
|
+
footprint=list(record.footprint),
|
|
1048
|
+
request=deepcopy(record.request),
|
|
1049
|
+
result=deepcopy(record.result),
|
|
1050
|
+
)
|
|
1051
|
+
|
|
1052
|
+
def take_over(self, ownership: Ownership, op_id: str) -> OperationRecord:
|
|
1053
|
+
with self._lock:
|
|
1054
|
+
self._fault("take_over")
|
|
1055
|
+
if ownership.claim is not None:
|
|
1056
|
+
raise PreCallValidationError("An existing recovery claim cannot take ownership of another operation")
|
|
1057
|
+
self._fence(ownership, "take_over", recovery=True)
|
|
1058
|
+
record = self.ops.get(op_id)
|
|
1059
|
+
if record is None:
|
|
1060
|
+
raise StateError(f"No operation {op_id}")
|
|
1061
|
+
if record.resolved:
|
|
1062
|
+
return self._view(record)
|
|
1063
|
+
holders = {record.run_id}
|
|
1064
|
+
if record.recovered_by is not None and record.recovered_by != ownership.run_id:
|
|
1065
|
+
holders.add(record.recovered_by)
|
|
1066
|
+
for holder in holders:
|
|
1067
|
+
owner = self.runs.get(holder)
|
|
1068
|
+
if owner is not None and owner.status == ACTIVE and owner.expires_at > self.now():
|
|
1069
|
+
raise StateLockError(f"Operation {op_id} belongs to run {owner.run_id}, whose ownership is live")
|
|
1070
|
+
record.epoch += 1
|
|
1071
|
+
record.attempt += 1
|
|
1072
|
+
record.recovered_by = ownership.run_id
|
|
1073
|
+
return self._view(record)
|
|
1074
|
+
|
|
1075
|
+
# -- history -----------------------------------------------------------------------
|
|
1076
|
+
|
|
1077
|
+
def _checkpoint_images(self, checkpoint: GraphCheckpoint) -> dict[tuple[str, str], RowWrite]:
|
|
1078
|
+
checkpoint.check_scope(self.get_backend_type(), self.state_id, self.lineage)
|
|
1079
|
+
images = {}
|
|
1080
|
+
for target in checkpoint.targets:
|
|
1081
|
+
record = next((row for row in self.history_records if (row.kind, row.key, row.revision) == (target.kind, target.key, target.revision)), None)
|
|
1082
|
+
if target.revision and record is None:
|
|
1083
|
+
raise StateError(f"{target.key}: its pinned checkpoint version is missing; restore refused")
|
|
1084
|
+
images[target.kind, target.key] = before_image(target.kind, target.key, record)
|
|
1085
|
+
return images
|
|
1086
|
+
|
|
1087
|
+
def _checkpoint(self, reference: str) -> GraphCheckpoint:
|
|
1088
|
+
checkpoint = self.checkpoints.get(checkpoint_id(reference))
|
|
1089
|
+
if checkpoint is None:
|
|
1090
|
+
raise StateError("This checkpoint is not retained in this graph state")
|
|
1091
|
+
checkpoint.check_scope(self.get_backend_type(), self.state_id, self.lineage)
|
|
1092
|
+
return checkpoint
|
|
1093
|
+
|
|
1094
|
+
def create_history_checkpoint(self, ownership: Ownership, targets: Sequence[tuple[str, str]], *, name: str, keep: int = 5) -> GraphCheckpoint:
|
|
1095
|
+
with self._lock:
|
|
1096
|
+
run = self._fence(ownership, "checkpoint")
|
|
1097
|
+
if type(keep) is not int or keep < 1:
|
|
1098
|
+
raise StateError("Keep at least one history checkpoint")
|
|
1099
|
+
if run.mutation_started or any(not record.resolved and record.run_id == ownership.run_id for record in self.ops.values()):
|
|
1100
|
+
raise PreCallValidationError("Capture a checkpoint before reserving calls or mutating state")
|
|
1101
|
+
targets = checked_targets(targets)
|
|
1102
|
+
if run.admission is not None:
|
|
1103
|
+
run.admission.check_targets(targets)
|
|
1104
|
+
demands = normalized({LeaseKey.entry(key): X for _kind, key in targets})
|
|
1105
|
+
self._validate_footprint(demands, ownership)
|
|
1106
|
+
pinned = []
|
|
1107
|
+
for kind, key in targets:
|
|
1108
|
+
row = (self.outputs if kind == OUTPUT else self.rows).get(key)
|
|
1109
|
+
version = row.version if row is not None else None
|
|
1110
|
+
record = next((row for row in reversed(self.history_records) if (row.kind, row.key, row.revision) == (kind, key, version.revision if version else 0)), None)
|
|
1111
|
+
if version is not None and record is None:
|
|
1112
|
+
raise StateError(f"{key}: current history is incomplete; checkpoint refused")
|
|
1113
|
+
image = before_image(kind, key, record)
|
|
1114
|
+
pinned.append(CheckpointTarget(kind, key, version.revision if version else 0, image_digest(image)))
|
|
1115
|
+
checkpoint = GraphCheckpoint(self.get_backend_type(), self.state_id, self.lineage, uuid.uuid4().hex, name, ownership.run_id, self.frontier, self._reservation, tuple(pinned))
|
|
1116
|
+
self.checkpoints[checkpoint.checkpoint_id] = checkpoint
|
|
1117
|
+
self._checkpoint_keep = keep
|
|
1118
|
+
self._prune_checkpoints()
|
|
1119
|
+
return checkpoint
|
|
1120
|
+
|
|
1121
|
+
def _prune_checkpoints(self) -> None:
|
|
1122
|
+
for key in self._prunable_checkpoints():
|
|
1123
|
+
self.checkpoints.pop(key)
|
|
1124
|
+
|
|
1125
|
+
def _prunable_checkpoints(self) -> set[str]:
|
|
1126
|
+
protected = {record.run_id for record in self.ops.values() if not record.resolved}
|
|
1127
|
+
protected.update(run_id for run_id, active in self.runs.items() if active.status == ACTIVE and active.expires_at > self.now())
|
|
1128
|
+
in_use = {receipt[0] for run_id, receipt in self.restore_receipts.items() if run_id in protected}
|
|
1129
|
+
older = list(self.checkpoints.values())[: -self._checkpoint_keep]
|
|
1130
|
+
return {old.checkpoint_id for old in older if old.run_id not in protected and old.checkpoint_id not in in_use}
|
|
1131
|
+
|
|
1132
|
+
def history_checkpoints(self) -> list[GraphCheckpoint]:
|
|
1133
|
+
with self._lock:
|
|
1134
|
+
return list(reversed(self.checkpoints.values()))
|
|
1135
|
+
|
|
1136
|
+
def prepare_history_restore(self, reference: str) -> CheckpointRestorePreview:
|
|
1137
|
+
with self._lock:
|
|
1138
|
+
checkpoint = self._checkpoint(reference)
|
|
1139
|
+
snapshot = self.snapshot()
|
|
1140
|
+
writes = restore_writes(checkpoint, self._checkpoint_images(checkpoint), snapshot)
|
|
1141
|
+
blockers = restore_blockers(checkpoint, writes, snapshot, self.history_records, list(self.ops.values()))
|
|
1142
|
+
return CheckpointRestorePreview(checkpoint, restore_leases(writes, snapshot), blockers)
|
|
1143
|
+
|
|
1144
|
+
def history_restore_receipt(self, run_id: str, reference: str, *, force: bool = False) -> int | None:
|
|
1145
|
+
with self._lock:
|
|
1146
|
+
receipt = self.restore_receipts.get(run_id)
|
|
1147
|
+
if receipt is None:
|
|
1148
|
+
return None
|
|
1149
|
+
if receipt[:2] != (checkpoint_id(reference), force) or type(force) is not bool:
|
|
1150
|
+
raise StateError("A restore run's checkpoint and force policy cannot change")
|
|
1151
|
+
return receipt[2]
|
|
1152
|
+
|
|
1153
|
+
def restore_history_checkpoint(self, ownership: Ownership, reference: str, *, force: bool = False) -> int:
|
|
1154
|
+
with self._lock:
|
|
1155
|
+
if (receipt := self.history_restore_receipt(ownership.run_id, reference, force=force)) is not None:
|
|
1156
|
+
return receipt
|
|
1157
|
+
self._fence(ownership, "restore checkpoint", restoring=True)
|
|
1158
|
+
checkpoint = self._checkpoint(reference)
|
|
1159
|
+
snapshot = self.snapshot()
|
|
1160
|
+
writes = restore_writes(checkpoint, self._checkpoint_images(checkpoint), snapshot)
|
|
1161
|
+
self._validate_footprint(restore_leases(writes, snapshot), ownership)
|
|
1162
|
+
require_restore_identities(writes, snapshot)
|
|
1163
|
+
require_no_restore_blockers(restore_blockers(checkpoint, writes, snapshot, self.history_records, list(self.ops.values())), force=force)
|
|
1164
|
+
sequence = self._commit(ownership, writes, restoring=True).sequence if writes else self.frontier
|
|
1165
|
+
self.restore_receipts[ownership.run_id] = (checkpoint.checkpoint_id, force, sequence)
|
|
1166
|
+
self._fault("restore_ack")
|
|
1167
|
+
return sequence
|
|
1168
|
+
|
|
1169
|
+
def pin_baseline(self, *, sequence: int | None = None, run_id: str | None = None) -> GraphBaseline:
|
|
1170
|
+
with self._lock:
|
|
1171
|
+
if sequence is not None and run_id is not None:
|
|
1172
|
+
raise StateError("A baseline names a sequence or a run, not both")
|
|
1173
|
+
if run_id is not None:
|
|
1174
|
+
commits = [commit[0] for commit in self.commits if commit[1] == run_id]
|
|
1175
|
+
if not commits:
|
|
1176
|
+
raise StateError(f"Run {run_id} has no committed state in this app")
|
|
1177
|
+
sequence = max(commits)
|
|
1178
|
+
sequence = self.frontier if sequence is None else sequence
|
|
1179
|
+
if type(sequence) is not int or not 0 <= sequence <= self.frontier:
|
|
1180
|
+
raise StateError(f"Baseline sequence must be between 0 and the frontier ({self.frontier})")
|
|
1181
|
+
self._check_history(sequence)
|
|
1182
|
+
origin = self._intent_records(sequence)
|
|
1183
|
+
require_known_intents(origin)
|
|
1184
|
+
baseline = GraphBaseline(self.get_backend_type(), self.state_id, self.lineage, sequence, uuid.uuid4().hex)
|
|
1185
|
+
self.baselines[baseline.pin_id] = baseline
|
|
1186
|
+
self._baseline_records[baseline.pin_id] = origin
|
|
1187
|
+
return baseline
|
|
1188
|
+
|
|
1189
|
+
def baseline_intents(self, baseline: GraphBaseline) -> list[IntentRecord]:
|
|
1190
|
+
with self._lock:
|
|
1191
|
+
baseline.check_scope(self.get_backend_type(), self.state_id, self.lineage)
|
|
1192
|
+
if self.baselines.get(baseline.pin_id) != baseline:
|
|
1193
|
+
raise StateError("This baseline is no longer pinned, or its reference was changed; pin a valid baseline")
|
|
1194
|
+
records = self._intent_records(baseline.sequence)
|
|
1195
|
+
if intent_snapshot_digest(records) != intent_snapshot_digest(self._baseline_records[baseline.pin_id]):
|
|
1196
|
+
raise StateError("The baseline's retained intent history is incomplete")
|
|
1197
|
+
return records
|
|
1198
|
+
|
|
1199
|
+
def known_intent_run(self, key: str, intent_fp: str | None, *, kind: str = RESOURCE, sequence: int | None = None) -> str | None:
|
|
1200
|
+
with self._lock:
|
|
1201
|
+
for record in reversed(self.history_records):
|
|
1202
|
+
if (sequence is None or record.sequence <= sequence) and (record.kind, record.key) == (kind, key) and (record.tombstone if intent_fp is None else not record.tombstone and record.intent_fp == intent_fp):
|
|
1203
|
+
return record.run_id or "unknown"
|
|
1204
|
+
return None
|
|
1205
|
+
|
|
1206
|
+
def unpin_baseline(self, pin_id: str) -> bool:
|
|
1207
|
+
with self._lock:
|
|
1208
|
+
if any((origin := run.baseline or (run.admission.baseline if run.admission else None)) is not None and origin.pin_id == pin_id and run.status == ACTIVE and run.expires_at > self.now() for run in self.runs.values()):
|
|
1209
|
+
raise StateLockError("An active run still uses this baseline; end its run before unpinning it")
|
|
1210
|
+
if self.baselines.pop(pin_id, None) is None:
|
|
1211
|
+
return False
|
|
1212
|
+
self._baseline_records.pop(pin_id, None)
|
|
1213
|
+
return True
|
|
1214
|
+
|
|
1215
|
+
def record_run_baseline(self, ownership: Ownership, baseline: GraphBaseline) -> None:
|
|
1216
|
+
with self._lock:
|
|
1217
|
+
run = self._queue_run(ownership)
|
|
1218
|
+
if ownership.claim is not None or run.operation == "recover":
|
|
1219
|
+
raise StateLockError("Recovery cannot change the original run's baseline")
|
|
1220
|
+
previous = run.baseline or (run.admission.baseline if run.admission else None)
|
|
1221
|
+
if previous == baseline:
|
|
1222
|
+
return
|
|
1223
|
+
if previous is not None:
|
|
1224
|
+
raise StateLockError("A run's baseline is immutable; end the run before changing it")
|
|
1225
|
+
if run.mutation_started or any(not record.resolved and ownership.run_id in {record.run_id, record.recovered_by} for record in self.ops.values()):
|
|
1226
|
+
raise StateLockError("Record the baseline before reserving operations or mutating state")
|
|
1227
|
+
self.baseline_intents(baseline)
|
|
1228
|
+
run.baseline = baseline
|
|
1229
|
+
|
|
1230
|
+
def _history_context(self, record: HistoryRecord) -> HistoryRecord:
|
|
1231
|
+
run = self.runs.get(record.run_id) if record.run_id else None
|
|
1232
|
+
if run is None:
|
|
1233
|
+
return record
|
|
1234
|
+
return replace(record, operation=run.operation, actor=run.info.get("user") or run.info.get("Who"), baseline=run.baseline or (run.admission.baseline if run.admission else None))
|
|
1235
|
+
|
|
1236
|
+
def history(self, address: str | None = None, *, limit: int = 100) -> list[HistoryRecord]:
|
|
1237
|
+
with self._lock:
|
|
1238
|
+
records = [record for record in self.history_records if address is None or record.key == address]
|
|
1239
|
+
return [self._history_context(record) for record in list(reversed(records))[:limit]]
|
|
1240
|
+
|
|
1241
|
+
def history_page(self, address: str | None = None, *, run_id: str | None = None, since: int = 0, limit: int = 100, cursor: str | None = None) -> HistoryPage:
|
|
1242
|
+
with self._lock:
|
|
1243
|
+
query = HistoryQuery.read((self.get_backend_type(), self.state_id, self.lineage), self.frontier, self.history_epoch, address=address, run_id=run_id, since=since, limit=limit, cursor=cursor)
|
|
1244
|
+
rows = [
|
|
1245
|
+
record
|
|
1246
|
+
for record in self.history_records
|
|
1247
|
+
if record.sequence <= query.frontier and record.sequence >= since and (address is None or record.key == address) and (run_id is None or record.run_id == run_id) and (query.after is None or position(record) > query.after)
|
|
1248
|
+
]
|
|
1249
|
+
rows.sort(key=position)
|
|
1250
|
+
records = [self._history_context(record) for record in rows[: limit + 1]]
|
|
1251
|
+
return query.page(records)
|
|
1252
|
+
|
|
1253
|
+
def _intent_records(self, sequence: int) -> list[IntentRecord]:
|
|
1254
|
+
records = {}
|
|
1255
|
+
for row in sorted(self.history_records, key=lambda row: (row.sequence, row.revision)):
|
|
1256
|
+
if row.sequence <= sequence:
|
|
1257
|
+
records[row.kind, row.key] = IntentRecord(row.kind, row.key, row.revision, row.sequence, row.intent_fp, row.tombstone, row.run_id)
|
|
1258
|
+
return list(records.values())
|
|
1259
|
+
|
|
1260
|
+
def _check_history(self, sequence: int) -> None:
|
|
1261
|
+
pins = [baseline for baseline in self.baselines.values() if baseline.sequence == sequence]
|
|
1262
|
+
if 0 < sequence <= self.pruned_before and not pins:
|
|
1263
|
+
raise StateError(f"History through sequence {self.pruned_before} was pruned; this frontier cannot be shown whole")
|
|
1264
|
+
records = self._intent_records(sequence)
|
|
1265
|
+
if any(intent_snapshot_digest(records) != intent_snapshot_digest(self._baseline_records[pin.pin_id]) for pin in pins):
|
|
1266
|
+
raise StateError("The pinned history is incomplete")
|
|
1267
|
+
if sequence == self.frontier:
|
|
1268
|
+
current = {(kind, key, row.version.revision) for kind, table in ((RESOURCE, self.rows), (OUTPUT, self.outputs)) for key, row in table.items()}
|
|
1269
|
+
if current != {(record.kind, record.key, record.revision) for record in records}:
|
|
1270
|
+
raise StateError("The current state's intent history is incomplete")
|
|
1271
|
+
|
|
1272
|
+
def _retention(self, days: int, preview: HistoryRetention | None = None):
|
|
1273
|
+
now = self.now()
|
|
1274
|
+
cutoff, frontier = (preview.cutoff, preview.frontier) if preview is not None else (now - days * 86400, self.frontier)
|
|
1275
|
+
if preview is not None:
|
|
1276
|
+
preview.check(self.get_backend_type(), self.state_id, self.lineage, now, self.frontier)
|
|
1277
|
+
dropped = self._prunable_checkpoints()
|
|
1278
|
+
checkpoints = [item for key, item in self.checkpoints.items() if key not in dropped and item.targets]
|
|
1279
|
+
pinned = {(item.kind, item.key, item.revision) for checkpoint in checkpoints for item in checkpoint.targets}
|
|
1280
|
+
pinned.update((record.kind, record.key, record.revision) for pin in self.baselines.values() for record in self._intent_records(pin.sequence))
|
|
1281
|
+
boundary = {}
|
|
1282
|
+
for row in self.history_records:
|
|
1283
|
+
if row.committed_at < cutoff:
|
|
1284
|
+
boundary[row.kind, row.key] = max(boundary.get((row.kind, row.key), 0), row.revision)
|
|
1285
|
+
versions = {
|
|
1286
|
+
(row.kind, row.key, row.revision)
|
|
1287
|
+
for row in self.history_records
|
|
1288
|
+
if row.committed_at < cutoff
|
|
1289
|
+
and row.sequence <= frontier
|
|
1290
|
+
and row.revision < boundary[row.kind, row.key]
|
|
1291
|
+
and (row.kind, row.key, row.revision) not in pinned
|
|
1292
|
+
and not any(row.sequence > checkpoint.sequence for checkpoint in checkpoints)
|
|
1293
|
+
}
|
|
1294
|
+
live = {key for key, run in self.runs.items() if run.status == ACTIVE and run.expires_at > now}
|
|
1295
|
+
operations = {
|
|
1296
|
+
key
|
|
1297
|
+
for key, record in self.ops.items()
|
|
1298
|
+
if record.resolved
|
|
1299
|
+
and record.resolved_at is not None
|
|
1300
|
+
and record.resolved_at < cutoff
|
|
1301
|
+
and record.run_id not in live
|
|
1302
|
+
and record.recovered_by not in live
|
|
1303
|
+
and not any(record.reservation > checkpoint.operation_frontier for checkpoint in checkpoints)
|
|
1304
|
+
}
|
|
1305
|
+
report = HistoryRetention(
|
|
1306
|
+
self.get_backend_type(),
|
|
1307
|
+
self.state_id,
|
|
1308
|
+
self.lineage,
|
|
1309
|
+
days,
|
|
1310
|
+
now,
|
|
1311
|
+
cutoff,
|
|
1312
|
+
frontier,
|
|
1313
|
+
self.pruned_before,
|
|
1314
|
+
self.history_epoch,
|
|
1315
|
+
len(self.baselines),
|
|
1316
|
+
RetentionCount(len(self.history_records), len(versions)),
|
|
1317
|
+
RetentionCount(len(self.ops), len(operations)),
|
|
1318
|
+
RetentionCount(len(self.checkpoints), len(dropped)),
|
|
1319
|
+
)
|
|
1320
|
+
return report, versions, operations, dropped
|
|
1321
|
+
|
|
1322
|
+
def preview_history_retention(self, *, days: int | None = None) -> HistoryRetention:
|
|
1323
|
+
with self._lock:
|
|
1324
|
+
return self._retention(retention_days(self.settings.history_retention_days if days is None else days))[0]
|
|
1325
|
+
|
|
1326
|
+
def prune_history(self, preview: HistoryRetention | None = None) -> HistoryRetention:
|
|
1327
|
+
with self._lock:
|
|
1328
|
+
self._fault("prune_history")
|
|
1329
|
+
report, versions, operations, dropped = self._retention(retention_days(preview.days if preview is not None else self.settings.history_retention_days), preview)
|
|
1330
|
+
successors = {}
|
|
1331
|
+
for row in sorted(self.history_records, key=lambda row: row.revision, reverse=True):
|
|
1332
|
+
key = (row.kind, row.key)
|
|
1333
|
+
if (row.kind, row.key, row.revision) in versions and key in successors and successors[key].sequence > row.sequence:
|
|
1334
|
+
self.pruned_before = max(self.pruned_before, successors[key].sequence - 1)
|
|
1335
|
+
successors[key] = row
|
|
1336
|
+
self.history_records = [row for row in self.history_records if (row.kind, row.key, row.revision) not in versions]
|
|
1337
|
+
for key in operations:
|
|
1338
|
+
self.ops.pop(key)
|
|
1339
|
+
for key in dropped:
|
|
1340
|
+
self.checkpoints.pop(key)
|
|
1341
|
+
self.history_epoch += int(bool(versions or operations or dropped))
|
|
1342
|
+
return replace(report, pruned=True, pruned_before=self.pruned_before, history_epoch=self.history_epoch)
|
|
1343
|
+
|
|
1344
|
+
def state_at(self, *, sequence: int | None = None, run_id: str | None = None, time: float | None = None, masked: bool = False) -> State:
|
|
1345
|
+
from netherframe.core.backends.graph_history import mask as mask_sensitive
|
|
1346
|
+
|
|
1347
|
+
with self._lock:
|
|
1348
|
+
if run_id is not None:
|
|
1349
|
+
sequences = [commit[0] for commit in self.commits if commit[1] == run_id]
|
|
1350
|
+
if not sequences:
|
|
1351
|
+
raise StateError(f"Run {run_id} committed nothing")
|
|
1352
|
+
sequence = max(sequences)
|
|
1353
|
+
elif time is not None:
|
|
1354
|
+
sequence = max((commit[0] for commit in self.commits if commit[2] <= time), default=0)
|
|
1355
|
+
limit = self.frontier if sequence is None else sequence
|
|
1356
|
+
if type(limit) is not int or not 0 <= limit <= self.frontier:
|
|
1357
|
+
raise StateError(f"History sequence must be between 0 and the frontier ({self.frontier})")
|
|
1358
|
+
self._check_history(limit)
|
|
1359
|
+
state = State(serial=limit, lineage=self.lineage)
|
|
1360
|
+
for record in self.history_records:
|
|
1361
|
+
if record.sequence > limit:
|
|
1362
|
+
continue
|
|
1363
|
+
if record.kind == RESOURCE:
|
|
1364
|
+
if record.tombstone:
|
|
1365
|
+
state.resources.pop(record.key, None)
|
|
1366
|
+
elif record.row is not None:
|
|
1367
|
+
entry = ResourceState.from_dict(record.row)
|
|
1368
|
+
if masked and record.sensitive_paths:
|
|
1369
|
+
entry.attributes = mask_sensitive(entry.attributes, record.sensitive_paths)
|
|
1370
|
+
state.resources[record.key] = entry
|
|
1371
|
+
elif record.kind == OUTPUT:
|
|
1372
|
+
if record.tombstone:
|
|
1373
|
+
state.outputs.pop(record.key, None)
|
|
1374
|
+
else:
|
|
1375
|
+
output = record.row
|
|
1376
|
+
if masked and isinstance(output, dict) and output.get("sensitive"):
|
|
1377
|
+
output = {**output, "value": "(sensitive value)"}
|
|
1378
|
+
state.outputs[record.key] = output
|
|
1379
|
+
return state
|
|
1380
|
+
|
|
1381
|
+
def mark_migrated(self, ownership: Ownership, target: str) -> None:
|
|
1382
|
+
with self._lock:
|
|
1383
|
+
self._fence(ownership, "mark_migrated")
|
|
1384
|
+
if not target or (self.migrated_to is not None and self.migrated_to != target):
|
|
1385
|
+
raise StateError("A migrated state's destination cannot be cleared or changed")
|
|
1386
|
+
self.migrated_to = target
|
|
1387
|
+
|
|
1388
|
+
def transfer_record(self, transfer_id: str) -> TransferRecord | None:
|
|
1389
|
+
with self._lock:
|
|
1390
|
+
return deepcopy(self.transfers.get(transfer_id))
|
|
1391
|
+
|
|
1392
|
+
def _transfer_fence(self, ownership: Ownership, transfer: StateTransfer, side: str) -> None:
|
|
1393
|
+
self._fence(ownership, "migration", migrating=True)
|
|
1394
|
+
if self.leases.get(ownership.run_id, {}).get("app") != X:
|
|
1395
|
+
raise PreCallValidationError("Migration requires the whole-app X lease")
|
|
1396
|
+
if storage_identity(self) != (transfer.source if side == "source" else transfer.target):
|
|
1397
|
+
raise StateError("Migration receipt belongs to another graph state")
|
|
1398
|
+
|
|
1399
|
+
def stage_transfer(self, ownership: Ownership, transfer: StateTransfer, *, replace_staged: bool = False) -> None:
|
|
1400
|
+
with self._lock:
|
|
1401
|
+
self._transfer_fence(ownership, transfer, "target")
|
|
1402
|
+
record = TransferRecord(transfer, "target", "staged")
|
|
1403
|
+
if existing := self.transfers.get(transfer.transfer_id):
|
|
1404
|
+
if existing not in (record, record.advance()):
|
|
1405
|
+
raise StateError("Migration receipt changed")
|
|
1406
|
+
return
|
|
1407
|
+
snapshot = self.snapshot()
|
|
1408
|
+
previous = self.transfers.get(self.transfer_id) if self.transfer_id is not None else None
|
|
1409
|
+
replacing = (
|
|
1410
|
+
replace_staged
|
|
1411
|
+
and previous is not None
|
|
1412
|
+
and previous.side == "target"
|
|
1413
|
+
and previous.phase == "staged"
|
|
1414
|
+
and (previous.transfer.source, previous.transfer.target, previous.transfer.direction) == (transfer.source, transfer.target, transfer.direction)
|
|
1415
|
+
)
|
|
1416
|
+
if (self.migrated_to is not None and not replacing) or snapshot.state.resources or snapshot.state.outputs or snapshot.unresolved or StateVersion.of(snapshot.state) != transfer.target_version:
|
|
1417
|
+
raise StateError("The graph destination already holds state or changed before staging")
|
|
1418
|
+
transfer.check_target(snapshot.state)
|
|
1419
|
+
if replacing and previous is not None:
|
|
1420
|
+
self.transfers[previous.transfer.transfer_id] = replace(previous, phase="aborted")
|
|
1421
|
+
self.transfers[transfer.transfer_id] = record
|
|
1422
|
+
self.transfer_id = transfer.transfer_id
|
|
1423
|
+
self.migrated_to = "pending migration"
|
|
1424
|
+
self.runs[ownership.run_id].mutation_started = True
|
|
1425
|
+
|
|
1426
|
+
def fence_transfer(self, ownership: Ownership, transfer: StateTransfer) -> None:
|
|
1427
|
+
with self._lock:
|
|
1428
|
+
self._transfer_fence(ownership, transfer, "source")
|
|
1429
|
+
record = TransferRecord(transfer, "source", "fenced")
|
|
1430
|
+
if existing := self.transfers.get(transfer.transfer_id):
|
|
1431
|
+
if existing not in (record, record.advance()) or self.transfer_id != transfer.transfer_id:
|
|
1432
|
+
raise StateError("Migration receipt changed")
|
|
1433
|
+
return
|
|
1434
|
+
snapshot = self.snapshot()
|
|
1435
|
+
if self.migrated_to is not None or snapshot.unresolved or StateVersion.of(snapshot.state) != transfer.source_version:
|
|
1436
|
+
raise StateError("The graph source changed before migration fencing")
|
|
1437
|
+
transfer.check_source(snapshot.state)
|
|
1438
|
+
self.transfers[transfer.transfer_id] = record
|
|
1439
|
+
self.transfer_id = transfer.transfer_id
|
|
1440
|
+
self.migrated_to = "document"
|
|
1441
|
+
self.runs[ownership.run_id].mutation_started = True
|
|
1442
|
+
|
|
1443
|
+
def publish_transfer(self, ownership: Ownership, transfer: StateTransfer, state: State) -> None:
|
|
1444
|
+
with self._lock:
|
|
1445
|
+
self._transfer_fence(ownership, transfer, "target")
|
|
1446
|
+
record = TransferRecord(transfer, "target", "staged")
|
|
1447
|
+
if self.transfers.get(transfer.transfer_id) == record.advance():
|
|
1448
|
+
return
|
|
1449
|
+
if self.transfers.get(transfer.transfer_id) != record or self.transfer_id != transfer.transfer_id:
|
|
1450
|
+
raise StateError("The migration destination is not staged for this transfer")
|
|
1451
|
+
writes = transfer_writes(self.snapshot(), transfer, state)
|
|
1452
|
+
self._commit(ownership, writes, migrating=True)
|
|
1453
|
+
self.transfers[transfer.transfer_id] = record.advance()
|
|
1454
|
+
self.transfer_id = None
|
|
1455
|
+
self.migrated_to = None
|
|
1456
|
+
|
|
1457
|
+
def finish_transfer(self, ownership: Ownership, transfer: StateTransfer) -> None:
|
|
1458
|
+
with self._lock:
|
|
1459
|
+
self._transfer_fence(ownership, transfer, "source")
|
|
1460
|
+
record = TransferRecord(transfer, "source", "fenced")
|
|
1461
|
+
if self.transfers.get(transfer.transfer_id) not in (record, record.advance()) or self.transfer_id != transfer.transfer_id:
|
|
1462
|
+
raise StateError("The migration source is not fenced for this transfer")
|
|
1463
|
+
self.transfers[transfer.transfer_id] = record.advance()
|
|
1464
|
+
self.runs[ownership.run_id].mutation_started = True
|
|
1465
|
+
|
|
1466
|
+
|
|
1467
|
+
def _same_row(actual: RowVersion | None, expected: Any, *, statuses: bool = True) -> bool:
|
|
1468
|
+
"""Whether a row is as expected: absent when expected absent; else the same revision, incarnation and tombstone, and (pre-call) provider, private data and status."""
|
|
1469
|
+
if expected is None:
|
|
1470
|
+
return actual is None
|
|
1471
|
+
if actual is None or not isinstance(expected, RowVersion):
|
|
1472
|
+
return False
|
|
1473
|
+
same = (actual.revision, actual.incarnation, actual.tombstone) == (expected.revision, expected.incarnation, expected.tombstone)
|
|
1474
|
+
if statuses:
|
|
1475
|
+
same = same and (actual.provider, actual.private_digest) == (expected.provider, expected.private_digest) and (actual.status == expected.status or actual.status == UNCERTAIN)
|
|
1476
|
+
return same
|
|
1477
|
+
|
|
1478
|
+
|
|
1479
|
+
def _describe(version: Any) -> str:
|
|
1480
|
+
if version is None:
|
|
1481
|
+
return "no row"
|
|
1482
|
+
if not isinstance(version, RowVersion):
|
|
1483
|
+
return str(version)
|
|
1484
|
+
return f"{'tombstone' if version.tombstone else 'revision'} {version.revision}, incarnation {version.incarnation}, {version.status}"
|