@pramen/server 0.0.14 → 0.0.16

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.
@@ -5,10 +5,30 @@
5
5
  // Reconciles the live store with the declared schema in two passes:
6
6
  // 1. additive (no data loss): missing table -> CREATE TABLE; missing column ->
7
7
  // ALTER TABLE ADD COLUMN (nullable).
8
- // 2. destructive: a live column the schema no longer declares is DROPPED, a type
9
- // change is applied, and a `renamedFrom` column is renamed — all via the
10
- // standard SQLite table-rebuild (create new, copy, drop old, rename). This is
11
- // auto-applied: a bad deploy CAN lose data, by design (WIP, no backward-compat).
8
+ // 2. reconcile existing columns + drop obsolete ones. A live column the schema no
9
+ // longer declares is DROPPED, a type change is applied, a `renamedFrom` column is
10
+ // renamed, and a MODIFIER change on an existing column (NOT NULL / DEFAULT /
11
+ // PRIMARY KEY) is enacted all via the standard SQLite table-rebuild (create new,
12
+ // copy, drop old, rename); UNIQUE is reconciled with a CREATE/DROP INDEX. Each
13
+ // change is classified SAFE (loses no data — applied always: a DEFAULT add/change,
14
+ // dropping a constraint, adding NOT NULL when a backfill/default covers it, adding
15
+ // UNIQUE with no duplicates) or DESTRUCTIVE (GATED behind PRAMEN_ALLOW_DESTRUCTIVE,
16
+ // off by default: a drop, a type change, a rename, a PRIMARY KEY change, adding
17
+ // NOT NULL over NULL rows with no default). Adding UNIQUE over duplicate values is
18
+ // always SKIPPED (the index can't build). `hidden()`/`generated()` are ORM-only —
19
+ // no physical column change, so they don't appear here.
20
+ //
21
+ // The guiding invariant: the schema hash is recorded ONLY when the store fully matches
22
+ // the schema. Any detected change that is SKIPPED (destructive-gated, a UNIQUE-over-
23
+ // duplicates, or a partition MOVE — see below) leaves the hash UNWRITTEN, so `schema
24
+ // status` keeps reporting drift and a later opt-in / data-fixed deploy retries. This is
25
+ // what stops a modifier change (e.g. an unenforced NOT NULL) from silently diverging the
26
+ // store from the schema while the hash claims "in sync". Local dev sets the flag on; a
27
+ // bad deploy CAN then lose data (WIP, no backward-compat).
28
+ //
29
+ // A partition MOVE (an entity reassigned to a different Durable Object) is never auto-
30
+ // applied — the data can't cross DOs — so it's detected and reported as a skipped manual
31
+ // migration (hash withheld), leaving the source DO's data intact.
12
32
  //
13
33
  // A schema hash in the internal `_pramen_meta` table lets an unchanged schema skip
14
34
  // introspection entirely on warm boots. The live table (PRAGMA) is the ground
@@ -18,10 +38,10 @@
18
38
  // A rename can't be inferred from a diff (a removed + added column is ambiguous),
19
39
  // so it must be declared with `renamedFrom`; otherwise it is applied as drop+add.
20
40
 
21
- import { addColumnSql, createTableSql, indexStatements, sqlType } from "./ddl";
41
+ import { addColumnSql, createTableSql, defaultSqlValue, indexName, indexStatements, sqlType } from "./ddl";
22
42
  import { digest } from "./digest";
23
43
  import { quoteIdent, type Driver } from "./driver";
24
- import { entitiesInPartition, validateSchema } from "../sdk/schema";
44
+ import { entitiesInPartition, partitionOf, validateSchema } from "../sdk/schema";
25
45
  import type { EntityFields, FieldDef, SchemaDef } from "../sdk/schema";
26
46
 
27
47
  export interface MigrationReport {
@@ -79,6 +99,95 @@ async function tableColumns(driver: Driver, table: string): Promise<Map<string,
79
99
  return new Map(rows.map((r) => [r.name, (r.type || "").toUpperCase()]));
80
100
  }
81
101
 
