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.
Files changed (40) hide show
  1. netherframe/backends/postgresql/__init__.py +59 -0
  2. netherframe/backends/postgresql/connection_settings.py +40 -0
  3. netherframe/backends/postgresql/graph.py +2511 -0
  4. netherframe/backends/postgresql/graph_authorization.py +102 -0
  5. netherframe/backends/postgresql/graph_checkpoints.py +239 -0
  6. netherframe/backends/postgresql/graph_completion.py +66 -0
  7. netherframe/backends/postgresql/graph_convergence.py +103 -0
  8. netherframe/backends/postgresql/graph_invalidation.py +115 -0
  9. netherframe/backends/postgresql/graph_lease_queue.py +236 -0
  10. netherframe/backends/postgresql/graph_planning_reads.py +97 -0
  11. netherframe/backends/postgresql/graph_publication.py +373 -0
  12. netherframe/backends/postgresql/graph_retention.py +141 -0
  13. netherframe/backends/postgresql/graph_reverse_edges.py +143 -0
  14. netherframe/backends/postgresql/graph_schema.py +2038 -0
  15. netherframe/backends/postgresql/graph_transfers.py +128 -0
  16. netherframe/backends/postgresql/postgresql.py +1207 -0
  17. netherframe/backends/postgresql/postgresql_backend_bootstrap.py +139 -0
  18. netherframe/backends/postgresql/py.typed +0 -0
  19. netherframe_backends_postgresql-0.2.1.dist-info/METADATA +138 -0
  20. netherframe_backends_postgresql-0.2.1.dist-info/RECORD +40 -0
  21. netherframe_backends_postgresql-0.2.1.dist-info/WHEEL +4 -0
  22. netherframe_backends_postgresql-0.2.1.dist-info/licenses/LICENSE +21 -0
  23. nf/backends/postgresql/__init__.py +4 -0
  24. nf/backends/postgresql/connection_settings.py +4 -0
  25. nf/backends/postgresql/graph.py +4 -0
  26. nf/backends/postgresql/graph_authorization.py +4 -0
  27. nf/backends/postgresql/graph_checkpoints.py +4 -0
  28. nf/backends/postgresql/graph_completion.py +4 -0
  29. nf/backends/postgresql/graph_convergence.py +4 -0
  30. nf/backends/postgresql/graph_invalidation.py +4 -0
  31. nf/backends/postgresql/graph_lease_queue.py +4 -0
  32. nf/backends/postgresql/graph_planning_reads.py +4 -0
  33. nf/backends/postgresql/graph_publication.py +4 -0
  34. nf/backends/postgresql/graph_retention.py +4 -0
  35. nf/backends/postgresql/graph_reverse_edges.py +4 -0
  36. nf/backends/postgresql/graph_schema.py +4 -0
  37. nf/backends/postgresql/graph_transfers.py +4 -0
  38. nf/backends/postgresql/postgresql.py +4 -0
  39. nf/backends/postgresql/postgresql_backend_bootstrap.py +4 -0
  40. nf/backends/postgresql/py.typed +0 -0
