@segmentstream/ontology 0.168.0 → 0.168.1

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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,13 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.168.1
4
+
5
+ The replication schema adds a content-free erasure journal, `_ontology_replication_erasures`.
6
+ Each row is a deleted record whose replicated history the platform erases from the workspace
7
+ warehouse, together with the audit of that erasure: when the record was deleted, when its history
8
+ left the warehouse, by which warehouse job, how many rows that job removed, and when a later check
9
+ found nothing left. This release queues nothing yet; preview databases start with an empty journal.
10
+
3
11
  ## 0.168.0
4
12
 
5
13
  A mailbox in `chat` takes `signature: true` beside its connection: the ontology's replies to mail,
@@ -255,7 +255,10 @@ export const applyMigration = (plan, options) => Effect.gen(function* () {
255
255
  const targetPresent = presence.targets && isNoopMigration(plan)
256
256
  ? "EXISTS (SELECT 1 FROM _ontology_replication_targets WHERE generation = active_generation)"
257
257
  : "false";
258
- const [state] = yield* sql.unsafe(`SELECT version, enabled, ${targetPresent} AS target_present, selection
258
+ const [state] = yield* sql.unsafe(
259
+ // Tables a release adds within the schema version are installed by its first migration.
260
+ `SELECT version, enabled, ${targetPresent} AS target_present, selection,
261
+ to_regclass('_ontology_replication_erasures') IS NOT NULL AS erasures
259
262
  FROM _ontology_replication WHERE id`);
260
263
  if (state?.enabled &&
261
264
  state.version >= 6 &&
@@ -273,6 +276,7 @@ export const applyMigration = (plan, options) => Effect.gen(function* () {
273
276
  }
274
277
  if (isNoopMigration(plan) &&
275
278
  state?.version === REPLICATION_SCHEMA_VERSION &&
279
+ state.erasures &&
276
280
  (!state.enabled || (state.target_present && replicatesAll(plan.target, state.selection)))) {
277
281
  if (options.workspaceId !== undefined || syncsIdentities(plan)) {
278
282
  // Under the migration lock, and only while the catalog still records this target.
@@ -52,6 +52,7 @@ export function preparePreviewDatabase({ sql, }) {
52
52
  "_ontology_replication_scans",
53
53
  "_ontology_replication_baselines",
54
54
  "_ontology_replication_receipts",
55
+ "_ontology_replication_erasures",
55
56
  "_ontology_replication_targets",
56
57
  ];
57
58
  if (present.has("_ontology_replication")) {
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Records whose replicated history the warehouse must lose: one row per deleted record of an
3
+ * entity that erases its history on delete. A row is the audit of its erasure as well, holding no
4
+ * content: which record, when it was deleted, when its history left the warehouse, by which
5
+ * warehouse job, how many rows that job removed, and when a later pass found nothing left.
6
+ *
7
+ * `due_at` batches the work by day: a deletion is erased from the next day's first pass, a failed
8
+ * attempt is retried an hour later, and an erased record is checked again once Pub/Sub can no
9
+ * longer deliver an event captured before the deletion.
10
+ */
11
+ export declare const REPLICATION_ERASURES_DDL: string[];
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Records whose replicated history the warehouse must lose: one row per deleted record of an
3
+ * entity that erases its history on delete. A row is the audit of its erasure as well, holding no
4
+ * content: which record, when it was deleted, when its history left the warehouse, by which
5
+ * warehouse job, how many rows that job removed, and when a later pass found nothing left.
6
+ *
7
+ * `due_at` batches the work by day: a deletion is erased from the next day's first pass, a failed
8
+ * attempt is retried an hour later, and an erased record is checked again once Pub/Sub can no
9
+ * longer deliver an event captured before the deletion.
10
+ */
11
+ export const REPLICATION_ERASURES_DDL = [
12
+ `CREATE TABLE IF NOT EXISTS _ontology_replication_erasures (
13
+ entity_id text NOT NULL, record_id uuid NOT NULL,
14
+ requested_at timestamptz NOT NULL DEFAULT now(),
15
+ due_at timestamptz NOT NULL DEFAULT date_trunc('day', now()) + interval '1 day',
16
+ attempts integer NOT NULL DEFAULT 0, failure text,
17
+ erased_at timestamptz, erased_job text, erased_rows bigint NOT NULL DEFAULT 0,
18
+ confirmed_at timestamptz,
19
+ PRIMARY KEY (entity_id, record_id)
20
+ )`,
21
+ `CREATE INDEX IF NOT EXISTS _ontology_replication_erasures_due
22
+ ON _ontology_replication_erasures (due_at, entity_id, record_id) WHERE confirmed_at IS NULL`,
23
+ ];
@@ -0,0 +1,56 @@
1
+ import { Effect } from "effect";
2
+ import type { SqlClient } from "effect/unstable/sql";
3
+ export { REPLICATION_ERASURES_DDL } from "./erasure-schema.js";
4
+ /** The most records one warehouse statement erases. */
5
+ export declare const REPLICATION_ERASURE_BATCH = 1000;
6
+ /**
7
+ * How long after its copies were scrubbed an event published before can still reach the warehouse:
8
+ * Pub/Sub keeps an undelivered message seven days. An erased record is confirmed by a pass after.
9
+ */
10
+ export declare const REPLICATION_ERASURE_CONFIRM_AFTER = "8 days";
11
+ export interface ReplicationErasureBatch {
12
+ readonly entityId: string;
13
+ readonly recordIds: readonly string[];
14
+ }
15
+ export interface ReplicationErasureScrub {
16
+ /** Staging objects of settled copy segments that held the records' events. */
17
+ readonly objectUris: readonly string[];
18
+ /** Copy segments that hold the records' events but have not settled yet: scrubbed later. */
19
+ readonly unsettled: number;
20
+ }
21
+ /**
22
+ * The next records due for erasure, of one entity. A source an SDK without erasure installed has
23
+ * none.
24
+ */
25
+ export declare const dueReplicationErasures: (sql: SqlClient.SqlClient, limit?: number) => Effect.Effect<{
26
+ entityId: string;
27
+ recordIds: string[];
28
+ } | undefined, import("effect/unstable/sql/SqlError").SqlError, never>;
29
+ /**
30
+ * Removes the records' content from every replication copy the source keeps: the events their
31
+ * history captured, delivery payloads kept for dropped history, baseline scan events and settled
32
+ * copy segments. Each copy keeps the event's identity and revision as a deletion, so a copy sent
33
+ * again can never show the record. Relationship events carry only ids and stay. A segment still
34
+ * being loaded keeps its events until it settles; the next pass scrubs it.
35
+ */
36
+ export declare const scrubReplicationErasures: (sql: SqlClient.SqlClient, batch: ReplicationErasureBatch) => Effect.Effect<{
37
+ objectUris: string[];
38
+ unsettled: number;
39
+ }, import("effect/unstable/sql/SqlError").SqlError, never>;
40
+ /**
41
+ * Records a warehouse erasure of the batch. The first erases the records. Their copies were scrubbed
42
+ * before it, so any event published since carries no content; one published earlier stays in
43
+ * Pub/Sub at most until the confirmation delay after that first erasure. A pass after that delay
44
+ * that removed nothing and found no unsettled copy confirms the records. Otherwise they are checked
45
+ * again the next day, or within the hour while a copy segment that holds them has not settled: it
46
+ * may still load their content, and its staging object is deleted once it has.
47
+ */
48
+ export declare const recordReplicationErasure: (sql: SqlClient.SqlClient, batch: ReplicationErasureBatch, outcome: {
49
+ readonly jobId: string;
50
+ readonly rows: number;
51
+ readonly unsettled: number;
52
+ }) => import("effect/unstable/sql/Statement").Statement<{
53
+ record_id: string;
54
+ }>;
55
+ /** A failed attempt is retried an hour later; its reason is a code, never content. */
56
+ export declare const recordReplicationErasureFailure: (sql: SqlClient.SqlClient, batch: ReplicationErasureBatch, failure: string) => Effect.Effect<number, import("effect/unstable/sql/SqlError").SqlError, never>;
@@ -0,0 +1,127 @@
1
+ import { Effect } from "effect";
2
+ import { historyTableName, quoteIdentifier as qi } from "../migrate/storage.js";
3
+ import { activeReplicationTarget } from "./store.js";
4
+ export { REPLICATION_ERASURES_DDL } from "./erasure-schema.js";
5
+ /** The most records one warehouse statement erases. */
6
+ export const REPLICATION_ERASURE_BATCH = 1000;
7
+ /**
8
+ * How long after its copies were scrubbed an event published before can still reach the warehouse:
9
+ * Pub/Sub keeps an undelivered message seven days. An erased record is confirmed by a pass after.
10
+ */
11
+ export const REPLICATION_ERASURE_CONFIRM_AFTER = "8 days";
12
+ /** What scrubbing a replicated event leaves: its identity and revision, no content, a deletion. */
13
+ const SCRUBBED = `'{"payload":"{}","deleted":true}'::jsonb`;
14
+ const present = (sql) => sql
15
+ .unsafe("SELECT to_regclass('_ontology_replication_erasures') IS NOT NULL AS present")
16
+ .pipe(Effect.map((rows) => rows[0]?.present === true));
17
+ /**
18
+ * The next records due for erasure, of one entity. A source an SDK without erasure installed has
19
+ * none.
20
+ */
21
+ export const dueReplicationErasures = (sql, limit = REPLICATION_ERASURE_BATCH) => Effect.gen(function* () {
22
+ if (!(yield* present(sql))) {
23
+ return undefined;
24
+ }
25
+ const [first] = yield* sql.unsafe(`SELECT entity_id FROM _ontology_replication_erasures
26
+ WHERE confirmed_at IS NULL AND due_at <= now() ORDER BY due_at LIMIT 1`);
27
+ if (!first) {
28
+ return undefined;
29
+ }
30
+ const rows = yield* sql.unsafe(`SELECT record_id::text FROM _ontology_replication_erasures
31
+ WHERE confirmed_at IS NULL AND due_at <= now() AND entity_id = $1
32
+ ORDER BY record_id LIMIT $2::int`, [first.entity_id, limit]);
33
+ return {
34
+ entityId: first.entity_id,
35
+ recordIds: rows.map((row) => row.record_id),
36
+ };
37
+ });
38
+ /**
39
+ * Removes the records' content from every replication copy the source keeps: the events their
40
+ * history captured, delivery payloads kept for dropped history, baseline scan events and settled
41
+ * copy segments. Each copy keeps the event's identity and revision as a deletion, so a copy sent
42
+ * again can never show the record. Relationship events carry only ids and stay. A segment still
43
+ * being loaded keeps its events until it settles; the next pass scrubs it.
44
+ */
45
+ export const scrubReplicationErasures = (sql, batch) => sql.withTransaction(Effect.gen(function* () {
46
+ const target = yield* activeReplicationTarget(sql);
47
+ const active = target?.manifest.entities.find((item) => item.id === batch.entityId)?.name;
48
+ // An entity removed from the ontology keeps its records and history under its last name,
49
+ // which the latest replication target that declared it records.
50
+ const [retained] = active
51
+ ? []
52
+ : yield* sql.unsafe(`SELECT e->>'name' AS name FROM _ontology_replication_targets t
53
+ CROSS JOIN LATERAL jsonb_array_elements(t.manifest->'entities') e
54
+ WHERE e->>'id' = $1 ORDER BY t.created_at DESC LIMIT 1`, [batch.entityId]);
55
+ const name = active ?? retained?.name;
56
+ const history = name ? historyTableName(name) : undefined;
57
+ const ids = JSON.stringify(batch.recordIds);
58
+ let events = [];
59
+ if (history) {
60
+ const [exists] = yield* sql.unsafe("SELECT to_regclass($1) IS NOT NULL AS present", [qi(history)]);
61
+ if (exists?.present) {
62
+ const scrubbed = yield* sql.unsafe(`UPDATE ${qi(history)} SET replication = replication || ${SCRUBBED}
63
+ WHERE record_id IN (SELECT value::uuid FROM jsonb_array_elements_text($1::jsonb))
64
+ AND replication IS NOT NULL AND replication->>'record_kind' = 'entity'
65
+ RETURNING id::text`, [ids]);
66
+ events = scrubbed.map((row) => row.id);
67
+ }
68
+ }
69
+ const delivered = yield* sql.unsafe(`UPDATE _ontology_replication_delivery d SET payload = d.payload || ${SCRUBBED}
70
+ WHERE d.payload IS NOT NULL AND d.payload->>'entity_id' = $1
71
+ AND d.payload->>'record_kind' = 'entity'
72
+ AND d.payload->>'record_key' IN (SELECT value FROM jsonb_array_elements_text($2::jsonb))
73
+ RETURNING d.event_id::text AS id`, [batch.entityId, ids]);
74
+ const baselines = yield* sql.unsafe(`UPDATE _ontology_replication_baselines SET event = event || ${SCRUBBED}
75
+ WHERE event->>'entity_id' = $1 AND event->>'record_kind' = 'entity'
76
+ AND event->>'record_key' IN (SELECT value FROM jsonb_array_elements_text($2::jsonb))
77
+ RETURNING id::text`, [batch.entityId, ids]);
78
+ events = [...events, ...delivered.map((row) => row.id), ...baselines.map((row) => row.id)];
79
+ if (!events.length) {
80
+ return { objectUris: [], unsettled: 0 };
81
+ }
82
+ const matches = `e->>'entity_id' = $1 AND e->>'record_kind' = 'entity'
83
+ AND e->>'record_key' IN (SELECT value FROM jsonb_array_elements_text($2::jsonb))`;
84
+ const settled = yield* sql.unsafe(`UPDATE _ontology_replication_segments s SET events = (
85
+ SELECT jsonb_agg(CASE WHEN ${matches} THEN e || ${SCRUBBED} ELSE e END ORDER BY n)
86
+ FROM jsonb_array_elements(s.events) WITH ORDINALITY AS item(e, n))
87
+ WHERE s.state <> 'pending' AND s.event_ids ?| ARRAY(SELECT jsonb_array_elements_text($3::jsonb))
88
+ RETURNING s.object_uri`, [batch.entityId, ids, JSON.stringify(events)]);
89
+ const [pending] = yield* sql.unsafe(`SELECT count(*)::int AS count FROM _ontology_replication_segments s
90
+ WHERE s.state = 'pending' AND s.event_ids ?| ARRAY(SELECT jsonb_array_elements_text($1::jsonb))`, [JSON.stringify(events)]);
91
+ return {
92
+ objectUris: settled.map((row) => row.object_uri),
93
+ unsettled: pending?.count ?? 0,
94
+ };
95
+ }));
96
+ /**
97
+ * Records a warehouse erasure of the batch. The first erases the records. Their copies were scrubbed
98
+ * before it, so any event published since carries no content; one published earlier stays in
99
+ * Pub/Sub at most until the confirmation delay after that first erasure. A pass after that delay
100
+ * that removed nothing and found no unsettled copy confirms the records. Otherwise they are checked
101
+ * again the next day, or within the hour while a copy segment that holds them has not settled: it
102
+ * may still load their content, and its staging object is deleted once it has.
103
+ */
104
+ export const recordReplicationErasure = (sql, batch, outcome) => sql.unsafe(`UPDATE _ontology_replication_erasures SET attempts = attempts + 1, failure = NULL,
105
+ erased_at = COALESCE(erased_at, now()), erased_job = $3, erased_rows = erased_rows + $4::bigint,
106
+ confirmed_at = CASE WHEN erased_at IS NOT NULL AND $4::bigint = 0 AND $5::int = 0
107
+ AND now() >= erased_at + interval '${REPLICATION_ERASURE_CONFIRM_AFTER}' THEN now() END,
108
+ due_at = CASE WHEN $5::int > 0 THEN now() + interval '1 hour'
109
+ WHEN erased_at IS NULL THEN now() + interval '${REPLICATION_ERASURE_CONFIRM_AFTER}'
110
+ ELSE now() + interval '1 day' END
111
+ WHERE entity_id = $1 AND confirmed_at IS NULL
112
+ AND record_id IN (SELECT value::uuid FROM jsonb_array_elements_text($2::jsonb))
113
+ RETURNING record_id::text`, [
114
+ batch.entityId,
115
+ JSON.stringify(batch.recordIds),
116
+ outcome.jobId,
117
+ outcome.rows,
118
+ outcome.unsettled,
119
+ ]);
120
+ /** A failed attempt is retried an hour later; its reason is a code, never content. */
121
+ export const recordReplicationErasureFailure = (sql, batch, failure) => sql
122
+ .unsafe(`UPDATE _ontology_replication_erasures SET attempts = attempts + 1, failure = $3,
123
+ due_at = now() + interval '1 hour'
124
+ WHERE entity_id = $1 AND confirmed_at IS NULL
125
+ AND record_id IN (SELECT value::uuid FROM jsonb_array_elements_text($2::jsonb))
126
+ RETURNING attempts`, [batch.entityId, JSON.stringify(batch.recordIds), failure])
127
+ .pipe(Effect.map((rows) => Math.max(0, ...rows.map((row) => row.attempts))));
@@ -3,6 +3,7 @@ import { columnName, historyTableName, quoteIdentifier as qi, quoteLiteral as ql
3
3
  import { replicatesRecords } from "../replicated-entities.js";
4
4
  import { replicatedFields, REPLICATION_RECORD_BYTES } from "./model.js";
5
5
  import { SHADOW_REPLICATION_DDL, SHADOW_CONTROL_JOBS_DDL, SHADOW_SOURCE_REPLACEMENTS_DDL, } from "./shadow-schema.js";
6
+ import { REPLICATION_ERASURES_DDL } from "./erasure-schema.js";
6
7
  export const REPLICATION_SCHEMA_VERSION = 6;
7
8
  /** Targets of sources not migrated since fills were introduced have no `fills` column. */
8
9
  export const REPLICATION_TARGET_FILLS = `COALESCE(to_jsonb(_ontology_replication_targets) -> 'fills',
@@ -111,6 +112,7 @@ export const REPLICATION_DDL = [
111
112
  ...SHADOW_REPLICATION_DDL,
112
113
  SHADOW_CONTROL_JOBS_DDL,
113
114
  SHADOW_SOURCE_REPLACEMENTS_DDL,
115
+ ...REPLICATION_ERASURES_DDL,
114
116
  `CREATE OR REPLACE FUNCTION _ontology_replication_guard() RETURNS trigger LANGUAGE plpgsql AS $$
115
117
  BEGIN
116
118
  IF (SELECT enabled FROM _ontology_replication WHERE id) AND
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@segmentstream/ontology",
3
- "version": "0.168.0",
3
+ "version": "0.168.1",
4
4
  "description": "Define a SegmentStream workspace app's ontology: entities, relationships, roles and actions, written with Effect.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "SegmentStream",