cursedbelt-server 4.52.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.
- package/dist/server/d1/pullD1.d.ts +51 -4
- package/dist/server/d1/pullD1.js +90 -11
- package/dist/server/engagement/index.d.ts +1 -1
- package/dist/server/engagement/index.js +1 -1
- package/dist/server/engagement/policy.d.ts +12 -1
- package/dist/server/engagement/policy.js +14 -2
- package/package.json +1 -1
- package/src/server/d1/pullD1.spec.ts +118 -7
- package/src/server/d1/pullD1.ts +103 -12
- package/src/server/dropzone/links.spec.ts +4 -1
- package/src/server/engagement/engagement.spec.ts +16 -0
- package/src/server/engagement/index.ts +1 -0
- package/src/server/engagement/policy.ts +16 -2
|
@@ -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
|
|
@@ -101,13 +130,31 @@ export declare const wranglerArgv: (bun?: string) => string[];
|
|
|
101
130
|
*/
|
|
102
131
|
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. */
|
|
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;
|
|
105
137
|
}): {
|
|
106
138
|
code: number;
|
|
107
139
|
stdout: string;
|
|
108
140
|
stderr: string;
|
|
109
141
|
};
|
|
110
|
-
/**
|
|
142
|
+
/**
|
|
143
|
+
* The environment {@link spawnWrangler} gives one call: this process's, wrangler's debug log pointed
|
|
144
|
+
* at a file in the call's own `scratch` directory, then the caller's `overlay` — which may still
|
|
145
|
+
* name a `WRANGLER_LOG_PATH` of its own.
|
|
146
|
+
*
|
|
147
|
+
* 🔴 Why the log is the call's own. Wrangler writes a `wrangler-<stamp>.log` into its global
|
|
148
|
+
* `logs/` for EVERY invocation, and with `--json` that log holds the command's whole result again.
|
|
149
|
+
* A backup is hundreds of paged `d1 execute --json` SELECTs, so every nightly backup copied its
|
|
150
|
+
* database into `~/Library/Preferences/.wrangler/logs`, in plain text. Measured 2026-10-28 (forge
|
|
151
|
+
* task 3877): 9,393 logs, 1.24 GB in five days; photos' nightly backup alone made 600 calls and 169 MB of them
|
|
152
|
+
* (its 171,590-row gazetteer at {@link PAGE_ROWS} a page); the runner's prune keeps five days.
|
|
153
|
+
* A file ending `.log` is a file to wrangler, not a directory, and the scratch directory goes
|
|
154
|
+
* with the call — unless the call failed, when {@link spawnToFile} leaves the log for its reader.
|
|
155
|
+
*/
|
|
156
|
+
export declare function wranglerSpawnEnv(scratch: string, overlay?: Record<string, string | undefined>, base?: Record<string, string | undefined>): Record<string, string | undefined>;
|
|
157
|
+
/** The real {@link Wrangler}: `bun x wrangler …` in `cwd`, with `env` added to this process's ({@link wranglerSpawnEnv}). */
|
|
111
158
|
export declare function spawnWrangler(options: {
|
|
112
159
|
cwd: string;
|
|
113
160
|
env?: Record<string, string | undefined>;
|
package/dist/server/d1/pullD1.js
CHANGED
|
@@ -44,7 +44,7 @@
|
|
|
44
44
|
* below still refuses a load short of what was read.
|
|
45
45
|
*/
|
|
46
46
|
import { Database } from 'bun:sqlite';
|
|
47
|
-
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
|
47
|
+
import { existsSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
|
48
48
|
import { tmpdir } from 'node:os';
|
|
49
49
|
import { join } from 'node:path';
|
|
50
50
|
/** Which side a backup must read. Pure, so every branch is testable without a network. */
|
|
@@ -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
|
|
@@ -130,18 +163,51 @@ export const wranglerArgv = (bun = process.execPath) => [bun, 'x', 'wrangler'];
|
|
|
130
163
|
export function spawnToFile(argv, options = {}) {
|
|
131
164
|
const dir = mkdtempSync(join(tmpdir(), 'cursedbelt-spawn-'));
|
|
132
165
|
const out = join(dir, 'stdout');
|
|
166
|
+
let code = 1;
|
|
133
167
|
try {
|
|
134
|
-
const
|
|
168
|
+
const env = typeof options.env === 'function' ? options.env(dir) : options.env;
|
|
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 });
|
|
135
171
|
const stdout = existsSync(out) ? readFileSync(out, 'utf8') : '';
|
|
136
|
-
|
|
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;
|
|
177
|
+
return { code, stdout, stderr: r.stderr.toString() };
|
|
137
178
|
}
|
|
138
179
|
finally {
|
|
139
|
-
|
|
180
|
+
// A failed call keeps whatever the child wrote beside its stdout — wrangler's debug log, whose
|
|
181
|
+
// path its own error message prints — for the OS to reap from tmpdir. A green one keeps nothing.
|
|
182
|
+
if (code === 0)
|
|
183
|
+
rmSync(dir, { recursive: true, force: true });
|
|
184
|
+
else {
|
|
185
|
+
rmSync(out, { force: true });
|
|
186
|
+
if (readdirSync(dir).length === 0)
|
|
187
|
+
rmSync(dir, { recursive: true, force: true });
|
|
188
|
+
}
|
|
140
189
|
}
|
|
141
190
|
}
|
|
142
|
-
/**
|
|
191
|
+
/**
|
|
192
|
+
* The environment {@link spawnWrangler} gives one call: this process's, wrangler's debug log pointed
|
|
193
|
+
* at a file in the call's own `scratch` directory, then the caller's `overlay` — which may still
|
|
194
|
+
* name a `WRANGLER_LOG_PATH` of its own.
|
|
195
|
+
*
|
|
196
|
+
* 🔴 Why the log is the call's own. Wrangler writes a `wrangler-<stamp>.log` into its global
|
|
197
|
+
* `logs/` for EVERY invocation, and with `--json` that log holds the command's whole result again.
|
|
198
|
+
* A backup is hundreds of paged `d1 execute --json` SELECTs, so every nightly backup copied its
|
|
199
|
+
* database into `~/Library/Preferences/.wrangler/logs`, in plain text. Measured 2026-10-28 (forge
|
|
200
|
+
* task 3877): 9,393 logs, 1.24 GB in five days; photos' nightly backup alone made 600 calls and 169 MB of them
|
|
201
|
+
* (its 171,590-row gazetteer at {@link PAGE_ROWS} a page); the runner's prune keeps five days.
|
|
202
|
+
* A file ending `.log` is a file to wrangler, not a directory, and the scratch directory goes
|
|
203
|
+
* with the call — unless the call failed, when {@link spawnToFile} leaves the log for its reader.
|
|
204
|
+
*/
|
|
205
|
+
export function wranglerSpawnEnv(scratch, overlay = {}, base = process.env) {
|
|
206
|
+
return { ...base, WRANGLER_LOG_PATH: join(scratch, 'wrangler.log'), ...overlay };
|
|
207
|
+
}
|
|
208
|
+
/** The real {@link Wrangler}: `bun x wrangler …` in `cwd`, with `env` added to this process's ({@link wranglerSpawnEnv}). */
|
|
143
209
|
export function spawnWrangler(options) {
|
|
144
|
-
return (args) => spawnToFile([...wranglerArgv(), ...args], { cwd: options.cwd, env:
|
|
210
|
+
return (args) => spawnToFile([...wranglerArgv(), ...args], { cwd: options.cwd, env: (scratch) => wranglerSpawnEnv(scratch, options.env) });
|
|
145
211
|
}
|
|
146
212
|
/**
|
|
147
213
|
* 🔴 Trailing NUL bytes off a `wrangler d1 export` file, in place. Returns how many were removed.
|
|
@@ -271,11 +337,16 @@ export function pageSql(plan, limit, after) {
|
|
|
271
337
|
* size back toward {@link PAGE_ROWS}. Before 4.33.1 nothing grew it back: desk's first launchd
|
|
272
338
|
* backup (2026-09-25) hit a few slow calls early and read its 3,381-row table 15 rows per call —
|
|
273
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.
|
|
274
344
|
*/
|
|
275
345
|
function dumpTable(caller, database, plan) {
|
|
276
346
|
const into = `INSERT INTO ${sqlIdent(plan.table)} (${plan.columns.map(sqlIdent).join(', ')}) VALUES (`;
|
|
277
347
|
const lines = [];
|
|
278
348
|
let limit = PAGE_ROWS;
|
|
349
|
+
let cap = MAX_PAGE_ROWS;
|
|
279
350
|
let after = {};
|
|
280
351
|
for (;;) {
|
|
281
352
|
let page;
|
|
@@ -287,22 +358,26 @@ function dumpTable(caller, database, plan) {
|
|
|
287
358
|
if (limit > 1) {
|
|
288
359
|
const next = Math.max(1, Math.floor(limit / 2));
|
|
289
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));
|
|
290
362
|
limit = next;
|
|
291
363
|
continue;
|
|
292
364
|
}
|
|
293
365
|
throw new Error(`could not read \`${plan.table}\` from D1: ${message}`);
|
|
294
366
|
}
|
|
367
|
+
let bytes = 0;
|
|
295
368
|
for (const row of page) {
|
|
296
369
|
const literals = plan.columns.map((_, i) => row[`c${i}`]);
|
|
297
370
|
if (literals.some((v) => typeof v !== 'string')) {
|
|
298
371
|
throw new Error(`D1 returned a non-literal value paging \`${plan.table}\` — refusing a snapshot that may not restore`);
|
|
299
372
|
}
|
|
300
|
-
|
|
373
|
+
const values = literals.join(', ');
|
|
374
|
+
bytes += values.length;
|
|
375
|
+
lines.push(`${into}${values});`);
|
|
301
376
|
}
|
|
302
377
|
if (page.length < limit)
|
|
303
378
|
break;
|
|
304
379
|
after = plan.key ? { key: Number(page[page.length - 1]?.k) } : { offset: (after.offset ?? 0) + page.length };
|
|
305
|
-
limit =
|
|
380
|
+
limit = nextPageRows(limit, page.length, bytes, cap);
|
|
306
381
|
}
|
|
307
382
|
return { text: lines.join('\n'), rows: lines.length };
|
|
308
383
|
}
|
|
@@ -386,9 +461,13 @@ export async function pullD1ToSqlite(options) {
|
|
|
386
461
|
}
|
|
387
462
|
}
|
|
388
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));
|
|
389
468
|
for (const { text } of dumps)
|
|
390
469
|
if (text)
|
|
391
|
-
|
|
470
|
+
load(text);
|
|
392
471
|
for (const t of triggers)
|
|
393
472
|
db.exec(t.sql);
|
|
394
473
|
if (options.afterLoadSql)
|
|
@@ -51,6 +51,6 @@ export { type AppEngagementSnapshot, createEngagementRecorder, type EngagementAp
|
|
|
51
51
|
export { type EngagementEnv, type EngagementEnvOptions, readEngagementEnv } from "./env.js";
|
|
52
52
|
export { actionsFromManifest } from "./manifestPlaces.js";
|
|
53
53
|
export { type EngagementPlace, engagementActionsFor, engagementPlacesFor } from "./places.js";
|
|
54
|
-
export { type ActionRef, classifyInterest, dayKey, daysSince, ENGAGEMENT_EXCLUDED_APPS, engagementAllowedForApp, foldView, INTEREST_ACTIVE_DAYS, INTEREST_FADING_DAYS, type InterestVerdict, MAX_DWELL_SLICE_MS, normalizePlaceId, OTHER_PLACE, type PlaceRef, resolvePlace, SESSION_GAP_MS, type ViewFold, } from "./policy.js";
|
|
54
|
+
export { type ActionRef, classifyInterest, dayKey, daysSince, ENGAGEMENT_EXCLUDED_APPS, ENGAGEMENT_ZONE, engagementAllowedForApp, foldView, INTEREST_ACTIVE_DAYS, INTEREST_FADING_DAYS, type InterestVerdict, MAX_DWELL_SLICE_MS, normalizePlaceId, OTHER_PLACE, type PlaceRef, resolvePlace, SESSION_GAP_MS, type ViewFold, } from "./policy.js";
|
|
55
55
|
export { ENGAGEMENT_DAY_RETENTION_DAYS, type EngagementDay, EngagementStore, type EngagementStoreOptions, type EngagementUser, type EngagementUserPlace, } from "./store.js";
|
|
56
56
|
export { type ActionEngagement, type AppEngagement, type DailyEngagement, type PlaceEngagement, returnCurve, summarize, type SummarizeInput, type UserEngagement, } from "./summary.js";
|
|
@@ -51,6 +51,6 @@ export { createEngagementRecorder, readAppEngagement, } from "./api.js";
|
|
|
51
51
|
export { readEngagementEnv } from "./env.js";
|
|
52
52
|
export { actionsFromManifest } from "./manifestPlaces.js";
|
|
53
53
|
export { engagementActionsFor, engagementPlacesFor } from "./places.js";
|
|
54
|
-
export { classifyInterest, dayKey, daysSince, ENGAGEMENT_EXCLUDED_APPS, engagementAllowedForApp, foldView, INTEREST_ACTIVE_DAYS, INTEREST_FADING_DAYS, MAX_DWELL_SLICE_MS, normalizePlaceId, OTHER_PLACE, resolvePlace, SESSION_GAP_MS, } from "./policy.js";
|
|
54
|
+
export { classifyInterest, dayKey, daysSince, ENGAGEMENT_EXCLUDED_APPS, ENGAGEMENT_ZONE, engagementAllowedForApp, foldView, INTEREST_ACTIVE_DAYS, INTEREST_FADING_DAYS, MAX_DWELL_SLICE_MS, normalizePlaceId, OTHER_PLACE, resolvePlace, SESSION_GAP_MS, } from "./policy.js";
|
|
55
55
|
export { ENGAGEMENT_DAY_RETENTION_DAYS, EngagementStore, } from "./store.js";
|
|
56
56
|
export { returnCurve, summarize, } from "./summary.js";
|
|
@@ -145,7 +145,18 @@ export interface ViewFold {
|
|
|
145
145
|
* number boring, never negative.
|
|
146
146
|
*/
|
|
147
147
|
export declare function foldView(lastTs: number | null, ts: number): ViewFold;
|
|
148
|
-
/**
|
|
148
|
+
/**
|
|
149
|
+
* The zone every daily row is counted in: the owner's (forge task 3846).
|
|
150
|
+
*
|
|
151
|
+
* A site-wide daily count has to pick ONE zone — two viewers in two zones cannot both have
|
|
152
|
+
* their own midnight on the same row — and the person who reads these charts is the owner,
|
|
153
|
+
* in Central time. Until 2026-10-28 the rows were UTC days, which turn over at 7 pm Central,
|
|
154
|
+
* so every evening visit landed on tomorrow. Rows written before then stay UTC days: a
|
|
155
|
+
* `(user, place, day)` row holds no hours to re-bucket it by. The console labels the chart
|
|
156
|
+
* with this zone (station `views/metrics/EngagementPanel.tsx`).
|
|
157
|
+
*/
|
|
158
|
+
export declare const ENGAGEMENT_ZONE = "America/Chicago";
|
|
159
|
+
/** `2026-08-14` for a timestamp, on {@link ENGAGEMENT_ZONE}'s clock. The day bucket every row is keyed on. */
|
|
149
160
|
export declare function dayKey(ts: number): string;
|
|
150
161
|
/** How many whole days ago `ts` was, relative to `now`. */
|
|
151
162
|
export declare function daysSince(ts: number, now: number): number;
|
|
@@ -38,6 +38,7 @@
|
|
|
38
38
|
* a drop-off signal stated in days rather than as a rate. Nothing is a ratio
|
|
39
39
|
* over a denominator of two.
|
|
40
40
|
*/
|
|
41
|
+
import { formatDate } from "cwip/date";
|
|
41
42
|
/** The bucket a view lands in when its place is not on the app's allowlist. */
|
|
42
43
|
export const OTHER_PLACE = "other";
|
|
43
44
|
/**
|
|
@@ -198,9 +199,20 @@ export function foldView(lastTs, ts) {
|
|
|
198
199
|
return { newSession: true, activeMs: 0 };
|
|
199
200
|
return { newSession: false, activeMs: Math.min(gap, MAX_DWELL_SLICE_MS) };
|
|
200
201
|
}
|
|
201
|
-
/**
|
|
202
|
+
/**
|
|
203
|
+
* The zone every daily row is counted in: the owner's (forge task 3846).
|
|
204
|
+
*
|
|
205
|
+
* A site-wide daily count has to pick ONE zone — two viewers in two zones cannot both have
|
|
206
|
+
* their own midnight on the same row — and the person who reads these charts is the owner,
|
|
207
|
+
* in Central time. Until 2026-10-28 the rows were UTC days, which turn over at 7 pm Central,
|
|
208
|
+
* so every evening visit landed on tomorrow. Rows written before then stay UTC days: a
|
|
209
|
+
* `(user, place, day)` row holds no hours to re-bucket it by. The console labels the chart
|
|
210
|
+
* with this zone (station `views/metrics/EngagementPanel.tsx`).
|
|
211
|
+
*/
|
|
212
|
+
export const ENGAGEMENT_ZONE = "America/Chicago";
|
|
213
|
+
/** `2026-08-14` for a timestamp, on {@link ENGAGEMENT_ZONE}'s clock. The day bucket every row is keyed on. */
|
|
202
214
|
export function dayKey(ts) {
|
|
203
|
-
return new Date(ts)
|
|
215
|
+
return formatDate(new Date(ts), "YYYY-MM-DD", ENGAGEMENT_ZONE);
|
|
204
216
|
}
|
|
205
217
|
/** How many whole days ago `ts` was, relative to `now`. */
|
|
206
218
|
export function daysSince(ts, now) {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "cursedbelt-server",
|
|
3
|
-
"version": "4.
|
|
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.",
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { Database } from 'bun:sqlite';
|
|
2
2
|
import { afterEach, describe, expect, test } from 'bun:test';
|
|
3
|
-
import { existsSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { chmodSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
|
4
4
|
import { tmpdir } from 'node:os';
|
|
5
5
|
import { join } from 'node:path';
|
|
6
6
|
import {
|
|
@@ -8,11 +8,12 @@ import {
|
|
|
8
8
|
chooseBackupSource,
|
|
9
9
|
pullD1ToSqlite,
|
|
10
10
|
servedRuntime,
|
|
11
|
+
spawnWrangler,
|
|
11
12
|
stripTrailingNuls,
|
|
12
13
|
type Wrangler,
|
|
13
14
|
wranglerArgv,
|
|
14
15
|
} from './localBackup.js';
|
|
15
|
-
import { PAGE_ROWS, pageSql, spawnToFile, tablePlan } from './pullD1.js';
|
|
16
|
+
import { isTransient, PAGE_ROWS, pageSql, spawnToFile, tablePlan } from './pullD1.js';
|
|
16
17
|
|
|
17
18
|
const dirs: string[] = [];
|
|
18
19
|
const scratch = (): string => {
|
|
@@ -198,10 +199,68 @@ describe('pulling D1 down — paged SELECTs, table by table, never an export', (
|
|
|
198
199
|
expect((db.query('select count(*) n from items_fts_map').get() as { n: number }).n).toBe(n);
|
|
199
200
|
db.close();
|
|
200
201
|
const mapPages = seen.map((a) => a[a.indexOf('--command') + 1] as string).filter((sql) => sql.includes('FROM "items_fts_map"'));
|
|
201
|
-
|
|
202
|
+
// 500, then 1,000 small rows: the second page is short, so the table ends there.
|
|
203
|
+
expect(mapPages).toHaveLength(2);
|
|
202
204
|
expect(mapPages[1]).toContain('WHERE _rowid_ >');
|
|
203
205
|
});
|
|
204
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
|
+
|
|
205
264
|
test('a WITHOUT ROWID table pages by its primary key and OFFSET', () => {
|
|
206
265
|
const plan = tablePlan('kv', 'CREATE TABLE kv (k TEXT PRIMARY KEY, v) WITHOUT ROWID', [
|
|
207
266
|
{ name: 'k', pk: 1 },
|
|
@@ -250,10 +309,7 @@ describe('pulling D1 down — paged SELECTs, table by table, never an export', (
|
|
|
250
309
|
const db = opened(dir);
|
|
251
310
|
expect((db.query('select count(*) n from items_fts_map').get() as { n: number }).n).toBe(n);
|
|
252
311
|
db.close();
|
|
253
|
-
const limits = seen
|
|
254
|
-
.map((a) => a[a.indexOf('--command') + 1] as string)
|
|
255
|
-
.filter((sql) => sql.includes('FROM "items_fts_map"'))
|
|
256
|
-
.map((sql) => Number(/LIMIT (\d+)/.exec(sql)?.[1]));
|
|
312
|
+
const limits = limitsOf(seen, 'items_fts_map');
|
|
257
313
|
// refused at 500, read at 250, then back to 500 for the rest.
|
|
258
314
|
expect(limits.slice(0, 3)).toEqual([PAGE_ROWS, PAGE_ROWS / 2, PAGE_ROWS]);
|
|
259
315
|
expect(limits.slice(2).every((limit) => limit === PAGE_ROWS)).toBe(true);
|
|
@@ -471,6 +527,61 @@ END;`;
|
|
|
471
527
|
expect(JSON.parse(r.stdout)).toHaveLength(1);
|
|
472
528
|
});
|
|
473
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
|
+
|
|
538
|
+
test("🔴 a wrangler call's debug log is the call's own — gone with a green call, kept for a red one", () => {
|
|
539
|
+
// `bun x wrangler` runs the cwd's own `node_modules/.bin/wrangler` first, so this one stands
|
|
540
|
+
// in for the real thing. It logs as wrangler does: every message, a `--json` result included,
|
|
541
|
+
// appended to `$WRANGLER_LOG_PATH`, else to a file of its own in the global `logs/`.
|
|
542
|
+
const cwd = scratch();
|
|
543
|
+
const home = join(cwd, 'home');
|
|
544
|
+
const global = join(home, 'Library', 'Preferences', '.wrangler', 'logs');
|
|
545
|
+
mkdirSync(join(cwd, 'node_modules', '.bin'), { recursive: true });
|
|
546
|
+
const fake = join(cwd, 'node_modules', '.bin', 'wrangler');
|
|
547
|
+
writeFileSync(
|
|
548
|
+
fake,
|
|
549
|
+
[
|
|
550
|
+
'#!/bin/sh',
|
|
551
|
+
`log="\${WRANGLER_LOG_PATH:-${global}}"`,
|
|
552
|
+
'case "$log" in *.log) ;; *) mkdir -p "$log"; log="$log/wrangler-$$.log" ;; esac',
|
|
553
|
+
'printf "the whole page again" >> "$log"',
|
|
554
|
+
'printf "[]"',
|
|
555
|
+
'exit "$1"',
|
|
556
|
+
].join('\n'),
|
|
557
|
+
);
|
|
558
|
+
chmodSync(fake, 0o755);
|
|
559
|
+
const wrangler = spawnWrangler({ cwd, env: { HOME: home } });
|
|
560
|
+
const kept = () => readdirSync(tmpdir()).filter((name) => name.startsWith('cursedbelt-spawn-'));
|
|
561
|
+
const before = new Set(kept());
|
|
562
|
+
|
|
563
|
+
const green = wrangler(['0']);
|
|
564
|
+
expect(green.code).toBe(0);
|
|
565
|
+
expect(green.stdout).toBe('[]');
|
|
566
|
+
// The failure this exists for: a nightly backup's every page, copied into the global logs.
|
|
567
|
+
expect(existsSync(global) ? readdirSync(global) : []).toEqual([]);
|
|
568
|
+
expect(kept().filter((name) => !before.has(name))).toEqual([]);
|
|
569
|
+
|
|
570
|
+
const red = wrangler(['1']);
|
|
571
|
+
expect(red.code).toBe(1);
|
|
572
|
+
expect(existsSync(global) ? readdirSync(global) : []).toEqual([]);
|
|
573
|
+
const left = kept().filter((name) => !before.has(name));
|
|
574
|
+
expect(left).toHaveLength(1);
|
|
575
|
+
const log = join(tmpdir(), left[0] as string, 'wrangler.log');
|
|
576
|
+
dirs.push(join(log, '..'));
|
|
577
|
+
expect(readFileSync(log, 'utf8')).toBe('the whole page again');
|
|
578
|
+
|
|
579
|
+
// A caller that names its own log path keeps it.
|
|
580
|
+
const mine = join(cwd, 'mine.log');
|
|
581
|
+
expect(spawnWrangler({ cwd, env: { HOME: home, WRANGLER_LOG_PATH: mine } })(['0']).code).toBe(0);
|
|
582
|
+
expect(readFileSync(mine, 'utf8')).toBe('the whole page again');
|
|
583
|
+
});
|
|
584
|
+
|
|
474
585
|
test('a cut page names its byte count, so a 64 KiB multiple is visible in the log', async () => {
|
|
475
586
|
const cut: Wrangler = () => ({ code: 0, stdout: '[{"results":[{"name":"ite', stderr: '' });
|
|
476
587
|
await expect(pull(scratch(), cut)).rejects.toThrow(/\(25 bytes of stdout\)/);
|
package/src/server/d1/pullD1.ts
CHANGED
|
@@ -45,7 +45,7 @@
|
|
|
45
45
|
*/
|
|
46
46
|
|
|
47
47
|
import { Database } from 'bun:sqlite';
|
|
48
|
-
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
|
48
|
+
import { existsSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
|
49
49
|
import { tmpdir } from 'node:os';
|
|
50
50
|
import { join } from 'node:path';
|
|
51
51
|
|
|
@@ -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
|
|
@@ -149,22 +185,64 @@ export const wranglerArgv = (bun: string = process.execPath): string[] => [bun,
|
|
|
149
185
|
*/
|
|
150
186
|
export function spawnToFile(
|
|
151
187
|
argv: string[],
|
|
152
|
-
options: {
|
|
188
|
+
options: {
|
|
189
|
+
cwd?: string;
|
|
190
|
+
/** The child's whole environment, or a function of this call's own scratch directory that returns it. */
|
|
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;
|
|
194
|
+
} = {},
|
|
153
195
|
): { code: number; stdout: string; stderr: string } {
|
|
154
196
|
const dir = mkdtempSync(join(tmpdir(), 'cursedbelt-spawn-'));
|
|
155
197
|
const out = join(dir, 'stdout');
|
|
198
|
+
let code = 1;
|
|
156
199
|
try {
|
|
157
|
-
const
|
|
200
|
+
const env = typeof options.env === 'function' ? options.env(dir) : options.env;
|
|
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 });
|
|
158
203
|
const stdout = existsSync(out) ? readFileSync(out, 'utf8') : '';
|
|
159
|
-
|
|
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;
|
|
209
|
+
return { code, stdout, stderr: r.stderr.toString() };
|
|
160
210
|
} finally {
|
|
161
|
-
|
|
211
|
+
// A failed call keeps whatever the child wrote beside its stdout — wrangler's debug log, whose
|
|
212
|
+
// path its own error message prints — for the OS to reap from tmpdir. A green one keeps nothing.
|
|
213
|
+
if (code === 0) rmSync(dir, { recursive: true, force: true });
|
|
214
|
+
else {
|
|
215
|
+
rmSync(out, { force: true });
|
|
216
|
+
if (readdirSync(dir).length === 0) rmSync(dir, { recursive: true, force: true });
|
|
217
|
+
}
|
|
162
218
|
}
|
|
163
219
|
}
|
|
164
220
|
|
|
165
|
-
/**
|
|
221
|
+
/**
|
|
222
|
+
* The environment {@link spawnWrangler} gives one call: this process's, wrangler's debug log pointed
|
|
223
|
+
* at a file in the call's own `scratch` directory, then the caller's `overlay` — which may still
|
|
224
|
+
* name a `WRANGLER_LOG_PATH` of its own.
|
|
225
|
+
*
|
|
226
|
+
* 🔴 Why the log is the call's own. Wrangler writes a `wrangler-<stamp>.log` into its global
|
|
227
|
+
* `logs/` for EVERY invocation, and with `--json` that log holds the command's whole result again.
|
|
228
|
+
* A backup is hundreds of paged `d1 execute --json` SELECTs, so every nightly backup copied its
|
|
229
|
+
* database into `~/Library/Preferences/.wrangler/logs`, in plain text. Measured 2026-10-28 (forge
|
|
230
|
+
* task 3877): 9,393 logs, 1.24 GB in five days; photos' nightly backup alone made 600 calls and 169 MB of them
|
|
231
|
+
* (its 171,590-row gazetteer at {@link PAGE_ROWS} a page); the runner's prune keeps five days.
|
|
232
|
+
* A file ending `.log` is a file to wrangler, not a directory, and the scratch directory goes
|
|
233
|
+
* with the call — unless the call failed, when {@link spawnToFile} leaves the log for its reader.
|
|
234
|
+
*/
|
|
235
|
+
export function wranglerSpawnEnv(
|
|
236
|
+
scratch: string,
|
|
237
|
+
overlay: Record<string, string | undefined> = {},
|
|
238
|
+
base: Record<string, string | undefined> = process.env,
|
|
239
|
+
): Record<string, string | undefined> {
|
|
240
|
+
return { ...base, WRANGLER_LOG_PATH: join(scratch, 'wrangler.log'), ...overlay };
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/** The real {@link Wrangler}: `bun x wrangler …` in `cwd`, with `env` added to this process's ({@link wranglerSpawnEnv}). */
|
|
166
244
|
export function spawnWrangler(options: { cwd: string; env?: Record<string, string | undefined> }): Wrangler {
|
|
167
|
-
return (args) => spawnToFile([...wranglerArgv(), ...args], { cwd: options.cwd, env:
|
|
245
|
+
return (args) => spawnToFile([...wranglerArgv(), ...args], { cwd: options.cwd, env: (scratch) => wranglerSpawnEnv(scratch, options.env) });
|
|
168
246
|
}
|
|
169
247
|
|
|
170
248
|
/**
|
|
@@ -339,11 +417,16 @@ export function pageSql(plan: TablePlan, limit: number, after: { key?: number; o
|
|
|
339
417
|
* size back toward {@link PAGE_ROWS}. Before 4.33.1 nothing grew it back: desk's first launchd
|
|
340
418
|
* backup (2026-09-25) hit a few slow calls early and read its 3,381-row table 15 rows per call —
|
|
341
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.
|
|
342
424
|
*/
|
|
343
425
|
function dumpTable(caller: Caller, database: string, plan: TablePlan): { text: string; rows: number } {
|
|
344
426
|
const into = `INSERT INTO ${sqlIdent(plan.table)} (${plan.columns.map(sqlIdent).join(', ')}) VALUES (`;
|
|
345
427
|
const lines: string[] = [];
|
|
346
428
|
let limit = PAGE_ROWS;
|
|
429
|
+
let cap = MAX_PAGE_ROWS;
|
|
347
430
|
let after: { key?: number; offset?: number } = {};
|
|
348
431
|
for (;;) {
|
|
349
432
|
let page: Array<Record<string, unknown>>;
|
|
@@ -354,21 +437,25 @@ function dumpTable(caller: Caller, database: string, plan: TablePlan): { text: s
|
|
|
354
437
|
if (limit > 1) {
|
|
355
438
|
const next = Math.max(1, Math.floor(limit / 2));
|
|
356
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));
|
|
357
441
|
limit = next;
|
|
358
442
|
continue;
|
|
359
443
|
}
|
|
360
444
|
throw new Error(`could not read \`${plan.table}\` from D1: ${message}`);
|
|
361
445
|
}
|
|
446
|
+
let bytes = 0;
|
|
362
447
|
for (const row of page) {
|
|
363
448
|
const literals = plan.columns.map((_, i) => row[`c${i}`]);
|
|
364
449
|
if (literals.some((v) => typeof v !== 'string')) {
|
|
365
450
|
throw new Error(`D1 returned a non-literal value paging \`${plan.table}\` — refusing a snapshot that may not restore`);
|
|
366
451
|
}
|
|
367
|
-
|
|
452
|
+
const values = literals.join(', ');
|
|
453
|
+
bytes += values.length;
|
|
454
|
+
lines.push(`${into}${values});`);
|
|
368
455
|
}
|
|
369
456
|
if (page.length < limit) break;
|
|
370
457
|
after = plan.key ? { key: Number(page[page.length - 1]?.k) } : { offset: (after.offset ?? 0) + page.length };
|
|
371
|
-
limit =
|
|
458
|
+
limit = nextPageRows(limit, page.length, bytes, cap);
|
|
372
459
|
}
|
|
373
460
|
return { text: lines.join('\n'), rows: lines.length };
|
|
374
461
|
}
|
|
@@ -460,7 +547,11 @@ export async function pullD1ToSqlite(options: PullD1Options): Promise<void> {
|
|
|
460
547
|
}
|
|
461
548
|
}
|
|
462
549
|
// One table at a time, so a fault is located rather than smeared over the whole load.
|
|
463
|
-
|
|
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);
|
|
464
555
|
for (const t of triggers) db.exec(t.sql);
|
|
465
556
|
if (options.afterLoadSql) db.exec(options.afterLoadSql);
|
|
466
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
|
-
|
|
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
|
|
|
@@ -19,6 +19,8 @@ import { createEngagementRecorder, readAppEngagement } from "./api.js";
|
|
|
19
19
|
import { readEngagementEnv } from "./env.js";
|
|
20
20
|
import {
|
|
21
21
|
classifyInterest,
|
|
22
|
+
dayKey,
|
|
23
|
+
ENGAGEMENT_ZONE,
|
|
22
24
|
engagementAllowedForApp,
|
|
23
25
|
foldView,
|
|
24
26
|
MAX_DWELL_SLICE_MS,
|
|
@@ -242,6 +244,20 @@ describe("sessionization — the gap rule", () => {
|
|
|
242
244
|
});
|
|
243
245
|
});
|
|
244
246
|
|
|
247
|
+
describe("a daily row is a day on the owner's clock (forge task 3846)", () => {
|
|
248
|
+
test("an evening visit in Central time lands on that evening's day, not UTC's tomorrow", () => {
|
|
249
|
+
expect(ENGAGEMENT_ZONE).toBe("America/Chicago");
|
|
250
|
+
expect(dayKey(Date.parse("2026-10-28T02:16:00.000Z"))).toBe("2026-10-27");
|
|
251
|
+
expect(dayKey(Date.parse("2026-10-28T05:00:00.000Z"))).toBe("2026-10-28");
|
|
252
|
+
});
|
|
253
|
+
|
|
254
|
+
test("the store writes the visit into that row", () => {
|
|
255
|
+
const s = store();
|
|
256
|
+
s.recordView({ userKey: "u", place: "files", ts: Date.parse("2026-10-28T02:16:00.000Z") });
|
|
257
|
+
expect(s.days(Date.parse("2026-10-27T12:00:00.000Z")).map((d) => d.day)).toEqual(["2026-10-27"]);
|
|
258
|
+
});
|
|
259
|
+
});
|
|
260
|
+
|
|
245
261
|
describe("the store credits dwell BACKWARDS, to the page you were reading", () => {
|
|
246
262
|
test("two minutes on `files` then a move to `ask` scores files, not ask", () => {
|
|
247
263
|
// Crediting forwards would make the most-abandoned page in the app score
|
|
@@ -39,6 +39,8 @@
|
|
|
39
39
|
* over a denominator of two.
|
|
40
40
|
*/
|
|
41
41
|
|
|
42
|
+
import { formatDate } from "cwip/date";
|
|
43
|
+
|
|
42
44
|
/** The bucket a view lands in when its place is not on the app's allowlist. */
|
|
43
45
|
export const OTHER_PLACE = "other";
|
|
44
46
|
|
|
@@ -226,9 +228,21 @@ export function foldView(lastTs: number | null, ts: number): ViewFold {
|
|
|
226
228
|
return { newSession: false, activeMs: Math.min(gap, MAX_DWELL_SLICE_MS) };
|
|
227
229
|
}
|
|
228
230
|
|
|
229
|
-
/**
|
|
231
|
+
/**
|
|
232
|
+
* The zone every daily row is counted in: the owner's (forge task 3846).
|
|
233
|
+
*
|
|
234
|
+
* A site-wide daily count has to pick ONE zone — two viewers in two zones cannot both have
|
|
235
|
+
* their own midnight on the same row — and the person who reads these charts is the owner,
|
|
236
|
+
* in Central time. Until 2026-10-28 the rows were UTC days, which turn over at 7 pm Central,
|
|
237
|
+
* so every evening visit landed on tomorrow. Rows written before then stay UTC days: a
|
|
238
|
+
* `(user, place, day)` row holds no hours to re-bucket it by. The console labels the chart
|
|
239
|
+
* with this zone (station `views/metrics/EngagementPanel.tsx`).
|
|
240
|
+
*/
|
|
241
|
+
export const ENGAGEMENT_ZONE = "America/Chicago";
|
|
242
|
+
|
|
243
|
+
/** `2026-08-14` for a timestamp, on {@link ENGAGEMENT_ZONE}'s clock. The day bucket every row is keyed on. */
|
|
230
244
|
export function dayKey(ts: number): string {
|
|
231
|
-
return new Date(ts)
|
|
245
|
+
return formatDate(new Date(ts), "YYYY-MM-DD", ENGAGEMENT_ZONE);
|
|
232
246
|
}
|
|
233
247
|
|
|
234
248
|
/** How many whole days ago `ts` was, relative to `now`. */
|