102
+ /** The constraint-bearing facts a migrator compares against a schema field's modifiers:
103
+ * SQL type, NOT NULL, PRIMARY KEY membership, and the raw DEFAULT text (as reported by
104
+ * PRAGMA — e.g. `'pending'`, `1`, `datetime('now')`, or null). */
105
+ interface LiveColumn {
106
+ type: string;
107
+ notNull: boolean;
108
+ pk: boolean;
109
+ default: string | null;
110
+ }
111
+
112
+ /** Full live column info (type + modifiers) via PRAGMA table_info. Empty if absent. */
113
+ async function liveColumnInfo(driver: Driver, table: string): Promise<Map<string, LiveColumn>> {
114
+ const rows = (await driver.exec(`PRAGMA table_info(${quoteIdent(table)})`, [])) as {
115
+ name: string;
116
+ type: string;
117
+ notnull: number;
118
+ dflt_value: string | null;
119
+ pk: number;
120
+ }[];
121
+ const out = new Map<string, LiveColumn>();
122
+ for (const r of rows) {
123
+ out.set(r.name, {
124
+ type: (r.type || "").toUpperCase(),
125
+ notNull: r.notnull === 1,
126
+ pk: r.pk > 0,
127
+ default: r.dflt_value ?? null,
128
+ });
129
+ }
130
+ return out;
131
+ }
132
+
133
+ /** The columns backed by a single-column UNIQUE index (a `unique()` constraint). Reads
134
+ * PRAGMA index_list + index_info; multi-column indexes are ignored (pramen only emits
135
+ * single-column ones). */
136
+ async function liveUniqueColumns(driver: Driver, table: string): Promise<Set<string>> {
137
+ const idx = (await driver.exec(`PRAGMA index_list(${quoteIdent(table)})`, [])) as { name: string; unique: number }[];
138
+ const out = new Set<string>();
139
+ for (const i of idx) {
140
+ if (i.unique !== 1) continue;
141
+ const cols = (await driver.exec(`PRAGMA index_info(${quoteIdent(i.name)})`, [])) as { name: string | null }[];
142
+ if (cols.length === 1 && cols[0]?.name) out.add(cols[0].name);
143
+ }
144
+ return out;
145
+ }
146
+
147
+ /** Does the column currently hold any NULL? (Adding NOT NULL to such a column is
148
+ * unsafe without a backfill default.) */
149
+ async function columnHasNulls(driver: Driver, table: string, col: string): Promise<boolean> {
150
+ const rows = await driver.exec(`SELECT 1 FROM ${quoteIdent(table)} WHERE ${quoteIdent(col)} IS NULL LIMIT 1`, []);
151
+ return rows.length > 0;
152
+ }
153
+
154
+ /** Does the column hold a duplicate non-NULL value? (Adding UNIQUE to such a column
155
+ * can't build the index.) NULLs are never "equal" in SQLite, so they're excluded. */
156
+ async function columnHasDuplicates(driver: Driver, table: string, col: string): Promise<boolean> {
157
+ const rows = await driver.exec(
158
+ `SELECT ${quoteIdent(col)} FROM ${quoteIdent(table)} WHERE ${quoteIdent(col)} IS NOT NULL GROUP BY ${quoteIdent(col)} HAVING COUNT(*) > 1 LIMIT 1`,
159
+ [],
160
+ );
161
+ return rows.length > 0;
162
+ }
163
+
164
+ /** Normalize a DEFAULT's SQL text for comparison: trim, and strip balanced outer
165
+ * parens (SQLite reports an expr default with or without the wrapping parens the DDL
166
+ * emitted — `(datetime('now'))` vs `datetime('now')` — depending on the engine, so the
167
+ * comparison must not depend on them). */
168
+ function normalizeDefault(s: string | null): string | null {
169
+ if (s == null) return null;
170
+ let t = s.trim();
171
+ while (t.length >= 2 && t[0] === "(" && t[t.length - 1] === ")" && outerParensBalanced(t)) {
172
+ t = t.slice(1, -1).trim();
173
+ }
174
+ return t;
175
+ }
176
+
177
+ /** Does the leading `(` in `t` match the trailing `)` (i.e. is the whole string wrapped
178
+ * in one paren group)? Prevents stripping `(a) + (b)`. */
179
+ function outerParensBalanced(t: string): boolean {
180
+ let depth = 0;
181
+ for (let i = 0; i < t.length; i++) {
182
+ if (t[i] === "(") depth++;
183
+ else if (t[i] === ")") {
184
+ depth--;
185
+ if (depth === 0 && i !== t.length - 1) return false;
186
+ }
187
+ }
188
+ return depth === 0;
189
+ }
190
+
82
191
  async function readMeta(driver: Driver, key: string): Promise<string | undefined> {
83
192
  const rows = (await driver.exec(`SELECT value FROM _pramen_meta WHERE key = ?`, [key])) as { value: string }[];
84
193
  return rows[0]?.value;
@@ -103,8 +212,15 @@ async function rebuildTable(driver: Driver, table: string, def: { fields: Entity
103
212
  const src = f.renamedFrom && live.has(f.renamedFrom) ? f.renamedFrom : live.has(name) ? name : undefined;
104
213
  if (!src) continue; // brand-new column with no source -> leave NULL
105
214
  const target = sqlType(f);
215
+ let expr = live.get(src) === target ? quoteIdent(src) : `CAST(${quoteIdent(src)} AS ${target})`;
216
+ // Backfill NULLs when the target is NOT NULL and carries a default — makes adding
217
+ // NOT NULL to a column with NULL rows safe (the copy fills them from the default),
218
+ // instead of the INSERT failing the new NOT NULL constraint.
219
+ const notNull = !!f.notNull || !!f.primaryKey;
220
+ const dflt = defaultSqlValue(f);
221
+ if (notNull && dflt !== null) expr = `COALESCE(${expr}, ${dflt})`;
106
222
  destCols.push(quoteIdent(name));
107
- srcExprs.push(live.get(src) === target ? quoteIdent(src) : `CAST(${quoteIdent(src)} AS ${target})`);
223
+ srcExprs.push(expr);
108
224
  }
109
225
  if (destCols.length > 0) {
110
226
  await driver.exec(`INSERT INTO ${quoteIdent(tmp)} (${destCols.join(", ")}) SELECT ${srcExprs.join(", ")} FROM ${quoteIdent(table)}`, []);
@@ -149,6 +265,9 @@ export async function migrate(driver: Driver, schema: SchemaDef, opts: MigrateOp
149
265
  const rebuilt: string[] = [];
150
266
  const droppedTables: string[] = [];
151
267
  const skipped: string[] = [];
268
+ // Per-table: columns whose new `unique()` can't be indexed (duplicate values) — the
269
+ // index pass must skip them so it doesn't throw. They're already reported in `skipped`.
270
+ const uniqueIndexSkip = new Map<string, Set<string>>();
152
271
 
153
272
  for (const [table, def] of entries) {
154
273
  const existing = await tableColumns(driver, table);
@@ -173,9 +292,13 @@ export async function migrate(driver: Driver, schema: SchemaDef, opts: MigrateOp
173
292
  added.push(`${table}.${name}`);
174
293
  }
175
294
 
176
- // Pass 2 — destructive: rebuild if any live column must be dropped, a declared
177
- // column changed type, or a rename hint points at an existing live column.
178
- const live = await tableColumns(driver, table); // re-read (now includes additively-added columns)
295
+ // Pass 2 — reconcile existing columns against the schema. Rebuild the table when a
296
+ // live column must be dropped, a declared column changed type, a rename hint points
297
+ // at an existing live column, or a MODIFIER changed on an existing column (NOT NULL,
298
+ // DEFAULT, PRIMARY KEY). UNIQUE is reconciled with an index (create/drop), no rebuild.
299
+ const liveInfo = await liveColumnInfo(driver, table); // re-read (includes additively-added columns)
300
+ const liveUnique = await liveUniqueColumns(driver, table);
301
+ const live = new Map([...liveInfo].map(([name, info]) => [name, info.type] as const)); // name -> type
179
302
  const desired = new Set(Object.keys(def.fields));
180
303
  const renamedSources = new Set<string>();
181
304
  for (const f of Object.values(def.fields)) {
@@ -186,24 +309,117 @@ export async function migrate(driver: Driver, schema: SchemaDef, opts: MigrateOp
186
309
  const needsTypeChange = Object.entries(def.fields).some(
187
310
  ([n, f]) => live.has(n) && live.get(n) !== sqlType(f as FieldDef),
188
311
  );
189
- const destructive = needsDrop || needsTypeChange || renamedSources.size > 0;
312
+
313
+ // Modifier reconciliation on existing (same-named) columns. A change to NOT NULL /
314
+ // DEFAULT / PRIMARY KEY is enacted by a table rebuild (which reconstructs the column
315
+ // to its exact declared shape); UNIQUE is an index op. Classify each as either a
316
+ // SAFE change (loses no data — applied always) or a DESTRUCTIVE one (gated behind
317
+ // allowDestructive). `hidden()`/`generated()` are ORM-only (no physical column
318
+ // change), so they never appear here.
319
+ let modifierRebuildSafe = false; // default add/change/remove, notNull widen, safe notNull add
320
+ let modifierRebuildDestructive = false; // notNull add over NULL rows w/o default, PK change
321
+ const destructiveReasons: string[] = [];
322
+ const dropUniqueCols: string[] = []; // `unique()` removed -> drop the managed index
323
+ for (const [name, field] of Object.entries(def.fields)) {
324
+ const info = liveInfo.get(name);
325
+ if (!info) continue; // new column (Pass 1) or a rename target — not an existing column
326
+ const f = field as FieldDef;
327
+ const fieldPk = !!f.primaryKey;
328
+ const fieldNotNull = !!f.notNull || fieldPk;
329
+
330
+ // DEFAULT add / change / remove — a rebuild backfills existing rows and applies the
331
+ // new default going forward; no data loss.
332
+ if (normalizeDefault(defaultSqlValue(f)) !== normalizeDefault(info.default)) modifierRebuildSafe = true;
333
+
334
+ // NOT NULL — PRAGMA reports notnull=0 for a PRIMARY KEY column, so only compare on
335
+ // non-PK columns (PK-ness is compared separately below).
336
+ if (!fieldPk && !info.pk) {
337
+ if (fieldNotNull && !info.notNull) {
338
+ const backfillable = defaultSqlValue(f) !== null;
339
+ if (!backfillable && (await columnHasNulls(driver, table, name))) {
340
+ modifierRebuildDestructive = true;
341
+ destructiveReasons.push(`NOT NULL ${name} (NULL rows, no default)`);
342
+ } else {
343
+ modifierRebuildSafe = true; // no NULLs, or backfilled from the default
344
+ }
345
+ } else if (!fieldNotNull && info.notNull) {
346
+ modifierRebuildSafe = true; // dropping NOT NULL only widens — safe
347
+ }
348
+ }
349
+
350
+ // PRIMARY KEY change — reshapes the table's key; treat as destructive.
351
+ if (fieldPk !== info.pk) {
352
+ modifierRebuildDestructive = true;
353
+ destructiveReasons.push(`PRIMARY KEY ${name}`);
354
+ }
355
+
356
+ // UNIQUE — reconciled with an index (create/drop), not a rebuild.
357
+ const fieldUnique = !!f.unique;
358
+ if (fieldUnique && !liveUnique.has(name)) {
359
+ // Added: safe only if no duplicate values exist; otherwise the index can't build.
360
+ if (await columnHasDuplicates(driver, table, name)) {
361
+ (uniqueIndexSkip.get(table) ?? uniqueIndexSkip.set(table, new Set()).get(table)!).add(name);
362
+ skipped.push(`add UNIQUE ${table}.${name} (duplicate values present)`);
363
+ }
364
+ // else: the index pass creates it below (no rebuild needed).
365
+ } else if (!fieldUnique && liveUnique.has(name)) {
366
+ dropUniqueCols.push(name); // drop the managed unique index (safe — no data loss)
367
+ }
368
+ }
369
+
370
+ const destructive = needsDrop || needsTypeChange || renamedSources.size > 0 || modifierRebuildDestructive;
190
371
  if (destructive && !allowDestructive) {
191
- // The destructive part is gated off — skip the whole rebuild (any pending
192
- // expr-default column waits until destructive migrations are allowed).
193
- skipped.push(`rebuild ${table} (drop/type-change/rename)`);
194
- } else if (destructive || needsAdditiveRebuild) {
195
- // An additive-only rebuild (just an expr-default column) needs no permission —
196
- // it loses no data.
372
+ // The destructive part is gated off — skip the whole rebuild (any pending safe
373
+ // rebuild for this table waits until destructive migrations are allowed).
374
+ const reasons = [
375
+ ...(needsDrop ? ["drop"] : []),
376
+ ...(needsTypeChange ? ["type-change"] : []),
377
+ ...(renamedSources.size > 0 ? ["rename"] : []),
378
+ ...destructiveReasons,
379
+ ];
380
+ skipped.push(`rebuild ${table} (${reasons.join(", ")})`);
381
+ } else if (destructive || needsAdditiveRebuild || modifierRebuildSafe) {
382
+ // A safe rebuild (expr-default column, default/notNull modifier change) needs no
383
+ // permission — it loses no data.
197
384
  await rebuildTable(driver, table, def, live);
198
385
  rebuilt.push(table);
199
386
  }
387
+
388
+ // Drop the managed unique index for a column that no longer declares `unique()`. A
389
+ // rebuild already dropped every index (and the index pass won't recreate this one),
390
+ // so this only matters when no rebuild ran — DROP INDEX IF EXISTS is a safe no-op
391
+ // otherwise. No data loss either way.
392
+ for (const col of dropUniqueCols) {
393
+ await driver.exec(`DROP INDEX IF EXISTS ${quoteIdent(indexName(table, col))}`, []);
394
+ }
395
+ }
396
+
397
+ // A partition MOVE — an entity that was applied in THIS partition before but the
398
+ // current schema assigns to a DIFFERENT partition — is NOT auto-migratable: the data
399
+ // lives in this DO's SQLite and boot migration can't move it across DOs. Detect it
400
+ // (scoped path only; the unscoped/single-store path never strands data), report it as
401
+ // a skipped manual migration, and leave the table in place so its data is preserved
402
+ // for a hand-run migration. Leaving it in `skipped` also withholds the hash.
403
+ if (opts.partition !== undefined) {
404
+ const prevRaw = await readMeta(driver, tablesKey);
405
+ if (prevRaw) {
406
+ const prevApplied = JSON.parse(prevRaw) as Record<string, string[]>;
407
+ for (const t of Object.keys(prevApplied)) {
408
+ if (!inScope.has(t) && t in schema && partitionOf(schema, t) !== opts.partition) {
409
+ skipped.push(
410
+ `move partition ${t} (${opts.partition} → ${partitionOf(schema, t)}) — data stays in this DO; manual cross-DO migration required`,
411
+ );
412
+ }
413
+ }
414
+ }
200
415
  }
201
416
 
202
417
  // Ensure unique/index declarations (idempotent, via IF NOT EXISTS). Indexes can be
203
418
  // added to an existing table without a rebuild; a stale index from a removed
204
- // declaration is left in place (cleanup is future work).
419
+ // declaration is dropped above. A column whose new `unique()` has duplicate values is
420
+ // skipped (reported above) so this doesn't throw.
205
421
  for (const [table, def] of entries) {
206
- for (const stmt of indexStatements(table, def)) await driver.exec(stmt, []);
422
+ for (const stmt of indexStatements(table, def, uniqueIndexSkip.get(table))) await driver.exec(stmt, []);
207
423
  }
208
424
 
209
425
  // Drop tables the schema no longer declares (internal bookkeeping tables skipped).
@@ -237,7 +453,8 @@ export async function migrate(driver: Driver, schema: SchemaDef, opts: MigrateOp
237
453
  await writeMeta(driver, tablesKey, tablesValue());
238
454
  } else {
239
455
  console.warn(
240
- `pramen: ${skipped.length} destructive migration(s) skipped (set PRAMEN_ALLOW_DESTRUCTIVE=true to apply): ${skipped.join("; ")}`,
456
+ `pramen: ${skipped.length} migration(s) skipped, schema hash left unwritten (a gated change needs ` +
457
+ `PRAMEN_ALLOW_DESTRUCTIVE=true; a UNIQUE-over-duplicates or partition move needs a manual fix): ${skipped.join("; ")}`,
241
458
  );
242
459
  }
243
460
  return { changed: true, created, added, rebuilt, droppedTables, skipped };
@@ -141,6 +141,17 @@ export async function drainOutbox(driver: Driver, tasks: TaskMap, now: number, l
141
141
  const kind = String(row.kind);
142
142
  const attempts = Number(row.attempts) + 1;
143
143
  const handler = tasks[kind];
144
+ // Re-stamp claimedAt to WALL-CLOCK time immediately before running this row, so its
145
+ // stale clock starts when its own processing starts — not when the whole batch was
146
+ // claimed. Otherwise a batch (up to `limit` rows) processed SEQUENTIALLY whose total
147
+ // time exceeds STALE_MS would leave the not-yet-run tail reclaimable by a concurrent
148
+ // drainer under the batch-shared claimedAt, running it twice. We use Date.now() (not
149
+ // the caller's fixed `now`) because that is the only clock that advances across the
150
+ // loop; the atomic claim above still gives disjoint batches for concurrent drainers.
151
+ await driver.exec(
152
+ `UPDATE ${d.id(OUTBOX_TABLE)} SET claimedAt = ${ph(1)} WHERE id = ${ph(2)}`,
153
+ enc(driver, [Date.now(), id]),
154
+ );
144
155
  try {
145
156
  if (!handler) throw new Error(`no task handler registered for kind ${JSON.stringify(kind)}`);
146
157
  await handler(JSON.parse(String(row.payload)), { id, attempts });
@@ -160,22 +171,34 @@ export async function drainOutbox(driver: Driver, tasks: TaskMap, now: number, l
160
171
  }
161
172
  }
162
173
 
163
- // remaining = pending AND due now; nextRunAt = the earliest pending runAt (any), so
164
- // the DO can schedule its alarm exactly when the next task including a backed-off
165
- // retry becomes due.
174
+ // remaining = pending AND due now. nextRunAt = the earliest moment the DO must wake to
175
+ // make progress, so it can re-arm its alarm exactly there. That is the min of:
176
+ // (a) MIN(runAt) over pending rows (a due-now or backed-off retry), and
177
+ // (b) MIN(claimedAt) + STALE_MS over 'processing' rows — a claim stranded by a
178
+ // crashed drainer becomes reclaimable at claimedAt + STALE_MS. Without folding
179
+ // this in, a mid-drain crash would leave a row 'processing' with no pending row
180
+ // to re-arm the alarm, and on a quiet tenant the task would stall forever (the
181
+ // alarm is the only DO-path drain trigger). Any processing rows here belong to a
182
+ // *different* (concurrent or crashed) drainer — our own batch is never left
183
+ // processing after this loop.
166
184
  const stats = await driver.exec(
167
185
  `SELECT ` +
168
186
  `(SELECT COUNT(*) FROM ${d.id(OUTBOX_TABLE)} WHERE status = ${ph(1)} AND runAt <= ${ph(2)}) AS due, ` +
169
- `(SELECT MIN(runAt) FROM ${d.id(OUTBOX_TABLE)} WHERE status = ${ph(3)}) AS nextRunAt`,
170
- enc(driver, ["pending", now, "pending"]),
187
+ `(SELECT MIN(runAt) FROM ${d.id(OUTBOX_TABLE)} WHERE status = ${ph(3)}) AS nextPending, ` +
188
+ `(SELECT MIN(claimedAt) FROM ${d.id(OUTBOX_TABLE)} WHERE status = ${ph(4)}) AS nextStale`,
189
+ enc(driver, ["pending", now, "pending", "processing"]),
171
190
  );
172
- const nextRaw = stats[0]?.nextRunAt;
191
+ const pendingRaw = stats[0]?.nextPending;
192
+ const staleRaw = stats[0]?.nextStale;
193
+ const candidates: number[] = [];
194
+ if (pendingRaw != null) candidates.push(Number(pendingRaw));
195
+ if (staleRaw != null) candidates.push(Number(staleRaw) + STALE_MS);
173
196
  return {
174
197
  processed: claimed.length,
175
198
  succeeded,
176
199
  failed,
177
200
  remaining: Number(stats[0]?.due ?? 0),
178
- nextRunAt: nextRaw == null ? null : Number(nextRaw),
201
+ nextRunAt: candidates.length ? Math.min(...candidates) : null,
179
202
  };
180
203
  }
181
204
 
@@ -62,14 +62,33 @@ export type AppQueueMap = Record<string, QueueHandler>;
62
62
 
63
63
  /** Resolve the handler for a batch's queue. Queue names are env-prefixed in remote
64
64
  * environments (`production-pramen-jobs`) but bare locally (`pramen-jobs`), so match
65
- * leniently: exact, then suffix (`…-<key>`), then — if there's exactly one handler —
66
- * fall through to it (the common single-queue app). Returns null if nothing matches. */
65
+ * leniently: exact, then the LONGEST `…-<key>` suffix, then — if there's exactly one
66
+ * handler — fall through to it (the common single-queue app). Returns null if nothing
67
+ * matches.
68
+ *
69
+ * The suffix match must prefer the longest key so `email-jobs` wins over `jobs` for
70
+ * `prod-email-jobs` (a plain `find` was insertion-order dependent and could misroute).
71
+ * We only match a handler key that is a `-`-delimited suffix of the incoming queue name
72
+ * (env prefix stripped) — never the reverse (a handler key ending in `-<queueName>`),
73
+ * which let a shorter queue name grab a longer, unrelated handler. */
67
74
  export function routeQueue(queues: AppQueueMap, queueName: string): QueueHandler | null {
68
75
  const keys = Object.keys(queues);
69
76
  if (queues[queueName]) return queues[queueName];
70
- const suffix = keys.find((k) => queueName.endsWith(`-${k}`) || k.endsWith(`-${queueName}`));
71
- if (suffix) return queues[suffix];
72
- if (keys.length === 1) return queues[keys[0]];
77
+ let best: string | null = null;
78
+ for (const k of keys) {
79
+ if (queueName.endsWith(`-${k}`) && (best === null || k.length > best.length)) best = k;
80
+ }
81
+ if (best !== null) return queues[best];
82
+ // Single-handler fallback: a lone queue whose env-prefixed name we couldn't suffix-
83
+ // match. Kept for the common single-queue app, but LOG it — otherwise a dead-letter
84
+ // queue (a distinct name) would silently route to the one handler and hide the misroute.
85
+ if (keys.length === 1) {
86
+ console.warn(
87
+ `pramen: routing queue '${queueName}' to the sole handler '${keys[0]}' by fallback ` +
88
+ `(no exact/suffix match — verify this isn't a dead-letter or foreign queue)`,
89
+ );
90
+ return queues[keys[0]];
91
+ }
73
92
  return null;
74
93
  }
75
94
 
@@ -91,7 +91,12 @@ export function compileExpr(expr: SqlExpr, dialect: Dialect, params: unknown[] =
91
91
  case "false":
92
92
  return { sql: "0", params };
93
93
  case "cmp":
94
- if (expr.value === null) return { sql: `${dialect.id(expr.col)} IS NULL`, params };
94
+ // A comparison against NULL is never TRUE in SQL (=, !=, <, > all yield NULL).
95
+ // Only the dedicated `null` node produces `IS NULL`; a `cmp` with a null operand
96
+ // matches nothing. (`eq()` already routes an equality-to-null to the `null` node,
97
+ // and the keyset comparator handles null order-keys explicitly — so no legitimate
98
+ // caller reaches here with a null value.)
99
+ if (expr.value === null) return { sql: "0", params };
95
100
  params.push(dialect.encode(expr.value));
96
101
  return { sql: `${dialect.id(expr.col)} ${expr.op} ${dialect.placeholder(params.length)}`, params };
97
102
  case "null":
@@ -145,7 +150,7 @@ export function evalExpr(expr: SqlExpr, row: Record<string, unknown>): boolean {
145
150
  return false;
146
151
  case "cmp": {
147
152
  const left = bind(row[expr.col]);
148
- if (expr.value === null) return left === null || left === undefined;
153
+ if (expr.value === null) return false; // comparison against NULL is never true (use the `null` node for IS NULL)
149
154
  if (left === null || left === undefined) return false; // NULL compared to a value -> false
150
155
  const right = bind(expr.value);
151
156
  switch (expr.op) {
@@ -1,56 +1,170 @@
1
- // Schema shape + diff — powers the CLI's `schema diff`. migrate() applies every
2
- // change on the next DO boot, additive AND destructive. A diff classifies each as
3
- // `destructive` (drop / type change rebuilds the table and CAN lose data) or not
4
- // (add table/column no data loss). A rename can't be detected from a shape diff;
5
- // it shows as drop+add unless declared with `renamedFrom` in the schema.
1
+ // Schema shape + diff — powers the CLI's `schema diff`. The diff is a REPORTING tool; it
2
+ // does not itself migrate. On the next DO boot migrate() applies ADDITIVE changes only
3
+ // (new table -> CREATE TABLE; new column -> ALTER TABLE ADD COLUMN). DESTRUCTIVE changes
4
+ // (drop column/table, type change, table rebuild) are SKIPPED unless the deploy sets
5
+ // PRAMEN_ALLOW_DESTRUCTIVE=true and when skipped the schema hash is left unwritten so a
6
+ // later opt-in deploy retries. A rename can't be detected from a shape diff; it shows as
7
+ // drop+add unless declared with `renamedFrom` in the schema.
8
+ //
9
+ // The shape records column type + the migration-relevant modifiers (notNull, unique,
10
+ // primaryKey, generated, default, hidden) and the entity's partition, so the diff REPORTS
11
+ // modifier and partition changes too. migrate() now RECONCILES modifier changes on an
12
+ // existing column (a NOT NULL / DEFAULT / PRIMARY KEY change via a rebuild, a UNIQUE
13
+ // change via a create/drop index), so a `change-column` is `appliesOnBoot: true`. It is
14
+ // flagged `destructive` when it tightens a constraint (adds NOT NULL / UNIQUE / PRIMARY
15
+ // KEY) — those apply only under PRAMEN_ALLOW_DESTRUCTIVE, or are skipped when the live
16
+ // data conflicts (NULL rows / duplicates), leaving the hash unwritten. A partition MOVE
17
+ // still CANNOT be enacted on boot (a partition is a separate Durable Object — it needs a
18
+ // manual cross-DO data migration), so it stays `appliesOnBoot: false`.
6
19
 
7
20
  import type { FieldDef, SchemaDef } from "../sdk/schema";
21
+ import { partitionOf } from "../sdk/schema";
8
22
 
9
- /** table -> column -> field type. The comparable surface of a schema. */
10
- export type SchemaShape = Record<string, Record<string, string>>;
23
+ /** The comparable fingerprint of a single column: type + migration-relevant modifiers. */
24
+ export interface ColumnShape {
25
+ type: string;
26
+ notNull?: boolean;
27
+ unique?: boolean;
28
+ primaryKey?: boolean;
29
+ generated?: boolean;
30
+ hidden?: boolean;
31
+ /** The literal or raw-SQL default, normalized to a string for comparison. */
32
+ default?: string;
33
+ }
34
+
35
+ /** The comparable fingerprint of a table: its partition + each column's shape. */
36
+ export interface TableShape {
37
+ partition: string;
38
+ columns: Record<string, ColumnShape>;
39
+ }
40
+
41
+ /** table -> table shape. The comparable surface of a schema. */
42
+ export type SchemaShape = Record<string, TableShape>;
43
+
44
+ function columnShape(f: FieldDef): ColumnShape {
45
+ const c: ColumnShape = { type: f.type };
46
+ if (f.notNull) c.notNull = true;
47
+ if (f.unique) c.unique = true;
48
+ if (f.primaryKey) c.primaryKey = true;
49
+ if (f.generated) c.generated = true;
50
+ if (f.hidden) c.hidden = true;
51
+ if (f.defaultExpr !== undefined) c.default = `(${f.defaultExpr})`;
52
+ else if (f.default !== undefined) c.default = JSON.stringify(f.default);
53
+ return c;
54
+ }
11
55
 
12
56
  export function schemaShape(schema: SchemaDef): SchemaShape {
13
57
  const out: SchemaShape = {};
14
58
  for (const [table, def] of Object.entries(schema)) {
15
- const cols: Record<string, string> = {};
16
- for (const [col, f] of Object.entries(def.fields)) cols[col] = (f as FieldDef).type;
17
- out[table] = cols;
59
+ const columns: Record<string, ColumnShape> = {};
60
+ for (const [col, f] of Object.entries(def.fields)) columns[col] = columnShape(f as FieldDef);
61
+ out[table] = { partition: partitionOf(schema, table), columns };
18
62
  }
19
63
  return out;
20
64
  }
21
65
 
66
+ /** The modifier fields compared for a `change-column` (everything but `type`). */
67
+ const MODIFIER_KEYS: (keyof ColumnShape)[] = ["notNull", "unique", "primaryKey", "generated", "hidden", "default"];
68
+
69
+ /** Does `next` tighten a constraint `prev` lacked (add NOT NULL / UNIQUE / PRIMARY KEY)?
70
+ * Such a change may require the destructive gate or be skipped when the live data
71
+ * conflicts (NULL rows / duplicates) — so the diff flags it `destructive`. */
72
+ function tightensConstraint(prev: ColumnShape, next: ColumnShape): boolean {
73
+ return (!!next.notNull && !prev.notNull) || (!!next.unique && !prev.unique) || (!!next.primaryKey && !prev.primaryKey);
74
+ }
75
+
76
+ function modifierDiff(prev: ColumnShape, next: ColumnShape): string | null {
77
+ const parts: string[] = [];
78
+ for (const k of MODIFIER_KEYS) {
79
+ if (prev[k] !== next[k]) parts.push(`${k}: ${fmt(prev[k])} → ${fmt(next[k])}`);
80
+ }
81
+ return parts.length ? parts.join(", ") : null;
82
+ }
83
+
84
+ function fmt(v: unknown): string {
85
+ return v === undefined ? "—" : String(v);
86
+ }
87
+
22
88
  export interface SchemaChange {
23
- kind: "add-table" | "drop-table" | "add-column" | "drop-column" | "change-type";
89
+ kind: "add-table" | "drop-table" | "add-column" | "drop-column" | "change-type" | "change-column" | "move-partition";
24
90
  table: string;
25
91
  column?: string;
26
92
  detail?: string;
27
- /** true = rebuilds the table and may lose data (drop / type change); false =
28
- * additive, no data loss. All changes are auto-applied on the next DO boot. */
93
+ /** true = rebuilds the table and may lose data (drop / type change). false = additive
94
+ * OR a metadata-only change (modifier / partition move) see `appliesOnBoot`. */
29
95
  destructive: boolean;
96
+ /** Whether migrate() enacts this change on the next DO boot. Additive changes are
97
+ * always applied; destructive changes (type/drop, or a constraint-tightening modifier
98
+ * change) apply only when the deploy sets PRAMEN_ALLOW_DESTRUCTIVE=true (and are
99
+ * skipped when the live data conflicts, leaving the hash unwritten). `false` here means
100
+ * the boot migrator will NEVER enact it — today only a partition MOVE (needs a manual
101
+ * cross-DO data migration). Reported for honesty. */
102
+ appliesOnBoot: boolean;
30
103
  }
31
104
 
32
105
  export function diffSchemaShape(prev: SchemaShape, next: SchemaShape): SchemaChange[] {
33
106
  const changes: SchemaChange[] = [];
34
107
 
35
108
  for (const table of Object.keys(next)) {
36
- if (!(table in prev)) {
37
- changes.push({ kind: "add-table", table, destructive: false });
109
+ const pt = prev[table];
110
+ if (!pt) {
111
+ changes.push({ kind: "add-table", table, destructive: false, appliesOnBoot: true });
38
112
  continue;
39
113
  }
40
- for (const col of Object.keys(next[table]!)) {
41
- if (!(col in prev[table]!)) {
42
- changes.push({ kind: "add-column", table, column: col, destructive: false });
43
- } else if (prev[table]![col] !== next[table]![col]) {
44
- changes.push({ kind: "change-type", table, column: col, detail: `${prev[table]![col]} → ${next[table]![col]}`, destructive: true });
114
+ const nt = next[table]!;
115
+ if (pt.partition !== nt.partition) {
116
+ changes.push({
117
+ kind: "move-partition",
118
+ table,
119
+ detail: `${pt.partition} → ${nt.partition}`,
120
+ destructive: false,
121
+ // A partition is a separate Durable Object; boot migration can't move a table's
122
+ // data across DOs. Needs a manual data migration.
123
+ appliesOnBoot: false,
124
+ });
125
+ }
126
+ for (const col of Object.keys(nt.columns)) {
127
+ const pc = pt.columns[col];
128
+ const ncol = nt.columns[col]!;
129
+ if (!pc) {
130
+ changes.push({ kind: "add-column", table, column: col, destructive: false, appliesOnBoot: true });
131
+ } else if (pc.type !== ncol.type) {
132
+ changes.push({
133
+ kind: "change-type",
134
+ table,
135
+ column: col,
136
+ detail: `${pc.type} → ${ncol.type}`,
137
+ destructive: true,
138
+ // Applied only under PRAMEN_ALLOW_DESTRUCTIVE (a table rebuild). Report it as
139
+ // boot-applicable — the destructive-gating note explains the opt-in.
140
+ appliesOnBoot: true,
141
+ });
142
+ } else {
143
+ const md = modifierDiff(pc, ncol);
144
+ if (md) {
145
+ changes.push({
146
+ kind: "change-column",
147
+ table,
148
+ column: col,
149
+ detail: md,
150
+ // Tightening a constraint (add NOT NULL / UNIQUE / PRIMARY KEY) rebuilds/
151
+ // indexes and applies only under PRAMEN_ALLOW_DESTRUCTIVE (or is skipped when
152
+ // live data conflicts). Loosening or a DEFAULT change is additive.
153
+ destructive: tightensConstraint(pc, ncol),
154
+ // migrate() now reconciles modifier changes on an existing column on boot.
155
+ appliesOnBoot: true,
156
+ });
157
+ }
45
158
  }
46
159
  }
47
- for (const col of Object.keys(prev[table]!)) {
48
- if (!(col in next[table]!)) changes.push({ kind: "drop-column", table, column: col, destructive: true });
160
+ for (const col of Object.keys(pt.columns)) {
161
+ if (!(col in nt.columns))
162
+ changes.push({ kind: "drop-column", table, column: col, destructive: true, appliesOnBoot: true });
49
163
  }
50
164
  }
51
165
 
52
166
  for (const table of Object.keys(prev)) {
53
- if (!(table in next)) changes.push({ kind: "drop-table", table, destructive: true });
167
+ if (!(table in next)) changes.push({ kind: "drop-table", table, destructive: true, appliesOnBoot: true });
54
168
  }
55
169
 
56
170
  return changes;
Binary file