@substrat-run/kernel 0.210.0 → 0.212.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,135 @@
1
+ import { type Instant, type StaleScope, type StaleScopeFindingKind, type StaleScopeTake, type TenantId } from '@substrat-run/contracts';
2
+ import type { RedactionSql } from './subject-redaction.js';
3
+ /**
4
+ * The daily stale-scopes report (#3313), as statements both adapters run against their directory:
5
+ * the SQLite host over better-sqlite3, the hosted one inside ControlPlaneDO. Written once so the
6
+ * two cannot report different things about the same fleet.
7
+ *
8
+ * It finds the scopes nothing will ever clean up: an active scope nobody uses, a fork with no
9
+ * expiry, a scope stuck half-made, one whose tenant or vertical is gone. It REPORTS and never moves
10
+ * a scope: a person archives through the doors that exist, and the retention reap deletes. Every
11
+ * finding but `idle` is decided from the directory's own rows, so no scope is woken (§5.4).
12
+ *
13
+ * `idle` reads the daily request rollup (`request-rollup.ts`): a scope's "last used" is the newest
14
+ * UTC day the rollup counted a routed request for it. That is the router's count of the requests it
15
+ * dispatched, so a scope reached only by peer calls or schedules has none, and a scope used once a
16
+ * year looks like a dead one. Nothing is stamped on the request path: a last-seen write there would
17
+ * be a write to the singleton directory on every request.
18
+ *
19
+ * `_substrat_stale_scopes` holds one row per (scope, finding) the latest report made, with the first
20
+ * and latest report that made it, so the list says how long each has been true rather than raising
21
+ * a fresh alert every day. A finding the latest report no longer makes is deleted.
22
+ * `_substrat_stale_scope_takes` holds one row per day a pass tried, with `meterDayTake`'s rules: a
23
+ * day is reported once, and a failed attempt carries the run of identical failures it belongs to.
24
+ */
25
+ export declare const STALE_SCOPES_DDL = "\n CREATE TABLE IF NOT EXISTS _substrat_stale_scopes (\n scope_id TEXT NOT NULL,\n finding TEXT NOT NULL,\n tenant_id TEXT NOT NULL,\n vertical TEXT,\n kind TEXT,\n status TEXT NOT NULL,\n forked_from TEXT,\n created_at TEXT NOT NULL,\n last_request_day TEXT,\n detail TEXT NOT NULL,\n first_seen TEXT NOT NULL,\n last_seen TEXT NOT NULL,\n PRIMARY KEY (scope_id, finding)\n );\n CREATE INDEX IF NOT EXISTS _substrat_stale_scopes_tenant ON _substrat_stale_scopes (tenant_id, finding);\n CREATE TABLE IF NOT EXISTS _substrat_stale_scope_takes (\n day TEXT PRIMARY KEY,\n attempted_at TEXT NOT NULL,\n taken_at TEXT,\n finding_count INTEGER,\n idle_judged INTEGER,\n error TEXT,\n failing_since TEXT,\n failing_count INTEGER\n );\n";
26
+ /** How many days without a routed request make an active primary scope `idle`, by default. */
27
+ export declare const STALE_SCOPE_IDLE_DAYS = 30;
28
+ /**
29
+ * The shortest and longest idle windows. At least 3, because the two newest days may not be rolled
30
+ * up yet and a window must hold a day that is; at most 85, the request rollup's lookback, because a
31
+ * window it cannot cover is never judged.
32
+ */
33
+ export declare const STALE_SCOPE_IDLE_DAYS_MIN = 3;
34
+ export declare const STALE_SCOPE_IDLE_DAYS_MAX = 85;
35
+ /** How long a scope may sit in `provisioning` before it is `stuck-provisioning`, by default. */
36
+ export declare const STALE_SCOPE_STUCK_MS = 86400000;
37
+ /**
38
+ * How long past its `expiresAt` a fork may stay before it is `expired-not-reaped`, by default. The
39
+ * GC runs every pass, so a day is many failed attempts, never one that is merely due.
40
+ */
41
+ export declare const STALE_SCOPE_EXPIRED_GRACE_MS = 86400000;
42
+ /** How long one report may take before the pass counts the attempt failed, by default. */
43
+ export declare const STALE_SCOPES_TIMEOUT_MS = 30000;
44
+ /** The most rows one `listStaleScopes` call returns, and its default. */
45
+ export declare const STALE_SCOPES_LIMIT_MAX = 10000;
46
+ export declare const STALE_SCOPES_LIMIT_DEFAULT = 1000;
47
+ /** The thresholds a report judges by. Each defaults to the constant above. */
48
+ export interface StaleScopeThresholds {
49
+ /** `STALE_SCOPE_IDLE_DAYS_MIN` to `STALE_SCOPE_IDLE_DAYS_MAX`. */
50
+ idleAfterDays?: number;
51
+ stuckAfterMs?: number;
52
+ expiredGraceMs?: number;
53
+ }
54
+ /**
55
+ * One attempt at the report of the UTC day of `at`. Without `error` the directory takes it; with
56
+ * it, the attempt failed and only the failure is recorded, naming the run it extends.
57
+ */
58
+ export type StaleScopeTakeInput = ({
59
+ at: string;
60
+ } & StaleScopeThresholds) | {
61
+ at: string;
62
+ error: string;
63
+ failingSince?: string;
64
+ failingCount?: number;
65
+ };
66
+ /** What one attempt did. */
67
+ export interface StaleScopeTakeResult {
68
+ day: string;
69
+ /** Whether this call took the day's report. False on every later attempt of the day. */
70
+ taken: boolean;
71
+ /** Findings the report holds, by kind; all zero when not taken. */
72
+ findings: Record<StaleScopeFindingKind, number>;
73
+ /** Findings this report made that the one before it did not. */
74
+ opened: number;
75
+ /** Findings the report before it made that this one did not. */
76
+ resolved: number;
77
+ idleJudged: boolean;
78
+ }
79
+ /** Filter for `listStaleScopes`: ordered by (tenant, finding, first seen, scope), at most `limit` rows. */
80
+ export interface StaleScopeFilter {
81
+ tenantId?: TenantId;
82
+ finding?: StaleScopeFindingKind;
83
+ limit?: number;
84
+ }
85
+ /** Filter for `listStaleScopeTakes`: inclusive UTC days. */
86
+ export interface StaleScopeTakeFilter {
87
+ since?: string;
88
+ until?: string;
89
+ }
90
+ interface ScopeRow {
91
+ scope_id: string;
92
+ tenant_id: string;
93
+ vertical: string | null;
94
+ kind: string | null;
95
+ status: string;
96
+ forked_from: string | null;
97
+ created_at: string;
98
+ expires_at: string | null;
99
+ tenant_status?: string | null;
100
+ }
101
+ interface Finding {
102
+ row: ScopeRow;
103
+ finding: StaleScopeFindingKind;
104
+ detail: string;
105
+ }
106
+ /** Whether `idleAfterDays` is a whole number of days the report can judge. */
107
+ export declare function assertIdleDays(name: string, days: number): number;
108
+ /**
109
+ * Every finding the directory supports at `at`. Pure reads, in the caller's transaction.
110
+ * `idleJudged` is false when the request rollup has not read every day of the idle window, which
111
+ * is a fleet without the rollup (a self-hosted directory) or one that started it recently.
112
+ */
113
+ export declare function staleScopeFindingsAt(sql: RedactionSql, at: Instant, thresholds?: StaleScopeThresholds): {
114
+ findings: Finding[];
115
+ lastRequestDay: Map<string, string>;
116
+ idleJudged: boolean;
117
+ };
118
+ /**
119
+ * Record one attempt at the report of the UTC day of `input.at`, in the caller's transaction.
120
+ *
121
+ * Without an error, it takes the report unless the day already has one: it reads the findings
122
+ * (`staleScopeFindingsAt`), upserts each (a new one gets `firstSeen`, every one gets `lastSeen` and
123
+ * its current detail), deletes every listed finding it did not make, and marks the day taken. When
124
+ * idle was not judged, the listed `idle` findings are left as they were. Every row is parsed before
125
+ * the first write, so a row that does not parse refuses the whole day.
126
+ *
127
+ * With an error, it records only the attempt and its run, and never over a day already taken.
128
+ */
129
+ export declare function recordStaleScopeRows(sql: RedactionSql, input: StaleScopeTakeInput): StaleScopeTakeResult;
130
+ /** The current findings — see `StaleScopeFilter`. Every row is parsed on the way out. */
131
+ export declare function listStaleScopeRows(sql: RedactionSql, filter?: StaleScopeFilter): StaleScope[];
132
+ /** The report's record of each day it tried, in day order — see `StaleScopeTakeFilter`. */
133
+ export declare function listStaleScopeTakeRows(sql: RedactionSql, filter?: StaleScopeTakeFilter): StaleScopeTake[];
134
+ export {};
135
+ //# sourceMappingURL=stale-scopes.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"stale-scopes.d.ts","sourceRoot":"","sources":["../src/stale-scopes.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,KAAK,OAAO,EAEZ,KAAK,UAAU,EACf,KAAK,qBAAqB,EAC1B,KAAK,cAAc,EACnB,KAAK,QAAQ,EACd,MAAM,yBAAyB,CAAC;AACjC,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,wBAAwB,CAAC;AAI3D;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,eAAO,MAAM,gBAAgB,kyBA2B5B,CAAC;AAEF,8FAA8F;AAC9F,eAAO,MAAM,qBAAqB,KAAK,CAAC;AACxC;;;;GAIG;AACH,eAAO,MAAM,yBAAyB,IAAI,CAAC;AAC3C,eAAO,MAAM,yBAAyB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AG,cAAc,EAAE,CAgC7G"}
@@ -0,0 +1,308 @@
1
+ import { staleScope, staleScopeTake, } from '@substrat-run/contracts';
2
+ import { assertRowLimit } from './retention.js';
3
+ import { pushDayWindow, utcDayOf } from './billing-retention.js';
4
+ /**
5
+ * The daily stale-scopes report (#3313), as statements both adapters run against their directory:
6
+ * the SQLite host over better-sqlite3, the hosted one inside ControlPlaneDO. Written once so the
7
+ * two cannot report different things about the same fleet.
8
+ *
9
+ * It finds the scopes nothing will ever clean up: an active scope nobody uses, a fork with no
10
+ * expiry, a scope stuck half-made, one whose tenant or vertical is gone. It REPORTS and never moves
11
+ * a scope: a person archives through the doors that exist, and the retention reap deletes. Every
12
+ * finding but `idle` is decided from the directory's own rows, so no scope is woken (§5.4).
13
+ *
14
+ * `idle` reads the daily request rollup (`request-rollup.ts`): a scope's "last used" is the newest
15
+ * UTC day the rollup counted a routed request for it. That is the router's count of the requests it
16
+ * dispatched, so a scope reached only by peer calls or schedules has none, and a scope used once a
17
+ * year looks like a dead one. Nothing is stamped on the request path: a last-seen write there would
18
+ * be a write to the singleton directory on every request.
19
+ *
20
+ * `_substrat_stale_scopes` holds one row per (scope, finding) the latest report made, with the first
21
+ * and latest report that made it, so the list says how long each has been true rather than raising
22
+ * a fresh alert every day. A finding the latest report no longer makes is deleted.
23
+ * `_substrat_stale_scope_takes` holds one row per day a pass tried, with `meterDayTake`'s rules: a
24
+ * day is reported once, and a failed attempt carries the run of identical failures it belongs to.
25
+ */
26
+ export const STALE_SCOPES_DDL = `
27
+ CREATE TABLE IF NOT EXISTS _substrat_stale_scopes (
28
+ scope_id TEXT NOT NULL,
29
+ finding TEXT NOT NULL,
30
+ tenant_id TEXT NOT NULL,
31
+ vertical TEXT,
32
+ kind TEXT,
33
+ status TEXT NOT NULL,
34
+ forked_from TEXT,
35
+ created_at TEXT NOT NULL,
36
+ last_request_day TEXT,
37
+ detail TEXT NOT NULL,
38
+ first_seen TEXT NOT NULL,
39
+ last_seen TEXT NOT NULL,
40
+ PRIMARY KEY (scope_id, finding)
41
+ );
42
+ CREATE INDEX IF NOT EXISTS _substrat_stale_scopes_tenant ON _substrat_stale_scopes (tenant_id, finding);
43
+ CREATE TABLE IF NOT EXISTS _substrat_stale_scope_takes (
44
+ day TEXT PRIMARY KEY,
45
+ attempted_at TEXT NOT NULL,
46
+ taken_at TEXT,
47
+ finding_count INTEGER,
48
+ idle_judged INTEGER,
49
+ error TEXT,
50
+ failing_since TEXT,
51
+ failing_count INTEGER
52
+ );
53
+ `;
54
+ /** How many days without a routed request make an active primary scope `idle`, by default. */
55
+ export const STALE_SCOPE_IDLE_DAYS = 30;
56
+ /**
57
+ * The shortest and longest idle windows. At least 3, because the two newest days may not be rolled
58
+ * up yet and a window must hold a day that is; at most 85, the request rollup's lookback, because a
59
+ * window it cannot cover is never judged.
60
+ */
61
+ export const STALE_SCOPE_IDLE_DAYS_MIN = 3;
62
+ export const STALE_SCOPE_IDLE_DAYS_MAX = 85;
63
+ /** How long a scope may sit in `provisioning` before it is `stuck-provisioning`, by default. */
64
+ export const STALE_SCOPE_STUCK_MS = 86_400_000;
65
+ /**
66
+ * How long past its `expiresAt` a fork may stay before it is `expired-not-reaped`, by default. The
67
+ * GC runs every pass, so a day is many failed attempts, never one that is merely due.
68
+ */
69
+ export const STALE_SCOPE_EXPIRED_GRACE_MS = 86_400_000;
70
+ /** How long one report may take before the pass counts the attempt failed, by default. */
71
+ export const STALE_SCOPES_TIMEOUT_MS = 30_000;
72
+ /** The most rows one `listStaleScopes` call returns, and its default. */
73
+ export const STALE_SCOPES_LIMIT_MAX = 10_000;
74
+ export const STALE_SCOPES_LIMIT_DEFAULT = 1_000;
75
+ const DAY_MS = 86_400_000;
76
+ /** The statuses a scope still holds data or a slot in: every one but archived and reaped. */
77
+ const LIVE = `('provisioning', 'active', 'suspended', 'archiving')`;
78
+ /** A fork or a clean-room preview: `isPrimaryScope`'s negation, over a directory row. */
79
+ const COPY = `(s.forked_from IS NOT NULL OR s.kind = 'preview')`;
80
+ const emptyCounts = () => ({
81
+ 'tenant-not-active': 0,
82
+ 'vertical-gone': 0,
83
+ unreachable: 0,
84
+ 'stuck-provisioning': 0,
85
+ 'no-expiry': 0,
86
+ 'expired-not-reaped': 0,
87
+ 'archived-undated': 0,
88
+ idle: 0,
89
+ });
90
+ const SCOPE_COLUMNS = 's.scope_id, s.tenant_id, s.vertical, s.kind, s.status, s.forked_from, s.created_at, s.expires_at';
91
+ function positiveMs(name, value) {
92
+ if (!(Number.isFinite(value) && value >= 0))
93
+ throw new Error(`${name} must be a non-negative number of ms, got ${String(value)}`);
94
+ return value;
95
+ }
96
+ /** Whether `idleAfterDays` is a whole number of days the report can judge. */
97
+ export function assertIdleDays(name, days) {
98
+ if (!(Number.isInteger(days) && days >= STALE_SCOPE_IDLE_DAYS_MIN && days <= STALE_SCOPE_IDLE_DAYS_MAX)) {
99
+ throw new Error(`${name} must be a whole number of days from ${STALE_SCOPE_IDLE_DAYS_MIN} to ${STALE_SCOPE_IDLE_DAYS_MAX}, got ${String(days)}`);
100
+ }
101
+ return days;
102
+ }
103
+ /**
104
+ * Every finding the directory supports at `at`. Pure reads, in the caller's transaction.
105
+ * `idleJudged` is false when the request rollup has not read every day of the idle window, which
106
+ * is a fleet without the rollup (a self-hosted directory) or one that started it recently.
107
+ */
108
+ export function staleScopeFindingsAt(sql, at, thresholds = {}) {
109
+ const atMs = Date.parse(at);
110
+ const idleDays = assertIdleDays('idleAfterDays', thresholds.idleAfterDays ?? STALE_SCOPE_IDLE_DAYS);
111
+ const stuckBefore = new Date(atMs - positiveMs('stuckAfterMs', thresholds.stuckAfterMs ?? STALE_SCOPE_STUCK_MS)).toISOString();
112
+ const expiredBefore = new Date(atMs - positiveMs('expiredGraceMs', thresholds.expiredGraceMs ?? STALE_SCOPE_EXPIRED_GRACE_MS)).toISOString();
113
+ const findings = [];
114
+ const add = (rows, finding, detail) => {
115
+ for (const row of rows)
116
+ findings.push({ row, finding, detail: detail(row) });
117
+ };
118
+ add(sql(`SELECT ${SCOPE_COLUMNS}, t.status AS tenant_status FROM scopes s LEFT JOIN tenants t ON t.tenant_id = s.tenant_id
119
+ WHERE s.status IN ${LIVE} AND (t.status IS NULL OR t.status <> 'active')`, []), 'tenant-not-active', (r) => (r.tenant_status ? `its tenant is ${r.tenant_status}` : 'its tenant is gone from the directory'));
120
+ add(sql(`SELECT ${SCOPE_COLUMNS} FROM scopes s
121
+ WHERE s.status IN ${LIVE} AND s.vertical IS NOT NULL
122
+ AND NOT EXISTS (SELECT 1 FROM verticals v WHERE v.slug = s.vertical)`, []), 'vertical-gone', (r) => `its vertical ${r.vertical} is gone from the registry`);
123
+ add(sql(`SELECT ${SCOPE_COLUMNS} FROM scopes s
124
+ WHERE s.status = 'active' AND NOT ${COPY}
125
+ AND NOT EXISTS (SELECT 1 FROM hostnames h WHERE h.scope_id = s.scope_id)
126
+ AND NOT EXISTS (SELECT 1 FROM peer_bindings p WHERE p.target_scope_id = s.scope_id AND p.invalidated = 0)`, []), 'unreachable', () => 'no hostname and no peer binding reaches it');
127
+ add(sql(`SELECT ${SCOPE_COLUMNS} FROM scopes s WHERE s.status = 'provisioning' AND s.created_at <= ?`, [stuckBefore]), 'stuck-provisioning', (r) => `still provisioning since ${r.created_at}`);
128
+ add(sql(`SELECT ${SCOPE_COLUMNS} FROM scopes s WHERE ${COPY} AND s.expires_at IS NULL AND s.status IN ${LIVE}`, []), 'no-expiry', (r) => r.forked_from
129
+ ? `a copy of ${r.forked_from} with no expiry: the snapshot GC never reaps it`
130
+ : 'a preview with no expiry: the snapshot GC never reaps it');
131
+ add(sql(`SELECT ${SCOPE_COLUMNS} FROM scopes s
132
+ WHERE ${COPY} AND s.expires_at IS NOT NULL AND s.expires_at <= ? AND s.status <> 'reaped'`, [expiredBefore]), 'expired-not-reaped', (r) => `expired at ${r.expires_at ?? ''} and the snapshot GC has not reaped it`);
133
+ add(sql(`SELECT ${SCOPE_COLUMNS} FROM scopes s WHERE s.status = 'archived' AND s.archived_at IS NULL`, []), 'archived-undated', () => 'archived with no archivedAt: the retention reap skips it');
134
+ const lastRequestDay = new Map(sql(`SELECT scope_id, MAX(day) AS day FROM _substrat_request_days WHERE requests > 0 GROUP BY scope_id`, []).map((r) => [r.scope_id, r.day]));
135
+ // Idle is judged only over a window the rollup has read: its first day, and every day after it
136
+ // that has ended and settled. A gap (a day whose read failed and waits its retry) holds the
137
+ // judgement back rather than reading as a day without traffic.
138
+ const windowStart = utcDayOf(atMs - idleDays * DAY_MS);
139
+ const lastDay = utcDayOf(atMs - 2 * DAY_MS);
140
+ const read = sql(`SELECT COUNT(*) AS n FROM _substrat_request_day_reads WHERE day >= ? AND day <= ? AND read_at IS NOT NULL`, [windowStart, lastDay]);
141
+ const windowDays = Math.round((Date.parse(`${lastDay}T00:00:00Z`) - Date.parse(`${windowStart}T00:00:00Z`)) / DAY_MS) + 1;
142
+ const idleJudged = (read[0]?.n ?? 0) >= windowDays;
143
+ if (idleJudged) {
144
+ const idleSince = new Date(atMs - idleDays * DAY_MS).toISOString();
145
+ const candidates = sql(`SELECT ${SCOPE_COLUMNS} FROM scopes s WHERE s.status = 'active' AND NOT ${COPY} AND s.created_at <= ?`, [idleSince]);
146
+ for (const row of candidates) {
147
+ const last = lastRequestDay.get(row.scope_id);
148
+ if (last !== undefined && last >= windowStart)
149
+ continue;
150
+ findings.push({
151
+ row,
152
+ finding: 'idle',
153
+ detail: last
154
+ ? `no routed request in ${idleDays} days; the last was on ${last}`
155
+ : `no routed request in ${idleDays} days, and none on record`,
156
+ });
157
+ }
158
+ }
159
+ return { findings, lastRequestDay, idleJudged };
160
+ }
161
+ /**
162
+ * Record one attempt at the report of the UTC day of `input.at`, in the caller's transaction.
163
+ *
164
+ * Without an error, it takes the report unless the day already has one: it reads the findings
165
+ * (`staleScopeFindingsAt`), upserts each (a new one gets `firstSeen`, every one gets `lastSeen` and
166
+ * its current detail), deletes every listed finding it did not make, and marks the day taken. When
167
+ * idle was not judged, the listed `idle` findings are left as they were. Every row is parsed before
168
+ * the first write, so a row that does not parse refuses the whole day.
169
+ *
170
+ * With an error, it records only the attempt and its run, and never over a day already taken.
171
+ */
172
+ export function recordStaleScopeRows(sql, input) {
173
+ const at = new Date(input.at).toISOString();
174
+ const day = at.slice(0, 10);
175
+ const none = { day, taken: false, findings: emptyCounts(), opened: 0, resolved: 0, idleJudged: false };
176
+ if ('error' in input) {
177
+ const since = new Date(input.failingSince ?? at).toISOString();
178
+ const count = input.failingCount ?? 1;
179
+ if (!(Number.isInteger(count) && count >= 1)) {
180
+ throw new Error(`failingCount must be a whole number, at least one, got ${String(count)}`);
181
+ }
182
+ sql(`INSERT INTO _substrat_stale_scope_takes
183
+ (day, attempted_at, taken_at, finding_count, idle_judged, error, failing_since, failing_count)
184
+ VALUES (?, ?, NULL, NULL, NULL, ?, ?, ?)
185
+ ON CONFLICT (day) DO UPDATE SET
186
+ attempted_at = excluded.attempted_at, error = excluded.error,
187
+ failing_since = excluded.failing_since, failing_count = excluded.failing_count
188
+ WHERE _substrat_stale_scope_takes.taken_at IS NULL`, [day, at, input.error || 'the report failed', since, count]);
189
+ return none;
190
+ }
191
+ const prior = sql('SELECT taken_at FROM _substrat_stale_scope_takes WHERE day = ?', [day]);
192
+ if (prior[0]?.taken_at)
193
+ return none;
194
+ const { findings, lastRequestDay, idleJudged } = staleScopeFindingsAt(sql, at, input);
195
+ const tenantSlug = new Map(sql('SELECT tenant_id, slug FROM tenants', []).map((t) => [t.tenant_id, t.slug]));
196
+ const existing = new Map(sql('SELECT scope_id, finding, first_seen FROM _substrat_stale_scopes', []).map((r) => [`${r.scope_id} ${r.finding}`, r.first_seen]));
197
+ // Parsed before the first write: a row that does not read as a finding refuses the day.
198
+ const rows = findings.map((f) => staleScope.parse({
199
+ tenantId: f.row.tenant_id,
200
+ tenantSlug: tenantSlug.get(f.row.tenant_id) ?? null,
201
+ scopeId: f.row.scope_id,
202
+ finding: f.finding,
203
+ vertical: f.row.vertical,
204
+ kind: f.row.kind,
205
+ status: f.row.status,
206
+ forkedFrom: f.row.forked_from,
207
+ createdAt: f.row.created_at,
208
+ lastRequestDay: lastRequestDay.get(f.row.scope_id) ?? null,
209
+ detail: f.detail,
210
+ firstSeen: existing.get(`${f.row.scope_id} ${f.finding}`) ?? at,
211
+ lastSeen: at,
212
+ }));
213
+ const counts = emptyCounts();
214
+ let opened = 0;
215
+ for (const r of rows) {
216
+ counts[r.finding] += 1;
217
+ if (!existing.has(`${r.scopeId} ${r.finding}`))
218
+ opened += 1;
219
+ sql(`INSERT INTO _substrat_stale_scopes
220
+ (scope_id, finding, tenant_id, vertical, kind, status, forked_from, created_at, last_request_day, detail, first_seen, last_seen)
221
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
222
+ ON CONFLICT (scope_id, finding) DO UPDATE SET
223
+ tenant_id = excluded.tenant_id, vertical = excluded.vertical, kind = excluded.kind, status = excluded.status,
224
+ forked_from = excluded.forked_from, created_at = excluded.created_at,
225
+ last_request_day = excluded.last_request_day, detail = excluded.detail, last_seen = excluded.last_seen`, [
226
+ r.scopeId,
227
+ r.finding,
228
+ r.tenantId,
229
+ r.vertical,
230
+ r.kind,
231
+ r.status,
232
+ r.forkedFrom,
233
+ r.createdAt,
234
+ r.lastRequestDay,
235
+ r.detail,
236
+ r.firstSeen,
237
+ r.lastSeen,
238
+ ]);
239
+ }
240
+ const keep = idleJudged ? '' : ` AND finding <> 'idle'`;
241
+ const resolved = sql(`SELECT COUNT(*) AS n FROM _substrat_stale_scopes WHERE last_seen <> ?${keep}`, [at])[0]?.n ?? 0;
242
+ sql(`DELETE FROM _substrat_stale_scopes WHERE last_seen <> ?${keep}`, [at]);
243
+ if (!idleJudged)
244
+ counts.idle = sql(`SELECT COUNT(*) AS n FROM _substrat_stale_scopes WHERE finding = 'idle'`, [])[0]?.n ?? 0;
245
+ const total = Object.values(counts).reduce((a, b) => a + b, 0);
246
+ sql(`INSERT INTO _substrat_stale_scope_takes
247
+ (day, attempted_at, taken_at, finding_count, idle_judged, error, failing_since, failing_count)
248
+ VALUES (?, ?, ?, ?, ?, NULL, NULL, NULL)
249
+ ON CONFLICT (day) DO UPDATE SET
250
+ attempted_at = excluded.attempted_at, taken_at = excluded.taken_at, finding_count = excluded.finding_count,
251
+ idle_judged = excluded.idle_judged, error = NULL, failing_since = NULL, failing_count = NULL`, [day, at, at, total, idleJudged ? 1 : 0]);
252
+ return { day, taken: true, findings: counts, opened, resolved, idleJudged };
253
+ }
254
+ /** The current findings — see `StaleScopeFilter`. Every row is parsed on the way out. */
255
+ export function listStaleScopeRows(sql, filter = {}) {
256
+ const where = [];
257
+ const params = [];
258
+ if (filter.tenantId !== undefined) {
259
+ where.push('f.tenant_id = ?');
260
+ params.push(filter.tenantId);
261
+ }
262
+ if (filter.finding !== undefined) {
263
+ where.push('f.finding = ?');
264
+ params.push(filter.finding);
265
+ }
266
+ params.push(Math.min(assertRowLimit('limit', filter.limit ?? STALE_SCOPES_LIMIT_DEFAULT), STALE_SCOPES_LIMIT_MAX));
267
+ const rows = sql(`SELECT f.scope_id, f.finding, f.tenant_id, t.slug AS tenant_slug, f.vertical, f.kind, f.status, f.forked_from,
268
+ f.created_at, f.last_request_day, f.detail, f.first_seen, f.last_seen
269
+ FROM _substrat_stale_scopes f LEFT JOIN tenants t ON t.tenant_id = f.tenant_id
270
+ ${where.length ? `WHERE ${where.join(' AND ')}` : ''}
271
+ ORDER BY f.tenant_id, f.finding, f.first_seen, f.scope_id LIMIT ?`, params);
272
+ return rows.map((r) => staleScope.parse({
273
+ tenantId: r.tenant_id,
274
+ tenantSlug: r.tenant_slug,
275
+ scopeId: r.scope_id,
276
+ finding: r.finding,
277
+ vertical: r.vertical,
278
+ kind: r.kind,
279
+ status: r.status,
280
+ forkedFrom: r.forked_from,
281
+ createdAt: r.created_at,
282
+ lastRequestDay: r.last_request_day,
283
+ detail: r.detail,
284
+ firstSeen: r.first_seen,
285
+ lastSeen: r.last_seen,
286
+ }));
287
+ }
288
+ /** The report's record of each day it tried, in day order — see `StaleScopeTakeFilter`. */
289
+ export function listStaleScopeTakeRows(sql, filter = {}) {
290
+ const where = [];
291
+ const params = [];
292
+ pushDayWindow(filter, where, params);
293
+ const rows = sql(`SELECT day, attempted_at, taken_at, finding_count, idle_judged, error, failing_since, failing_count
294
+ FROM _substrat_stale_scope_takes
295
+ ${where.length ? `WHERE ${where.join(' AND ')}` : ''}
296
+ ORDER BY day`, params);
297
+ return rows.map((r) => staleScopeTake.parse({
298
+ day: r.day,
299
+ attemptedAt: r.attempted_at,
300
+ takenAt: r.taken_at,
301
+ findings: r.finding_count,
302
+ idleJudged: r.idle_judged === null ? null : r.idle_judged === 1,
303
+ error: r.error,
304
+ failingSince: r.failing_since,
305
+ failingCount: r.failing_count,
306
+ }));
307
+ }
308
+ //# sourceMappingURL=stale-scopes.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"stale-scopes.js","sourceRoot":"","sources":["../src/stale-scopes.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,UAAU,EACV,cAAc,GAOf,MAAM,yBAAyB,CAAC;AAEjC,OAAO,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAChD,OAAO,EAAE,aAAa,EAAE,QAAQ,EAAE,MAAM,wBAAwB,CAAC;AAEjE;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,MAAM,CAAC,MAAM,gBAAgB,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;CA2B/B,CAAC;AAEF,8FAA8F;AAC9F,MAAM,CAAC,MAAM,qBAAqB,GAAG,EAAE,CAAC;AACxC;;;;GAIG;AACH,MAAM,CAAC,MAAM,yBAAyB,GAAG,CAAC,CAAC;AAC3C,MAAM,CAAC,MAAM,yBAAyB,GAAG,EAAE,CAAC;AAC5C,gGAAgG;AAChG,MAAM,CAAC,MAAM,oBAAoB,GAAG,UAAU,CAAC;AAC/C;;;GAGG;AACH,MAAM,CAAC,MAAM,4BAA4B,GAAG,UAAU,CAAC;AACvD,0FAA0F;A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,CAAC,YAAY;QAC3B,OAAO,EAAE,CAAC,CAAC,QAAQ;QACnB,QAAQ,EAAE,CAAC,CAAC,aAAa;QACzB,UAAU,EAAE,CAAC,CAAC,WAAW,KAAK,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,WAAW,KAAK,CAAC;QAC/D,KAAK,EAAE,CAAC,CAAC,KAAK;QACd,YAAY,EAAE,CAAC,CAAC,aAAa;QAC7B,YAAY,EAAE,CAAC,CAAC,aAAa;KAC9B,CAAC,CACH,CAAC;AACJ,CAAC"}
@@ -17,9 +17,12 @@
17
17
  *
