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,2038 @@
1
+ """The PostgreSQL graph state backend's schema, as versioned migrations.
2
+
3
+ Each migration runs once, in order. Release migrations are recorded in ``<prefix>schema_migrations``;
4
+ the historical development migrations keep a separate ledger. ``{s}`` is the schema,
5
+ ``{p}`` the table prefix, ``{v}`` the prefix of the
6
+ read-only views (empty for the default ``nf_`` tables, so the views are ``resources_current``,
7
+ ``history`` and so on).
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ #: Version 1: rows, operations and recovery under an app-wide lease (the RFC's phase 1)
13
+ V1 = """
14
+ CREATE TABLE IF NOT EXISTS {s}.{p}apps (
15
+ state_id text PRIMARY KEY,
16
+ lineage text NOT NULL,
17
+ schema_version integer NOT NULL,
18
+ -- The ownership epoch: each run and recoverer takes the next
19
+ epoch bigint NOT NULL DEFAULT 0,
20
+ -- The commit counter: each commit takes the next sequence inside its transaction, so the
21
+ -- frontier (the last committed sequence) only ever moves past committed sequences
22
+ frontier bigint NOT NULL DEFAULT 0,
23
+ -- Versions committed at or before this sequence may have been pruned (retention)
24
+ pruned_before bigint NOT NULL DEFAULT 0,
25
+ metadata jsonb NOT NULL DEFAULT '{{}}'::jsonb,
26
+ migrated_to text,
27
+ created_at timestamptz NOT NULL DEFAULT clock_timestamp()
28
+ );
29
+
30
+ CREATE TABLE IF NOT EXISTS {s}.{p}runs (
31
+ run_id text PRIMARY KEY,
32
+ state_id text NOT NULL REFERENCES {s}.{p}apps (state_id),
33
+ epoch bigint NOT NULL,
34
+ operation text NOT NULL,
35
+ actor text,
36
+ host text,
37
+ pid integer,
38
+ status text NOT NULL CHECK (status IN ('active', 'ended', 'expired')),
39
+ started_at timestamptz NOT NULL DEFAULT clock_timestamp(),
40
+ expires_at timestamptz NOT NULL,
41
+ ended_at timestamptz,
42
+ providers_killed_at timestamptz
43
+ );
44
+ CREATE INDEX IF NOT EXISTS {p}runs_state ON {s}.{p}runs (state_id, started_at);
45
+
46
+ CREATE TABLE IF NOT EXISTS {s}.{p}leases (
47
+ state_id text NOT NULL REFERENCES {s}.{p}apps (state_id),
48
+ key text NOT NULL,
49
+ holder text NOT NULL,
50
+ mode text NOT NULL CHECK (mode IN ('IS', 'IX', 'S', 'SIX', 'X')),
51
+ acquired_at timestamptz NOT NULL DEFAULT clock_timestamp(),
52
+ PRIMARY KEY (state_id, key, holder)
53
+ );
54
+
55
+ CREATE TABLE IF NOT EXISTS {s}.{p}entries (
56
+ state_id text NOT NULL REFERENCES {s}.{p}apps (state_id),
57
+ address text NOT NULL,
58
+ revision bigint NOT NULL,
59
+ incarnation bigint NOT NULL,
60
+ status text NOT NULL CHECK (status IN ('ready', 'tainted', 'uncertain')),
61
+ tombstone boolean NOT NULL DEFAULT false,
62
+ stack_id text,
63
+ type text,
64
+ name text,
65
+ provider text,
66
+ entry jsonb,
67
+ private bytea,
68
+ private_digest text NOT NULL DEFAULT '',
69
+ object_identity text,
70
+ sensitive_paths jsonb NOT NULL DEFAULT '[]'::jsonb,
71
+ run_id text,
72
+ sequence bigint NOT NULL,
73
+ updated_at timestamptz NOT NULL DEFAULT clock_timestamp(),
74
+ PRIMARY KEY (state_id, address)
75
+ );
76
+ -- Two addresses can never manage one object
77
+ CREATE UNIQUE INDEX IF NOT EXISTS {p}entries_object_identity ON {s}.{p}entries (state_id, object_identity) WHERE object_identity IS NOT NULL AND NOT tombstone;
78
+
79
+ CREATE TABLE IF NOT EXISTS {s}.{p}outputs (
80
+ state_id text NOT NULL REFERENCES {s}.{p}apps (state_id),
81
+ key text NOT NULL,
82
+ revision bigint NOT NULL,
83
+ tombstone boolean NOT NULL DEFAULT false,
84
+ value jsonb,
85
+ sensitive boolean NOT NULL DEFAULT false,
86
+ run_id text,
87
+ sequence bigint NOT NULL,
88
+ updated_at timestamptz NOT NULL DEFAULT clock_timestamp(),
89
+ PRIMARY KEY (state_id, key)
90
+ );
91
+
92
+ -- Data source results: a cache, never versioned or compared
93
+ CREATE TABLE IF NOT EXISTS {s}.{p}observations (
94
+ state_id text NOT NULL REFERENCES {s}.{p}apps (state_id),
95
+ address text NOT NULL,
96
+ entry jsonb NOT NULL,
97
+ private bytea,
98
+ run_id text,
99
+ updated_at timestamptz NOT NULL DEFAULT clock_timestamp(),
100
+ PRIMARY KEY (state_id, address)
101
+ );
102
+
103
+ CREATE TABLE IF NOT EXISTS {s}.{p}versions (
104
+ state_id text NOT NULL REFERENCES {s}.{p}apps (state_id),
105
+ kind text NOT NULL CHECK (kind IN ('resource', 'output')),
106
+ key text NOT NULL,
107
+ revision bigint NOT NULL,
108
+ sequence bigint NOT NULL,
109
+ run_id text,
110
+ op_id text,
111
+ tombstone boolean NOT NULL DEFAULT false,
112
+ row_data jsonb,
113
+ sensitive_paths jsonb NOT NULL DEFAULT '[]'::jsonb,
114
+ committed_at timestamptz NOT NULL DEFAULT clock_timestamp(),
115
+ PRIMARY KEY (state_id, kind, key, revision)
116
+ );
117
+ CREATE INDEX IF NOT EXISTS {p}versions_sequence ON {s}.{p}versions (state_id, sequence);
118
+
119
+ CREATE TABLE IF NOT EXISTS {s}.{p}commits (
120
+ state_id text NOT NULL REFERENCES {s}.{p}apps (state_id),
121
+ sequence bigint NOT NULL,
122
+ run_id text NOT NULL,
123
+ epoch bigint NOT NULL,
124
+ -- When the commit's fence checked the run's ownership (its row then held FOR SHARE until the
125
+ -- commit, so no takeover could come between), and the lease expiry it checked against
126
+ fenced_at timestamptz NOT NULL,
127
+ committed_at timestamptz NOT NULL,
128
+ lease_expires_at timestamptz NOT NULL,
129
+ PRIMARY KEY (state_id, sequence)
130
+ );
131
+
132
+ CREATE TABLE IF NOT EXISTS {s}.{p}operations (
133
+ op_id text PRIMARY KEY,
134
+ state_id text NOT NULL REFERENCES {s}.{p}apps (state_id),
135
+ run_id text NOT NULL,
136
+ epoch bigint NOT NULL,
137
+ attempt integer NOT NULL DEFAULT 1,
138
+ recovered_by text,
139
+ address text NOT NULL,
140
+ footprint jsonb NOT NULL DEFAULT '[]'::jsonb,
141
+ object_identity text,
142
+ action text NOT NULL,
143
+ stage text NOT NULL CHECK (stage IN ('reserved', 'dispatched', 'returned', 'delete_dispatched', 'delete_committed', 'create_dispatched', 'committed', 'aborted')),
144
+ expected jsonb,
145
+ expected_provider text,
146
+ request jsonb NOT NULL DEFAULT '{{}}'::jsonb,
147
+ request_digest text,
148
+ result jsonb,
149
+ error text,
150
+ outcome text,
151
+ owner_host text,
152
+ owner_pid integer,
153
+ provider_pid integer,
154
+ created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
155
+ dispatched_at timestamptz,
156
+ returned_at timestamptz,
157
+ resolved_at timestamptz
158
+ );
159
+ CREATE INDEX IF NOT EXISTS {p}operations_unresolved ON {s}.{p}operations (state_id) WHERE stage NOT IN ('committed', 'aborted');
160
+
161
+ -- Masks the attributes at ``paths`` (a JSON array of key paths) in ``attributes``
162
+ CREATE OR REPLACE FUNCTION {s}.{p}mask(attributes jsonb, paths jsonb) RETURNS jsonb
163
+ LANGUAGE plpgsql IMMUTABLE AS $$
164
+ DECLARE
165
+ path jsonb;
166
+ keys text[];
167
+ masked jsonb := attributes;
168
+ BEGIN
169
+ IF attributes IS NULL OR paths IS NULL OR jsonb_typeof(attributes) <> 'object' THEN
170
+ RETURN attributes;
171
+ END IF;
172
+ FOR path IN SELECT value FROM jsonb_array_elements(paths) LOOP
173
+ keys := ARRAY(SELECT jsonb_array_elements_text(path));
174
+ IF masked #> keys IS NOT NULL THEN
175
+ masked := jsonb_set(masked, keys, '"(sensitive)"'::jsonb, false);
176
+ END IF;
177
+ END LOOP;
178
+ RETURN masked;
179
+ END
180
+ $$;
181
+
182
+ -- Read-only views, sensitive values masked; ``nf state query`` sees only these
183
+ CREATE OR REPLACE VIEW {s}.{v}resources_current AS
184
+ SELECT e.state_id, e.address, e.stack_id, e.type, e.name, e.provider, e.revision, e.incarnation, e.status,
185
+ e.object_identity, {s}.{p}mask(e.entry -> 'attributes', e.sensitive_paths) AS attributes,
186
+ e.entry -> 'dependencies' AS dependencies, e.run_id, e.sequence, e.updated_at
187
+ FROM {s}.{p}entries e WHERE NOT e.tombstone;
188
+
189
+ CREATE OR REPLACE VIEW {s}.{v}outputs_current AS
190
+ SELECT o.state_id, o.key, o.revision,
191
+ CASE WHEN o.sensitive THEN '"(sensitive)"'::jsonb ELSE o.value -> 'value' END AS value,
192
+ o.sensitive, o.run_id, o.sequence, o.updated_at
193
+ FROM {s}.{p}outputs o WHERE NOT o.tombstone;
194
+
195
+ CREATE OR REPLACE VIEW {s}.{v}history AS
196
+ SELECT v.state_id, v.kind, v.key, v.revision, v.sequence, v.run_id, v.op_id, v.tombstone, v.committed_at,
197
+ r.operation, r.actor,
198
+ CASE
199
+ WHEN v.kind = 'resource' THEN {s}.{p}mask(v.row_data -> 'attributes', v.sensitive_paths)
200
+ WHEN coalesce((v.row_data ->> 'sensitive')::boolean, false) THEN '"(sensitive)"'::jsonb
201
+ ELSE v.row_data -> 'value'
202
+ END AS value
203
+ FROM {s}.{p}versions v LEFT JOIN {s}.{p}runs r ON r.run_id = v.run_id;
204
+
205
+ CREATE OR REPLACE VIEW {s}.{v}runs AS
206
+ SELECT run_id, state_id, epoch, operation, actor, host, status, started_at, expires_at, ended_at, providers_killed_at
207
+ FROM {s}.{p}runs;
208
+
209
+ CREATE OR REPLACE VIEW {s}.{v}operations AS
210
+ SELECT op_id, state_id, run_id, epoch, attempt, recovered_by, address, action, stage, outcome, error,
211
+ created_at, dispatched_at, returned_at, resolved_at
212
+ FROM {s}.{p}operations;
213
+ """
214
+
215
+ #: Version 2: intent survives state refresh, deletion and history retention.
216
+ V2 = """
217
+ ALTER TABLE {s}.{p}entries ADD COLUMN intent_fp text;
218
+ ALTER TABLE {s}.{p}outputs ADD COLUMN intent_fp text;
219
+ ALTER TABLE {s}.{p}versions ADD COLUMN intent_fp text;
220
+ UPDATE {s}.{p}apps SET schema_version = 2;
221
+
222
+ CREATE OR REPLACE VIEW {s}.{v}resources_current AS
223
+ SELECT e.state_id, e.address, e.stack_id, e.type, e.name, e.provider, e.revision, e.incarnation, e.status,
224
+ e.object_identity, {s}.{p}mask(e.entry -> 'attributes', e.sensitive_paths) AS attributes,
225
+ e.entry -> 'dependencies' AS dependencies, e.run_id, e.sequence, e.updated_at, e.intent_fp
226
+ FROM {s}.{p}entries e WHERE NOT e.tombstone;
227
+
228
+ CREATE OR REPLACE VIEW {s}.{v}outputs_current AS
229
+ SELECT o.state_id, o.key, o.revision,
230
+ CASE WHEN o.sensitive THEN '"(sensitive)"'::jsonb ELSE o.value -> 'value' END AS value,
231
+ o.sensitive, o.run_id, o.sequence, o.updated_at, o.intent_fp
232
+ FROM {s}.{p}outputs o WHERE NOT o.tombstone;
233
+
234
+ CREATE OR REPLACE VIEW {s}.{v}history AS
235
+ SELECT v.state_id, v.kind, v.key, v.revision, v.sequence, v.run_id, v.op_id, v.tombstone, v.committed_at,
236
+ r.operation, r.actor,
237
+ CASE
238
+ WHEN v.kind = 'resource' THEN {s}.{p}mask(v.row_data -> 'attributes', v.sensitive_paths)
239
+ WHEN coalesce((v.row_data ->> 'sensitive')::boolean, false) THEN '"(sensitive)"'::jsonb
240
+ ELSE v.row_data -> 'value'
241
+ END AS value, v.intent_fp
242
+ FROM {s}.{p}versions v LEFT JOIN {s}.{p}runs r ON r.run_id = v.run_id;
243
+ """
244
+
245
+ V3 = """
246
+ CREATE TABLE {s}.{p}baselines (
247
+ state_id text NOT NULL REFERENCES {s}.{p}apps (state_id),
248
+ pin_id text NOT NULL,
249
+ lineage text NOT NULL,
250
+ sequence bigint NOT NULL CHECK (sequence >= 0),
251
+ intent_digest text NOT NULL,
252
+ created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
253
+ PRIMARY KEY (state_id, pin_id)
254
+ );
255
+ CREATE INDEX {p}baselines_sequence ON {s}.{p}baselines (state_id, sequence);
256
+ UPDATE {s}.{p}apps SET schema_version = 3;
257
+ """
258
+
259
+ V4 = """
260
+ -- Older retention recorded the deleted sequence, which does not prove later
261
+ -- snapshots complete. Preserve a conservative boundary for already-pruned apps.
262
+ UPDATE {s}.{p}apps SET pruned_before = greatest(pruned_before, frontier - 1) WHERE pruned_before > 0;
263
+ ALTER TABLE {s}.{p}entries ADD COLUMN inputs jsonb;
264
+ ALTER TABLE {s}.{p}entries ADD COLUMN applied_fp text;
265
+ ALTER TABLE {s}.{p}entries DROP CONSTRAINT {p}entries_status_check;
266
+ ALTER TABLE {s}.{p}entries ADD CONSTRAINT {p}entries_status_check CHECK (status IN ('ready', 'tainted', 'uncertain', 'stale_inputs', 'unconverged'));
267
+ ALTER TABLE {s}.{p}outputs ADD COLUMN inputs jsonb;
268
+ ALTER TABLE {s}.{p}outputs ADD COLUMN applied_fp text;
269
+ ALTER TABLE {s}.{p}outputs ADD COLUMN status text NOT NULL DEFAULT 'ready' CHECK (status IN ('ready', 'stale_inputs', 'unconverged'));
270
+ ALTER TABLE {s}.{p}versions ADD COLUMN inputs jsonb;
271
+ ALTER TABLE {s}.{p}versions ADD COLUMN applied_fp text;
272
+ ALTER TABLE {s}.{p}versions ADD COLUMN status text NOT NULL DEFAULT 'ready';
273
+ CREATE INDEX {p}entries_inputs ON {s}.{p}entries USING gin (inputs jsonb_path_ops) WHERE NOT tombstone;
274
+ CREATE INDEX {p}outputs_inputs ON {s}.{p}outputs USING gin (inputs jsonb_path_ops) WHERE NOT tombstone;
275
+
276
+ CREATE FUNCTION {s}.{p}mask_at(value jsonb, keys text[]) RETURNS jsonb
277
+ LANGUAGE plpgsql IMMUTABLE AS $$
278
+ DECLARE
279
+ result jsonb;
280
+ BEGIN
281
+ IF array_length(keys, 1) IS NULL THEN
282
+ RETURN '"(sensitive)"'::jsonb;
283
+ END IF;
284
+ IF jsonb_typeof(value) = 'array' THEN
285
+ SELECT coalesce(jsonb_agg({s}.{p}mask_at(item, keys) ORDER BY ordinal), '[]'::jsonb)
286
+ INTO result FROM jsonb_array_elements(value) WITH ORDINALITY AS element(item, ordinal);
287
+ RETURN result;
288
+ END IF;
289
+ IF jsonb_typeof(value) = 'object' AND value ? keys[1] THEN
290
+ RETURN jsonb_set(value, ARRAY[keys[1]], {s}.{p}mask_at(value -> keys[1], keys[2:]), false);
291
+ END IF;
292
+ RETURN value;
293
+ END;
294
+ $$;
295
+
296
+ CREATE OR REPLACE FUNCTION {s}.{p}mask(attributes jsonb, paths jsonb) RETURNS jsonb
297
+ LANGUAGE plpgsql IMMUTABLE AS $$
298
+ DECLARE
299
+ masked jsonb := attributes;
300
+ path jsonb;
301
+ keys text[];
302
+ BEGIN
303
+ FOR path IN SELECT jsonb_array_elements(coalesce(paths, '[]'::jsonb)) LOOP
304
+ SELECT array_agg(key ORDER BY ordinal) INTO keys FROM jsonb_array_elements_text(path) WITH ORDINALITY AS part(key, ordinal);
305
+ masked := {s}.{p}mask_at(masked, keys);
306
+ END LOOP;
307
+ RETURN masked;
308
+ END;
309
+ $$;
310
+
311
+ CREATE OR REPLACE VIEW {s}.{v}resources_current AS
312
+ SELECT e.state_id, e.address, e.stack_id, e.type, e.name, e.provider, e.revision, e.incarnation, e.status,
313
+ e.object_identity, {s}.{p}mask(e.entry -> 'attributes', e.sensitive_paths) AS attributes,
314
+ e.entry -> 'dependencies' AS dependencies, e.run_id, e.sequence, e.updated_at, e.intent_fp, e.inputs, e.applied_fp
315
+ FROM {s}.{p}entries e WHERE NOT e.tombstone;
316
+
317
+ CREATE OR REPLACE VIEW {s}.{v}outputs_current AS
318
+ SELECT o.state_id, o.key, o.revision,
319
+ CASE WHEN o.sensitive THEN '"(sensitive)"'::jsonb ELSE o.value -> 'value' END AS value,
320
+ o.sensitive, o.run_id, o.sequence, o.updated_at, o.intent_fp, o.inputs, o.applied_fp, o.status
321
+ FROM {s}.{p}outputs o WHERE NOT o.tombstone;
322
+
323
+ CREATE OR REPLACE VIEW {s}.{v}history AS
324
+ SELECT v.state_id, v.kind, v.key, v.revision, v.sequence, v.run_id, v.op_id, v.tombstone, v.committed_at,
325
+ r.operation, r.actor,
326
+ CASE
327
+ WHEN v.kind = 'resource' THEN {s}.{p}mask(v.row_data -> 'attributes', v.sensitive_paths)
328
+ WHEN coalesce((v.row_data ->> 'sensitive')::boolean, false) THEN '"(sensitive)"'::jsonb
329
+ ELSE v.row_data -> 'value'
330
+ END AS value, v.intent_fp, v.inputs, v.applied_fp, v.status
331
+ FROM {s}.{p}versions v LEFT JOIN {s}.{p}runs r ON r.run_id = v.run_id;
332
+
333
+ CREATE VIEW {s}.{v}dependencies AS
334
+ SELECT e.state_id, e.address AS dependent, 'resource'::text AS dependent_kind,
335
+ input ->> 'kind' AS kind, input ->> 'key' AS target, input ->> 'revision' AS consumed_revision
336
+ FROM {s}.{p}entries e CROSS JOIN LATERAL jsonb_array_elements(e.inputs) input WHERE NOT e.tombstone
337
+ UNION ALL
338
+ SELECT o.state_id, o.key AS dependent, 'output'::text AS dependent_kind,
339
+ input ->> 'kind' AS kind, input ->> 'key' AS target, input ->> 'revision' AS consumed_revision
340
+ FROM {s}.{p}outputs o CROSS JOIN LATERAL jsonb_array_elements(o.inputs) input WHERE NOT o.tombstone;
341
+ UPDATE {s}.{p}apps SET schema_version = 4;
342
+ """
343
+
344
+ #: Version 5: replacement triggers distinguish completed operations from metadata-only revisions.
345
+ V5 = """
346
+ ALTER TABLE {s}.{p}entries ADD COLUMN mutation_revision bigint NOT NULL DEFAULT 0;
347
+ ALTER TABLE {s}.{p}versions ADD COLUMN mutation_revision bigint NOT NULL DEFAULT 0;
348
+ -- Legacy history may have pruned the operation's version. Current revision is a
349
+ -- conservative bound in that case, so an outstanding trigger cannot be lost.
350
+ UPDATE {s}.{p}entries e SET mutation_revision = coalesce((
351
+ SELECT max(v.revision) FROM {s}.{p}versions v
352
+ WHERE v.state_id = e.state_id AND v.kind = 'resource' AND v.key = e.address AND v.op_id IS NOT NULL
353
+ ), e.revision);
354
+ UPDATE {s}.{p}versions v SET mutation_revision = coalesce((
355
+ SELECT max(m.revision) FROM {s}.{p}versions m
356
+ WHERE m.state_id = v.state_id AND m.kind = 'resource' AND m.key = v.key
357
+ AND m.revision <= v.revision AND m.op_id IS NOT NULL
358
+ ), 0) WHERE v.kind = 'resource';
359
+ CREATE OR REPLACE VIEW {s}.{v}resources_current AS
360
+ SELECT e.state_id, e.address, e.stack_id, e.type, e.name, e.provider, e.revision, e.incarnation, e.status,
361
+ e.object_identity, {s}.{p}mask(e.entry -> 'attributes', e.sensitive_paths) AS attributes,
362
+ e.entry -> 'dependencies' AS dependencies, e.run_id, e.sequence, e.updated_at, e.intent_fp,
363
+ e.inputs, e.applied_fp, e.mutation_revision
364
+ FROM {s}.{p}entries e WHERE NOT e.tombstone;
365
+ UPDATE {s}.{p}apps SET schema_version = 5;
366
+ """
367
+
368
+ #: Version 6: ownership without leases, atomic requests and the fair lease queue.
369
+ V6 = """
370
+ ALTER TABLE {s}.{p}runs ADD COLUMN lease_phase text NOT NULL DEFAULT 'granted' CHECK (lease_phase IN ('pending', 'granted'));
371
+ ALTER TABLE {s}.{p}runs ADD COLUMN lease_set jsonb;
372
+ UPDATE {s}.{p}runs SET lease_set = '{{"app":"X"}}'::jsonb WHERE lease_phase = 'granted';
373
+ ALTER TABLE {s}.{p}leases ADD COLUMN ticket bigint;
374
+ CREATE TABLE {s}.{p}lease_queue (
375
+ ticket bigserial PRIMARY KEY,
376
+ state_id text NOT NULL REFERENCES {s}.{p}apps (state_id),
377
+ run_id text NOT NULL UNIQUE REFERENCES {s}.{p}runs (run_id),
378
+ epoch bigint NOT NULL,
379
+ request jsonb NOT NULL,
380
+ requested_at timestamptz NOT NULL DEFAULT clock_timestamp()
381
+ );
382
+ CREATE INDEX {p}lease_queue_state ON {s}.{p}lease_queue (state_id, ticket);
383
+ CREATE VIEW {s}.{v}leases AS
384
+ SELECT state_id, key, holder, mode, acquired_at, ticket FROM {s}.{p}leases;
385
+ CREATE VIEW {s}.{v}lease_queue AS
386
+ SELECT state_id, ticket, run_id, epoch, request, requested_at FROM {s}.{p}lease_queue;
387
+ UPDATE {s}.{p}apps SET schema_version = 6;
388
+ """
389
+
390
+ #: Version 7: authoritative reverse predicates, maintained even by document/state edits.
391
+ V7 = r"""
392
+ CREATE TABLE {s}.{p}edges (
393
+ state_id text NOT NULL REFERENCES {s}.{p}apps (state_id),
394
+ target_kind text NOT NULL CHECK (target_kind IN ('resource', 'output', 'scope', 'enumeration')),
395
+ target text NOT NULL,
396
+ dependent_kind text NOT NULL CHECK (dependent_kind IN ('resource', 'output')),
397
+ dependent text NOT NULL,
398
+ PRIMARY KEY (state_id, target_kind, target, dependent_kind, dependent)
399
+ );
400
+ CREATE INDEX {p}edges_dependent ON {s}.{p}edges (state_id, dependent_kind, dependent);
401
+ CREATE TABLE {s}.{p}edge_generations (
402
+ state_id text NOT NULL REFERENCES {s}.{p}apps (state_id),
403
+ target_kind text NOT NULL,
404
+ target text NOT NULL,
405
+ generation bigint NOT NULL,
406
+ PRIMARY KEY (state_id, target_kind, target)
407
+ );
408
+
409
+ CREATE FUNCTION {s}.{p}set_edges(app text, kind text, address text, inputs jsonb, dependencies jsonb, deleted boolean)
410
+ RETURNS void LANGUAGE plpgsql AS $$
411
+ DECLARE
412
+ wanted jsonb := '[]'::jsonb;
413
+ changed jsonb := '[]'::jsonb;
414
+ item jsonb;
415
+ dependency text;
416
+ dependency_kind text;
417
+ edge record;
418
+ BEGIN
419
+ IF NOT deleted THEN
420
+ IF inputs IS NULL OR inputs = 'null'::jsonb THEN
421
+ wanted := '[{{"kind":"scope","key":"app"}}]'::jsonb;
422
+ ELSIF jsonb_typeof(inputs) <> 'array' THEN
423
+ RAISE EXCEPTION 'Malformed authoritative graph inputs';
424
+ ELSE
425
+ FOR item IN SELECT value FROM jsonb_array_elements(inputs) LOOP
426
+ IF item ->> 'kind' NOT IN ('resource', 'output', 'scope', 'enumeration')
427
+ OR coalesce(item ->> 'key', '') = '' OR item ->> 'kind' IS NULL
428
+ OR (item ->> 'kind' IN ('scope', 'enumeration') AND item ->> 'key' <> 'app'
429
+ AND item ->> 'key' NOT LIKE 'stack:_%') THEN
430
+ RAISE EXCEPTION 'Malformed authoritative graph input target';
431
+ END IF;
432
+ wanted := wanted || jsonb_build_object('kind', item ->> 'kind', 'key', item ->> 'key');
433
+ END LOOP;
434
+ END IF;
435
+ FOR dependency IN SELECT jsonb_array_elements_text(coalesce(dependencies, '[]'::jsonb)) LOOP
436
+ IF dependency ~ '^.+\.[^.\s\[\]]+\.[^.\s\[\]]+$' THEN
437
+ dependency_kind := CASE WHEN dependency ~ '\.output\.[^.]+$' THEN 'output' ELSE 'resource' END;
438
+ wanted := wanted || jsonb_build_object('kind', dependency_kind, 'key', dependency);
439
+ ELSE
440
+ wanted := wanted || '{{"kind":"scope","key":"app"}}'::jsonb;
441
+ END IF;
442
+ END LOOP;
443
+ END IF;
444
+ FOR edge IN
445
+ DELETE FROM {s}.{p}edges e
446
+ WHERE e.state_id = app AND e.dependent_kind = kind AND e.dependent = address
447
+ AND NOT EXISTS (SELECT 1 FROM jsonb_array_elements(wanted) w WHERE w ->> 'kind' = e.target_kind AND w ->> 'key' = e.target)
448
+ RETURNING e.target_kind, e.target
449
+ LOOP
450
+ changed := changed || jsonb_build_object('kind', edge.target_kind, 'key', edge.target);
451
+ END LOOP;
452
+ FOR edge IN
453
+ INSERT INTO {s}.{p}edges (state_id, target_kind, target, dependent_kind, dependent)
454
+ SELECT DISTINCT app, w ->> 'kind', w ->> 'key', kind, address FROM jsonb_array_elements(wanted) w
455
+ ON CONFLICT DO NOTHING RETURNING target_kind, target
456
+ LOOP
457
+ changed := changed || jsonb_build_object('kind', edge.target_kind, 'key', edge.target);
458
+ END LOOP;
459
+ INSERT INTO {s}.{p}edge_generations (state_id, target_kind, target, generation)
460
+ SELECT DISTINCT app, w ->> 'kind', w ->> 'key', 1 FROM jsonb_array_elements(changed) w
461
+ ON CONFLICT (state_id, target_kind, target) DO UPDATE SET generation = {p}edge_generations.generation + 1;
462
+ END;
463
+ $$;
464
+
465
+ CREATE FUNCTION {s}.{p}resource_edges() RETURNS trigger LANGUAGE plpgsql AS $$
466
+ BEGIN
467
+ IF TG_OP = 'DELETE' THEN
468
+ PERFORM {s}.{p}set_edges(OLD.state_id, 'resource', OLD.address, NULL, NULL, true);
469
+ RETURN OLD;
470
+ END IF;
471
+ PERFORM {s}.{p}set_edges(NEW.state_id, 'resource', NEW.address, NEW.inputs, NEW.entry -> 'dependencies', NEW.tombstone);
472
+ RETURN NEW;
473
+ END;
474
+ $$;
475
+ CREATE FUNCTION {s}.{p}output_edges() RETURNS trigger LANGUAGE plpgsql AS $$
476
+ BEGIN
477
+ IF TG_OP = 'DELETE' THEN
478
+ PERFORM {s}.{p}set_edges(OLD.state_id, 'output', OLD.key, NULL, NULL, true);
479
+ RETURN OLD;
480
+ END IF;
481
+ PERFORM {s}.{p}set_edges(NEW.state_id, 'output', NEW.key, NEW.inputs, NULL, NEW.tombstone);
482
+ RETURN NEW;
483
+ END;
484
+ $$;
485
+ CREATE TRIGGER {p}resource_edges AFTER INSERT OR UPDATE OF inputs, entry, tombstone OR DELETE ON {s}.{p}entries
486
+ FOR EACH ROW EXECUTE FUNCTION {s}.{p}resource_edges();
487
+ CREATE TRIGGER {p}output_edges AFTER INSERT OR UPDATE OF inputs, tombstone OR DELETE ON {s}.{p}outputs
488
+ FOR EACH ROW EXECUTE FUNCTION {s}.{p}output_edges();
489
+ SELECT {s}.{p}set_edges(state_id, 'resource', address, inputs, entry -> 'dependencies', tombstone) FROM {s}.{p}entries;
490
+ SELECT {s}.{p}set_edges(state_id, 'output', key, inputs, NULL, tombstone) FROM {s}.{p}outputs;
491
+ CREATE OR REPLACE VIEW {s}.{v}dependencies AS
492
+ SELECT e.state_id, e.dependent, e.dependent_kind, e.target_kind AS kind, e.target,
493
+ consumed.value ->> 'revision' AS consumed_revision
494
+ FROM {s}.{p}edges e
495
+ LEFT JOIN {s}.{p}entries r ON e.dependent_kind = 'resource' AND r.state_id = e.state_id AND r.address = e.dependent
496
+ LEFT JOIN {s}.{p}outputs o ON e.dependent_kind = 'output' AND o.state_id = e.state_id AND o.key = e.dependent
497
+ LEFT JOIN LATERAL (
498
+ SELECT input AS value FROM jsonb_array_elements(
499
+ CASE WHEN jsonb_typeof(coalesce(r.inputs, o.inputs)) = 'array' THEN coalesce(r.inputs, o.inputs) ELSE '[]'::jsonb END
500
+ ) input WHERE input ->> 'kind' = e.target_kind AND input ->> 'key' = e.target LIMIT 1
501
+ ) consumed ON true;
502
+ CREATE VIEW {s}.{v}edge_generations AS SELECT state_id, target_kind AS kind, target, generation FROM {s}.{p}edge_generations;
503
+ UPDATE {s}.{p}apps SET schema_version = 7;
504
+ """
505
+
506
+ #: Version 8: scoped reads detect value and membership ABA without metadata churn.
507
+ V8 = """
508
+ ALTER TABLE {s}.{p}entries ADD COLUMN value_revision bigint NOT NULL DEFAULT 0;
509
+ ALTER TABLE {s}.{p}entries ADD COLUMN membership_revision bigint NOT NULL DEFAULT 0;
510
+ ALTER TABLE {s}.{p}outputs ADD COLUMN value_revision bigint NOT NULL DEFAULT 0;
511
+ ALTER TABLE {s}.{p}outputs ADD COLUMN membership_revision bigint NOT NULL DEFAULT 0;
512
+ ALTER TABLE {s}.{p}versions ADD COLUMN value_revision bigint NOT NULL DEFAULT 0;
513
+ ALTER TABLE {s}.{p}versions ADD COLUMN membership_revision bigint NOT NULL DEFAULT 0;
514
+ UPDATE {s}.{p}entries SET value_revision = revision, membership_revision = revision;
515
+ UPDATE {s}.{p}outputs SET value_revision = revision, membership_revision = revision;
516
+ UPDATE {s}.{p}versions SET value_revision = revision, membership_revision = revision;
517
+
518
+ CREATE FUNCTION {s}.{p}resource_value_revisions() RETURNS trigger LANGUAGE plpgsql AS $$
519
+ BEGIN
520
+ IF TG_OP = 'INSERT' THEN
521
+ NEW.value_revision := NEW.revision;
522
+ NEW.membership_revision := NEW.revision;
523
+ ELSE
524
+ NEW.value_revision := CASE WHEN
525
+ ROW(OLD.tombstone, OLD.incarnation, OLD.provider, OLD.private_digest, OLD.entry -> 'attributes') IS DISTINCT FROM
526
+ ROW(NEW.tombstone, NEW.incarnation, NEW.provider, NEW.private_digest, NEW.entry -> 'attributes')
527
+ THEN NEW.revision ELSE OLD.value_revision END;
528
+ NEW.membership_revision := CASE WHEN OLD.tombstone IS DISTINCT FROM NEW.tombstone
529
+ THEN NEW.revision ELSE OLD.membership_revision END;
530
+ END IF;
531
+ RETURN NEW;
532
+ END;
533
+ $$;
534
+ CREATE FUNCTION {s}.{p}output_value_revisions() RETURNS trigger LANGUAGE plpgsql AS $$
535
+ BEGIN
536
+ IF TG_OP = 'INSERT' THEN
537
+ NEW.value_revision := NEW.revision;
538
+ NEW.membership_revision := NEW.revision;
539
+ ELSE
540
+ NEW.value_revision := CASE WHEN ROW(OLD.tombstone, OLD.value) IS DISTINCT FROM ROW(NEW.tombstone, NEW.value)
541
+ THEN NEW.revision ELSE OLD.value_revision END;
542
+ NEW.membership_revision := CASE WHEN OLD.tombstone IS DISTINCT FROM NEW.tombstone
543
+ THEN NEW.revision ELSE OLD.membership_revision END;
544
+ END IF;
545
+ RETURN NEW;
546
+ END;
547
+ $$;
548
+ CREATE TRIGGER {p}resource_value_revisions BEFORE INSERT OR UPDATE ON {s}.{p}entries
549
+ FOR EACH ROW EXECUTE FUNCTION {s}.{p}resource_value_revisions();
550
+ CREATE TRIGGER {p}output_value_revisions BEFORE INSERT OR UPDATE ON {s}.{p}outputs
551
+ FOR EACH ROW EXECUTE FUNCTION {s}.{p}output_value_revisions();
552
+ CREATE OR REPLACE VIEW {s}.{v}resources_current AS
553
+ SELECT e.state_id, e.address, e.stack_id, e.type, e.name, e.provider, e.revision, e.incarnation, e.status,
554
+ e.object_identity, {s}.{p}mask(e.entry -> 'attributes', e.sensitive_paths) AS attributes,
555
+ e.entry -> 'dependencies' AS dependencies, e.run_id, e.sequence, e.updated_at, e.intent_fp,
556
+ e.inputs, e.applied_fp, e.mutation_revision, e.value_revision, e.membership_revision
557
+ FROM {s}.{p}entries e WHERE NOT e.tombstone;
558
+ CREATE OR REPLACE VIEW {s}.{v}outputs_current AS
559
+ SELECT o.state_id, o.key, o.revision,
560
+ CASE WHEN o.sensitive THEN '"(sensitive)"'::jsonb ELSE o.value -> 'value' END AS value,
561
+ o.sensitive, o.run_id, o.sequence, o.updated_at, o.intent_fp, o.inputs, o.applied_fp, o.status,
562
+ o.value_revision, o.membership_revision
563
+ FROM {s}.{p}outputs o WHERE NOT o.tombstone;
564
+ CREATE OR REPLACE VIEW {s}.{v}history AS
565
+ SELECT v.state_id, v.kind, v.key, v.revision, v.sequence, v.run_id, v.op_id, v.tombstone, v.committed_at,
566
+ r.operation, r.actor,
567
+ CASE
568
+ WHEN v.kind = 'resource' THEN {s}.{p}mask(v.row_data -> 'attributes', v.sensitive_paths)
569
+ WHEN coalesce((v.row_data ->> 'sensitive')::boolean, false) THEN '"(sensitive)"'::jsonb
570
+ ELSE v.row_data -> 'value'
571
+ END AS value, v.intent_fp, v.inputs, v.applied_fp, v.status, v.mutation_revision,
572
+ v.value_revision, v.membership_revision
573
+ FROM {s}.{p}versions v LEFT JOIN {s}.{p}runs r ON r.run_id = v.run_id;
574
+ UPDATE {s}.{p}apps SET schema_version = 8;
575
+ """
576
+
577
+ #: Version 9: retain a run's grant after the first dispatch or durable commit.
578
+ V9 = """
579
+ CREATE TABLE {s}.{p}run_mutations (
580
+ run_id text PRIMARY KEY REFERENCES {s}.{p}runs (run_id),
581
+ state_id text NOT NULL REFERENCES {s}.{p}apps (state_id),
582
+ started_at timestamptz NOT NULL,
583
+ cause text NOT NULL
584
+ );
585
+ INSERT INTO {s}.{p}run_mutations (run_id, state_id, started_at, cause)
586
+ SELECT r.run_id, r.state_id, clock_timestamp(), 'legacy_mutation'
587
+ FROM {s}.{p}runs r
588
+ WHERE EXISTS (SELECT 1 FROM {s}.{p}commits c WHERE c.run_id = r.run_id)
589
+ OR EXISTS (SELECT 1 FROM {s}.{p}operations o WHERE o.state_id = r.state_id AND o.epoch = r.epoch
590
+ AND (o.dispatched_at IS NOT NULL OR o.stage IN ('returned', 'delete_committed', 'committed')));
591
+
592
+ -- A separate marker avoids upgrading the run's SHARE fence to UPDATE when
593
+ -- several operations dispatch concurrently within one run. It also lets old
594
+ -- writers participate: the marker is written in their existing transaction.
595
+ CREATE FUNCTION {s}.{p}note_operation_mutation() RETURNS trigger LANGUAGE plpgsql AS $$
596
+ BEGIN
597
+ IF NEW.dispatched_at IS NOT NULL OR NEW.stage IN ('dispatched', 'delete_dispatched', 'create_dispatched', 'returned', 'delete_committed', 'committed') THEN
598
+ INSERT INTO {s}.{p}run_mutations (run_id, state_id, started_at, cause)
599
+ SELECT r.run_id, r.state_id, clock_timestamp(), 'provider_dispatch'
600
+ FROM {s}.{p}runs r WHERE r.state_id = NEW.state_id AND r.epoch = NEW.epoch
601
+ ON CONFLICT (run_id) DO NOTHING;
602
+ END IF;
603
+ RETURN NEW;
604
+ END;
605
+ $$;
606
+ CREATE TRIGGER {p}operation_mutation AFTER INSERT OR UPDATE OF stage ON {s}.{p}operations
607
+ FOR EACH ROW EXECUTE FUNCTION {s}.{p}note_operation_mutation();
608
+ CREATE FUNCTION {s}.{p}note_commit_mutation() RETURNS trigger LANGUAGE plpgsql AS $$
609
+ BEGIN
610
+ INSERT INTO {s}.{p}run_mutations (run_id, state_id, started_at, cause)
611
+ VALUES (NEW.run_id, NEW.state_id, NEW.committed_at, 'state_commit')
612
+ ON CONFLICT (run_id) DO NOTHING;
613
+ RETURN NEW;
614
+ END;
615
+ $$;
616
+ CREATE TRIGGER {p}commit_mutation AFTER INSERT ON {s}.{p}commits
617
+ FOR EACH ROW EXECUTE FUNCTION {s}.{p}note_commit_mutation();
618
+ CREATE OR REPLACE VIEW {s}.{v}runs AS
619
+ SELECT r.run_id, r.state_id, r.epoch, r.operation, r.actor, r.host, r.status, r.started_at, r.expires_at,
620
+ r.ended_at, r.providers_killed_at, m.started_at AS mutation_started_at, m.cause AS mutation_cause
621
+ FROM {s}.{p}runs r LEFT JOIN {s}.{p}run_mutations m ON m.run_id = r.run_id;
622
+ UPDATE {s}.{p}apps SET schema_version = 9;
623
+ """
624
+
625
+ #: Version 10: canonical cloud ownership requires a participating writer.
626
+ V10 = """
627
+ CREATE INDEX {p}entries_graph_bound ON {s}.{p}entries (state_id, type)
628
+ WHERE NOT tombstone AND coalesce(entry #> '{{metadata,graph_object}}', 'null'::jsonb) <> 'null'::jsonb;
629
+ CREATE INDEX {p}entries_graph_legacy ON {s}.{p}entries (state_id, type)
630
+ WHERE NOT tombstone AND (object_identity IS NULL OR object_identity NOT LIKE 'nf-object-v1:%');
631
+ CREATE FUNCTION {s}.{p}require_identity_writer() RETURNS trigger LANGUAGE plpgsql AS $$
632
+ BEGIN
633
+ IF current_setting('netherframe.graph_identity_protocol', true) IS DISTINCT FROM '1' THEN
634
+ RAISE EXCEPTION 'Graph cloud ownership requires an updated writer; upgrade Netherframe before dispatching or writing state';
635
+ END IF;
636
+ RETURN NEW;
637
+ END;
638
+ $$;
639
+ CREATE TRIGGER {p}identity_writer_entry BEFORE INSERT OR UPDATE ON {s}.{p}entries
640
+ FOR EACH ROW EXECUTE FUNCTION {s}.{p}require_identity_writer();
641
+ -- An old owner may still return a call sent before the migration. Keep that
642
+ -- result recoverable, while refusing its next dispatch or state claim.
643
+ CREATE TRIGGER {p}identity_writer_operation BEFORE INSERT OR UPDATE OF stage ON {s}.{p}operations
644
+ FOR EACH ROW WHEN (NEW.stage IN ('reserved', 'dispatched', 'delete_dispatched', 'create_dispatched'))
645
+ EXECUTE FUNCTION {s}.{p}require_identity_writer();
646
+ UPDATE {s}.{p}apps SET schema_version = 10;
647
+ """
648
+
649
+ #: Version 11: operation footprints persist independently of run grants.
650
+ V11 = """
651
+ CREATE OR REPLACE FUNCTION {s}.{p}require_identity_writer() RETURNS trigger LANGUAGE plpgsql AS $$
652
+ BEGIN
653
+ IF current_setting('netherframe.graph_identity_protocol', true) IS DISTINCT FROM '2' THEN
654
+ RAISE EXCEPTION 'Graph operation footprint validation requires an updated writer; upgrade Netherframe before dispatching or writing state';
655
+ END IF;
656
+ RETURN NEW;
657
+ END;
658
+ $$;
659
+ CREATE FUNCTION {s}.{p}protect_operation_request() RETURNS trigger LANGUAGE plpgsql AS $$
660
+ BEGIN
661
+ IF TG_OP = 'UPDATE' AND (NEW.request IS DISTINCT FROM OLD.request OR NEW.request_digest IS DISTINCT FROM OLD.request_digest) THEN
662
+ RAISE EXCEPTION 'An operation request and its lease footprint are immutable';
663
+ END IF;
664
+ IF TG_OP = 'INSERT' THEN
665
+ IF jsonb_typeof(NEW.request -> 'lease_footprint') IS DISTINCT FROM 'object'
666
+ OR NOT (NEW.request -> 'lease_footprint' ? 'app') THEN
667
+ RAISE EXCEPTION 'An operation requires its complete lease footprint before reservation';
668
+ END IF;
669
+ END IF;
670
+ RETURN NEW;
671
+ END;
672
+ $$;
673
+ CREATE TRIGGER {p}operation_request_immutable BEFORE INSERT OR UPDATE OF request, request_digest ON {s}.{p}operations
674
+ FOR EACH ROW EXECUTE FUNCTION {s}.{p}protect_operation_request();
675
+ CREATE VIEW {s}.{v}operation_leases AS
676
+ SELECT o.state_id, o.op_id, o.run_id, o.recovered_by, o.stage, lease.key, lease.value AS mode
677
+ FROM {s}.{p}operations o
678
+ CROSS JOIN LATERAL jsonb_each_text(coalesce(o.request -> 'lease_footprint', '{{"app":"X"}}'::jsonb)) lease
679
+ WHERE o.stage NOT IN ('committed', 'aborted');
680
+ UPDATE {s}.{p}apps SET schema_version = 11;
681
+ """
682
+
683
+ #: Version 12: recovery attempts have their own fenced operation claims.
684
+ V12 = """
685
+ CREATE OR REPLACE FUNCTION {s}.{p}require_identity_writer() RETURNS trigger LANGUAGE plpgsql AS $$
686
+ BEGIN
687
+ IF current_setting('netherframe.graph_identity_protocol', true) IS DISTINCT FROM '3' THEN
688
+ RAISE EXCEPTION 'Graph recovery claim validation requires an updated writer; upgrade Netherframe before dispatching or writing state';
689
+ END IF;
690
+ RETURN NEW;
691
+ END;
692
+ $$;
693
+ CREATE FUNCTION {s}.{p}protect_operation_owner() RETURNS trigger LANGUAGE plpgsql AS $$
694
+ BEGIN
695
+ IF current_setting('netherframe.graph_identity_protocol', true) IS DISTINCT FROM '3' THEN
696
+ -- Keep an original call's result after an online upgrade, but do not
697
+ -- let an obsolete recoverer steal or resolve another attempt's claim.
698
+ IF TG_OP = 'UPDATE' AND OLD.recovered_by IS NULL
699
+ AND OLD.stage IN ('dispatched', 'delete_dispatched', 'create_dispatched')
700
+ AND NEW.stage = 'returned' AND NEW.epoch = OLD.epoch AND NEW.attempt = OLD.attempt
701
+ AND NEW.recovered_by IS NOT DISTINCT FROM OLD.recovered_by THEN
702
+ RETURN NEW;
703
+ END IF;
704
+ RAISE EXCEPTION 'Graph recovery claim validation requires an updated writer; upgrade Netherframe before changing operation ownership or resolution';
705
+ END IF;
706
+ RETURN NEW;
707
+ END;
708
+ $$;
709
+ CREATE TRIGGER {p}operation_owner BEFORE INSERT OR UPDATE OF epoch, attempt, recovered_by, stage ON {s}.{p}operations
710
+ FOR EACH ROW EXECUTE FUNCTION {s}.{p}protect_operation_owner();
711
+ UPDATE {s}.{p}apps SET schema_version = 12;
712
+ """
713
+
714
+ #: Version 13: a partial grant mutates only through an immutable admitted plan.
715
+ V13 = """
716
+ ALTER TABLE {s}.{p}runs ADD COLUMN admitted_plan jsonb;
717
+ CREATE INDEX {p}active_plan_baseline ON {s}.{p}runs (state_id, (admitted_plan #>> '{{baseline,pin_id}}'))
718
+ WHERE status = 'active' AND admitted_plan IS NOT NULL;
719
+ CREATE OR REPLACE FUNCTION {s}.{p}require_identity_writer() RETURNS trigger LANGUAGE plpgsql AS $$
720
+ BEGIN
721
+ IF current_setting('netherframe.graph_identity_protocol', true) IS DISTINCT FROM '4' THEN
722
+ RAISE EXCEPTION 'Graph plan admission requires an updated writer; upgrade Netherframe before dispatching or writing state';
723
+ END IF;
724
+ RETURN NEW;
725
+ END;
726
+ $$;
727
+ CREATE OR REPLACE FUNCTION {s}.{p}protect_operation_owner() RETURNS trigger LANGUAGE plpgsql AS $$
728
+ BEGIN
729
+ IF current_setting('netherframe.graph_identity_protocol', true) IS DISTINCT FROM '4' THEN
730
+ IF TG_OP = 'UPDATE' AND OLD.recovered_by IS NULL
731
+ AND OLD.stage IN ('dispatched', 'delete_dispatched', 'create_dispatched')
732
+ AND NEW.stage = 'returned' AND NEW.epoch = OLD.epoch AND NEW.attempt = OLD.attempt
733
+ AND NEW.recovered_by IS NOT DISTINCT FROM OLD.recovered_by THEN
734
+ RETURN NEW;
735
+ END IF;
736
+ RAISE EXCEPTION 'Graph plan admission requires an updated writer; upgrade Netherframe before changing operation ownership or resolution';
737
+ END IF;
738
+ RETURN NEW;
739
+ END;
740
+ $$;
741
+ CREATE FUNCTION {s}.{p}protect_plan_admission() RETURNS trigger LANGUAGE plpgsql AS $$
742
+ BEGIN
743
+ IF NEW.admitted_plan IS NOT DISTINCT FROM OLD.admitted_plan THEN
744
+ RETURN NEW;
745
+ END IF;
746
+ IF current_setting('netherframe.graph_identity_protocol', true) IS DISTINCT FROM '4' THEN
747
+ RAISE EXCEPTION 'Graph plan admission requires an updated writer';
748
+ END IF;
749
+ IF EXISTS (SELECT 1 FROM {s}.{p}run_mutations m WHERE m.run_id = OLD.run_id)
750
+ OR EXISTS (SELECT 1 FROM {s}.{p}operations o WHERE (o.run_id = OLD.run_id OR o.recovered_by = OLD.run_id)
751
+ AND o.stage NOT IN ('committed', 'aborted')) THEN
752
+ RAISE EXCEPTION 'An admitted plan cannot change after reserving operations or mutating state';
753
+ END IF;
754
+ IF OLD.admitted_plan IS NOT NULL AND NEW.admitted_plan IS NOT NULL THEN
755
+ RAISE EXCEPTION 'Release the entire grant and admission before replanning';
756
+ END IF;
757
+ IF NEW.admitted_plan IS NOT NULL AND NEW.lease_phase <> 'granted' THEN
758
+ RAISE EXCEPTION 'Plan admission requires a complete granted lease set';
759
+ END IF;
760
+ RETURN NEW;
761
+ END;
762
+ $$;
763
+ CREATE TRIGGER {p}plan_admission BEFORE UPDATE OF admitted_plan ON {s}.{p}runs
764
+ FOR EACH ROW EXECUTE FUNCTION {s}.{p}protect_plan_admission();
765
+ CREATE OR REPLACE VIEW {s}.{v}runs AS
766
+ SELECT r.run_id, r.state_id, r.epoch, r.operation, r.actor, r.host, r.status, r.started_at, r.expires_at,
767
+ r.ended_at, r.providers_killed_at, m.started_at AS mutation_started_at, m.cause AS mutation_cause,
768
+ r.admitted_plan -> 'baseline' AS baseline, r.admitted_plan -> 'basis' AS plan_basis
769
+ FROM {s}.{p}runs r LEFT JOIN {s}.{p}run_mutations m ON m.run_id = r.run_id;
770
+ UPDATE {s}.{p}apps SET schema_version = 13;
771
+ """
772
+
773
+ #: Version 14: obsolete writers must not replay operation-backed errored rows.
774
+ V14 = """
775
+ CREATE OR REPLACE FUNCTION {s}.{p}require_identity_writer() RETURNS trigger LANGUAGE plpgsql AS $$
776
+ BEGIN
777
+ IF current_setting('netherframe.graph_identity_protocol', true) IS DISTINCT FROM '5' THEN
778
+ RAISE EXCEPTION 'Kept operation recovery requires an updated writer; upgrade Netherframe before dispatching or writing state';
779
+ END IF;
780
+ RETURN NEW;
781
+ END;
782
+ $$;
783
+ CREATE OR REPLACE FUNCTION {s}.{p}protect_operation_owner() RETURNS trigger LANGUAGE plpgsql AS $$
784
+ BEGIN
785
+ IF current_setting('netherframe.graph_identity_protocol', true) IS DISTINCT FROM '5' THEN
786
+ IF TG_OP = 'UPDATE' AND OLD.recovered_by IS NULL
787
+ AND OLD.stage IN ('dispatched', 'delete_dispatched', 'create_dispatched')
788
+ AND NEW.stage = 'returned' AND NEW.epoch = OLD.epoch AND NEW.attempt = OLD.attempt
789
+ AND NEW.recovered_by IS NOT DISTINCT FROM OLD.recovered_by THEN
790
+ RETURN NEW;
791
+ END IF;
792
+ RAISE EXCEPTION 'Kept operation recovery requires an updated writer; upgrade Netherframe before changing operation ownership or resolution';
793
+ END IF;
794
+ RETURN NEW;
795
+ END;
796
+ $$;
797
+ CREATE OR REPLACE FUNCTION {s}.{p}protect_plan_admission() RETURNS trigger LANGUAGE plpgsql AS $$
798
+ BEGIN
799
+ IF NEW.admitted_plan IS NOT DISTINCT FROM OLD.admitted_plan THEN
800
+ RETURN NEW;
801
+ END IF;
802
+ IF current_setting('netherframe.graph_identity_protocol', true) IS DISTINCT FROM '5' THEN
803
+ RAISE EXCEPTION 'Kept operation recovery requires an updated writer';
804
+ END IF;
805
+ IF EXISTS (SELECT 1 FROM {s}.{p}run_mutations m WHERE m.run_id = OLD.run_id)
806
+ OR EXISTS (SELECT 1 FROM {s}.{p}operations o WHERE (o.run_id = OLD.run_id OR o.recovered_by = OLD.run_id)
807
+ AND o.stage NOT IN ('committed', 'aborted')) THEN
808
+ RAISE EXCEPTION 'An admitted plan cannot change after reserving operations or mutating state';
809
+ END IF;
810
+ IF OLD.admitted_plan IS NOT NULL AND NEW.admitted_plan IS NOT NULL THEN
811
+ RAISE EXCEPTION 'Release the entire grant and admission before replanning';
812
+ END IF;
813
+ IF NEW.admitted_plan IS NOT NULL AND NEW.lease_phase <> 'granted' THEN
814
+ RAISE EXCEPTION 'Plan admission requires a complete granted lease set';
815
+ END IF;
816
+ RETURN NEW;
817
+ END;
818
+ $$;
819
+ UPDATE {s}.{p}apps SET schema_version = 14;
820
+ """
821
+
822
+ #: Version 15: every new grant accounts for retained operation holders.
823
+ V15 = """
824
+ CREATE FUNCTION {s}.{p}require_operation_queue_writer() RETURNS trigger LANGUAGE plpgsql AS $$
825
+ BEGIN
826
+ IF current_setting('netherframe.graph_queue_protocol', true) IS DISTINCT FROM '1' THEN
827
+ RAISE EXCEPTION 'Operation-aware lease admission requires an updated writer; upgrade Netherframe before acquiring a grant';
828
+ END IF;
829
+ RETURN NEW;
830
+ END;
831
+ $$;
832
+ CREATE TRIGGER {p}operation_queue_writer BEFORE INSERT OR UPDATE ON {s}.{p}leases
833
+ FOR EACH ROW EXECUTE FUNCTION {s}.{p}require_operation_queue_writer();
834
+ UPDATE {s}.{p}apps SET schema_version = 15;
835
+ """
836
+
837
+ #: Version 16: every rollback-enabled create retains its compensation coverage.
838
+ V16 = """
839
+ CREATE OR REPLACE FUNCTION {s}.{p}require_identity_writer() RETURNS trigger LANGUAGE plpgsql AS $$
840
+ BEGIN
841
+ IF current_setting('netherframe.graph_identity_protocol', true) IS DISTINCT FROM '6' THEN
842
+ RAISE EXCEPTION 'Pre-acquired rollback compensation requires an updated writer; upgrade Netherframe before dispatching or writing state';
843
+ END IF;
844
+ RETURN NEW;
845
+ END;
846
+ $$;
847
+ CREATE OR REPLACE FUNCTION {s}.{p}protect_operation_owner() RETURNS trigger LANGUAGE plpgsql AS $$
848
+ BEGIN
849
+ IF current_setting('netherframe.graph_identity_protocol', true) IS DISTINCT FROM '6' THEN
850
+ IF TG_OP = 'UPDATE' AND OLD.recovered_by IS NULL
851
+ AND OLD.stage IN ('dispatched', 'delete_dispatched', 'create_dispatched')
852
+ AND NEW.stage = 'returned' AND NEW.epoch = OLD.epoch AND NEW.attempt = OLD.attempt
853
+ AND NEW.recovered_by IS NOT DISTINCT FROM OLD.recovered_by THEN
854
+ RETURN NEW;
855
+ END IF;
856
+ RAISE EXCEPTION 'Pre-acquired rollback compensation requires an updated writer; upgrade Netherframe before changing operation ownership or resolution';
857
+ END IF;
858
+ RETURN NEW;
859
+ END;
860
+ $$;
861
+ CREATE OR REPLACE FUNCTION {s}.{p}protect_plan_admission() RETURNS trigger LANGUAGE plpgsql AS $$
862
+ BEGIN
863
+ IF NEW.admitted_plan IS NOT DISTINCT FROM OLD.admitted_plan THEN
864
+ RETURN NEW;
865
+ END IF;
866
+ IF current_setting('netherframe.graph_identity_protocol', true) IS DISTINCT FROM '6' THEN
867
+ RAISE EXCEPTION 'Pre-acquired rollback compensation requires an updated writer';
868
+ END IF;
869
+ IF EXISTS (SELECT 1 FROM {s}.{p}run_mutations m WHERE m.run_id = OLD.run_id)
870
+ OR EXISTS (SELECT 1 FROM {s}.{p}operations o WHERE (o.run_id = OLD.run_id OR o.recovered_by = OLD.run_id)
871
+ AND o.stage NOT IN ('committed', 'aborted')) THEN
872
+ RAISE EXCEPTION 'An admitted plan cannot change after reserving operations or mutating state';
873
+ END IF;
874
+ IF OLD.admitted_plan IS NOT NULL AND NEW.admitted_plan IS NOT NULL THEN
875
+ RAISE EXCEPTION 'Release the entire grant and admission before replanning';
876
+ END IF;
877
+ IF NEW.admitted_plan IS NOT NULL AND NEW.lease_phase <> 'granted' THEN
878
+ RAISE EXCEPTION 'Plan admission requires a complete granted lease set';
879
+ END IF;
880
+ RETURN NEW;
881
+ END;
882
+ $$;
883
+ UPDATE {s}.{p}apps SET schema_version = 16;
884
+ """
885
+
886
+ #: Version 17: pinned write sets, durable restore receipts and consumer evidence.
887
+ V17 = """
888
+
889
+ ALTER TABLE {s}.{p}operations ADD COLUMN reservation bigint GENERATED ALWAYS AS IDENTITY;
890
+ CREATE INDEX {p}operations_reservation ON {s}.{p}operations (state_id, reservation);
891
+ CREATE TABLE {s}.{p}checkpoints (
892
+ state_id text NOT NULL REFERENCES {s}.{p}apps (state_id),
893
+ checkpoint_id text PRIMARY KEY,
894
+ checkpoint_order bigint GENERATED ALWAYS AS IDENTITY,
895
+ run_id text NOT NULL,
896
+ sequence bigint NOT NULL,
897
+ operation_frontier bigint NOT NULL,
898
+ manifest jsonb NOT NULL,
899
+ keep_count integer NOT NULL CHECK (keep_count > 0),
900
+ created_at timestamptz NOT NULL DEFAULT clock_timestamp()
901
+ );
902
+ CREATE INDEX {p}checkpoints_state ON {s}.{p}checkpoints (state_id, checkpoint_order);
903
+ CREATE OR REPLACE VIEW {s}.{v}checkpoints AS
904
+ SELECT state_id, checkpoint_id, run_id, sequence, operation_frontier, manifest, created_at FROM {s}.{p}checkpoints;
905
+ CREATE TABLE {s}.{p}checkpoint_restores (
906
+ state_id text NOT NULL REFERENCES {s}.{p}apps (state_id),
907
+ run_id text NOT NULL,
908
+ checkpoint_id text NOT NULL,
909
+ force boolean NOT NULL,
910
+ sequence bigint NOT NULL,
911
+ PRIMARY KEY (state_id, run_id)
912
+ );
913
+ CREATE OR REPLACE VIEW {s}.{v}checkpoint_restores AS
914
+ SELECT state_id, run_id, checkpoint_id, force, sequence FROM {s}.{p}checkpoint_restores;
915
+ CREATE FUNCTION {s}.{p}protect_checkpoint_pin() RETURNS trigger LANGUAGE plpgsql AS $$
916
+ BEGIN
917
+ IF current_setting('netherframe.graph_identity_protocol', true) IS DISTINCT FROM '7' THEN
918
+ RAISE EXCEPTION 'Pinned history restore requires an updated writer';
919
+ END IF;
920
+ IF TG_OP = 'UPDATE' THEN
921
+ RAISE EXCEPTION 'A checkpoint origin and write set are immutable';
922
+ END IF;
923
+ IF TG_OP = 'DELETE' THEN
924
+ IF EXISTS (SELECT 1 FROM {s}.{p}runs r WHERE r.run_id = OLD.run_id AND r.status = 'active' AND r.expires_at > clock_timestamp())
925
+ OR EXISTS (SELECT 1 FROM {s}.{p}operations o WHERE o.state_id = OLD.state_id AND o.run_id = OLD.run_id AND o.stage NOT IN ('committed', 'aborted'))
926
+ OR EXISTS (SELECT 1 FROM {s}.{p}checkpoint_restores x JOIN {s}.{p}runs r USING (run_id) WHERE x.state_id = OLD.state_id AND x.checkpoint_id = OLD.checkpoint_id AND r.status = 'active' AND r.expires_at > clock_timestamp()) THEN
927
+ RAISE EXCEPTION 'An active run or unresolved operation still uses this checkpoint';
928
+ END IF;
929
+ RETURN OLD;
930
+ END IF;
931
+ RETURN NEW;
932
+ END;
933
+ $$;
934
+ CREATE TRIGGER {p}checkpoint_pin BEFORE INSERT OR UPDATE OR DELETE ON {s}.{p}checkpoints
935
+ FOR EACH ROW EXECUTE FUNCTION {s}.{p}protect_checkpoint_pin();
936
+ CREATE FUNCTION {s}.{p}protect_checkpoint_evidence() RETURNS trigger LANGUAGE plpgsql AS $$
937
+ BEGIN
938
+ IF current_setting('netherframe.graph_identity_protocol', true) IS DISTINCT FROM '7' THEN
939
+ RAISE EXCEPTION 'Pinned history retention requires an updated writer';
940
+ END IF;
941
+ IF TG_TABLE_NAME = '{p}versions' THEN
942
+ IF EXISTS (SELECT 1 FROM {s}.{p}checkpoints c WHERE c.state_id = OLD.state_id AND jsonb_array_length(c.manifest -> 'targets') > 0
943
+ AND (OLD.sequence > c.sequence OR EXISTS (SELECT 1 FROM jsonb_to_recordset(c.manifest -> 'targets') AS t(kind text, key text, revision bigint)
944
+ WHERE (t.kind, t.key, t.revision) = (OLD.kind, OLD.key, OLD.revision)))) THEN
945
+ RAISE EXCEPTION 'A pinned checkpoint still needs this version or consumer history';
946
+ END IF;
947
+ ELSE
948
+ IF OLD.stage NOT IN ('committed', 'aborted')
949
+ OR EXISTS (SELECT 1 FROM {s}.{p}runs r WHERE r.run_id IN (OLD.run_id, OLD.recovered_by) AND r.status = 'active' AND r.expires_at > clock_timestamp())
950
+ OR EXISTS (SELECT 1 FROM {s}.{p}checkpoints c WHERE c.state_id = OLD.state_id AND jsonb_array_length(c.manifest -> 'targets') > 0 AND OLD.reservation > c.operation_frontier) THEN
951
+ RAISE EXCEPTION 'A live run, unresolved operation or pinned checkpoint still needs this operation';
952
+ END IF;
953
+ END IF;
954
+ RETURN OLD;
955
+ END;
956
+ $$;
957
+ CREATE TRIGGER {p}checkpoint_versions BEFORE DELETE ON {s}.{p}versions
958
+ FOR EACH ROW EXECUTE FUNCTION {s}.{p}protect_checkpoint_evidence();
959
+ CREATE TRIGGER {p}checkpoint_operations BEFORE DELETE ON {s}.{p}operations
960
+ FOR EACH ROW EXECUTE FUNCTION {s}.{p}protect_checkpoint_evidence();
961
+ CREATE FUNCTION {s}.{p}protect_checkpoint_receipt() RETURNS trigger LANGUAGE plpgsql AS $$
962
+ BEGIN
963
+ IF current_setting('netherframe.graph_identity_protocol', true) IS DISTINCT FROM '7' THEN
964
+ RAISE EXCEPTION 'Pinned history restore requires an updated writer';
965
+ END IF;
966
+ IF TG_OP = 'UPDATE' THEN
967
+ RAISE EXCEPTION 'A restore receipt is immutable';
968
+ END IF;
969
+ IF TG_OP = 'DELETE' THEN
970
+ IF EXISTS (SELECT 1 FROM {s}.{p}runs r WHERE r.run_id = OLD.run_id AND r.status = 'active' AND r.expires_at > clock_timestamp()) THEN
971
+ RAISE EXCEPTION 'An active run still uses this restore receipt';
972
+ END IF;
973
+ RETURN OLD;
974
+ END IF;
975
+ RETURN NEW;
976
+ END;
977
+ $$;
978
+ CREATE TRIGGER {p}checkpoint_restore_writer BEFORE INSERT OR UPDATE OR DELETE ON {s}.{p}checkpoint_restores
979
+ FOR EACH ROW EXECUTE FUNCTION {s}.{p}protect_checkpoint_receipt();
980
+ CREATE OR REPLACE FUNCTION {s}.{p}require_identity_writer() RETURNS trigger LANGUAGE plpgsql AS $$
981
+ BEGIN
982
+ IF current_setting('netherframe.graph_identity_protocol', true) IS DISTINCT FROM '7' THEN
983
+ RAISE EXCEPTION 'Pinned history restore requires an updated writer; upgrade Netherframe before dispatching or writing state';
984
+ END IF;
985
+ RETURN NEW;
986
+ END;
987
+ $$;
988
+ CREATE OR REPLACE FUNCTION {s}.{p}protect_operation_owner() RETURNS trigger LANGUAGE plpgsql AS $$
989
+ BEGIN
990
+ IF current_setting('netherframe.graph_identity_protocol', true) IS DISTINCT FROM '7' THEN
991
+ IF TG_OP = 'UPDATE' AND OLD.recovered_by IS NULL
992
+ AND OLD.stage IN ('dispatched', 'delete_dispatched', 'create_dispatched')
993
+ AND NEW.stage = 'returned' AND NEW.epoch = OLD.epoch AND NEW.attempt = OLD.attempt
994
+ AND NEW.recovered_by IS NOT DISTINCT FROM OLD.recovered_by THEN
995
+ RETURN NEW;
996
+ END IF;
997
+ RAISE EXCEPTION 'Pinned history restore requires an updated writer; upgrade Netherframe before changing operation ownership or resolution';
998
+ END IF;
999
+ RETURN NEW;
1000
+ END;
1001
+ $$;
1002
+ CREATE OR REPLACE FUNCTION {s}.{p}protect_plan_admission() RETURNS trigger LANGUAGE plpgsql AS $$
1003
+ BEGIN
1004
+ IF NEW.admitted_plan IS NOT DISTINCT FROM OLD.admitted_plan THEN
1005
+ RETURN NEW;
1006
+ END IF;
1007
+ IF current_setting('netherframe.graph_identity_protocol', true) IS DISTINCT FROM '7' THEN
1008
+ RAISE EXCEPTION 'Pinned history restore requires an updated writer';
1009
+ END IF;
1010
+ IF EXISTS (SELECT 1 FROM {s}.{p}run_mutations m WHERE m.run_id = OLD.run_id)
1011
+ OR EXISTS (SELECT 1 FROM {s}.{p}operations o WHERE (o.run_id = OLD.run_id OR o.recovered_by = OLD.run_id)
1012
+ AND o.stage NOT IN ('committed', 'aborted')) THEN
1013
+ RAISE EXCEPTION 'An admitted plan cannot change after reserving operations or mutating state';
1014
+ END IF;
1015
+ IF OLD.admitted_plan IS NOT NULL AND NEW.admitted_plan IS NOT NULL THEN
1016
+ RAISE EXCEPTION 'Release the entire grant and admission before replanning';
1017
+ END IF;
1018
+ IF NEW.admitted_plan IS NOT NULL AND NEW.lease_phase <> 'granted' THEN
1019
+ RAISE EXCEPTION 'Plan admission requires a complete granted lease set';
1020
+ END IF;
1021
+ RETURN NEW;
1022
+ END;
1023
+ $$;
1024
+ UPDATE {s}.{p}apps SET schema_version = 17;
1025
+ """
1026
+
1027
+ #: Version 18: staged, fenced, resumable cross-backend state transfers.
1028
+ V18 = """
1029
+ ALTER TABLE {s}.{p}apps ADD COLUMN transfer_id text;
1030
+ ALTER TABLE {s}.{p}apps ADD COLUMN transfers jsonb NOT NULL DEFAULT '{{}}'::jsonb;
1031
+ CREATE TABLE {s}.{p}migration_guards (state_id text PRIMARY KEY REFERENCES {s}.{p}apps(state_id), migrated_to text);
1032
+ INSERT INTO {s}.{p}migration_guards (state_id, migrated_to) SELECT state_id, migrated_to FROM {s}.{p}apps;
1033
+ CREATE FUNCTION {s}.{p}initialize_migration_guard() RETURNS trigger LANGUAGE plpgsql AS $$
1034
+ BEGIN
1035
+ INSERT INTO {s}.{p}migration_guards (state_id, migrated_to) VALUES (NEW.state_id, NEW.migrated_to) ON CONFLICT DO NOTHING;
1036
+ RETURN NEW;
1037
+ END;
1038
+ $$;
1039
+ CREATE TRIGGER {p}initialize_migration_guard AFTER INSERT ON {s}.{p}apps
1040
+ FOR EACH ROW EXECUTE FUNCTION {s}.{p}initialize_migration_guard();
1041
+ CREATE FUNCTION {s}.{p}synchronize_migration_guard() RETURNS trigger LANGUAGE plpgsql AS $$
1042
+ BEGIN
1043
+ UPDATE {s}.{p}migration_guards SET migrated_to = NEW.migrated_to WHERE state_id = NEW.state_id;
1044
+ RETURN NEW;
1045
+ END;
1046
+ $$;
1047
+ CREATE TRIGGER {p}synchronize_migration_guard AFTER UPDATE OF migrated_to ON {s}.{p}apps
1048
+ FOR EACH ROW EXECUTE FUNCTION {s}.{p}synchronize_migration_guard();
1049
+ CREATE FUNCTION {s}.{p}protect_migration_guard() RETURNS trigger LANGUAGE plpgsql AS $$
1050
+ BEGIN
1051
+ IF TG_OP = 'DELETE' THEN
1052
+ RAISE EXCEPTION 'A migration guard cannot be removed';
1053
+ END IF;
1054
+ IF NEW.migrated_to IS DISTINCT FROM (SELECT migrated_to FROM {s}.{p}apps WHERE state_id = NEW.state_id) THEN
1055
+ RAISE EXCEPTION 'A migration guard must match its app fence';
1056
+ END IF;
1057
+ RETURN NEW;
1058
+ END;
1059
+ $$;
1060
+ CREATE TRIGGER {p}protect_migration_guard BEFORE UPDATE OR DELETE ON {s}.{p}migration_guards
1061
+ FOR EACH ROW EXECUTE FUNCTION {s}.{p}protect_migration_guard();
1062
+ CREATE OR REPLACE FUNCTION {s}.{p}protect_checkpoint_pin() RETURNS trigger LANGUAGE plpgsql AS $$
1063
+ BEGIN
1064
+ IF current_setting('netherframe.graph_identity_protocol', true) IS DISTINCT FROM '8' THEN
1065
+ RAISE EXCEPTION 'Migration cutover requires an updated writer';
1066
+ END IF;
1067
+ IF TG_OP = 'UPDATE' THEN
1068
+ RAISE EXCEPTION 'A checkpoint origin and write set are immutable';
1069
+ END IF;
1070
+ IF TG_OP = 'DELETE' THEN
1071
+ IF EXISTS (SELECT 1 FROM {s}.{p}runs r WHERE r.run_id = OLD.run_id AND r.status = 'active' AND r.expires_at > clock_timestamp())
1072
+ OR EXISTS (SELECT 1 FROM {s}.{p}operations o WHERE o.state_id = OLD.state_id AND o.run_id = OLD.run_id AND o.stage NOT IN ('committed', 'aborted'))
1073
+ OR EXISTS (SELECT 1 FROM {s}.{p}checkpoint_restores x JOIN {s}.{p}runs r USING (run_id) WHERE x.state_id = OLD.state_id AND x.checkpoint_id = OLD.checkpoint_id AND r.status = 'active' AND r.expires_at > clock_timestamp()) THEN
1074
+ RAISE EXCEPTION 'An active run or unresolved operation still uses this checkpoint';
1075
+ END IF;
1076
+ RETURN OLD;
1077
+ END IF;
1078
+ RETURN NEW;
1079
+ END;
1080
+ $$;
1081
+ CREATE OR REPLACE FUNCTION {s}.{p}protect_checkpoint_evidence() RETURNS trigger LANGUAGE plpgsql AS $$
1082
+ BEGIN
1083
+ IF current_setting('netherframe.graph_identity_protocol', true) IS DISTINCT FROM '8' THEN
1084
+ RAISE EXCEPTION 'Migration cutover requires an updated writer';
1085
+ END IF;
1086
+ IF TG_TABLE_NAME = '{p}versions' THEN
1087
+ IF EXISTS (SELECT 1 FROM {s}.{p}checkpoints c WHERE c.state_id = OLD.state_id AND jsonb_array_length(c.manifest -> 'targets') > 0
1088
+ AND (OLD.sequence > c.sequence OR EXISTS (SELECT 1 FROM jsonb_to_recordset(c.manifest -> 'targets') AS t(kind text, key text, revision bigint)
1089
+ WHERE (t.kind, t.key, t.revision) = (OLD.kind, OLD.key, OLD.revision)))) THEN
1090
+ RAISE EXCEPTION 'A pinned checkpoint still needs this version or consumer history';
1091
+ END IF;
1092
+ ELSE
1093
+ IF OLD.stage NOT IN ('committed', 'aborted')
1094
+ OR EXISTS (SELECT 1 FROM {s}.{p}runs r WHERE r.run_id IN (OLD.run_id, OLD.recovered_by) AND r.status = 'active' AND r.expires_at > clock_timestamp())
1095
+ OR EXISTS (SELECT 1 FROM {s}.{p}checkpoints c WHERE c.state_id = OLD.state_id AND jsonb_array_length(c.manifest -> 'targets') > 0 AND OLD.reservation > c.operation_frontier) THEN
1096
+ RAISE EXCEPTION 'A live run, unresolved operation or pinned checkpoint still needs this operation';
1097
+ END IF;
1098
+ END IF;
1099
+ RETURN OLD;
1100
+ END;
1101
+ $$;
1102
+ CREATE OR REPLACE FUNCTION {s}.{p}protect_checkpoint_receipt() RETURNS trigger LANGUAGE plpgsql AS $$
1103
+ BEGIN
1104
+ IF current_setting('netherframe.graph_identity_protocol', true) IS DISTINCT FROM '8' THEN
1105
+ RAISE EXCEPTION 'Migration cutover requires an updated writer';
1106
+ END IF;
1107
+ IF TG_OP = 'UPDATE' THEN
1108
+ RAISE EXCEPTION 'A restore receipt is immutable';
1109
+ END IF;
1110
+ IF TG_OP = 'DELETE' THEN
1111
+ IF EXISTS (SELECT 1 FROM {s}.{p}runs r WHERE r.run_id = OLD.run_id AND r.status = 'active' AND r.expires_at > clock_timestamp()) THEN
1112
+ RAISE EXCEPTION 'An active run still uses this restore receipt';
1113
+ END IF;
1114
+ RETURN OLD;
1115
+ END IF;
1116
+ RETURN NEW;
1117
+ END;
1118
+ $$;
1119
+ CREATE OR REPLACE FUNCTION {s}.{p}require_identity_writer() RETURNS trigger LANGUAGE plpgsql AS $$
1120
+ BEGIN
1121
+ IF current_setting('netherframe.graph_identity_protocol', true) IS DISTINCT FROM '8' THEN
1122
+ RAISE EXCEPTION 'Migration cutover requires an updated writer; upgrade Netherframe before dispatching or writing state';
1123
+ END IF;
1124
+ IF TG_OP = 'DELETE' THEN
1125
+ RETURN OLD;
1126
+ END IF;
1127
+ RETURN NEW;
1128
+ END;
1129
+ $$;
1130
+ CREATE OR REPLACE FUNCTION {s}.{p}protect_operation_owner() RETURNS trigger LANGUAGE plpgsql AS $$
1131
+ BEGIN
1132
+ IF current_setting('netherframe.graph_identity_protocol', true) IS DISTINCT FROM '8' THEN
1133
+ IF TG_OP = 'UPDATE' AND OLD.recovered_by IS NULL
1134
+ AND OLD.stage IN ('dispatched', 'delete_dispatched', 'create_dispatched')
1135
+ AND NEW.stage = 'returned' AND NEW.epoch = OLD.epoch AND NEW.attempt = OLD.attempt
1136
+ AND NEW.recovered_by IS NOT DISTINCT FROM OLD.recovered_by THEN
1137
+ RETURN NEW;
1138
+ END IF;
1139
+ RAISE EXCEPTION 'Migration cutover requires an updated writer; upgrade Netherframe before changing operation ownership or resolution';
1140
+ END IF;
1141
+ RETURN NEW;
1142
+ END;
1143
+ $$;
1144
+ CREATE OR REPLACE FUNCTION {s}.{p}protect_plan_admission() RETURNS trigger LANGUAGE plpgsql AS $$
1145
+ BEGIN
1146
+ IF NEW.admitted_plan IS NOT DISTINCT FROM OLD.admitted_plan THEN
1147
+ RETURN NEW;
1148
+ END IF;
1149
+ IF current_setting('netherframe.graph_identity_protocol', true) IS DISTINCT FROM '8' THEN
1150
+ RAISE EXCEPTION 'Migration cutover requires an updated writer';
1151
+ END IF;
1152
+ IF EXISTS (SELECT 1 FROM {s}.{p}run_mutations m WHERE m.run_id = OLD.run_id)
1153
+ OR EXISTS (SELECT 1 FROM {s}.{p}operations o WHERE (o.run_id = OLD.run_id OR o.recovered_by = OLD.run_id)
1154
+ AND o.stage NOT IN ('committed', 'aborted')) THEN
1155
+ RAISE EXCEPTION 'An admitted plan cannot change after reserving operations or mutating state';
1156
+ END IF;
1157
+ IF OLD.admitted_plan IS NOT NULL AND NEW.admitted_plan IS NOT NULL THEN
1158
+ RAISE EXCEPTION 'Release the entire grant and admission before replanning';
1159
+ END IF;
1160
+ IF NEW.admitted_plan IS NOT NULL AND NEW.lease_phase <> 'granted' THEN
1161
+ RAISE EXCEPTION 'Plan admission requires a complete granted lease set';
1162
+ END IF;
1163
+ RETURN NEW;
1164
+ END;
1165
+ $$;
1166
+ CREATE TRIGGER {p}transfer_app_writer BEFORE UPDATE OF frontier, metadata, migrated_to, transfer_id, transfers ON {s}.{p}apps
1167
+ FOR EACH ROW EXECUTE FUNCTION {s}.{p}require_identity_writer();
1168
+ CREATE TRIGGER {p}transfer_output_writer BEFORE INSERT OR UPDATE OR DELETE ON {s}.{p}outputs
1169
+ FOR EACH ROW EXECUTE FUNCTION {s}.{p}require_identity_writer();
1170
+ CREATE TRIGGER {p}transfer_observation_writer BEFORE INSERT OR UPDATE OR DELETE ON {s}.{p}observations
1171
+ FOR EACH ROW EXECUTE FUNCTION {s}.{p}require_identity_writer();
1172
+ CREATE OR REPLACE VIEW {s}.{v}state_transfers AS
1173
+ SELECT a.state_id, entry.key AS transfer_id, entry.value ->> 'side' AS side,
1174
+ entry.value ->> 'phase' AS phase, entry.value -> 'transfer' AS receipt
1175
+ FROM {s}.{p}apps a CROSS JOIN LATERAL jsonb_each(a.transfers) entry;
1176
+ CREATE FUNCTION {s}.{p}protect_transfer_receipts() RETURNS trigger LANGUAGE plpgsql AS $$
1177
+ DECLARE
1178
+ item record;
1179
+ next_receipt jsonb;
1180
+ BEGIN
1181
+ FOR item IN SELECT key, value FROM jsonb_each(OLD.transfers) LOOP
1182
+ next_receipt := NEW.transfers -> item.key;
1183
+ IF next_receipt IS NULL OR (next_receipt - 'phase') IS DISTINCT FROM (item.value - 'phase') THEN
1184
+ RAISE EXCEPTION 'Migration receipts cannot be removed or rewritten';
1185
+ END IF;
1186
+ IF next_receipt ->> 'phase' IS DISTINCT FROM item.value ->> 'phase'
1187
+ AND NOT coalesce(((item.value ->> 'phase' = 'staged' AND next_receipt ->> 'phase' IN ('published', 'aborted'))
1188
+ OR (item.value ->> 'phase' = 'fenced' AND next_receipt ->> 'phase' = 'complete')), false) THEN
1189
+ RAISE EXCEPTION 'Migration receipt phase cannot be replayed';
1190
+ END IF;
1191
+ END LOOP;
1192
+ IF OLD.transfer_id IS NOT NULL AND OLD.transfers #>> ARRAY[OLD.transfer_id, 'side'] = 'source'
1193
+ AND (NEW.transfer_id IS DISTINCT FROM OLD.transfer_id OR NEW.migrated_to IS DISTINCT FROM OLD.migrated_to) THEN
1194
+ RAISE EXCEPTION 'A migration source fence cannot be lifted or redirected';
1195
+ END IF;
1196
+ IF OLD.transfer_id IS NOT NULL AND OLD.transfers #>> ARRAY[OLD.transfer_id, 'phase'] = 'staged'
1197
+ AND (NEW.transfer_id IS DISTINCT FROM OLD.transfer_id OR NEW.migrated_to IS DISTINCT FROM OLD.migrated_to) THEN
1198
+ IF NOT coalesce(((NEW.transfer_id IS NULL AND NEW.migrated_to IS NULL AND NEW.transfers #>> ARRAY[OLD.transfer_id, 'phase'] = 'published')
1199
+ OR (NEW.transfer_id IS NOT NULL AND NEW.migrated_to IS NOT NULL
1200
+ AND NEW.transfers #>> ARRAY[OLD.transfer_id, 'phase'] = 'aborted'
1201
+ AND NEW.transfers #>> ARRAY[NEW.transfer_id, 'phase'] = 'staged')), false) THEN
1202
+ RAISE EXCEPTION 'A staged destination fence requires atomic publication or restaging';
1203
+ END IF;
1204
+ END IF;
1205
+ RETURN NEW;
1206
+ END;
1207
+ $$;
1208
+ CREATE TRIGGER {p}transfer_receipts BEFORE UPDATE OF transfers, migrated_to, transfer_id ON {s}.{p}apps
1209
+ FOR EACH ROW EXECUTE FUNCTION {s}.{p}protect_transfer_receipts();
1210
+ UPDATE {s}.{p}apps SET schema_version = 18;
1211
+ """
1212
+
1213
+ V19 = """
1214
+ CREATE OR REPLACE FUNCTION {s}.{p}protect_checkpoint_pin() RETURNS trigger LANGUAGE plpgsql AS $$
1215
+ BEGIN
1216
+ IF current_setting('netherframe.graph_identity_protocol', true) IS DISTINCT FROM '9' THEN
1217
+ RAISE EXCEPTION 'Atomic move protocol requires an updated writer';
1218
+ END IF;
1219
+ IF TG_OP = 'UPDATE' THEN
1220
+ RAISE EXCEPTION 'A checkpoint origin and write set are immutable';
1221
+ END IF;
1222
+ IF TG_OP = 'DELETE' THEN
1223
+ IF EXISTS (SELECT 1 FROM {s}.{p}runs r WHERE r.run_id = OLD.run_id AND r.status = 'active' AND r.expires_at > clock_timestamp())
1224
+ OR EXISTS (SELECT 1 FROM {s}.{p}operations o WHERE o.state_id = OLD.state_id AND o.run_id = OLD.run_id AND o.stage NOT IN ('committed', 'aborted'))
1225
+ OR EXISTS (SELECT 1 FROM {s}.{p}checkpoint_restores x JOIN {s}.{p}runs r USING (run_id) WHERE x.state_id = OLD.state_id AND x.checkpoint_id = OLD.checkpoint_id AND r.status = 'active' AND r.expires_at > clock_timestamp()) THEN
1226
+ RAISE EXCEPTION 'An active run or unresolved operation still uses this checkpoint';
1227
+ END IF;
1228
+ RETURN OLD;
1229
+ END IF;
1230
+ RETURN NEW;
1231
+ END;
1232
+ $$;
1233
+ CREATE OR REPLACE FUNCTION {s}.{p}protect_checkpoint_evidence() RETURNS trigger LANGUAGE plpgsql AS $$
1234
+ BEGIN
1235
+ IF current_setting('netherframe.graph_identity_protocol', true) IS DISTINCT FROM '9' THEN
1236
+ RAISE EXCEPTION 'Atomic move protocol requires an updated writer';
1237
+ END IF;
1238
+ IF TG_TABLE_NAME = '{p}versions' THEN
1239
+ IF EXISTS (SELECT 1 FROM {s}.{p}checkpoints c WHERE c.state_id = OLD.state_id AND jsonb_array_length(c.manifest -> 'targets') > 0
1240
+ AND (OLD.sequence > c.sequence OR EXISTS (SELECT 1 FROM jsonb_to_recordset(c.manifest -> 'targets') AS t(kind text, key text, revision bigint)
1241
+ WHERE (t.kind, t.key, t.revision) = (OLD.kind, OLD.key, OLD.revision)))) THEN
1242
+ RAISE EXCEPTION 'A pinned checkpoint still needs this version or consumer history';
1243
+ END IF;
1244
+ ELSE
1245
+ IF OLD.stage NOT IN ('committed', 'aborted')
1246
+ OR EXISTS (SELECT 1 FROM {s}.{p}runs r WHERE r.run_id IN (OLD.run_id, OLD.recovered_by) AND r.status = 'active' AND r.expires_at > clock_timestamp())
1247
+ OR EXISTS (SELECT 1 FROM {s}.{p}checkpoints c WHERE c.state_id = OLD.state_id AND jsonb_array_length(c.manifest -> 'targets') > 0 AND OLD.reservation > c.operation_frontier) THEN
1248
+ RAISE EXCEPTION 'A live run, unresolved operation or pinned checkpoint still needs this operation';
1249
+ END IF;
1250
+ END IF;
1251
+ RETURN OLD;
1252
+ END;
1253
+ $$;
1254
+ CREATE OR REPLACE FUNCTION {s}.{p}protect_checkpoint_receipt() RETURNS trigger LANGUAGE plpgsql AS $$
1255
+ BEGIN
1256
+ IF current_setting('netherframe.graph_identity_protocol', true) IS DISTINCT FROM '9' THEN
1257
+ RAISE EXCEPTION 'Atomic move protocol requires an updated writer';
1258
+ END IF;
1259
+ IF TG_OP = 'UPDATE' THEN
1260
+ RAISE EXCEPTION 'A restore receipt is immutable';
1261
+ END IF;
1262
+ IF TG_OP = 'DELETE' THEN
1263
+ IF EXISTS (SELECT 1 FROM {s}.{p}runs r WHERE r.run_id = OLD.run_id AND r.status = 'active' AND r.expires_at > clock_timestamp()) THEN
1264
+ RAISE EXCEPTION 'An active run still uses this restore receipt';
1265
+ END IF;
1266
+ RETURN OLD;
1267
+ END IF;
1268
+ RETURN NEW;
1269
+ END;
1270
+ $$;
1271
+ CREATE OR REPLACE FUNCTION {s}.{p}require_identity_writer() RETURNS trigger LANGUAGE plpgsql AS $$
1272
+ BEGIN
1273
+ IF current_setting('netherframe.graph_identity_protocol', true) IS DISTINCT FROM '9' THEN
1274
+ RAISE EXCEPTION 'Atomic move protocol requires an updated writer; upgrade Netherframe before dispatching or writing state';
1275
+ END IF;
1276
+ IF TG_OP = 'DELETE' THEN
1277
+ RETURN OLD;
1278
+ END IF;
1279
+ RETURN NEW;
1280
+ END;
1281
+ $$;
1282
+ CREATE OR REPLACE FUNCTION {s}.{p}protect_operation_owner() RETURNS trigger LANGUAGE plpgsql AS $$
1283
+ BEGIN
1284
+ IF current_setting('netherframe.graph_identity_protocol', true) IS DISTINCT FROM '9' THEN
1285
+ IF TG_OP = 'UPDATE' AND OLD.recovered_by IS NULL
1286
+ AND OLD.stage IN ('dispatched', 'delete_dispatched', 'create_dispatched')
1287
+ AND NEW.stage = 'returned' AND NEW.epoch = OLD.epoch AND NEW.attempt = OLD.attempt
1288
+ AND NEW.recovered_by IS NOT DISTINCT FROM OLD.recovered_by THEN
1289
+ RETURN NEW;
1290
+ END IF;
1291
+ RAISE EXCEPTION 'Atomic move protocol requires an updated writer; upgrade Netherframe before changing operation ownership or resolution';
1292
+ END IF;
1293
+ RETURN NEW;
1294
+ END;
1295
+ $$;
1296
+ CREATE OR REPLACE FUNCTION {s}.{p}protect_plan_admission() RETURNS trigger LANGUAGE plpgsql AS $$
1297
+ BEGIN
1298
+ IF NEW.admitted_plan IS NOT DISTINCT FROM OLD.admitted_plan THEN
1299
+ RETURN NEW;
1300
+ END IF;
1301
+ IF current_setting('netherframe.graph_identity_protocol', true) IS DISTINCT FROM '9' THEN
1302
+ RAISE EXCEPTION 'Atomic move protocol requires an updated writer';
1303
+ END IF;
1304
+ IF EXISTS (SELECT 1 FROM {s}.{p}run_mutations m WHERE m.run_id = OLD.run_id)
1305
+ OR EXISTS (SELECT 1 FROM {s}.{p}operations o WHERE (o.run_id = OLD.run_id OR o.recovered_by = OLD.run_id)
1306
+ AND o.stage NOT IN ('committed', 'aborted')) THEN
1307
+ RAISE EXCEPTION 'An admitted plan cannot change after reserving operations or mutating state';
1308
+ END IF;
1309
+ IF OLD.admitted_plan IS NOT NULL AND NEW.admitted_plan IS NOT NULL THEN
1310
+ RAISE EXCEPTION 'Release the entire grant and admission before replanning';
1311
+ END IF;
1312
+ IF NEW.admitted_plan IS NOT NULL AND NEW.lease_phase <> 'granted' THEN
1313
+ RAISE EXCEPTION 'Plan admission requires a complete granted lease set';
1314
+ END IF;
1315
+ RETURN NEW;
1316
+ END;
1317
+ $$;
1318
+ UPDATE {s}.{p}apps SET schema_version = 19;
1319
+ """
1320
+
1321
+ V20 = """
1322
+ ALTER TABLE {s}.{p}apps ADD COLUMN history_epoch bigint NOT NULL DEFAULT 0;
1323
+ CREATE OR REPLACE FUNCTION {s}.{p}protect_checkpoint_pin() RETURNS trigger LANGUAGE plpgsql AS $$
1324
+ BEGIN
1325
+ IF current_setting('netherframe.graph_identity_protocol', true) IS DISTINCT FROM '10' THEN
1326
+ RAISE EXCEPTION 'History administration requires an updated writer';
1327
+ END IF;
1328
+ IF TG_OP = 'UPDATE' THEN
1329
+ RAISE EXCEPTION 'A checkpoint origin and write set are immutable';
1330
+ END IF;
1331
+ IF TG_OP = 'DELETE' THEN
1332
+ IF EXISTS (SELECT 1 FROM {s}.{p}runs r WHERE r.run_id = OLD.run_id AND r.status = 'active' AND r.expires_at > clock_timestamp())
1333
+ OR EXISTS (SELECT 1 FROM {s}.{p}operations o WHERE o.state_id = OLD.state_id AND o.run_id = OLD.run_id AND o.stage NOT IN ('committed', 'aborted'))
1334
+ OR EXISTS (SELECT 1 FROM {s}.{p}checkpoint_restores x JOIN {s}.{p}runs r USING (run_id) WHERE x.state_id = OLD.state_id AND x.checkpoint_id = OLD.checkpoint_id AND r.status = 'active' AND r.expires_at > clock_timestamp()) THEN
1335
+ RAISE EXCEPTION 'An active run or unresolved operation still uses this checkpoint';
1336
+ END IF;
1337
+ RETURN OLD;
1338
+ END IF;
1339
+ RETURN NEW;
1340
+ END;
1341
+ $$;
1342
+ CREATE OR REPLACE FUNCTION {s}.{p}protect_checkpoint_evidence() RETURNS trigger LANGUAGE plpgsql AS $$
1343
+ BEGIN
1344
+ IF current_setting('netherframe.graph_identity_protocol', true) IS DISTINCT FROM '10' THEN
1345
+ RAISE EXCEPTION 'History administration requires an updated writer';
1346
+ END IF;
1347
+ IF TG_TABLE_NAME = '{p}versions' THEN
1348
+ IF EXISTS (SELECT 1 FROM {s}.{p}checkpoints c WHERE c.state_id = OLD.state_id AND jsonb_array_length(c.manifest -> 'targets') > 0
1349
+ AND (OLD.sequence > c.sequence OR EXISTS (SELECT 1 FROM jsonb_to_recordset(c.manifest -> 'targets') AS t(kind text, key text, revision bigint)
1350
+ WHERE (t.kind, t.key, t.revision) = (OLD.kind, OLD.key, OLD.revision)))) THEN
1351
+ RAISE EXCEPTION 'A pinned checkpoint still needs this version or consumer history';
1352
+ END IF;
1353
+ ELSE
1354
+ IF OLD.stage NOT IN ('committed', 'aborted')
1355
+ OR EXISTS (SELECT 1 FROM {s}.{p}runs r WHERE r.run_id IN (OLD.run_id, OLD.recovered_by) AND r.status = 'active' AND r.expires_at > clock_timestamp())
1356
+ OR EXISTS (SELECT 1 FROM {s}.{p}checkpoints c WHERE c.state_id = OLD.state_id AND jsonb_array_length(c.manifest -> 'targets') > 0 AND OLD.reservation > c.operation_frontier) THEN
1357
+ RAISE EXCEPTION 'A live run, unresolved operation or pinned checkpoint still needs this operation';
1358
+ END IF;
1359
+ END IF;
1360
+ RETURN OLD;
1361
+ END;
1362
+ $$;
1363
+ CREATE OR REPLACE FUNCTION {s}.{p}protect_checkpoint_receipt() RETURNS trigger LANGUAGE plpgsql AS $$
1364
+ BEGIN
1365
+ IF current_setting('netherframe.graph_identity_protocol', true) IS DISTINCT FROM '10' THEN
1366
+ RAISE EXCEPTION 'History administration requires an updated writer';
1367
+ END IF;
1368
+ IF TG_OP = 'UPDATE' THEN
1369
+ RAISE EXCEPTION 'A restore receipt is immutable';
1370
+ END IF;
1371
+ IF TG_OP = 'DELETE' THEN
1372
+ IF EXISTS (SELECT 1 FROM {s}.{p}runs r WHERE r.run_id = OLD.run_id AND r.status = 'active' AND r.expires_at > clock_timestamp()) THEN
1373
+ RAISE EXCEPTION 'An active run still uses this restore receipt';
1374
+ END IF;
1375
+ RETURN OLD;
1376
+ END IF;
1377
+ RETURN NEW;
1378
+ END;
1379
+ $$;
1380
+ CREATE OR REPLACE FUNCTION {s}.{p}require_identity_writer() RETURNS trigger LANGUAGE plpgsql AS $$
1381
+ BEGIN
1382
+ IF current_setting('netherframe.graph_identity_protocol', true) IS DISTINCT FROM '10' THEN
1383
+ RAISE EXCEPTION 'History administration requires an updated writer; upgrade Netherframe before dispatching or writing state';
1384
+ END IF;
1385
+ IF TG_OP = 'DELETE' THEN
1386
+ RETURN OLD;
1387
+ END IF;
1388
+ RETURN NEW;
1389
+ END;
1390
+ $$;
1391
+ CREATE OR REPLACE FUNCTION {s}.{p}protect_operation_owner() RETURNS trigger LANGUAGE plpgsql AS $$
1392
+ BEGIN
1393
+ IF current_setting('netherframe.graph_identity_protocol', true) IS DISTINCT FROM '10' THEN
1394
+ IF TG_OP = 'UPDATE' AND OLD.recovered_by IS NULL
1395
+ AND OLD.stage IN ('dispatched', 'delete_dispatched', 'create_dispatched')
1396
+ AND NEW.stage = 'returned' AND NEW.epoch = OLD.epoch AND NEW.attempt = OLD.attempt
1397
+ AND NEW.recovered_by IS NOT DISTINCT FROM OLD.recovered_by THEN
1398
+ RETURN NEW;
1399
+ END IF;
1400
+ RAISE EXCEPTION 'History administration requires an updated writer; upgrade Netherframe before changing operation ownership or resolution';
1401
+ END IF;
1402
+ RETURN NEW;
1403
+ END;
1404
+ $$;
1405
+ CREATE OR REPLACE FUNCTION {s}.{p}protect_plan_admission() RETURNS trigger LANGUAGE plpgsql AS $$
1406
+ BEGIN
1407
+ IF NEW.admitted_plan IS NOT DISTINCT FROM OLD.admitted_plan THEN
1408
+ RETURN NEW;
1409
+ END IF;
1410
+ IF current_setting('netherframe.graph_identity_protocol', true) IS DISTINCT FROM '10' THEN
1411
+ RAISE EXCEPTION 'History administration requires an updated writer';
1412
+ END IF;
1413
+ IF EXISTS (SELECT 1 FROM {s}.{p}run_mutations m WHERE m.run_id = OLD.run_id)
1414
+ OR EXISTS (SELECT 1 FROM {s}.{p}operations o WHERE (o.run_id = OLD.run_id OR o.recovered_by = OLD.run_id)
1415
+ AND o.stage NOT IN ('committed', 'aborted')) THEN
1416
+ RAISE EXCEPTION 'An admitted plan cannot change after reserving operations or mutating state';
1417
+ END IF;
1418
+ IF OLD.admitted_plan IS NOT NULL AND NEW.admitted_plan IS NOT NULL THEN
1419
+ RAISE EXCEPTION 'Release the entire grant and admission before replanning';
1420
+ END IF;
1421
+ IF NEW.admitted_plan IS NOT NULL AND NEW.lease_phase <> 'granted' THEN
1422
+ RAISE EXCEPTION 'Plan admission requires a complete granted lease set';
1423
+ END IF;
1424
+ RETURN NEW;
1425
+ END;
1426
+ $$;
1427
+ CREATE TRIGGER {p}history_admin_writer BEFORE UPDATE OF pruned_before, history_epoch ON {s}.{p}apps
1428
+ FOR EACH ROW EXECUTE FUNCTION {s}.{p}require_identity_writer();
1429
+ UPDATE {s}.{p}apps SET schema_version = 20;
1430
+ """
1431
+
1432
+ #: Version 21: fence writers that lack final ownership checks around complete SQL mutations.
1433
+ V21 = """
1434
+ CREATE OR REPLACE FUNCTION {s}.{p}protect_checkpoint_pin() RETURNS trigger LANGUAGE plpgsql AS $$
1435
+ BEGIN
1436
+ IF current_setting('netherframe.graph_identity_protocol', true) IS DISTINCT FROM '11' THEN
1437
+ RAISE EXCEPTION 'Owned transaction fencing requires an updated writer';
1438
+ END IF;
1439
+ IF TG_OP = 'UPDATE' THEN
1440
+ RAISE EXCEPTION 'A checkpoint origin and write set are immutable';
1441
+ END IF;
1442
+ IF TG_OP = 'DELETE' THEN
1443
+ IF EXISTS (SELECT 1 FROM {s}.{p}runs r WHERE r.run_id = OLD.run_id AND r.status = 'active' AND r.expires_at > clock_timestamp())
1444
+ OR EXISTS (SELECT 1 FROM {s}.{p}operations o WHERE o.state_id = OLD.state_id AND o.run_id = OLD.run_id AND o.stage NOT IN ('committed', 'aborted'))
1445
+ OR EXISTS (SELECT 1 FROM {s}.{p}checkpoint_restores x JOIN {s}.{p}runs r USING (run_id) WHERE x.state_id = OLD.state_id AND x.checkpoint_id = OLD.checkpoint_id AND r.status = 'active' AND r.expires_at > clock_timestamp()) THEN
1446
+ RAISE EXCEPTION 'An active run or unresolved operation still uses this checkpoint';
1447
+ END IF;
1448
+ RETURN OLD;
1449
+ END IF;
1450
+ RETURN NEW;
1451
+ END;
1452
+ $$;
1453
+ CREATE OR REPLACE FUNCTION {s}.{p}protect_checkpoint_evidence() RETURNS trigger LANGUAGE plpgsql AS $$
1454
+ BEGIN
1455
+ IF current_setting('netherframe.graph_identity_protocol', true) IS DISTINCT FROM '11' THEN
1456
+ RAISE EXCEPTION 'Owned transaction fencing requires an updated writer';
1457
+ END IF;
1458
+ IF TG_TABLE_NAME = '{p}versions' THEN
1459
+ IF EXISTS (SELECT 1 FROM {s}.{p}checkpoints c WHERE c.state_id = OLD.state_id AND jsonb_array_length(c.manifest -> 'targets') > 0
1460
+ AND (OLD.sequence > c.sequence OR EXISTS (SELECT 1 FROM jsonb_to_recordset(c.manifest -> 'targets') AS t(kind text, key text, revision bigint)
1461
+ WHERE (t.kind, t.key, t.revision) = (OLD.kind, OLD.key, OLD.revision)))) THEN
1462
+ RAISE EXCEPTION 'A pinned checkpoint still needs this version or consumer history';
1463
+ END IF;
1464
+ ELSE
1465
+ IF OLD.stage NOT IN ('committed', 'aborted')
1466
+ OR EXISTS (SELECT 1 FROM {s}.{p}runs r WHERE r.run_id IN (OLD.run_id, OLD.recovered_by) AND r.status = 'active' AND r.expires_at > clock_timestamp())
1467
+ OR EXISTS (SELECT 1 FROM {s}.{p}checkpoints c WHERE c.state_id = OLD.state_id AND jsonb_array_length(c.manifest -> 'targets') > 0 AND OLD.reservation > c.operation_frontier) THEN
1468
+ RAISE EXCEPTION 'A live run, unresolved operation or pinned checkpoint still needs this operation';
1469
+ END IF;
1470
+ END IF;
1471
+ RETURN OLD;
1472
+ END;
1473
+ $$;
1474
+ CREATE OR REPLACE FUNCTION {s}.{p}protect_checkpoint_receipt() RETURNS trigger LANGUAGE plpgsql AS $$
1475
+ BEGIN
1476
+ IF current_setting('netherframe.graph_identity_protocol', true) IS DISTINCT FROM '11' THEN
1477
+ RAISE EXCEPTION 'Owned transaction fencing requires an updated writer';
1478
+ END IF;
1479
+ IF TG_OP = 'UPDATE' THEN
1480
+ RAISE EXCEPTION 'A restore receipt is immutable';
1481
+ END IF;
1482
+ IF TG_OP = 'DELETE' THEN
1483
+ IF EXISTS (SELECT 1 FROM {s}.{p}runs r WHERE r.run_id = OLD.run_id AND r.status = 'active' AND r.expires_at > clock_timestamp()) THEN
1484
+ RAISE EXCEPTION 'An active run still uses this restore receipt';
1485
+ END IF;
1486
+ RETURN OLD;
1487
+ END IF;
1488
+ RETURN NEW;
1489
+ END;
1490
+ $$;
1491
+ CREATE OR REPLACE FUNCTION {s}.{p}require_identity_writer() RETURNS trigger LANGUAGE plpgsql AS $$
1492
+ BEGIN
1493
+ IF current_setting('netherframe.graph_identity_protocol', true) IS DISTINCT FROM '11' THEN
1494
+ RAISE EXCEPTION 'Owned transaction fencing requires an updated writer; upgrade Netherframe before dispatching or writing state';
1495
+ END IF;
1496
+ IF TG_OP = 'DELETE' THEN
1497
+ RETURN OLD;
1498
+ END IF;
1499
+ RETURN NEW;
1500
+ END;
1501
+ $$;
1502
+ CREATE OR REPLACE FUNCTION {s}.{p}protect_operation_owner() RETURNS trigger LANGUAGE plpgsql AS $$
1503
+ BEGIN
1504
+ IF current_setting('netherframe.graph_identity_protocol', true) IS DISTINCT FROM '11' THEN
1505
+ IF TG_OP = 'UPDATE' AND OLD.recovered_by IS NULL
1506
+ AND OLD.stage IN ('dispatched', 'delete_dispatched', 'create_dispatched')
1507
+ AND NEW.stage = 'returned' AND NEW.epoch = OLD.epoch AND NEW.attempt = OLD.attempt
1508
+ AND NEW.recovered_by IS NOT DISTINCT FROM OLD.recovered_by THEN
1509
+ RETURN NEW;
1510
+ END IF;
1511
+ RAISE EXCEPTION 'Owned transaction fencing requires an updated writer; upgrade Netherframe before changing operation ownership or resolution';
1512
+ END IF;
1513
+ RETURN NEW;
1514
+ END;
1515
+ $$;
1516
+ CREATE OR REPLACE FUNCTION {s}.{p}protect_plan_admission() RETURNS trigger LANGUAGE plpgsql AS $$
1517
+ BEGIN
1518
+ IF NEW.admitted_plan IS NOT DISTINCT FROM OLD.admitted_plan THEN
1519
+ RETURN NEW;
1520
+ END IF;
1521
+ IF current_setting('netherframe.graph_identity_protocol', true) IS DISTINCT FROM '11' THEN
1522
+ RAISE EXCEPTION 'Owned transaction fencing requires an updated writer';
1523
+ END IF;
1524
+ IF EXISTS (SELECT 1 FROM {s}.{p}run_mutations m WHERE m.run_id = OLD.run_id)
1525
+ OR EXISTS (SELECT 1 FROM {s}.{p}operations o WHERE (o.run_id = OLD.run_id OR o.recovered_by = OLD.run_id)
1526
+ AND o.stage NOT IN ('committed', 'aborted')) THEN
1527
+ RAISE EXCEPTION 'An admitted plan cannot change after reserving operations or mutating state';
1528
+ END IF;
1529
+ IF OLD.admitted_plan IS NOT NULL AND NEW.admitted_plan IS NOT NULL THEN
1530
+ RAISE EXCEPTION 'Release the entire grant and admission before replanning';
1531
+ END IF;
1532
+ IF NEW.admitted_plan IS NOT NULL AND NEW.lease_phase <> 'granted' THEN
1533
+ RAISE EXCEPTION 'Plan admission requires a complete granted lease set';
1534
+ END IF;
1535
+ RETURN NEW;
1536
+ END;
1537
+ $$;
1538
+ UPDATE {s}.{p}apps SET schema_version = 21;
1539
+ """
1540
+
1541
+ #: Version 22: canonical keys follow provider wire coercion. Retain coarse
1542
+ #: holds for earlier immutable requests; fence their writers and queue clients.
1543
+ #: The existing ownership guards are unchanged apart from their protocol gate.
1544
+ V22 = (
1545
+ V21.replace("IS DISTINCT FROM '11'", "IS DISTINCT FROM '12'").replace("Owned transaction fencing", "Wire identity fencing").replace("schema_version = 21", "schema_version = 22")
1546
+ + """
1547
+ CREATE OR REPLACE FUNCTION {s}.{p}require_operation_queue_writer() RETURNS trigger LANGUAGE plpgsql AS $$
1548
+ BEGIN
1549
+ IF current_setting('netherframe.graph_queue_protocol', true) IS DISTINCT FROM '2' THEN
1550
+ RAISE EXCEPTION 'Wire identity lease admission requires an updated writer; upgrade Netherframe before acquiring a grant';
1551
+ END IF;
1552
+ RETURN NEW;
1553
+ END;
1554
+ $$;
1555
+ CREATE OR REPLACE VIEW {s}.{v}operation_leases AS
1556
+ SELECT o.state_id, o.op_id, o.run_id, o.recovered_by, o.stage, lease.key, lease.value AS mode
1557
+ FROM {s}.{p}operations o
1558
+ CROSS JOIN LATERAL jsonb_each_text(CASE WHEN (o.request -> 'wire_identity_version')::text = '1'
1559
+ THEN coalesce(o.request -> 'lease_footprint', '{{"app":"X"}}'::jsonb)
1560
+ ELSE '{{"app":"X"}}'::jsonb END) lease
1561
+ WHERE o.stage NOT IN ('committed', 'aborted');
1562
+ """
1563
+ )
1564
+
1565
+ #: Version 23: old recovery observations and partial error responses could
1566
+ #: falsely claim configuration convergence. Certify retained legacy readiness
1567
+ #: once, before its operation evidence can be pruned; never rewrite history.
1568
+ V23 = (
1569
+ """
1570
+ -- Ownership transactions take the run lock before app/data locks. Wait for
1571
+ -- their old statements before installing guards and capturing evidence.
1572
+ LOCK TABLE {s}.{p}runs IN EXCLUSIVE MODE;
1573
+ LOCK TABLE {s}.{p}apps IN EXCLUSIVE MODE;
1574
+ LOCK TABLE {s}.{p}entries, {s}.{p}versions, {s}.{p}operations IN EXCLUSIVE MODE;
1575
+ """
1576
+ + V21.replace("IS DISTINCT FROM '11'", "IS DISTINCT FROM '13'").replace("Owned transaction fencing", "Convergence evidence fencing").replace("schema_version = 21", "schema_version = 23")
1577
+ + """
1578
+ SELECT set_config('netherframe.graph_identity_protocol', '13', true);
1579
+ ALTER TABLE {s}.{p}apps ADD COLUMN convergence_frontier bigint NOT NULL DEFAULT 0;
1580
+ UPDATE {s}.{p}apps SET convergence_frontier = frontier;
1581
+
1582
+ CREATE TABLE {s}.{p}convergence_evidence (
1583
+ state_id text NOT NULL,
1584
+ kind text NOT NULL DEFAULT 'resource' CHECK (kind = 'resource'),
1585
+ key text NOT NULL,
1586
+ revision bigint NOT NULL,
1587
+ verified boolean NOT NULL,
1588
+ PRIMARY KEY (state_id, kind, key, revision),
1589
+ FOREIGN KEY (state_id, kind, key, revision)
1590
+ REFERENCES {s}.{p}versions (state_id, kind, key, revision) ON DELETE CASCADE
1591
+ );
1592
+
1593
+ CREATE FUNCTION {s}.{p}protect_convergence_evidence() RETURNS trigger LANGUAGE plpgsql AS $$
1594
+ BEGIN
1595
+ IF TG_OP = 'UPDATE' THEN
1596
+ RAISE EXCEPTION 'Legacy convergence evidence is immutable';
1597
+ END IF;
1598
+ IF TG_OP = 'DELETE' THEN
1599
+ IF EXISTS (SELECT 1 FROM {s}.{p}versions v
1600
+ WHERE (v.state_id, v.kind, v.key, v.revision) = (OLD.state_id, OLD.kind, OLD.key, OLD.revision)) THEN
1601
+ RAISE EXCEPTION 'A retained version still needs its convergence evidence';
1602
+ END IF;
1603
+ RETURN OLD;
1604
+ END IF;
1605
+ IF current_setting('netherframe.graph_identity_protocol', true) IS DISTINCT FROM '13' THEN
1606
+ RAISE EXCEPTION 'Convergence evidence requires an updated writer';
1607
+ END IF;
1608
+ RETURN NEW;
1609
+ END;
1610
+ $$;
1611
+ CREATE TRIGGER {p}convergence_evidence_immutable BEFORE INSERT OR UPDATE OR DELETE ON {s}.{p}convergence_evidence
1612
+ FOR EACH ROW EXECUTE FUNCTION {s}.{p}protect_convergence_evidence();
1613
+
1614
+ -- graph_convergence.backfill_legacy_convergence qualifies canonical identities
1615
+ -- and fingerprints in the same migration transaction, before its version is
1616
+ -- recorded. This uses the portable identity codec instead of guessing keys in SQL.
1617
+ """
1618
+ )
1619
+
1620
+ # Shared by admission and the diagnostic view. Wire identity and temporary
1621
+ # input capture are independent proofs; JSON null/empty arguments need none.
1622
+ OPERATION_FOOTPRINT_V1_SQL = """CASE WHEN (request -> 'wire_identity_version')::text = '1' AND
1623
+ CASE WHEN request ? 'ephemeral_inputs_version' THEN (request -> 'ephemeral_inputs_version')::text = '1'
1624
+ ELSE NOT (request ? 'state_move')
1625
+ AND coalesce(request #> ARRAY['before', 'metadata', 'ephemeral_arguments'], 'null'::jsonb) IN ('null'::jsonb, '[]'::jsonb)
1626
+ AND coalesce(request #> ARRAY['template', 'metadata', 'ephemeral_arguments'], 'null'::jsonb) IN ('null'::jsonb, '[]'::jsonb)
1627
+ END
1628
+ THEN coalesce(request -> 'lease_footprint', jsonb_build_object('app', 'X'))
1629
+ ELSE jsonb_build_object('app', 'X') END"""
1630
+
1631
+ #: Version 24: legacy ephemeral calls can have empty inputs despite reading
1632
+ #: managed state. Keep their immutable requests, broaden exclusion, and qualify
1633
+ #: old readiness (including checkpoint before-images) separately from V23's
1634
+ #: immutable configuration/object certificates.
1635
+ V24 = (
1636
+ """
1637
+ LOCK TABLE {s}.{p}runs IN EXCLUSIVE MODE;
1638
+ LOCK TABLE {s}.{p}apps IN EXCLUSIVE MODE;
1639
+ LOCK TABLE {s}.{p}entries, {s}.{p}versions, {s}.{p}operations IN EXCLUSIVE MODE;
1640
+ LOCK TABLE {s}.{p}leases, {s}.{p}lease_queue IN EXCLUSIVE MODE;
1641
+ SELECT set_config('netherframe.graph_identity_protocol', '14', true);
1642
+ """
1643
+ + V21.replace("IS DISTINCT FROM '11'", "IS DISTINCT FROM '14'").replace("Owned transaction fencing", "Ephemeral input fencing").replace("schema_version = 21", "schema_version = 24")
1644
+ + """
1645
+ CREATE OR REPLACE FUNCTION {s}.{p}require_operation_queue_writer() RETURNS trigger LANGUAGE plpgsql AS $$
1646
+ BEGIN
1647
+ IF current_setting('netherframe.graph_queue_protocol', true) IS DISTINCT FROM '3' THEN
1648
+ RAISE EXCEPTION 'Ephemeral input lease admission requires an updated writer; upgrade Netherframe before acquiring a grant';
1649
+ END IF;
1650
+ RETURN NEW;
1651
+ END;
1652
+ $$;
1653
+ CREATE OR REPLACE VIEW {s}.{v}operation_leases AS
1654
+ SELECT o.state_id, o.op_id, o.run_id, o.recovered_by, o.stage, lease.key, lease.value AS mode
1655
+ FROM {s}.{p}operations o
1656
+ CROSS JOIN LATERAL jsonb_each_text(/*qualified footprint*/) lease
1657
+ WHERE o.stage NOT IN ('committed', 'aborted');
1658
+
1659
+ ALTER TABLE {s}.{p}apps ADD COLUMN ephemeral_inputs_frontier bigint NOT NULL DEFAULT 0;
1660
+ UPDATE {s}.{p}apps SET ephemeral_inputs_frontier = frontier;
1661
+ UPDATE {s}.{p}entries SET inputs = NULL,
1662
+ status = CASE WHEN status = 'ready' THEN 'unconverged' ELSE status END, updated_at = clock_timestamp()
1663
+ WHERE NOT tombstone
1664
+ AND coalesce(entry #> ARRAY['metadata', 'ephemeral_arguments'], 'null'::jsonb) NOT IN ('null'::jsonb, '[]'::jsonb);
1665
+
1666
+ CREATE OR REPLACE FUNCTION {s}.{p}protect_convergence_evidence() RETURNS trigger LANGUAGE plpgsql AS $$
1667
+ BEGIN
1668
+ IF TG_OP = 'UPDATE' THEN
1669
+ RAISE EXCEPTION 'Legacy convergence evidence is immutable';
1670
+ END IF;
1671
+ IF TG_OP = 'DELETE' THEN
1672
+ IF EXISTS (SELECT 1 FROM {s}.{p}versions v
1673
+ WHERE (v.state_id, v.kind, v.key, v.revision) = (OLD.state_id, OLD.kind, OLD.key, OLD.revision)) THEN
1674
+ RAISE EXCEPTION 'A retained version still needs its convergence evidence';
1675
+ END IF;
1676
+ RETURN OLD;
1677
+ END IF;
1678
+ IF current_setting('netherframe.graph_identity_protocol', true) IS DISTINCT FROM '14' THEN
1679
+ RAISE EXCEPTION 'Convergence evidence requires an updated writer';
1680
+ END IF;
1681
+ RETURN NEW;
1682
+ END;
1683
+ $$;
1684
+ """.replace("/*qualified footprint*/", OPERATION_FOOTPRINT_V1_SQL)
1685
+ )
1686
+
1687
+ #: Version 25: capture v2 includes opaque ephemeral observations. Earlier v1
1688
+ #: requests only captured evaluated configuration/provider inputs. Requalify
1689
+ #: marked rows/checkpoints at this frontier, retaining the old immutable data.
1690
+ OPERATION_FOOTPRINT_V2_SQL = OPERATION_FOOTPRINT_V1_SQL.replace("'ephemeral_inputs_version')::text = '1'", "'ephemeral_inputs_version')::text = '2'")
1691
+ V25 = (
1692
+ V24.replace("IS DISTINCT FROM '14'", "IS DISTINCT FROM '15'")
1693
+ .replace("IS DISTINCT FROM '3'", "IS DISTINCT FROM '4'")
1694
+ .replace("graph_identity_protocol', '14', true", "graph_identity_protocol', '15', true")
1695
+ .replace("schema_version = 24", "schema_version = 25")
1696
+ .replace("ALTER TABLE {s}.{p}apps ADD COLUMN ephemeral_inputs_frontier bigint NOT NULL DEFAULT 0;", "")
1697
+ .replace(OPERATION_FOOTPRINT_V1_SQL, OPERATION_FOOTPRINT_V2_SQL)
1698
+ )
1699
+
1700
+ #: Version 26: absent ephemeral metadata never attests absence of indirect reads.
1701
+ #: Capture v3 follows a new frontier: old metadata edits/restores could copy
1702
+ #: incomplete inputs into a newer sequence without recapturing them.
1703
+ #: Old current rows and checkpoint images need unknown inputs regardless of kind
1704
+ #: or argument metadata. Immutable history and operation requests stay unchanged.
1705
+ OPERATION_FOOTPRINT_V3_SQL = """CASE WHEN (request -> 'wire_identity_version')::text = '1'
1706
+ AND (request -> 'ephemeral_inputs_version')::text = '3'
1707
+ THEN coalesce(request -> 'lease_footprint', jsonb_build_object('app', 'X'))
1708
+ ELSE jsonb_build_object('app', 'X') END"""
1709
+ V26 = (
1710
+ V25.replace("IS DISTINCT FROM '15'", "IS DISTINCT FROM '16'")
1711
+ .replace("IS DISTINCT FROM '4'", "IS DISTINCT FROM '5'")
1712
+ .replace("graph_identity_protocol', '15', true", "graph_identity_protocol', '16', true")
1713
+ .replace("schema_version = 25", "schema_version = 26")
1714
+ .replace(OPERATION_FOOTPRINT_V2_SQL, OPERATION_FOOTPRINT_V3_SQL)
1715
+ .replace(
1716
+ """UPDATE {s}.{p}entries SET inputs = NULL,
1717
+ status = CASE WHEN status = 'ready' THEN 'unconverged' ELSE status END, updated_at = clock_timestamp()
1718
+ WHERE NOT tombstone
1719
+ AND coalesce(entry #> ARRAY['metadata', 'ephemeral_arguments'], 'null'::jsonb) NOT IN ('null'::jsonb, '[]'::jsonb);""",
1720
+ """UPDATE {s}.{p}entries e SET inputs = NULL,
1721
+ status = CASE WHEN e.status = 'ready' THEN 'unconverged' ELSE e.status END, updated_at = clock_timestamp()
1722
+ FROM {s}.{p}apps a WHERE e.state_id = a.state_id AND NOT e.tombstone AND e.sequence <= a.ephemeral_inputs_frontier;
1723
+ UPDATE {s}.{p}outputs o SET inputs = NULL,
1724
+ status = CASE WHEN o.status = 'ready' THEN 'unconverged' ELSE o.status END, updated_at = clock_timestamp()
1725
+ FROM {s}.{p}apps a WHERE o.state_id = a.state_id AND NOT o.tombstone AND o.sequence <= a.ephemeral_inputs_frontier;""",
1726
+ )
1727
+ )
1728
+
1729
+ #: Version 27: capture v4 rejects unqualified observation caches. Prior v3
1730
+ #: rows/calls could certify empty inputs after consuming a stored data result,
1731
+ #: or reuse a runtime result from another state/run/planning phase.
1732
+ OPERATION_FOOTPRINT_V4_SQL = OPERATION_FOOTPRINT_V3_SQL.replace("'ephemeral_inputs_version')::text = '3'", "'ephemeral_inputs_version')::text = '4'")
1733
+ V27 = (
1734
+ V26.replace("IS DISTINCT FROM '16'", "IS DISTINCT FROM '17'")
1735
+ .replace("IS DISTINCT FROM '5'", "IS DISTINCT FROM '6'")
1736
+ .replace("graph_identity_protocol', '16', true", "graph_identity_protocol', '17', true")
1737
+ .replace("schema_version = 26", "schema_version = 27")
1738
+ .replace(OPERATION_FOOTPRINT_V3_SQL, OPERATION_FOOTPRINT_V4_SQL)
1739
+ )
1740
+
1741
+ #: Version 28: capture v5 carries reads on environment memo hits. Older runtime
1742
+ #: captures could mistake an already-evaluated managed operand for a pure value.
1743
+ OPERATION_FOOTPRINT_SQL = OPERATION_FOOTPRINT_V4_SQL.replace("'ephemeral_inputs_version')::text = '4'", "'ephemeral_inputs_version')::text = '5'")
1744
+ V28 = (
1745
+ V27.replace("IS DISTINCT FROM '17'", "IS DISTINCT FROM '18'")
1746
+ .replace("IS DISTINCT FROM '6'", "IS DISTINCT FROM '7'")
1747
+ .replace("graph_identity_protocol', '17', true", "graph_identity_protocol', '18', true")
1748
+ .replace("schema_version = 27", "schema_version = 28")
1749
+ .replace(OPERATION_FOOTPRINT_V4_SQL, OPERATION_FOOTPRINT_SQL)
1750
+ )
1751
+
1752
+ #: Version 29: retain the branch origin for serial runs as well as admitted plans.
1753
+ #: Historical context only; input evidence and mutation protocols are unchanged.
1754
+ V29 = """
1755
+ ALTER TABLE {s}.{p}runs ADD COLUMN baseline jsonb;
1756
+ UPDATE {s}.{p}runs SET baseline = admitted_plan -> 'baseline'
1757
+ WHERE jsonb_typeof(admitted_plan -> 'baseline') = 'object';
1758
+ CREATE FUNCTION {s}.{p}protect_run_baseline() RETURNS trigger LANGUAGE plpgsql AS $$
1759
+ BEGIN
1760
+ IF OLD.baseline IS NOT NULL AND NEW.baseline IS DISTINCT FROM OLD.baseline THEN
1761
+ RAISE EXCEPTION 'A run baseline is immutable';
1762
+ END IF;
1763
+ IF NEW.baseline IS NOT NULL AND jsonb_typeof(NEW.admitted_plan -> 'baseline') = 'object'
1764
+ AND NEW.baseline IS DISTINCT FROM NEW.admitted_plan -> 'baseline' THEN
1765
+ RAISE EXCEPTION 'The admitted plan and run baseline must agree';
1766
+ END IF;
1767
+ IF NEW.baseline IS DISTINCT FROM OLD.baseline AND (
1768
+ EXISTS (SELECT 1 FROM {s}.{p}run_mutations WHERE run_id = OLD.run_id)
1769
+ OR EXISTS (SELECT 1 FROM {s}.{p}operations WHERE (run_id = OLD.run_id OR recovered_by = OLD.run_id)
1770
+ AND stage NOT IN ('committed', 'aborted'))) THEN
1771
+ RAISE EXCEPTION 'Record the baseline before reserving operations or mutating state';
1772
+ END IF;
1773
+ RETURN NEW;
1774
+ END;
1775
+ $$;
1776
+ CREATE TRIGGER {p}run_baseline BEFORE UPDATE OF baseline, admitted_plan ON {s}.{p}runs
1777
+ FOR EACH ROW EXECUTE FUNCTION {s}.{p}protect_run_baseline();
1778
+ CREATE OR REPLACE VIEW {s}.{v}runs AS
1779
+ SELECT r.run_id, r.state_id, r.epoch, r.operation, r.actor, r.host, r.status, r.started_at, r.expires_at,
1780
+ r.ended_at, r.providers_killed_at, m.started_at AS mutation_started_at, m.cause AS mutation_cause,
1781
+ coalesce(r.baseline, r.admitted_plan -> 'baseline') AS baseline, r.admitted_plan -> 'basis' AS plan_basis
1782
+ FROM {s}.{p}runs r LEFT JOIN {s}.{p}run_mutations m ON m.run_id = r.run_id;
1783
+ CREATE OR REPLACE VIEW {s}.{v}history AS
1784
+ SELECT v.state_id, v.kind, v.key, v.revision, v.sequence, v.run_id, v.op_id, v.tombstone, v.committed_at,
1785
+ r.operation, r.actor,
1786
+ CASE
1787
+ WHEN v.kind = 'resource' THEN {s}.{p}mask(v.row_data -> 'attributes', v.sensitive_paths)
1788
+ WHEN coalesce((v.row_data ->> 'sensitive')::boolean, false) THEN '"(sensitive)"'::jsonb
1789
+ ELSE v.row_data -> 'value'
1790
+ END AS value, v.intent_fp, v.inputs, v.applied_fp, v.status, v.mutation_revision,
1791
+ v.value_revision, v.membership_revision, coalesce(r.baseline, r.admitted_plan -> 'baseline') AS baseline
1792
+ FROM {s}.{p}versions v LEFT JOIN {s}.{p}runs r ON r.run_id = v.run_id;
1793
+ UPDATE {s}.{p}apps SET schema_version = 29;
1794
+ """
1795
+
1796
+ # A pre-qualification writer could keep a narrow object footprint even when
1797
+ # its run required app X. Retain old requests unchanged, but exclude broadly.
1798
+ OPERATION_FOOTPRINT_V5_SQL = OPERATION_FOOTPRINT_SQL
1799
+ OPERATION_FOOTPRINT_SQL = OPERATION_FOOTPRINT_V5_SQL.replace("CASE WHEN (request -> 'wire_identity_version')", "CASE WHEN (request -> 'identity_qualification_version')::text = '1' AND (request -> 'wire_identity_version')")
1800
+ V30 = (
1801
+ """
1802
+ LOCK TABLE {s}.{p}runs IN EXCLUSIVE MODE;
1803
+ LOCK TABLE {s}.{p}apps IN EXCLUSIVE MODE;
1804
+ LOCK TABLE {s}.{p}entries, {s}.{p}versions, {s}.{p}operations IN EXCLUSIVE MODE;
1805
+ LOCK TABLE {s}.{p}leases, {s}.{p}lease_queue IN EXCLUSIVE MODE;
1806
+ SELECT set_config('netherframe.graph_identity_protocol', '19', true);
1807
+ """
1808
+ + V21.replace("IS DISTINCT FROM '11'", "IS DISTINCT FROM '19'").replace("Owned transaction fencing", "Qualified identity fencing").replace("schema_version = 21", "schema_version = 30")
1809
+ + """
1810
+ CREATE OR REPLACE FUNCTION {s}.{p}require_operation_queue_writer() RETURNS trigger LANGUAGE plpgsql AS $$
1811
+ BEGIN
1812
+ IF current_setting('netherframe.graph_queue_protocol', true) IS DISTINCT FROM '8' THEN
1813
+ RAISE EXCEPTION 'Qualified identity lease admission requires an updated writer; upgrade Netherframe before acquiring a grant';
1814
+ END IF;
1815
+ RETURN NEW;
1816
+ END;
1817
+ $$;
1818
+ CREATE OR REPLACE VIEW {s}.{v}operation_leases AS
1819
+ SELECT o.state_id, o.op_id, o.run_id, o.recovered_by, o.stage, lease.key, lease.value AS mode
1820
+ FROM {s}.{p}operations o
1821
+ CROSS JOIN LATERAL jsonb_each_text(/*qualified footprint*/) lease
1822
+ WHERE o.stage NOT IN ('committed', 'aborted');
1823
+ CREATE OR REPLACE FUNCTION {s}.{p}protect_convergence_evidence() RETURNS trigger LANGUAGE plpgsql AS $$
1824
+ BEGIN
1825
+ IF TG_OP = 'UPDATE' THEN
1826
+ RAISE EXCEPTION 'Legacy convergence evidence is immutable';
1827
+ END IF;
1828
+ IF TG_OP = 'DELETE' THEN
1829
+ IF EXISTS (SELECT 1 FROM {s}.{p}versions v
1830
+ WHERE (v.state_id, v.kind, v.key, v.revision) = (OLD.state_id, OLD.kind, OLD.key, OLD.revision)) THEN
1831
+ RAISE EXCEPTION 'A retained version still needs its convergence evidence';
1832
+ END IF;
1833
+ RETURN OLD;
1834
+ END IF;
1835
+ IF current_setting('netherframe.graph_identity_protocol', true) IS DISTINCT FROM '19' THEN
1836
+ RAISE EXCEPTION 'Convergence evidence requires an updated writer';
1837
+ END IF;
1838
+ RETURN NEW;
1839
+ END;
1840
+ $$;
1841
+ """.replace("/*qualified footprint*/", OPERATION_FOOTPRINT_SQL)
1842
+ )
1843
+
1844
+ # Retained evidence is bound to its reviewed row revision. A v30 writer may
1845
+ # leave this column untouched, but its next revision can never inherit the old
1846
+ # qualification. Legacy rows remain unknown until a reviewed full plan writes it.
1847
+ V31 = """
1848
+ ALTER TABLE {s}.{p}entries ADD COLUMN planning_context jsonb;
1849
+ ALTER TABLE {s}.{p}outputs ADD COLUMN planning_context jsonb;
1850
+ ALTER TABLE {s}.{p}versions ADD COLUMN planning_context jsonb;
1851
+ UPDATE {s}.{p}apps SET schema_version = 31;
1852
+ """
1853
+
1854
+ # Independent of the writer version: older recovery clients must retain a
1855
+ # response/probe receipt too. Existing in-flight rows are preserved verbatim.
1856
+ V32 = """
1857
+ CREATE OR REPLACE FUNCTION {s}.{p}protect_operation_completion() RETURNS trigger LANGUAGE plpgsql AS $$
1858
+ BEGIN
1859
+ IF NEW.stage IS DISTINCT FROM OLD.stage THEN
1860
+ IF (OLD.stage IN ('dispatched', 'delete_dispatched', 'create_dispatched') AND NEW.stage <> 'returned')
1861
+ OR (NEW.stage IN ('committed', 'aborted', 'delete_committed') AND NOT (
1862
+ (OLD.stage = 'reserved' AND NEW.stage = 'aborted')
1863
+ OR (OLD.stage = 'reserved' AND OLD.action IN ('move', 'import') AND NEW.stage = 'committed')
1864
+ OR OLD.stage = 'returned'
1865
+ OR (OLD.stage = 'delete_committed' AND NEW.stage = 'committed'))) THEN
1866
+ RAISE EXCEPTION 'Operation completion requires a returned result or verified recovery observation';
1867
+ END IF;
1868
+ END IF;
1869
+ RETURN NEW;
1870
+ END;
1871
+ $$;
1872
+ CREATE TRIGGER operation_completion BEFORE UPDATE ON {s}.{p}operations
1873
+ FOR EACH ROW EXECUTE FUNCTION {s}.{p}protect_operation_completion();
1874
+ UPDATE {s}.{p}apps SET schema_version = 32;
1875
+ """
1876
+
1877
+ #: Version 33: exact grant validation once at installation, invalidated by SQL lease edits.
1878
+ V33 = """
1879
+ CREATE TABLE {s}.{p}grant_checks (
1880
+ state_id text NOT NULL,
1881
+ run_id text NOT NULL,
1882
+ complete boolean NOT NULL DEFAULT false,
1883
+ PRIMARY KEY (state_id, run_id)
1884
+ );
1885
+
1886
+ -- A true certificate is always computed from the actual mapping. Even direct
1887
+ -- SQL cannot turn a damaged grant's certificate back on without repairing it.
1888
+ CREATE FUNCTION {s}.{p}validate_grant_check() RETURNS trigger LANGUAGE plpgsql AS $$
1889
+ BEGIN
1890
+ IF NEW.complete THEN
1891
+ SELECT coalesce(r.lease_phase = 'granted' AND r.lease_set IS NOT NULL
1892
+ AND r.lease_set = coalesce((SELECT jsonb_object_agg(l.key, l.mode)
1893
+ FROM {s}.{p}leases l WHERE l.state_id = NEW.state_id AND l.holder = NEW.run_id), '{{}}'::jsonb), false)
1894
+ INTO NEW.complete FROM {s}.{p}runs r WHERE r.state_id = NEW.state_id AND r.run_id = NEW.run_id;
1895
+ NEW.complete := coalesce(NEW.complete, false);
1896
+ END IF;
1897
+ RETURN NEW;
1898
+ END;
1899
+ $$;
1900
+ CREATE TRIGGER {p}validate_grant_check BEFORE INSERT OR UPDATE ON {s}.{p}grant_checks
1901
+ FOR EACH ROW EXECUTE FUNCTION {s}.{p}validate_grant_check();
1902
+
1903
+ CREATE FUNCTION {s}.{p}install_grant_check() RETURNS trigger LANGUAGE plpgsql AS $$
1904
+ BEGIN
1905
+ -- Lock/create the certificate before checking. A concurrent lease edit
1906
+ -- must publish its invalidation under this same lock before it can commit.
1907
+ INSERT INTO {s}.{p}grant_checks (state_id, run_id, complete) VALUES (NEW.state_id, NEW.run_id, false)
1908
+ ON CONFLICT (state_id, run_id) DO UPDATE SET complete = false;
1909
+ UPDATE {s}.{p}grant_checks SET complete = true WHERE state_id = NEW.state_id AND run_id = NEW.run_id;
1910
+ RETURN NEW;
1911
+ END;
1912
+ $$;
1913
+ CREATE TRIGGER {p}install_grant_check AFTER INSERT OR UPDATE OF lease_phase, lease_set, state_id, run_id ON {s}.{p}runs
1914
+ FOR EACH ROW EXECUTE FUNCTION {s}.{p}install_grant_check();
1915
+
1916
+ CREATE FUNCTION {s}.{p}invalidate_grant_check() RETURNS trigger LANGUAGE plpgsql AS $$
1917
+ DECLARE changed record;
1918
+ BEGIN
1919
+ FOR changed IN SELECT DISTINCT state_id, run_id FROM
1920
+ (VALUES (OLD.state_id, OLD.holder), (NEW.state_id, NEW.holder)) AS affected(state_id, run_id)
1921
+ WHERE state_id IS NOT NULL AND run_id IS NOT NULL ORDER BY state_id, run_id
1922
+ LOOP
1923
+ INSERT INTO {s}.{p}grant_checks AS checks (state_id, run_id, complete) VALUES (changed.state_id, changed.run_id, false)
1924
+ ON CONFLICT (state_id, run_id) DO UPDATE SET complete = false WHERE checks.complete;
1925
+ END LOOP;
1926
+ RETURN NULL;
1927
+ END;
1928
+ $$;
1929
+ CREATE TRIGGER {p}invalidate_grant_check AFTER INSERT OR DELETE OR UPDATE OF state_id, key, holder, mode ON {s}.{p}leases
1930
+ FOR EACH ROW EXECUTE FUNCTION {s}.{p}invalidate_grant_check();
1931
+
1932
+ CREATE FUNCTION {s}.{p}invalidate_all_grant_checks() RETURNS trigger LANGUAGE plpgsql AS $$
1933
+ BEGIN
1934
+ UPDATE {s}.{p}grant_checks SET complete = false;
1935
+ RETURN NULL;
1936
+ END;
1937
+ $$;
1938
+ CREATE TRIGGER {p}invalidate_all_grant_checks AFTER TRUNCATE ON {s}.{p}leases
1939
+ FOR EACH STATEMENT EXECUTE FUNCTION {s}.{p}invalidate_all_grant_checks();
1940
+
1941
+ -- The validator checks pre-existing grants rather than assuming they survived.
1942
+ INSERT INTO {s}.{p}grant_checks (state_id, run_id, complete) SELECT state_id, run_id, true FROM {s}.{p}runs;
1943
+ UPDATE {s}.{p}apps SET schema_version = 33;
1944
+ """
1945
+
1946
+ #: Version 34: small, database-derived permission projections. Checking one
1947
+ #: target must not repeatedly decompress the full retained admission proof.
1948
+ V34 = """
1949
+ ALTER TABLE {s}.{p}runs
1950
+ ADD COLUMN admitted_writes jsonb GENERATED ALWAYS AS (admitted_plan #> '{{basis,writes}}') STORED,
1951
+ ADD COLUMN admitted_auxiliary jsonb GENERATED ALWAYS AS (admitted_plan #> '{{basis,auxiliary}}') STORED,
1952
+ ADD COLUMN admitted_actions jsonb GENERATED ALWAYS AS (admitted_plan #> '{{basis,actions}}') STORED;
1953
+ UPDATE {s}.{p}apps SET schema_version = 34;
1954
+ """
1955
+
1956
+ #: Version 35: exact database-derived ordering dependencies for metadata reads.
1957
+ #: The rewrite backfills existing entries; history and row versions do not change.
1958
+ V35 = """
1959
+ ALTER TABLE {s}.{p}entries
1960
+ ADD COLUMN dependency_targets jsonb GENERATED ALWAYS AS (entry -> 'dependencies') STORED;
1961
+
1962
+ -- AFTER triggers see generated values. Reuse the same projection so normal
1963
+ -- publication does not extract dependencies from a large entry a second time.
1964
+ CREATE OR REPLACE FUNCTION {s}.{p}resource_edges() RETURNS trigger LANGUAGE plpgsql AS $$
1965
+ BEGIN
1966
+ IF TG_OP = 'DELETE' THEN
1967
+ PERFORM {s}.{p}set_edges(OLD.state_id, 'resource', OLD.address, NULL, NULL, true);
1968
+ RETURN OLD;
1969
+ END IF;
1970
+ PERFORM {s}.{p}set_edges(NEW.state_id, 'resource', NEW.address, NEW.inputs, NEW.dependency_targets, NEW.tombstone);
1971
+ RETURN NEW;
1972
+ END;
1973
+ $$;
1974
+ UPDATE {s}.{p}apps SET schema_version = 35;
1975
+ """
1976
+
1977
+ MIGRATIONS: list[tuple[int, str]] = [
1978
+ (1, V1),
1979
+ (2, V2),
1980
+ (3, V3),
1981
+ (4, V4),
1982
+ (5, V5),
1983
+ (6, V6),
1984
+ (7, V7),
1985
+ (8, V8),
1986
+ (9, V9),
1987
+ (10, V10),
1988
+ (11, V11),
1989
+ (12, V12),
1990
+ (13, V13),
1991
+ (14, V14),
1992
+ (15, V15),
1993
+ (16, V16),
1994
+ (17, V17),
1995
+ (18, V18),
1996
+ (19, V19),
1997
+ (20, V20),
1998
+ (21, V21),
1999
+ (22, V22),
2000
+ (23, V23),
2001
+ (24, V24),
2002
+ (25, V25),
2003
+ (26, V26),
2004
+ (27, V27),
2005
+ (28, V28),
2006
+ (29, V29),
2007
+ (30, V30),
2008
+ (31, V31),
2009
+ (32, V32),
2010
+ (33, V33),
2011
+ (34, V34),
2012
+ (35, V35),
2013
+ ]
2014
+
2015
+ #: The views a read-only role may select from
2016
+ VIEWS = ("resources_current", "outputs_current", "history", "runs", "operations", "dependencies", "leases", "lease_queue", "edge_generations", "operation_leases", "checkpoints", "checkpoint_restores", "state_transfers")
2017
+
2018
+ RELEASE_WRITER_PROTOCOL = "release-1"
2019
+ _DEVELOPMENT_OPERATION_FOOTPRINT_SQL = OPERATION_FOOTPRINT_SQL
2020
+ OPERATION_FOOTPRINT_SQL = _DEVELOPMENT_OPERATION_FOOTPRINT_SQL.replace(
2021
+ "(request -> 'ephemeral_inputs_version')::text = '5'",
2022
+ """(CASE WHEN request ? 'input_capture_format' THEN (request -> 'input_capture_format')::text = '1'
2023
+ AND NOT (request ? 'ephemeral_inputs_version')
2024
+ ELSE (request -> 'ephemeral_inputs_version')::text = '5' END)""",
2025
+ )
2026
+ # Reuse the active writer guards. The development protocols stay in the historical
2027
+ # migrations so databases can still be upgraded from any of those schemas.
2028
+ RELEASE_MIGRATIONS = (
2029
+ (
2030
+ 1,
2031
+ V30.replace(_DEVELOPMENT_OPERATION_FOOTPRINT_SQL, OPERATION_FOOTPRINT_SQL)
2032
+ .replace("graph_identity_protocol', '19', true", f"graph_identity_protocol', '{RELEASE_WRITER_PROTOCOL}', true")
2033
+ .replace("IS DISTINCT FROM '19'", f"IS DISTINCT FROM '{RELEASE_WRITER_PROTOCOL}'")
2034
+ .replace("IS DISTINCT FROM '8'", f"IS DISTINCT FROM '{RELEASE_WRITER_PROTOCOL}'")
2035
+ .replace("schema_version = 30", "schema_version = 1"),
2036
+ ),
2037
+ )
2038
+ SCHEMA_VERSION = RELEASE_MIGRATIONS[-1][0]