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,236 @@
|
|
|
1
|
+
"""Atomic, fair lease sets over graph ownership rows.
|
|
2
|
+
|
|
3
|
+
State mutations require whole-app X or an admitted immutable graph plan.
|
|
4
|
+
Registration and queueing may hold nothing; a granted set is immutable until
|
|
5
|
+
released in full.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from collections import defaultdict
|
|
11
|
+
from collections.abc import Mapping
|
|
12
|
+
from typing import TYPE_CHECKING, Any
|
|
13
|
+
import uuid
|
|
14
|
+
|
|
15
|
+
from netherframe.core.backends.graph_leases import X, LeaseKey, can_grant, decode_set, normalized
|
|
16
|
+
from netherframe.core.backends.graph_diagnostics import GraphConflictReport, LeaseBlocker, lease_report
|
|
17
|
+
from netherframe.core.backends.graph_state import Ownership, OwnershipLostError
|
|
18
|
+
from netherframe.core.exceptions import StateError, StateLockError
|
|
19
|
+
from netherframe.core.serialization import orjson_compat as json
|
|
20
|
+
|
|
21
|
+
if TYPE_CHECKING:
|
|
22
|
+
import asyncpg
|
|
23
|
+
|
|
24
|
+
from .graph import PostgreSQLGraphBackend
|
|
25
|
+
from netherframe.core.backends.graph_plan_basis import GraphPlanBasis
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class PostgreSQLLeaseQueue:
|
|
29
|
+
def __init__(self, backend: PostgreSQLGraphBackend) -> None:
|
|
30
|
+
self.backend = backend
|
|
31
|
+
|
|
32
|
+
async def fence(self, conn: asyncpg.Connection, ownership: Ownership) -> Any:
|
|
33
|
+
backend = self.backend
|
|
34
|
+
row = await conn.fetchrow(f"SELECT epoch, status, expires_at, lease_phase, lease_set, operation FROM {backend._t('runs')} WHERE run_id = $1 AND state_id = $2 FOR UPDATE", ownership.run_id, backend.state_id)
|
|
35
|
+
if row is None or row["epoch"] != ownership.epoch or row["status"] != "active" or not await conn.fetchval("SELECT $1::timestamptz > clock_timestamp()", row["expires_at"]):
|
|
36
|
+
raise OwnershipLostError(f"Run {ownership.run_id} cannot use the lease queue: its ownership expired or was taken over")
|
|
37
|
+
return row
|
|
38
|
+
|
|
39
|
+
async def open(self, info: dict[str, Any], ttl: float, operation: str) -> Ownership:
|
|
40
|
+
if ttl <= 0:
|
|
41
|
+
raise StateError("A run's lease TTL must be positive")
|
|
42
|
+
backend = self.backend
|
|
43
|
+
run_id = uuid.uuid4().hex
|
|
44
|
+
async with backend._tx() as conn:
|
|
45
|
+
epoch = await conn.fetchval(f"UPDATE {backend._t('apps')} SET epoch = epoch + 1 WHERE state_id = $1 RETURNING epoch", backend.state_id)
|
|
46
|
+
await conn.execute(
|
|
47
|
+
f"INSERT INTO {backend._t('runs')} (run_id, state_id, epoch, operation, actor, host, pid, status, expires_at, lease_phase) VALUES ($1, $2, $3, $4, $5, $6, $7, 'active', clock_timestamp() + make_interval(secs => $8), 'pending')",
|
|
48
|
+
run_id,
|
|
49
|
+
backend.state_id,
|
|
50
|
+
epoch,
|
|
51
|
+
operation,
|
|
52
|
+
str(info.get("user") or ""),
|
|
53
|
+
str(info.get("host") or ""),
|
|
54
|
+
info.get("pid"),
|
|
55
|
+
float(ttl),
|
|
56
|
+
)
|
|
57
|
+
return Ownership(run_id, int(epoch), ttl, operation)
|
|
58
|
+
|
|
59
|
+
async def expire(self) -> None:
|
|
60
|
+
"""Lock expired owners before the app row, matching every other graph transaction."""
|
|
61
|
+
backend = self.backend
|
|
62
|
+
async with backend._tx(readonly=True) as conn:
|
|
63
|
+
expired = await conn.fetch(f"SELECT run_id FROM {backend._t('runs')} WHERE state_id = $1 AND status = 'active' AND expires_at <= clock_timestamp()", backend.state_id)
|
|
64
|
+
for owner in expired:
|
|
65
|
+
async with backend._tx() as conn:
|
|
66
|
+
row = await conn.fetchrow(f"SELECT expires_at <= clock_timestamp() AS expired, status FROM {backend._t('runs')} WHERE run_id = $1 FOR UPDATE", owner["run_id"])
|
|
67
|
+
if row is not None and row["status"] == "active" and row["expired"]:
|
|
68
|
+
await conn.execute(f"SELECT 1 FROM {backend._t('apps')} WHERE state_id = $1 FOR UPDATE", backend.state_id)
|
|
69
|
+
await backend._quarantine(conn, owner["run_id"])
|
|
70
|
+
|
|
71
|
+
async def request(self, ownership: Ownership, request: Mapping[LeaseKey, str]) -> int:
|
|
72
|
+
wanted = normalized(request)
|
|
73
|
+
backend = self.backend
|
|
74
|
+
async with backend._owned_tx(ownership, "lease request", planning=True) as transaction:
|
|
75
|
+
conn, run = transaction.conn, transaction.run
|
|
76
|
+
await conn.execute(f"SELECT 1 FROM {backend._t('apps')} WHERE state_id = $1 FOR UPDATE", backend.state_id)
|
|
77
|
+
return await self._request_on(conn, run, ownership, wanted)
|
|
78
|
+
|
|
79
|
+
async def _request_on(self, conn: asyncpg.Connection, run: Any, ownership: Ownership, wanted: dict[str, str]) -> int:
|
|
80
|
+
"""The caller holds the ownership and app locks until the final refence."""
|
|
81
|
+
backend = self.backend
|
|
82
|
+
if run["operation"] == "recover":
|
|
83
|
+
raise StateError("Recovery inherits operation footprints and cannot request a new run grant")
|
|
84
|
+
previous = await conn.fetchrow(f"SELECT ticket, request, epoch FROM {backend._t('lease_queue')} WHERE state_id = $1 AND run_id = $2", backend.state_id, ownership.run_id)
|
|
85
|
+
if previous is not None:
|
|
86
|
+
if previous["epoch"] != ownership.epoch:
|
|
87
|
+
raise OwnershipLostError("The queued lease request belongs to a different ownership epoch")
|
|
88
|
+
stored = json.loads(previous["request"]) if isinstance(previous["request"], str) else previous["request"]
|
|
89
|
+
if decode_set(stored) != wanted:
|
|
90
|
+
raise StateLockError("A queued lease set is immutable; cancel it before requesting another")
|
|
91
|
+
return int(previous["ticket"])
|
|
92
|
+
if run["lease_phase"] == "granted":
|
|
93
|
+
raise StateLockError("A granted lease set cannot grow; release it before requesting another")
|
|
94
|
+
if await conn.fetchval(f"SELECT 1 FROM {backend._t('run_mutations')} WHERE run_id = $1", ownership.run_id):
|
|
95
|
+
raise StateLockError("A run cannot request another lease set after its first mutation; end the run before replanning")
|
|
96
|
+
return int(await conn.fetchval(f"INSERT INTO {backend._t('lease_queue')} (state_id, run_id, epoch, request) VALUES ($1, $2, $3, $4) RETURNING ticket", backend.state_id, ownership.run_id, ownership.epoch, json.dumps(wanted)))
|
|
97
|
+
|
|
98
|
+
async def request_and_grant(self, ownership: Ownership, request: Mapping[LeaseKey, str]) -> bool:
|
|
99
|
+
wanted = normalized(request)
|
|
100
|
+
# Expiry takes other owners' locks before the app lock, never inside
|
|
101
|
+
# this owned transaction. Unresolved operations keep their footprints.
|
|
102
|
+
await self.expire()
|
|
103
|
+
backend = self.backend
|
|
104
|
+
async with backend._owned_tx(ownership, "request and grant leases", planning=True) as transaction:
|
|
105
|
+
conn, run = transaction.conn, transaction.run
|
|
106
|
+
await conn.execute(f"SELECT 1 FROM {backend._t('apps')} WHERE state_id = $1 FOR UPDATE", backend.state_id)
|
|
107
|
+
ticket = await self._request_on(conn, run, ownership, wanted)
|
|
108
|
+
# The ticket and immutable request were read/inserted under these
|
|
109
|
+
# same locks. Reuse them without another round trip or fence scope.
|
|
110
|
+
return await self._grant_on(conn, ownership, ticket, wanted)
|
|
111
|
+
|
|
112
|
+
async def grant(self, ownership: Ownership) -> bool:
|
|
113
|
+
await self.expire()
|
|
114
|
+
backend = self.backend
|
|
115
|
+
async with backend._owned_tx(ownership, "grant leases", planning=True) as transaction:
|
|
116
|
+
conn, run = transaction.conn, transaction.run
|
|
117
|
+
await conn.execute(f"SELECT 1 FROM {backend._t('apps')} WHERE state_id = $1 FOR UPDATE", backend.state_id)
|
|
118
|
+
# The ownership scope rechecks time and the installed grant at
|
|
119
|
+
# its tail, after all predicate reads and lease-row inserts.
|
|
120
|
+
if run["lease_phase"] == "granted":
|
|
121
|
+
expected = decode_set(json.loads(run["lease_set"]) if isinstance(run["lease_set"], str) else run["lease_set"])
|
|
122
|
+
rows = await conn.fetch(f"SELECT key, mode FROM {backend._t('leases')} WHERE state_id = $1 AND holder = $2", backend.state_id, ownership.run_id)
|
|
123
|
+
if {row["key"]: row["mode"] for row in rows} != expected:
|
|
124
|
+
raise OwnershipLostError("The run lost part of its granted lease set")
|
|
125
|
+
return True
|
|
126
|
+
row = await conn.fetchrow(f"SELECT ticket, request FROM {backend._t('lease_queue')} WHERE state_id = $1 AND run_id = $2 AND epoch = $3", backend.state_id, ownership.run_id, ownership.epoch)
|
|
127
|
+
if row is None:
|
|
128
|
+
raise StateLockError("The run has no queued lease request")
|
|
129
|
+
wanted = decode_set(json.loads(row["request"]) if isinstance(row["request"], str) else row["request"])
|
|
130
|
+
return await self._grant_on(conn, ownership, int(row["ticket"]), wanted)
|
|
131
|
+
|
|
132
|
+
async def _grant_on(self, conn: asyncpg.Connection, ownership: Ownership, ticket: int, wanted: dict[str, str]) -> bool:
|
|
133
|
+
"""Check every holder/waiter and install the set inside the caller's fence."""
|
|
134
|
+
backend = self.backend
|
|
135
|
+
rows = await conn.fetch(f"SELECT key, mode, holder FROM {backend._t('leases')} WHERE state_id = $1", backend.state_id)
|
|
136
|
+
holders: dict[str, dict[str, str]] = defaultdict(dict)
|
|
137
|
+
for held in rows:
|
|
138
|
+
if held["holder"] != ownership.run_id:
|
|
139
|
+
holders[held["holder"]][held["key"]] = held["mode"]
|
|
140
|
+
older = await conn.fetch(f"SELECT request FROM {backend._t('lease_queue')} WHERE state_id = $1 AND ticket < $2 ORDER BY ticket", backend.state_id, ticket)
|
|
141
|
+
waiting = [decode_set(json.loads(item["request"]) if isinstance(item["request"], str) else item["request"]) for item in older]
|
|
142
|
+
from .graph_schema import OPERATION_FOOTPRINT_SQL
|
|
143
|
+
|
|
144
|
+
operations = await conn.fetch(
|
|
145
|
+
f"SELECT {OPERATION_FOOTPRINT_SQL} AS footprint FROM {backend._t('operations')} WHERE state_id = $1 AND stage NOT IN ('committed', 'aborted')",
|
|
146
|
+
backend.state_id,
|
|
147
|
+
)
|
|
148
|
+
retained = [decode_set(json.loads(item["footprint"]) if isinstance(item["footprint"], str) else item["footprint"]) for item in operations]
|
|
149
|
+
if not can_grant(wanted, [*holders.values(), *retained], waiting):
|
|
150
|
+
return False
|
|
151
|
+
await conn.executemany(f"INSERT INTO {backend._t('leases')} (state_id, key, holder, mode, ticket) VALUES ($1, $2, $3, $4, $5)", [(backend.state_id, key, ownership.run_id, mode, ticket) for key, mode in wanted.items()])
|
|
152
|
+
await conn.execute(f"UPDATE {backend._t('runs')} SET lease_phase = 'granted', lease_set = $2 WHERE run_id = $1", ownership.run_id, json.dumps(wanted))
|
|
153
|
+
await conn.execute(f"DELETE FROM {backend._t('lease_queue')} WHERE run_id = $1", ownership.run_id)
|
|
154
|
+
return True
|
|
155
|
+
|
|
156
|
+
async def release(self, ownership: Ownership) -> None:
|
|
157
|
+
backend = self.backend
|
|
158
|
+
async with backend._owned_tx(ownership, "release leases", planning=True) as transaction:
|
|
159
|
+
conn = transaction.conn
|
|
160
|
+
await conn.execute(f"SELECT 1 FROM {backend._t('apps')} WHERE state_id = $1 FOR UPDATE", backend.state_id)
|
|
161
|
+
pending = await conn.fetchval(f"SELECT op_id FROM {backend._t('operations')} WHERE (run_id = $1 OR recovered_by = $1) AND stage NOT IN ('committed', 'aborted') LIMIT 1", ownership.run_id)
|
|
162
|
+
if pending is not None:
|
|
163
|
+
raise StateLockError(f"Operation {pending} still holds its footprint; resolve it before releasing the lease set")
|
|
164
|
+
# This statement runs after fence acquired the ownership lock. A
|
|
165
|
+
# mutation that held SHARE before us has now committed its marker;
|
|
166
|
+
# reading it in fence's earlier statement snapshot would miss it.
|
|
167
|
+
if await conn.fetchval(f"SELECT 1 FROM {backend._t('run_mutations')} WHERE run_id = $1", ownership.run_id):
|
|
168
|
+
raise StateLockError("A run cannot release its lease set after its first mutation; end the run before replanning")
|
|
169
|
+
await conn.execute(f"DELETE FROM {backend._t('leases')} WHERE state_id = $1 AND holder = $2", backend.state_id, ownership.run_id)
|
|
170
|
+
await conn.execute(f"DELETE FROM {backend._t('lease_queue')} WHERE run_id = $1", ownership.run_id)
|
|
171
|
+
await conn.execute(f"UPDATE {backend._t('runs')} SET lease_phase = 'pending', lease_set = NULL, admitted_plan = NULL WHERE run_id = $1", ownership.run_id)
|
|
172
|
+
|
|
173
|
+
async def held(self, ownership: Ownership) -> dict[str, str]:
|
|
174
|
+
backend = self.backend
|
|
175
|
+
async with backend._tx(readonly=True) as conn:
|
|
176
|
+
rows = await conn.fetch(f"SELECT key, mode FROM {backend._t('leases')} WHERE state_id = $1 AND holder = $2", backend.state_id, ownership.run_id)
|
|
177
|
+
return {row["key"]: row["mode"] for row in rows}
|
|
178
|
+
|
|
179
|
+
async def explain(self, ownership: Ownership, basis: GraphPlanBasis | None) -> GraphConflictReport:
|
|
180
|
+
"""One read-only snapshot; no fencing locks, expiration or ticket edits."""
|
|
181
|
+
from .graph_schema import OPERATION_FOOTPRINT_SQL
|
|
182
|
+
|
|
183
|
+
backend = self.backend
|
|
184
|
+
|
|
185
|
+
def leases(value: Any) -> dict[str, str]:
|
|
186
|
+
return decode_set(json.loads(value) if isinstance(value, str) else value)
|
|
187
|
+
|
|
188
|
+
async with backend._tx(readonly=True, isolation="repeatable_read") as conn:
|
|
189
|
+
row = await conn.fetchrow(
|
|
190
|
+
f"""SELECT q.ticket, q.request, a.frontier FROM {backend._t("lease_queue")} q
|
|
191
|
+
JOIN {backend._t("runs")} r ON r.run_id = q.run_id AND r.state_id = q.state_id
|
|
192
|
+
JOIN {backend._t("apps")} a ON a.state_id = q.state_id
|
|
193
|
+
WHERE q.state_id = $1 AND q.run_id = $2 AND q.epoch = $3 AND r.epoch = $3
|
|
194
|
+
AND r.status = 'active' AND r.expires_at > transaction_timestamp()""",
|
|
195
|
+
backend.state_id,
|
|
196
|
+
ownership.run_id,
|
|
197
|
+
ownership.epoch,
|
|
198
|
+
)
|
|
199
|
+
if row is None:
|
|
200
|
+
raise StateLockError("The run has no live queued lease request to explain")
|
|
201
|
+
held = await conn.fetch(
|
|
202
|
+
f"""SELECT l.holder, l.key, l.mode FROM {backend._t("leases")} l
|
|
203
|
+
JOIN {backend._t("runs")} r ON r.run_id = l.holder AND r.state_id = l.state_id
|
|
204
|
+
WHERE l.state_id = $1 AND l.holder <> $2 AND r.status = 'active' AND r.expires_at > transaction_timestamp()""",
|
|
205
|
+
backend.state_id,
|
|
206
|
+
ownership.run_id,
|
|
207
|
+
)
|
|
208
|
+
holders: dict[str, dict[str, str]] = defaultdict(dict)
|
|
209
|
+
for item in held:
|
|
210
|
+
holders[item["holder"]][item["key"]] = item["mode"]
|
|
211
|
+
older = await conn.fetch(
|
|
212
|
+
f"""SELECT q.run_id, q.request FROM {backend._t("lease_queue")} q
|
|
213
|
+
JOIN {backend._t("runs")} r ON r.run_id = q.run_id AND r.state_id = q.state_id
|
|
214
|
+
WHERE q.state_id = $1 AND q.ticket < $2 AND r.status = 'active' AND r.expires_at > transaction_timestamp()""",
|
|
215
|
+
backend.state_id,
|
|
216
|
+
row["ticket"],
|
|
217
|
+
)
|
|
218
|
+
operations = await conn.fetch(
|
|
219
|
+
f"SELECT op_id, run_id, recovered_by, {OPERATION_FOOTPRINT_SQL} AS footprint FROM {backend._t('operations')} WHERE state_id = $1 AND stage NOT IN ('committed', 'aborted')",
|
|
220
|
+
backend.state_id,
|
|
221
|
+
)
|
|
222
|
+
blockers = [LeaseBlocker(key, value) for key, value in holders.items()]
|
|
223
|
+
blockers.extend(LeaseBlocker(item["run_id"], leases(item["request"]), "older_waiter") for item in older)
|
|
224
|
+
blockers.extend(LeaseBlocker(item["recovered_by"] or item["run_id"], leases(item["footprint"]), "retained_operation", item["op_id"]) for item in operations)
|
|
225
|
+
return lease_report(leases(row["request"]), blockers, run_id=ownership.run_id, ticket=int(row["ticket"]), frontier=int(row["frontier"]), basis=basis)
|
|
226
|
+
|
|
227
|
+
async def acquire(self, info: dict[str, Any], ttl: float, operation: str) -> Ownership | None:
|
|
228
|
+
ownership = await self.open(info, ttl, operation)
|
|
229
|
+
granted = False
|
|
230
|
+
try:
|
|
231
|
+
await self.request(ownership, {LeaseKey(): X})
|
|
232
|
+
granted = await self.grant(ownership)
|
|
233
|
+
return ownership if granted else None
|
|
234
|
+
finally:
|
|
235
|
+
if not granted:
|
|
236
|
+
await self.backend._release(ownership)
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
"""Complete planning metadata and bounded selections in the caller's snapshot."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections import defaultdict
|
|
6
|
+
from typing import TYPE_CHECKING, Any, Literal
|
|
7
|
+
|
|
8
|
+
from netherframe.core.serialization import orjson_compat as json
|
|
9
|
+
|
|
10
|
+
if TYPE_CHECKING:
|
|
11
|
+
import asyncpg
|
|
12
|
+
from netherframe.core.backends.graph_baseline import GraphBaseline
|
|
13
|
+
|
|
14
|
+
from .graph import PostgreSQLGraphBackend
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
async def read_payloads(backend: PostgreSQLGraphBackend, conn: asyncpg.Connection, table: Literal["entries", "outputs"], keys: list[str], population: int) -> list[asyncpg.Record]:
|
|
18
|
+
"""Read unique, existing keys using the complete metadata population.
|
|
19
|
+
|
|
20
|
+
Generic ANY/VALUES plans can repeatedly scan requested keys for every row.
|
|
21
|
+
For bounded dense selections, IS TRUE retains a hashed membership subplan
|
|
22
|
+
instead of flattening it into a nested-loop semi-join. Sparse selections use
|
|
23
|
+
indexed point lookups in one request; the primary key makes LIMIT 1 exact.
|
|
24
|
+
The 1/16 density threshold is a read-cost heuristic, never a selection rule.
|
|
25
|
+
Bound the extra hash input; larger selections retain the general array path.
|
|
26
|
+
"""
|
|
27
|
+
if not keys:
|
|
28
|
+
return []
|
|
29
|
+
column = {"entries": "address", "outputs": "key"}[table]
|
|
30
|
+
if len(keys) == 1:
|
|
31
|
+
return await conn.fetch(f"SELECT * FROM {backend._t(table)} WHERE state_id = $1 AND {column} = $2::text", backend.state_id, keys[0])
|
|
32
|
+
if len(keys) <= 1024 and sum(len(key.encode("utf-8")) for key in keys) <= 262144:
|
|
33
|
+
if len(keys) * 16 >= population:
|
|
34
|
+
return await conn.fetch(f"SELECT * FROM {backend._t(table)} WHERE state_id = $1 AND ({column} IN (SELECT unnest($2::text[]))) IS TRUE", backend.state_id, keys)
|
|
35
|
+
return await conn.fetch(f"SELECT selected.* FROM unnest($2::text[]) AS wanted(key) CROSS JOIN LATERAL (SELECT * FROM {backend._t(table)} WHERE state_id = $1 AND {column} = wanted.key LIMIT 1) selected", backend.state_id, keys)
|
|
36
|
+
return await conn.fetch(f"SELECT * FROM {backend._t(table)} WHERE state_id = $1 AND {column} = ANY($2::text[])", backend.state_id, keys)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
async def read_metadata(backend: PostgreSQLGraphBackend, conn: asyncpg.Connection, baseline: GraphBaseline | None) -> dict[str, list[dict[str, Any]]]:
|
|
40
|
+
"""Batch heterogeneous metadata as tagged rows, not a cross-product or aggregate.
|
|
41
|
+
|
|
42
|
+
Selected payloads still use their native columns (including private bytea)
|
|
43
|
+
in the caller's repeatable-read transaction. Only the metadata projections
|
|
44
|
+
below enter JSON envelopes. Every call rereads the complete capture; there
|
|
45
|
+
is no frontier-only shortcut or cache across validation points.
|
|
46
|
+
"""
|
|
47
|
+
table = backend._t
|
|
48
|
+
context = "planning_context" if backend._planning_contexts else "NULL AS planning_context"
|
|
49
|
+
columns = f"revision, status, tombstone, intent_fp, inputs, applied_fp, run_id, {context}"
|
|
50
|
+
# Ordering-only dependencies are independent of observed inputs. Retain
|
|
51
|
+
# their exact projection without unpacking unrelated provider attributes.
|
|
52
|
+
dependencies = "dependency_targets" if backend._planning_dependencies else "entry -> 'dependencies'"
|
|
53
|
+
queries = {
|
|
54
|
+
"app": f"SELECT lineage, frontier, migrated_to, transfer_id, metadata ? 'stack_outputs' AS legacy_outputs FROM {table('apps')} WHERE state_id = $1",
|
|
55
|
+
"baseline": f"SELECT lineage, sequence, intent_digest FROM {table('baselines')} WHERE state_id = $1 AND pin_id = $2",
|
|
56
|
+
"origin": f"SELECT DISTINCT ON (kind, key) kind, key, revision, sequence, intent_fp, tombstone, run_id FROM {table('versions')} WHERE state_id = $1 AND sequence <= $3 ORDER BY kind, key, sequence DESC, revision DESC",
|
|
57
|
+
"resource": f"SELECT address AS key, incarnation, {columns}, {dependencies} AS dependency_targets FROM {table('entries')} WHERE state_id = $1",
|
|
58
|
+
"output": f"SELECT key, 0 AS incarnation, {columns}, NULL AS dependency_targets FROM {table('outputs')} WHERE state_id = $1",
|
|
59
|
+
"edges": f"SELECT target_kind, target, dependent_kind, dependent FROM {table('edges')} WHERE state_id = $1",
|
|
60
|
+
"generations": f"SELECT target_kind, target, generation FROM {table('edge_generations')} WHERE state_id = $1",
|
|
61
|
+
"operations": backend._operations_sql("o.stage NOT IN ('committed', 'aborted')"),
|
|
62
|
+
"observations": f"SELECT address FROM {table('observations')} WHERE state_id = $1",
|
|
63
|
+
}
|
|
64
|
+
query = "\nUNION ALL\n".join(f"SELECT '{kind}' AS section, to_jsonb(item) AS data FROM ({sql}) item" for kind, sql in queries.items())
|
|
65
|
+
rows = await conn.fetch(query, backend.state_id, baseline.pin_id if baseline else None, baseline.sequence if baseline else None)
|
|
66
|
+
result = defaultdict(list)
|
|
67
|
+
for row in rows:
|
|
68
|
+
result[row["section"]].append(json.loads(row["data"]))
|
|
69
|
+
return result
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
async def read_scope_metadata(backend: PostgreSQLGraphBackend, conn: asyncpg.Connection, *, include_metadata: bool) -> dict[str, list[dict[str, Any]]]:
|
|
73
|
+
"""Complete semantic counters/topology for private broad-proof validation.
|
|
74
|
+
|
|
75
|
+
This is not an application snapshot: explicit row expectations and auxiliary
|
|
76
|
+
observations still need their payloads. Legacy value counters and overlapping
|
|
77
|
+
observation addresses are detected by the caller before it uses these rows.
|
|
78
|
+
The caller retains the app-row lock throughout all proof reads.
|
|
79
|
+
"""
|
|
80
|
+
table = backend._t
|
|
81
|
+
dependencies = "dependency_targets" if backend._planning_dependencies else "entry -> 'dependencies'"
|
|
82
|
+
metadata = "metadata" if include_metadata else "'{}'::jsonb AS metadata"
|
|
83
|
+
columns = "revision, status, tombstone, inputs, value_revision, membership_revision"
|
|
84
|
+
queries = {
|
|
85
|
+
"app": f"SELECT lineage, frontier, migrated_to, transfer_id, {metadata} FROM {table('apps')} WHERE state_id = $1",
|
|
86
|
+
"resource": f"SELECT address AS key, incarnation, {columns}, {dependencies} AS dependency_targets FROM {table('entries')} WHERE state_id = $1",
|
|
87
|
+
"output": f"SELECT key, 0 AS incarnation, {columns}, NULL AS dependency_targets FROM {table('outputs')} WHERE state_id = $1",
|
|
88
|
+
"edges": f"SELECT target_kind, target, dependent_kind, dependent FROM {table('edges')} WHERE state_id = $1",
|
|
89
|
+
"generations": f"SELECT target_kind, target, generation FROM {table('edge_generations')} WHERE state_id = $1",
|
|
90
|
+
"operations": backend._operations_sql("o.stage NOT IN ('committed', 'aborted')"),
|
|
91
|
+
"observations": f"SELECT address, entry #>> '{{metadata,terraform_mode}}' = 'data' AS is_data_source FROM {table('observations')} WHERE state_id = $1",
|
|
92
|
+
}
|
|
93
|
+
query = "\nUNION ALL\n".join(f"SELECT '{kind}' AS section, to_jsonb(item) AS data FROM ({sql}) item" for kind, sql in queries.items())
|
|
94
|
+
result = defaultdict(list)
|
|
95
|
+
for row in await conn.fetch(query, backend.state_id):
|
|
96
|
+
result[row["section"]].append(json.loads(row["data"]))
|
|
97
|
+
return result
|