netherframe.backends.postgresql 0.2.1__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/backends/postgresql/__init__.py +59 -0
- netherframe/backends/postgresql/connection_settings.py +40 -0
- netherframe/backends/postgresql/graph.py +2511 -0
- netherframe/backends/postgresql/graph_authorization.py +102 -0
- netherframe/backends/postgresql/graph_checkpoints.py +239 -0
- netherframe/backends/postgresql/graph_completion.py +66 -0
- netherframe/backends/postgresql/graph_convergence.py +103 -0
- netherframe/backends/postgresql/graph_invalidation.py +115 -0
- netherframe/backends/postgresql/graph_lease_queue.py +236 -0
- netherframe/backends/postgresql/graph_planning_reads.py +97 -0
- netherframe/backends/postgresql/graph_publication.py +373 -0
- netherframe/backends/postgresql/graph_retention.py +141 -0
- netherframe/backends/postgresql/graph_reverse_edges.py +143 -0
- netherframe/backends/postgresql/graph_schema.py +2038 -0
- netherframe/backends/postgresql/graph_transfers.py +128 -0
- netherframe/backends/postgresql/postgresql.py +1207 -0
- netherframe/backends/postgresql/postgresql_backend_bootstrap.py +139 -0
- netherframe/backends/postgresql/py.typed +0 -0
- netherframe_backends_postgresql-0.2.1.dist-info/METADATA +138 -0
- netherframe_backends_postgresql-0.2.1.dist-info/RECORD +40 -0
- netherframe_backends_postgresql-0.2.1.dist-info/WHEEL +4 -0
- netherframe_backends_postgresql-0.2.1.dist-info/licenses/LICENSE +21 -0
- nf/backends/postgresql/__init__.py +4 -0
- nf/backends/postgresql/connection_settings.py +4 -0
- nf/backends/postgresql/graph.py +4 -0
- nf/backends/postgresql/graph_authorization.py +4 -0
- nf/backends/postgresql/graph_checkpoints.py +4 -0
- nf/backends/postgresql/graph_completion.py +4 -0
- nf/backends/postgresql/graph_convergence.py +4 -0
- nf/backends/postgresql/graph_invalidation.py +4 -0
- nf/backends/postgresql/graph_lease_queue.py +4 -0
- nf/backends/postgresql/graph_planning_reads.py +4 -0
- nf/backends/postgresql/graph_publication.py +4 -0
- nf/backends/postgresql/graph_retention.py +4 -0
- nf/backends/postgresql/graph_reverse_edges.py +4 -0
- nf/backends/postgresql/graph_schema.py +4 -0
- nf/backends/postgresql/graph_transfers.py +4 -0
- nf/backends/postgresql/postgresql.py +4 -0
- nf/backends/postgresql/postgresql_backend_bootstrap.py +4 -0
- nf/backends/postgresql/py.typed +0 -0
|
@@ -0,0 +1,2511 @@
|
|
|
1
|
+
"""PostgreSQL graph state backend: rows, operations and recovery under an app-wide lease.
|
|
2
|
+
|
|
3
|
+
See ``netherframe.core.backends.graph_state`` for the protocol, ``graph_schema`` for the tables,
|
|
4
|
+
and docs/advanced/hybrid-execution/graph-state-backend.md for its use. Hybrid only: Terraform
|
|
5
|
+
cannot read this state, and the backend is not a synthesizable ``Backend`` construct.
|
|
6
|
+
|
|
7
|
+
Every reserve, dispatch, return and commit locks the run's ownership row ``FOR SHARE`` and checks
|
|
8
|
+
its epoch, its status and ``expires_at > clock_timestamp()`` in the same transaction; renewal and
|
|
9
|
+
takeover lock it ``FOR UPDATE``. Lock order is run row, then the app row, then entry rows, in
|
|
10
|
+
every transaction, so they cannot deadlock one another.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import asyncio
|
|
16
|
+
import re
|
|
17
|
+
import ssl
|
|
18
|
+
import threading
|
|
19
|
+
import uuid
|
|
20
|
+
from collections import OrderedDict
|
|
21
|
+
from collections.abc import Callable, Mapping, Sequence
|
|
22
|
+
from contextlib import ExitStack, asynccontextmanager, suppress
|
|
23
|
+
from dataclasses import dataclass, field, replace
|
|
24
|
+
from pathlib import Path
|
|
25
|
+
from typing import TYPE_CHECKING, Any, cast
|
|
26
|
+
|
|
27
|
+
import anyio.from_thread
|
|
28
|
+
import asyncpg
|
|
29
|
+
from netherframe.backends.postgresql import connection_settings as connection
|
|
30
|
+
from netherframe.core.backends.graph_settings import GraphStateSettings
|
|
31
|
+
from netherframe.core.backends.graph_inputs import STALE_INPUTS, changed_inputs, decode_inputs, effective_status, encode_inputs, input_covers
|
|
32
|
+
from netherframe.core.backends.graph_ownership import ObjectCheck, ObjectOwner, ownership_problems
|
|
33
|
+
from netherframe.core.providers.provider_address import stored_provider_source
|
|
34
|
+
from netherframe.core.backends.graph_object_guard import ObjectEntryGuard, ObjectOperationGuard, ObjectRequest, bind_operation_request, object_problems, object_request
|
|
35
|
+
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
|
|
36
|
+
from netherframe.core.backends.graph_baseline import GraphBaseline, IntentRecord, intent_snapshot_digest, require_known_intents
|
|
37
|
+
from netherframe.core.backends.graph_planning import GraphEntrySummary, GraphPlanningOperation, GraphPlanningRow, GraphPlanningView, PlanningKey, planning_keys
|
|
38
|
+
from netherframe.core.backends.graph_edges import EdgeIndex, GraphEdge, targets_of
|
|
39
|
+
from netherframe.core.backends.graph_plan_guard import (
|
|
40
|
+
ROLLBACK_DELETE,
|
|
41
|
+
ROLLBACK_ENABLED,
|
|
42
|
+
ROLLBACK_OF,
|
|
43
|
+
GraphPlanAdmission,
|
|
44
|
+
operation_permission,
|
|
45
|
+
require_existing_identity,
|
|
46
|
+
require_operation_contracts,
|
|
47
|
+
require_rollback_source,
|
|
48
|
+
require_write_contracts,
|
|
49
|
+
)
|
|
50
|
+
from netherframe.core.backends.graph_kept_return import KeptReturn
|
|
51
|
+
from netherframe.core.backends.graph_recovery import Probe, recovery_probe_result
|
|
52
|
+
from netherframe.core.backends.graph_state import (
|
|
53
|
+
ACTIVE,
|
|
54
|
+
COMMITTED,
|
|
55
|
+
FINAL_STAGES,
|
|
56
|
+
IN_FLIGHT_STAGES,
|
|
57
|
+
METADATA,
|
|
58
|
+
OBSERVATION,
|
|
59
|
+
OUTPUT,
|
|
60
|
+
RESOURCE,
|
|
61
|
+
UNCERTAIN,
|
|
62
|
+
UNCHECKED,
|
|
63
|
+
CommitResult,
|
|
64
|
+
GraphSnapshot,
|
|
65
|
+
GraphStateBackend,
|
|
66
|
+
HistoryRecord,
|
|
67
|
+
OperationRecord,
|
|
68
|
+
OperationSpec,
|
|
69
|
+
Ownership,
|
|
70
|
+
OwnershipLostError,
|
|
71
|
+
PreCallValidationError,
|
|
72
|
+
QuarantinedError,
|
|
73
|
+
RowVersion,
|
|
74
|
+
RowWrite,
|
|
75
|
+
StaleGraphPlanError,
|
|
76
|
+
SiblingOperationBusyError,
|
|
77
|
+
object_identity,
|
|
78
|
+
private_digest,
|
|
79
|
+
validate_write_operations,
|
|
80
|
+
validate_recovery_writes,
|
|
81
|
+
validate_operation_resolution,
|
|
82
|
+
validate_operation_dispatch,
|
|
83
|
+
)
|
|
84
|
+
from netherframe.core.backends.state_models import ResourceState, State
|
|
85
|
+
from netherframe.core.exceptions import ConfigurationError, StateConflictError, StateError, StateLockError
|
|
86
|
+
from netherframe.core.logging import get_logger
|
|
87
|
+
from netherframe.core.backends.graph_inputs import value_fingerprint
|
|
88
|
+
from netherframe.core.serialization import orjson_compat as json
|
|
89
|
+
|
|
90
|
+
from .graph_schema import MIGRATIONS, RELEASE_MIGRATIONS, RELEASE_WRITER_PROTOCOL, SCHEMA_VERSION, VIEWS
|
|
91
|
+
from .graph_retention import PostgreSQLHistoryRetention
|
|
92
|
+
from netherframe.core.backends.graph_retention import HistoryRetention
|
|
93
|
+
from netherframe.core.backends.graph_history import HistoryPage, HistoryQuery
|
|
94
|
+
from .graph_lease_queue import PostgreSQLLeaseQueue
|
|
95
|
+
from .graph_reverse_edges import PostgreSQLReverseEdges
|
|
96
|
+
from .graph_checkpoints import PostgreSQLHistoryCheckpoints
|
|
97
|
+
from .graph_transfers import PostgreSQLStateTransfers
|
|
98
|
+
from .graph_publication import MAX_ROWS as PUBLICATION_MAX_ROWS, legacy_normalization, publish_creation_batch, publish_state_batch
|
|
99
|
+
from .graph_invalidation import publish_stale_batch
|
|
100
|
+
from .graph_planning_reads import read_metadata, read_payloads, read_scope_metadata
|
|
101
|
+
from netherframe.core.backends.graph_migration import StateTransfer, TransferRecord
|
|
102
|
+
from netherframe.core.backends.graph_edges import EdgePredicate
|
|
103
|
+
from netherframe.core.backends.graph_plan_basis import GraphPlanBasis
|
|
104
|
+
from netherframe.core.backends.graph_diagnostics import GraphConflictReport
|
|
105
|
+
from netherframe.core.backends.graph_planning_context import bind_planning_context, read_planning_context
|
|
106
|
+
from netherframe.core.backends.graph_leases import LeaseKey, missing_leases
|
|
107
|
+
|
|
108
|
+
if TYPE_CHECKING:
|
|
109
|
+
from collections.abc import AsyncGenerator
|
|
110
|
+
|
|
111
|
+
logger = get_logger(__name__)
|
|
112
|
+
|
|
113
|
+
_IDENTIFIER = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
|
|
114
|
+
_UNRESOLVED = "stage NOT IN ('committed', 'aborted')"
|
|
115
|
+
_DEVELOPMENT_MIGRATIONS = MIGRATIONS
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _identifier(value: str, what: str) -> str:
|
|
119
|
+
if not _IDENTIFIER.fullmatch(value):
|
|
120
|
+
raise ConfigurationError(f"{what} {value!r} must be a plain SQL identifier (letters, digits, underscores)")
|
|
121
|
+
# These identifiers are unquoted in SQL. Match PostgreSQL's case folding
|
|
122
|
+
# for state identity, migration locks, role lookup and view naming too.
|
|
123
|
+
return value.lower()
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _json(value: Any) -> str:
|
|
127
|
+
return json.dumps(value, default=str)
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _load(value: Any) -> Any:
|
|
131
|
+
return json.loads(value) if isinstance(value, (str, bytes)) else value
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def _version_of(row: Mapping[str, Any] | asyncpg.Record) -> RowVersion:
|
|
135
|
+
return RowVersion(
|
|
136
|
+
revision=int(row["revision"]),
|
|
137
|
+
incarnation=int(row["incarnation"]),
|
|
138
|
+
status=str(row["status"]),
|
|
139
|
+
provider=str(row["provider"] or ""),
|
|
140
|
+
private_digest=str(row["private_digest"] or ""),
|
|
141
|
+
object_identity=row["object_identity"],
|
|
142
|
+
tombstone=bool(row["tombstone"]),
|
|
143
|
+
intent_fp=row.get("intent_fp"),
|
|
144
|
+
inputs=decode_inputs(_load(row.get("inputs"))),
|
|
145
|
+
applied_fp=row.get("applied_fp"),
|
|
146
|
+
run_id=row.get("run_id"),
|
|
147
|
+
mutation_revision=int(row.get("mutation_revision") or 0),
|
|
148
|
+
value_revision=int(row.get("value_revision") or 0),
|
|
149
|
+
membership_revision=int(row.get("membership_revision") or 0),
|
|
150
|
+
planning_context=read_planning_context(_load(row.get("planning_context"))),
|
|
151
|
+
value_fp=value_fingerprint([_load(row.get("entry", {})).get("attributes", {}) if row.get("entry") is not None else None, str(row.get("provider") or ""), str(row.get("private_digest") or "")]),
|
|
152
|
+
)
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def _same(actual: RowVersion | None, expected: Any, *, statuses: bool) -> bool:
|
|
156
|
+
if expected is None:
|
|
157
|
+
return actual is None
|
|
158
|
+
if actual is None or not isinstance(expected, RowVersion):
|
|
159
|
+
return False
|
|
160
|
+
same = (actual.revision, actual.incarnation, actual.tombstone) == (expected.revision, expected.incarnation, expected.tombstone)
|
|
161
|
+
if statuses:
|
|
162
|
+
same = same and (actual.provider, actual.private_digest) == (expected.provider, expected.private_digest) and actual.status in {expected.status, UNCERTAIN}
|
|
163
|
+
return same
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def _describe(version: Any) -> str:
|
|
167
|
+
if version is None:
|
|
168
|
+
return "no row"
|
|
169
|
+
if not isinstance(version, RowVersion):
|
|
170
|
+
return str(version)
|
|
171
|
+
return f"{'tombstone' if version.tombstone else 'revision'} {version.revision}, incarnation {version.incarnation}, {version.status}"
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def _entry_document(entry: ResourceState) -> dict[str, Any]:
|
|
175
|
+
document = entry.to_dict()
|
|
176
|
+
document.pop("private", None)
|
|
177
|
+
return document
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def _entry_of(document: Any, private: bytes | None, status: str) -> ResourceState:
|
|
181
|
+
entry = ResourceState.from_dict(_load(document))
|
|
182
|
+
entry.private = bytes(private) if private else b""
|
|
183
|
+
entry.tainted = entry.tainted or status == "tainted"
|
|
184
|
+
return entry
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
@dataclass(frozen=True)
|
|
188
|
+
class _OwnedTransaction:
|
|
189
|
+
"""Locked ownership and an optional graph sequence awaiting its final fence."""
|
|
190
|
+
|
|
191
|
+
conn: asyncpg.Connection
|
|
192
|
+
ownership: Ownership
|
|
193
|
+
run: Mapping[str, Any]
|
|
194
|
+
planning: bool = False
|
|
195
|
+
sequences: list[int] = field(default_factory=list)
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
class PostgreSQLGraphBackend(GraphStateBackend):
|
|
199
|
+
"""A graph state backend in PostgreSQL (see the module's documentation).
|
|
200
|
+
|
|
201
|
+
Connection settings are flags (``nf --postgresql-host ...``), else ``[tool.nf.config]``
|
|
202
|
+
(``postgresql_host``, ``_port``, ``_database``, ``_username``, ``_ssl_mode``), else the
|
|
203
|
+
arguments. The password is never an argument nor a flag: it is read from a file
|
|
204
|
+
(``--postgresql-password-file``, or ``password_file``, such as a mounted secret), or a callable
|
|
205
|
+
(``password_source``, such as a secrets manager client), and never logged or returned by
|
|
206
|
+
``get_config``. Nothing is read from the environment.
|
|
207
|
+
"""
|
|
208
|
+
|
|
209
|
+
def __init__(
|
|
210
|
+
self,
|
|
211
|
+
*,
|
|
212
|
+
state_id: str = "default",
|
|
213
|
+
host: str | None = None,
|
|
214
|
+
port: int | None = None,
|
|
215
|
+
database: str | None = None,
|
|
216
|
+
username: str | None = None,
|
|
217
|
+
password_file: str | Path | None = None,
|
|
218
|
+
password_source: Callable[[], str] | None = None,
|
|
219
|
+
schema: str = "nf_graph",
|
|
220
|
+
table_prefix: str = "nf_",
|
|
221
|
+
ssl_mode: str | None = None,
|
|
222
|
+
ssl_ca: str | None = None,
|
|
223
|
+
pool_size: int = 10,
|
|
224
|
+
command_timeout: float = 60.0,
|
|
225
|
+
reader_role: str | None = None,
|
|
226
|
+
create_schema: bool = True,
|
|
227
|
+
lease_ttl: float | None = None,
|
|
228
|
+
lease_renew_interval: float | None = None,
|
|
229
|
+
operation_quiescence: float | None = None,
|
|
230
|
+
kill_providers_on_lease_loss: bool | None = None,
|
|
231
|
+
history_retention_days: int | None = None,
|
|
232
|
+
lease_timeout: float | None = None,
|
|
233
|
+
approval_timeout: float | None = None,
|
|
234
|
+
) -> None:
|
|
235
|
+
self.state_id = state_id
|
|
236
|
+
self.host = str(connection.setting("host", host, "localhost"))
|
|
237
|
+
self.port = int(connection.setting("port", port, 5432, parser=lambda value: int(str(value))))
|
|
238
|
+
self.database = connection.setting("database", database)
|
|
239
|
+
self.username = connection.setting("username", username)
|
|
240
|
+
if not self.database or not self.username:
|
|
241
|
+
raise ConfigurationError("The PostgreSQL graph backend needs a database and a username (--postgresql-database and --postgresql-username, [tool.nf.config], or arguments)")
|
|
242
|
+
self._password_file = connection.password_file(password_file)
|
|
243
|
+
self._password_source = password_source
|
|
244
|
+
self.schema = _identifier(schema, "schema")
|
|
245
|
+
self.table_prefix = _identifier(table_prefix, "table_prefix")
|
|
246
|
+
self.view_prefix = "" if self.table_prefix == "nf_" else self.table_prefix
|
|
247
|
+
self.reader_role = _identifier(reader_role or f"{self.schema}_reader", "reader_role")
|
|
248
|
+
self.ssl_mode = str(connection.setting("ssl_mode", ssl_mode, "prefer"))
|
|
249
|
+
if self.ssl_mode not in {"disable", "allow", "prefer", "require", "verify-ca", "verify-full"}:
|
|
250
|
+
raise ConfigurationError(f"Unknown PostgreSQL ssl_mode: {self.ssl_mode!r}")
|
|
251
|
+
self.ssl_ca = ssl_ca
|
|
252
|
+
self.pool_size = pool_size
|
|
253
|
+
self.command_timeout = command_timeout
|
|
254
|
+
self.create_schema = create_schema
|
|
255
|
+
self.settings = GraphStateSettings.resolve(
|
|
256
|
+
lease_ttl=lease_ttl,
|
|
257
|
+
lease_renew_interval=lease_renew_interval,
|
|
258
|
+
operation_quiescence=operation_quiescence,
|
|
259
|
+
kill_providers_on_lease_loss=kill_providers_on_lease_loss,
|
|
260
|
+
history_retention_days=history_retention_days,
|
|
261
|
+
lease_timeout=lease_timeout,
|
|
262
|
+
approval_timeout=approval_timeout,
|
|
263
|
+
)
|
|
264
|
+
self.application_name = f"nf-graph-{uuid.uuid4().hex[:12]}"
|
|
265
|
+
self._pool: asyncpg.Pool | None = None
|
|
266
|
+
self._pool_lock = threading.Lock()
|
|
267
|
+
self._connection_lock = asyncio.Lock()
|
|
268
|
+
self._portal: Any = None
|
|
269
|
+
self._portal_stack: ExitStack | None = None
|
|
270
|
+
self._initialized = False
|
|
271
|
+
self._release_schema = False
|
|
272
|
+
self._run_baselines = False
|
|
273
|
+
self._planning_contexts = False
|
|
274
|
+
self._grant_checks = False
|
|
275
|
+
self._admission_projections = False
|
|
276
|
+
self._planning_dependencies = False
|
|
277
|
+
self._closed = False
|
|
278
|
+
self._close_done = threading.Event()
|
|
279
|
+
self._object_claims: OrderedDict[tuple[str, str], tuple[int, ObjectRequest]] = OrderedDict()
|
|
280
|
+
self._object_claim_bytes = 0
|
|
281
|
+
|
|
282
|
+
# -- configuration -----------------------------------------------------------------
|
|
283
|
+
|
|
284
|
+
def _password(self) -> str:
|
|
285
|
+
if self._password_source is not None:
|
|
286
|
+
return self._password_source()
|
|
287
|
+
if self._password_file is not None:
|
|
288
|
+
return connection.read_password_file(self._password_file)
|
|
289
|
+
raise ConfigurationError("No PostgreSQL password: give it in a file (--postgresql-password-file, postgresql_password_file in [tool.nf.config], or password_file), or a password_source")
|
|
290
|
+
|
|
291
|
+
supports_state_transfers = True
|
|
292
|
+
|
|
293
|
+
def get_backend_type(self) -> str:
|
|
294
|
+
return "postgresql-graph"
|
|
295
|
+
|
|
296
|
+
def state_identity(self) -> dict[str, Any]:
|
|
297
|
+
return {"backend": self.get_backend_type(), "host": self.host, "port": self.port, "database": self.database, "schema": self.schema, "table_prefix": self.table_prefix, "state_id": self.state_id}
|
|
298
|
+
|
|
299
|
+
def get_config(self) -> dict[str, Any]:
|
|
300
|
+
return {
|
|
301
|
+
"type": self.get_backend_type(),
|
|
302
|
+
"host": self.host,
|
|
303
|
+
"port": self.port,
|
|
304
|
+
"database": self.database,
|
|
305
|
+
"username": self.username,
|
|
306
|
+
"schema": self.schema,
|
|
307
|
+
"table_prefix": self.table_prefix,
|
|
308
|
+
"state_id": self.state_id,
|
|
309
|
+
"ssl_mode": self.ssl_mode,
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
def _t(self, name: str) -> str:
|
|
313
|
+
return f"{self.schema}.{self.table_prefix}{name}"
|
|
314
|
+
|
|
315
|
+
def _ssl(self) -> str | ssl.SSLContext:
|
|
316
|
+
if self.ssl_mode in {"disable", "allow", "prefer"}:
|
|
317
|
+
# Let asyncpg negotiate advisory TLS and its fallback. False
|
|
318
|
+
# disables TLS even when the server supports or requires it.
|
|
319
|
+
return self.ssl_mode
|
|
320
|
+
context = ssl.create_default_context(cafile=self.ssl_ca) if self.ssl_ca else ssl.create_default_context()
|
|
321
|
+
if self.ssl_mode == "require" and not self.ssl_ca:
|
|
322
|
+
context.check_hostname = False
|
|
323
|
+
context.verify_mode = ssl.CERT_NONE
|
|
324
|
+
elif self.ssl_mode != "verify-full":
|
|
325
|
+
context.check_hostname = False
|
|
326
|
+
return context
|
|
327
|
+
|
|
328
|
+
# -- connections -------------------------------------------------------------------
|
|
329
|
+
|
|
330
|
+
def _run(self, function: Callable[..., Any], *args: Any) -> Any:
|
|
331
|
+
"""Run an async method on the backend's own event loop thread (callable from any thread, the heartbeat's included)."""
|
|
332
|
+
with self._pool_lock:
|
|
333
|
+
self._check_open()
|
|
334
|
+
if self._portal is None:
|
|
335
|
+
self._portal_stack = ExitStack()
|
|
336
|
+
self._portal = self._portal_stack.enter_context(cast("Any", anyio.from_thread).start_blocking_portal())
|
|
337
|
+
portal = self._portal
|
|
338
|
+
return portal.call(function, *args)
|
|
339
|
+
|
|
340
|
+
def _check_open(self) -> None:
|
|
341
|
+
if self._closed:
|
|
342
|
+
raise OwnershipLostError("The PostgreSQL graph backend is closed; create a new backend instance before using it")
|
|
343
|
+
|
|
344
|
+
async def _get_pool(self) -> asyncpg.Pool:
|
|
345
|
+
self._check_open()
|
|
346
|
+
pool = self._pool
|
|
347
|
+
if pool is not None and not pool._closed and self._initialized:
|
|
348
|
+
return pool
|
|
349
|
+
async with self._connection_lock:
|
|
350
|
+
self._check_open()
|
|
351
|
+
pool = self._pool
|
|
352
|
+
if pool is None or pool._closed:
|
|
353
|
+
pool = await asyncpg.create_pool(
|
|
354
|
+
host=self.host,
|
|
355
|
+
port=self.port,
|
|
356
|
+
database=self.database,
|
|
357
|
+
user=self.username,
|
|
358
|
+
password=self._password(),
|
|
359
|
+
min_size=1,
|
|
360
|
+
max_size=self.pool_size,
|
|
361
|
+
command_timeout=self.command_timeout,
|
|
362
|
+
ssl=self._ssl(),
|
|
363
|
+
server_settings={"application_name": self.application_name},
|
|
364
|
+
)
|
|
365
|
+
if self._closed:
|
|
366
|
+
await pool.close()
|
|
367
|
+
self._check_open()
|
|
368
|
+
self._pool = pool
|
|
369
|
+
if not self._initialized:
|
|
370
|
+
await self._migrate(pool)
|
|
371
|
+
self._check_open()
|
|
372
|
+
self._initialized = True
|
|
373
|
+
return pool
|
|
374
|
+
|
|
375
|
+
@asynccontextmanager
|
|
376
|
+
async def _tx(self, *, readonly: bool = False, isolation: str = "read_committed") -> AsyncGenerator[asyncpg.Connection]:
|
|
377
|
+
pool = await self._get_pool()
|
|
378
|
+
async with pool.acquire() as conn, conn.transaction(isolation=isolation, readonly=readonly):
|
|
379
|
+
if not readonly:
|
|
380
|
+
identity_protocol, queue_protocol = (RELEASE_WRITER_PROTOCOL, RELEASE_WRITER_PROTOCOL) if self._release_schema else ("19", "8")
|
|
381
|
+
await conn.execute(f"SET LOCAL netherframe.graph_identity_protocol = '{identity_protocol}'; SET LOCAL netherframe.graph_queue_protocol = '{queue_protocol}'")
|
|
382
|
+
yield conn
|
|
383
|
+
|
|
384
|
+
@asynccontextmanager
|
|
385
|
+
async def _mutation(self, conn: asyncpg.Connection, ownership: Ownership, what: str, *, recovery: bool = False, restoring: bool = False, migrating: bool = False, planning: bool = False) -> AsyncGenerator[_OwnedTransaction]:
|
|
386
|
+
"""One ownership proof for the complete transaction, including its tail.
|
|
387
|
+
|
|
388
|
+
Initial locks freeze role, epoch and migration metadata. A successful
|
|
389
|
+
body must still own its registration and complete grant after all row
|
|
390
|
+
waits, state writes and receipts. That observation is the publication
|
|
391
|
+
decision point; the SQL transaction retains its locks through commit.
|
|
392
|
+
A failure rolls it back. Commit audit timestamps use that observation.
|
|
393
|
+
"""
|
|
394
|
+
# Tuple SHARE holders can let new readers bypass a waiting UPDATE,
|
|
395
|
+
# starving renewal under continuous resource work. The advisory queue
|
|
396
|
+
# gives renewal a turn before new owned transactions enter. Shared
|
|
397
|
+
# turns preserve sibling concurrency; all existing fences still apply.
|
|
398
|
+
gate = "pg_advisory_xact_lock" if what == "renew" else "pg_advisory_xact_lock_shared"
|
|
399
|
+
await conn.execute(f"SELECT {gate}(hashtextextended($1, 0))", "nf-graph-renew:" + _json([self.schema.lower(), self.table_prefix.lower(), self.state_id, ownership.run_id]))
|
|
400
|
+
run = await PostgreSQLLeaseQueue(self).fence(conn, ownership) if planning else await self._fence(conn, ownership, what, recovery=recovery, restoring=restoring, migrating=migrating)
|
|
401
|
+
transaction = _OwnedTransaction(conn, ownership, run, planning)
|
|
402
|
+
yield transaction # noqa: RUF075 - only successful bodies publish; _tx rolls back errors
|
|
403
|
+
grant = await self._refence(conn, ownership, what, allow_pending=planning or recovery)
|
|
404
|
+
for sequence in transaction.sequences:
|
|
405
|
+
await conn.execute(
|
|
406
|
+
f"INSERT INTO {self._t('commits')} (state_id, sequence, run_id, epoch, fenced_at, committed_at, lease_expires_at) VALUES ($1, $2, $3, $4, $5, clock_timestamp(), $6)",
|
|
407
|
+
self.state_id,
|
|
408
|
+
sequence,
|
|
409
|
+
ownership.run_id,
|
|
410
|
+
ownership.epoch,
|
|
411
|
+
grant["fenced_at"],
|
|
412
|
+
run["expires_at"],
|
|
413
|
+
)
|
|
414
|
+
|
|
415
|
+
@asynccontextmanager
|
|
416
|
+
async def _owned_tx(self, ownership: Ownership, what: str, *, recovery: bool = False, restoring: bool = False, migrating: bool = False, planning: bool = False) -> AsyncGenerator[_OwnedTransaction]:
|
|
417
|
+
async with self._tx() as conn, self._mutation(conn, ownership, what, recovery=recovery, restoring=restoring, migrating=migrating, planning=planning) as transaction:
|
|
418
|
+
yield transaction
|
|
419
|
+
|
|
420
|
+
async def _migrate(self, pool: asyncpg.Pool) -> None:
|
|
421
|
+
"""Apply the migrations not applied yet (serialized across processes by an advisory lock), and make sure the app's row exists."""
|
|
422
|
+
async with pool.acquire() as conn:
|
|
423
|
+
async with conn.transaction():
|
|
424
|
+
await conn.execute("SELECT pg_advisory_xact_lock(hashtext($1))", f"nf-graph-migrate:{self.schema}.{self.table_prefix}")
|
|
425
|
+
if self.create_schema:
|
|
426
|
+
await conn.execute(f"CREATE SCHEMA IF NOT EXISTS {self.schema}")
|
|
427
|
+
ledger = self._t("schema_migrations")
|
|
428
|
+
create_ledger = f"CREATE TABLE IF NOT EXISTS {ledger} (version integer PRIMARY KEY, applied_at timestamptz NOT NULL DEFAULT clock_timestamp())"
|
|
429
|
+
archive_name = f"{self.table_prefix}development_schema_migrations"
|
|
430
|
+
released = await conn.fetchval("SELECT to_regclass($1) IS NOT NULL", f"{self.schema}.{archive_name}")
|
|
431
|
+
release_schema = MIGRATIONS is _DEVELOPMENT_MIGRATIONS
|
|
432
|
+
if released and not release_schema:
|
|
433
|
+
raise StateError("A development writer cannot open this released graph state schema")
|
|
434
|
+
await conn.execute(create_ledger)
|
|
435
|
+
if not released:
|
|
436
|
+
await self._apply_schema_migrations(conn, ledger, MIGRATIONS, development=True)
|
|
437
|
+
if release_schema:
|
|
438
|
+
await conn.execute(f"ALTER TABLE {ledger} RENAME TO {archive_name}")
|
|
439
|
+
await conn.execute(create_ledger)
|
|
440
|
+
if release_schema:
|
|
441
|
+
await self._apply_schema_migrations(conn, ledger, RELEASE_MIGRATIONS, development=False)
|
|
442
|
+
await conn.execute(
|
|
443
|
+
f"INSERT INTO {self._t('apps')} (state_id, lineage, schema_version) VALUES ($1, $2, $3) ON CONFLICT (state_id) DO NOTHING",
|
|
444
|
+
self.state_id,
|
|
445
|
+
str(uuid.uuid4()),
|
|
446
|
+
SCHEMA_VERSION,
|
|
447
|
+
)
|
|
448
|
+
self._release_schema = release_schema
|
|
449
|
+
self._run_baselines = any(version >= 29 for version, _ in MIGRATIONS)
|
|
450
|
+
self._planning_contexts = any(version >= 31 for version, _ in MIGRATIONS)
|
|
451
|
+
self._grant_checks = any(version >= 33 for version, _ in MIGRATIONS)
|
|
452
|
+
self._admission_projections = any(version >= 34 for version, _ in MIGRATIONS)
|
|
453
|
+
self._planning_dependencies = any(version >= 35 for version, _ in MIGRATIONS)
|
|
454
|
+
await self._grant_reader(conn)
|
|
455
|
+
|
|
456
|
+
async def _apply_schema_migrations(self, conn: asyncpg.Connection, ledger: str, migrations: Sequence[tuple[int, str]], *, development: bool) -> None:
|
|
457
|
+
applied = {row["version"] for row in await conn.fetch(f"SELECT version FROM {ledger}")}
|
|
458
|
+
if not applied.issubset(version for version, _ in migrations):
|
|
459
|
+
raise StateError("Unsupported PostgreSQL graph state schema; upgrade Netherframe")
|
|
460
|
+
series = "development" if development else "release"
|
|
461
|
+
for version, sql in migrations:
|
|
462
|
+
if version in applied:
|
|
463
|
+
continue
|
|
464
|
+
await conn.execute(sql.format(s=self.schema, p=self.table_prefix, v=self.view_prefix))
|
|
465
|
+
if development and version == 23:
|
|
466
|
+
from .graph_convergence import backfill_legacy_convergence
|
|
467
|
+
|
|
468
|
+
await backfill_legacy_convergence(conn, self)
|
|
469
|
+
await conn.execute(f"INSERT INTO {ledger} (version) VALUES ($1)", version)
|
|
470
|
+
logger.info(f"Applied graph state {series} migration {version} to {self.schema}")
|
|
471
|
+
|
|
472
|
+
async def _grant_reader(self, conn: asyncpg.Connection) -> None:
|
|
473
|
+
"""Create the read-only role ``nf state query`` runs as, with SELECT on the views only (best effort: it needs CREATEROLE)."""
|
|
474
|
+
views = ", ".join(f"{self.schema}.{self.view_prefix}{view}" for view in VIEWS)
|
|
475
|
+
statements = [
|
|
476
|
+
f"DO $$ BEGIN IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = '{self.reader_role}') THEN CREATE ROLE {self.reader_role} NOLOGIN; END IF; END $$",
|
|
477
|
+
f"GRANT USAGE ON SCHEMA {self.schema} TO {self.reader_role}",
|
|
478
|
+
f"GRANT SELECT ON {views} TO {self.reader_role}",
|
|
479
|
+
f"GRANT EXECUTE ON FUNCTION {self.schema}.{self.table_prefix}mask(jsonb, jsonb) TO {self.reader_role}",
|
|
480
|
+
f"GRANT EXECUTE ON FUNCTION {self.schema}.{self.table_prefix}mask_at(jsonb, text[]) TO {self.reader_role}",
|
|
481
|
+
f"GRANT {self.reader_role} TO CURRENT_USER",
|
|
482
|
+
]
|
|
483
|
+
try:
|
|
484
|
+
async with conn.transaction():
|
|
485
|
+
await conn.execute("SELECT pg_advisory_xact_lock(hashtext($1))", f"nf-graph-reader:{self.reader_role}")
|
|
486
|
+
for statement in statements:
|
|
487
|
+
await conn.execute(statement)
|
|
488
|
+
except asyncpg.PostgresError as exc:
|
|
489
|
+
logger.warning(f"Could not set up the read-only role {self.reader_role} for `nf state query` ({exc}); a database administrator can grant SELECT on the views to it")
|
|
490
|
+
|
|
491
|
+
def terminate_connections(self) -> int:
|
|
492
|
+
"""Drop this backend's database connections from the server's side (fault injection: a dropped connection); how many."""
|
|
493
|
+
return int(self._run(self._terminate))
|
|
494
|
+
|
|
495
|
+
async def _terminate(self) -> int:
|
|
496
|
+
pool = await self._get_pool()
|
|
497
|
+
async with pool.acquire() as conn:
|
|
498
|
+
rows = await conn.fetch(
|
|
499
|
+
"SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE application_name = $1 AND pid <> pg_backend_pid()",
|
|
500
|
+
self.application_name,
|
|
501
|
+
)
|
|
502
|
+
return len(rows)
|
|
503
|
+
|
|
504
|
+
def close(self) -> None:
|
|
505
|
+
"""Permanently close this instance; owners cannot renew or start new mutations."""
|
|
506
|
+
with self._pool_lock:
|
|
507
|
+
first = not self._closed
|
|
508
|
+
self._closed = True
|
|
509
|
+
portal, pool, stack = self._portal, self._pool, self._portal_stack
|
|
510
|
+
if not first:
|
|
511
|
+
self._close_done.wait()
|
|
512
|
+
return
|
|
513
|
+
try:
|
|
514
|
+
try:
|
|
515
|
+
if portal is not None and pool is not None:
|
|
516
|
+
with suppress(Exception):
|
|
517
|
+
portal.call(pool.close)
|
|
518
|
+
finally:
|
|
519
|
+
if stack is not None:
|
|
520
|
+
with suppress(Exception):
|
|
521
|
+
stack.close()
|
|
522
|
+
finally:
|
|
523
|
+
with self._pool_lock:
|
|
524
|
+
self._pool = None
|
|
525
|
+
self._portal_stack = None
|
|
526
|
+
self._portal = None
|
|
527
|
+
self._object_claims.clear()
|
|
528
|
+
self._object_claim_bytes = 0
|
|
529
|
+
self._close_done.set()
|
|
530
|
+
|
|
531
|
+
# -- ownership ---------------------------------------------------------------------
|
|
532
|
+
|
|
533
|
+
async def _fence(self, conn: asyncpg.Connection, ownership: Ownership, what: str, *, recovery: bool = False, restoring: bool = False, migrating: bool = False) -> Mapping[str, Any]:
|
|
534
|
+
"""Lock the run's ownership row FOR SHARE and check it still owns the app: its epoch, status, lease and unexpired lease, by the database's clock."""
|
|
535
|
+
guard_mode = "UPDATE" if migrating or what in {"mark migrated", "migration"} else "SHARE"
|
|
536
|
+
run = await conn.fetchrow(
|
|
537
|
+
f"""
|
|
538
|
+
SELECT r.epoch, r.status, r.expires_at, r.lease_phase, r.operation, r.admitted_plan IS NOT NULL AS admitted,
|
|
539
|
+
g.migrated_to AS migration_target,
|
|
540
|
+
coalesce(r.lease_set ->> 'app' = 'X', false) AS whole_app,
|
|
541
|
+
r.lease_phase = 'granted' AND coalesce(r.lease_set ->> 'app' = 'X', false) AS holds
|
|
542
|
+
FROM {self._t("runs")} r JOIN {self._t("migration_guards")} g ON g.state_id = r.state_id
|
|
543
|
+
WHERE r.run_id = $1 AND r.state_id = $2 FOR SHARE OF r FOR {guard_mode} OF g
|
|
544
|
+
""",
|
|
545
|
+
ownership.run_id,
|
|
546
|
+
self.state_id,
|
|
547
|
+
)
|
|
548
|
+
if run is None or run["status"] != ACTIVE or run["epoch"] != ownership.epoch:
|
|
549
|
+
raise OwnershipLostError(f"Run {ownership.run_id} no longer owns the app's state ({what} refused)")
|
|
550
|
+
if migrating and (run["operation"] != "migrate" or run["admitted"] or ownership.claim is not None):
|
|
551
|
+
raise PreCallValidationError("State transfer requires its own whole-app migration run")
|
|
552
|
+
if restoring and (run["operation"] != "restore-checkpoint" or run["admitted"] or ownership.claim is not None):
|
|
553
|
+
raise PreCallValidationError("A checkpoint restore needs its own state-only run")
|
|
554
|
+
if run["operation"] == "restore-checkpoint" and (what in {"reserve", "dispatch", "mark migrated"} or (what == "commit" and not restoring)):
|
|
555
|
+
raise PreCallValidationError("A checkpoint restore can only write its verified before-images")
|
|
556
|
+
# The guard is locked with the run, without another round trip. Normal
|
|
557
|
+
# commits keep SHARE here while independently advancing the app frontier.
|
|
558
|
+
# Lock waits return the updated guard tuple; clock/grant state below is
|
|
559
|
+
# read in a fresh statement after both locks have been acquired.
|
|
560
|
+
migrated = run["migration_target"]
|
|
561
|
+
# A SELECT's clock/subqueries can have been evaluated before waiting
|
|
562
|
+
# for its row lock. Read both liveness and the complete grant after it.
|
|
563
|
+
grant = await self._grant_state(conn, ownership)
|
|
564
|
+
if not grant["live"]:
|
|
565
|
+
raise OwnershipLostError(f"Run {ownership.run_id} no longer owns the app's state ({what} refused)")
|
|
566
|
+
if ownership.claim is not None and not recovery:
|
|
567
|
+
raise PreCallValidationError("An operation claim cannot authorize new calls or unrelated state administration")
|
|
568
|
+
if run["lease_phase"] == "granted" and not grant["complete"]:
|
|
569
|
+
raise OwnershipLostError("The run lost part of its granted lease set")
|
|
570
|
+
if run["admitted"] and what == "mark migrated":
|
|
571
|
+
raise PreCallValidationError("An admitted resource plan cannot authorize app migration")
|
|
572
|
+
if run["admitted"] and recovery:
|
|
573
|
+
raise PreCallValidationError("An admitted resource plan cannot authorize recovery; register a recoverer")
|
|
574
|
+
if not run["holds"] and not (not recovery and run["admitted"] and run["lease_phase"] == "granted") and not (recovery and run["operation"] == "recover") and not (restoring and run["lease_phase"] == "granted"):
|
|
575
|
+
if run["whole_app"]:
|
|
576
|
+
raise OwnershipLostError(f"Run {ownership.run_id} lost its whole-app lease ({what} refused)")
|
|
577
|
+
raise PreCallValidationError("State mutations require a whole-app X lease or an admitted graph plan")
|
|
578
|
+
if migrated is not None and what not in {"mark migrated", "migration"} and not migrating:
|
|
579
|
+
raise PreCallValidationError("This graph state is fenced by migration; ordinary mutations are refused")
|
|
580
|
+
return {**dict(run), "fenced_at": grant["fenced_at"], "live": grant["live"]}
|
|
581
|
+
|
|
582
|
+
async def _complete_grant(self, conn: asyncpg.Connection, ownership: Ownership) -> bool:
|
|
583
|
+
return bool((await self._grant_state(conn, ownership))["complete"])
|
|
584
|
+
|
|
585
|
+
async def _grant_state(self, conn: asyncpg.Connection, ownership: Ownership) -> asyncpg.Record:
|
|
586
|
+
if self._grant_checks:
|
|
587
|
+
# SQL validates the exact grant at installation and invalidates its
|
|
588
|
+
# certificate transactionally on every lease edit. Keep this read
|
|
589
|
+
# at both fences: invalidation can commit while an operation waits,
|
|
590
|
+
# and expiry must always use a fresh database clock.
|
|
591
|
+
return await conn.fetchrow(
|
|
592
|
+
f"""WITH instant AS MATERIALIZED (SELECT clock_timestamp() AS at)
|
|
593
|
+
SELECT instant.at AS fenced_at, r.expires_at > instant.at AS live, r.lease_phase,
|
|
594
|
+
r.lease_phase = 'granted' AND coalesce(c.complete, false) AS complete
|
|
595
|
+
FROM {self._t("runs")} r CROSS JOIN instant
|
|
596
|
+
LEFT JOIN {self._t("grant_checks")} c ON c.state_id = r.state_id AND c.run_id = r.run_id
|
|
597
|
+
WHERE r.run_id = $1 AND r.state_id = $2""",
|
|
598
|
+
ownership.run_id,
|
|
599
|
+
self.state_id,
|
|
600
|
+
)
|
|
601
|
+
# Expand the stored grant once. Per-held-key JSON lookups repeatedly
|
|
602
|
+
# process a large toasted value. Both differences are needed: a count
|
|
603
|
+
# or coverage check alone would accept extra keys or mode changes.
|
|
604
|
+
return await conn.fetchrow(
|
|
605
|
+
f"""WITH instant AS MATERIALIZED (SELECT clock_timestamp() AS at),
|
|
606
|
+
run AS MATERIALIZED (
|
|
607
|
+
SELECT expires_at, lease_phase, lease_set FROM {self._t("runs")} WHERE run_id = $1 AND state_id = $2
|
|
608
|
+
),
|
|
609
|
+
wanted AS MATERIALIZED (SELECT item.key COLLATE "C" AS key, item.value COLLATE "C" AS mode FROM run r CROSS JOIN LATERAL jsonb_each_text(r.lease_set) item),
|
|
610
|
+
actual AS MATERIALIZED (SELECT key COLLATE "C" AS key, mode COLLATE "C" AS mode FROM {self._t("leases")} WHERE state_id = $2 AND holder = $1)
|
|
611
|
+
SELECT instant.at AS fenced_at, r.expires_at > instant.at AS live, r.lease_phase,
|
|
612
|
+
r.lease_phase = 'granted' AND r.lease_set IS NOT NULL
|
|
613
|
+
AND NOT EXISTS (SELECT key, mode FROM wanted EXCEPT SELECT key, mode FROM actual)
|
|
614
|
+
AND NOT EXISTS (SELECT key, mode FROM actual EXCEPT SELECT key, mode FROM wanted) AS complete
|
|
615
|
+
FROM run r CROSS JOIN instant""",
|
|
616
|
+
ownership.run_id,
|
|
617
|
+
self.state_id,
|
|
618
|
+
)
|
|
619
|
+
|
|
620
|
+
async def _refence(self, conn: asyncpg.Connection, ownership: Ownership, what: str, *, allow_pending: bool = False) -> asyncpg.Record:
|
|
621
|
+
"""Refresh time and the actual grant while the initial fence's locks remain held.
|
|
622
|
+
|
|
623
|
+
The run/guard locks already freeze epoch, role and migration metadata.
|
|
624
|
+
Only the clock and independently stored lease rows need a fresh read.
|
|
625
|
+
Explicit recovery claims inherit their retained operation footprint.
|
|
626
|
+
"""
|
|
627
|
+
grant = await self._grant_state(conn, ownership)
|
|
628
|
+
if not grant["live"] or ((not allow_pending or grant["lease_phase"] == "granted") and not grant["complete"]):
|
|
629
|
+
raise OwnershipLostError(f"Run {ownership.run_id} lost ownership or part of its grant ({what} refused)")
|
|
630
|
+
return grant
|
|
631
|
+
|
|
632
|
+
async def _check_admitted_targets(self, conn: asyncpg.Connection, ownership: Ownership, targets: Sequence[tuple[str, str]], *, action: str | None = None) -> bool:
|
|
633
|
+
# Generated columns retain the exact JSON projections, including NULLs.
|
|
634
|
+
# SQL derives them on admission/release and refuses independent edits;
|
|
635
|
+
# permission checks still run inside the same fenced transaction.
|
|
636
|
+
writes = "r.admitted_writes" if self._admission_projections else "r.admitted_plan #> '{basis,writes}'"
|
|
637
|
+
auxiliary = "r.admitted_auxiliary" if self._admission_projections else "r.admitted_plan #> '{basis,auxiliary}'"
|
|
638
|
+
actions = "r.admitted_actions -> target.key" if self._admission_projections else "r.admitted_plan #> ARRAY['basis', 'actions', target.key]"
|
|
639
|
+
if len(targets) >= 64:
|
|
640
|
+
# Expand once for publication-sized batches. Small checks retain
|
|
641
|
+
# containment: expanding a large permission set costs more for them.
|
|
642
|
+
action_set = "r.admitted_actions" if self._admission_projections else "r.admitted_plan #> '{basis,actions}'"
|
|
643
|
+
row = await conn.fetchrow(
|
|
644
|
+
f"""WITH run AS MATERIALIZED (
|
|
645
|
+
SELECT r.admitted_plan IS NOT NULL AS admitted, {writes} AS writes,
|
|
646
|
+
{auxiliary} AS auxiliary, {action_set} AS actions
|
|
647
|
+
FROM {self._t("runs")} r WHERE r.run_id = $1 AND r.state_id = $2),
|
|
648
|
+
allowed AS MATERIALIZED (
|
|
649
|
+
SELECT item.kind, item.key FROM run CROSS JOIN LATERAL
|
|
650
|
+
jsonb_to_recordset(coalesce(run.writes, '[]'::jsonb)) item(kind text, key text)
|
|
651
|
+
UNION ALL
|
|
652
|
+
SELECT item.kind, item.key FROM run CROSS JOIN LATERAL
|
|
653
|
+
jsonb_to_recordset(coalesce(run.auxiliary, '[]'::jsonb)) item(kind text, key text))
|
|
654
|
+
SELECT r.admitted, ARRAY(
|
|
655
|
+
SELECT target.kind || ':' || target.key
|
|
656
|
+
FROM jsonb_to_recordset($3::jsonb) target(kind text, key text)
|
|
657
|
+
WHERE r.admitted AND (
|
|
658
|
+
NOT EXISTS (SELECT 1 FROM allowed a WHERE a.kind = target.kind AND a.key = target.key)
|
|
659
|
+
OR ($4::text IS NOT NULL AND NOT coalesce(r.actions -> target.key, '[]'::jsonb) ? $4))) AS outside
|
|
660
|
+
FROM run r""",
|
|
661
|
+
ownership.run_id,
|
|
662
|
+
self.state_id,
|
|
663
|
+
_json([{"kind": kind, "key": key} for kind, key in targets]),
|
|
664
|
+
action,
|
|
665
|
+
)
|
|
666
|
+
if row["outside"]:
|
|
667
|
+
raise PreCallValidationError("Mutation is outside the admitted plan's closed write set or possible action: " + ", ".join(sorted(row["outside"])))
|
|
668
|
+
return row["admitted"]
|
|
669
|
+
row = await conn.fetchrow(
|
|
670
|
+
f"""SELECT r.admitted_plan IS NOT NULL AS admitted,
|
|
671
|
+
ARRAY(SELECT target.kind || ':' || target.key FROM jsonb_to_recordset($3::jsonb) AS target(kind text, key text)
|
|
672
|
+
WHERE r.admitted_plan IS NOT NULL AND (NOT (({writes}) @>
|
|
673
|
+
jsonb_build_array(jsonb_build_object('kind', target.kind, 'key', target.key))
|
|
674
|
+
OR coalesce({auxiliary}, '[]'::jsonb) @>
|
|
675
|
+
jsonb_build_array(jsonb_build_object('kind', target.kind, 'key', target.key)))
|
|
676
|
+
OR ($4::text IS NOT NULL AND NOT coalesce({actions}, '[]'::jsonb) ? $4))) AS outside
|
|
677
|
+
FROM {self._t("runs")} r WHERE r.run_id = $1 AND r.state_id = $2""",
|
|
678
|
+
ownership.run_id,
|
|
679
|
+
self.state_id,
|
|
680
|
+
_json([{"kind": kind, "key": key} for kind, key in targets]),
|
|
681
|
+
action,
|
|
682
|
+
)
|
|
683
|
+
if row["outside"]:
|
|
684
|
+
raise PreCallValidationError("Mutation is outside the admitted plan's closed write set or possible action: " + ", ".join(sorted(row["outside"])))
|
|
685
|
+
return row["admitted"]
|
|
686
|
+
|
|
687
|
+
def acquire(self, info: Mapping[str, Any], *, ttl: float, operation: str) -> Ownership | None:
|
|
688
|
+
return self._run(self._acquire, dict(info), ttl, operation)
|
|
689
|
+
|
|
690
|
+
async def _acquire(self, info: dict[str, Any], ttl: float, operation: str) -> Ownership | None:
|
|
691
|
+
return await PostgreSQLLeaseQueue(self).acquire(info, ttl, operation)
|
|
692
|
+
|
|
693
|
+
def open_run(self, info: Mapping[str, Any], *, ttl: float, operation: str) -> Ownership:
|
|
694
|
+
return self._run(PostgreSQLLeaseQueue(self).open, dict(info), ttl, operation)
|
|
695
|
+
|
|
696
|
+
def request_leases(self, ownership: Ownership, request: Mapping[LeaseKey, str]) -> int:
|
|
697
|
+
return self._run(PostgreSQLLeaseQueue(self).request, ownership, request)
|
|
698
|
+
|
|
699
|
+
def try_grant_leases(self, ownership: Ownership) -> bool:
|
|
700
|
+
return self._run(PostgreSQLLeaseQueue(self).grant, ownership)
|
|
701
|
+
|
|
702
|
+
def request_and_try_grant_leases(self, ownership: Ownership, request: Mapping[LeaseKey, str]) -> bool:
|
|
703
|
+
return self._run(PostgreSQLLeaseQueue(self).request_and_grant, ownership, request)
|
|
704
|
+
|
|
705
|
+
def explain_lease_request(self, ownership: Ownership, *, basis: GraphPlanBasis | None = None) -> GraphConflictReport:
|
|
706
|
+
return self._run(PostgreSQLLeaseQueue(self).explain, ownership, basis)
|
|
707
|
+
|
|
708
|
+
def release_leases(self, ownership: Ownership) -> None:
|
|
709
|
+
self._run(PostgreSQLLeaseQueue(self).release, ownership)
|
|
710
|
+
|
|
711
|
+
def held_leases(self, ownership: Ownership) -> dict[str, str]:
|
|
712
|
+
return self._run(PostgreSQLLeaseQueue(self).held, ownership)
|
|
713
|
+
|
|
714
|
+
def validate_plan_basis(self, ownership: Ownership, basis: GraphPlanBasis) -> None:
|
|
715
|
+
self._run(self._validate_plan_basis, ownership, basis)
|
|
716
|
+
|
|
717
|
+
async def _plan_lease_set(self, conn: asyncpg.Connection, ownership: Ownership, run: Mapping[str, Any]) -> tuple[dict[str, str], bool]:
|
|
718
|
+
"""Read the exact-grant certificate and lock its coverage in one request.
|
|
719
|
+
|
|
720
|
+
The caller already holds the run and app locks. Materializing held rows
|
|
721
|
+
retains their SHARE locks, including when coverage is checked in Python.
|
|
722
|
+
A lease edit may commit while this statement waits: its certificate can
|
|
723
|
+
come from the earlier statement snapshot, so the transaction's final
|
|
724
|
+
refence must still read a fresh certificate and database clock.
|
|
725
|
+
"""
|
|
726
|
+
if not self._grant_checks:
|
|
727
|
+
complete = await self._complete_grant(conn, ownership)
|
|
728
|
+
rows = await conn.fetch(f"SELECT key, mode FROM {self._t('leases')} WHERE state_id = $1 AND holder = $2 FOR SHARE", self.state_id, ownership.run_id)
|
|
729
|
+
return {row["key"]: row["mode"] for row in rows}, complete
|
|
730
|
+
rows = await conn.fetch(
|
|
731
|
+
f"""WITH held AS MATERIALIZED (
|
|
732
|
+
SELECT key, mode FROM {self._t("leases")} WHERE state_id = $1 AND holder = $2 FOR SHARE
|
|
733
|
+
)
|
|
734
|
+
SELECT held.key, held.mode, certificate.complete
|
|
735
|
+
FROM (SELECT coalesce((SELECT complete FROM {self._t("grant_checks")} WHERE state_id = $1 AND run_id = $2), false) AS complete) certificate
|
|
736
|
+
LEFT JOIN held ON true""",
|
|
737
|
+
self.state_id,
|
|
738
|
+
ownership.run_id,
|
|
739
|
+
)
|
|
740
|
+
return {row["key"]: row["mode"] for row in rows if row["key"] is not None}, run["lease_phase"] == "granted" and bool(rows[0]["complete"])
|
|
741
|
+
|
|
742
|
+
async def _validate_plan_basis(self, ownership: Ownership, basis: GraphPlanBasis) -> None:
|
|
743
|
+
async with self._owned_tx(ownership, "plan validation", planning=True) as transaction:
|
|
744
|
+
conn, run = transaction.conn, transaction.run
|
|
745
|
+
# Keep the short proof read consistent with graph commits. Using
|
|
746
|
+
# READ COMMITTED also lets fence follow a valid renewal that it
|
|
747
|
+
# waited for, rather than failing on an obsolete ownership tuple.
|
|
748
|
+
await conn.execute(f"SELECT 1 FROM {self._t('apps')} WHERE state_id = $1 FOR SHARE", self.state_id)
|
|
749
|
+
held, complete = await self._plan_lease_set(conn, ownership, run)
|
|
750
|
+
if run["lease_phase"] == "granted" and not complete:
|
|
751
|
+
raise OwnershipLostError("The run lost part of its granted lease set")
|
|
752
|
+
missing = missing_leases(held, basis.required_leases())
|
|
753
|
+
if missing:
|
|
754
|
+
raise PreCallValidationError("Plan is not covered by granted leases: " + ", ".join(sorted(missing)))
|
|
755
|
+
problems, report = await self._plan_diagnostics(conn, basis, ownership.run_id)
|
|
756
|
+
if problems:
|
|
757
|
+
raise StaleGraphPlanError("Plan preconditions changed; replan before applying:\n" + "\n".join(problems), graph_conflicts=report.to_dict() if report is not None else None)
|
|
758
|
+
|
|
759
|
+
def admit_plan(self, ownership: Ownership, basis: GraphPlanBasis, baseline: GraphBaseline | None) -> None:
|
|
760
|
+
self._run(self._admit_plan, ownership, basis, baseline)
|
|
761
|
+
|
|
762
|
+
async def _admit_plan(self, ownership: Ownership, basis: GraphPlanBasis, baseline: GraphBaseline | None) -> None:
|
|
763
|
+
async with self._owned_tx(ownership, "plan admission", planning=True) as transaction:
|
|
764
|
+
conn, run = transaction.conn, transaction.run
|
|
765
|
+
if ownership.claim is not None or run["operation"] == "recover":
|
|
766
|
+
raise PreCallValidationError("Recovery inherits operation coverage and cannot admit a new mutation plan")
|
|
767
|
+
await conn.execute(f"SELECT 1 FROM {self._t('apps')} WHERE state_id = $1 FOR UPDATE", self.state_id)
|
|
768
|
+
held, complete = await self._plan_lease_set(conn, ownership, run)
|
|
769
|
+
if not complete:
|
|
770
|
+
raise PreCallValidationError("Plan admission requires the run's entire granted lease set")
|
|
771
|
+
admission = GraphPlanAdmission(basis, baseline, run["operation"] if baseline is None else None)
|
|
772
|
+
encoded = admission.to_dict()
|
|
773
|
+
previous = await conn.fetchval(f"SELECT admitted_plan FROM {self._t('runs')} WHERE run_id = $1", ownership.run_id)
|
|
774
|
+
if previous is not None:
|
|
775
|
+
if _load(previous) != encoded:
|
|
776
|
+
raise StateLockError("An admitted plan is immutable; release the entire grant before replanning")
|
|
777
|
+
return
|
|
778
|
+
if await conn.fetchval(
|
|
779
|
+
f"SELECT EXISTS (SELECT 1 FROM {self._t('run_mutations')} WHERE run_id = $1) OR EXISTS (SELECT 1 FROM {self._t('operations')} WHERE (run_id = $1 OR recovered_by = $1) AND stage NOT IN ('committed', 'aborted'))",
|
|
780
|
+
ownership.run_id,
|
|
781
|
+
):
|
|
782
|
+
raise StateLockError("Admit a plan before reserving operations or mutating state")
|
|
783
|
+
if baseline is not None:
|
|
784
|
+
if self._run_baselines:
|
|
785
|
+
recorded = _load(await conn.fetchval(f"SELECT baseline FROM {self._t('runs')} WHERE run_id = $1", ownership.run_id))
|
|
786
|
+
if recorded is not None and recorded != baseline.to_dict():
|
|
787
|
+
raise StateLockError("The admitted plan and run baseline must agree")
|
|
788
|
+
await self._baseline_intents_on(conn, baseline)
|
|
789
|
+
if missing := missing_leases(held, basis.required_leases()):
|
|
790
|
+
raise PreCallValidationError("Plan is not covered by granted leases: " + ", ".join(sorted(missing)))
|
|
791
|
+
problems, report = await self._plan_diagnostics(conn, basis, ownership.run_id)
|
|
792
|
+
if problems:
|
|
793
|
+
raise StaleGraphPlanError("Plan preconditions changed; replan before applying:\n" + "\n".join(problems), graph_conflicts=report.to_dict() if report is not None else None)
|
|
794
|
+
admission.check_existing_identities()
|
|
795
|
+
await conn.execute(f"UPDATE {self._t('runs')} SET admitted_plan = $2 WHERE run_id = $1", ownership.run_id, _json(encoded))
|
|
796
|
+
|
|
797
|
+
async def _quarantine(self, conn: asyncpg.Connection, holder: str) -> None:
|
|
798
|
+
"""End a holder whose lease expired (or that ended without releasing): its unresolved operations keep their addresses, which become uncertain when their call may have been sent."""
|
|
799
|
+
await conn.execute(f"UPDATE {self._t('runs')} SET status = 'expired', ended_at = clock_timestamp() WHERE run_id = $1 AND status = 'active'", holder)
|
|
800
|
+
marked = await conn.execute(
|
|
801
|
+
f"""
|
|
802
|
+
UPDATE {self._t("entries")} e SET status = 'uncertain'
|
|
803
|
+
FROM {self._t("operations")} o
|
|
804
|
+
WHERE o.state_id = $1 AND o.run_id = $2 AND o.{_UNRESOLVED} AND o.stage <> 'reserved'
|
|
805
|
+
AND e.state_id = o.state_id AND e.address = o.address AND NOT e.tombstone
|
|
806
|
+
""",
|
|
807
|
+
self.state_id,
|
|
808
|
+
holder,
|
|
809
|
+
)
|
|
810
|
+
await conn.execute(f"DELETE FROM {self._t('leases')} WHERE state_id = $1 AND holder = $2", self.state_id, holder)
|
|
811
|
+
await conn.execute(f"DELETE FROM {self._t('lease_queue')} WHERE state_id = $1 AND run_id = $2", self.state_id, holder)
|
|
812
|
+
logger.warning(f"Expired ownership of run {holder} ({marked})")
|
|
813
|
+
|
|
814
|
+
def renew(self, ownership: Ownership) -> None:
|
|
815
|
+
self._run(self._renew, ownership)
|
|
816
|
+
|
|
817
|
+
async def _renew(self, ownership: Ownership) -> None:
|
|
818
|
+
async with self._owned_tx(ownership, "renew", planning=True) as transaction:
|
|
819
|
+
conn = transaction.conn
|
|
820
|
+
# Use the same exact set comparison as the publication fence.
|
|
821
|
+
# A correlated lookup inside UPDATE can materialize every held key
|
|
822
|
+
# for every wanted key when a fresh grant outgrows table statistics.
|
|
823
|
+
if transaction.run["lease_phase"] == "granted" and not await self._complete_grant(conn, ownership):
|
|
824
|
+
raise OwnershipLostError("The run lost part of its granted lease set")
|
|
825
|
+
renewed = await conn.fetchval(
|
|
826
|
+
f"""
|
|
827
|
+
UPDATE {self._t("runs")} r SET expires_at = clock_timestamp() + make_interval(secs => $3)
|
|
828
|
+
WHERE r.run_id = $1 AND r.epoch = $2 AND r.status = 'active' AND r.expires_at > clock_timestamp()
|
|
829
|
+
AND r.state_id = $4
|
|
830
|
+
RETURNING r.run_id
|
|
831
|
+
""",
|
|
832
|
+
ownership.run_id,
|
|
833
|
+
ownership.epoch,
|
|
834
|
+
float(ownership.ttl),
|
|
835
|
+
self.state_id,
|
|
836
|
+
)
|
|
837
|
+
if renewed is None:
|
|
838
|
+
raise OwnershipLostError(f"Run {ownership.run_id} could not renew its lease: it expired or was taken over")
|
|
839
|
+
|
|
840
|
+
def release(self, ownership: Ownership) -> None:
|
|
841
|
+
self._run(self._release, ownership)
|
|
842
|
+
|
|
843
|
+
async def _release(self, ownership: Ownership) -> None:
|
|
844
|
+
async with self._tx() as conn:
|
|
845
|
+
epoch = await conn.fetchval(f"SELECT epoch FROM {self._t('runs')} WHERE run_id = $1 AND state_id = $2 FOR UPDATE", ownership.run_id, self.state_id)
|
|
846
|
+
if epoch != ownership.epoch:
|
|
847
|
+
return
|
|
848
|
+
await conn.execute(
|
|
849
|
+
f"UPDATE {self._t('runs')} SET status = 'ended', ended_at = clock_timestamp() WHERE run_id = $1 AND epoch = $2 AND state_id = $3 AND status = 'active'",
|
|
850
|
+
ownership.run_id,
|
|
851
|
+
ownership.epoch,
|
|
852
|
+
self.state_id,
|
|
853
|
+
)
|
|
854
|
+
await conn.execute(f"DELETE FROM {self._t('leases')} WHERE state_id = $1 AND holder = $2", self.state_id, ownership.run_id)
|
|
855
|
+
await conn.execute(f"DELETE FROM {self._t('lease_queue')} WHERE state_id = $1 AND run_id = $2", self.state_id, ownership.run_id)
|
|
856
|
+
with suppress(Exception):
|
|
857
|
+
await self._prune_history()
|
|
858
|
+
|
|
859
|
+
def preview_history_retention(self, *, days: int | None = None) -> HistoryRetention:
|
|
860
|
+
return self._run(PostgreSQLHistoryRetention(self).preview, days)
|
|
861
|
+
|
|
862
|
+
def prune_history(self, preview: HistoryRetention | None = None) -> HistoryRetention:
|
|
863
|
+
return self._run(PostgreSQLHistoryRetention(self).apply, preview)
|
|
864
|
+
|
|
865
|
+
async def _prune_history(self) -> None:
|
|
866
|
+
await PostgreSQLHistoryRetention(self).cleanup()
|
|
867
|
+
|
|
868
|
+
def report_providers_killed(self, ownership: Ownership) -> None:
|
|
869
|
+
self._run(self._report_killed, ownership)
|
|
870
|
+
|
|
871
|
+
async def _report_killed(self, ownership: Ownership) -> None:
|
|
872
|
+
async with self._tx() as conn:
|
|
873
|
+
await conn.execute(f"UPDATE {self._t('runs')} SET providers_killed_at = clock_timestamp() WHERE run_id = $1 AND state_id = $2 AND epoch = $3", ownership.run_id, self.state_id, ownership.epoch)
|
|
874
|
+
|
|
875
|
+
def current_owner(self) -> dict[str, Any] | None:
|
|
876
|
+
return self._run(self._current_owner)
|
|
877
|
+
|
|
878
|
+
async def _current_owner(self) -> dict[str, Any] | None:
|
|
879
|
+
async with self._tx(readonly=True) as conn:
|
|
880
|
+
row = await conn.fetchrow(
|
|
881
|
+
f"""
|
|
882
|
+
SELECT r.run_id, r.operation, r.actor, r.host, r.epoch, r.expires_at
|
|
883
|
+
FROM {self._t("leases")} l JOIN {self._t("runs")} r ON r.run_id = l.holder
|
|
884
|
+
WHERE l.state_id = $1 AND l.key = 'app' AND l.mode = 'X' AND r.status = 'active' AND r.expires_at > clock_timestamp()
|
|
885
|
+
""",
|
|
886
|
+
self.state_id,
|
|
887
|
+
)
|
|
888
|
+
if row is None:
|
|
889
|
+
return None
|
|
890
|
+
return {"ID": row["run_id"], "Operation": row["operation"], "Who": f"{row['actor']}@{row['host']}", "epoch": row["epoch"], "expires_at": row["expires_at"].isoformat()}
|
|
891
|
+
|
|
892
|
+
def end_run(self, run_id: str) -> None:
|
|
893
|
+
self._run(self._end_run, run_id)
|
|
894
|
+
|
|
895
|
+
async def _end_run(self, run_id: str) -> None:
|
|
896
|
+
async with self._tx() as conn:
|
|
897
|
+
run = await conn.fetchrow(f"SELECT status FROM {self._t('runs')} WHERE run_id = $1 AND state_id = $2 FOR UPDATE", run_id, self.state_id)
|
|
898
|
+
if run is None or run["status"] != ACTIVE:
|
|
899
|
+
raise StateLockError(f"Run {run_id} has no active ownership of this state")
|
|
900
|
+
dispatched = await conn.fetch(
|
|
901
|
+
f"SELECT op_id, action, address, stage FROM {self._t('operations')} WHERE run_id = $1 AND stage = ANY($2::text[])",
|
|
902
|
+
run_id,
|
|
903
|
+
sorted(IN_FLIGHT_STAGES),
|
|
904
|
+
)
|
|
905
|
+
if dispatched:
|
|
906
|
+
held = "; ".join(f"{row['op_id']} {row['action']} {row['address']} ({row['stage']})" for row in dispatched)
|
|
907
|
+
raise StateLockError(f"Run {run_id} holds dispatched operations, which force-unlock cannot clear; resolve them with `nf state recover`: {held}")
|
|
908
|
+
await self._quarantine(conn, run_id)
|
|
909
|
+
await conn.execute(f"UPDATE {self._t('runs')} SET status = 'ended' WHERE run_id = $1", run_id)
|
|
910
|
+
|
|
911
|
+
# -- reading -----------------------------------------------------------------------
|
|
912
|
+
|
|
913
|
+
def snapshot(self) -> GraphSnapshot:
|
|
914
|
+
return self._run(self._snapshot)
|
|
915
|
+
|
|
916
|
+
def snapshot_unchanged(self, frontier: int, lineage: str) -> bool:
|
|
917
|
+
return self._run(self._snapshot_unchanged, frontier, lineage)
|
|
918
|
+
|
|
919
|
+
async def _snapshot_unchanged(self, frontier: int, lineage: str) -> bool:
|
|
920
|
+
async with self._tx(readonly=True) as conn:
|
|
921
|
+
return bool(
|
|
922
|
+
await conn.fetchval(
|
|
923
|
+
f"""SELECT frontier = $2 AND lineage = $3 AND schema_version = $4
|
|
924
|
+
AND migrated_to IS NULL AND transfer_id IS NULL
|
|
925
|
+
AND NOT EXISTS (SELECT 1 FROM {self._t("operations")} WHERE state_id = $1 AND {_UNRESOLVED})
|
|
926
|
+
FROM {self._t("apps")} WHERE state_id = $1""",
|
|
927
|
+
self.state_id,
|
|
928
|
+
frontier,
|
|
929
|
+
lineage,
|
|
930
|
+
SCHEMA_VERSION,
|
|
931
|
+
)
|
|
932
|
+
)
|
|
933
|
+
|
|
934
|
+
async def _snapshot(self) -> GraphSnapshot:
|
|
935
|
+
async with self._tx(readonly=True, isolation="repeatable_read") as conn:
|
|
936
|
+
return await self._snapshot_on(conn)
|
|
937
|
+
|
|
938
|
+
async def _snapshot_on(self, conn: asyncpg.Connection) -> GraphSnapshot:
|
|
939
|
+
app = await conn.fetchrow(f"SELECT lineage, frontier, metadata, migrated_to, transfer_id FROM {self._t('apps')} WHERE state_id = $1", self.state_id)
|
|
940
|
+
entries = await conn.fetch(f"SELECT * FROM {self._t('entries')} WHERE state_id = $1", self.state_id)
|
|
941
|
+
outputs = await conn.fetch(f"SELECT * FROM {self._t('outputs')} WHERE state_id = $1", self.state_id)
|
|
942
|
+
observations = await conn.fetch(f"SELECT address, entry, private FROM {self._t('observations')} WHERE state_id = $1", self.state_id)
|
|
943
|
+
operations = await self._operations(conn, unresolved=True, op_id=None)
|
|
944
|
+
edge_index = await PostgreSQLReverseEdges(self).snapshot(conn)
|
|
945
|
+
snapshot = self._snapshot_view(app, entries, outputs, observations, operations, edge_index)
|
|
946
|
+
edge_index.validate(
|
|
947
|
+
GraphEdge(target, kind, key)
|
|
948
|
+
for kind, versions in ((RESOURCE, snapshot.versions), (OUTPUT, snapshot.output_versions))
|
|
949
|
+
for key, version in versions.items()
|
|
950
|
+
if not version.tombstone
|
|
951
|
+
for target in targets_of(version.inputs, snapshot.state.resources[key].dependencies if kind == RESOURCE else ())
|
|
952
|
+
)
|
|
953
|
+
return snapshot
|
|
954
|
+
|
|
955
|
+
def planning_view(self, keys: Sequence[PlanningKey] = (), *, baseline: GraphBaseline | None = None, expected_capture: str | None = None) -> GraphPlanningView:
|
|
956
|
+
return self._run(self._planning_view, planning_keys(keys), baseline, expected_capture)
|
|
957
|
+
|
|
958
|
+
async def _planning_view(self, keys: frozenset[PlanningKey], baseline: GraphBaseline | None, expected_capture: str | None) -> GraphPlanningView:
|
|
959
|
+
# All summary, origin, topology and selected payload reads share this
|
|
960
|
+
# MVCC snapshot. No transaction remains open during provider evaluation.
|
|
961
|
+
async with self._tx(readonly=True, isolation="repeatable_read") as conn:
|
|
962
|
+
return await self._planning_view_on(conn, keys, baseline, expected_capture)
|
|
963
|
+
|
|
964
|
+
async def _planning_view_on(self, conn: asyncpg.Connection, keys: frozenset[PlanningKey], baseline: GraphBaseline | None, expected_capture: str | None) -> GraphPlanningView:
|
|
965
|
+
metadata = await self._planning_metadata(conn, baseline)
|
|
966
|
+
[app] = metadata["app"]
|
|
967
|
+
origin = tuple(self._checked_baseline_intents(baseline, app["lineage"], metadata["baseline"], metadata["origin"])) if baseline is not None else ()
|
|
968
|
+
summaries, expected_edges = self._planning_summaries(metadata)
|
|
969
|
+
# Complete metadata in this same snapshot proves absence without a body
|
|
970
|
+
# read. Tombstones remain summaries and must still load their exact proof.
|
|
971
|
+
resources = sorted(key for kind, key in keys if kind == RESOURCE and (kind, key) in summaries)
|
|
972
|
+
outputs = sorted(key for kind, key in keys if kind == OUTPUT and (kind, key) in summaries)
|
|
973
|
+
rows = {}
|
|
974
|
+
if resources:
|
|
975
|
+
entries = await read_payloads(self, conn, "entries", resources, len(metadata["resource"]))
|
|
976
|
+
for row in entries:
|
|
977
|
+
rows[RESOURCE, row["address"]] = GraphPlanningRow(_version_of(row), None if row["tombstone"] else _entry_of(row["entry"], row["private"], row["status"]))
|
|
978
|
+
if outputs:
|
|
979
|
+
entries = await read_payloads(self, conn, "outputs", outputs, len(metadata["output"]))
|
|
980
|
+
for row in entries:
|
|
981
|
+
rows[OUTPUT, row["key"]] = GraphPlanningRow(self._output_version(row), None if row["tombstone"] else _load(row["value"]))
|
|
982
|
+
edge_index = EdgeIndex(PostgreSQLReverseEdges._edges(metadata["edges"]), PostgreSQLReverseEdges._generations(metadata["generations"]))
|
|
983
|
+
edge_index.validate(expected_edges)
|
|
984
|
+
operations = self._operation_records(metadata["operations"])
|
|
985
|
+
cleanup_keys = {(OBSERVATION, row["address"]) for row in metadata["observations"]}
|
|
986
|
+
if app["legacy_outputs"]:
|
|
987
|
+
cleanup_keys.add((METADATA, METADATA))
|
|
988
|
+
view = GraphPlanningView(
|
|
989
|
+
app["lineage"],
|
|
990
|
+
int(app["frontier"]),
|
|
991
|
+
summaries,
|
|
992
|
+
keys,
|
|
993
|
+
rows,
|
|
994
|
+
backend_type=self.get_backend_type(),
|
|
995
|
+
state_id=self.state_id,
|
|
996
|
+
origin=origin,
|
|
997
|
+
baseline=baseline,
|
|
998
|
+
edge_index=edge_index,
|
|
999
|
+
unresolved=tuple(GraphPlanningOperation.of(record) for record in operations),
|
|
1000
|
+
migrated_to=app["migrated_to"],
|
|
1001
|
+
transfer_id=app["transfer_id"],
|
|
1002
|
+
cleanup_keys=frozenset(cleanup_keys),
|
|
1003
|
+
)
|
|
1004
|
+
return view.require_capture(expected_capture)
|
|
1005
|
+
|
|
1006
|
+
async def _planning_metadata(self, conn: asyncpg.Connection, baseline: GraphBaseline | None):
|
|
1007
|
+
return await read_metadata(self, conn, baseline)
|
|
1008
|
+
|
|
1009
|
+
def check_planning_ownership(self, view: GraphPlanningView, checks: Sequence[ObjectCheck]) -> GraphPlanningView:
|
|
1010
|
+
return self._run(self._check_planning_ownership, view, tuple(checks))
|
|
1011
|
+
|
|
1012
|
+
async def _check_planning_ownership(self, view: GraphPlanningView, checks: tuple[ObjectCheck, ...]) -> GraphPlanningView:
|
|
1013
|
+
async with self._tx(readonly=True, isolation="repeatable_read") as conn:
|
|
1014
|
+
checked = await self._planning_view_on(conn, frozenset(), view.baseline, view.capture)
|
|
1015
|
+
if problems := ownership_problems(checks, await self._planning_owners(conn, checks)):
|
|
1016
|
+
raise StateError("Planning cloud ownership validation failed:\n" + "\n".join(problems))
|
|
1017
|
+
return checked
|
|
1018
|
+
|
|
1019
|
+
async def _planning_owners(self, conn: asyncpg.Connection, checks: Sequence[ObjectCheck]) -> list[ObjectOwner]:
|
|
1020
|
+
if not checks:
|
|
1021
|
+
return []
|
|
1022
|
+
# Each branch matches an existing ownership index. Project only owner
|
|
1023
|
+
# metadata, never attributes/private or the complete entry JSON. Source
|
|
1024
|
+
# matching follows the same legacy provider resolution as dispatch.
|
|
1025
|
+
bound_types = sorted({kind for check in checks for _source, kind in check.bound_sources})
|
|
1026
|
+
unbound_types = sorted({kind for check in checks for _source, kind in check.sources - check.bound_sources})
|
|
1027
|
+
rows = await conn.fetch(
|
|
1028
|
+
f"""WITH owners AS (
|
|
1029
|
+
SELECT address FROM {self._t("entries")} WHERE state_id = $1 AND NOT tombstone AND address = ANY($2::text[])
|
|
1030
|
+
UNION SELECT address FROM {self._t("entries")} WHERE state_id = $1 AND NOT tombstone AND object_identity = ANY($3::text[])
|
|
1031
|
+
UNION SELECT address FROM {self._t("entries")} WHERE state_id = $1 AND NOT tombstone AND type = ANY($4::text[])
|
|
1032
|
+
AND (object_identity IS NULL OR object_identity NOT LIKE 'nf-object-v1:%')
|
|
1033
|
+
UNION SELECT address FROM {self._t("entries")} WHERE state_id = $1 AND NOT tombstone AND type = ANY($5::text[])
|
|
1034
|
+
AND coalesce(entry #> '{{metadata,graph_object}}', 'null'::jsonb) <> 'null'::jsonb
|
|
1035
|
+
)
|
|
1036
|
+
SELECT e.address, e.provider, e.type, e.object_identity,
|
|
1037
|
+
e.entry #>> '{{metadata,provider_state,provider_source}}' AS provider_source,
|
|
1038
|
+
coalesce(e.entry #> '{{metadata,graph_object}}', 'null'::jsonb) <> 'null'::jsonb AS bound
|
|
1039
|
+
FROM owners JOIN {self._t("entries")} e ON e.state_id = $1 AND e.address = owners.address""",
|
|
1040
|
+
self.state_id,
|
|
1041
|
+
[check.address for check in checks],
|
|
1042
|
+
sorted({identity for check in checks for identity in check.identities}),
|
|
1043
|
+
bound_types,
|
|
1044
|
+
unbound_types,
|
|
1045
|
+
)
|
|
1046
|
+
return [
|
|
1047
|
+
ObjectOwner(
|
|
1048
|
+
row["address"],
|
|
1049
|
+
stored_provider_source(row["provider"], {"provider_source": row["provider_source"]}).fqn,
|
|
1050
|
+
row["type"],
|
|
1051
|
+
row["object_identity"] if row["object_identity"] and row["object_identity"].startswith("nf-object-v1:") else None,
|
|
1052
|
+
row["bound"],
|
|
1053
|
+
)
|
|
1054
|
+
for row in rows
|
|
1055
|
+
]
|
|
1056
|
+
|
|
1057
|
+
@staticmethod
|
|
1058
|
+
def _planning_summaries(metadata) -> tuple[dict[PlanningKey, GraphEntrySummary], frozenset[GraphEdge]]:
|
|
1059
|
+
result = {}
|
|
1060
|
+
expected_edges = set()
|
|
1061
|
+
for kind in (RESOURCE, OUTPUT):
|
|
1062
|
+
for row in metadata[kind]:
|
|
1063
|
+
key = row["key"]
|
|
1064
|
+
inputs = decode_inputs(_load(row["inputs"]))
|
|
1065
|
+
if not row["tombstone"]:
|
|
1066
|
+
expected_edges.update(GraphEdge(target, kind, key) for target in targets_of(inputs, _load(row["dependency_targets"]) or ()))
|
|
1067
|
+
result[kind, key] = GraphEntrySummary(
|
|
1068
|
+
kind,
|
|
1069
|
+
key,
|
|
1070
|
+
int(row["revision"]),
|
|
1071
|
+
int(row["incarnation"]),
|
|
1072
|
+
row["status"],
|
|
1073
|
+
row["tombstone"],
|
|
1074
|
+
row["intent_fp"],
|
|
1075
|
+
inputs,
|
|
1076
|
+
row["applied_fp"],
|
|
1077
|
+
row["run_id"],
|
|
1078
|
+
read_planning_context(_load(row["planning_context"])),
|
|
1079
|
+
)
|
|
1080
|
+
return result, frozenset(expected_edges)
|
|
1081
|
+
|
|
1082
|
+
def _snapshot_view(self, app, entries, outputs, observations, operations, edge_index) -> GraphSnapshot:
|
|
1083
|
+
frontier = int(app["frontier"])
|
|
1084
|
+
state = State(serial=frontier, lineage=app["lineage"], metadata=_load(app["metadata"]) or {})
|
|
1085
|
+
versions: dict[str, RowVersion] = {}
|
|
1086
|
+
for row in entries:
|
|
1087
|
+
versions[row["address"]] = _version_of(row)
|
|
1088
|
+
if not row["tombstone"]:
|
|
1089
|
+
state.resources[row["address"]] = _entry_of(row["entry"], row["private"], row["status"])
|
|
1090
|
+
output_versions: dict[str, RowVersion] = {}
|
|
1091
|
+
for row in outputs:
|
|
1092
|
+
output_versions[row["key"]] = self._output_version(row)
|
|
1093
|
+
if not row["tombstone"]:
|
|
1094
|
+
state.outputs[row["key"]] = _load(row["value"])
|
|
1095
|
+
for row in observations:
|
|
1096
|
+
state.resources[row["address"]] = _entry_of(row["entry"], row["private"], "ready")
|
|
1097
|
+
return GraphSnapshot(state, versions, output_versions, frontier, app["lineage"], operations, app["migrated_to"], edge_index, app["transfer_id"])
|
|
1098
|
+
|
|
1099
|
+
async def _plan_problems(self, conn: asyncpg.Connection, basis: GraphPlanBasis, run_id: str) -> list[str]:
|
|
1100
|
+
return (await self._plan_diagnostics(conn, basis, run_id))[0]
|
|
1101
|
+
|
|
1102
|
+
async def _scope_plan_view(self, conn: asyncpg.Connection, basis: GraphPlanBasis) -> tuple[GraphSnapshot, list[ObjectOwner] | None]:
|
|
1103
|
+
"""Private validation view: complete scopes/index, selected exact rows.
|
|
1104
|
+
|
|
1105
|
+
Only scope revision/status checks may inspect compact RowVersions. Every
|
|
1106
|
+
explicit row expectation retains its full version, including value and
|
|
1107
|
+
private-state fingerprints. Never return this view as application state.
|
|
1108
|
+
"""
|
|
1109
|
+
metadata = await read_scope_metadata(self, conn, include_metadata=any(item.kind == METADATA for item in basis.auxiliary))
|
|
1110
|
+
resource_keys = {row["key"] for row in metadata[RESOURCE]}
|
|
1111
|
+
if any(int(row["value_revision"] or 0) <= 0 for kind in (RESOURCE, OUTPUT) for row in metadata[kind]) or any(row["address"] in resource_keys or not row["is_data_source"] for row in metadata["observations"]):
|
|
1112
|
+
# Legacy digests need values. A legacy observation can also replace
|
|
1113
|
+
# a managed entry's dependencies/ownership in the merged snapshot.
|
|
1114
|
+
return await self._snapshot_on(conn), None
|
|
1115
|
+
versions: dict[str, dict[str, RowVersion]] = {RESOURCE: {}, OUTPUT: {}}
|
|
1116
|
+
expected_edges = set()
|
|
1117
|
+
for kind in (RESOURCE, OUTPUT):
|
|
1118
|
+
for row in metadata[kind]:
|
|
1119
|
+
key = row["key"]
|
|
1120
|
+
versions[kind][key] = RowVersion(
|
|
1121
|
+
int(row["revision"]),
|
|
1122
|
+
int(row["incarnation"]),
|
|
1123
|
+
status=row["status"],
|
|
1124
|
+
tombstone=row["tombstone"],
|
|
1125
|
+
value_revision=int(row["value_revision"]),
|
|
1126
|
+
membership_revision=int(row["membership_revision"]),
|
|
1127
|
+
)
|
|
1128
|
+
if not row["tombstone"]:
|
|
1129
|
+
expected_edges.update(GraphEdge(target, kind, key) for target in targets_of(decode_inputs(row["inputs"]), row["dependency_targets"] or ()))
|
|
1130
|
+
edge_index = EdgeIndex(PostgreSQLReverseEdges._edges(metadata["edges"]), PostgreSQLReverseEdges._generations(metadata["generations"]))
|
|
1131
|
+
edge_index.validate(expected_edges)
|
|
1132
|
+
keys = {(row.kind, row.key) for row in basis.rows}
|
|
1133
|
+
observation_keys = [item.key for item in basis.auxiliary if item.kind == OBSERVATION]
|
|
1134
|
+
keys.update((RESOURCE, key) for key in observation_keys)
|
|
1135
|
+
selected = {}
|
|
1136
|
+
for kind, table in ((RESOURCE, "entries"), (OUTPUT, "outputs")):
|
|
1137
|
+
wanted = sorted(key for item_kind, key in keys if item_kind == kind and key in versions[kind])
|
|
1138
|
+
selected[kind] = await read_payloads(self, conn, table, wanted, len(versions[kind]))
|
|
1139
|
+
observations = await conn.fetch(f"SELECT address, entry, private FROM {self._t('observations')} WHERE state_id = $1 AND address = ANY($2::text[])", self.state_id, observation_keys) if observation_keys else []
|
|
1140
|
+
[app] = metadata["app"]
|
|
1141
|
+
snapshot = self._snapshot_view(app, selected[RESOURCE], selected[OUTPUT], observations, self._operation_records(metadata["operations"]), edge_index)
|
|
1142
|
+
snapshot.versions = {**versions[RESOURCE], **snapshot.versions}
|
|
1143
|
+
snapshot.output_versions = {**versions[OUTPUT], **snapshot.output_versions}
|
|
1144
|
+
owners = None
|
|
1145
|
+
if basis.object_checks:
|
|
1146
|
+
# Preserve broad validation's ownership reconstruction from stored
|
|
1147
|
+
# locators/attributes. Indexed canonical columns alone cannot prove
|
|
1148
|
+
# equivalence if they disagree with those records. Reuse selected
|
|
1149
|
+
# entries and fetch only other live ownership documents; private
|
|
1150
|
+
# bytea and unrelated output/cache values are not needed here.
|
|
1151
|
+
owners = [ObjectOwner.of(entry) for entry in snapshot.state.resources.values() if not entry.is_data_source]
|
|
1152
|
+
other = await conn.fetch(
|
|
1153
|
+
f"SELECT entry, status FROM {self._t('entries')} WHERE state_id = $1 AND NOT tombstone AND address <> ALL($2::text[])",
|
|
1154
|
+
self.state_id,
|
|
1155
|
+
list(snapshot.state.resources),
|
|
1156
|
+
)
|
|
1157
|
+
for row in other:
|
|
1158
|
+
entry = _entry_of(row["entry"], None, row["status"])
|
|
1159
|
+
if not entry.is_data_source:
|
|
1160
|
+
owners.append(ObjectOwner.of(entry))
|
|
1161
|
+
return snapshot, owners
|
|
1162
|
+
|
|
1163
|
+
async def _plan_diagnostics(self, conn: asyncpg.Connection, basis: GraphPlanBasis, run_id: str) -> tuple[list[str], GraphConflictReport | None]:
|
|
1164
|
+
"""Validate exactly the declared proof under the caller's app-row lock.
|
|
1165
|
+
|
|
1166
|
+
Opaque value/membership scopes need complete metadata, including
|
|
1167
|
+
tombstones and outputs. Concrete proofs need only their expected rows,
|
|
1168
|
+
consumed revisions, auxiliary values and covering reverse predicates.
|
|
1169
|
+
All unresolved operations remain visible, including absent creates.
|
|
1170
|
+
Never publish this partial view as an application snapshot.
|
|
1171
|
+
"""
|
|
1172
|
+
from netherframe.core.backends.graph_diagnostics import validation_report
|
|
1173
|
+
|
|
1174
|
+
if any(proof.input.kind not in {RESOURCE, OUTPUT} for proof in basis.inputs):
|
|
1175
|
+
snapshot, owners = await self._scope_plan_view(conn, basis)
|
|
1176
|
+
problems = basis.problems(snapshot, run_id=run_id, object_owners=owners)
|
|
1177
|
+
return problems, validation_report(basis, snapshot, problems, run_id=run_id) if problems else None
|
|
1178
|
+
keys = {(row.kind, row.key) for row in basis.rows}
|
|
1179
|
+
keys.update((proof.input.kind, proof.input.key) for proof in basis.inputs)
|
|
1180
|
+
observation_keys = [item.key for item in basis.auxiliary if item.kind == OBSERVATION]
|
|
1181
|
+
# AuxiliaryExpectation.observe follows the same merged resource/cache
|
|
1182
|
+
# view as a full snapshot, even for a legacy observation address.
|
|
1183
|
+
keys.update((RESOURCE, key) for key in observation_keys)
|
|
1184
|
+
app = await conn.fetchrow(f"SELECT lineage, frontier, metadata, migrated_to, transfer_id FROM {self._t('apps')} WHERE state_id = $1", self.state_id)
|
|
1185
|
+
resource_keys = sorted(key for kind, key in keys if kind == RESOURCE)
|
|
1186
|
+
output_keys = sorted(key for kind, key in keys if kind == OUTPUT)
|
|
1187
|
+
entries = await conn.fetch(f"SELECT * FROM {self._t('entries')} WHERE state_id = $1 AND address = ANY($2::text[])", self.state_id, resource_keys) if resource_keys else []
|
|
1188
|
+
outputs = await conn.fetch(f"SELECT * FROM {self._t('outputs')} WHERE state_id = $1 AND key = ANY($2::text[])", self.state_id, output_keys) if output_keys else []
|
|
1189
|
+
observations = await conn.fetch(f"SELECT address, entry, private FROM {self._t('observations')} WHERE state_id = $1 AND address = ANY($2::text[])", self.state_id, observation_keys) if observation_keys else []
|
|
1190
|
+
operations = await self._operations(conn, unresolved=True, op_id=None)
|
|
1191
|
+
edge_index = await PostgreSQLReverseEdges(self).for_plan(conn, basis.edges)
|
|
1192
|
+
snapshot = self._snapshot_view(app, entries, outputs, observations, operations, edge_index)
|
|
1193
|
+
problems = basis.problems(snapshot, run_id=run_id, object_owners=await self._planning_owners(conn, basis.object_checks))
|
|
1194
|
+
return problems, validation_report(basis, snapshot, problems, run_id=run_id) if problems else None
|
|
1195
|
+
|
|
1196
|
+
def edge_predicate(self, key: str, *, kind: str = RESOURCE) -> EdgePredicate:
|
|
1197
|
+
return self._run(self._edge_predicate, kind, key)
|
|
1198
|
+
|
|
1199
|
+
async def _edge_predicate(self, kind: str, key: str) -> EdgePredicate:
|
|
1200
|
+
async with self._tx(readonly=True, isolation="repeatable_read") as conn:
|
|
1201
|
+
return await PostgreSQLReverseEdges(self).predicate(conn, kind, key)
|
|
1202
|
+
|
|
1203
|
+
# -- operations --------------------------------------------------------------------
|
|
1204
|
+
|
|
1205
|
+
async def _held(self, conn: asyncpg.Connection, keys: Sequence[str], run_id: str, *, other_than: Sequence[str] = ()) -> asyncpg.Record | None:
|
|
1206
|
+
"""An unresolved operation of another run holding one of ``keys`` (its address or footprint)."""
|
|
1207
|
+
return await conn.fetchrow(
|
|
1208
|
+
f"""
|
|
1209
|
+
SELECT op_id, action, address, stage, run_id FROM {self._t("operations")}
|
|
1210
|
+
WHERE state_id = $1 AND {_UNRESOLVED} AND run_id <> $2 AND NOT (op_id = ANY($4::text[]))
|
|
1211
|
+
AND (address = ANY($3::text[]) OR footprint ?| $3::text[])
|
|
1212
|
+
LIMIT 1
|
|
1213
|
+
""",
|
|
1214
|
+
self.state_id,
|
|
1215
|
+
run_id,
|
|
1216
|
+
list(keys),
|
|
1217
|
+
list(other_than),
|
|
1218
|
+
)
|
|
1219
|
+
|
|
1220
|
+
supports_creation_arms = True
|
|
1221
|
+
|
|
1222
|
+
def arm_creations(self, ownership: Ownership, specs: Sequence[OperationSpec]) -> None:
|
|
1223
|
+
from .graph_authorization import arm_creations
|
|
1224
|
+
|
|
1225
|
+
self._run(arm_creations, self, ownership, specs)
|
|
1226
|
+
|
|
1227
|
+
def reserve(self, ownership: Ownership, spec: OperationSpec) -> None:
|
|
1228
|
+
self._run(self._reserve, ownership, spec)
|
|
1229
|
+
|
|
1230
|
+
async def _reserve(self, ownership: Ownership, spec: OperationSpec) -> None:
|
|
1231
|
+
from netherframe.core.backends.graph_moves import check_move_reservation, move_plan
|
|
1232
|
+
|
|
1233
|
+
spec.request = bind_operation_request(spec)
|
|
1234
|
+
async with self._owned_tx(ownership, "reserve") as transaction:
|
|
1235
|
+
conn, run = transaction.conn, transaction.run
|
|
1236
|
+
if run["admitted"] and await self._check_admitted_targets(conn, ownership, [(RESOURCE, key) for key in (spec.address, *spec.footprint)], action=operation_permission(spec)):
|
|
1237
|
+
require_operation_contracts(spec)
|
|
1238
|
+
if spec.action == "create":
|
|
1239
|
+
actions = "admitted_actions -> $2::text" if self._admission_projections else "admitted_plan #> ARRAY['basis', 'actions', $2::text]"
|
|
1240
|
+
spec.request[ROLLBACK_ENABLED] = not run["admitted"] or bool(await conn.fetchval(f"SELECT coalesce({actions}, '[]'::jsonb) ? $3 FROM {self._t('runs')} WHERE run_id = $1", ownership.run_id, spec.address, ROLLBACK_DELETE))
|
|
1241
|
+
else:
|
|
1242
|
+
spec.request.pop(ROLLBACK_ENABLED, None)
|
|
1243
|
+
# Serialize identity reservations with one another and row commits.
|
|
1244
|
+
# No provider call runs while this short transaction is open.
|
|
1245
|
+
await conn.execute(f"SELECT 1 FROM {self._t('apps')} WHERE state_id = $1 FOR UPDATE", self.state_id)
|
|
1246
|
+
if group := move_plan(spec.request):
|
|
1247
|
+
if run["admitted"]:
|
|
1248
|
+
await self._check_admitted_targets(conn, ownership, list(group.basis.writes | {(item.kind, item.key) for item in group.basis.auxiliary}))
|
|
1249
|
+
check_move_reservation(spec, await self._snapshot_on(conn), ownership.run_id)
|
|
1250
|
+
keys = [spec.address, *spec.footprint]
|
|
1251
|
+
holder = await self._held(conn, keys, ownership.run_id)
|
|
1252
|
+
if holder is not None:
|
|
1253
|
+
raise QuarantinedError(
|
|
1254
|
+
f"{holder['address']} is held by unresolved operation {holder['op_id']} ({holder['action']}, {holder['stage']}, run {holder['run_id']}); resolve it with `nf state recover {holder['op_id']}` first",
|
|
1255
|
+
)
|
|
1256
|
+
row = await conn.fetchrow(f"SELECT * FROM {self._t('entries')} WHERE state_id = $1 AND address = $2 FOR UPDATE", self.state_id, spec.address)
|
|
1257
|
+
actual = _version_of(row) if row is not None else None
|
|
1258
|
+
if run["admitted"]:
|
|
1259
|
+
require_existing_identity(actual, spec.address)
|
|
1260
|
+
if not _same(actual, spec.expected, statuses=True):
|
|
1261
|
+
raise PreCallValidationError(f"{spec.address} changed since this run read it (expected {_describe(spec.expected)}, found {_describe(actual)}); nothing was sent")
|
|
1262
|
+
await self._validate_rollback_source(conn, ownership, spec, actual)
|
|
1263
|
+
if actual is not None and actual.status == UNCERTAIN:
|
|
1264
|
+
raise QuarantinedError(f"{spec.address} is uncertain (an earlier operation's outcome is unknown); resolve it with `nf state recover` first")
|
|
1265
|
+
await self._validate_inputs(conn, spec.address, spec.request, ownership.run_id)
|
|
1266
|
+
before = _entry_of(row["entry"], row["private"], row["status"]) if row is not None and not row["tombstone"] else None
|
|
1267
|
+
spec.request[FOOTPRINT] = operation_footprint(spec, before, actual)
|
|
1268
|
+
operations = await self._validate_footprint(conn, spec.request[FOOTPRINT], ownership, allocation_scopes=tuple(object_request(spec.request, spec.action).allocation_scopes))
|
|
1269
|
+
await self._validate_objects(conn, spec.address, spec.request, spec.action, run_id=ownership.run_id, operation_snapshot=operations)
|
|
1270
|
+
await conn.execute(
|
|
1271
|
+
f"""
|
|
1272
|
+
INSERT INTO {self._t("operations")} (op_id, state_id, run_id, epoch, address, footprint, object_identity, action, stage,
|
|
1273
|
+
expected, expected_provider, request, request_digest, owner_host, owner_pid, provider_pid)
|
|
1274
|
+
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 'reserved', $9, $10, $11, $12, $13, $14, $15)
|
|
1275
|
+
""",
|
|
1276
|
+
spec.op_id,
|
|
1277
|
+
self.state_id,
|
|
1278
|
+
ownership.run_id,
|
|
1279
|
+
ownership.epoch,
|
|
1280
|
+
spec.address,
|
|
1281
|
+
_json(list(spec.footprint)),
|
|
1282
|
+
actual.object_identity if actual is not None else None,
|
|
1283
|
+
spec.action,
|
|
1284
|
+
_json(spec.expected.to_dict()) if spec.expected is not None else None,
|
|
1285
|
+
spec.provider,
|
|
1286
|
+
_json(spec.request),
|
|
1287
|
+
spec.request_digest,
|
|
1288
|
+
spec.owner_host,
|
|
1289
|
+
spec.owner_pid,
|
|
1290
|
+
spec.provider_pid,
|
|
1291
|
+
)
|
|
1292
|
+
|
|
1293
|
+
async def _locked_operation(self, conn: asyncpg.Connection, ownership: Ownership, op_id: str, *, include_request: bool = False) -> asyncpg.Record:
|
|
1294
|
+
# The caller holds its ownership transaction throughout this row wait.
|
|
1295
|
+
request_column = ", request" if include_request else ""
|
|
1296
|
+
record = await conn.fetchrow(f"SELECT op_id, epoch, attempt, run_id, recovered_by, stage, address, footprint, action{request_column} FROM {self._t('operations')} WHERE op_id = $1 AND state_id = $2 FOR UPDATE", op_id, self.state_id)
|
|
1297
|
+
if record is None:
|
|
1298
|
+
raise StateError(f"No operation {op_id}")
|
|
1299
|
+
ownership.check_operation(record["op_id"], record["run_id"], int(record["epoch"]), int(record["attempt"]), record["recovered_by"])
|
|
1300
|
+
if record["stage"] in FINAL_STAGES:
|
|
1301
|
+
raise StateError(f"Operation {op_id} is already {record['stage']}")
|
|
1302
|
+
return record
|
|
1303
|
+
|
|
1304
|
+
async def _locked_operations(self, conn: asyncpg.Connection, ownership: Ownership, op_ids: Sequence[str]) -> dict[str, asyncpg.Record]:
|
|
1305
|
+
"""Lock a bounded publication's operations, retaining every ownership check."""
|
|
1306
|
+
rows = await conn.fetch(
|
|
1307
|
+
f"SELECT op_id, epoch, attempt, run_id, recovered_by, stage, address, footprint, action, request, error FROM {self._t('operations')} WHERE state_id = $1 AND op_id = ANY($2::text[]) ORDER BY op_id FOR UPDATE",
|
|
1308
|
+
self.state_id,
|
|
1309
|
+
list(op_ids),
|
|
1310
|
+
)
|
|
1311
|
+
records = {record["op_id"]: record for record in rows}
|
|
1312
|
+
for op_id in op_ids:
|
|
1313
|
+
record = records.get(op_id)
|
|
1314
|
+
if record is None:
|
|
1315
|
+
raise StateError(f"No operation {op_id}")
|
|
1316
|
+
ownership.check_operation(record["op_id"], record["run_id"], int(record["epoch"]), int(record["attempt"]), record["recovered_by"])
|
|
1317
|
+
if record["stage"] in FINAL_STAGES:
|
|
1318
|
+
raise StateError(f"Operation {op_id} is already {record['stage']}")
|
|
1319
|
+
return records
|
|
1320
|
+
|
|
1321
|
+
def dispatch(self, ownership: Ownership, op_id: str, stage: str = "dispatched", *, provider_pid: int | None = None) -> None:
|
|
1322
|
+
self._run(self._dispatch, ownership, op_id, stage, provider_pid)
|
|
1323
|
+
|
|
1324
|
+
async def _dispatch(self, ownership: Ownership, op_id: str, stage: str, provider_pid: int | None) -> None:
|
|
1325
|
+
from netherframe.core.backends.graph_moves import MOVE_GROUP
|
|
1326
|
+
|
|
1327
|
+
async with self._owned_tx(ownership, "dispatch", recovery=ownership.claim is not None) as transaction:
|
|
1328
|
+
conn = transaction.conn
|
|
1329
|
+
await self._locked_operation(conn, ownership, op_id)
|
|
1330
|
+
if ownership.claim is not None:
|
|
1331
|
+
raise PreCallValidationError("Recovery resolves old operations; it cannot dispatch a new provider mutation")
|
|
1332
|
+
await conn.execute(f"SELECT 1 FROM {self._t('apps')} WHERE state_id = $1 FOR UPDATE", self.state_id)
|
|
1333
|
+
[operation] = await self._operations(conn, unresolved=True, op_id=op_id)
|
|
1334
|
+
validate_operation_dispatch(operation.stage, stage)
|
|
1335
|
+
if MOVE_GROUP in operation.request:
|
|
1336
|
+
raise PreCallValidationError("A state move conversion is read-only and cannot dispatch a provider mutation")
|
|
1337
|
+
spec = OperationSpec(operation.op_id, operation.address, operation.action, operation.expected, operation.expected_provider or "", operation.request, operation.footprint)
|
|
1338
|
+
if transaction.run["admitted"] and await self._check_admitted_targets(conn, ownership, [(RESOURCE, key) for key in (operation.address, *operation.footprint)], action=operation_permission(spec)):
|
|
1339
|
+
require_operation_contracts(spec)
|
|
1340
|
+
if operation_permission(spec) == ROLLBACK_DELETE:
|
|
1341
|
+
current = await conn.fetchrow(f"SELECT * FROM {self._t('entries')} WHERE state_id = $1 AND address = $2", self.state_id, operation.address)
|
|
1342
|
+
await self._validate_rollback_source(conn, ownership, spec, _version_of(current) if current is not None else None)
|
|
1343
|
+
operations = await self._validate_footprint(conn, retained_footprint(operation), ownership, exclude=(op_id,), allocation_scopes=tuple(object_request(operation.request, operation.action).allocation_scopes))
|
|
1344
|
+
await self._validate_inputs(conn, operation.address, operation.request, ownership.run_id)
|
|
1345
|
+
await self._validate_objects(conn, operation.address, operation.request, operation.action, exclude_op=op_id, run_id=ownership.run_id, operation_snapshot=operations)
|
|
1346
|
+
await conn.execute(
|
|
1347
|
+
f"UPDATE {self._t('operations')} SET stage = $2, dispatched_at = clock_timestamp(), result = NULL, error = NULL, provider_pid = coalesce($3, provider_pid) WHERE op_id = $1",
|
|
1348
|
+
op_id,
|
|
1349
|
+
stage,
|
|
1350
|
+
provider_pid,
|
|
1351
|
+
)
|
|
1352
|
+
|
|
1353
|
+
async def _validate_rollback_source(self, conn: asyncpg.Connection, ownership: Ownership, spec: OperationSpec, current: RowVersion | None) -> None:
|
|
1354
|
+
if operation_permission(spec) != ROLLBACK_DELETE:
|
|
1355
|
+
return
|
|
1356
|
+
records = await self._operations(conn, unresolved=False, op_id=spec.request[ROLLBACK_OF])
|
|
1357
|
+
require_rollback_source(spec, ownership, records[0] if records else None, current)
|
|
1358
|
+
|
|
1359
|
+
def record_return(self, ownership: Ownership, op_id: str, result: dict[str, Any] | None, error: str | None = None) -> None:
|
|
1360
|
+
self._run(self._record_return, ownership, op_id, result, error)
|
|
1361
|
+
|
|
1362
|
+
# Qualified protocol, but the E56 end-to-end gate regresses wall time and
|
|
1363
|
+
# publication count. The qualification harness opts in explicitly.
|
|
1364
|
+
supports_creation_completions = False
|
|
1365
|
+
# Raw-only cohorts use the same fenced receipt primitive without taking
|
|
1366
|
+
# the app publication frontier or offering optional state writes.
|
|
1367
|
+
supports_creation_return_batches = True
|
|
1368
|
+
|
|
1369
|
+
def complete_creations(self, ownership, completions):
|
|
1370
|
+
from .graph_completion import complete_creations
|
|
1371
|
+
|
|
1372
|
+
return self._run(complete_creations, self, ownership, list(completions))
|
|
1373
|
+
|
|
1374
|
+
async def _record_return(self, ownership: Ownership, op_id: str, result: dict[str, Any] | None, error: str | None) -> None:
|
|
1375
|
+
async with self._owned_tx(ownership, "return", recovery=ownership.claim is not None) as transaction:
|
|
1376
|
+
conn = transaction.conn
|
|
1377
|
+
record = await self._locked_operation(conn, ownership, op_id)
|
|
1378
|
+
if ownership.claim is not None:
|
|
1379
|
+
raise PreCallValidationError("A recovery claim cannot replace the original call's returned result")
|
|
1380
|
+
await conn.execute(
|
|
1381
|
+
f"UPDATE {self._t('operations')} SET stage = 'returned', result = $2, error = $3, returned_at = clock_timestamp() WHERE op_id = $1",
|
|
1382
|
+
op_id,
|
|
1383
|
+
_json({"stage": record["stage"], "value": result}),
|
|
1384
|
+
error,
|
|
1385
|
+
)
|
|
1386
|
+
|
|
1387
|
+
def restore_return(self, ownership: Ownership, kept: KeptReturn) -> None:
|
|
1388
|
+
self._run(self._restore_return, ownership, kept)
|
|
1389
|
+
|
|
1390
|
+
async def _restore_return(self, ownership: Ownership, kept: KeptReturn) -> None:
|
|
1391
|
+
if ownership.claim is None:
|
|
1392
|
+
raise PreCallValidationError("Restoring a kept response requires its explicit recovery claim")
|
|
1393
|
+
async with self._owned_tx(ownership, "restore kept return", recovery=True) as transaction:
|
|
1394
|
+
conn = transaction.conn
|
|
1395
|
+
await self._locked_operation(conn, ownership, kept.identity.op_id)
|
|
1396
|
+
[record] = await self._operations(conn, unresolved=False, op_id=kept.identity.op_id)
|
|
1397
|
+
if kept.check(record):
|
|
1398
|
+
return
|
|
1399
|
+
await conn.execute(
|
|
1400
|
+
f"UPDATE {self._t('operations')} SET stage = 'returned', result = $2, error = $3, returned_at = clock_timestamp() WHERE op_id = $1",
|
|
1401
|
+
kept.identity.op_id,
|
|
1402
|
+
_json(kept.envelope),
|
|
1403
|
+
kept.error,
|
|
1404
|
+
)
|
|
1405
|
+
|
|
1406
|
+
def commit(self, ownership: Ownership, writes: Sequence[RowWrite], *, ops: Mapping[str, str] | None = None, outcome: str | None = None) -> CommitResult:
|
|
1407
|
+
try:
|
|
1408
|
+
return self._run(self._commit, ownership, list(writes), dict(ops or {}), outcome)
|
|
1409
|
+
except asyncpg.UniqueViolationError as exc:
|
|
1410
|
+
raise StateConflictError(f"Two addresses would manage the same object, which the graph state refuses: {getattr(exc, 'detail', None) or exc}") from exc
|
|
1411
|
+
|
|
1412
|
+
def record_recovery_probe(self, ownership: Ownership, op_id: str, probe: Probe, *, quiescence: float | None, confirm_terminated: bool) -> None:
|
|
1413
|
+
self._run(self._record_recovery_probe, ownership, op_id, probe, quiescence, confirm_terminated)
|
|
1414
|
+
|
|
1415
|
+
async def _record_recovery_probe(self, ownership: Ownership, op_id: str, probe: Probe, quiescence: float | None, confirm_terminated: bool) -> None:
|
|
1416
|
+
if ownership.claim is None:
|
|
1417
|
+
raise PreCallValidationError("A recovery observation requires its explicit operation claim")
|
|
1418
|
+
async with self._owned_tx(ownership, "record recovery probe", recovery=True) as transaction:
|
|
1419
|
+
conn = transaction.conn
|
|
1420
|
+
await self._locked_operation(conn, ownership, op_id)
|
|
1421
|
+
[record] = await self._operations(conn, unresolved=False, op_id=op_id)
|
|
1422
|
+
result = recovery_probe_result(record, probe, quiescence=quiescence, confirm_terminated=confirm_terminated)
|
|
1423
|
+
await conn.execute(f"UPDATE {self._t('operations')} SET stage = 'returned', result = $2, error = NULL, returned_at = clock_timestamp() WHERE op_id = $1", op_id, _json(result))
|
|
1424
|
+
|
|
1425
|
+
async def _commit(self, ownership: Ownership, writes: list[RowWrite], ops: dict[str, str], outcome: str | None) -> CommitResult:
|
|
1426
|
+
async with self._owned_tx(ownership, "commit", recovery=ownership.claim is not None) as transaction:
|
|
1427
|
+
return await self._commit_on(transaction, writes, ops, outcome)
|
|
1428
|
+
|
|
1429
|
+
async def _commit_on(self, transaction: _OwnedTransaction, writes: list[RowWrite], ops: dict[str, str], outcome: str | None, records=None) -> CommitResult:
|
|
1430
|
+
from netherframe.core.backends.graph_moves import MOVE_GROUP, check_move_commit, move_targets
|
|
1431
|
+
|
|
1432
|
+
if transaction.planning:
|
|
1433
|
+
raise PreCallValidationError("A planning scope cannot commit resource state")
|
|
1434
|
+
if transaction.sequences:
|
|
1435
|
+
raise PreCallValidationError("A SQL transaction publishes one graph commit sequence")
|
|
1436
|
+
conn, ownership, run = transaction.conn, transaction.ownership, transaction.run
|
|
1437
|
+
if ownership.claim is None and run["admitted"] and await self._check_admitted_targets(conn, ownership, [(write.kind, write.key) for write in writes]):
|
|
1438
|
+
require_write_contracts(writes)
|
|
1439
|
+
validate_recovery_writes(ownership, writes, ops)
|
|
1440
|
+
footprints = {}
|
|
1441
|
+
if records is None:
|
|
1442
|
+
records = await self._locked_operations(conn, ownership, list(ops)) if 2 <= len(ops) <= PUBLICATION_MAX_ROWS else {}
|
|
1443
|
+
for op_id, stage in ops.items():
|
|
1444
|
+
record = records[op_id] if op_id in records else await self._locked_operation(conn, ownership, op_id, include_request=True)
|
|
1445
|
+
validate_operation_resolution(record["stage"], stage, action=record["action"])
|
|
1446
|
+
records[op_id] = record
|
|
1447
|
+
footprints[op_id] = [record["address"], *(_load(record["footprint"]) or [])]
|
|
1448
|
+
groups = {}
|
|
1449
|
+
group_records = {}
|
|
1450
|
+
for op_id, record in records.items():
|
|
1451
|
+
if MOVE_GROUP in (_load(record["request"]) or {}):
|
|
1452
|
+
[group_records[op_id]] = await self._operations(conn, unresolved=True, op_id=op_id)
|
|
1453
|
+
if group_records:
|
|
1454
|
+
if set(records) != set(group_records) or any(ops[op_id] != COMMITTED for op_id in group_records):
|
|
1455
|
+
raise StateError("An atomic move must commit in its own transaction")
|
|
1456
|
+
groups = move_targets(group_records)
|
|
1457
|
+
validate_write_operations(writes, footprints, groups)
|
|
1458
|
+
ordered = sorted(writes, key=lambda write: not write.removal)
|
|
1459
|
+
resource_keys = [write.key for write in ordered if write.kind == RESOURCE]
|
|
1460
|
+
if resource_keys:
|
|
1461
|
+
holder = await self._held(conn, resource_keys, ownership.run_id, other_than=[write.op_id for write in ordered if write.op_id] + list(ops))
|
|
1462
|
+
if holder is not None:
|
|
1463
|
+
raise QuarantinedError(f"{holder['address']} is held by unresolved operation {holder['op_id']}; resolve it with `nf state recover {holder['op_id']}` first")
|
|
1464
|
+
# The commit counter, inside the transaction: sequence order is commit order
|
|
1465
|
+
sequence = int(await conn.fetchval(f"UPDATE {self._t('apps')} SET frontier = frontier + 1 WHERE state_id = $1 RETURNING frontier", self.state_id))
|
|
1466
|
+
moving = check_move_commit(group_records, writes, await self._snapshot_on(conn)) if group_records else set()
|
|
1467
|
+
output_keys = [write.key for write in ordered if write.kind == OUTPUT]
|
|
1468
|
+
resource_rows = await conn.fetch(f"SELECT * FROM {self._t('entries')} WHERE state_id = $1 AND address = ANY($2::text[])", self.state_id, resource_keys) if resource_keys else []
|
|
1469
|
+
output_rows = await conn.fetch(f"SELECT * FROM {self._t('outputs')} WHERE state_id = $1 AND key = ANY($2::text[])", self.state_id, output_keys) if output_keys else []
|
|
1470
|
+
old_resources = {row["address"]: row for row in resource_rows}
|
|
1471
|
+
old_outputs = {row["key"]: row for row in output_rows}
|
|
1472
|
+
demands = []
|
|
1473
|
+
for write in ordered:
|
|
1474
|
+
old = (old_outputs if write.kind == OUTPUT else old_resources).get(write.key)
|
|
1475
|
+
before = _entry_of(old["entry"], old["private"], old["status"]) if old is not None and write.kind == RESOURCE and not old["tombstone"] else None
|
|
1476
|
+
version = (self._output_version(old) if write.kind == OUTPUT else _version_of(old)) if old is not None else None
|
|
1477
|
+
if ownership.claim is None and run["admitted"] and write.kind == RESOURCE:
|
|
1478
|
+
require_existing_identity(version, write.key)
|
|
1479
|
+
operation = records.get(write.op_id) if write.op_id is not None else None
|
|
1480
|
+
demands.append(write_footprint(write, before, version, action=operation["action"] if operation is not None else None))
|
|
1481
|
+
operation_snapshot = await self._validate_footprint(conn, combine_footprints(demands), ownership, exclude=tuple(ops), recovering=tuple(ops)) if demands else None
|
|
1482
|
+
if moving:
|
|
1483
|
+
# The collective check above established final uniqueness. Release
|
|
1484
|
+
# the group's old keys together, inside this transaction, so swaps
|
|
1485
|
+
# do not transiently violate the immediate unique index.
|
|
1486
|
+
await conn.execute(f"UPDATE {self._t('entries')} SET object_identity = NULL WHERE state_id = $1 AND address = ANY($2::text[])", self.state_id, sorted(moving))
|
|
1487
|
+
result = CommitResult(sequence)
|
|
1488
|
+
owners = [(write.kind, write.key) for write in ordered if write.kind in {RESOURCE, OUTPUT}]
|
|
1489
|
+
reverse_edges = PostgreSQLReverseEdges(self)
|
|
1490
|
+
before_edges = await reverse_edges.for_owners(conn, owners)
|
|
1491
|
+
bulk = await publish_state_batch(self, conn, ownership, ordered, sequence, operation_snapshot or ()) if not ops and ownership.claim is None else None
|
|
1492
|
+
bulk_creations = False
|
|
1493
|
+
if ops and ownership.claim is None and 2 <= len(ops) <= PUBLICATION_MAX_ROWS and all(stage == COMMITTED for stage in ops.values()):
|
|
1494
|
+
bulk = await publish_creation_batch(self, conn, ownership, ordered, sequence, records, operation_snapshot or ())
|
|
1495
|
+
bulk_creations = bulk is not None
|
|
1496
|
+
if bulk is not None:
|
|
1497
|
+
result.versions.update(bulk)
|
|
1498
|
+
object_entries = await self._object_entry_guard(conn, ordered, old_resources) if bulk is None and any(write.kind == RESOURCE and not write.removal for write in ordered) else None
|
|
1499
|
+
for write in ordered if bulk is None else ():
|
|
1500
|
+
if write.kind == METADATA:
|
|
1501
|
+
await conn.execute(f"UPDATE {self._t('apps')} SET metadata = $2 WHERE state_id = $1", self.state_id, _json(write.entry or {}))
|
|
1502
|
+
elif write.kind == OBSERVATION:
|
|
1503
|
+
await self._observe(conn, ownership, write)
|
|
1504
|
+
elif write.kind == OUTPUT:
|
|
1505
|
+
result.versions[OUTPUT, write.key] = await self._write_output(conn, ownership, write, sequence)
|
|
1506
|
+
else:
|
|
1507
|
+
original = _version_of(old_resources[write.key]) if write.key in moving and write.key in old_resources else None
|
|
1508
|
+
result.versions[RESOURCE, write.key] = await self._write_entry(
|
|
1509
|
+
conn, ownership, write, sequence, validate_objects=write.key not in moving, original=original, operation_snapshot=operation_snapshot, object_entries=object_entries
|
|
1510
|
+
)
|
|
1511
|
+
if object_entries is not None:
|
|
1512
|
+
object_entries.replace(write.key, None if write.removal else write.entry)
|
|
1513
|
+
await self._mark_stale_inputs(conn, ownership, result)
|
|
1514
|
+
result.edge_delta = await reverse_edges.delta(conn, before_edges, owners)
|
|
1515
|
+
if bulk_creations:
|
|
1516
|
+
await conn.execute(
|
|
1517
|
+
f"UPDATE {self._t('operations')} SET stage = 'committed', outcome = $2, resolved_at = clock_timestamp() WHERE state_id = $1 AND op_id = ANY($3::text[])",
|
|
1518
|
+
self.state_id,
|
|
1519
|
+
outcome or f"committed at sequence {sequence}",
|
|
1520
|
+
list(ops),
|
|
1521
|
+
)
|
|
1522
|
+
for op_id, stage in () if bulk_creations else ops.items():
|
|
1523
|
+
final = stage in FINAL_STAGES
|
|
1524
|
+
await conn.execute(
|
|
1525
|
+
f"UPDATE {self._t('operations')} SET stage = $2, outcome = CASE WHEN $3 THEN $4 ELSE outcome END, resolved_at = CASE WHEN $3 THEN clock_timestamp() ELSE resolved_at END WHERE op_id = $1",
|
|
1526
|
+
op_id,
|
|
1527
|
+
stage,
|
|
1528
|
+
final,
|
|
1529
|
+
outcome or f"committed at sequence {sequence}",
|
|
1530
|
+
)
|
|
1531
|
+
transaction.sequences.append(sequence)
|
|
1532
|
+
return result
|
|
1533
|
+
|
|
1534
|
+
async def _observe(self, conn: asyncpg.Connection, ownership: Ownership, write: RowWrite) -> None:
|
|
1535
|
+
if write.removal:
|
|
1536
|
+
await conn.execute(f"DELETE FROM {self._t('observations')} WHERE state_id = $1 AND address = $2", self.state_id, write.key)
|
|
1537
|
+
return
|
|
1538
|
+
entry: ResourceState = write.entry
|
|
1539
|
+
await conn.execute(
|
|
1540
|
+
f"""
|
|
1541
|
+
INSERT INTO {self._t("observations")} (state_id, address, entry, private, run_id) VALUES ($1, $2, $3, $4, $5)
|
|
1542
|
+
ON CONFLICT (state_id, address) DO UPDATE SET entry = EXCLUDED.entry, private = EXCLUDED.private, run_id = EXCLUDED.run_id, updated_at = clock_timestamp()
|
|
1543
|
+
""",
|
|
1544
|
+
self.state_id,
|
|
1545
|
+
write.key,
|
|
1546
|
+
_json(_entry_document(entry)),
|
|
1547
|
+
entry.private or None,
|
|
1548
|
+
ownership.run_id,
|
|
1549
|
+
)
|
|
1550
|
+
|
|
1551
|
+
async def _validate_inputs(self, conn: asyncpg.Connection, address: str, request: Mapping[str, Any], run_id: str) -> None:
|
|
1552
|
+
inputs = decode_inputs(request.get("inputs"))
|
|
1553
|
+
if not inputs:
|
|
1554
|
+
return
|
|
1555
|
+
scoped = any(item.kind in {"scope", "enumeration"} for item in inputs)
|
|
1556
|
+
resource_keys = [item.key for item in inputs if item.kind == RESOURCE]
|
|
1557
|
+
output_keys = [item.key for item in inputs if item.kind == OUTPUT]
|
|
1558
|
+
entries = await conn.fetch(f"SELECT * FROM {self._t('entries')} WHERE state_id = $1 AND ($2::boolean OR address = ANY($3::text[]))", self.state_id, scoped, resource_keys) if scoped or resource_keys else []
|
|
1559
|
+
output_rows = await conn.fetch(f"SELECT * FROM {self._t('outputs')} WHERE state_id = $1 AND ($2::boolean OR key = ANY($3::text[]))", self.state_id, scoped, output_keys) if scoped or output_keys else []
|
|
1560
|
+
resources = {row["address"]: _version_of(row) for row in entries}
|
|
1561
|
+
outputs = {row["key"]: self._output_version(row) for row in output_rows}
|
|
1562
|
+
changed = changed_inputs(inputs, resources, outputs, owner=(RESOURCE, address))
|
|
1563
|
+
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)]
|
|
1564
|
+
operations = await conn.fetch(f"SELECT address, footprint FROM {self._t('operations')} WHERE state_id = $1 AND run_id <> $2 AND {_UNRESOLVED}", self.state_id, run_id)
|
|
1565
|
+
uncertain.extend(key for operation in operations for key in (operation["address"], *(_load(operation["footprint"]) or [])) if any(input_covers(item, RESOURCE, key) for item in inputs))
|
|
1566
|
+
if changed or uncertain:
|
|
1567
|
+
keys = sorted({item.key for item in changed} | set(uncertain))
|
|
1568
|
+
raise PreCallValidationError(f"{address}: consumed inputs changed or are unresolved before dispatch: {', '.join(keys)}; replan before applying")
|
|
1569
|
+
|
|
1570
|
+
async def _validate_footprint(
|
|
1571
|
+
self, conn: asyncpg.Connection, wanted: Mapping[str, str], ownership: Ownership, *, exclude: Sequence[str] = (), recovering: Sequence[str] = (), allocation_scopes: Sequence[str] = ()
|
|
1572
|
+
) -> ObjectOperationGuard:
|
|
1573
|
+
if ownership.claim is not None:
|
|
1574
|
+
operation = await self._locked_operation(conn, ownership, ownership.claim.op_id, include_request=True)
|
|
1575
|
+
held = recovery_footprint(_load(operation["request"]) or {})
|
|
1576
|
+
else:
|
|
1577
|
+
# Coverage only depends on the demanded keys and their ancestors.
|
|
1578
|
+
# Fetching the complete run grant here made N independent row
|
|
1579
|
+
# commits transfer O(N²) leases. Initial and tail fences still
|
|
1580
|
+
# verify the complete grant, including unrelated keys and modes.
|
|
1581
|
+
keys = set(wanted)
|
|
1582
|
+
for encoded in wanted:
|
|
1583
|
+
key = LeaseKey.decode(encoded)
|
|
1584
|
+
keys.update(LeaseKey(key.parts[:length]).encoded for length in range(len(key.parts)))
|
|
1585
|
+
rows = await conn.fetch(f"SELECT key, mode FROM {self._t('leases')} WHERE state_id = $1 AND holder = $2 AND key = ANY($3::text[]) FOR SHARE", self.state_id, ownership.run_id, sorted(keys))
|
|
1586
|
+
held = {row["key"]: row["mode"] for row in rows}
|
|
1587
|
+
if missing_leases(held, wanted):
|
|
1588
|
+
raise PreCallValidationError("The mutation's full footprint is not covered by the run's granted leases")
|
|
1589
|
+
operations = ObjectOperationGuard(await self._operation_guards(conn))
|
|
1590
|
+
if ownership.claim is None:
|
|
1591
|
+
if blocked := conflicting_owned_operations(wanted, operations, run_id=ownership.run_id, exclude=exclude, allocation_scopes=allocation_scopes):
|
|
1592
|
+
raise SiblingOperationBusyError([(record.op_id, record.address) for record in operations if record.op_id in blocked])
|
|
1593
|
+
if problems := footprint_problems(wanted, operations, run_id=ownership.run_id, exclude=exclude, recovering=recovering):
|
|
1594
|
+
raise QuarantinedError("Mutation blocked by operation quarantine:\n" + "\n".join(problems))
|
|
1595
|
+
return operations
|
|
1596
|
+
|
|
1597
|
+
async def _object_entry_guard(self, conn: asyncpg.Connection, writes: Sequence[RowWrite], old_rows: Mapping[str, Any]) -> ObjectEntryGuard:
|
|
1598
|
+
"""Load peer evidence once while this commit owns the app frontier lock.
|
|
1599
|
+
|
|
1600
|
+
Unchanged legacy normalization cannot conflict with unknown peers. Omit
|
|
1601
|
+
those rows at SQL selection too, while still checking every bound peer
|
|
1602
|
+
and identity learned by earlier writes. Existing partial indexes cover
|
|
1603
|
+
the legacy and bound predicates.
|
|
1604
|
+
"""
|
|
1605
|
+
addresses, identities, legacy_types, bound_types, normalizing_types = set(), set(), set(), set(), set()
|
|
1606
|
+
for write in writes:
|
|
1607
|
+
if write.kind != RESOURCE or write.removal:
|
|
1608
|
+
continue
|
|
1609
|
+
addresses.add(write.key)
|
|
1610
|
+
claims = object_request({"template": write.entry.to_dict()}, "import")
|
|
1611
|
+
identities.update(claims.identities)
|
|
1612
|
+
old = old_rows.get(write.key)
|
|
1613
|
+
previous = _entry_of(old["entry"], old["private"], old["status"]) if old is not None and not old["tombstone"] else None
|
|
1614
|
+
types = {kind for _source, kind in claims.sources}
|
|
1615
|
+
if claims.bound_sources:
|
|
1616
|
+
(normalizing_types if legacy_normalization(write, previous) else legacy_types).update(types)
|
|
1617
|
+
else:
|
|
1618
|
+
bound_types.update(types)
|
|
1619
|
+
rows = await conn.fetch(
|
|
1620
|
+
f"""SELECT entry, private, status, object_identity FROM {self._t("entries")} WHERE state_id = $1 AND NOT tombstone
|
|
1621
|
+
AND (address = ANY($2::text[]) OR object_identity = ANY($3::text[])
|
|
1622
|
+
OR (type = ANY($4::text[]) AND (object_identity IS NULL OR object_identity NOT LIKE 'nf-object-v1:%'))
|
|
1623
|
+
OR (type = ANY($5::text[]) AND coalesce(entry #> '{{metadata,graph_object}}', 'null'::jsonb) <> 'null'::jsonb)
|
|
1624
|
+
OR (type = ANY($6::text[]) AND (object_identity IS NULL OR object_identity NOT LIKE 'nf-object-v1:%')
|
|
1625
|
+
AND coalesce(entry #> '{{metadata,graph_object}}', 'null'::jsonb) <> 'null'::jsonb))""",
|
|
1626
|
+
self.state_id,
|
|
1627
|
+
sorted(addresses),
|
|
1628
|
+
sorted(identities),
|
|
1629
|
+
sorted(legacy_types),
|
|
1630
|
+
sorted(bound_types),
|
|
1631
|
+
sorted(normalizing_types),
|
|
1632
|
+
)
|
|
1633
|
+
return ObjectEntryGuard([_entry_of(row["entry"], row["private"], row["status"]) for row in rows])
|
|
1634
|
+
|
|
1635
|
+
async def _validate_objects(
|
|
1636
|
+
self,
|
|
1637
|
+
conn: asyncpg.Connection,
|
|
1638
|
+
address: str,
|
|
1639
|
+
request: Mapping[str, Any],
|
|
1640
|
+
action: str,
|
|
1641
|
+
*,
|
|
1642
|
+
exclude_op: str | None = None,
|
|
1643
|
+
allow_legacy_normalization: bool = False,
|
|
1644
|
+
run_id: str | None = None,
|
|
1645
|
+
operation_snapshot: Sequence[OperationRecord] | None = None,
|
|
1646
|
+
object_entries: ObjectEntryGuard | None = None,
|
|
1647
|
+
) -> None:
|
|
1648
|
+
claims = object_request(request, action)
|
|
1649
|
+
rows = (
|
|
1650
|
+
await conn.fetch(
|
|
1651
|
+
f"""SELECT entry, private, status FROM {self._t("entries")} WHERE state_id = $1 AND NOT tombstone
|
|
1652
|
+
AND (address = $2 OR object_identity = ANY($3::text[]) OR (type = ANY($4::text[]) AND (
|
|
1653
|
+
($5::boolean AND (object_identity IS NULL OR object_identity NOT LIKE 'nf-object-v1:%'))
|
|
1654
|
+
OR (NOT $5::boolean AND coalesce(entry #> '{{metadata,graph_object}}', 'null'::jsonb) <> 'null'::jsonb))))""",
|
|
1655
|
+
self.state_id,
|
|
1656
|
+
address,
|
|
1657
|
+
list(claims.identities),
|
|
1658
|
+
[kind for _source, kind in claims.sources],
|
|
1659
|
+
bool(claims.bound_sources),
|
|
1660
|
+
)
|
|
1661
|
+
if object_entries is None
|
|
1662
|
+
else ()
|
|
1663
|
+
)
|
|
1664
|
+
entries = object_entries.candidates(address, claims, allow_legacy_normalization=allow_legacy_normalization) if object_entries is not None else [_entry_of(row["entry"], row["private"], row["status"]) for row in rows]
|
|
1665
|
+
# Callers may reuse the footprint check's ledger only while holding the
|
|
1666
|
+
# same app-row lock: no new reservation, dispatch or publication can
|
|
1667
|
+
# change its exclusion evidence. Return/abort can only relax it. Entry
|
|
1668
|
+
# candidates above remain fresh, including earlier writes in this batch.
|
|
1669
|
+
operations = await self._operation_guards(conn) if operation_snapshot is None else operation_snapshot
|
|
1670
|
+
if problems := object_problems(address, request, action, entries, operations, exclude_op=exclude_op, allow_legacy_normalization=allow_legacy_normalization, run_id=run_id, claims=claims):
|
|
1671
|
+
raise PreCallValidationError("Cloud ownership validation failed:\n" + "\n".join(problems))
|
|
1672
|
+
|
|
1673
|
+
async def _mark_stale_inputs(self, conn: asyncpg.Connection, ownership: Ownership, result: CommitResult) -> None:
|
|
1674
|
+
"""Version stale consumers in the input's transaction, including transitive ones.
|
|
1675
|
+
|
|
1676
|
+
The app counter row serializes commits while its app lease is held.
|
|
1677
|
+
Later resource leasing also protects this predicate with reverse-edge keys.
|
|
1678
|
+
"""
|
|
1679
|
+
excluded: set[tuple[str, str]] = set()
|
|
1680
|
+
changed = set(result.versions)
|
|
1681
|
+
reverse_edges = PostgreSQLReverseEdges(self)
|
|
1682
|
+
while changed:
|
|
1683
|
+
# Versions just returned by this transaction already tell us which
|
|
1684
|
+
# written rows can need their own inputs checked. Empty inputs
|
|
1685
|
+
# cannot become stale, and stale rows need no second invalidation.
|
|
1686
|
+
check_written = {(kind, key) for kind, key in changed if result.versions[kind, key].status == "ready" and result.versions[kind, key].inputs}
|
|
1687
|
+
entries = await reverse_edges.ready_consumers(conn, changed, RESOURCE, sorted(key for kind, key in check_written if kind == RESOURCE))
|
|
1688
|
+
outputs = await reverse_edges.ready_consumers(conn, changed, OUTPUT, sorted(key for kind, key in check_written if kind == OUTPUT))
|
|
1689
|
+
candidates = [(RESOURCE, row["address"], row) for row in entries] + [(OUTPUT, row["key"], row) for row in outputs]
|
|
1690
|
+
candidates = [(kind, key, row) for kind, key, row in candidates if (kind, key) not in excluded]
|
|
1691
|
+
if not candidates:
|
|
1692
|
+
return
|
|
1693
|
+
reads = [item for _, _, row in candidates for item in decode_inputs(_load(row["inputs"])) or ()]
|
|
1694
|
+
if not reads:
|
|
1695
|
+
return
|
|
1696
|
+
scoped = any(item.kind in {"scope", "enumeration"} for item in reads)
|
|
1697
|
+
resource_keys = [item.key for item in reads if item.kind == RESOURCE]
|
|
1698
|
+
output_keys = [item.key for item in reads if item.kind == OUTPUT]
|
|
1699
|
+
resource_rows = await conn.fetch(f"SELECT * FROM {self._t('entries')} WHERE state_id = $1 AND ($2::boolean OR address = ANY($3::text[]))", self.state_id, scoped, resource_keys) if scoped or resource_keys else []
|
|
1700
|
+
output_rows = await conn.fetch(f"SELECT * FROM {self._t('outputs')} WHERE state_id = $1 AND ($2::boolean OR key = ANY($3::text[]))", self.state_id, scoped, output_keys) if scoped or output_keys else []
|
|
1701
|
+
resources = {row["address"]: _version_of(row) for row in resource_rows}
|
|
1702
|
+
output_versions = {row["key"]: self._output_version(row) for row in output_rows}
|
|
1703
|
+
changed = set()
|
|
1704
|
+
stale = []
|
|
1705
|
+
for kind, key, row in candidates:
|
|
1706
|
+
version = _version_of(row) if kind == RESOURCE else self._output_version(row)
|
|
1707
|
+
if not changed_inputs(version.inputs, resources, output_versions, owner=(kind, key)):
|
|
1708
|
+
continue
|
|
1709
|
+
stale.append((kind, key, row))
|
|
1710
|
+
bulk = await publish_stale_batch(self, conn, ownership, stale, result.sequence)
|
|
1711
|
+
if bulk is not None:
|
|
1712
|
+
result.versions.update(bulk)
|
|
1713
|
+
changed.update(bulk)
|
|
1714
|
+
excluded.update(bulk)
|
|
1715
|
+
continue
|
|
1716
|
+
for kind, key, row in stale:
|
|
1717
|
+
version = _version_of(row) if kind == RESOURCE else self._output_version(row)
|
|
1718
|
+
value = _entry_of(row["entry"], row["private"], row["status"]) if kind == RESOURCE else _load(row["value"])
|
|
1719
|
+
write = RowWrite(kind, key, value, expected=version, status=STALE_INPUTS, sensitive_paths=_load(row["sensitive_paths"]) or [] if kind == RESOURCE else [])
|
|
1720
|
+
if kind == RESOURCE:
|
|
1721
|
+
# Only status changes here; retain ownership even while the
|
|
1722
|
+
# operation that just returned is awaiting its final stage.
|
|
1723
|
+
result.versions[kind, key] = await self._write_entry(conn, ownership, write, result.sequence, validate_objects=False)
|
|
1724
|
+
else:
|
|
1725
|
+
result.versions[kind, key] = await self._write_output(conn, ownership, write, result.sequence)
|
|
1726
|
+
excluded.add((kind, key))
|
|
1727
|
+
changed.add((kind, key))
|
|
1728
|
+
|
|
1729
|
+
@staticmethod
|
|
1730
|
+
def _output_version(row: Mapping[str, Any] | asyncpg.Record) -> RowVersion:
|
|
1731
|
+
return RowVersion(
|
|
1732
|
+
int(row["revision"]),
|
|
1733
|
+
0,
|
|
1734
|
+
status=str(row["status"]),
|
|
1735
|
+
tombstone=bool(row["tombstone"]),
|
|
1736
|
+
intent_fp=row["intent_fp"],
|
|
1737
|
+
inputs=decode_inputs(_load(row["inputs"])),
|
|
1738
|
+
applied_fp=row["applied_fp"],
|
|
1739
|
+
value_fp=value_fingerprint(_load(row["value"])),
|
|
1740
|
+
run_id=row.get("run_id"),
|
|
1741
|
+
value_revision=int(row.get("value_revision") or 0),
|
|
1742
|
+
membership_revision=int(row.get("membership_revision") or 0),
|
|
1743
|
+
planning_context=read_planning_context(_load(row.get("planning_context"))),
|
|
1744
|
+
)
|
|
1745
|
+
|
|
1746
|
+
async def _write_output(self, conn: asyncpg.Connection, ownership: Ownership, write: RowWrite, sequence: int) -> RowVersion:
|
|
1747
|
+
if write.planning_context is not None and not self._planning_contexts:
|
|
1748
|
+
raise StateError("Retained planning context requires schema 31; reopen with the updated backend")
|
|
1749
|
+
old = await conn.fetchrow(f"SELECT * FROM {self._t('outputs')} WHERE state_id = $1 AND key = $2 FOR UPDATE", self.state_id, write.key)
|
|
1750
|
+
actual = self._output_version(old) if old is not None else None
|
|
1751
|
+
if write.expected is not UNCHECKED and not _same(actual, write.expected, statuses=False):
|
|
1752
|
+
raise StateConflictError(f"Output {write.key} changed since this run read it (expected {_describe(write.expected)}, found {_describe(actual)}); not written")
|
|
1753
|
+
revision = (actual.revision if actual else 0) + 1
|
|
1754
|
+
value = write.entry
|
|
1755
|
+
sensitive = bool(value.get("sensitive")) if isinstance(value, dict) else False
|
|
1756
|
+
intent_fp = (actual.intent_fp if actual else None) if write.intent_fp is UNCHECKED else write.intent_fp
|
|
1757
|
+
inputs = (actual.inputs if actual else None) if write.inputs is UNCHECKED else write.inputs
|
|
1758
|
+
applied_fp = (actual.applied_fp if actual else None) if write.applied_fp is UNCHECKED else write.applied_fp
|
|
1759
|
+
status = effective_status(write.status, actual, evaluated=write.inputs is not UNCHECKED and write.inputs is not None)
|
|
1760
|
+
planning_context = bind_planning_context(write.planning_context, revision, intent_fp, removal=write.removal)
|
|
1761
|
+
semantic = await conn.fetchrow(
|
|
1762
|
+
f"""
|
|
1763
|
+
INSERT INTO {self._t("outputs")} (state_id, key, revision, tombstone, value, sensitive, run_id, sequence, intent_fp, inputs, applied_fp, status{", planning_context" if self._planning_contexts else ""}) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12{", $13" if self._planning_contexts else ""})
|
|
1764
|
+
ON CONFLICT (state_id, key) DO UPDATE SET revision = EXCLUDED.revision, tombstone = EXCLUDED.tombstone, value = EXCLUDED.value,
|
|
1765
|
+
sensitive = EXCLUDED.sensitive, run_id = EXCLUDED.run_id, sequence = EXCLUDED.sequence, intent_fp = EXCLUDED.intent_fp,
|
|
1766
|
+
inputs = EXCLUDED.inputs, applied_fp = EXCLUDED.applied_fp, status = EXCLUDED.status{", planning_context = EXCLUDED.planning_context" if self._planning_contexts else ""}, updated_at = clock_timestamp()
|
|
1767
|
+
RETURNING value_revision, membership_revision
|
|
1768
|
+
""",
|
|
1769
|
+
self.state_id,
|
|
1770
|
+
write.key,
|
|
1771
|
+
revision,
|
|
1772
|
+
write.removal,
|
|
1773
|
+
_json(value) if value is not None else None,
|
|
1774
|
+
sensitive,
|
|
1775
|
+
ownership.run_id,
|
|
1776
|
+
sequence,
|
|
1777
|
+
intent_fp,
|
|
1778
|
+
_json(encode_inputs(inputs)) if inputs is not None else None,
|
|
1779
|
+
applied_fp,
|
|
1780
|
+
status,
|
|
1781
|
+
*([_json(planning_context.to_dict()) if planning_context is not None else None] if self._planning_contexts else []),
|
|
1782
|
+
)
|
|
1783
|
+
version = RowVersion(revision, 0, status=status, tombstone=write.removal, intent_fp=intent_fp, inputs=inputs, applied_fp=applied_fp, value_fp=value_fingerprint(value), planning_context=planning_context)
|
|
1784
|
+
version = replace(version, value_revision=int(semantic["value_revision"]), membership_revision=int(semantic["membership_revision"]))
|
|
1785
|
+
await self._version(conn, ownership, OUTPUT, write.key, revision, sequence, write, value, [], version)
|
|
1786
|
+
return replace(version, run_id=ownership.run_id)
|
|
1787
|
+
|
|
1788
|
+
async def _write_entry(
|
|
1789
|
+
self,
|
|
1790
|
+
conn: asyncpg.Connection,
|
|
1791
|
+
ownership: Ownership,
|
|
1792
|
+
write: RowWrite,
|
|
1793
|
+
sequence: int,
|
|
1794
|
+
*,
|
|
1795
|
+
validate_objects: bool = True,
|
|
1796
|
+
original: RowVersion | None = None,
|
|
1797
|
+
operation_snapshot: Sequence[OperationRecord] | None = None,
|
|
1798
|
+
object_entries: ObjectEntryGuard | None = None,
|
|
1799
|
+
) -> RowVersion:
|
|
1800
|
+
if write.planning_context is not None and not self._planning_contexts:
|
|
1801
|
+
raise StateError("Retained planning context requires schema 31; reopen with the updated backend")
|
|
1802
|
+
old = await conn.fetchrow(f"SELECT * FROM {self._t('entries')} WHERE state_id = $1 AND address = $2 FOR UPDATE", self.state_id, write.key)
|
|
1803
|
+
actual = original if original is not None else _version_of(old) if old is not None else None
|
|
1804
|
+
if write.expected is not UNCHECKED and not _same(actual, write.expected, statuses=False):
|
|
1805
|
+
raise StateConflictError(f"{write.key} changed since this run read it (expected {_describe(write.expected)}, found {_describe(actual)}); not written")
|
|
1806
|
+
if not write.removal and validate_objects:
|
|
1807
|
+
previous = _entry_of(old["entry"], old["private"], old["status"]) if old is not None and not old["tombstone"] else None
|
|
1808
|
+
normalizing = legacy_normalization(write, previous)
|
|
1809
|
+
action = "import" if write.op_id is None and previous is None else "state"
|
|
1810
|
+
await self._validate_objects(
|
|
1811
|
+
conn, write.key, {"template": write.entry.to_dict()}, action, exclude_op=write.op_id, allow_legacy_normalization=normalizing, run_id=ownership.run_id, operation_snapshot=operation_snapshot, object_entries=object_entries
|
|
1812
|
+
)
|
|
1813
|
+
revision = (actual.revision if actual else 0) + 1
|
|
1814
|
+
mutation_revision = revision if write.op_id is not None else actual.mutation_revision if actual else 0
|
|
1815
|
+
incarnation = actual.incarnation if actual else 0
|
|
1816
|
+
intent_fp = (actual.intent_fp if actual else None) if write.intent_fp is UNCHECKED else write.intent_fp
|
|
1817
|
+
inputs = (actual.inputs if actual else None) if write.inputs is UNCHECKED else write.inputs
|
|
1818
|
+
applied_fp = (actual.applied_fp if actual else None) if write.applied_fp is UNCHECKED else write.applied_fp
|
|
1819
|
+
planning_context = bind_planning_context(write.planning_context, revision, intent_fp, removal=write.removal)
|
|
1820
|
+
if write.removal:
|
|
1821
|
+
version = (
|
|
1822
|
+
replace(actual, revision=revision, tombstone=True, status="ready", object_identity=None, private_digest="", intent_fp=intent_fp, value_fp=value_fingerprint([None, actual.provider, ""]))
|
|
1823
|
+
if actual
|
|
1824
|
+
else RowVersion(revision, incarnation, tombstone=True, intent_fp=intent_fp, value_fp=value_fingerprint([None, "", ""]))
|
|
1825
|
+
)
|
|
1826
|
+
version = replace(version, mutation_revision=mutation_revision, planning_context=None)
|
|
1827
|
+
if actual is not None:
|
|
1828
|
+
semantic = await conn.fetchrow(
|
|
1829
|
+
f"""
|
|
1830
|
+
UPDATE {self._t("entries")} SET revision = $3, tombstone = true, status = 'ready', object_identity = NULL, entry = NULL, private = NULL,
|
|
1831
|
+
private_digest = '', run_id = $4, sequence = $5, intent_fp = $6, mutation_revision = $7{", planning_context = NULL" if self._planning_contexts else ""}, updated_at = clock_timestamp()
|
|
1832
|
+
WHERE state_id = $1 AND address = $2
|
|
1833
|
+
RETURNING value_revision, membership_revision
|
|
1834
|
+
""",
|
|
1835
|
+
self.state_id,
|
|
1836
|
+
write.key,
|
|
1837
|
+
revision,
|
|
1838
|
+
ownership.run_id,
|
|
1839
|
+
sequence,
|
|
1840
|
+
intent_fp,
|
|
1841
|
+
mutation_revision,
|
|
1842
|
+
)
|
|
1843
|
+
else:
|
|
1844
|
+
semantic = await conn.fetchrow(
|
|
1845
|
+
f"""
|
|
1846
|
+
INSERT INTO {self._t("entries")} (state_id, address, revision, incarnation, status, tombstone, run_id, sequence, intent_fp, mutation_revision)
|
|
1847
|
+
VALUES ($1, $2, $3, $4, 'ready', true, $5, $6, $7, $8)
|
|
1848
|
+
RETURNING value_revision, membership_revision
|
|
1849
|
+
""",
|
|
1850
|
+
self.state_id,
|
|
1851
|
+
write.key,
|
|
1852
|
+
revision,
|
|
1853
|
+
incarnation,
|
|
1854
|
+
ownership.run_id,
|
|
1855
|
+
sequence,
|
|
1856
|
+
intent_fp,
|
|
1857
|
+
mutation_revision,
|
|
1858
|
+
)
|
|
1859
|
+
version = replace(version, value_revision=int(semantic["value_revision"]), membership_revision=int(semantic["membership_revision"]))
|
|
1860
|
+
await self._version(conn, ownership, RESOURCE, write.key, revision, sequence, write, None, [], version)
|
|
1861
|
+
return replace(version, run_id=ownership.run_id)
|
|
1862
|
+
entry: ResourceState = write.entry
|
|
1863
|
+
if write.new_incarnation or actual is None:
|
|
1864
|
+
incarnation += 1
|
|
1865
|
+
status = effective_status(write.status, actual, tainted=entry.tainted, evaluated=write.inputs is not UNCHECKED and write.inputs is not None)
|
|
1866
|
+
version = RowVersion(
|
|
1867
|
+
revision,
|
|
1868
|
+
incarnation,
|
|
1869
|
+
status,
|
|
1870
|
+
entry.provider,
|
|
1871
|
+
private_digest(entry.private),
|
|
1872
|
+
object_identity(entry),
|
|
1873
|
+
intent_fp=intent_fp,
|
|
1874
|
+
inputs=inputs,
|
|
1875
|
+
applied_fp=applied_fp,
|
|
1876
|
+
value_fp=value_fingerprint([entry.attributes, entry.provider, private_digest(entry.private)]),
|
|
1877
|
+
mutation_revision=mutation_revision,
|
|
1878
|
+
planning_context=planning_context,
|
|
1879
|
+
)
|
|
1880
|
+
# Keep the old external JSONB datum when its complete representation is
|
|
1881
|
+
# unchanged. Check value changes first, avoiding text conversion on the
|
|
1882
|
+
# usual update path. JSONB equality also equates 1 and 1.0, so equal values
|
|
1883
|
+
# still need C-collated text comparison to preserve representation changes.
|
|
1884
|
+
semantic = await conn.fetchrow(
|
|
1885
|
+
f"""
|
|
1886
|
+
INSERT INTO {self._t("entries")} AS stored (state_id, address, revision, incarnation, status, tombstone, stack_id, type, name, provider, entry, private,
|
|
1887
|
+
private_digest, object_identity, sensitive_paths, run_id, sequence, intent_fp, inputs, applied_fp, mutation_revision{", planning_context" if self._planning_contexts else ""})
|
|
1888
|
+
VALUES ($1, $2, $3, $4, $5, false, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20{", $21" if self._planning_contexts else ""})
|
|
1889
|
+
ON CONFLICT (state_id, address) DO UPDATE SET revision = EXCLUDED.revision, incarnation = EXCLUDED.incarnation, status = EXCLUDED.status,
|
|
1890
|
+
tombstone = false, stack_id = EXCLUDED.stack_id, type = EXCLUDED.type, name = EXCLUDED.name, provider = EXCLUDED.provider,
|
|
1891
|
+
entry = CASE WHEN stored.entry IS DISTINCT FROM EXCLUDED.entry THEN EXCLUDED.entry
|
|
1892
|
+
WHEN stored.entry::text COLLATE "C" IS NOT DISTINCT FROM EXCLUDED.entry::text COLLATE "C" THEN stored.entry ELSE EXCLUDED.entry END,
|
|
1893
|
+
private = EXCLUDED.private, private_digest = EXCLUDED.private_digest, object_identity = EXCLUDED.object_identity,
|
|
1894
|
+
sensitive_paths = EXCLUDED.sensitive_paths, run_id = EXCLUDED.run_id, sequence = EXCLUDED.sequence, intent_fp = EXCLUDED.intent_fp,
|
|
1895
|
+
inputs = EXCLUDED.inputs, applied_fp = EXCLUDED.applied_fp, mutation_revision = EXCLUDED.mutation_revision{", planning_context = EXCLUDED.planning_context" if self._planning_contexts else ""}, updated_at = clock_timestamp()
|
|
1896
|
+
RETURNING value_revision, membership_revision
|
|
1897
|
+
""",
|
|
1898
|
+
self.state_id,
|
|
1899
|
+
write.key,
|
|
1900
|
+
revision,
|
|
1901
|
+
incarnation,
|
|
1902
|
+
version.status,
|
|
1903
|
+
entry.stack_id,
|
|
1904
|
+
entry.type,
|
|
1905
|
+
entry.id,
|
|
1906
|
+
entry.provider,
|
|
1907
|
+
_json(_entry_document(entry)),
|
|
1908
|
+
entry.private or None,
|
|
1909
|
+
version.private_digest,
|
|
1910
|
+
version.object_identity,
|
|
1911
|
+
_json(write.sensitive_paths),
|
|
1912
|
+
ownership.run_id,
|
|
1913
|
+
sequence,
|
|
1914
|
+
intent_fp,
|
|
1915
|
+
_json(encode_inputs(inputs)) if inputs is not None else None,
|
|
1916
|
+
applied_fp,
|
|
1917
|
+
mutation_revision,
|
|
1918
|
+
*([_json(planning_context.to_dict()) if planning_context is not None else None] if self._planning_contexts else []),
|
|
1919
|
+
)
|
|
1920
|
+
version = replace(version, value_revision=int(semantic["value_revision"]), membership_revision=int(semantic["membership_revision"]))
|
|
1921
|
+
await self._version(conn, ownership, RESOURCE, write.key, revision, sequence, write, entry.to_dict(), write.sensitive_paths, version)
|
|
1922
|
+
return replace(version, run_id=ownership.run_id)
|
|
1923
|
+
|
|
1924
|
+
async def _version(self, conn: asyncpg.Connection, ownership: Ownership, kind: str, key: str, revision: int, sequence: int, write: RowWrite, row: Any, sensitive_paths: list[list[str]], version: RowVersion) -> None:
|
|
1925
|
+
await conn.execute(
|
|
1926
|
+
f"""
|
|
1927
|
+
INSERT INTO {self._t("versions")} (state_id, kind, key, revision, sequence, run_id, op_id, tombstone, row_data, sensitive_paths, intent_fp, inputs, applied_fp, status, mutation_revision, value_revision, membership_revision{", planning_context" if self._planning_contexts else ""})
|
|
1928
|
+
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17{", $18" if self._planning_contexts else ""})
|
|
1929
|
+
""",
|
|
1930
|
+
self.state_id,
|
|
1931
|
+
kind,
|
|
1932
|
+
key,
|
|
1933
|
+
revision,
|
|
1934
|
+
sequence,
|
|
1935
|
+
ownership.run_id,
|
|
1936
|
+
write.op_id,
|
|
1937
|
+
write.removal,
|
|
1938
|
+
_json(row) if row is not None else None,
|
|
1939
|
+
_json(sensitive_paths),
|
|
1940
|
+
version.intent_fp,
|
|
1941
|
+
_json(encode_inputs(version.inputs)) if version.inputs is not None else None,
|
|
1942
|
+
version.applied_fp,
|
|
1943
|
+
version.status,
|
|
1944
|
+
version.mutation_revision,
|
|
1945
|
+
version.value_revision,
|
|
1946
|
+
version.membership_revision,
|
|
1947
|
+
*([_json(version.planning_context.to_dict()) if version.planning_context is not None else None] if self._planning_contexts else []),
|
|
1948
|
+
)
|
|
1949
|
+
|
|
1950
|
+
def abort(self, ownership: Ownership, op_id: str, reason: str) -> None:
|
|
1951
|
+
self._run(self._abort, ownership, op_id, reason)
|
|
1952
|
+
|
|
1953
|
+
async def _abort(self, ownership: Ownership, op_id: str, reason: str) -> None:
|
|
1954
|
+
from netherframe.core.backends.graph_moves import move_original_status
|
|
1955
|
+
|
|
1956
|
+
async with self._owned_tx(ownership, "abort", recovery=ownership.claim is not None) as transaction:
|
|
1957
|
+
conn = transaction.conn
|
|
1958
|
+
await self._locked_operation(conn, ownership, op_id)
|
|
1959
|
+
[record] = await self._operations(conn, unresolved=True, op_id=op_id)
|
|
1960
|
+
original_status = move_original_status(record)
|
|
1961
|
+
validate_operation_resolution(record.stage, "aborted", action=record.action)
|
|
1962
|
+
if not has_input_provenance(record.request) and original_status in {None, "ready"}:
|
|
1963
|
+
original_status = "unconverged"
|
|
1964
|
+
address = await conn.fetchval(
|
|
1965
|
+
f"UPDATE {self._t('operations')} SET stage = 'aborted', outcome = $2, resolved_at = clock_timestamp() WHERE op_id = $1 RETURNING address",
|
|
1966
|
+
op_id,
|
|
1967
|
+
reason,
|
|
1968
|
+
)
|
|
1969
|
+
await self._settle(conn, address, original_status=original_status)
|
|
1970
|
+
|
|
1971
|
+
async def _settle(self, conn: asyncpg.Connection, address: str, *, original_status: str | None = None) -> None:
|
|
1972
|
+
"""Clear an address's uncertain status once no unresolved operation holds it."""
|
|
1973
|
+
await conn.execute(
|
|
1974
|
+
f"""
|
|
1975
|
+
UPDATE {self._t("entries")} e SET status = CASE WHEN (e.entry ->> 'status') = 'tainted' THEN 'tainted' ELSE coalesce($3, 'ready') END
|
|
1976
|
+
WHERE e.state_id = $1 AND e.address = $2 AND e.status = 'uncertain'
|
|
1977
|
+
AND NOT EXISTS (SELECT 1 FROM {self._t("operations")} o WHERE o.state_id = e.state_id AND o.{_UNRESOLVED} AND (o.address = e.address OR o.footprint ? e.address))
|
|
1978
|
+
""",
|
|
1979
|
+
self.state_id,
|
|
1980
|
+
address,
|
|
1981
|
+
original_status,
|
|
1982
|
+
)
|
|
1983
|
+
|
|
1984
|
+
def mark_uncertain(self, ownership: Ownership, op_id: str, reason: str) -> None:
|
|
1985
|
+
self._run(self._mark_uncertain, ownership, op_id, reason)
|
|
1986
|
+
|
|
1987
|
+
async def _mark_uncertain(self, ownership: Ownership, op_id: str, reason: str) -> None:
|
|
1988
|
+
async with self._owned_tx(ownership, "mark uncertain", recovery=ownership.claim is not None) as transaction:
|
|
1989
|
+
conn = transaction.conn
|
|
1990
|
+
await self._locked_operation(conn, ownership, op_id)
|
|
1991
|
+
address = await conn.fetchval(f"UPDATE {self._t('operations')} SET outcome = $2 WHERE op_id = $1 RETURNING address", op_id, f"outcome unknown: {reason}")
|
|
1992
|
+
await conn.execute(f"UPDATE {self._t('entries')} SET status = 'uncertain' WHERE state_id = $1 AND address = $2 AND NOT tombstone", self.state_id, address)
|
|
1993
|
+
|
|
1994
|
+
def operations(self, *, unresolved: bool = True, op_id: str | None = None) -> list[OperationRecord]:
|
|
1995
|
+
return self._run(self._operations_tx, unresolved, op_id)
|
|
1996
|
+
|
|
1997
|
+
async def _operations_tx(self, unresolved: bool, op_id: str | None) -> list[OperationRecord]:
|
|
1998
|
+
async with self._tx(readonly=True) as conn:
|
|
1999
|
+
return await self._operations(conn, unresolved=unresolved, op_id=op_id)
|
|
2000
|
+
|
|
2001
|
+
async def _operations(self, conn: asyncpg.Connection, *, unresolved: bool, op_id: str | None, after_reservation: int | None = None) -> list[OperationRecord]:
|
|
2002
|
+
rows = await conn.fetch(
|
|
2003
|
+
self._operations_sql(f"($2::boolean IS FALSE OR o.{_UNRESOLVED}) AND ($3::text IS NULL OR o.op_id = $3) AND ($4::bigint IS NULL OR o.reservation > $4)"),
|
|
2004
|
+
self.state_id,
|
|
2005
|
+
unresolved,
|
|
2006
|
+
op_id,
|
|
2007
|
+
after_reservation,
|
|
2008
|
+
)
|
|
2009
|
+
return self._operation_records(rows)
|
|
2010
|
+
|
|
2011
|
+
def _decode_guard_claims(self, raw: Any, operation: OperationRecord) -> ObjectRequest:
|
|
2012
|
+
"""Memoize only a pure calculation from exact PostgreSQL JSON text.
|
|
2013
|
+
|
|
2014
|
+
Every transaction rereads stages, owners, footprints and requests. A
|
|
2015
|
+
different action or byte of request text gets a fresh decode. The cache
|
|
2016
|
+
holds no live authority; legacy/malformed evidence keeps the same lazy
|
|
2017
|
+
checks as the ordinary guard. Caller-owned lease maps never escape into
|
|
2018
|
+
the cache. Bound both retained text bytes and item count per backend.
|
|
2019
|
+
"""
|
|
2020
|
+
if type(raw) is not str or len(raw) > 16384:
|
|
2021
|
+
return object_request(operation.request, operation.action)
|
|
2022
|
+
key = operation.action, raw
|
|
2023
|
+
if (cached := self._object_claims.get(key)) is not None:
|
|
2024
|
+
self._object_claims.move_to_end(key)
|
|
2025
|
+
claims = cached[1]
|
|
2026
|
+
else:
|
|
2027
|
+
claims = object_request(operation.request, operation.action)
|
|
2028
|
+
strings = (operation.action, raw, *claims.identities, *claims.leases, *claims.allocation_scopes, *(part for source in claims.sources | claims.bound_sources for part in source))
|
|
2029
|
+
size = sum(len(value.encode("utf-8", errors="surrogatepass")) for value in strings) if all(type(value) is str for value in strings) else 65537
|
|
2030
|
+
if size <= 65536:
|
|
2031
|
+
while self._object_claims and (len(self._object_claims) >= 512 or self._object_claim_bytes + size > 4 * 1024 * 1024):
|
|
2032
|
+
self._object_claim_bytes -= self._object_claims.popitem(last=False)[1][0]
|
|
2033
|
+
self._object_claims[key] = size, claims
|
|
2034
|
+
self._object_claim_bytes += size
|
|
2035
|
+
return replace(claims, leases=dict(claims.leases))
|
|
2036
|
+
|
|
2037
|
+
async def _operation_guards(self, conn: asyncpg.Connection) -> ObjectOperationGuard:
|
|
2038
|
+
"""Unresolved exclusion evidence, never a recovery or status record.
|
|
2039
|
+
|
|
2040
|
+
Permission checks need the complete request, including legacy evidence,
|
|
2041
|
+
recovery origins and move footprints. They do not inspect responses,
|
|
2042
|
+
expected row versions, process metadata or the owner's liveness. Keep
|
|
2043
|
+
those potentially large fields and the run/lease joins out of this read.
|
|
2044
|
+
Callers reuse it only within their app-row-locked transaction.
|
|
2045
|
+
"""
|
|
2046
|
+
rows = await conn.fetch(
|
|
2047
|
+
f"""SELECT op_id, run_id, epoch, address, action, stage, request, footprint, recovered_by
|
|
2048
|
+
FROM {self._t("operations")} WHERE state_id = $1 AND {_UNRESOLVED} ORDER BY created_at""",
|
|
2049
|
+
self.state_id,
|
|
2050
|
+
)
|
|
2051
|
+
operations = [
|
|
2052
|
+
OperationRecord(
|
|
2053
|
+
op_id=row["op_id"],
|
|
2054
|
+
run_id=row["run_id"],
|
|
2055
|
+
epoch=int(row["epoch"]),
|
|
2056
|
+
address=row["address"],
|
|
2057
|
+
action=row["action"],
|
|
2058
|
+
stage=row["stage"],
|
|
2059
|
+
request=_load(row["request"]) or {},
|
|
2060
|
+
footprint=list(_load(row["footprint"]) or []),
|
|
2061
|
+
recovered_by=row["recovered_by"],
|
|
2062
|
+
)
|
|
2063
|
+
for row in rows
|
|
2064
|
+
]
|
|
2065
|
+
raw_requests = {id(operation): row["request"] for operation, row in zip(operations, rows, strict=True)}
|
|
2066
|
+
return ObjectOperationGuard(operations, decode=lambda operation: self._decode_guard_claims(raw_requests.get(id(operation)), operation))
|
|
2067
|
+
|
|
2068
|
+
def _operations_sql(self, predicate: str) -> str:
|
|
2069
|
+
return f"""
|
|
2070
|
+
SELECT o.*, extract(epoch FROM clock_timestamp() - o.dispatched_at) AS dispatched_for,
|
|
2071
|
+
extract(epoch FROM o.created_at) AS created, extract(epoch FROM o.dispatched_at) AS dispatched,
|
|
2072
|
+
extract(epoch FROM o.returned_at) AS returned, extract(epoch FROM o.resolved_at) AS resolved,
|
|
2073
|
+
r.status AS owner_status, r.providers_killed_at IS NOT NULL AS providers_killed,
|
|
2074
|
+
(r.status = 'active' AND r.expires_at > clock_timestamp()
|
|
2075
|
+
AND EXISTS (SELECT 1 FROM {self._t("leases")} l WHERE l.state_id = r.state_id AND l.key = 'app' AND l.holder = r.run_id)) AS owner_live
|
|
2076
|
+
FROM {self._t("operations")} o LEFT JOIN {self._t("runs")} r ON r.run_id = o.run_id
|
|
2077
|
+
WHERE o.state_id = $1 AND {predicate}
|
|
2078
|
+
ORDER BY o.created_at
|
|
2079
|
+
"""
|
|
2080
|
+
|
|
2081
|
+
@staticmethod
|
|
2082
|
+
def _operation_records(rows) -> list[OperationRecord]:
|
|
2083
|
+
records = []
|
|
2084
|
+
for row in rows:
|
|
2085
|
+
expected = _load(row["expected"])
|
|
2086
|
+
records.append(
|
|
2087
|
+
OperationRecord(
|
|
2088
|
+
op_id=row["op_id"],
|
|
2089
|
+
run_id=row["run_id"],
|
|
2090
|
+
epoch=int(row["epoch"]),
|
|
2091
|
+
address=row["address"],
|
|
2092
|
+
action=row["action"],
|
|
2093
|
+
stage=row["stage"],
|
|
2094
|
+
attempt=int(row["attempt"]),
|
|
2095
|
+
expected=RowVersion.from_dict(expected) if expected else None,
|
|
2096
|
+
expected_provider=row["expected_provider"] or "",
|
|
2097
|
+
object_identity=row["object_identity"],
|
|
2098
|
+
request=_load(row["request"]) or {},
|
|
2099
|
+
request_digest=row["request_digest"],
|
|
2100
|
+
reservation=int(row["reservation"]),
|
|
2101
|
+
result=_load(row["result"]),
|
|
2102
|
+
error=row["error"],
|
|
2103
|
+
footprint=list(_load(row["footprint"]) or []),
|
|
2104
|
+
owner_host=row["owner_host"] or "",
|
|
2105
|
+
owner_pid=row["owner_pid"],
|
|
2106
|
+
provider_pid=row["provider_pid"],
|
|
2107
|
+
recovered_by=row["recovered_by"],
|
|
2108
|
+
outcome=row["outcome"],
|
|
2109
|
+
created_at=float(row["created"]) if row["created"] is not None else None,
|
|
2110
|
+
dispatched_at=float(row["dispatched"]) if row["dispatched"] is not None else None,
|
|
2111
|
+
returned_at=float(row["returned"]) if row["returned"] is not None else None,
|
|
2112
|
+
resolved_at=float(row["resolved"]) if row["resolved"] is not None else None,
|
|
2113
|
+
dispatched_for=float(row["dispatched_for"]) if row["dispatched_for"] is not None else None,
|
|
2114
|
+
owner_status=row["owner_status"],
|
|
2115
|
+
owner_live=bool(row["owner_live"]),
|
|
2116
|
+
owner_providers_killed=bool(row["providers_killed"]),
|
|
2117
|
+
),
|
|
2118
|
+
)
|
|
2119
|
+
return records
|
|
2120
|
+
|
|
2121
|
+
def take_over(self, ownership: Ownership, op_id: str) -> OperationRecord:
|
|
2122
|
+
return self._run(self._take_over, ownership, op_id)
|
|
2123
|
+
|
|
2124
|
+
async def _take_over(self, ownership: Ownership, op_id: str) -> OperationRecord:
|
|
2125
|
+
if ownership.claim is not None:
|
|
2126
|
+
raise PreCallValidationError("An existing recovery claim cannot take ownership of another operation")
|
|
2127
|
+
async with self._owned_tx(ownership, "take over", recovery=True) as transaction:
|
|
2128
|
+
conn = transaction.conn
|
|
2129
|
+
record = await conn.fetchrow(f"SELECT run_id, recovered_by, stage FROM {self._t('operations')} WHERE op_id = $1 AND state_id = $2 FOR UPDATE", op_id, self.state_id)
|
|
2130
|
+
if record is None:
|
|
2131
|
+
raise StateError(f"No operation {op_id}")
|
|
2132
|
+
if record["stage"] not in FINAL_STAGES:
|
|
2133
|
+
holders = {record["run_id"]}
|
|
2134
|
+
if record["recovered_by"] is not None and record["recovered_by"] != ownership.run_id:
|
|
2135
|
+
holders.add(record["recovered_by"])
|
|
2136
|
+
for holder in sorted(holders):
|
|
2137
|
+
owner = await conn.fetchrow(f"SELECT status, expires_at > clock_timestamp() AS live FROM {self._t('runs')} WHERE run_id = $1 FOR SHARE", holder)
|
|
2138
|
+
if owner is not None and owner["status"] == ACTIVE and owner["live"]:
|
|
2139
|
+
raise StateLockError(f"Operation {op_id} belongs to run {holder}, whose ownership is live")
|
|
2140
|
+
# The operation's epoch advances independently of registration order.
|
|
2141
|
+
await conn.execute(
|
|
2142
|
+
f"UPDATE {self._t('operations')} SET epoch = epoch + 1, attempt = attempt + 1, recovered_by = $2 WHERE op_id = $1",
|
|
2143
|
+
op_id,
|
|
2144
|
+
ownership.run_id,
|
|
2145
|
+
)
|
|
2146
|
+
records = await self._operations(conn, unresolved=False, op_id=op_id)
|
|
2147
|
+
return records[0]
|
|
2148
|
+
|
|
2149
|
+
# -- history -----------------------------------------------------------------------
|
|
2150
|
+
|
|
2151
|
+
def create_history_checkpoint(self, ownership: Ownership, targets: Sequence[tuple[str, str]], *, name: str, keep: int = 5):
|
|
2152
|
+
return self._run(PostgreSQLHistoryCheckpoints(self).create, ownership, targets, name, keep)
|
|
2153
|
+
|
|
2154
|
+
def history_checkpoints(self):
|
|
2155
|
+
return self._run(PostgreSQLHistoryCheckpoints(self).list_checkpoints)
|
|
2156
|
+
|
|
2157
|
+
def prepare_history_restore(self, reference: str):
|
|
2158
|
+
return self._run(PostgreSQLHistoryCheckpoints(self).prepare, reference)
|
|
2159
|
+
|
|
2160
|
+
def restore_history_checkpoint(self, ownership: Ownership, reference: str, *, force: bool = False) -> int:
|
|
2161
|
+
try:
|
|
2162
|
+
return self._run(PostgreSQLHistoryCheckpoints(self).restore, ownership, reference, force)
|
|
2163
|
+
except asyncpg.UniqueViolationError as exc:
|
|
2164
|
+
raise StateConflictError("Checkpoint restore cannot claim an object managed by another address") from exc
|
|
2165
|
+
|
|
2166
|
+
def history_restore_receipt(self, run_id: str, reference: str, *, force: bool = False) -> int | None:
|
|
2167
|
+
return self._run(PostgreSQLHistoryCheckpoints(self).receipt, run_id, reference, force)
|
|
2168
|
+
|
|
2169
|
+
def pin_baseline(self, *, sequence: int | None = None, run_id: str | None = None) -> GraphBaseline:
|
|
2170
|
+
return self._run(self._pin_baseline, sequence, run_id)
|
|
2171
|
+
|
|
2172
|
+
def known_intent_run(self, key: str, intent_fp: str | None, *, kind: str = RESOURCE, sequence: int | None = None) -> str | None:
|
|
2173
|
+
return self._run(self._known_intent_run, key, intent_fp, kind, sequence)
|
|
2174
|
+
|
|
2175
|
+
def known_intent_runs(self, intents: Mapping[tuple[str, str], str | None], *, sequence: int | None = None) -> dict[tuple[str, str], str]:
|
|
2176
|
+
if not intents:
|
|
2177
|
+
return {}
|
|
2178
|
+
requested = [{"kind": kind, "key": key, "intent_fp": intent} for (kind, key), intent in intents.items()]
|
|
2179
|
+
return self._run(self._known_intent_runs, requested, sequence)
|
|
2180
|
+
|
|
2181
|
+
async def _known_intent_runs(self, requested: list[dict[str, Any]], sequence: int | None) -> dict[tuple[str, str], str]:
|
|
2182
|
+
async with self._tx(readonly=True) as conn:
|
|
2183
|
+
rows = await conn.fetch(
|
|
2184
|
+
f"""SELECT wanted.kind, wanted.key, retained.run_id
|
|
2185
|
+
FROM jsonb_to_recordset($2::jsonb) AS wanted(kind text, key text, intent_fp text)
|
|
2186
|
+
CROSS JOIN LATERAL (
|
|
2187
|
+
SELECT coalesce(v.run_id, 'unknown') AS run_id FROM {self._t("versions")} v
|
|
2188
|
+
WHERE v.state_id = $1 AND v.kind = wanted.kind AND v.key = wanted.key
|
|
2189
|
+
AND ((wanted.intent_fp IS NULL AND v.tombstone) OR (NOT v.tombstone AND v.intent_fp = wanted.intent_fp))
|
|
2190
|
+
AND ($3::bigint IS NULL OR v.sequence <= $3)
|
|
2191
|
+
ORDER BY v.sequence DESC, v.revision DESC LIMIT 1
|
|
2192
|
+
) retained""",
|
|
2193
|
+
self.state_id,
|
|
2194
|
+
_json(requested),
|
|
2195
|
+
sequence,
|
|
2196
|
+
)
|
|
2197
|
+
return {(row["kind"], row["key"]): row["run_id"] for row in rows}
|
|
2198
|
+
|
|
2199
|
+
async def _known_intent_run(self, key: str, intent_fp: str | None, kind: str, sequence: int | None) -> str | None:
|
|
2200
|
+
async with self._tx(readonly=True) as conn:
|
|
2201
|
+
return await conn.fetchval(
|
|
2202
|
+
f"SELECT coalesce(run_id, 'unknown') FROM {self._t('versions')} WHERE state_id = $1 AND kind = $2 AND key = $3 AND (($4::text IS NULL AND tombstone) OR (NOT tombstone AND intent_fp = $4)) AND ($5::bigint IS NULL OR sequence <= $5) ORDER BY sequence DESC, revision DESC LIMIT 1",
|
|
2203
|
+
self.state_id,
|
|
2204
|
+
kind,
|
|
2205
|
+
key,
|
|
2206
|
+
intent_fp,
|
|
2207
|
+
sequence,
|
|
2208
|
+
)
|
|
2209
|
+
|
|
2210
|
+
async def _intent_records(self, conn: asyncpg.Connection, sequence: int) -> list[IntentRecord]:
|
|
2211
|
+
rows = await conn.fetch(
|
|
2212
|
+
f"SELECT DISTINCT ON (kind, key) kind, key, revision, sequence, intent_fp, tombstone, run_id FROM {self._t('versions')} WHERE state_id = $1 AND sequence <= $2 ORDER BY kind, key, sequence DESC, revision DESC",
|
|
2213
|
+
self.state_id,
|
|
2214
|
+
sequence,
|
|
2215
|
+
)
|
|
2216
|
+
return [IntentRecord(row["kind"], row["key"], int(row["revision"]), int(row["sequence"]), row["intent_fp"], bool(row["tombstone"]), row["run_id"]) for row in rows]
|
|
2217
|
+
|
|
2218
|
+
async def _check_current_history(self, conn: asyncpg.Connection, sequence: int, records: list[IntentRecord] | None = None) -> None:
|
|
2219
|
+
records = await self._intent_records(conn, sequence) if records is None else records
|
|
2220
|
+
entries = await conn.fetch(f"SELECT address, revision FROM {self._t('entries')} WHERE state_id = $1", self.state_id)
|
|
2221
|
+
outputs = await conn.fetch(f"SELECT key, revision FROM {self._t('outputs')} WHERE state_id = $1", self.state_id)
|
|
2222
|
+
current = {(RESOURCE, row["address"], int(row["revision"])) for row in entries} | {(OUTPUT, row["key"], int(row["revision"])) for row in outputs}
|
|
2223
|
+
if current != {(record.kind, record.key, record.revision) for record in records}:
|
|
2224
|
+
raise StateError("The current state's intent history is incomplete; refusing to treat missing versions as absence")
|
|
2225
|
+
|
|
2226
|
+
async def _pin_baseline(self, sequence: int | None, run_id: str | None) -> GraphBaseline:
|
|
2227
|
+
if sequence is not None and run_id is not None:
|
|
2228
|
+
raise StateError("A baseline names a sequence or a run, not both")
|
|
2229
|
+
async with self._tx() as conn:
|
|
2230
|
+
app = await conn.fetchrow(f"SELECT lineage, frontier, pruned_before FROM {self._t('apps')} WHERE state_id = $1 FOR UPDATE", self.state_id)
|
|
2231
|
+
if run_id is not None:
|
|
2232
|
+
sequence = await conn.fetchval(f"SELECT max(sequence) FROM {self._t('commits')} WHERE state_id = $1 AND run_id = $2", self.state_id, run_id)
|
|
2233
|
+
if sequence is None:
|
|
2234
|
+
raise StateError(f"Run {run_id} has no committed state in this app")
|
|
2235
|
+
sequence = int(app["frontier"]) if sequence is None else sequence
|
|
2236
|
+
if type(sequence) is not int or not 0 <= sequence <= int(app["frontier"]):
|
|
2237
|
+
raise StateError(f"Baseline sequence must be between 0 and the frontier ({app['frontier']})")
|
|
2238
|
+
pinned_digest = await conn.fetchval(f"SELECT intent_digest FROM {self._t('baselines')} WHERE state_id = $1 AND sequence = $2 LIMIT 1", self.state_id, sequence)
|
|
2239
|
+
# A deleted version can also be the last version *before* a later
|
|
2240
|
+
# frontier. A deletion watermark alone cannot prove that frontier
|
|
2241
|
+
# complete. Retained boundary versions prove newer frontiers;
|
|
2242
|
+
# older ones require an existing pin protecting their origin.
|
|
2243
|
+
if 0 < sequence <= int(app["pruned_before"]) and pinned_digest is None:
|
|
2244
|
+
raise StateError(f"Baseline sequence {sequence} is older than retained history; it cannot be treated as an empty state")
|
|
2245
|
+
records = await self._intent_records(conn, sequence)
|
|
2246
|
+
if pinned_digest is not None and intent_snapshot_digest(records) != pinned_digest:
|
|
2247
|
+
raise StateError("The baseline's retained intent history is incomplete; refusing to treat lost history as absence")
|
|
2248
|
+
if sequence == int(app["frontier"]):
|
|
2249
|
+
await self._check_current_history(conn, sequence, records)
|
|
2250
|
+
require_known_intents(records)
|
|
2251
|
+
baseline = GraphBaseline(self.get_backend_type(), self.state_id, app["lineage"], sequence, uuid.uuid4().hex)
|
|
2252
|
+
await conn.execute(
|
|
2253
|
+
f"INSERT INTO {self._t('baselines')} (state_id, pin_id, lineage, sequence, intent_digest) VALUES ($1, $2, $3, $4, $5)",
|
|
2254
|
+
self.state_id,
|
|
2255
|
+
baseline.pin_id,
|
|
2256
|
+
baseline.lineage,
|
|
2257
|
+
baseline.sequence,
|
|
2258
|
+
intent_snapshot_digest(records),
|
|
2259
|
+
)
|
|
2260
|
+
return baseline
|
|
2261
|
+
|
|
2262
|
+
def baseline_intents(self, baseline: GraphBaseline) -> list[IntentRecord]:
|
|
2263
|
+
return self._run(self._baseline_intents, baseline)
|
|
2264
|
+
|
|
2265
|
+
async def _baseline_intents(self, baseline: GraphBaseline) -> list[IntentRecord]:
|
|
2266
|
+
async with self._tx(readonly=True, isolation="repeatable_read") as conn:
|
|
2267
|
+
return await self._baseline_intents_on(conn, baseline)
|
|
2268
|
+
|
|
2269
|
+
async def _baseline_intents_on(self, conn: asyncpg.Connection, baseline: GraphBaseline) -> list[IntentRecord]:
|
|
2270
|
+
# Keep each validation boundary, but read its lineage, pin and retained
|
|
2271
|
+
# history in one statement snapshot. Typed tagged rows avoid repeating
|
|
2272
|
+
# pin metadata, aggregating the origin, or encoding/decoding each intent
|
|
2273
|
+
# as JSON. Null fields only align the three projections.
|
|
2274
|
+
query = f"""
|
|
2275
|
+
SELECT 'app' AS section, lineage, NULL::text AS intent_digest,
|
|
2276
|
+
NULL::text AS kind, NULL::text AS key, NULL::bigint AS revision,
|
|
2277
|
+
NULL::bigint AS sequence, NULL::text AS intent_fp,
|
|
2278
|
+
NULL::boolean AS tombstone, NULL::text AS run_id
|
|
2279
|
+
FROM {self._t("apps")} WHERE state_id = $1
|
|
2280
|
+
UNION ALL
|
|
2281
|
+
SELECT 'pin', lineage, intent_digest, NULL, NULL, NULL, sequence, NULL, NULL, NULL
|
|
2282
|
+
FROM {self._t("baselines")} WHERE state_id = $1 AND pin_id = $2
|
|
2283
|
+
UNION ALL
|
|
2284
|
+
SELECT 'origin', NULL, NULL, kind, key, revision, sequence, intent_fp, tombstone, run_id
|
|
2285
|
+
FROM (SELECT DISTINCT ON (kind, key) kind, key, revision, sequence, intent_fp, tombstone, run_id
|
|
2286
|
+
FROM {self._t("versions")} WHERE state_id = $1 AND sequence <= $3
|
|
2287
|
+
ORDER BY kind, key, sequence DESC, revision DESC) origin
|
|
2288
|
+
"""
|
|
2289
|
+
sections: dict[str, list[Any]] = {kind: [] for kind in ("app", "pin", "origin")}
|
|
2290
|
+
for row in await conn.fetch(query, self.state_id, baseline.pin_id, baseline.sequence):
|
|
2291
|
+
sections[row["section"]].append(row)
|
|
2292
|
+
if not sections["app"]:
|
|
2293
|
+
raise StateError("This baseline's graph state no longer exists; pin the state this app actually uses")
|
|
2294
|
+
lineage = sections["app"][0]["lineage"]
|
|
2295
|
+
return self._checked_baseline_intents(baseline, lineage, sections["pin"], sections["origin"])
|
|
2296
|
+
|
|
2297
|
+
def _checked_baseline_intents(self, baseline: GraphBaseline, lineage: str, pins, rows) -> list[IntentRecord]:
|
|
2298
|
+
baseline.check_scope(self.get_backend_type(), self.state_id, lineage)
|
|
2299
|
+
if len(pins) != 1 or (pins[0]["lineage"], int(pins[0]["sequence"])) != (baseline.lineage, baseline.sequence):
|
|
2300
|
+
raise StateError("This baseline is no longer pinned, or its reference was changed; pin a valid baseline")
|
|
2301
|
+
records = [row if isinstance(row, IntentRecord) else IntentRecord(row["kind"], row["key"], int(row["revision"]), int(row["sequence"]), row["intent_fp"], bool(row["tombstone"]), row["run_id"]) for row in rows]
|
|
2302
|
+
if intent_snapshot_digest(records) != pins[0]["intent_digest"]:
|
|
2303
|
+
raise StateError("The baseline's retained intent history is incomplete; refusing to treat lost history as absence")
|
|
2304
|
+
return records
|
|
2305
|
+
|
|
2306
|
+
def unpin_baseline(self, pin_id: str) -> bool:
|
|
2307
|
+
return self._run(self._unpin_baseline, pin_id)
|
|
2308
|
+
|
|
2309
|
+
async def _unpin_baseline(self, pin_id: str) -> bool:
|
|
2310
|
+
async with self._tx() as conn:
|
|
2311
|
+
await conn.fetchrow(f"SELECT state_id FROM {self._t('apps')} WHERE state_id = $1 FOR UPDATE", self.state_id)
|
|
2312
|
+
origin = "coalesce(baseline, admitted_plan -> 'baseline')" if self._run_baselines else "admitted_plan -> 'baseline'"
|
|
2313
|
+
if await conn.fetchval(f"SELECT 1 FROM {self._t('runs')} WHERE state_id = $1 AND ({origin}) ->> 'pin_id' = $2 AND status = 'active' AND expires_at > clock_timestamp() LIMIT 1", self.state_id, pin_id):
|
|
2314
|
+
raise StateLockError("An active run still uses this baseline; end its run before unpinning it")
|
|
2315
|
+
row = await conn.fetchrow(f"DELETE FROM {self._t('baselines')} WHERE state_id = $1 AND pin_id = $2 RETURNING pin_id", self.state_id, pin_id)
|
|
2316
|
+
return row is not None
|
|
2317
|
+
|
|
2318
|
+
def record_run_baseline(self, ownership: Ownership, baseline: GraphBaseline) -> None:
|
|
2319
|
+
self._run(self._record_run_baseline, ownership, baseline)
|
|
2320
|
+
|
|
2321
|
+
async def _record_run_baseline(self, ownership: Ownership, baseline: GraphBaseline) -> None:
|
|
2322
|
+
async with self._owned_tx(ownership, "record baseline", planning=True) as transaction:
|
|
2323
|
+
conn, run = transaction.conn, transaction.run
|
|
2324
|
+
if not self._run_baselines:
|
|
2325
|
+
raise StateError("Upgrade the graph schema before recording run baselines")
|
|
2326
|
+
if ownership.claim is not None or run["operation"] == "recover":
|
|
2327
|
+
raise StateLockError("Recovery cannot change the original run's baseline")
|
|
2328
|
+
previous = _load(await conn.fetchval(f"SELECT coalesce(baseline, admitted_plan -> 'baseline') FROM {self._t('runs')} WHERE run_id = $1", ownership.run_id))
|
|
2329
|
+
if previous == baseline.to_dict():
|
|
2330
|
+
return
|
|
2331
|
+
if previous is not None:
|
|
2332
|
+
raise StateLockError("A run's baseline is immutable; end the run before changing it")
|
|
2333
|
+
if await conn.fetchval(
|
|
2334
|
+
f"SELECT EXISTS (SELECT 1 FROM {self._t('run_mutations')} WHERE run_id = $1) OR EXISTS (SELECT 1 FROM {self._t('operations')} WHERE (run_id = $1 OR recovered_by = $1) AND stage NOT IN ('committed', 'aborted'))",
|
|
2335
|
+
ownership.run_id,
|
|
2336
|
+
):
|
|
2337
|
+
raise StateLockError("Record the baseline before reserving operations or mutating state")
|
|
2338
|
+
# Serialize with pin release/pruning, without acquiring mutation permission.
|
|
2339
|
+
await conn.execute(f"SELECT 1 FROM {self._t('apps')} WHERE state_id = $1 FOR SHARE", self.state_id)
|
|
2340
|
+
await self._baseline_intents_on(conn, baseline)
|
|
2341
|
+
await conn.execute(f"UPDATE {self._t('runs')} SET baseline = $2 WHERE run_id = $1", ownership.run_id, _json(baseline.to_dict()))
|
|
2342
|
+
|
|
2343
|
+
def history(self, address: str | None = None, *, limit: int = 100) -> list[HistoryRecord]:
|
|
2344
|
+
return self._run(self._history, address, limit)
|
|
2345
|
+
|
|
2346
|
+
async def _history(self, address: str | None, limit: int) -> list[HistoryRecord]:
|
|
2347
|
+
async with self._tx(readonly=True) as conn:
|
|
2348
|
+
return await self._history_on(conn, address, limit)
|
|
2349
|
+
|
|
2350
|
+
def history_page(self, address: str | None = None, *, run_id: str | None = None, since: int = 0, limit: int = 100, cursor: str | None = None) -> HistoryPage:
|
|
2351
|
+
return self._run(self._history_page, address, run_id, since, limit, cursor)
|
|
2352
|
+
|
|
2353
|
+
async def _history_page(self, address: str | None, run_id: str | None, since: int, limit: int, cursor: str | None) -> HistoryPage:
|
|
2354
|
+
async with self._tx(readonly=True, isolation="repeatable_read") as conn:
|
|
2355
|
+
app = await conn.fetchrow(f"SELECT lineage, frontier, history_epoch FROM {self._t('apps')} WHERE state_id = $1", self.state_id)
|
|
2356
|
+
query = HistoryQuery.read((self.get_backend_type(), self.state_id, app["lineage"]), int(app["frontier"]), int(app["history_epoch"]), address=address, run_id=run_id, since=since, limit=limit, cursor=cursor)
|
|
2357
|
+
return query.page(await self._history_on(conn, address, limit + 1, query))
|
|
2358
|
+
|
|
2359
|
+
async def _history_on(self, conn: asyncpg.Connection, address: str | None, limit: int, query: HistoryQuery | None = None) -> list[HistoryRecord]:
|
|
2360
|
+
after = query.after if query is not None else None
|
|
2361
|
+
origin = "coalesce(r.baseline, r.admitted_plan -> 'baseline')" if self._run_baselines else "r.admitted_plan -> 'baseline'"
|
|
2362
|
+
context_column = "v.planning_context" if self._planning_contexts else "NULL AS planning_context"
|
|
2363
|
+
rows = await conn.fetch(
|
|
2364
|
+
f"""
|
|
2365
|
+
SELECT v.kind, v.key, v.revision, v.sequence, v.run_id, v.op_id, v.tombstone, extract(epoch FROM v.committed_at) AS at,
|
|
2366
|
+
r.operation, r.actor, h.value, v.intent_fp, v.inputs, v.applied_fp, v.status, v.mutation_revision, v.value_revision, v.membership_revision,
|
|
2367
|
+
{origin} AS baseline, {context_column}
|
|
2368
|
+
FROM {self._t("versions")} v
|
|
2369
|
+
LEFT JOIN {self._t("runs")} r ON r.run_id = v.run_id
|
|
2370
|
+
LEFT JOIN {self.schema}.{self.view_prefix}history h ON h.state_id = v.state_id AND h.kind = v.kind AND h.key = v.key AND h.revision = v.revision
|
|
2371
|
+
WHERE v.state_id = $1 AND ($2::text IS NULL OR v.key = $2) AND v.sequence <= $4 AND v.sequence >= $6
|
|
2372
|
+
AND ($5::text IS NULL OR v.run_id = $5)
|
|
2373
|
+
AND ($7::bigint IS NULL OR (-v.sequence, v.kind COLLATE "C", v.key COLLATE "C", -v.revision) > ($7, $8::text, $9::text, $10::bigint))
|
|
2374
|
+
ORDER BY v.sequence DESC, v.kind COLLATE "C", v.key COLLATE "C", v.revision DESC LIMIT $3
|
|
2375
|
+
""",
|
|
2376
|
+
self.state_id,
|
|
2377
|
+
address,
|
|
2378
|
+
limit,
|
|
2379
|
+
query.frontier if query is not None else 2**63 - 1,
|
|
2380
|
+
query.run_id if query is not None else None,
|
|
2381
|
+
query.since if query is not None else 0,
|
|
2382
|
+
*(after or (None, None, None, None)),
|
|
2383
|
+
)
|
|
2384
|
+
return [
|
|
2385
|
+
HistoryRecord(
|
|
2386
|
+
row["kind"],
|
|
2387
|
+
row["key"],
|
|
2388
|
+
int(row["revision"]),
|
|
2389
|
+
int(row["sequence"]),
|
|
2390
|
+
row["run_id"],
|
|
2391
|
+
row["op_id"],
|
|
2392
|
+
bool(row["tombstone"]),
|
|
2393
|
+
float(row["at"]),
|
|
2394
|
+
row["operation"],
|
|
2395
|
+
row["actor"],
|
|
2396
|
+
{"value": _load(row["value"])},
|
|
2397
|
+
intent_fp=row["intent_fp"],
|
|
2398
|
+
inputs=decode_inputs(_load(row["inputs"])),
|
|
2399
|
+
applied_fp=row["applied_fp"],
|
|
2400
|
+
status=row["status"],
|
|
2401
|
+
masked=True,
|
|
2402
|
+
mutation_revision=int(row["mutation_revision"]),
|
|
2403
|
+
value_revision=int(row["value_revision"]),
|
|
2404
|
+
membership_revision=int(row["membership_revision"]),
|
|
2405
|
+
baseline=GraphBaseline.from_dict(value) if (value := _load(row["baseline"])) is not None else None,
|
|
2406
|
+
planning_context=read_planning_context(_load(row["planning_context"])),
|
|
2407
|
+
)
|
|
2408
|
+
for row in rows
|
|
2409
|
+
]
|
|
2410
|
+
|
|
2411
|
+
def state_at(self, *, sequence: int | None = None, run_id: str | None = None, time: float | None = None) -> State:
|
|
2412
|
+
return self._run(self._state_at, sequence, run_id, time)
|
|
2413
|
+
|
|
2414
|
+
async def _state_at(self, sequence: int | None, run_id: str | None, time: float | None) -> State:
|
|
2415
|
+
async with self._tx(readonly=True, isolation="repeatable_read") as conn:
|
|
2416
|
+
app = await conn.fetchrow(f"SELECT lineage, frontier, pruned_before, metadata FROM {self._t('apps')} WHERE state_id = $1", self.state_id)
|
|
2417
|
+
if run_id is not None:
|
|
2418
|
+
sequence = await conn.fetchval(f"SELECT max(sequence) FROM {self._t('commits')} WHERE state_id = $1 AND run_id = $2", self.state_id, run_id)
|
|
2419
|
+
if sequence is None:
|
|
2420
|
+
raise StateError(f"Run {run_id} committed nothing")
|
|
2421
|
+
elif time is not None:
|
|
2422
|
+
sequence = await conn.fetchval(f"SELECT coalesce(max(sequence), 0) FROM {self._t('commits')} WHERE state_id = $1 AND committed_at <= to_timestamp($2)", self.state_id, time)
|
|
2423
|
+
limit = int(app["frontier"]) if sequence is None else int(sequence)
|
|
2424
|
+
if not 0 <= limit <= int(app["frontier"]):
|
|
2425
|
+
raise StateError(f"History sequence must be between 0 and the frontier ({app['frontier']})")
|
|
2426
|
+
pinned_digest = await conn.fetchval(f"SELECT intent_digest FROM {self._t('baselines')} WHERE state_id = $1 AND sequence = $2 LIMIT 1", self.state_id, limit)
|
|
2427
|
+
if 0 < limit <= int(app["pruned_before"]) and pinned_digest is None:
|
|
2428
|
+
raise StateError(f"History before sequence {app['pruned_before']} was pruned (history_retention_days); sequence {limit} cannot be shown whole")
|
|
2429
|
+
if pinned_digest is not None and intent_snapshot_digest(await self._intent_records(conn, limit)) != pinned_digest:
|
|
2430
|
+
raise StateError("The pinned history is incomplete; refusing to treat missing versions as absence")
|
|
2431
|
+
if limit == int(app["frontier"]):
|
|
2432
|
+
await self._check_current_history(conn, limit)
|
|
2433
|
+
rows = await conn.fetch(
|
|
2434
|
+
f"""
|
|
2435
|
+
SELECT DISTINCT ON (kind, key) kind, key, tombstone, row_data FROM {self._t("versions")}
|
|
2436
|
+
WHERE state_id = $1 AND sequence <= $2 ORDER BY kind, key, sequence DESC, revision DESC
|
|
2437
|
+
""",
|
|
2438
|
+
self.state_id,
|
|
2439
|
+
limit,
|
|
2440
|
+
)
|
|
2441
|
+
state = State(serial=limit, lineage=app["lineage"], metadata=_load(app["metadata"]) or {})
|
|
2442
|
+
for row in rows:
|
|
2443
|
+
if row["tombstone"] or row["row_data"] is None:
|
|
2444
|
+
continue
|
|
2445
|
+
if row["kind"] == RESOURCE:
|
|
2446
|
+
state.resources[row["key"]] = ResourceState.from_dict(_load(row["row_data"]))
|
|
2447
|
+
else:
|
|
2448
|
+
state.outputs[row["key"]] = _load(row["row_data"])
|
|
2449
|
+
return state
|
|
2450
|
+
|
|
2451
|
+
def query(self, sql: str, *, timeout: float = 30.0) -> tuple[list[str], list[tuple[Any, ...]]]:
|
|
2452
|
+
"""Run ``sql`` in a read-only transaction, as the read-only role (the views only), with a statement timeout."""
|
|
2453
|
+
return self._run(self._query, sql, timeout)
|
|
2454
|
+
|
|
2455
|
+
async def _query(self, sql: str, statement_timeout: float) -> tuple[list[str], list[tuple[Any, ...]]]:
|
|
2456
|
+
async with self._tx(readonly=True) as conn:
|
|
2457
|
+
await conn.execute(f"SET LOCAL statement_timeout = {int(statement_timeout * 1000)}")
|
|
2458
|
+
await conn.execute(f"SET LOCAL search_path = {self.schema}")
|
|
2459
|
+
try:
|
|
2460
|
+
await conn.execute(f"SET LOCAL ROLE {self.reader_role}")
|
|
2461
|
+
except asyncpg.PostgresError as exc:
|
|
2462
|
+
raise StateError(
|
|
2463
|
+
f"Queries run as the read-only role {self.reader_role}, which this user cannot assume ({exc}); a database administrator can create it with SELECT on the views and grant it to {self.username}",
|
|
2464
|
+
) from exc
|
|
2465
|
+
statement = await conn.prepare(sql)
|
|
2466
|
+
columns = [attribute.name for attribute in statement.get_attributes()]
|
|
2467
|
+
rows = await statement.fetch()
|
|
2468
|
+
return columns, [tuple(row) for row in rows]
|
|
2469
|
+
|
|
2470
|
+
def commit_log(self) -> list[dict[str, Any]]:
|
|
2471
|
+
"""Every commit with its run's epoch and lease expiry when it committed (oracles: none without a live lease)."""
|
|
2472
|
+
return self._run(self._commit_log)
|
|
2473
|
+
|
|
2474
|
+
async def _commit_log(self) -> list[dict[str, Any]]:
|
|
2475
|
+
async with self._tx(readonly=True) as conn:
|
|
2476
|
+
rows = await conn.fetch(
|
|
2477
|
+
f"SELECT c.sequence, c.run_id, c.epoch, c.fenced_at, c.committed_at, c.lease_expires_at, r.epoch AS run_epoch FROM {self._t('commits')} c LEFT JOIN {self._t('runs')} r USING (run_id) WHERE c.state_id = $1 ORDER BY c.sequence",
|
|
2478
|
+
self.state_id,
|
|
2479
|
+
)
|
|
2480
|
+
return [dict(row) for row in rows]
|
|
2481
|
+
|
|
2482
|
+
# -- migration ---------------------------------------------------------------------
|
|
2483
|
+
|
|
2484
|
+
def mark_migrated(self, ownership: Ownership, target: str) -> None:
|
|
2485
|
+
self._run(self._mark_migrated, ownership, target)
|
|
2486
|
+
|
|
2487
|
+
async def _mark_migrated(self, ownership: Ownership, target: str) -> None:
|
|
2488
|
+
async with self._owned_tx(ownership, "mark migrated") as transaction:
|
|
2489
|
+
conn = transaction.conn
|
|
2490
|
+
current = await conn.fetchval(f"SELECT migrated_to FROM {self._t('apps')} WHERE state_id = $1", self.state_id)
|
|
2491
|
+
if not target or (current is not None and current != target):
|
|
2492
|
+
raise StateError("A migrated state's destination cannot be cleared or changed")
|
|
2493
|
+
await conn.execute(f"UPDATE {self._t('apps')} SET migrated_to = $2 WHERE state_id = $1", self.state_id, target)
|
|
2494
|
+
|
|
2495
|
+
def transfer_record(self, transfer_id: str) -> TransferRecord | None:
|
|
2496
|
+
return self._run(PostgreSQLStateTransfers(self).record, transfer_id)
|
|
2497
|
+
|
|
2498
|
+
def stage_transfer(self, ownership: Ownership, transfer: StateTransfer, *, replace_staged: bool = False) -> None:
|
|
2499
|
+
self._run(PostgreSQLStateTransfers(self).stage, ownership, transfer, replace_staged)
|
|
2500
|
+
|
|
2501
|
+
def fence_transfer(self, ownership: Ownership, transfer: StateTransfer) -> None:
|
|
2502
|
+
self._run(PostgreSQLStateTransfers(self).fence, ownership, transfer)
|
|
2503
|
+
|
|
2504
|
+
def publish_transfer(self, ownership: Ownership, transfer: StateTransfer, state: State) -> None:
|
|
2505
|
+
self._run(PostgreSQLStateTransfers(self).publish, ownership, transfer, state)
|
|
2506
|
+
|
|
2507
|
+
def finish_transfer(self, ownership: Ownership, transfer: StateTransfer) -> None:
|
|
2508
|
+
self._run(PostgreSQLStateTransfers(self).finish, ownership, transfer)
|
|
2509
|
+
|
|
2510
|
+
|
|
2511
|
+
__all__ = ["PostgreSQLGraphBackend"]
|