18
18
  * Paging: each source is walked in turn, events first and then each declared entity in
19
19
  * registration order, until the page's budget of events plus rows is spent. The cursor names the
20
- * source and where in it to resume. An entity's rows are paged by offset in the table's own scan
21
- * order, which is stable while the scope does not change between pages; the caller reads the pages
22
- * of one request back to back.
20
+ * source and where in it to resume. The pages of one request are separate reads (a separate RPC on
21
+ * a Durable Object), so the scope can change between them, and both sources resume by key: events
22
+ * after the last outbox id, an entity's rows after the last primary key in key order (#3303). A row
23
+ * written or deleted between two pages then repeats or skips no other row. A manifest derived
24
+ * before the erasure declaration carried the key has none to seek on; its rows are paged by offset
25
+ * in scan order, and each listing says which (`paging`), so the package can state it.
23
26
  */
24
27
  import { type SubjectReadPage, type SubjectReadRequest } from '@substrat-run/contracts';
25
28
  import { type ModuleErasurePlan } from './module-erasure.js';
@@ -1 +1 @@
1
- {"version":3,"file":"subject-access.d.ts","sourceRoot":"","sources":["../src/subject-access.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,OAAO,EAKL,KAAK,eAAe,EACpB,KAAK,kBAAkB,EAGxB,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAAkC,KAAK,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AAC7F,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AA0CjD;;;;GAIG;AACH,wBAAgB,eAAe,CAAC,KAAK,EAAE;IACrC,QAAQ,CAAC,GAAG,EAAE,IAAI,CAAC,SAAS,EAAE,OAAO,CAAC,CAAC;IACvC,QAAQ,CAAC,KAAK,EAAE,SAAS,iBAAiB,EAAE,CAAC;IAC7C,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,IAAI,CAAC,EAAE,kBAAkB,CAAC;CACpC,GAAG,eAAe,CA4DlB"}
1
+ {"version":3,"file":"subject-access.d.ts","sourceRoot":"","sources":["../src/subject-access.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,OAAO,EAKL,KAAK,eAAe,EACpB,KAAK,kBAAkB,EAGxB,MAAM,yBAAyB,CAAC;AAEjC,OAAO,EAAmD,KAAK,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AAC9G,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AA0FjD;;;;GAIG;AACH,wBAAgB,eAAe,CAAC,KAAK,EAAE;IACrC,QAAQ,CAAC,GAAG,EAAE,IAAI,CAAC,SAAS,EAAE,OAAO,CAAC,CAAC;IACvC,QAAQ,CAAC,KAAK,EAAE,SAAS,iBAAiB,EAAE,CAAC;IAC7C,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,IAAI,CAAC,EAAE,kBAAkB,CAAC;CACpC,GAAG,eAAe,CA2FlB"}