cursedbelt-server 4.54.0 → 4.55.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.
@@ -71,9 +71,30 @@ export declare function servedRuntime(url: string, { attempts, sleep }?: {
71
71
  * Rows per paged `SELECT`. The fleet's largest table held 290 rows when this was set (collections'
72
72
  * `items`, 2026-09-25) and one `wrangler` call costs ~1 s, so a page this size is one call per
73
73
  * table for every app today. A page D1 refuses — too large a response — is halved and asked
74
- * again, down to one row, before it is a refusal.
74
+ * again, down to one row, before it is a refusal. It is where every table STARTS: small rows grow
75
+ * past it ({@link nextPageRows}).
75
76
  */
76
77
  export declare const PAGE_ROWS = 500;
78
+ /**
79
+ * 🔴 How far a table of small rows grows its pages, and the bytes a grown page may carry.
80
+ *
81
+ * At a fixed {@link PAGE_ROWS} the cost of a pull is its ROW count, ~1.5 s of `bun x wrangler` per
82
+ * 500 rows whatever they hold. Measured 2026-10-29: photos' 171,590-row gazetteer and 40,841
83
+ * `asset_tags` made its backup ~600 calls, 730 s on 2026-10-28, 873 s that night, and then
84
+ * past the recovery backup's 900 s ceiling on both WDElementsBlack runs of 2026-10-29 (exit
85
+ * 143, twice each), so the drive carried a stale photos snapshot. A page of tiny rows is a
86
+ * few KB, so it doubles while the rows it read stay small: to {@link MAX_PAGE_ROWS}, while
87
+ * that many rows of the size just read stay under {@link PAGE_BYTES}. Large rows never grow
88
+ * past {@link PAGE_ROWS}, which is where they were already proven.
89
+ */
90
+ export declare const MAX_PAGE_ROWS = 10000;
91
+ export declare const PAGE_BYTES = 4000000;
92
+ /**
93
+ * The next page's size after one of `limit` rows came back with `rows` rows and `bytes` of SQL
94
+ * literals. It doubles, but never past `cap` (lowered by a refusal: see {@link dumpTable}), and
95
+ * never past {@link PAGE_ROWS} unless rows of this size fit {@link PAGE_BYTES}.
96
+ */
97
+ export declare function nextPageRows(limit: number, rows: number, bytes: number, cap?: number): number;
77
98
  /** One `wrangler` invocation, as {@link pullD1ToSqlite} needs it. Injected so a spec runs none. */
78
99
  export type Wrangler = (args: string[]) => {
79
100
  code: number;
@@ -86,9 +107,17 @@ export type Wrangler = (args: string[]) => {
86
107
  * line until 4.22.0.
87
108
  */
88
109
  export declare const wranglerArgv: (bun?: string) => string[];
110
+ /**
111
+ * 🔴 How long one `wrangler` call may run before it is killed. Without it a call whose connection
112
+ * stalled never returned: measured 2026-10-29, a photos pull logged two `fetch failed` retries and
113
+ * then sat 20 minutes on one call, which inside the recovery backup is the 900 s ceiling's kill and
114
+ * a stale snapshot. A kill reads as `ETIMEDOUT`, which {@link isTransient} waits out and asks again.
115
+ * A healthy page of {@link PAGE_BYTES} answers in seconds.
116
+ */
117
+ export declare const CALL_TIMEOUT_MS = 120000;
89
118
  /**
90
119
  * Run `argv` to completion with its stdout written to a FILE, never a pipe, and return what it
91
- * wrote.
120
+ * wrote — or kill it at `timeoutMs` and say so in a message {@link isTransient} recognizes.
92
121
  *
93
122
  * 🔴 A Bun child that ends with `process.exit()` drops whatever of its stdout the pipe had not
94
123
  * taken yet, at a 64 KiB boundary — and wrangler is a Bun child whenever `node` is not on PATH
@@ -103,6 +132,8 @@ export declare function spawnToFile(argv: string[], options?: {
103
132
  cwd?: string;
104
133
  /** The child's whole environment, or a function of this call's own scratch directory that returns it. */
105
134
  env?: Record<string, string | undefined> | ((scratch: string) => Record<string, string | undefined>);
135
+ /** Kill the child after this long ({@link CALL_TIMEOUT_MS} by default). */
136
+ timeoutMs?: number;
106
137
  }): {
107
138
  code: number;
108
139
  stdout: string;
@@ -105,18 +105,51 @@ export async function servedRuntime(url, { attempts = 3, sleep = (ms) => new Pro
105
105
  * Rows per paged `SELECT`. The fleet's largest table held 290 rows when this was set (collections'
106
106
  * `items`, 2026-09-25) and one `wrangler` call costs ~1 s, so a page this size is one call per
107
107
  * table for every app today. A page D1 refuses — too large a response — is halved and asked
108
- * again, down to one row, before it is a refusal.
108
+ * again, down to one row, before it is a refusal. It is where every table STARTS: small rows grow
109
+ * past it ({@link nextPageRows}).
109
110
  */
110
111
  export const PAGE_ROWS = 500;
112
+ /**
113
+ * 🔴 How far a table of small rows grows its pages, and the bytes a grown page may carry.
114
+ *
115
+ * At a fixed {@link PAGE_ROWS} the cost of a pull is its ROW count, ~1.5 s of `bun x wrangler` per
116
+ * 500 rows whatever they hold. Measured 2026-10-29: photos' 171,590-row gazetteer and 40,841
117
+ * `asset_tags` made its backup ~600 calls, 730 s on 2026-10-28, 873 s that night, and then
118
+ * past the recovery backup's 900 s ceiling on both WDElementsBlack runs of 2026-10-29 (exit
119
+ * 143, twice each), so the drive carried a stale photos snapshot. A page of tiny rows is a
120
+ * few KB, so it doubles while the rows it read stay small: to {@link MAX_PAGE_ROWS}, while
121
+ * that many rows of the size just read stay under {@link PAGE_BYTES}. Large rows never grow
122
+ * past {@link PAGE_ROWS}, which is where they were already proven.
123
+ */
124
+ export const MAX_PAGE_ROWS = 10_000;
125
+ export const PAGE_BYTES = 4_000_000;
126
+ /**
127
+ * The next page's size after one of `limit` rows came back with `rows` rows and `bytes` of SQL
128
+ * literals. It doubles, but never past `cap` (lowered by a refusal: see {@link dumpTable}), and
129
+ * never past {@link PAGE_ROWS} unless rows of this size fit {@link PAGE_BYTES}.
130
+ */
131
+ export function nextPageRows(limit, rows, bytes, cap = MAX_PAGE_ROWS) {
132
+ const perRow = rows > 0 ? bytes / rows : 0;
133
+ const fits = perRow > 0 ? Math.floor(PAGE_BYTES / perRow) : MAX_PAGE_ROWS;
134
+ return Math.max(1, Math.min(cap, limit * 2, Math.max(PAGE_ROWS, fits)));
135
+ }
111
136
  /**
112
137
  * The argv that runs `wrangler`: THIS bun binary's `x`, never a bare `bunx` — a launchd job's
113
138
  * PATH has no `bunx` (task 2112), and vault's and patterns' nightly backups each carried this
114
139
  * line until 4.22.0.
115
140
  */
116
141
  export const wranglerArgv = (bun = process.execPath) => [bun, 'x', 'wrangler'];
142
+ /**
143
+ * 🔴 How long one `wrangler` call may run before it is killed. Without it a call whose connection
144
+ * stalled never returned: measured 2026-10-29, a photos pull logged two `fetch failed` retries and
145
+ * then sat 20 minutes on one call, which inside the recovery backup is the 900 s ceiling's kill and
146
+ * a stale snapshot. A kill reads as `ETIMEDOUT`, which {@link isTransient} waits out and asks again.
147
+ * A healthy page of {@link PAGE_BYTES} answers in seconds.
148
+ */
149
+ export const CALL_TIMEOUT_MS = 120_000;
117
150
  /**
118
151
  * Run `argv` to completion with its stdout written to a FILE, never a pipe, and return what it
119
- * wrote.
152
+ * wrote — or kill it at `timeoutMs` and say so in a message {@link isTransient} recognizes.
120
153
  *
121
154
  * 🔴 A Bun child that ends with `process.exit()` drops whatever of its stdout the pipe had not
122
155
  * taken yet, at a 64 KiB boundary — and wrangler is a Bun child whenever `node` is not on PATH
@@ -133,9 +166,14 @@ export function spawnToFile(argv, options = {}) {
133
166
  let code = 1;
134
167
  try {
135
168
  const env = typeof options.env === 'function' ? options.env(dir) : options.env;
136
- const r = Bun.spawnSync(argv, { cwd: options.cwd, env, stdout: Bun.file(out), stderr: 'pipe' });
137
- code = r.exitCode ?? 1;
169
+ const timeoutMs = options.timeoutMs ?? CALL_TIMEOUT_MS;
170
+ const r = Bun.spawnSync(argv, { cwd: options.cwd, env, stdout: Bun.file(out), stderr: 'pipe', timeout: timeoutMs });
138
171
  const stdout = existsSync(out) ? readFileSync(out, 'utf8') : '';
172
+ if (r.exitedDueToTimeout || r.exitCode === null) {
173
+ code = 124;
174
+ return { code, stdout, stderr: `${argv.slice(0, 4).join(' ')} … did not finish in ${timeoutMs / 1000}s and was killed (ETIMEDOUT)` };
175
+ }
176
+ code = r.exitCode;
139
177
  return { code, stdout, stderr: r.stderr.toString() };
140
178
  }
141
179
  finally {
@@ -299,11 +337,16 @@ export function pageSql(plan, limit, after) {
299
337
  * size back toward {@link PAGE_ROWS}. Before 4.33.1 nothing grew it back: desk's first launchd
300
338
  * backup (2026-09-25) hit a few slow calls early and read its 3,381-row table 15 rows per call —
301
339
  * 225 two-minute calls, on course for hours. Only a refusal at ONE row is fatal.
340
+ *
341
+ * Small rows grow on past {@link PAGE_ROWS} ({@link nextPageRows}). A refusal of a page that
342
+ * large caps the rest of the table at half of it, so a size D1 refused is never asked again;
343
+ * a refusal at or under {@link PAGE_ROWS} caps it there, which is the old behavior exactly.
302
344
  */
303
345
  function dumpTable(caller, database, plan) {
304
346
  const into = `INSERT INTO ${sqlIdent(plan.table)} (${plan.columns.map(sqlIdent).join(', ')}) VALUES (`;
305
347
  const lines = [];
306
348
  let limit = PAGE_ROWS;
349
+ let cap = MAX_PAGE_ROWS;
307
350
  let after = {};
308
351
  for (;;) {
309
352
  let page;
@@ -315,22 +358,26 @@ function dumpTable(caller, database, plan) {
315
358
  if (limit > 1) {
316
359
  const next = Math.max(1, Math.floor(limit / 2));
317
360
  caller.log(`pull D1: \`${plan.table}\` refused a page of ${limit} — asking for ${next}: ${message}`);
361
+ cap = Math.min(cap, Math.max(PAGE_ROWS, next));
318
362
  limit = next;
319
363
  continue;
320
364
  }
321
365
  throw new Error(`could not read \`${plan.table}\` from D1: ${message}`);
322
366
  }
367
+ let bytes = 0;
323
368
  for (const row of page) {
324
369
  const literals = plan.columns.map((_, i) => row[`c${i}`]);
325
370
  if (literals.some((v) => typeof v !== 'string')) {
326
371
  throw new Error(`D1 returned a non-literal value paging \`${plan.table}\` — refusing a snapshot that may not restore`);
327
372
  }
328
- lines.push(`${into}${literals.join(', ')});`);
373
+ const values = literals.join(', ');
374
+ bytes += values.length;
375
+ lines.push(`${into}${values});`);
329
376
  }
330
377
  if (page.length < limit)
331
378
  break;
332
379
  after = plan.key ? { key: Number(page[page.length - 1]?.k) } : { offset: (after.offset ?? 0) + page.length };
333
- limit = Math.min(PAGE_ROWS, limit * 2);
380
+ limit = nextPageRows(limit, page.length, bytes, cap);
334
381
  }
335
382
  return { text: lines.join('\n'), rows: lines.length };
336
383
  }
@@ -414,9 +461,13 @@ export async function pullD1ToSqlite(options) {
414
461
  }
415
462
  }
416
463
  // One table at a time, so a fault is located rather than smeared over the whole load.
464
+ // 🔴 And each table in ONE transaction: bare, every row's INSERT is its own commit and its
465
+ // own journal and sync. Measured 2026-10-29 (forge task 3957), photos' ~400 s load; 3,000
466
+ // rows took 2,881 ms bare and 13 ms in a transaction.
467
+ const load = db.transaction((text) => db.exec(text));
417
468
  for (const { text } of dumps)
418
469
  if (text)
419
- db.exec(text);
470
+ load(text);
420
471
  for (const t of triggers)
421
472
  db.exec(t.sql);
422
473
  if (options.afterLoadSql)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cursedbelt-server",
3
- "version": "4.54.0",
3
+ "version": "4.55.0",
4
4
  "license": "ISC",
5
5
  "type": "module",
6
6
  "description": "The app-facing Bun/Hono server tier of the cursedbelt split — storage, sharing, activity, guard, sync. React-free; cursedbelt-core below it.",
@@ -13,7 +13,7 @@ import {
13
13
  type Wrangler,
14
14
  wranglerArgv,
15
15
  } from './localBackup.js';
16
- import { PAGE_ROWS, pageSql, spawnToFile, tablePlan } from './pullD1.js';
16
+ import { isTransient, PAGE_ROWS, pageSql, spawnToFile, tablePlan } from './pullD1.js';
17
17
 
18
18
  const dirs: string[] = [];
19
19
  const scratch = (): string => {
@@ -199,10 +199,68 @@ describe('pulling D1 down — paged SELECTs, table by table, never an export', (
199
199
  expect((db.query('select count(*) n from items_fts_map').get() as { n: number }).n).toBe(n);
200
200
  db.close();
201
201
  const mapPages = seen.map((a) => a[a.indexOf('--command') + 1] as string).filter((sql) => sql.includes('FROM "items_fts_map"'));
202
- expect(mapPages).toHaveLength(3);
202
+ // 500, then 1,000 small rows: the second page is short, so the table ends there.
203
+ expect(mapPages).toHaveLength(2);
203
204
  expect(mapPages[1]).toContain('WHERE _rowid_ >');
204
205
  });
205
206
 
207
+ test('🔴 a table loads in one transaction, never one commit per row (photos, 2026-10-29: ~400 s of the backup was the load)', async () => {
208
+ const dir = scratch();
209
+ const n = 1_200;
210
+ const source = live(
211
+ `WITH RECURSIVE s(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM s WHERE i < ${n}) INSERT INTO items SELECT 'i' || i, 'x' FROM s;`,
212
+ );
213
+ await pull(dir, d1(source).run);
214
+ // The header's file change counter (bytes 24–27) counts every commit that wrote the file.
215
+ const header = readFileSync(join(dir, 'pulled.sqlite')).subarray(0, 100);
216
+ const commits = new DataView(header.buffer, header.byteOffset).getUint32(24);
217
+ expect(commits).toBeLessThan(100);
218
+ });
219
+
220
+ /** The LIMIT of every paged SELECT of `table`, in order. */
221
+ const limitsOf = (seen: string[][], table: string): number[] =>
222
+ seen
223
+ .map((a) => a[a.indexOf('--command') + 1] as string)
224
+ .filter((sql) => sql.includes(`FROM "${table}"`))
225
+ .map((sql) => Number(/LIMIT (\d+)/.exec(sql)?.[1]));
226
+
227
+ test('🔴 small rows grow their pages past PAGE_ROWS (photos, 2026-10-29: ~600 calls of 500 rows ran past the 900 s ceiling)', async () => {
228
+ const dir = scratch();
229
+ const n = PAGE_ROWS * 6;
230
+ const source = live(
231
+ `WITH RECURSIVE s(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM s WHERE i < ${n}) INSERT INTO items_fts_map (item_id, text) SELECT 'i' || i, 't' FROM s; INSERT INTO items VALUES ('i1', 'x');`,
232
+ );
233
+ const { run, seen } = d1(source);
234
+ await pull(dir, run);
235
+ const db = opened(dir);
236
+ expect((db.query('select count(*) n from items_fts_map').get() as { n: number }).n).toBe(n);
237
+ db.close();
238
+ // 500 + 1,000 + a short page of 1,500 — three calls where a fixed page made seven.
239
+ expect(limitsOf(seen, 'items_fts_map')).toEqual([PAGE_ROWS, PAGE_ROWS * 2, PAGE_ROWS * 4]);
240
+ });
241
+
242
+ test('large rows never grow past PAGE_ROWS, and a refused grown page caps the rest of the table at half of it', async () => {
243
+ const dir = scratch();
244
+ // 20 KB a row: past PAGE_BYTES / PAGE_ROWS (8 KB), so these rows may not grow a page.
245
+ const big = 20_000;
246
+ const n = PAGE_ROWS * 2 + 7;
247
+ const source = live(
248
+ `WITH RECURSIVE s(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM s WHERE i < ${n}) INSERT INTO items_fts_map (item_id, text) SELECT 'i' || i, printf('%.${big}c', 'x') FROM s; INSERT INTO items VALUES ('i1', 'x');`,
249
+ );
250
+ const { run, seen } = d1(source);
251
+ await pull(dir, run);
252
+ expect(limitsOf(seen, 'items_fts_map')).toEqual([PAGE_ROWS, PAGE_ROWS, PAGE_ROWS]);
253
+
254
+ const n2 = PAGE_ROWS * 8;
255
+ const grown = live(
256
+ `WITH RECURSIVE s(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM s WHERE i < ${n2}) INSERT INTO items_fts_map (item_id, text) SELECT 'i' || i, 't' FROM s; INSERT INTO items VALUES ('i1', 'x');`,
257
+ );
258
+ const refused = d1(grown, { failWhen: (sql) => sql.includes('FROM "items_fts_map"') && sql.includes(`LIMIT ${PAGE_ROWS * 4}`) });
259
+ await pull(scratch(), refused.run);
260
+ // 500, 1,000, 2,000 refused, then never more than 1,000 again.
261
+ expect(limitsOf(refused.seen, 'items_fts_map')).toEqual([PAGE_ROWS, PAGE_ROWS * 2, PAGE_ROWS * 4, PAGE_ROWS * 2, PAGE_ROWS * 2, PAGE_ROWS * 2]);
262
+ });
263
+
206
264
  test('a WITHOUT ROWID table pages by its primary key and OFFSET', () => {
207
265
  const plan = tablePlan('kv', 'CREATE TABLE kv (k TEXT PRIMARY KEY, v) WITHOUT ROWID', [
208
266
  { name: 'k', pk: 1 },
@@ -251,10 +309,7 @@ describe('pulling D1 down — paged SELECTs, table by table, never an export', (
251
309
  const db = opened(dir);
252
310
  expect((db.query('select count(*) n from items_fts_map').get() as { n: number }).n).toBe(n);
253
311
  db.close();
254
- const limits = seen
255
- .map((a) => a[a.indexOf('--command') + 1] as string)
256
- .filter((sql) => sql.includes('FROM "items_fts_map"'))
257
- .map((sql) => Number(/LIMIT (\d+)/.exec(sql)?.[1]));
312
+ const limits = limitsOf(seen, 'items_fts_map');
258
313
  // refused at 500, read at 250, then back to 500 for the rest.
259
314
  expect(limits.slice(0, 3)).toEqual([PAGE_ROWS, PAGE_ROWS / 2, PAGE_ROWS]);
260
315
  expect(limits.slice(2).every((limit) => limit === PAGE_ROWS)).toBe(true);
@@ -472,6 +527,14 @@ END;`;
472
527
  expect(JSON.parse(r.stdout)).toHaveLength(1);
473
528
  });
474
529
 
530
+ test('🔴 a call that never answers is killed, and the kill reads as the wire failing — asked again, never hung on (photos, 2026-10-29: 20 minutes on one call)', () => {
531
+ const started = Date.now();
532
+ const r = spawnToFile(['sleep', '3'], { timeoutMs: 200 });
533
+ expect(Date.now() - started).toBeLessThan(2_500);
534
+ expect(r.code).not.toBe(0);
535
+ expect(isTransient(r.stderr)).toBe(true);
536
+ });
537
+
475
538
  test("🔴 a wrangler call's debug log is the call's own — gone with a green call, kept for a red one", () => {
476
539
  // `bun x wrangler` runs the cwd's own `node_modules/.bin/wrangler` first, so this one stands
477
540
  // in for the real thing. It logs as wrangler does: every message, a `--json` result included,
@@ -120,10 +120,37 @@ export async function servedRuntime(
120
120
  * Rows per paged `SELECT`. The fleet's largest table held 290 rows when this was set (collections'
121
121
  * `items`, 2026-09-25) and one `wrangler` call costs ~1 s, so a page this size is one call per
122
122
  * table for every app today. A page D1 refuses — too large a response — is halved and asked
123
- * again, down to one row, before it is a refusal.
123
+ * again, down to one row, before it is a refusal. It is where every table STARTS: small rows grow
124
+ * past it ({@link nextPageRows}).
124
125
  */
125
126
  export const PAGE_ROWS = 500;
126
127
 
128
+ /**
129
+ * 🔴 How far a table of small rows grows its pages, and the bytes a grown page may carry.
130
+ *
131
+ * At a fixed {@link PAGE_ROWS} the cost of a pull is its ROW count, ~1.5 s of `bun x wrangler` per
132
+ * 500 rows whatever they hold. Measured 2026-10-29: photos' 171,590-row gazetteer and 40,841
133
+ * `asset_tags` made its backup ~600 calls, 730 s on 2026-10-28, 873 s that night, and then
134
+ * past the recovery backup's 900 s ceiling on both WDElementsBlack runs of 2026-10-29 (exit
135
+ * 143, twice each), so the drive carried a stale photos snapshot. A page of tiny rows is a
136
+ * few KB, so it doubles while the rows it read stay small: to {@link MAX_PAGE_ROWS}, while
137
+ * that many rows of the size just read stay under {@link PAGE_BYTES}. Large rows never grow
138
+ * past {@link PAGE_ROWS}, which is where they were already proven.
139
+ */
140
+ export const MAX_PAGE_ROWS = 10_000;
141
+ export const PAGE_BYTES = 4_000_000;
142
+
143
+ /**
144
+ * The next page's size after one of `limit` rows came back with `rows` rows and `bytes` of SQL
145
+ * literals. It doubles, but never past `cap` (lowered by a refusal: see {@link dumpTable}), and
146
+ * never past {@link PAGE_ROWS} unless rows of this size fit {@link PAGE_BYTES}.
147
+ */
148
+ export function nextPageRows(limit: number, rows: number, bytes: number, cap: number = MAX_PAGE_ROWS): number {
149
+ const perRow = rows > 0 ? bytes / rows : 0;
150
+ const fits = perRow > 0 ? Math.floor(PAGE_BYTES / perRow) : MAX_PAGE_ROWS;
151
+ return Math.max(1, Math.min(cap, limit * 2, Math.max(PAGE_ROWS, fits)));
152
+ }
153
+
127
154
  /** One `wrangler` invocation, as {@link pullD1ToSqlite} needs it. Injected so a spec runs none. */
128
155
  export type Wrangler = (args: string[]) => { code: number; stdout: string; stderr: string };
129
156
 
@@ -134,9 +161,18 @@ export type Wrangler = (args: string[]) => { code: number; stdout: string; stder
134
161
  */
135
162
  export const wranglerArgv = (bun: string = process.execPath): string[] => [bun, 'x', 'wrangler'];
136
163
 
164
+ /**
165
+ * 🔴 How long one `wrangler` call may run before it is killed. Without it a call whose connection
166
+ * stalled never returned: measured 2026-10-29, a photos pull logged two `fetch failed` retries and
167
+ * then sat 20 minutes on one call, which inside the recovery backup is the 900 s ceiling's kill and
168
+ * a stale snapshot. A kill reads as `ETIMEDOUT`, which {@link isTransient} waits out and asks again.
169
+ * A healthy page of {@link PAGE_BYTES} answers in seconds.
170
+ */
171
+ export const CALL_TIMEOUT_MS = 120_000;
172
+
137
173
  /**
138
174
  * Run `argv` to completion with its stdout written to a FILE, never a pipe, and return what it
139
- * wrote.
175
+ * wrote — or kill it at `timeoutMs` and say so in a message {@link isTransient} recognizes.
140
176
  *
141
177
  * 🔴 A Bun child that ends with `process.exit()` drops whatever of its stdout the pipe had not
142
178
  * taken yet, at a 64 KiB boundary — and wrangler is a Bun child whenever `node` is not on PATH
@@ -153,6 +189,8 @@ export function spawnToFile(
153
189
  cwd?: string;
154
190
  /** The child's whole environment, or a function of this call's own scratch directory that returns it. */
155
191
  env?: Record<string, string | undefined> | ((scratch: string) => Record<string, string | undefined>);
192
+ /** Kill the child after this long ({@link CALL_TIMEOUT_MS} by default). */
193
+ timeoutMs?: number;
156
194
  } = {},
157
195
  ): { code: number; stdout: string; stderr: string } {
158
196
  const dir = mkdtempSync(join(tmpdir(), 'cursedbelt-spawn-'));
@@ -160,9 +198,14 @@ export function spawnToFile(
160
198
  let code = 1;
161
199
  try {
162
200
  const env = typeof options.env === 'function' ? options.env(dir) : options.env;
163
- const r = Bun.spawnSync(argv, { cwd: options.cwd, env, stdout: Bun.file(out), stderr: 'pipe' });
164
- code = r.exitCode ?? 1;
201
+ const timeoutMs = options.timeoutMs ?? CALL_TIMEOUT_MS;
202
+ const r = Bun.spawnSync(argv, { cwd: options.cwd, env, stdout: Bun.file(out), stderr: 'pipe', timeout: timeoutMs });
165
203
  const stdout = existsSync(out) ? readFileSync(out, 'utf8') : '';
204
+ if (r.exitedDueToTimeout || r.exitCode === null) {
205
+ code = 124;
206
+ return { code, stdout, stderr: `${argv.slice(0, 4).join(' ')} … did not finish in ${timeoutMs / 1000}s and was killed (ETIMEDOUT)` };
207
+ }
208
+ code = r.exitCode;
166
209
  return { code, stdout, stderr: r.stderr.toString() };
167
210
  } finally {
168
211
  // A failed call keeps whatever the child wrote beside its stdout — wrangler's debug log, whose
@@ -374,11 +417,16 @@ export function pageSql(plan: TablePlan, limit: number, after: { key?: number; o
374
417
  * size back toward {@link PAGE_ROWS}. Before 4.33.1 nothing grew it back: desk's first launchd
375
418
  * backup (2026-09-25) hit a few slow calls early and read its 3,381-row table 15 rows per call —
376
419
  * 225 two-minute calls, on course for hours. Only a refusal at ONE row is fatal.
420
+ *
421
+ * Small rows grow on past {@link PAGE_ROWS} ({@link nextPageRows}). A refusal of a page that
422
+ * large caps the rest of the table at half of it, so a size D1 refused is never asked again;
423
+ * a refusal at or under {@link PAGE_ROWS} caps it there, which is the old behavior exactly.
377
424
  */
378
425
  function dumpTable(caller: Caller, database: string, plan: TablePlan): { text: string; rows: number } {
379
426
  const into = `INSERT INTO ${sqlIdent(plan.table)} (${plan.columns.map(sqlIdent).join(', ')}) VALUES (`;
380
427
  const lines: string[] = [];
381
428
  let limit = PAGE_ROWS;
429
+ let cap = MAX_PAGE_ROWS;
382
430
  let after: { key?: number; offset?: number } = {};
383
431
  for (;;) {
384
432
  let page: Array<Record<string, unknown>>;
@@ -389,21 +437,25 @@ function dumpTable(caller: Caller, database: string, plan: TablePlan): { text: s
389
437
  if (limit > 1) {
390
438
  const next = Math.max(1, Math.floor(limit / 2));
391
439
  caller.log(`pull D1: \`${plan.table}\` refused a page of ${limit} — asking for ${next}: ${message}`);
440
+ cap = Math.min(cap, Math.max(PAGE_ROWS, next));
392
441
  limit = next;
393
442
  continue;
394
443
  }
395
444
  throw new Error(`could not read \`${plan.table}\` from D1: ${message}`);
396
445
  }
446
+ let bytes = 0;
397
447
  for (const row of page) {
398
448
  const literals = plan.columns.map((_, i) => row[`c${i}`]);
399
449
  if (literals.some((v) => typeof v !== 'string')) {
400
450
  throw new Error(`D1 returned a non-literal value paging \`${plan.table}\` — refusing a snapshot that may not restore`);
401
451
  }
402
- lines.push(`${into}${literals.join(', ')});`);
452
+ const values = literals.join(', ');
453
+ bytes += values.length;
454
+ lines.push(`${into}${values});`);
403
455
  }
404
456
  if (page.length < limit) break;
405
457
  after = plan.key ? { key: Number(page[page.length - 1]?.k) } : { offset: (after.offset ?? 0) + page.length };
406
- limit = Math.min(PAGE_ROWS, limit * 2);
458
+ limit = nextPageRows(limit, page.length, bytes, cap);
407
459
  }
408
460
  return { text: lines.join('\n'), rows: lines.length };
409
461
  }
@@ -495,7 +547,11 @@ export async function pullD1ToSqlite(options: PullD1Options): Promise<void> {
495
547
  }
496
548
  }
497
549
  // One table at a time, so a fault is located rather than smeared over the whole load.
498
- for (const { text } of dumps) if (text) db.exec(text);
550
+ // 🔴 And each table in ONE transaction: bare, every row's INSERT is its own commit and its
551
+ // own journal and sync. Measured 2026-10-29 (forge task 3957), photos' ~400 s load; 3,000
552
+ // rows took 2,881 ms bare and 13 ms in a transaction.
553
+ const load = db.transaction((text: string) => db.exec(text));
554
+ for (const { text } of dumps) if (text) load(text);
499
555
  for (const t of triggers) db.exec(t.sql);
500
556
  if (options.afterLoadSql) db.exec(options.afterLoadSql);
501
557
  // 🔴 Every table holds as many rows as were read from D1, or this is not a backup: the check
@@ -201,7 +201,10 @@ describe("linkSource and the link beside the code", () => {
201
201
  test("linkedRoomBytes is what statfs says minus the floor and what is owed; a store that is not there holds nothing back", () => {
202
202
  const room = linkedRoomBytes(base);
203
203
  expect(typeof room).toBe("number");
204
- expect(linkedRoomBytes(base, 1024)).toBe((room as number) - 1024);
204
+ // Two statfs reads on a disk something else is writing (a backup, 2026-10-29) differ by what
205
+ // it wrote between them, so what is owed is a terabyte and the check allows 256 MiB of churn.
206
+ const owed = 2 ** 40;
207
+ expect(Math.abs((linkedRoomBytes(base, owed) as number) - ((room as number) - owed))).toBeLessThan(2 ** 28);
205
208
  expect(linkedRoomBytes(join(base, "no", "such", "store"))).toBeNull();
206
209
  });
207
210