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,102 @@
|
|
|
1
|
+
"""Set-based fresh-create authorization inside one fenced transaction."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections import defaultdict
|
|
6
|
+
from typing import TYPE_CHECKING
|
|
7
|
+
|
|
8
|
+
from netherframe.core.backends.graph_authorization import arm_payload, creation_arm_cohort
|
|
9
|
+
from netherframe.core.backends.graph_footprints import FOOTPRINT, combine_footprints
|
|
10
|
+
from netherframe.core.backends.graph_inputs import changed_inputs, decode_inputs, input_covers
|
|
11
|
+
from netherframe.core.backends.graph_object_guard import ObjectOperationGuard, object_problems, object_request
|
|
12
|
+
from netherframe.core.backends.graph_state import RESOURCE, UNCERTAIN, PreCallValidationError, QuarantinedError
|
|
13
|
+
|
|
14
|
+
if TYPE_CHECKING:
|
|
15
|
+
from collections.abc import Sequence
|
|
16
|
+
from netherframe.core.backends.graph_state import OperationSpec, Ownership
|
|
17
|
+
from .graph import PostgreSQLGraphBackend
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
async def arm_creations(backend: PostgreSQLGraphBackend, ownership: Ownership, specs: Sequence[OperationSpec]) -> None:
|
|
21
|
+
from .graph import _entry_of, _json, _version_of
|
|
22
|
+
|
|
23
|
+
prepared, proposed = creation_arm_cohort(ownership, specs)
|
|
24
|
+
async with backend._owned_tx(ownership, "arm creations") as transaction:
|
|
25
|
+
conn, run = transaction.conn, transaction.run
|
|
26
|
+
if not run["holds"] or run["admitted"] or run["operation"] != "apply":
|
|
27
|
+
raise PreCallValidationError("Creation authorization requires an unadmitted whole-app apply")
|
|
28
|
+
await conn.execute(f"SELECT 1 FROM {backend._t('apps')} WHERE state_id = $1 FOR UPDATE", backend.state_id)
|
|
29
|
+
addresses = [spec.address for spec in prepared]
|
|
30
|
+
holder = await backend._held(conn, addresses, ownership.run_id)
|
|
31
|
+
if holder is not None:
|
|
32
|
+
raise QuarantinedError(f"{holder['address']} is held by unresolved operation {holder['op_id']}; recover it before applying")
|
|
33
|
+
all_inputs = {}
|
|
34
|
+
for spec in prepared:
|
|
35
|
+
inputs = decode_inputs(spec.request["inputs"])
|
|
36
|
+
if inputs is None:
|
|
37
|
+
raise PreCallValidationError("Creation authorization requires known consumed inputs")
|
|
38
|
+
all_inputs[spec.address] = inputs
|
|
39
|
+
reads = [item for inputs in all_inputs.values() for item in inputs]
|
|
40
|
+
scoped = any(item.kind in {"scope", "enumeration"} for item in reads)
|
|
41
|
+
resource_keys = set(addresses) | {item.key for item in reads if item.kind == RESOURCE}
|
|
42
|
+
output_keys = {item.key for item in reads if item.kind == "output"}
|
|
43
|
+
rows = await conn.fetch(
|
|
44
|
+
f"SELECT * FROM {backend._t('entries')} WHERE state_id = $1 AND ($2::boolean OR address = ANY($3::text[])) ORDER BY address FOR UPDATE",
|
|
45
|
+
backend.state_id,
|
|
46
|
+
scoped,
|
|
47
|
+
sorted(resource_keys),
|
|
48
|
+
)
|
|
49
|
+
resources = {row["address"]: _version_of(row) for row in rows}
|
|
50
|
+
if present := set(addresses) & resources.keys():
|
|
51
|
+
raise PreCallValidationError(f"{sorted(present)[0]} changed since this run read it (expected absent); nothing was sent")
|
|
52
|
+
outputs = {}
|
|
53
|
+
if scoped or output_keys:
|
|
54
|
+
rows = await conn.fetch(f"SELECT * FROM {backend._t('outputs')} WHERE state_id = $1 AND ($2::boolean OR key = ANY($3::text[]))", backend.state_id, scoped, sorted(output_keys))
|
|
55
|
+
outputs = {row["key"]: backend._output_version(row) for row in rows}
|
|
56
|
+
operations = await backend._validate_footprint(conn, combine_footprints([spec.request[FOOTPRINT] for spec in prepared]), ownership)
|
|
57
|
+
for spec in prepared:
|
|
58
|
+
inputs = all_inputs[spec.address]
|
|
59
|
+
stale = changed_inputs(inputs, resources, outputs, owner=(RESOURCE, spec.address))
|
|
60
|
+
uncertain = [key for key, version in resources.items() if version.status == UNCERTAIN and key != spec.address and any(input_covers(item, RESOURCE, key) for item in inputs)]
|
|
61
|
+
uncertain.extend(key for operation in operations if operation.run_id != ownership.run_id for key in (operation.address, *operation.footprint) if any(input_covers(item, RESOURCE, key) for item in inputs))
|
|
62
|
+
if stale or uncertain:
|
|
63
|
+
raise PreCallValidationError(f"{spec.address}: consumed inputs changed or are unresolved before dispatch; replan before applying")
|
|
64
|
+
claims = {spec.address: object_request(spec.request, spec.action) for spec in prepared}
|
|
65
|
+
candidates = await conn.fetch(
|
|
66
|
+
f"""SELECT type, object_identity, entry, private, status FROM {backend._t("entries")}
|
|
67
|
+
WHERE state_id = $1 AND NOT tombstone AND
|
|
68
|
+
(address = ANY($2::text[]) OR object_identity = ANY($3::text[]) OR
|
|
69
|
+
(type = ANY($4::text[]) AND (object_identity IS NULL OR object_identity NOT LIKE 'nf-object-v1:%')))""",
|
|
70
|
+
backend.state_id,
|
|
71
|
+
addresses,
|
|
72
|
+
sorted({identity for claim in claims.values() for identity in claim.identities}),
|
|
73
|
+
sorted({kind for claim in claims.values() for _source, kind in claim.sources}),
|
|
74
|
+
)
|
|
75
|
+
known, unknown = defaultdict(list), defaultdict(list)
|
|
76
|
+
for row in candidates:
|
|
77
|
+
entry = _entry_of(row["entry"], row["private"], row["status"])
|
|
78
|
+
if row["object_identity"] and row["object_identity"].startswith("nf-object-v1:"):
|
|
79
|
+
known[row["object_identity"]].append(entry)
|
|
80
|
+
else:
|
|
81
|
+
unknown[row["type"]].append(entry)
|
|
82
|
+
object_guard = ObjectOperationGuard(operations, additional=proposed)
|
|
83
|
+
for spec in prepared:
|
|
84
|
+
claim = claims[spec.address]
|
|
85
|
+
peers = [entry for identity in claim.identities for entry in known[identity]]
|
|
86
|
+
peers.extend(entry for kind in {kind for _source, kind in claim.sources} for entry in unknown[kind])
|
|
87
|
+
if problems := object_problems(spec.address, spec.request, spec.action, peers, object_guard, exclude_op=spec.op_id, run_id=ownership.run_id, claims=claim):
|
|
88
|
+
raise PreCallValidationError("Cloud ownership validation failed:\n" + "\n".join(problems))
|
|
89
|
+
payload = [arm_payload(spec) for spec in prepared]
|
|
90
|
+
await conn.execute(
|
|
91
|
+
f"""INSERT INTO {backend._t("operations")} (op_id, state_id, run_id, epoch, address, footprint,
|
|
92
|
+
object_identity, action, stage, expected, expected_provider, request, request_digest,
|
|
93
|
+
owner_host, owner_pid, provider_pid, dispatched_at)
|
|
94
|
+
SELECT w.op_id, $1, $3, $4, w.address, '[]'::jsonb, NULL, 'create', 'dispatched', NULL,
|
|
95
|
+
w.provider, w.request, w.request_digest, w.owner_host, w.owner_pid, w.provider_pid, clock_timestamp()
|
|
96
|
+
FROM jsonb_to_recordset($2::jsonb) AS w(op_id text, address text, provider text, request jsonb,
|
|
97
|
+
request_digest text, owner_host text, owner_pid integer, provider_pid integer)""",
|
|
98
|
+
backend.state_id,
|
|
99
|
+
_json(payload),
|
|
100
|
+
ownership.run_id,
|
|
101
|
+
ownership.epoch,
|
|
102
|
+
)
|
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
"""Pinned write-set checkpoints and atomic state-only restore transactions."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Mapping, Sequence
|
|
6
|
+
from typing import TYPE_CHECKING, Any
|
|
7
|
+
import uuid
|
|
8
|
+
|
|
9
|
+
from netherframe.core.backends.graph_checkpoint import (
|
|
10
|
+
CheckpointRestorePreview,
|
|
11
|
+
CheckpointTarget,
|
|
12
|
+
GraphCheckpoint,
|
|
13
|
+
before_image,
|
|
14
|
+
checked_targets,
|
|
15
|
+
checkpoint_id,
|
|
16
|
+
image_digest,
|
|
17
|
+
require_no_restore_blockers,
|
|
18
|
+
require_restore_identities,
|
|
19
|
+
restore_blockers,
|
|
20
|
+
restore_leases,
|
|
21
|
+
restore_writes,
|
|
22
|
+
)
|
|
23
|
+
from netherframe.core.backends.graph_inputs import UNCONVERGED, decode_inputs
|
|
24
|
+
from netherframe.core.backends.graph_leases import X, LeaseKey, normalized
|
|
25
|
+
from netherframe.core.backends.graph_state import HistoryRecord, Ownership, PreCallValidationError, RowWrite
|
|
26
|
+
from netherframe.core.exceptions import StateError
|
|
27
|
+
from netherframe.core.serialization import orjson_compat as json
|
|
28
|
+
|
|
29
|
+
if TYPE_CHECKING:
|
|
30
|
+
import asyncpg
|
|
31
|
+
from .graph import PostgreSQLGraphBackend
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _load(value: Any) -> Any:
|
|
35
|
+
return json.loads(value) if isinstance(value, str | bytes) else value
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _record(row: Mapping[str, Any]) -> HistoryRecord:
|
|
39
|
+
return HistoryRecord(
|
|
40
|
+
row["kind"],
|
|
41
|
+
row["key"],
|
|
42
|
+
int(row["revision"]),
|
|
43
|
+
int(row["sequence"]),
|
|
44
|
+
row["run_id"],
|
|
45
|
+
row["op_id"],
|
|
46
|
+
bool(row["tombstone"]),
|
|
47
|
+
0,
|
|
48
|
+
row=_load(row.get("row_data")),
|
|
49
|
+
intent_fp=row["intent_fp"],
|
|
50
|
+
inputs=decode_inputs(_load(row["inputs"])),
|
|
51
|
+
applied_fp=row["applied_fp"],
|
|
52
|
+
status=row["status"],
|
|
53
|
+
sensitive_paths=tuple(tuple(path) for path in _load(row["sensitive_paths"]) or ()),
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class PostgreSQLHistoryCheckpoints:
|
|
58
|
+
def __init__(self, backend: PostgreSQLGraphBackend) -> None:
|
|
59
|
+
self.b = backend
|
|
60
|
+
|
|
61
|
+
async def get(self, conn: asyncpg.Connection, reference: str) -> GraphCheckpoint:
|
|
62
|
+
row = await conn.fetchrow(
|
|
63
|
+
f"SELECT c.manifest, c.run_id, c.sequence, c.operation_frontier, a.lineage FROM {self.b._t('checkpoints')} c JOIN {self.b._t('apps')} a USING (state_id) WHERE c.state_id = $1 AND c.checkpoint_id = $2",
|
|
64
|
+
self.b.state_id,
|
|
65
|
+
checkpoint_id(reference),
|
|
66
|
+
)
|
|
67
|
+
if row is None:
|
|
68
|
+
raise StateError("This checkpoint is not retained in this graph state")
|
|
69
|
+
checkpoint = GraphCheckpoint.from_dict(_load(row["manifest"]))
|
|
70
|
+
checkpoint.check_scope(self.b.get_backend_type(), self.b.state_id, row["lineage"])
|
|
71
|
+
if checkpoint.checkpoint_id != checkpoint_id(reference) or (checkpoint.run_id, checkpoint.sequence, checkpoint.operation_frontier) != (row["run_id"], int(row["sequence"]), int(row["operation_frontier"])):
|
|
72
|
+
raise StateError("The checkpoint reference was changed")
|
|
73
|
+
return checkpoint
|
|
74
|
+
|
|
75
|
+
async def images(self, conn: asyncpg.Connection, targets: Sequence[CheckpointTarget]) -> dict[tuple[str, str], RowWrite]:
|
|
76
|
+
requested = json.dumps([{"kind": item.kind, "key": item.key, "revision": item.revision} for item in targets])
|
|
77
|
+
rows = await conn.fetch(
|
|
78
|
+
f"SELECT v.* FROM {self.b._t('versions')} v JOIN jsonb_to_recordset($2::jsonb) AS t(kind text, key text, revision bigint) ON (v.kind, v.key, v.revision) = (t.kind, t.key, t.revision) WHERE v.state_id = $1",
|
|
79
|
+
self.b.state_id,
|
|
80
|
+
requested,
|
|
81
|
+
)
|
|
82
|
+
records = {(row["kind"], row["key"]): _record(row) for row in rows}
|
|
83
|
+
images = {}
|
|
84
|
+
for target in targets:
|
|
85
|
+
record = records.get((target.kind, target.key))
|
|
86
|
+
if target.revision and record is None:
|
|
87
|
+
raise StateError(f"{target.key}: its pinned checkpoint version is missing; restore refused")
|
|
88
|
+
images[target.kind, target.key] = before_image(target.kind, target.key, record)
|
|
89
|
+
return images
|
|
90
|
+
|
|
91
|
+
async def evidence(self, conn: asyncpg.Connection, checkpoint: GraphCheckpoint):
|
|
92
|
+
rows = await conn.fetch(f"SELECT * FROM {self.b._t('versions')} WHERE state_id = $1 AND sequence > $2 AND run_id IS DISTINCT FROM $3", self.b.state_id, checkpoint.sequence, checkpoint.run_id)
|
|
93
|
+
# Requests without a committed row still record possible consumption.
|
|
94
|
+
operations = await self.b._operations(conn, unresolved=False, op_id=None, after_reservation=checkpoint.operation_frontier)
|
|
95
|
+
return [_record(row) for row in rows], operations
|
|
96
|
+
|
|
97
|
+
async def qualify_convergence(self, conn: asyncpg.Connection, checkpoint: GraphCheckpoint, writes: Sequence[RowWrite]) -> None:
|
|
98
|
+
"""Qualify legacy readiness and inputs after verifying the immutable image.
|
|
99
|
+
|
|
100
|
+
Newer versions were written behind the convergence protocol fence.
|
|
101
|
+
Older ready flags need their upgrade certificate, even after journal
|
|
102
|
+
retention. The ephemeral frontier independently qualifies input capture.
|
|
103
|
+
"""
|
|
104
|
+
targets = json.dumps([{"kind": target.kind, "key": target.key, "revision": target.revision} for target in checkpoint.targets])
|
|
105
|
+
rows = await conn.fetch(
|
|
106
|
+
f"""SELECT v.kind, v.key, (v.sequence <= a.ephemeral_inputs_frontier) AS unknown_inputs
|
|
107
|
+
FROM {self.b._t("versions")} v
|
|
108
|
+
JOIN {self.b._t("apps")} a USING (state_id)
|
|
109
|
+
JOIN jsonb_to_recordset($2::jsonb) AS t(kind text, key text, revision bigint)
|
|
110
|
+
ON (v.kind, v.key, v.revision) = (t.kind, t.key, t.revision)
|
|
111
|
+
LEFT JOIN {self.b._t("convergence_evidence")} c
|
|
112
|
+
ON (c.state_id, c.kind, c.key, c.revision) = (v.state_id, v.kind, v.key, v.revision)
|
|
113
|
+
WHERE v.state_id = $1 AND v.kind IN ('resource', 'output') AND (
|
|
114
|
+
(v.kind = 'resource' AND v.sequence <= a.convergence_frontier AND NOT coalesce(c.verified, false))
|
|
115
|
+
OR v.sequence <= a.ephemeral_inputs_frontier)""",
|
|
116
|
+
self.b.state_id,
|
|
117
|
+
targets,
|
|
118
|
+
)
|
|
119
|
+
unverified = {(row["kind"], row["key"]) for row in rows}
|
|
120
|
+
unknown_inputs = {(row["kind"], row["key"]) for row in rows if row["unknown_inputs"]}
|
|
121
|
+
for write in writes:
|
|
122
|
+
if (write.kind, write.key) in unknown_inputs and not write.removal:
|
|
123
|
+
write.inputs = None
|
|
124
|
+
if (write.kind, write.key) in unverified and not write.removal and write.status == "ready":
|
|
125
|
+
write.status = UNCONVERGED
|
|
126
|
+
|
|
127
|
+
async def prunable(self, conn: asyncpg.Connection) -> list[str]:
|
|
128
|
+
# Newest checkpoints count toward the limit even while active. Older
|
|
129
|
+
# active origins, unresolved operations and active restore receipts pin.
|
|
130
|
+
rows = await conn.fetch(
|
|
131
|
+
f"""SELECT c.checkpoint_id FROM {self.b._t("checkpoints")} c WHERE c.state_id = $1
|
|
132
|
+
AND c.checkpoint_id NOT IN (SELECT checkpoint_id FROM {self.b._t("checkpoints")} WHERE state_id = $1 ORDER BY checkpoint_order DESC LIMIT coalesce((SELECT keep_count FROM {self.b._t("checkpoints")} WHERE state_id = $1 ORDER BY checkpoint_order DESC LIMIT 1), 5))
|
|
133
|
+
AND NOT EXISTS (SELECT 1 FROM {self.b._t("runs")} r WHERE r.run_id = c.run_id AND r.status = 'active' AND r.expires_at > clock_timestamp())
|
|
134
|
+
AND NOT EXISTS (SELECT 1 FROM {self.b._t("operations")} o WHERE o.state_id = c.state_id AND o.run_id = c.run_id AND o.stage NOT IN ('committed', 'aborted'))
|
|
135
|
+
AND NOT EXISTS (SELECT 1 FROM {self.b._t("checkpoint_restores")} x JOIN {self.b._t("runs")} r USING (run_id) WHERE x.state_id = c.state_id AND x.checkpoint_id = c.checkpoint_id AND r.status = 'active' AND r.expires_at > clock_timestamp())""",
|
|
136
|
+
self.b.state_id,
|
|
137
|
+
)
|
|
138
|
+
return [row["checkpoint_id"] for row in rows]
|
|
139
|
+
|
|
140
|
+
async def prune(self, conn: asyncpg.Connection) -> int:
|
|
141
|
+
ids = await self.prunable(conn)
|
|
142
|
+
rows = await conn.fetch(f"DELETE FROM {self.b._t('checkpoints')} WHERE state_id = $1 AND checkpoint_id = ANY($2::text[]) RETURNING checkpoint_id", self.b.state_id, ids)
|
|
143
|
+
return len(rows)
|
|
144
|
+
|
|
145
|
+
async def create(self, ownership: Ownership, targets: Sequence[tuple[str, str]], name: str, keep: int) -> GraphCheckpoint:
|
|
146
|
+
if type(keep) is not int or keep < 1:
|
|
147
|
+
raise StateError("Keep at least one history checkpoint")
|
|
148
|
+
targets = checked_targets(targets)
|
|
149
|
+
async with self.b._owned_tx(ownership, "checkpoint") as transaction:
|
|
150
|
+
conn, run = transaction.conn, transaction.run
|
|
151
|
+
app = await conn.fetchrow(f"SELECT lineage, frontier FROM {self.b._t('apps')} WHERE state_id = $1 FOR UPDATE", self.b.state_id)
|
|
152
|
+
if await conn.fetchval(
|
|
153
|
+
f"SELECT EXISTS (SELECT 1 FROM {self.b._t('run_mutations')} WHERE run_id = $1) OR EXISTS (SELECT 1 FROM {self.b._t('operations')} WHERE run_id = $1 AND stage NOT IN ('committed', 'aborted'))", ownership.run_id
|
|
154
|
+
):
|
|
155
|
+
raise PreCallValidationError("Capture a checkpoint before reserving calls or mutating state")
|
|
156
|
+
if run["admitted"]:
|
|
157
|
+
await self.b._check_admitted_targets(conn, ownership, targets)
|
|
158
|
+
await self.b._validate_footprint(conn, normalized({LeaseKey.entry(key): X for _kind, key in targets}), ownership)
|
|
159
|
+
# Checkpoint creation needs only the selected current revisions and
|
|
160
|
+
# their retained images, never every resource/provider payload.
|
|
161
|
+
selected = json.dumps([{"kind": kind, "key": key} for kind, key in targets])
|
|
162
|
+
rows = await conn.fetch(
|
|
163
|
+
f"""WITH selected AS (SELECT * FROM jsonb_to_recordset($2::jsonb) AS t(kind text, key text))
|
|
164
|
+
SELECT 'resource' AS kind, e.address AS key, e.revision FROM {self.b._t("entries")} e
|
|
165
|
+
JOIN selected t ON t.kind = 'resource' AND e.address = t.key WHERE e.state_id = $1
|
|
166
|
+
UNION ALL
|
|
167
|
+
SELECT 'output' AS kind, o.key, o.revision FROM {self.b._t("outputs")} o
|
|
168
|
+
JOIN selected t ON t.kind = 'output' AND o.key = t.key WHERE o.state_id = $1""",
|
|
169
|
+
self.b.state_id,
|
|
170
|
+
selected,
|
|
171
|
+
)
|
|
172
|
+
current = {(row["kind"], row["key"]): int(row["revision"]) for row in rows}
|
|
173
|
+
revisions = [CheckpointTarget(kind, key, current.get((kind, key), 0), "0" * 64) for kind, key in targets]
|
|
174
|
+
images = await self.images(conn, revisions)
|
|
175
|
+
pinned = tuple(CheckpointTarget(item.kind, item.key, item.revision, image_digest(images[item.kind, item.key])) for item in revisions)
|
|
176
|
+
frontier = int(await conn.fetchval(f"SELECT coalesce(max(reservation), 0) FROM {self.b._t('operations')} WHERE state_id = $1", self.b.state_id))
|
|
177
|
+
checkpoint = GraphCheckpoint(self.b.get_backend_type(), self.b.state_id, app["lineage"], uuid.uuid4().hex, name, ownership.run_id, int(app["frontier"]), frontier, pinned)
|
|
178
|
+
await conn.execute(
|
|
179
|
+
f"INSERT INTO {self.b._t('checkpoints')} (state_id, checkpoint_id, run_id, sequence, operation_frontier, manifest, keep_count) VALUES ($1, $2, $3, $4, $5, $6::jsonb, $7)",
|
|
180
|
+
self.b.state_id,
|
|
181
|
+
checkpoint.checkpoint_id,
|
|
182
|
+
ownership.run_id,
|
|
183
|
+
checkpoint.sequence,
|
|
184
|
+
checkpoint.operation_frontier,
|
|
185
|
+
json.dumps(checkpoint.to_dict()),
|
|
186
|
+
keep,
|
|
187
|
+
)
|
|
188
|
+
await self.prune(conn)
|
|
189
|
+
return checkpoint
|
|
190
|
+
|
|
191
|
+
async def list_checkpoints(self) -> list[GraphCheckpoint]:
|
|
192
|
+
async with self.b._tx(readonly=True) as conn:
|
|
193
|
+
rows = await conn.fetch(f"SELECT manifest FROM {self.b._t('checkpoints')} WHERE state_id = $1 ORDER BY checkpoint_order DESC", self.b.state_id)
|
|
194
|
+
return [GraphCheckpoint.from_dict(_load(row["manifest"])) for row in rows]
|
|
195
|
+
|
|
196
|
+
async def prepare(self, reference: str) -> CheckpointRestorePreview:
|
|
197
|
+
async with self.b._tx(readonly=True, isolation="repeatable_read") as conn:
|
|
198
|
+
checkpoint = await self.get(conn, reference)
|
|
199
|
+
snapshot = await self.b._snapshot_on(conn)
|
|
200
|
+
writes = restore_writes(checkpoint, await self.images(conn, checkpoint.targets), snapshot)
|
|
201
|
+
await self.qualify_convergence(conn, checkpoint, writes)
|
|
202
|
+
history, operations = await self.evidence(conn, checkpoint)
|
|
203
|
+
return CheckpointRestorePreview(checkpoint, restore_leases(writes, snapshot), restore_blockers(checkpoint, writes, snapshot, history, operations))
|
|
204
|
+
|
|
205
|
+
async def receipt_on(self, conn: asyncpg.Connection, run_id: str, reference: str, force: bool) -> int | None:
|
|
206
|
+
row = await conn.fetchrow(f"SELECT checkpoint_id, force, sequence FROM {self.b._t('checkpoint_restores')} WHERE state_id = $1 AND run_id = $2", self.b.state_id, run_id)
|
|
207
|
+
if row is None:
|
|
208
|
+
return None
|
|
209
|
+
if (row["checkpoint_id"], row["force"]) != (checkpoint_id(reference), force) or type(force) is not bool:
|
|
210
|
+
raise StateError("A restore run's checkpoint and force policy cannot change")
|
|
211
|
+
return int(row["sequence"])
|
|
212
|
+
|
|
213
|
+
async def receipt(self, run_id: str, reference: str, force: bool) -> int | None:
|
|
214
|
+
async with self.b._tx(readonly=True) as conn:
|
|
215
|
+
return await self.receipt_on(conn, run_id, reference, force)
|
|
216
|
+
|
|
217
|
+
async def restore(self, ownership: Ownership, reference: str, force: bool) -> int:
|
|
218
|
+
async with self.b._tx() as conn:
|
|
219
|
+
if (receipt := await self.receipt_on(conn, ownership.run_id, reference, force)) is not None:
|
|
220
|
+
return receipt
|
|
221
|
+
async with self.b._mutation(conn, ownership, "restore checkpoint", restoring=True) as transaction:
|
|
222
|
+
await conn.fetchrow(f"SELECT state_id FROM {self.b._t('apps')} WHERE state_id = $1 FOR UPDATE", self.b.state_id)
|
|
223
|
+
# Recheck after the app lock; no transaction or clock observation
|
|
224
|
+
# from preview is authority for this write.
|
|
225
|
+
if (receipt := await self.receipt_on(conn, ownership.run_id, reference, force)) is not None:
|
|
226
|
+
return receipt
|
|
227
|
+
checkpoint = await self.get(conn, reference)
|
|
228
|
+
snapshot = await self.b._snapshot_on(conn)
|
|
229
|
+
writes = restore_writes(checkpoint, await self.images(conn, checkpoint.targets), snapshot)
|
|
230
|
+
await self.qualify_convergence(conn, checkpoint, writes)
|
|
231
|
+
await self.b._validate_footprint(conn, restore_leases(writes, snapshot), ownership)
|
|
232
|
+
require_restore_identities(writes, snapshot)
|
|
233
|
+
history, operations = await self.evidence(conn, checkpoint)
|
|
234
|
+
require_no_restore_blockers(restore_blockers(checkpoint, writes, snapshot, history, operations), force=force)
|
|
235
|
+
sequence = (await self.b._commit_on(transaction, writes, {}, None)).sequence if writes else snapshot.frontier
|
|
236
|
+
await conn.execute(
|
|
237
|
+
f"INSERT INTO {self.b._t('checkpoint_restores')} (state_id, run_id, checkpoint_id, force, sequence) VALUES ($1, $2, $3, $4, $5)", self.b.state_id, ownership.run_id, checkpoint.checkpoint_id, force, sequence
|
|
238
|
+
)
|
|
239
|
+
return sequence
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
"""Raw responses survive a rejected opportunistic publication."""
|
|
2
|
+
|
|
3
|
+
import asyncpg
|
|
4
|
+
|
|
5
|
+
from netherframe.core.backends.graph_completion import CompletionResult, check_cohort, check_record, ready_writes
|
|
6
|
+
from netherframe.core.backends.graph_plan_guard import require_write_contracts
|
|
7
|
+
from netherframe.core.backends.graph_state import COMMITTED, PreCallValidationError
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
async def complete_creations(backend, ownership, items):
|
|
11
|
+
from .graph import _json
|
|
12
|
+
|
|
13
|
+
check_cohort(ownership, items)
|
|
14
|
+
async with backend._owned_tx(ownership, "complete creations") as transaction:
|
|
15
|
+
conn = transaction.conn
|
|
16
|
+
if transaction.run["admitted"] or transaction.run["operation"] != "apply":
|
|
17
|
+
raise PreCallValidationError("Completion requires unadmitted whole-app ownership")
|
|
18
|
+
rows = await conn.fetch(
|
|
19
|
+
f"""SELECT op_id, epoch, attempt, run_id, recovered_by, stage, address, action, request_digest
|
|
20
|
+
FROM {backend._t("operations")} WHERE state_id=$1 AND op_id=ANY($2::text[])
|
|
21
|
+
ORDER BY op_id FOR UPDATE""",
|
|
22
|
+
backend.state_id,
|
|
23
|
+
[item.identity.op_id for item in items],
|
|
24
|
+
)
|
|
25
|
+
records = {row["op_id"]: row for row in rows}
|
|
26
|
+
for item in items:
|
|
27
|
+
record = records.get(item.identity.op_id)
|
|
28
|
+
if record is None:
|
|
29
|
+
raise PreCallValidationError("Completion operation no longer exists")
|
|
30
|
+
ownership.check_operation(record["op_id"], record["run_id"], int(record["epoch"]), int(record["attempt"]), record["recovered_by"])
|
|
31
|
+
check_record(item, record)
|
|
32
|
+
await conn.execute(
|
|
33
|
+
f"""UPDATE {backend._t("operations")} AS o SET stage='returned', result=v.result,
|
|
34
|
+
error=NULL, returned_at=clock_timestamp()
|
|
35
|
+
FROM jsonb_to_recordset($1::jsonb) AS v(op_id text, result jsonb)
|
|
36
|
+
WHERE o.op_id=v.op_id AND o.state_id=$2""",
|
|
37
|
+
_json([{"op_id": item.identity.op_id, "result": {"stage": "dispatched", "value": item.result}} for item in items]),
|
|
38
|
+
backend.state_id,
|
|
39
|
+
)
|
|
40
|
+
writes = []
|
|
41
|
+
try:
|
|
42
|
+
# Taking the slots never waits for row construction or a provider.
|
|
43
|
+
# Raw outcomes above are outside this publication savepoint.
|
|
44
|
+
writes = ready_writes(items)
|
|
45
|
+
require_write_contracts(writes)
|
|
46
|
+
result = None
|
|
47
|
+
if writes:
|
|
48
|
+
async with conn.transaction():
|
|
49
|
+
# Publication must not hold raw durability behind another
|
|
50
|
+
# app decision. A busy frontier uses ordinary publication later.
|
|
51
|
+
await conn.fetchval(f"SELECT frontier FROM {backend._t('apps')} WHERE state_id=$1 FOR UPDATE NOWAIT", backend.state_id)
|
|
52
|
+
records = await backend._locked_operations(conn, ownership, [write.op_id for write in writes])
|
|
53
|
+
if any(record["stage"] != "returned" or record["action"] != "create" or record["error"] is not None for record in records.values()):
|
|
54
|
+
raise PreCallValidationError("Completion publication requires successful returned creates")
|
|
55
|
+
result = await backend._commit_on(transaction, writes, {write.op_id: COMMITTED for write in writes}, None, records)
|
|
56
|
+
except asyncpg.LockNotAvailableError:
|
|
57
|
+
transaction.sequences.clear()
|
|
58
|
+
receipt = CompletionResult()
|
|
59
|
+
except Exception as exc:
|
|
60
|
+
# If rollback itself fails this outer transaction also fails; the
|
|
61
|
+
# engine journals every raw response. Never retry a lost reply.
|
|
62
|
+
transaction.sequences.clear()
|
|
63
|
+
receipt = CompletionResult(writes=tuple(writes), rejection=f"{type(exc).__name__}: {exc}")
|
|
64
|
+
else:
|
|
65
|
+
receipt = CompletionResult(result, tuple(writes))
|
|
66
|
+
return receipt
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
"""Upgrade old readiness claims without confusing configurations or cloud objects.
|
|
2
|
+
|
|
3
|
+
The schema migration holds its ownership/data locks for this entire backfill.
|
|
4
|
+
Certificates preserve the result after old operation journals are pruned; later
|
|
5
|
+
checkpoint restores qualify the immutable before-image through those certificates.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from collections.abc import Mapping
|
|
11
|
+
from typing import TYPE_CHECKING, Any
|
|
12
|
+
import re
|
|
13
|
+
|
|
14
|
+
from netherframe.core.backends.graph_identity import locator_of
|
|
15
|
+
from netherframe.core.backends.graph_object_guard import source_of
|
|
16
|
+
from netherframe.core.backends.graph_state import object_identity
|
|
17
|
+
from netherframe.core.backends.state_models import ResourceState
|
|
18
|
+
from netherframe.core.exceptions import StateError
|
|
19
|
+
from netherframe.core.logging import get_logger
|
|
20
|
+
from netherframe.core.serialization import orjson_compat as json
|
|
21
|
+
|
|
22
|
+
if TYPE_CHECKING:
|
|
23
|
+
import asyncpg
|
|
24
|
+
from .graph import PostgreSQLGraphBackend
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _load(value: Any) -> Any:
|
|
28
|
+
return json.loads(value) if isinstance(value, str | bytes) else value
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def verified_legacy_version(row: Mapping[str, Any]) -> bool:
|
|
32
|
+
"""A successful response must cover this configuration and this object.
|
|
33
|
+
|
|
34
|
+
A later refresh may report legitimate drift, so equality of whole state
|
|
35
|
+
values would wrongly discard valid convergence. Conversely a state-only
|
|
36
|
+
restore may carry another fingerprint/object while retaining the last
|
|
37
|
+
mutation counter, which cannot certify the restored configuration.
|
|
38
|
+
"""
|
|
39
|
+
try:
|
|
40
|
+
request, result = _load(row["request"]), _load(row["result"])
|
|
41
|
+
if not isinstance(request, Mapping) or not isinstance(result, Mapping):
|
|
42
|
+
return False
|
|
43
|
+
encoding = request.get("encoding_version")
|
|
44
|
+
if type(encoding) is not int or encoding != 1 or not re.fullmatch(r"[0-9a-f]{64}", row["request_digest"] or ""):
|
|
45
|
+
return False
|
|
46
|
+
if row["stage"] != "committed" or row["action"] not in {"create", "update", "replace"} or row["error"] is not None or "observation" in result:
|
|
47
|
+
return False
|
|
48
|
+
if result.get("stage") not in {"dispatched", "create_dispatched"}:
|
|
49
|
+
return False
|
|
50
|
+
value = result.get("value")
|
|
51
|
+
if not isinstance(value, Mapping) or not isinstance(value.get("state"), Mapping) or "unknown_values" in value:
|
|
52
|
+
return False
|
|
53
|
+
applied = request.get("applied_fp")
|
|
54
|
+
intent = row["intent_fp"]
|
|
55
|
+
if not isinstance(intent, str) or not intent or not isinstance(applied, str) or not applied or row["applied_fp"] != applied or row["mutation_applied_fp"] != applied:
|
|
56
|
+
return False
|
|
57
|
+
current = ResourceState.from_dict(_load(row["row_data"]))
|
|
58
|
+
mutation = ResourceState.from_dict(_load(row["mutation_row"]))
|
|
59
|
+
if current.resource_id != row["key"] or mutation.resource_id != row["key"]:
|
|
60
|
+
return False
|
|
61
|
+
for entry in (current, mutation):
|
|
62
|
+
locator = locator_of(entry.metadata, entry.type)
|
|
63
|
+
if locator is None or locator.scope.source != source_of(entry):
|
|
64
|
+
return False # An alias or opaque id cannot prove the actual cloud namespace.
|
|
65
|
+
returned = mutation.copy()
|
|
66
|
+
returned.attributes = dict(value["state"])
|
|
67
|
+
returned.identity = dict(value["identity"]) if isinstance(value.get("identity"), Mapping) else None
|
|
68
|
+
identity = object_identity(mutation)
|
|
69
|
+
return identity is not None and identity == object_identity(current) == object_identity(returned)
|
|
70
|
+
except KeyError, TypeError, ValueError, AttributeError, StateError:
|
|
71
|
+
return False # Ambiguous, missing or malformed legacy evidence never certifies ready.
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
async def backfill_legacy_convergence(conn: asyncpg.Connection, backend: PostgreSQLGraphBackend) -> None:
|
|
75
|
+
query = f"""SELECT v.state_id, v.key, v.revision, v.row_data, v.intent_fp, v.applied_fp,
|
|
76
|
+
mutation.row_data AS mutation_row, mutation.applied_fp AS mutation_applied_fp,
|
|
77
|
+
o.stage, o.action, o.error, o.request, o.request_digest, o.result
|
|
78
|
+
FROM {backend._t("versions")} v
|
|
79
|
+
LEFT JOIN {backend._t("versions")} mutation ON mutation.state_id = v.state_id
|
|
80
|
+
AND mutation.kind = v.kind AND mutation.key = v.key AND mutation.revision = v.mutation_revision
|
|
81
|
+
LEFT JOIN {backend._t("operations")} o ON o.state_id = v.state_id AND o.op_id = mutation.op_id
|
|
82
|
+
WHERE v.kind = 'resource' AND v.status = 'ready' AND NOT v.tombstone"""
|
|
83
|
+
insert = f"INSERT INTO {backend._t('convergence_evidence')} (state_id, kind, key, revision, verified) VALUES ($1, 'resource', $2, $3, $4)"
|
|
84
|
+
pending = []
|
|
85
|
+
inspected, verified = 0, 0
|
|
86
|
+
async for row in conn.cursor(query, prefetch=100):
|
|
87
|
+
certified = verified_legacy_version(row)
|
|
88
|
+
inspected += 1
|
|
89
|
+
verified += int(certified)
|
|
90
|
+
pending.append((row["state_id"], row["key"], row["revision"], certified))
|
|
91
|
+
if len(pending) == 100:
|
|
92
|
+
await conn.executemany(insert, pending)
|
|
93
|
+
pending.clear()
|
|
94
|
+
if pending:
|
|
95
|
+
await conn.executemany(insert, pending)
|
|
96
|
+
# Readiness, like quarantine, is operational metadata. Row values, revisions,
|
|
97
|
+
# fingerprints, pins and historical before-images remain unchanged. Old plans
|
|
98
|
+
# assuming a ready target fail their RowVersion comparison after this change.
|
|
99
|
+
result = await conn.execute(f"""UPDATE {backend._t("entries")} e SET status = 'unconverged', updated_at = clock_timestamp()
|
|
100
|
+
WHERE e.status = 'ready' AND NOT e.tombstone AND NOT EXISTS (
|
|
101
|
+
SELECT 1 FROM {backend._t("convergence_evidence")} c
|
|
102
|
+
WHERE (c.state_id, c.kind, c.key, c.revision) = (e.state_id, 'resource', e.address, e.revision) AND c.verified)""")
|
|
103
|
+
get_logger(__name__).info_with_fields("Qualified legacy graph convergence", inspected=inspected, verified=verified, reclassified=int(result.rsplit(" ", 1)[-1]))
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
"""Bounded stale-consumer writes inside the producer's fenced transaction."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import replace
|
|
6
|
+
from typing import TYPE_CHECKING, Any
|
|
7
|
+
|
|
8
|
+
from netherframe.core.backends.graph_inputs import STALE_INPUTS, stored_values_equal
|
|
9
|
+
from netherframe.core.backends.graph_state import RESOURCE, object_identity, private_digest
|
|
10
|
+
from netherframe.core.exceptions import StateConflictError
|
|
11
|
+
|
|
12
|
+
if TYPE_CHECKING:
|
|
13
|
+
import asyncpg
|
|
14
|
+
from netherframe.core.backends.graph_state import Ownership, RowVersion
|
|
15
|
+
from .graph import PostgreSQLGraphBackend
|
|
16
|
+
|
|
17
|
+
MAX_ROWS = 128
|
|
18
|
+
MAX_TARGET_BYTES = 64 * 1024
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _chunks(prepared):
|
|
22
|
+
chunk, size = [], 2
|
|
23
|
+
for item in prepared:
|
|
24
|
+
if chunk and (item[0] != chunk[0][0] or len(chunk) >= MAX_ROWS or size + item[3] + 1 > MAX_TARGET_BYTES):
|
|
25
|
+
yield chunk
|
|
26
|
+
chunk, size = [], 2
|
|
27
|
+
size += item[3] + bool(chunk)
|
|
28
|
+
chunk.append(item)
|
|
29
|
+
if chunk:
|
|
30
|
+
yield chunk
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
async def publish_stale_batch(backend: PostgreSQLGraphBackend, conn: asyncpg.Connection, owner: Ownership, candidates: list[tuple[str, str, Any]], sequence: int) -> dict[tuple[str, str], RowVersion] | None:
|
|
34
|
+
"""Publish status/history together, or retain the legacy writer unchanged.
|
|
35
|
+
|
|
36
|
+
The caller has the app frontier lock and already evaluated changed_inputs.
|
|
37
|
+
Chunking bounds target parameters, not transaction atomicity or history size.
|
|
38
|
+
No provider result or independently acknowledged publication is introduced.
|
|
39
|
+
"""
|
|
40
|
+
from .graph import _entry_document, _entry_of, _json, _load, _version_of
|
|
41
|
+
|
|
42
|
+
if not backend._planning_contexts:
|
|
43
|
+
return None
|
|
44
|
+
prepared = []
|
|
45
|
+
for kind, key, row in candidates:
|
|
46
|
+
if kind == RESOURCE:
|
|
47
|
+
# Older/noncanonical documents can require the ordinary writer's
|
|
48
|
+
# representation repair. Do not change that behavior incidentally.
|
|
49
|
+
entry = _entry_of(row["entry"], row["private"], row["status"])
|
|
50
|
+
columns = (row["stack_id"], row["type"], row["name"], row["provider"], row["object_identity"], row["private_digest"])
|
|
51
|
+
canonical = (entry.stack_id, entry.type, entry.id, entry.provider, object_identity(entry), private_digest(entry.private))
|
|
52
|
+
if columns != canonical or not stored_values_equal(_entry_document(entry), _load(row["entry"])) or not isinstance(_load(row["sensitive_paths"]), list):
|
|
53
|
+
return None
|
|
54
|
+
version = _version_of(row)
|
|
55
|
+
else:
|
|
56
|
+
value = _load(row["value"])
|
|
57
|
+
if bool(row["sensitive"]) != (bool(value.get("sensitive")) if isinstance(value, dict) else False):
|
|
58
|
+
return None
|
|
59
|
+
version = backend._output_version(row)
|
|
60
|
+
target = {"key": key, "revision": version.revision, "incarnation": version.incarnation, "tombstone": version.tombstone}
|
|
61
|
+
size = len(_json(target).encode("utf-8"))
|
|
62
|
+
if size + 2 > MAX_TARGET_BYTES:
|
|
63
|
+
return None
|
|
64
|
+
prepared.append((kind, target, version, size))
|
|
65
|
+
|
|
66
|
+
result = {}
|
|
67
|
+
for chunk in _chunks(prepared):
|
|
68
|
+
kind = chunk[0][0]
|
|
69
|
+
resource = kind == RESOURCE
|
|
70
|
+
table, key_column = ("entries", "address") if resource else ("outputs", "key")
|
|
71
|
+
targets = [item[1] for item in chunk]
|
|
72
|
+
keys = [target["key"] for target in targets]
|
|
73
|
+
rows = await conn.fetch(
|
|
74
|
+
f"SELECT {key_column} AS key, revision, {'incarnation' if resource else '0 AS incarnation'}, tombstone FROM {backend._t(table)} WHERE state_id = $1 AND {key_column} = ANY($2::text[]) ORDER BY {key_column} FOR UPDATE",
|
|
75
|
+
backend.state_id,
|
|
76
|
+
keys,
|
|
77
|
+
)
|
|
78
|
+
actual = {row["key"]: dict(row) for row in rows}
|
|
79
|
+
for target in targets:
|
|
80
|
+
if actual.get(target["key"]) != target:
|
|
81
|
+
raise StateConflictError(f"{target['key']} changed since its stale inputs were evaluated; not written")
|
|
82
|
+
rows = await conn.fetch(
|
|
83
|
+
f"""UPDATE {backend._t(table)} SET revision = revision + 1, status = 'stale_inputs',
|
|
84
|
+
planning_context = NULL, run_id = $3, sequence = $4, updated_at = clock_timestamp()
|
|
85
|
+
WHERE state_id = $1 AND {key_column} = ANY($2::text[])
|
|
86
|
+
RETURNING {key_column} AS key, revision, value_revision, membership_revision""",
|
|
87
|
+
backend.state_id,
|
|
88
|
+
keys,
|
|
89
|
+
owner.run_id,
|
|
90
|
+
sequence,
|
|
91
|
+
)
|
|
92
|
+
if len(rows) != len(targets):
|
|
93
|
+
raise StateConflictError("Stale consumer publication lost a locked row; not written")
|
|
94
|
+
previous = {item[1]["key"]: item[2] for item in chunk}
|
|
95
|
+
for row in rows:
|
|
96
|
+
result[kind, row["key"]] = replace(
|
|
97
|
+
previous[row["key"]], revision=int(row["revision"]), status=STALE_INPUTS, run_id=owner.run_id, planning_context=None, value_revision=int(row["value_revision"]), membership_revision=int(row["membership_revision"])
|
|
98
|
+
)
|
|
99
|
+
# The row remains in PostgreSQL, including opaque private data. Base64
|
|
100
|
+
# from encode() wraps lines; ResourceState's history encoding does not.
|
|
101
|
+
document = "e.entry || CASE WHEN octet_length(e.private) > 0 THEN jsonb_build_object('private', replace(encode(e.private, 'base64'), E'\\n', '')) ELSE '{}'::jsonb END" if resource else "e.value"
|
|
102
|
+
await conn.execute(
|
|
103
|
+
f"""INSERT INTO {backend._t("versions")} (state_id, kind, key, revision, sequence, run_id,
|
|
104
|
+
op_id, tombstone, row_data, sensitive_paths, intent_fp, inputs, applied_fp, status,
|
|
105
|
+
mutation_revision, value_revision, membership_revision, planning_context)
|
|
106
|
+
SELECT e.state_id, $3, e.{key_column}, e.revision, e.sequence, e.run_id, NULL,
|
|
107
|
+
e.tombstone, {document}, {"e.sensitive_paths" if resource else "'[]'::jsonb"},
|
|
108
|
+
e.intent_fp, e.inputs, e.applied_fp, e.status, {"e.mutation_revision" if resource else "0"},
|
|
109
|
+
e.value_revision, e.membership_revision, e.planning_context
|
|
110
|
+
FROM {backend._t(table)} e WHERE e.state_id = $1 AND e.{key_column} = ANY($2::text[])""",
|
|
111
|
+
backend.state_id,
|
|
112
|
+
keys,
|
|
113
|
+
kind,
|
|
114
|
+
)
|
|
115
|
+
return result
|