@@ -0,0 +1,373 @@
1
+ """Bounded publication inside the existing fenced commit transaction.
2
+
3
+ Established canonical objects and unchanged legacy rows gaining canonical evidence
4
+ enter this state-only path. Successful returned creates have a separate fresh-row path.
5
+ Recovery, moves and mixed publications retain the general writer. Entry triggers,
6
+ history and the enclosing commit's invalidation/fences remain authoritative;
7
+ a conflict rejects the complete transaction.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from collections import defaultdict
13
+ from dataclasses import replace
14
+ from typing import TYPE_CHECKING
15
+
16
+ from netherframe.core.backends.graph_inputs import effective_status, encode_inputs, stored_values_equal, value_fingerprint
17
+ from netherframe.core.backends.graph_identity import locator_of
18
+ from netherframe.core.backends.graph_object_guard import ObjectOperationGuard, object_problems, object_request
19
+ from netherframe.core.backends.graph_planning_context import bind_planning_context
20
+ from netherframe.core.backends.graph_state import CREATE, RETURNED, RESOURCE, UNCHECKED, PreCallValidationError, RowVersion, object_identity, private_digest
21
+ from netherframe.core.exceptions import StateConflictError
22
+
23
+ if TYPE_CHECKING:
24
+ import asyncpg
25
+ from collections.abc import Mapping, Sequence
26
+ from netherframe.core.backends.graph_state import OperationRecord, Ownership, RowWrite
27
+ from netherframe.core.backends.state_models import ResourceState
28
+ from .graph import PostgreSQLGraphBackend
29
+
30
+ # SQL payload bounds, not permission to split an atomic caller transaction.
31
+ MAX_ROWS = 256
32
+ MAX_BYTES = 1024 * 1024
33
+
34
+
35
+ def legacy_normalization(write: RowWrite, previous: ResourceState | None) -> bool:
36
+ """Adding ownership evidence may bypass unknown peers only without a mutation."""
37
+ return (
38
+ write.op_id is None
39
+ and previous is not None
40
+ and locator_of(previous.metadata, previous.type) is None
41
+ and stored_values_equal(previous.attributes, write.entry.attributes)
42
+ and stored_values_equal(previous.identity, write.entry.identity)
43
+ and previous.provider == write.entry.provider
44
+ and previous.private == write.entry.private
45
+ )
46
+
47
+
48
+ def _payload_chunks(items: list[dict]) -> list[str] | None:
49
+ """Encode bounded SQL arrays without dividing the caller's publication.
50
+
51
+ Check all items before any write: one oversized row retains the general
52
+ writer for the entire publication. Reuse encoded rows instead of serializing
53
+ the full payload twice. MAX_ROWS remains the whole-batch eligibility bound.
54
+ """
55
+ from .graph import _json
56
+
57
+ chunks, pending = [], []
58
+ size = 2 # JSON array brackets.
59
+ for item in items:
60
+ encoded = _json(item)
61
+ length = len(encoded.encode("utf-8"))
62
+ if length + 2 > MAX_BYTES:
63
+ return None
64
+ if size + length + bool(pending) > MAX_BYTES:
65
+ chunks.append("[" + ",".join(pending) + "]")
66
+ pending, size = [], 2
67
+ size += length + bool(pending)
68
+ pending.append(encoded)
69
+ if pending:
70
+ chunks.append("[" + ",".join(pending) + "]")
71
+ return chunks
72
+
73
+
74
+ async def publish_creation_batch(
75
+ backend: PostgreSQLGraphBackend,
76
+ conn: asyncpg.Connection,
77
+ ownership: Ownership,
78
+ writes: list[RowWrite],
79
+ sequence: int,
80
+ records: Mapping[str, asyncpg.Record],
81
+ operations: Sequence[OperationRecord],
82
+ ) -> dict[tuple[str, str], RowVersion] | None:
83
+ """Publish bounded fresh creates; None leaves the general writer in charge.
84
+
85
+ The caller holds all operation rows and the app frontier, and has checked
86
+ admission, resolution, request/write binding and the combined footprint.
87
+ Raw results are already durable. Validate every row and peer before inserting
88
+ anything; keep history, trigger counters and final fencing in this transaction.
89
+ Tombstones, singletons and unsupported/mixed records use the general writer.
90
+ """
91
+ from .graph import _entry_document, _entry_of
92
+
93
+ if not backend._planning_contexts or not 2 <= len(writes) <= MAX_ROWS or len({write.key for write in writes}) != len(writes):
94
+ return None
95
+ if len(records) != len(writes) or any(
96
+ write.kind != RESOURCE
97
+ or write.removal
98
+ or not write.new_incarnation
99
+ or write.expected is not None
100
+ or write.op_id is None
101
+ or write.op_id not in records
102
+ or records[write.op_id]["action"] != CREATE
103
+ or records[write.op_id]["stage"] != RETURNED
104
+ or records[write.op_id]["error"] is not None
105
+ for write in writes
106
+ ):
107
+ return None
108
+ prepared, versions, requests = [], {}, {}
109
+ identities, types = set(), set()
110
+ for write in writes:
111
+ entry = write.entry
112
+ identity = object_identity(entry)
113
+ if entry.is_data_source or entry.resource_id != write.key or not identity or not identity.startswith("nf-object-v1:"):
114
+ return None
115
+ document = entry.to_dict()
116
+ request = {"template": document}
117
+ claims = object_request(request, "state")
118
+ if not claims.bound_sources or claims.sources != claims.bound_sources:
119
+ return None
120
+ requests[write.key] = request, claims
121
+ identities.update(claims.identities)
122
+ types.update(kind for _source, kind in claims.sources)
123
+ intent = None if write.intent_fp is UNCHECKED else write.intent_fp
124
+ inputs = None if write.inputs is UNCHECKED else write.inputs
125
+ applied = None if write.applied_fp is UNCHECKED else write.applied_fp
126
+ status = effective_status(write.status, None, tainted=entry.tainted, evaluated=write.inputs is not UNCHECKED and write.inputs is not None)
127
+ context = bind_planning_context(write.planning_context, 1, intent)
128
+ digest = private_digest(entry.private)
129
+ versions[RESOURCE, write.key] = RowVersion(
130
+ 1,
131
+ 1,
132
+ status,
133
+ entry.provider,
134
+ digest,
135
+ identity,
136
+ intent_fp=intent,
137
+ inputs=inputs,
138
+ applied_fp=applied,
139
+ value_fp=value_fingerprint([entry.attributes, entry.provider, digest]),
140
+ mutation_revision=1,
141
+ planning_context=context,
142
+ run_id=ownership.run_id,
143
+ )
144
+ item = {
145
+ "address": write.key,
146
+ "op_id": write.op_id,
147
+ "status": status,
148
+ "stack_id": entry.stack_id,
149
+ "type": entry.type,
150
+ "name": entry.id,
151
+ "provider": entry.provider,
152
+ "entry": _entry_document(entry),
153
+ "private": document.get("private"),
154
+ "private_digest": digest,
155
+ "object_identity": identity,
156
+ "row_data": document,
157
+ "sensitive_paths": write.sensitive_paths,
158
+ "intent_fp": intent,
159
+ "inputs": encode_inputs(inputs) if inputs is not None else None,
160
+ "applied_fp": applied,
161
+ "planning_context": context.to_dict() if context is not None else None,
162
+ }
163
+ prepared.append(item)
164
+
165
+ payloads = _payload_chunks(prepared)
166
+ if payloads is None:
167
+ return None
168
+
169
+ old = await conn.fetch(f"SELECT address FROM {backend._t('entries')} WHERE state_id = $1 AND address = ANY($2::text[]) ORDER BY address FOR UPDATE", backend.state_id, list(requests))
170
+ if old:
171
+ raise StateConflictError(f"{old[0]['address']} changed since this run read it (expected absent); not written")
172
+ candidates = await conn.fetch(
173
+ f"""SELECT address, type, object_identity, entry, private, status FROM {backend._t("entries")}
174
+ WHERE state_id = $1 AND NOT tombstone AND
175
+ (address = ANY($2::text[]) OR object_identity = ANY($3::text[]) OR
176
+ (type = ANY($4::text[]) AND (object_identity IS NULL OR object_identity NOT LIKE 'nf-object-v1:%')))""",
177
+ backend.state_id,
178
+ list(requests),
179
+ sorted(identities),
180
+ sorted(types),
181
+ )
182
+ by_identity, unknown = defaultdict(list), defaultdict(list)
183
+ for row in candidates:
184
+ entry = _entry_of(row["entry"], row["private"], row["status"])
185
+ if row["object_identity"] and row["object_identity"].startswith("nf-object-v1:"):
186
+ by_identity[row["object_identity"]].append(entry)
187
+ else:
188
+ unknown[row["type"]].append(entry)
189
+ # The ordinary writer sees earlier inserted rows. The set writer must also
190
+ # see every proposed peer, including identities learned from returned calls.
191
+ for write in writes:
192
+ by_identity[versions[RESOURCE, write.key].object_identity].append(write.entry)
193
+ object_guard = ObjectOperationGuard(operations)
194
+ for write in writes:
195
+ request, claims = requests[write.key]
196
+ peers = [entry for identity in claims.identities for entry in by_identity[identity]]
197
+ peers.extend(entry for kind in {kind for _source, kind in claims.sources} for entry in unknown[kind])
198
+ if problems := object_problems(write.key, request, "state", peers, object_guard, exclude_op=write.op_id, run_id=ownership.run_id, claims=claims):
199
+ raise PreCallValidationError("Cloud ownership validation failed:\n" + "\n".join(problems))
200
+
201
+ for payload in payloads:
202
+ rows = await conn.fetch(
203
+ f"""INSERT INTO {backend._t("entries")} (state_id, address, revision, incarnation, status, tombstone,
204
+ stack_id, type, name, provider, entry, private, private_digest, object_identity, sensitive_paths,
205
+ run_id, sequence, intent_fp, inputs, applied_fp, mutation_revision, planning_context)
206
+ SELECT $1, w.address, 1, 1, w.status, false, w.stack_id, w.type, w.name, w.provider,
207
+ w.entry, decode(w.private, 'base64'), w.private_digest, w.object_identity, w.sensitive_paths,
208
+ $3, $4, w.intent_fp, w.inputs, w.applied_fp, 1, w.planning_context
209
+ FROM jsonb_to_recordset($2::jsonb) AS w(address text, status text, stack_id text, type text,
210
+ name text, provider text, entry jsonb, private text, private_digest text, object_identity text,
211
+ sensitive_paths jsonb, intent_fp text, inputs jsonb, applied_fp text, planning_context jsonb)
212
+ RETURNING address, value_revision, membership_revision""",
213
+ backend.state_id,
214
+ payload,
215
+ ownership.run_id,
216
+ sequence,
217
+ )
218
+ for row in rows:
219
+ key = RESOURCE, row["address"]
220
+ versions[key] = replace(versions[key], value_revision=int(row["value_revision"]), membership_revision=int(row["membership_revision"]))
221
+ await conn.execute(
222
+ f"""INSERT INTO {backend._t("versions")} (state_id, kind, key, revision, sequence, run_id,
223
+ op_id, tombstone, row_data, sensitive_paths, intent_fp, inputs, applied_fp, status,
224
+ mutation_revision, value_revision, membership_revision, planning_context)
225
+ SELECT e.state_id, 'resource', e.address, e.revision, e.sequence, e.run_id, w.op_id, false,
226
+ w.row_data, e.sensitive_paths, e.intent_fp, e.inputs, e.applied_fp, e.status,
227
+ e.mutation_revision, e.value_revision, e.membership_revision, e.planning_context
228
+ FROM jsonb_to_recordset($2::jsonb) AS w(address text, op_id text, row_data jsonb)
229
+ JOIN {backend._t("entries")} e ON e.state_id = $1 AND e.address = w.address""",
230
+ backend.state_id,
231
+ payload,
232
+ )
233
+ return versions
234
+
235
+
236
+ async def publish_state_batch(backend: PostgreSQLGraphBackend, conn: asyncpg.Connection, ownership: Ownership, writes: list[RowWrite], sequence: int, operations: Sequence[OperationRecord]) -> dict[tuple[str, str], RowVersion] | None:
237
+ """Return published versions, or None to use the general writer unchanged.
238
+
239
+ The caller owns the app frontier lock. It has
240
+ already validated admission, recovery contracts and the combined footprint.
241
+ Reuse that transaction's operation evidence while the app lock excludes new
242
+ reservations, dispatches and publications; return/abort only relax exclusions.
243
+ No SQL writes occur before the whole batch passes eligibility and validation.
244
+ """
245
+ from .graph import _describe, _entry_document, _entry_of, _same, _version_of
246
+
247
+ if not backend._planning_contexts or not 2 <= len(writes) <= MAX_ROWS or len({write.key for write in writes}) != len(writes):
248
+ return None
249
+ if any(write.kind != RESOURCE or write.removal or write.op_id is not None or write.new_incarnation for write in writes):
250
+ return None
251
+ rows = await conn.fetch(f"SELECT * FROM {backend._t('entries')} WHERE state_id = $1 AND address = ANY($2::text[]) ORDER BY address FOR UPDATE", backend.state_id, [write.key for write in writes])
252
+ old_rows = {row["address"]: row for row in rows}
253
+ prepared = []
254
+ versions = {}
255
+ requests = {}
256
+ normalizing = {}
257
+ for write in writes:
258
+ old = old_rows.get(write.key)
259
+ if old is None or old["tombstone"]:
260
+ return None
261
+ entry = write.entry
262
+ identity = object_identity(entry)
263
+ previous = _entry_of(old["entry"], old["private"], old["status"])
264
+ normalizing[write.key] = legacy_normalization(write, previous)
265
+ if (
266
+ entry.is_data_source
267
+ or entry.resource_id != write.key
268
+ or not identity
269
+ or not identity.startswith("nf-object-v1:")
270
+ or (identity != old["object_identity"] and not normalizing[write.key])
271
+ or entry.provider != old["provider"]
272
+ or entry.type != old["type"]
273
+ or (entry.private or None) != old["private"]
274
+ ):
275
+ return None
276
+ actual = _version_of(old)
277
+ if write.expected is not UNCHECKED and not _same(actual, write.expected, statuses=False):
278
+ raise StateConflictError(f"{write.key} changed since this run read it (expected {_describe(write.expected)}, found {_describe(actual)}); not written")
279
+ revision = actual.revision + 1
280
+ intent = actual.intent_fp if write.intent_fp is UNCHECKED else write.intent_fp
281
+ inputs = actual.inputs if write.inputs is UNCHECKED else write.inputs
282
+ applied = actual.applied_fp if write.applied_fp is UNCHECKED else write.applied_fp
283
+ status = effective_status(write.status, actual, tainted=entry.tainted, evaluated=write.inputs is not UNCHECKED and write.inputs is not None)
284
+ context = bind_planning_context(write.planning_context, revision, intent)
285
+ versions[RESOURCE, write.key] = replace(
286
+ actual,
287
+ revision=revision,
288
+ status=status,
289
+ intent_fp=intent,
290
+ inputs=inputs,
291
+ applied_fp=applied,
292
+ planning_context=context,
293
+ run_id=ownership.run_id,
294
+ value_fp=value_fingerprint([entry.attributes, entry.provider, actual.private_digest]),
295
+ object_identity=identity,
296
+ )
297
+ document = entry.to_dict()
298
+ request = {"template": document}
299
+ claims = object_request(request, "state")
300
+ # Unbound results retain the general writer; unchanged legacy rows may
301
+ # gain their canonical identity through this same fenced publication.
302
+ if not claims.bound_sources or claims.sources != claims.bound_sources:
303
+ return None
304
+ requests[write.key] = request, claims
305
+ item = {
306
+ "address": write.key,
307
+ "revision": revision,
308
+ "status": status,
309
+ "stack_id": entry.stack_id,
310
+ "name": entry.id,
311
+ "entry": _entry_document(entry),
312
+ "row_data": document,
313
+ "sensitive_paths": write.sensitive_paths,
314
+ "intent_fp": intent,
315
+ "inputs": encode_inputs(inputs) if inputs is not None else None,
316
+ "applied_fp": applied,
317
+ "planning_context": context.to_dict() if context is not None else None,
318
+ "object_identity": identity,
319
+ }
320
+ prepared.append(item)
321
+
322
+ payloads = _payload_chunks(prepared)
323
+ if payloads is None:
324
+ return None
325
+
326
+ candidates = await backend._object_entry_guard(conn, writes, old_rows)
327
+ for write in writes:
328
+ address = write.key
329
+ request, claims = requests[address]
330
+ peers = candidates.candidates(address, claims, allow_legacy_normalization=normalizing[address])
331
+ if problems := object_problems(address, request, "state", peers, operations, run_id=ownership.run_id, allow_legacy_normalization=normalizing[address], claims=claims):
332
+ raise PreCallValidationError("Cloud ownership validation failed:\n" + "\n".join(problems))
333
+ candidates.replace(address, write.entry)
334
+
335
+ for payload in payloads:
336
+ # Value changes skip text conversion. Equal values need a C-collated text
337
+ # comparison too: JSONB equates numeric representations such as 1 and 1.0.
338
+ rows = await conn.fetch(
339
+ f"""UPDATE {backend._t("entries")} e SET revision = w.revision, status = w.status,
340
+ stack_id = w.stack_id, name = w.name,
341
+ entry = CASE WHEN e.entry IS DISTINCT FROM w.entry THEN w.entry
342
+ WHEN e.entry::text COLLATE "C" IS NOT DISTINCT FROM w.entry::text COLLATE "C" THEN e.entry ELSE w.entry END,
343
+ sensitive_paths = w.sensitive_paths,
344
+ run_id = $3, sequence = $4, intent_fp = w.intent_fp, inputs = w.inputs,
345
+ applied_fp = w.applied_fp, planning_context = w.planning_context,
346
+ object_identity = w.object_identity, updated_at = clock_timestamp()
347
+ FROM jsonb_to_recordset($2::jsonb) AS w(address text, revision bigint, status text,
348
+ stack_id text, name text, entry jsonb, sensitive_paths jsonb, intent_fp text,
349
+ inputs jsonb, applied_fp text, planning_context jsonb, object_identity text)
350
+ WHERE e.state_id = $1 AND e.address = w.address
351
+ RETURNING e.address, e.value_revision, e.membership_revision""",
352
+ backend.state_id,
353
+ payload,
354
+ ownership.run_id,
355
+ sequence,
356
+ )
357
+ for row in rows:
358
+ key = RESOURCE, row["address"]
359
+ versions[key] = replace(versions[key], value_revision=int(row["value_revision"]), membership_revision=int(row["membership_revision"]))
360
+ # Join the updated rows so history records trigger-derived semantic counters.
361
+ await conn.execute(
362
+ f"""INSERT INTO {backend._t("versions")} (state_id, kind, key, revision, sequence, run_id,
363
+ op_id, tombstone, row_data, sensitive_paths, intent_fp, inputs, applied_fp, status,
364
+ mutation_revision, value_revision, membership_revision, planning_context)
365
+ SELECT e.state_id, 'resource', e.address, e.revision, e.sequence, e.run_id, NULL, false,
366
+ w.row_data, e.sensitive_paths, e.intent_fp, e.inputs, e.applied_fp, e.status,
367
+ e.mutation_revision, e.value_revision, e.membership_revision, e.planning_context
368
+ FROM jsonb_to_recordset($2::jsonb) AS w(address text, row_data jsonb)
369
+ JOIN {backend._t("entries")} e ON e.state_id = $1 AND e.address = w.address""",
370
+ backend.state_id,
371
+ payload,
372
+ )
373
+ return versions
@@ -0,0 +1,141 @@
1
+ """Preview and prune one state's evidence under the same pin and history guards."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import replace
6
+ from typing import TYPE_CHECKING
7
+
8
+ from netherframe.core.backends.graph_retention import HistoryRetention, RetentionCount, retention_days
9
+
10
+ from .graph_checkpoints import PostgreSQLHistoryCheckpoints
11
+
12
+ if TYPE_CHECKING:
13
+ import asyncpg
14
+ from .graph import PostgreSQLGraphBackend
15
+
16
+
17
+ class PostgreSQLHistoryRetention:
18
+ def __init__(self, backend: PostgreSQLGraphBackend) -> None:
19
+ self.b = backend
20
+
21
+ def versions(self) -> str:
22
+ # Keep the successor lookup parameterized by resource. When statistics
23
+ # underestimate a newly populated state, a flattened EXISTS semi-join
24
+ # can otherwise scan that entire state's history once for every row.
25
+ return f"""v.state_id = $1 AND v.sequence <= $4 AND v.committed_at < to_timestamp($2)
26
+ AND (SELECT 1 FROM {self.b._t("versions")} w
27
+ WHERE w.state_id = v.state_id AND w.kind = v.kind AND w.key = v.key
28
+ AND w.revision > v.revision AND w.committed_at < to_timestamp($2) LIMIT 1) IS NOT NULL
29
+ AND NOT EXISTS (SELECT 1 FROM {self.b._t("checkpoints")} c WHERE c.state_id = v.state_id
30
+ AND NOT (c.checkpoint_id = ANY($3::text[])) AND jsonb_array_length(c.manifest -> 'targets') > 0
31
+ AND (v.sequence > c.sequence OR EXISTS (
32
+ SELECT 1 FROM jsonb_to_recordset(c.manifest -> 'targets') AS t(kind text, key text, revision bigint)
33
+ WHERE (t.kind, t.key, t.revision) = (v.kind, v.key, v.revision))))
34
+ AND NOT EXISTS (SELECT 1 FROM {self.b._t("baselines")} b
35
+ WHERE b.state_id = v.state_id AND v.sequence <= b.sequence
36
+ AND NOT EXISTS (SELECT 1 FROM {self.b._t("versions")} w
37
+ WHERE w.state_id = v.state_id AND w.kind = v.kind AND w.key = v.key
38
+ AND (w.sequence > v.sequence OR (w.sequence = v.sequence AND w.revision > v.revision)) AND w.sequence <= b.sequence))"""
39
+
40
+ def operations(self) -> str:
41
+ return f"""o.state_id = $1 AND o.stage IN ('committed', 'aborted')
42
+ AND o.resolved_at < to_timestamp($2)
43
+ AND NOT EXISTS (SELECT 1 FROM {self.b._t("runs")} r
44
+ WHERE r.run_id IN (o.run_id, o.recovered_by) AND r.status = 'active' AND r.expires_at > clock_timestamp())
45
+ AND NOT EXISTS (SELECT 1 FROM {self.b._t("checkpoints")} c
46
+ WHERE c.state_id = o.state_id AND NOT (c.checkpoint_id = ANY($3::text[]))
47
+ AND jsonb_array_length(c.manifest -> 'targets') > 0 AND o.reservation > c.operation_frontier)"""
48
+
49
+ async def inspect(self, conn: asyncpg.Connection, days: int, preview: HistoryRetention | None = None) -> tuple[HistoryRetention, list[str]]:
50
+ app = await conn.fetchrow(f"SELECT lineage, frontier, pruned_before, history_epoch, extract(epoch FROM clock_timestamp()) AS now FROM {self.b._t('apps')} WHERE state_id = $1", self.b.state_id)
51
+ now = float(app["now"])
52
+ cutoff = preview.cutoff if preview is not None else now - days * 86400
53
+ frontier = preview.frontier if preview is not None else int(app["frontier"])
54
+ if preview is not None:
55
+ preview.check(self.b.get_backend_type(), self.b.state_id, app["lineage"], now, int(app["frontier"]))
56
+ dropped = await PostgreSQLHistoryCheckpoints(self.b).prunable(conn)
57
+ versions = await conn.fetchrow(f"SELECT count(*) AS total, count(*) FILTER (WHERE {self.versions()}) AS eligible FROM {self.b._t('versions')} v WHERE v.state_id = $1", self.b.state_id, cutoff, dropped, frontier)
58
+ operations = await conn.fetchrow(f"SELECT count(*) AS total, count(*) FILTER (WHERE {self.operations()}) AS eligible FROM {self.b._t('operations')} o WHERE o.state_id = $1", self.b.state_id, cutoff, dropped)
59
+ checkpoints = int(await conn.fetchval(f"SELECT count(*) FROM {self.b._t('checkpoints')} WHERE state_id = $1", self.b.state_id))
60
+ baselines = int(await conn.fetchval(f"SELECT count(*) FROM {self.b._t('baselines')} WHERE state_id = $1", self.b.state_id))
61
+ return HistoryRetention(
62
+ self.b.get_backend_type(),
63
+ self.b.state_id,
64
+ app["lineage"],
65
+ days,
66
+ now,
67
+ cutoff,
68
+ frontier,
69
+ int(app["pruned_before"]),
70
+ int(app["history_epoch"]),
71
+ baselines,
72
+ RetentionCount(int(versions["total"]), int(versions["eligible"])),
73
+ RetentionCount(int(operations["total"]), int(operations["eligible"])),
74
+ RetentionCount(checkpoints, len(dropped)),
75
+ ), dropped
76
+
77
+ async def preview(self, days: int | None) -> HistoryRetention:
78
+ days = retention_days(self.b.settings.history_retention_days if days is None else days)
79
+ async with self.b._tx(readonly=True, isolation="repeatable_read") as conn:
80
+ report, _dropped = await self.inspect(conn, days)
81
+ return report
82
+
83
+ async def apply(self, preview: HistoryRetention | None = None) -> HistoryRetention:
84
+ days = retention_days(preview.days if preview is not None else self.b.settings.history_retention_days)
85
+ async with self.b._tx() as conn:
86
+ # Baselines, checkpoint creation, reservation and commits serialize
87
+ # here. Counts from a preview never authorize deletion on their own.
88
+ await conn.fetchrow(f"SELECT state_id FROM {self.b._t('apps')} WHERE state_id = $1 FOR UPDATE", self.b.state_id)
89
+ report, _dropped = await self.inspect(conn, days, preview)
90
+ counts, pruned_before, history_epoch = await self._prune(conn, report.cutoff, report.frontier)
91
+ return replace(
92
+ report,
93
+ pruned=True,
94
+ pruned_before=pruned_before,
95
+ history_epoch=history_epoch,
96
+ versions=RetentionCount(report.versions.total, counts[0]),
97
+ operations=RetentionCount(report.operations.total, counts[1]),
98
+ checkpoints=RetentionCount(report.checkpoints.total, counts[2]),
99
+ )
100
+
101
+ async def cleanup(self) -> None:
102
+ """Run release maintenance without computing a discarded count report.
103
+
104
+ Keep the same app lock, post-lock clock/frontier observation, deletion
105
+ predicates and marker update as explicit pruning. There is no scheduling
106
+ delay, eligibility shortcut or separate deletion implementation.
107
+ """
108
+ days = retention_days(self.b.settings.history_retention_days)
109
+ async with self.b._tx() as conn:
110
+ await conn.fetchrow(f"SELECT state_id FROM {self.b._t('apps')} WHERE state_id = $1 FOR UPDATE", self.b.state_id)
111
+ app = await conn.fetchrow(f"SELECT frontier, extract(epoch FROM clock_timestamp()) AS now FROM {self.b._t('apps')} WHERE state_id = $1", self.b.state_id)
112
+ await self._prune(conn, float(app["now"]) - days * 86400, int(app["frontier"]))
113
+
114
+ async def _prune(self, conn: asyncpg.Connection, cutoff: float, frontier: int) -> tuple[tuple[int, int, int], int, int]:
115
+ removed_checkpoints = await PostgreSQLHistoryCheckpoints(self.b).prune(conn)
116
+ gone = await conn.fetchrow(
117
+ f"""WITH gone AS (
118
+ DELETE FROM {self.b._t("versions")} v WHERE {self.versions()}
119
+ RETURNING (SELECT CASE WHEN w.sequence > v.sequence THEN w.sequence - 1 ELSE NULL END
120
+ FROM {self.b._t("versions")} w WHERE w.state_id = v.state_id AND w.kind = v.kind AND w.key = v.key
121
+ AND w.revision > v.revision ORDER BY w.revision LIMIT 1) AS incomplete_through)
122
+ SELECT count(*) AS count, max(incomplete_through) AS boundary FROM gone""",
123
+ self.b.state_id,
124
+ cutoff,
125
+ [],
126
+ frontier,
127
+ )
128
+ removed_operations = await conn.fetchval(
129
+ f"WITH gone AS (DELETE FROM {self.b._t('operations')} o WHERE {self.operations()} RETURNING op_id) SELECT count(*) FROM gone",
130
+ self.b.state_id,
131
+ cutoff,
132
+ [],
133
+ )
134
+ counts = (int(gone["count"]), int(removed_operations), removed_checkpoints)
135
+ app = await conn.fetchrow(
136
+ f"UPDATE {self.b._t('apps')} SET pruned_before = greatest(pruned_before, coalesce($2::bigint, 0)), history_epoch = history_epoch + $3 WHERE state_id = $1 RETURNING pruned_before, history_epoch",
137
+ self.b.state_id,
138
+ gone["boundary"],
139
+ int(any(counts)),
140
+ )
141
+ return counts, int(app["pruned_before"]), int(app["history_epoch"])
@@ -0,0 +1,143 @@
1
+ """Short consistent reads of authoritative reverse edges and commit-local deltas."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Sequence
6
+ from typing import TYPE_CHECKING
7
+
8
+ from netherframe.core.backends.graph_edges import EdgeDelta, EdgeIndex, EdgePredicate, EdgeTarget, GraphEdge, covering_targets
9
+ from netherframe.core.serialization import orjson_compat as json
10
+
11
+ if TYPE_CHECKING:
12
+ import asyncpg
13
+ from netherframe.core.backends.graph_plan_basis import EdgeExpectation
14
+
15
+ from .graph import PostgreSQLGraphBackend
16
+
17
+
18
+ class PostgreSQLReverseEdges:
19
+ def __init__(self, backend: PostgreSQLGraphBackend) -> None:
20
+ self.backend = backend
21
+
22
+ async def ready_consumers(self, conn: asyncpg.Connection, changed: set[tuple[str, str]], kind: str, check_written: Sequence[str]):
23
+ """Find candidate rows without scanning each input JSON for every target.
24
+
25
+ Concrete and broad predicates use separate index lookups. Keep newly
26
+ written rows with inputs in the set: their own inputs may already be stale. Edges
27
+ include ordering dependencies and unknown-input scopes, so the caller
28
+ must still use changed_inputs to decide which candidates need a write.
29
+
30
+ Group concrete targets by kind. A correlated lookup per target can
31
+ repeatedly scan one app's edges when fresh/stale statistics choose the
32
+ owner index; these branches perform at most one lookup per kind.
33
+ """
34
+ backend = self.backend
35
+ table, key = ("entries", "address") if kind == "resource" else ("outputs", "key")
36
+ return await conn.fetch(
37
+ f"""WITH candidates AS MATERIALIZED (
38
+ SELECT unnest($4::text[]) AS key
39
+ UNION SELECT dependent FROM {backend._t("edges")}
40
+ WHERE state_id = $1 AND target_kind = 'resource'
41
+ AND target = ANY($2::text[]) AND dependent_kind = $5
42
+ UNION SELECT dependent FROM {backend._t("edges")}
43
+ WHERE state_id = $1 AND target_kind = 'output'
44
+ AND target = ANY($3::text[]) AND dependent_kind = $5
45
+ UNION SELECT dependent FROM {backend._t("edges")}
46
+ WHERE state_id = $1 AND target_kind IN ('scope', 'enumeration')
47
+ AND dependent_kind = $5)
48
+ SELECT e.* FROM candidates c CROSS JOIN LATERAL (
49
+ SELECT * FROM {backend._t(table)} e WHERE e.state_id = $1 AND e.{key} = c.key
50
+ AND NOT e.tombstone AND e.status = 'ready'
51
+ AND e.inputs IS NOT NULL AND e.inputs NOT IN ('null'::jsonb, '[]'::jsonb)
52
+ OFFSET 0) e""",
53
+ backend.state_id,
54
+ sorted(key for target_kind, key in changed if target_kind == "resource"),
55
+ sorted(key for target_kind, key in changed if target_kind == "output"),
56
+ list(check_written),
57
+ kind,
58
+ )
59
+
60
+ @staticmethod
61
+ def _edges(rows) -> frozenset[GraphEdge]:
62
+ return frozenset(GraphEdge(EdgeTarget(row["target_kind"], row["target"]), row["dependent_kind"], row["dependent"]) for row in rows)
63
+
64
+ @staticmethod
65
+ def _generations(rows) -> dict[EdgeTarget, int]:
66
+ return {EdgeTarget(row["target_kind"], row["target"]): int(row["generation"]) for row in rows}
67
+
68
+ async def snapshot(self, conn: asyncpg.Connection) -> EdgeIndex:
69
+ backend = self.backend
70
+ rows = await conn.fetch(f"SELECT * FROM {backend._t('edges')} WHERE state_id = $1", backend.state_id)
71
+ generations = await conn.fetch(f"SELECT * FROM {backend._t('edge_generations')} WHERE state_id = $1", backend.state_id)
72
+ return EdgeIndex(self._edges(rows), self._generations(generations))
73
+
74
+ async def for_plan(self, conn: asyncpg.Connection, expectations: Sequence[EdgeExpectation]) -> EdgeIndex:
75
+ """Only covering generations and destructive predicates' consumers.
76
+
77
+ A non-destructive proof needs the counters, not every broad observer's
78
+ outgoing edges. A destructive proof must also see concrete, app and
79
+ stack consumers, including output consumers outside its closed writes.
80
+ """
81
+ backend = self.backend
82
+ targets = {target for item in expectations for target in covering_targets(item.kind, item.key)}
83
+ if not targets:
84
+ return EdgeIndex()
85
+
86
+ def encoded(values):
87
+ return json.dumps([{"kind": target.kind, "key": target.key} for target in sorted(values)])
88
+
89
+ generations = await conn.fetch(
90
+ f"SELECT g.* FROM {backend._t('edge_generations')} g JOIN jsonb_to_recordset($2::jsonb) AS target(kind text, key text) ON target.kind = g.target_kind AND target.key = g.target WHERE g.state_id = $1",
91
+ backend.state_id,
92
+ encoded(targets),
93
+ )
94
+ destructive = {target for item in expectations if item.destructive for target in covering_targets(item.kind, item.key)}
95
+ rows = (
96
+ await conn.fetch(
97
+ f"SELECT e.* FROM {backend._t('edges')} e JOIN jsonb_to_recordset($2::jsonb) AS target(kind text, key text) ON target.kind = e.target_kind AND target.key = e.target WHERE e.state_id = $1",
98
+ backend.state_id,
99
+ encoded(destructive),
100
+ )
101
+ if destructive
102
+ else []
103
+ )
104
+ return EdgeIndex(self._edges(rows), self._generations(generations))
105
+
106
+ async def for_owners(self, conn: asyncpg.Connection, owners: Sequence[tuple[str, str]]) -> frozenset[GraphEdge]:
107
+ backend = self.backend
108
+ if not owners:
109
+ return frozenset()
110
+ rows = await conn.fetch(
111
+ f"SELECT e.* FROM {backend._t('edges')} e JOIN jsonb_to_recordset($2::jsonb) AS owner(kind text, key text) ON owner.kind = e.dependent_kind AND owner.key = e.dependent WHERE e.state_id = $1",
112
+ backend.state_id,
113
+ json.dumps([{"kind": kind, "key": key} for kind, key in sorted(set(owners))]),
114
+ )
115
+ return self._edges(rows)
116
+
117
+ async def delta(self, conn: asyncpg.Connection, before: frozenset[GraphEdge], owners: Sequence[tuple[str, str]]) -> EdgeDelta:
118
+ backend = self.backend
119
+ after = await self.for_owners(conn, owners)
120
+ targets = {edge.target for edge in before | after}
121
+ if not targets:
122
+ return EdgeDelta()
123
+ generations = await conn.fetch(
124
+ f"SELECT g.* FROM {backend._t('edge_generations')} g JOIN jsonb_to_recordset($2::jsonb) AS target(kind text, key text) ON target.kind = g.target_kind AND target.key = g.target WHERE g.state_id = $1",
125
+ backend.state_id,
126
+ json.dumps([{"kind": target.kind, "key": target.key} for target in sorted(targets)]),
127
+ )
128
+ return EdgeDelta(after - before, before - after, self._generations(generations))
129
+
130
+ async def predicate(self, conn: asyncpg.Connection, kind: str, key: str) -> EdgePredicate:
131
+ backend = self.backend
132
+ targets = json.dumps([{"kind": target.kind, "key": target.key} for target in covering_targets(kind, key)])
133
+ rows = await conn.fetch(
134
+ f"SELECT e.* FROM {backend._t('edges')} e JOIN jsonb_to_recordset($2::jsonb) AS target(kind text, key text) ON target.kind = e.target_kind AND target.key = e.target WHERE e.state_id = $1",
135
+ backend.state_id,
136
+ targets,
137
+ )
138
+ generations = await conn.fetch(
139
+ f"SELECT g.* FROM {backend._t('edge_generations')} g JOIN jsonb_to_recordset($2::jsonb) AS target(kind text, key text) ON target.kind = g.target_kind AND target.key = g.target WHERE g.state_id = $1",
140
+ backend.state_id,
141
+ targets,
142
+ )
143
+ return EdgeIndex(self._edges(rows), self._generations(generations)).predicate(kind, key)