@hotmeshio/hotmesh 0.32.0 → 0.33.0

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.
@@ -0,0 +1,87 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.readReplicationSlots = exports.readTablesStats = exports.readTableStats = exports.hasEscalationsTable = exports.withTransaction = exports.toNumber = exports.assertPositiveInt = exports.assertTarget = void 0;
4
+ const sql_1 = require("./sql");
5
+ function assertTarget(target) {
6
+ if (!sql_1.RETENTION_TARGETS.includes(target)) {
7
+ throw new Error(`Unknown retention target "${target}"; expected one of ${sql_1.RETENTION_TARGETS.join(', ')}`);
8
+ }
9
+ }
10
+ exports.assertTarget = assertTarget;
11
+ function assertPositiveInt(name, value, max) {
12
+ if (!Number.isInteger(value) || value < 1 || value > max) {
13
+ throw new Error(`${name} must be an integer from 1 to ${max}; received ${value}`);
14
+ }
15
+ }
16
+ exports.assertPositiveInt = assertPositiveInt;
17
+ const toNumber = (value) => value == null ? 0 : Number(value);
18
+ exports.toNumber = toNumber;
19
+ /**
20
+ * Runs `work` inside one transaction on the caller's client with
21
+ * transaction-scoped timeouts. Rolls back on error, or always when
22
+ * `rollback` is set.
23
+ */
24
+ async function withTransaction(client, settings, work) {
25
+ await client.query(settings.readOnly
26
+ ? 'BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY'
27
+ : 'BEGIN');
28
+ try {
29
+ if (settings.lockTimeoutMs != null) {
30
+ await client.query(`SET LOCAL lock_timeout = ${Math.trunc(settings.lockTimeoutMs)}`);
31
+ }
32
+ if (settings.statementTimeoutMs != null) {
33
+ await client.query(`SET LOCAL statement_timeout = ${Math.trunc(settings.statementTimeoutMs)}`);
34
+ }
35
+ const result = await work();
36
+ await client.query(settings.rollback ? 'ROLLBACK' : 'COMMIT');
37
+ return result;
38
+ }
39
+ catch (error) {
40
+ await client.query('ROLLBACK').catch(() => undefined);
41
+ throw error;
42
+ }
43
+ }
44
+ exports.withTransaction = withTransaction;
45
+ async function hasEscalationsTable(client) {
46
+ const { rows } = await client.query(`SELECT to_regclass('public.hmsh_escalations') IS NOT NULL AS present`);
47
+ return rows[0]?.present === true;
48
+ }
49
+ exports.hasEscalationsTable = hasEscalationsTable;
50
+ async function readTableStats(client, table) {
51
+ const { rows } = await client.query(sql_1.tableStatsSQL, [table]);
52
+ const row = rows[0] ?? {};
53
+ return {
54
+ table,
55
+ liveRows: (0, exports.toNumber)(row.live_rows),
56
+ deadRows: (0, exports.toNumber)(row.dead_rows),
57
+ totalBytes: (0, exports.toNumber)(row.total_bytes),
58
+ indexBytes: (0, exports.toNumber)(row.index_bytes),
59
+ lastAutovacuum: row.last_autovacuum ?? null,
60
+ lastAutoanalyze: row.last_autoanalyze ?? null,
61
+ };
62
+ }
63
+ exports.readTableStats = readTableStats;
64
+ /** Statistics for several tables, read one after another on the client. */
65
+ async function readTablesStats(client, tables) {
66
+ const stats = [];
67
+ for (const table of tables)
68
+ stats.push(await readTableStats(client, table));
69
+ return stats;
70
+ }
71
+ exports.readTablesStats = readTablesStats;
72
+ /** Slots and their WAL lag, or null when the role cannot read them. */
73
+ async function readReplicationSlots(client) {
74
+ try {
75
+ const { rows } = await client.query(sql_1.replicationSlotsSQL);
76
+ return rows.map((row) => ({
77
+ name: row.slot_name,
78
+ plugin: row.plugin ?? null,
79
+ active: row.active === true,
80
+ lagBytes: row.lag_bytes == null ? null : Number(row.lag_bytes),
81
+ }));
82
+ }
83
+ catch {
84
+ return null;
85
+ }
86
+ }
87
+ exports.readReplicationSlots = readReplicationSlots;
@@ -0,0 +1,55 @@
1
+ import { RetentionEscalationReference, RetentionTarget } from '../../../types/retention';
2
+ /**
3
+ * SQL for retention. Identifiers come from `DBA.safeName` (lowercase
4
+ * letters, digits, underscores) so interpolating them is safe; every
5
+ * value is a bound parameter.
6
+ */
7
+ export declare const RETENTION_TARGETS: RetentionTarget[];
8
+ /** Targets stored as tables inside each app schema. */
9
+ export declare const SCHEMA_TARGETS: RetentionTarget[];
10
+ export declare const ESCALATIONS_TABLE = "public.hmsh_escalations";
11
+ /** When an escalation ended; matches the expression of `idx_hmsh_esc_ended_at`. */
12
+ export declare const ENDED_AT = "COALESCE(e.resolved_at, e.updated_at)";
13
+ export declare const HISTOGRAM_BUCKETS: readonly ["day", "week", "month"];
14
+ /** Renders a timestamptz as ISO 8601 UTC with microseconds, so it round-trips exactly. */
15
+ export declare const iso: (column: string) => string;
16
+ /**
17
+ * A job is in scope when it finished, its engine retention ended before
18
+ * `asOf`, and it completed before `before`. `updated_at` records the last
19
+ * status change, which for a finished job is its completion.
20
+ *
21
+ * @param before positional parameter holding the cutoff
22
+ * @param asOf positional parameter holding the frozen instant
23
+ */
24
+ export declare const jobsInScope: (before: string, asOf: string) => string;
25
+ /** True when the job's workflow has a pending escalation. */
26
+ export declare const pendingEscalation: () => string;
27
+ /** True when the job's root or parent workflow is still running. */
28
+ export declare const openOrigin: (schema: string) => string;
29
+ /** The full eligibility predicate for jobs, protections included. */
30
+ export declare const jobsEligible: (schema: string, before: string, asOf: string, hasEscalations: boolean) => string;
31
+ /**
32
+ * A stream message is in scope when it was processed before `before`
33
+ * (and before `asOf`), and is not dead-lettered unless asked.
34
+ */
35
+ export declare const streamsEligible: (before: string, asOf: string, includeDeadLettered: string) => string;
36
+ /** Continue after a job watermark (`expired_at`, `id`). */
37
+ export declare const jobsAfter: (at: string, id: string) => string;
38
+ /** Continue after a stream watermark (`expired_at`, `stream_name`, `id`). */
39
+ export declare const streamsAfter: (at: string, stream: string, id: string) => string;
40
+ /** An ended escalation of the app, ended before `before` and `asOf`. */
41
+ export declare const escalationsInScope: (app: string, before: string, asOf: string) => string;
42
+ /** True when an outside table still names the escalation with an open reference. */
43
+ export declare const openReference: (references: RetentionEscalationReference[]) => string;
44
+ /** The full eligibility predicate for escalations, open references excluded. */
45
+ export declare const escalationsEligible: (app: string, before: string, asOf: string, references: RetentionEscalationReference[]) => string;
46
+ /** Continue after an escalation watermark (ended time, `id`). */
47
+ export declare const escalationsAfter: (at: string, id: string) => string;
48
+ /** Storage statistics summed across a table's partitions, or for the table itself. */
49
+ export declare const tableStatsSQL: string;
50
+ export declare const replicationSlotsSQL = "\n SELECT\n slot_name,\n plugin,\n active,\n CASE WHEN pg_is_in_recovery() THEN NULL\n ELSE pg_wal_lsn_diff(pg_current_wal_lsn(), COALESCE(confirmed_flush_lsn, restart_lsn))\n END::bigint AS lag_bytes\n FROM pg_replication_slots\n ORDER BY slot_name";
51
+ export declare const longTransactionsSQL = "\n SELECT\n pid,\n EXTRACT(EPOCH FROM (now() - xact_start))::int AS seconds,\n state,\n left(query, 200) AS query\n FROM pg_stat_activity\n WHERE xact_start < now() - interval '60 seconds'\n AND pid <> pg_backend_pid()\n ORDER BY xact_start\n LIMIT 10";
52
+ export declare const backlogSQL: (schema: string) => string;
53
+ export declare const discoverAppsSQL = "\n SELECT n.nspname AS schema, array_agg(c.relname::text ORDER BY c.relname) AS tables\n FROM pg_class c\n JOIN pg_namespace n ON n.oid = c.relnamespace\n WHERE c.relname = ANY ($1::text[])\n AND c.relkind IN ('p', 'r')\n AND NOT c.relispartition\n GROUP BY n.nspname\n ORDER BY n.nspname";
54
+ /** The tables whose storage a target's rows occupy. */
55
+ export declare const tablesFor: (schema: string, target: RetentionTarget) => string[];
@@ -0,0 +1,188 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.tablesFor = exports.discoverAppsSQL = exports.backlogSQL = exports.longTransactionsSQL = exports.replicationSlotsSQL = exports.tableStatsSQL = exports.escalationsAfter = exports.escalationsEligible = exports.openReference = exports.escalationsInScope = exports.streamsAfter = exports.jobsAfter = exports.streamsEligible = exports.jobsEligible = exports.openOrigin = exports.pendingEscalation = exports.jobsInScope = exports.iso = exports.HISTOGRAM_BUCKETS = exports.ENDED_AT = exports.ESCALATIONS_TABLE = exports.SCHEMA_TARGETS = exports.RETENTION_TARGETS = void 0;
4
+ /**
5
+ * SQL for retention. Identifiers come from `DBA.safeName` (lowercase
6
+ * letters, digits, underscores) so interpolating them is safe; every
7
+ * value is a bound parameter.
8
+ */
9
+ exports.RETENTION_TARGETS = [
10
+ 'jobs',
11
+ 'engine_streams',
12
+ 'worker_streams',
13
+ 'escalations',
14
+ ];
15
+ /** Targets stored as tables inside each app schema. */
16
+ exports.SCHEMA_TARGETS = [
17
+ 'jobs',
18
+ 'engine_streams',
19
+ 'worker_streams',
20
+ ];
21
+ exports.ESCALATIONS_TABLE = 'public.hmsh_escalations';
22
+ /** When an escalation ended; matches the expression of `idx_hmsh_esc_ended_at`. */
23
+ exports.ENDED_AT = 'COALESCE(e.resolved_at, e.updated_at)';
24
+ /** Every state transition guards `status = 'pending'`, so ended rows are inert. */
25
+ const ENDED_STATUSES = `e.status <> 'pending' AND e.status IN ('resolved', 'cancelled', 'expired')`;
26
+ const SQL_NAME = /^[a-z_][a-z0-9_]*(\.[a-z_][a-z0-9_]*)?$/;
27
+ exports.HISTOGRAM_BUCKETS = ['day', 'week', 'month'];
28
+ /** Renders a timestamptz as ISO 8601 UTC with microseconds, so it round-trips exactly. */
29
+ const iso = (column) => `to_char(${column} AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"')`;
30
+ exports.iso = iso;
31
+ /** `hmsh:<app>:j:` for a job row, taken from its own key. */
32
+ const KEY_PREFIX = `substr(j.key, 1, strpos(j.key, ':j:') + 2)`;
33
+ /** The job id portion of a job key. */
34
+ const JOB_ID = `substr(j.key, strpos(j.key, ':j:') + 3)`;
35
+ /**
36
+ * A job is in scope when it finished, its engine retention ended before
37
+ * `asOf`, and it completed before `before`. `updated_at` records the last
38
+ * status change, which for a finished job is its completion.
39
+ *
40
+ * @param before positional parameter holding the cutoff
41
+ * @param asOf positional parameter holding the frozen instant
42
+ */
43
+ const jobsInScope = (before, asOf) => `
44
+ j.expired_at IS NOT NULL
45
+ AND j.expired_at < ${asOf}::timestamptz
46
+ AND j.updated_at < ${before}::timestamptz`;
47
+ exports.jobsInScope = jobsInScope;
48
+ /** True when the job's workflow has a pending escalation. */
49
+ const pendingEscalation = () => `
50
+ EXISTS (
51
+ SELECT 1 FROM public.hmsh_escalations e
52
+ WHERE e.workflow_id = ${JOB_ID} AND e.status = 'pending'
53
+ )`;
54
+ exports.pendingEscalation = pendingEscalation;
55
+ /** True when the job's root or parent workflow is still running. */
56
+ const openOrigin = (schema) => `
57
+ EXISTS (
58
+ SELECT 1 FROM ${schema}.jobs p
59
+ WHERE p.key = ANY (ARRAY[${KEY_PREFIX} || j.origin_id, ${KEY_PREFIX} || j.parent_id])
60
+ AND p.expired_at IS NULL
61
+ AND p.id <> j.id
62
+ )`;
63
+ exports.openOrigin = openOrigin;
64
+ /** The full eligibility predicate for jobs, protections included. */
65
+ const jobsEligible = (schema, before, asOf, hasEscalations) => `
66
+ ${(0, exports.jobsInScope)(before, asOf)}
67
+ ${hasEscalations ? `AND NOT ${(0, exports.pendingEscalation)()}` : ''}
68
+ AND NOT ${(0, exports.openOrigin)(schema)}`;
69
+ exports.jobsEligible = jobsEligible;
70
+ /**
71
+ * A stream message is in scope when it was processed before `before`
72
+ * (and before `asOf`), and is not dead-lettered unless asked.
73
+ */
74
+ const streamsEligible = (before, asOf, includeDeadLettered) => `
75
+ s.expired_at IS NOT NULL
76
+ AND s.expired_at < ${before}::timestamptz
77
+ AND s.expired_at < ${asOf}::timestamptz
78
+ AND (${includeDeadLettered}::boolean OR s.dead_lettered_at IS NULL)`;
79
+ exports.streamsEligible = streamsEligible;
80
+ /** Continue after a job watermark (`expired_at`, `id`). */
81
+ const jobsAfter = (at, id) => `
82
+ AND j.expired_at >= ${at}::timestamptz
83
+ AND (j.expired_at > ${at}::timestamptz OR j.id > ${id}::uuid)`;
84
+ exports.jobsAfter = jobsAfter;
85
+ /** Continue after a stream watermark (`expired_at`, `stream_name`, `id`). */
86
+ const streamsAfter = (at, stream, id) => `
87
+ AND s.expired_at >= ${at}::timestamptz
88
+ AND (
89
+ s.expired_at > ${at}::timestamptz
90
+ OR (s.stream_name, s.id) > (${stream}::text, ${id}::bigint)
91
+ )`;
92
+ exports.streamsAfter = streamsAfter;
93
+ /** An ended escalation of the app, ended before `before` and `asOf`. */
94
+ const escalationsInScope = (app, before, asOf) => `
95
+ e.app_id = ${app}
96
+ AND ${ENDED_STATUSES}
97
+ AND ${exports.ENDED_AT} < ${before}::timestamptz
98
+ AND ${exports.ENDED_AT} < ${asOf}::timestamptz`;
99
+ exports.escalationsInScope = escalationsInScope;
100
+ /** True when an outside table still names the escalation with an open reference. */
101
+ const openReference = (references) => {
102
+ if (references.length === 0)
103
+ return 'false';
104
+ return references
105
+ .map((r) => {
106
+ for (const name of [r.table, r.column, r.openColumn]) {
107
+ if (!SQL_NAME.test(name))
108
+ throw new Error(`Invalid SQL name in escalation reference: ${name}`);
109
+ }
110
+ return `EXISTS (SELECT 1 FROM ${r.table} r WHERE r.${r.column} = e.id AND r.${r.openColumn} IS NULL)`;
111
+ })
112
+ .join(' OR ');
113
+ };
114
+ exports.openReference = openReference;
115
+ /** The full eligibility predicate for escalations, open references excluded. */
116
+ const escalationsEligible = (app, before, asOf, references) => `
117
+ ${(0, exports.escalationsInScope)(app, before, asOf)}
118
+ AND NOT (${(0, exports.openReference)(references)})`;
119
+ exports.escalationsEligible = escalationsEligible;
120
+ /** Continue after an escalation watermark (ended time, `id`). */
121
+ const escalationsAfter = (at, id) => `
122
+ AND ${exports.ENDED_AT} >= ${at}::timestamptz
123
+ AND (${exports.ENDED_AT} > ${at}::timestamptz OR e.id > ${id}::uuid)`;
124
+ exports.escalationsAfter = escalationsAfter;
125
+ /** Storage statistics summed across a table's partitions, or for the table itself. */
126
+ exports.tableStatsSQL = `
127
+ SELECT
128
+ COALESCE(sum(GREATEST(s.n_live_tup, c.reltuples::bigint, 0)), 0)::bigint AS live_rows,
129
+ COALESCE(sum(s.n_dead_tup), 0)::bigint AS dead_rows,
130
+ COALESCE(sum(pg_total_relation_size(c.oid)), 0)::bigint AS total_bytes,
131
+ COALESCE(sum(pg_indexes_size(c.oid)), 0)::bigint AS index_bytes,
132
+ ${(0, exports.iso)('max(s.last_autovacuum)')} AS last_autovacuum,
133
+ ${(0, exports.iso)('max(s.last_autoanalyze)')} AS last_autoanalyze
134
+ FROM (
135
+ -- Leaf partitions of a partitioned table, or the table itself when it
136
+ -- has none. UNION keeps one row where a version lists the table as its
137
+ -- own leaf.
138
+ SELECT relid FROM pg_partition_tree($1::regclass) WHERE isleaf
139
+ UNION
140
+ SELECT $1::regclass AS relid
141
+ WHERE (SELECT relkind FROM pg_class WHERE oid = $1::regclass) <> 'p'
142
+ ) t
143
+ JOIN pg_class c ON c.oid = t.relid
144
+ LEFT JOIN pg_stat_user_tables s ON s.relid = t.relid`;
145
+ exports.replicationSlotsSQL = `
146
+ SELECT
147
+ slot_name,
148
+ plugin,
149
+ active,
150
+ CASE WHEN pg_is_in_recovery() THEN NULL
151
+ ELSE pg_wal_lsn_diff(pg_current_wal_lsn(), COALESCE(confirmed_flush_lsn, restart_lsn))
152
+ END::bigint AS lag_bytes
153
+ FROM pg_replication_slots
154
+ ORDER BY slot_name`;
155
+ exports.longTransactionsSQL = `
156
+ SELECT
157
+ pid,
158
+ EXTRACT(EPOCH FROM (now() - xact_start))::int AS seconds,
159
+ state,
160
+ left(query, 200) AS query
161
+ FROM pg_stat_activity
162
+ WHERE xact_start < now() - interval '60 seconds'
163
+ AND pid <> pg_backend_pid()
164
+ ORDER BY xact_start
165
+ LIMIT 10`;
166
+ const backlogSQL = (schema) => `
167
+ SELECT
168
+ (SELECT count(*) FROM ${schema}.engine_streams WHERE expired_at IS NULL)::bigint AS engine,
169
+ (SELECT count(*) FROM ${schema}.worker_streams WHERE expired_at IS NULL)::bigint AS worker`;
170
+ exports.backlogSQL = backlogSQL;
171
+ exports.discoverAppsSQL = `
172
+ SELECT n.nspname AS schema, array_agg(c.relname::text ORDER BY c.relname) AS tables
173
+ FROM pg_class c
174
+ JOIN pg_namespace n ON n.oid = c.relnamespace
175
+ WHERE c.relname = ANY ($1::text[])
176
+ AND c.relkind IN ('p', 'r')
177
+ AND NOT c.relispartition
178
+ GROUP BY n.nspname
179
+ ORDER BY n.nspname`;
180
+ /** The tables whose storage a target's rows occupy. */
181
+ const tablesFor = (schema, target) => {
182
+ if (target === 'jobs')
183
+ return [`${schema}.jobs`, `${schema}.jobs_attributes`];
184
+ if (target === 'escalations')
185
+ return [exports.ESCALATIONS_TABLE];
186
+ return [`${schema}.${target}`];
187
+ };
188
+ exports.tablesFor = tablesFor;
@@ -0,0 +1,6 @@
1
+ import { RetentionSurvey, SurveyRetentionOptions } from '../../../types/retention';
2
+ /**
3
+ * Counts what one walk over the criteria would delete and what it would
4
+ * keep, in one repeatable-read snapshot, then reads database health.
5
+ */
6
+ export declare function surveyRetention(schema: string, options: SurveyRetentionOptions): Promise<RetentionSurvey>;
@@ -0,0 +1,289 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.surveyRetention = void 0;
4
+ const sql_1 = require("./sql");
5
+ const session_1 = require("./session");
6
+ const toHistogram = (rows) => rows
7
+ .filter((row) => row.bucket != null)
8
+ .map((row) => ({ bucket: row.bucket, count: (0, session_1.toNumber)(row.count) }));
9
+ const bytesPerRow = (stats) => stats.liveRows > 0 ? stats.totalBytes / stats.liveRows : 0;
10
+ /**
11
+ * Counts what one walk over the criteria would delete and what it would
12
+ * keep, in one repeatable-read snapshot, then reads database health.
13
+ */
14
+ async function surveyRetention(schema, options) {
15
+ const bucket = options.bucket ?? 'week';
16
+ if (!sql_1.HISTOGRAM_BUCKETS.includes(bucket)) {
17
+ throw new Error(`bucket must be one of ${sql_1.HISTOGRAM_BUCKETS.join(', ')}`);
18
+ }
19
+ options.criteria.forEach((c) => (0, session_1.assertTarget)(c.target));
20
+ const { client } = options;
21
+ // 1. Freeze the scope and count every target in one snapshot
22
+ const { surveyedAt, targets } = await (0, session_1.withTransaction)(client, {
23
+ readOnly: true,
24
+ statementTimeoutMs: options.statementTimeoutMs ?? 120000,
25
+ }, async () => {
26
+ const { rows } = await client.query(`SELECT ${(0, sql_1.iso)('now()')} AS now`);
27
+ const now = rows[0].now;
28
+ const context = {
29
+ client,
30
+ appId: options.appId,
31
+ schema,
32
+ asOf: now,
33
+ bucket,
34
+ hasEscalations: await (0, session_1.hasEscalationsTable)(client),
35
+ exactAttributeJobs: options.exactAttributeJobs ?? 5000,
36
+ attributeSampleJobs: options.attributeSampleJobs ?? 500,
37
+ };
38
+ const surveyed = [];
39
+ for (const criteria of options.criteria) {
40
+ const scoped = { ...context, asOf: criteria.asOf ?? now };
41
+ surveyed.push(await surveyTarget(scoped, criteria));
42
+ }
43
+ return { surveyedAt: now, targets: surveyed };
44
+ });
45
+ // 2. Read health outside the snapshot so a denied view cannot abort it
46
+ const health = await readHealth(client, schema);
47
+ return { appId: options.appId, schema, surveyedAt, targets, health };
48
+ }
49
+ exports.surveyRetention = surveyRetention;
50
+ function surveyTarget(context, criteria) {
51
+ if (criteria.target === 'jobs')
52
+ return surveyJobs(context, criteria);
53
+ if (criteria.target === 'escalations')
54
+ return surveyEscalations(context, criteria);
55
+ return surveyStreams(context, criteria);
56
+ }
57
+ async function surveyEscalations(context, criteria) {
58
+ const { client, appId, asOf, bucket, hasEscalations } = context;
59
+ if (!hasEscalations) {
60
+ throw new Error(`${sql_1.ESCALATIONS_TABLE} is missing; escalations cannot be surveyed`);
61
+ }
62
+ const references = criteria.references ?? [];
63
+ const params = [appId, criteria.before, asOf];
64
+ // 1. Kept: still pending, ended after the cutoff, or named by an open reference
65
+ const held = await client.query(`SELECT
66
+ (SELECT count(*) FROM ${sql_1.ESCALATIONS_TABLE} e
67
+ WHERE e.app_id = $1 AND e.status = 'pending')::bigint AS pending,
68
+ (SELECT count(*) FROM ${sql_1.ESCALATIONS_TABLE} e
69
+ WHERE e.app_id = $1 AND e.status <> 'pending'
70
+ AND e.status IN ('resolved', 'cancelled', 'expired')
71
+ AND ${sql_1.ENDED_AT} >= $2::timestamptz)::bigint AS newer,
72
+ (SELECT count(*) FROM ${sql_1.ESCALATIONS_TABLE} e
73
+ WHERE ${(0, sql_1.escalationsInScope)('$1', '$2', '$3')}
74
+ AND (${(0, sql_1.openReference)(references)}))::bigint AS open_reference`, params);
75
+ // 2. Eligible: total, range, histogram, and roles in one pass
76
+ const grouped = await client.query(`SELECT
77
+ GROUPING(date_trunc('${bucket}', ${sql_1.ENDED_AT}), e.role) AS grouping,
78
+ ${(0, sql_1.iso)(`date_trunc('${bucket}', ${sql_1.ENDED_AT})`)} AS bucket,
79
+ e.role,
80
+ count(*)::bigint AS count,
81
+ ${(0, sql_1.iso)(`min(${sql_1.ENDED_AT})`)} AS oldest,
82
+ ${(0, sql_1.iso)(`max(${sql_1.ENDED_AT})`)} AS newest
83
+ FROM ${sql_1.ESCALATIONS_TABLE} e
84
+ WHERE ${(0, sql_1.escalationsEligible)('$1', '$2', '$3', references)}
85
+ GROUP BY GROUPING SETS ((date_trunc('${bucket}', ${sql_1.ENDED_AT})), (e.role), ())`, params);
86
+ const total = grouped.rows.find((row) => row.grouping === 3);
87
+ const count = (0, session_1.toNumber)(total?.count);
88
+ const tables = [await (0, session_1.readTableStats)(client, sql_1.ESCALATIONS_TABLE)];
89
+ return {
90
+ target: 'escalations',
91
+ before: criteria.before,
92
+ asOf,
93
+ includeDeadLettered: false,
94
+ eligible: count,
95
+ oldest: total?.oldest ?? null,
96
+ newest: total?.newest ?? null,
97
+ protected: {
98
+ pending: (0, session_1.toNumber)(held.rows[0].pending),
99
+ newerThanCutoffEnded: (0, session_1.toNumber)(held.rows[0].newer),
100
+ openReference: (0, session_1.toNumber)(held.rows[0].open_reference),
101
+ },
102
+ histogram: toHistogram(grouped.rows
103
+ .filter((row) => row.grouping === 1)
104
+ .sort((a, b) => a.bucket.localeCompare(b.bucket))),
105
+ byRole: grouped.rows
106
+ .filter((row) => row.grouping === 2)
107
+ .map((row) => ({
108
+ entity: row.role ?? null,
109
+ count: (0, session_1.toNumber)(row.count),
110
+ }))
111
+ .sort((a, b) => b.count - a.count)
112
+ .slice(0, 20),
113
+ estimatedBytes: Math.round(bytesPerRow(tables[0]) * count),
114
+ tables,
115
+ };
116
+ }
117
+ async function surveyJobs(context, criteria) {
118
+ const { client, schema, asOf, bucket, hasEscalations } = context;
119
+ const params = [criteria.before, asOf];
120
+ // 1. Jobs kept because they are running or inside engine retention
121
+ const held = await client.query(`SELECT
122
+ (SELECT count(*) FROM ${schema}.jobs WHERE expired_at IS NULL)::bigint AS open,
123
+ (SELECT count(*) FROM ${schema}.jobs WHERE expired_at >= $1::timestamptz)::bigint AS in_retention`, [asOf]);
124
+ // 2. Past retention: split by cutoff, then by protection
125
+ const escalation = hasEscalations ? (0, sql_1.pendingEscalation)() : 'false';
126
+ const split = await client.query(`SELECT
127
+ count(*) FILTER (WHERE NOT before_cutoff)::bigint AS newer,
128
+ count(*) FILTER (WHERE before_cutoff AND escalated)::bigint AS pending_escalation,
129
+ count(*) FILTER (WHERE before_cutoff AND NOT escalated AND origin_open)::bigint AS open_origin
130
+ FROM (
131
+ SELECT
132
+ j.updated_at < $1::timestamptz AS before_cutoff,
133
+ CASE WHEN j.updated_at < $1::timestamptz THEN ${escalation} ELSE false END AS escalated,
134
+ CASE WHEN j.updated_at < $1::timestamptz THEN ${(0, sql_1.openOrigin)(schema)} ELSE false END AS origin_open
135
+ FROM ${schema}.jobs j
136
+ WHERE j.expired_at IS NOT NULL AND j.expired_at < $2::timestamptz
137
+ ) classified`, params);
138
+ // 3. Eligible jobs: total, range, histogram, and entities in one pass
139
+ const eligible = (0, sql_1.jobsEligible)(schema, '$1', '$2', hasEscalations);
140
+ const grouped = await client.query(`SELECT
141
+ GROUPING(date_trunc('${bucket}', j.updated_at), j.entity) AS grouping,
142
+ ${(0, sql_1.iso)(`date_trunc('${bucket}', j.updated_at)`)} AS bucket,
143
+ j.entity,
144
+ count(*)::bigint AS count,
145
+ ${(0, sql_1.iso)('min(j.updated_at)')} AS oldest,
146
+ ${(0, sql_1.iso)('max(j.updated_at)')} AS newest
147
+ FROM ${schema}.jobs j
148
+ WHERE ${eligible}
149
+ GROUP BY GROUPING SETS ((date_trunc('${bucket}', j.updated_at)), (j.entity), ())`, params);
150
+ const total = grouped.rows.find((row) => row.grouping === 3);
151
+ const count = (0, session_1.toNumber)(total?.count);
152
+ const byEntity = grouped.rows
153
+ .filter((row) => row.grouping === 2)
154
+ .map((row) => ({
155
+ entity: row.entity ?? null,
156
+ count: (0, session_1.toNumber)(row.count),
157
+ }))
158
+ .sort((a, b) => b.count - a.count)
159
+ .slice(0, 20);
160
+ // 4. Attribute rows that leave with the jobs
161
+ const attributes = await estimateAttributes(context, criteria, count);
162
+ // 5. Storage those rows hold
163
+ const tables = await (0, session_1.readTablesStats)(client, (0, sql_1.tablesFor)(schema, 'jobs'));
164
+ const estimatedBytes = Math.round(bytesPerRow(tables[0]) * count + bytesPerRow(tables[1]) * attributes.rows);
165
+ return {
166
+ target: 'jobs',
167
+ before: criteria.before,
168
+ asOf,
169
+ includeDeadLettered: false,
170
+ eligible: count,
171
+ oldest: total?.oldest ?? null,
172
+ newest: total?.newest ?? null,
173
+ protected: {
174
+ open: (0, session_1.toNumber)(held.rows[0].open),
175
+ inRetention: (0, session_1.toNumber)(held.rows[0].in_retention),
176
+ newerThanCutoff: (0, session_1.toNumber)(split.rows[0].newer),
177
+ pendingEscalation: (0, session_1.toNumber)(split.rows[0].pending_escalation),
178
+ openOrigin: (0, session_1.toNumber)(split.rows[0].open_origin),
179
+ },
180
+ histogram: toHistogram(grouped.rows
181
+ .filter((row) => row.grouping === 1)
182
+ .sort((a, b) => a.bucket.localeCompare(b.bucket))),
183
+ byEntity,
184
+ attributes,
185
+ estimatedBytes,
186
+ tables,
187
+ };
188
+ }
189
+ async function estimateAttributes(context, criteria, eligibleJobs) {
190
+ if (eligibleJobs === 0) {
191
+ return { rows: 0, exact: true, perJob: 0, sampled: 0 };
192
+ }
193
+ const { client, schema, asOf, hasEscalations } = context;
194
+ const exact = eligibleJobs <= context.exactAttributeJobs;
195
+ const sampleLimit = exact ? eligibleJobs : context.attributeSampleJobs;
196
+ const { rows } = await client.query(`SELECT count(*)::bigint AS rows, count(DISTINCT v.id)::bigint AS jobs
197
+ FROM (
198
+ SELECT j.id FROM ${schema}.jobs j
199
+ WHERE ${(0, sql_1.jobsEligible)(schema, '$1', '$2', hasEscalations)}
200
+ ORDER BY j.expired_at, j.id
201
+ LIMIT $3
202
+ ) v
203
+ LEFT JOIN ${schema}.jobs_attributes a ON a.job_id = v.id`, [criteria.before, asOf, sampleLimit]);
204
+ const counted = (0, session_1.toNumber)(rows[0].rows);
205
+ const sampled = (0, session_1.toNumber)(rows[0].jobs);
206
+ const perJob = sampled > 0 ? counted / sampled : 0;
207
+ return {
208
+ rows: exact ? counted : Math.round(perJob * eligibleJobs),
209
+ exact,
210
+ perJob: Math.round(perJob * 10) / 10,
211
+ sampled,
212
+ };
213
+ }
214
+ async function surveyStreams(context, criteria) {
215
+ const { client, schema, asOf, bucket } = context;
216
+ const table = `${schema}.${criteria.target}`;
217
+ const includeDeadLettered = criteria.includeDeadLettered === true;
218
+ const params = [criteria.before, asOf, includeDeadLettered];
219
+ // 1. Messages kept: unprocessed, processed after the cutoff, dead-lettered
220
+ const held = await client.query(`SELECT
221
+ (SELECT count(*) FROM ${table} WHERE expired_at IS NULL)::bigint AS unprocessed,
222
+ (SELECT count(*) FROM ${table}
223
+ WHERE expired_at IS NOT NULL AND expired_at >= $1::timestamptz)::bigint AS newer,
224
+ (SELECT count(*) FROM ${table}
225
+ WHERE expired_at IS NOT NULL AND expired_at < $1::timestamptz
226
+ AND expired_at < $2::timestamptz
227
+ AND dead_lettered_at IS NOT NULL AND NOT $3::boolean)::bigint AS dead_lettered`, params);
228
+ // 2. Eligible messages: total, range, histogram in one pass
229
+ const grouped = await client.query(`SELECT
230
+ GROUPING(date_trunc('${bucket}', s.expired_at)) AS grouping,
231
+ ${(0, sql_1.iso)(`date_trunc('${bucket}', s.expired_at)`)} AS bucket,
232
+ count(*)::bigint AS count,
233
+ ${(0, sql_1.iso)('min(s.expired_at)')} AS oldest,
234
+ ${(0, sql_1.iso)('max(s.expired_at)')} AS newest
235
+ FROM ${table} s
236
+ WHERE ${(0, sql_1.streamsEligible)('$1', '$2', '$3')}
237
+ GROUP BY GROUPING SETS ((date_trunc('${bucket}', s.expired_at)), ())`, params);
238
+ const total = grouped.rows.find((row) => row.grouping === 1);
239
+ const count = (0, session_1.toNumber)(total?.count);
240
+ const tables = [await (0, session_1.readTableStats)(client, table)];
241
+ return {
242
+ target: criteria.target,
243
+ before: criteria.before,
244
+ asOf,
245
+ includeDeadLettered,
246
+ eligible: count,
247
+ oldest: total?.oldest ?? null,
248
+ newest: total?.newest ?? null,
249
+ protected: {
250
+ unprocessed: (0, session_1.toNumber)(held.rows[0].unprocessed),
251
+ newerThanCutoffMessages: (0, session_1.toNumber)(held.rows[0].newer),
252
+ deadLettered: (0, session_1.toNumber)(held.rows[0].dead_lettered),
253
+ },
254
+ histogram: toHistogram(grouped.rows
255
+ .filter((row) => row.grouping === 0)
256
+ .sort((a, b) => a.bucket.localeCompare(b.bucket))),
257
+ estimatedBytes: Math.round(bytesPerRow(tables[0]) * count),
258
+ tables,
259
+ };
260
+ }
261
+ async function readHealth(client, schema) {
262
+ const version = await client.query('SHOW server_version');
263
+ const backlog = await client.query((0, sql_1.backlogSQL)(schema));
264
+ const replicationSlots = await (0, session_1.readReplicationSlots)(client);
265
+ const longTransactions = await readLongTransactions(client);
266
+ return {
267
+ serverVersion: version.rows[0].server_version,
268
+ backlog: {
269
+ engine: (0, session_1.toNumber)(backlog.rows[0].engine),
270
+ worker: (0, session_1.toNumber)(backlog.rows[0].worker),
271
+ },
272
+ replicationSlots,
273
+ longTransactions,
274
+ };
275
+ }
276
+ async function readLongTransactions(client) {
277
+ try {
278
+ const { rows } = await client.query(sql_1.longTransactionsSQL);
279
+ return rows.map((row) => ({
280
+ pid: Number(row.pid),
281
+ seconds: Number(row.seconds),
282
+ state: row.state ?? null,
283
+ query: row.query ?? null,
284
+ }));
285
+ }
286
+ catch {
287
+ return null;
288
+ }
289
+ }
@@ -111,6 +111,10 @@ export declare class EscalationClientService {
111
111
  */
112
112
  count(params?: ListEscalationsParams): Promise<number>;
113
113
  /**
114
+ * @deprecated Use `DBA.deleteRetentionBatch({ criteria: { target: 'escalations', ... } })`,
115
+ * which walks ended rows oldest first by end time, honors a minimum age,
116
+ * and keeps escalations named by open references such as undelivered relay outcomes.
117
+ *
114
118
  * Retention: deletes terminal escalation rows (`resolved`/`cancelled`/`expired`)
115
119
  * whose `updated_at` is older than the horizon (a Postgres interval string,
116
120
  * e.g. `'90 days'`). Terminal rows are inert — every engine state transition
@@ -238,6 +238,10 @@ class EscalationClientService {
238
238
  return hm.engine.store.countEscalations(params ?? {});
239
239
  }
240
240
  /**
241
+ * @deprecated Use `DBA.deleteRetentionBatch({ criteria: { target: 'escalations', ... } })`,
242
+ * which walks ended rows oldest first by end time, honors a minimum age,
243
+ * and keeps escalations named by open references such as undelivered relay outcomes.
244
+ *
241
245
  * Retention: deletes terminal escalation rows (`resolved`/`cancelled`/`expired`)
242
246
  * whose `updated_at` is older than the horizon (a Postgres interval string,
243
247
  * e.g. `'90 days'`). Terminal rows are inert — every engine state transition
@@ -1,6 +1,9 @@
1
1
  import { ProviderConfig } from './provider';
2
2
  /**
3
3
  * Options for `DBA.prune()`.
4
+ *
5
+ * @deprecated `DBA.prune()` is superseded by `DBA.surveyRetention()` and
6
+ * `DBA.deleteRetentionBatch()`.
4
7
  */
5
8
  export interface PruneOptions {
6
9
  /**