@vellumai/assistant 0.10.0-dev.202606201839.e485b5f → 0.10.0-dev.202606202036.1fd8f36
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/openapi.yaml +5 -0
- package/package.json +1 -1
- package/scripts/memory-inspect.ts +24 -14
- package/src/__tests__/db-migration-rollback.test.ts +3 -3
- package/src/__tests__/llm-usage-store.test.ts +39 -0
- package/src/daemon/lifecycle.ts +1 -1
- package/src/memory/db-init.ts +2 -2
- package/src/memory/llm-usage-store.ts +31 -1
- package/src/memory/migrations/__tests__/run-migrations.test.ts +90 -17
- package/src/memory/migrations/run-migrations.ts +20 -5
- package/src/runtime/routes/usage-routes.ts +3 -0
package/openapi.yaml
CHANGED
|
@@ -27120,6 +27120,10 @@ paths:
|
|
|
27120
27120
|
type: number
|
|
27121
27121
|
eventCount:
|
|
27122
27122
|
type: number
|
|
27123
|
+
turnCount:
|
|
27124
|
+
anyOf:
|
|
27125
|
+
- type: number
|
|
27126
|
+
- type: "null"
|
|
27123
27127
|
required:
|
|
27124
27128
|
- group
|
|
27125
27129
|
- groupId
|
|
@@ -27129,6 +27133,7 @@ paths:
|
|
|
27129
27133
|
- totalCacheReadTokens
|
|
27130
27134
|
- totalEstimatedCostUsd
|
|
27131
27135
|
- eventCount
|
|
27136
|
+
- turnCount
|
|
27132
27137
|
additionalProperties: false
|
|
27133
27138
|
description: Grouped usage entries
|
|
27134
27139
|
required:
|
package/package.json
CHANGED
|
@@ -22,10 +22,13 @@ import {
|
|
|
22
22
|
queryNodes,
|
|
23
23
|
} from "../src/memory/graph/store.js";
|
|
24
24
|
import type { ScoredNode } from "../src/memory/graph/types.js";
|
|
25
|
-
import {
|
|
25
|
+
import {
|
|
26
|
+
initQdrantClient,
|
|
27
|
+
resolveQdrantUrl,
|
|
28
|
+
} from "../src/memory/qdrant-client.js";
|
|
26
29
|
|
|
27
30
|
// Initialize DB and Qdrant before anything else
|
|
28
|
-
initializeDb();
|
|
31
|
+
await initializeDb();
|
|
29
32
|
const config = getConfig();
|
|
30
33
|
try {
|
|
31
34
|
initQdrantClient({
|
|
@@ -83,7 +86,7 @@ async function main() {
|
|
|
83
86
|
} else if (args.includes("--narrative")) {
|
|
84
87
|
await runNarrative();
|
|
85
88
|
} else if (args.includes("--decay")) {
|
|
86
|
-
runDecay();
|
|
89
|
+
await runDecay();
|
|
87
90
|
} else {
|
|
88
91
|
console.log(`Memory Graph Inspector
|
|
89
92
|
|
|
@@ -211,7 +214,8 @@ async function showStats() {
|
|
|
211
214
|
}
|
|
212
215
|
|
|
213
216
|
async function showContextLoad() {
|
|
214
|
-
const { loadContextMemory } =
|
|
217
|
+
const { loadContextMemory } =
|
|
218
|
+
await import("../src/memory/graph/retriever.js");
|
|
215
219
|
|
|
216
220
|
console.log("\n Simulating context load (conversation start)...\n");
|
|
217
221
|
|
|
@@ -227,7 +231,8 @@ async function showContextLoad() {
|
|
|
227
231
|
console.log(` Triggered: ${result.triggeredNodes.length} triggers fired`);
|
|
228
232
|
|
|
229
233
|
// Show assembled context
|
|
230
|
-
const { assembleContextBlock } =
|
|
234
|
+
const { assembleContextBlock } =
|
|
235
|
+
await import("../src/memory/graph/injection.js");
|
|
231
236
|
const block = assembleContextBlock(result.nodes, {
|
|
232
237
|
serendipityNodes: result.serendipityNodes,
|
|
233
238
|
});
|
|
@@ -245,7 +250,8 @@ async function showContextLoad() {
|
|
|
245
250
|
|
|
246
251
|
async function showQuery(query: string) {
|
|
247
252
|
const { embedWithRetry } = await import("../src/memory/embed.js");
|
|
248
|
-
const { searchGraphNodes } =
|
|
253
|
+
const { searchGraphNodes } =
|
|
254
|
+
await import("../src/memory/graph/graph-search.js");
|
|
249
255
|
const { getNodesByIds } = await import("../src/memory/graph/store.js");
|
|
250
256
|
|
|
251
257
|
console.log(`\n Searching: "${query}"\n`);
|
|
@@ -369,7 +375,8 @@ function showNode(nodeId: string) {
|
|
|
369
375
|
async function showTurn(userMessage: string) {
|
|
370
376
|
const { retrieveForTurn } = await import("../src/memory/graph/retriever.js");
|
|
371
377
|
const { InContextTracker } = await import("../src/memory/graph/injection.js");
|
|
372
|
-
const { assembleInjectionBlock } =
|
|
378
|
+
const { assembleInjectionBlock } =
|
|
379
|
+
await import("../src/memory/graph/injection.js");
|
|
373
380
|
|
|
374
381
|
const tracker = new InContextTracker();
|
|
375
382
|
|
|
@@ -440,7 +447,8 @@ async function runBootstrap() {
|
|
|
440
447
|
}
|
|
441
448
|
|
|
442
449
|
async function runJournalBootstrap() {
|
|
443
|
-
const { bootstrapFromJournal } =
|
|
450
|
+
const { bootstrapFromJournal } =
|
|
451
|
+
await import("../src/memory/graph/bootstrap.js");
|
|
444
452
|
|
|
445
453
|
console.log("\n Extracting from journal files...\n");
|
|
446
454
|
const result = await bootstrapFromJournal();
|
|
@@ -450,7 +458,8 @@ async function runJournalBootstrap() {
|
|
|
450
458
|
}
|
|
451
459
|
|
|
452
460
|
async function runConsolidate() {
|
|
453
|
-
const { runConsolidation } =
|
|
461
|
+
const { runConsolidation } =
|
|
462
|
+
await import("../src/memory/graph/consolidation.js");
|
|
454
463
|
console.log("\n Running consolidation...\n");
|
|
455
464
|
const result = await runConsolidation("default", config);
|
|
456
465
|
console.log(
|
|
@@ -469,7 +478,8 @@ async function runConsolidate() {
|
|
|
469
478
|
}
|
|
470
479
|
|
|
471
480
|
async function runPatterns() {
|
|
472
|
-
const { runPatternScan } =
|
|
481
|
+
const { runPatternScan } =
|
|
482
|
+
await import("../src/memory/graph/pattern-scan.js");
|
|
473
483
|
console.log("\n Running pattern scan...\n");
|
|
474
484
|
const result = await runPatternScan("default", config);
|
|
475
485
|
console.log(
|
|
@@ -481,7 +491,8 @@ async function runPatterns() {
|
|
|
481
491
|
}
|
|
482
492
|
|
|
483
493
|
async function runNarrative() {
|
|
484
|
-
const { runNarrativeRefinement } =
|
|
494
|
+
const { runNarrativeRefinement } =
|
|
495
|
+
await import("../src/memory/graph/narrative.js");
|
|
485
496
|
console.log("\n Running narrative refinement...\n");
|
|
486
497
|
const result = await runNarrativeRefinement("default", config);
|
|
487
498
|
console.log(
|
|
@@ -500,9 +511,8 @@ async function runNarrative() {
|
|
|
500
511
|
console.log();
|
|
501
512
|
}
|
|
502
513
|
|
|
503
|
-
function runDecay() {
|
|
504
|
-
|
|
505
|
-
const { runDecayTick } = require("../src/memory/graph/decay.js") as typeof import("../src/memory/graph/decay.js");
|
|
514
|
+
async function runDecay() {
|
|
515
|
+
const { runDecayTick } = await import("../src/memory/graph/decay.js");
|
|
506
516
|
console.log("\n Running decay tick...\n");
|
|
507
517
|
const result = runDecayTick("default");
|
|
508
518
|
console.log(` Nodes processed: ${result.nodesProcessed}`);
|
|
@@ -1038,7 +1038,7 @@ describe("rollbackMemoryMigration", () => {
|
|
|
1038
1038
|
expect(cp1000!.value).toBe("1");
|
|
1039
1039
|
});
|
|
1040
1040
|
|
|
1041
|
-
test("clears forward-step checkpoints so a re-upgrade re-applies a rolled-back registry-backed step", () => {
|
|
1041
|
+
test("clears forward-step checkpoints so a re-upgrade re-applies a rolled-back registry-backed step", async () => {
|
|
1042
1042
|
/**
|
|
1043
1043
|
* A registry-backed migration that is also a named forward step is tracked
|
|
1044
1044
|
* in both the registry checkpoint (via withCrashRecovery) and the runner's
|
|
@@ -1083,7 +1083,7 @@ describe("rollbackMemoryMigration", () => {
|
|
|
1083
1083
|
});
|
|
1084
1084
|
|
|
1085
1085
|
// AND the step has run once through the runner, recording both checkpoints.
|
|
1086
|
-
runMigrationSteps(db, [migrateTestStepRollback]);
|
|
1086
|
+
await runMigrationSteps(db, [migrateTestStepRollback]);
|
|
1087
1087
|
expect(hasTable()).toBe(true);
|
|
1088
1088
|
expect(
|
|
1089
1089
|
raw
|
|
@@ -1098,7 +1098,7 @@ describe("rollbackMemoryMigration", () => {
|
|
|
1098
1098
|
expect(hasTable()).toBe(false);
|
|
1099
1099
|
|
|
1100
1100
|
// WHEN the runner executes the forward steps again on a later upgrade.
|
|
1101
|
-
runMigrationSteps(db, [migrateTestStepRollback]);
|
|
1101
|
+
await runMigrationSteps(db, [migrateTestStepRollback]);
|
|
1102
1102
|
|
|
1103
1103
|
// THEN the rolled-back step re-applies instead of being skipped.
|
|
1104
1104
|
expect(hasTable()).toBe(true);
|
|
@@ -1306,6 +1306,41 @@ describe("getUsageGroupBreakdown", () => {
|
|
|
1306
1306
|
expect(groups[0].totalOutputTokens).toBe(125);
|
|
1307
1307
|
expect(groups[0].totalEstimatedCostUsd).toBeCloseTo(0.05);
|
|
1308
1308
|
expect(groups[0].eventCount).toBe(2);
|
|
1309
|
+
// No user messages were inserted, so the conversation has zero turns.
|
|
1310
|
+
expect(groups[0].turnCount).toBe(0);
|
|
1311
|
+
});
|
|
1312
|
+
|
|
1313
|
+
test("counts conversation turns from eligible user messages when grouping by conversation", () => {
|
|
1314
|
+
const db = getDb();
|
|
1315
|
+
const conversationId = "conv-turns-1";
|
|
1316
|
+
const now = Date.now();
|
|
1317
|
+
db.run(
|
|
1318
|
+
`INSERT INTO conversations (id, title, created_at, updated_at) VALUES ('${conversationId}', 'Turn counting', ${now}, ${now})`,
|
|
1319
|
+
);
|
|
1320
|
+
// Two user turns; the second turn has two LLM calls, but the count comes
|
|
1321
|
+
// from the user messages (2), not the number of LLM calls (3).
|
|
1322
|
+
db.run(
|
|
1323
|
+
`INSERT INTO messages (id, conversation_id, role, content, created_at) VALUES ('u1', '${conversationId}', 'user', 'first', 500)`,
|
|
1324
|
+
);
|
|
1325
|
+
db.run(
|
|
1326
|
+
`INSERT INTO messages (id, conversation_id, role, content, created_at) VALUES ('u2', '${conversationId}', 'user', 'second', 2000)`,
|
|
1327
|
+
);
|
|
1328
|
+
// Tool-result user messages are not real turns and must be excluded.
|
|
1329
|
+
db.run(
|
|
1330
|
+
`INSERT INTO messages (id, conversation_id, role, content, created_at) VALUES ('tr1', '${conversationId}', 'user', '[{"type":"tool_result","tool_use_id":"x","content":""}]', 2100)`,
|
|
1331
|
+
);
|
|
1332
|
+
insertEventAt(1000, { conversationId, inputTokens: 100 });
|
|
1333
|
+
insertEventAt(2500, { conversationId, inputTokens: 100 });
|
|
1334
|
+
insertEventAt(2600, { conversationId, inputTokens: 100 });
|
|
1335
|
+
|
|
1336
|
+
const groups = getUsageGroupBreakdown(
|
|
1337
|
+
{ from: 0, to: 5000 },
|
|
1338
|
+
"conversation",
|
|
1339
|
+
);
|
|
1340
|
+
expect(groups).toHaveLength(1);
|
|
1341
|
+
expect(groups[0].groupId).toBe(conversationId);
|
|
1342
|
+
expect(groups[0].eventCount).toBe(3);
|
|
1343
|
+
expect(groups[0].turnCount).toBe(2);
|
|
1309
1344
|
});
|
|
1310
1345
|
|
|
1311
1346
|
test("returns groupId null for the Other bucket when grouping by conversation and events have no conversation id", () => {
|
|
@@ -1329,6 +1364,8 @@ describe("getUsageGroupBreakdown", () => {
|
|
|
1329
1364
|
expect(groups[0].groupId).toBeNull();
|
|
1330
1365
|
expect(groups[0].totalInputTokens).toBe(300);
|
|
1331
1366
|
expect(groups[0].eventCount).toBe(2);
|
|
1367
|
+
// The Other bucket has no parent conversation, so turns are undefined.
|
|
1368
|
+
expect(groups[0].turnCount).toBeNull();
|
|
1332
1369
|
});
|
|
1333
1370
|
|
|
1334
1371
|
test("returns groupId null for every row when grouping by a non-conversation dimension", () => {
|
|
@@ -1348,6 +1385,8 @@ describe("getUsageGroupBreakdown", () => {
|
|
|
1348
1385
|
expect(groups.length).toBeGreaterThan(0);
|
|
1349
1386
|
for (const row of groups) {
|
|
1350
1387
|
expect(row.groupId).toBeNull();
|
|
1388
|
+
// Turns are only computed for the conversation grouping.
|
|
1389
|
+
expect(row.turnCount).toBeNull();
|
|
1351
1390
|
}
|
|
1352
1391
|
});
|
|
1353
1392
|
});
|
package/src/daemon/lifecycle.ts
CHANGED
|
@@ -410,7 +410,7 @@ export async function runDaemon(): Promise<void> {
|
|
|
410
410
|
// remains reachable for health checks and diagnostics.
|
|
411
411
|
let dbReady = false;
|
|
412
412
|
try {
|
|
413
|
-
initializeDb();
|
|
413
|
+
await initializeDb();
|
|
414
414
|
dbReady = true;
|
|
415
415
|
log.info("Daemon startup: DB initialized");
|
|
416
416
|
} catch (err) {
|
package/src/memory/db-init.ts
CHANGED
|
@@ -332,7 +332,7 @@ function saveTemplate(): void {
|
|
|
332
332
|
|
|
333
333
|
// ---------------------------------------------------------------------------
|
|
334
334
|
|
|
335
|
-
export function initializeDb(): void {
|
|
335
|
+
export async function initializeDb(): Promise<void> {
|
|
336
336
|
if (process.env.BUN_TEST === "1" && tryRestoreTemplate()) {
|
|
337
337
|
return;
|
|
338
338
|
}
|
|
@@ -595,7 +595,7 @@ export function initializeDb(): void {
|
|
|
595
595
|
// broken migration doesn't prevent independent later ones from succeeding.
|
|
596
596
|
// The runner creates the checkpoint ledger, recovers crashed migrations, then
|
|
597
597
|
// records each step so an already-migrated database skips it on later boots.
|
|
598
|
-
const { failed, skipped } = runMigrationSteps(database, migrationSteps);
|
|
598
|
+
const { failed, skipped } = await runMigrationSteps(database, migrationSteps);
|
|
599
599
|
|
|
600
600
|
log.debug(
|
|
601
601
|
{
|
|
@@ -363,6 +363,14 @@ export interface UsageGroupBreakdown {
|
|
|
363
363
|
totalCacheReadTokens: number;
|
|
364
364
|
totalEstimatedCostUsd: number;
|
|
365
365
|
eventCount: number;
|
|
366
|
+
/**
|
|
367
|
+
* Number of turns in the conversation — the count of eligible user messages
|
|
368
|
+
* (tool-result turns excluded). Only populated when `groupBy ===
|
|
369
|
+
* "conversation"` (and `null` for that mode's "Other" bucket, which has no
|
|
370
|
+
* parent conversation). `null` for every other grouping, where a turn count
|
|
371
|
+
* has no well-defined meaning.
|
|
372
|
+
*/
|
|
373
|
+
turnCount: number | null;
|
|
366
374
|
}
|
|
367
375
|
|
|
368
376
|
// -- raw row shapes returned by SQLite aggregation queries --
|
|
@@ -388,6 +396,8 @@ interface GroupRow {
|
|
|
388
396
|
total_cache_read_tokens: number;
|
|
389
397
|
total_estimated_cost_usd: number | null;
|
|
390
398
|
event_count: number;
|
|
399
|
+
/** Only selected by the conversation grouping query; absent otherwise. */
|
|
400
|
+
turn_count?: number | null;
|
|
391
401
|
}
|
|
392
402
|
|
|
393
403
|
type UsageQueryParam = ScheduleAttributionSqlParam;
|
|
@@ -645,6 +655,9 @@ function mapGroupRow(
|
|
|
645
655
|
totalCacheReadTokens: row.total_cache_read_tokens,
|
|
646
656
|
totalEstimatedCostUsd: row.total_estimated_cost_usd ?? 0,
|
|
647
657
|
eventCount: row.event_count,
|
|
658
|
+
// Turns are only meaningful per conversation; other dimensions select no
|
|
659
|
+
// turn_count column, so this collapses to null.
|
|
660
|
+
turnCount: groupBy === "conversation" ? (row.turn_count ?? null) : null,
|
|
648
661
|
};
|
|
649
662
|
}
|
|
650
663
|
|
|
@@ -678,7 +691,24 @@ export function getUsageGroupBreakdown(
|
|
|
678
691
|
COALESCE(SUM(e.cache_creation_input_tokens), 0) AS total_cache_creation_tokens,
|
|
679
692
|
COALESCE(SUM(e.cache_read_input_tokens), 0) AS total_cache_read_tokens,
|
|
680
693
|
COALESCE(SUM(e.estimated_cost_usd), 0) AS total_estimated_cost_usd,
|
|
681
|
-
COALESCE(SUM(COALESCE(e.llm_call_count, 1)), 0) AS event_count
|
|
694
|
+
COALESCE(SUM(COALESCE(e.llm_call_count, 1)), 0) AS event_count,
|
|
695
|
+
-- Number of turns in the conversation: the count of eligible user
|
|
696
|
+
-- messages (tool-result turns excluded, mirroring the turnIndex
|
|
697
|
+
-- definition). Evaluated once per conversation group via the
|
|
698
|
+
-- idx_messages_conversation_id index rather than once per usage event,
|
|
699
|
+
-- so it stays cheap as call volume grows. NULL for the "Other" (no
|
|
700
|
+
-- conversation) bucket. Note: derived from surviving messages, so a
|
|
701
|
+
-- turn removed via Undo (deleteLastExchange) stops being counted even
|
|
702
|
+
-- though its billed usage still shows up in Cost/Tokens.
|
|
703
|
+
CASE WHEN e.conversation_id IS NULL THEN NULL
|
|
704
|
+
ELSE (
|
|
705
|
+
SELECT COUNT(*) FROM messages AS m2
|
|
706
|
+
WHERE m2.conversation_id = e.conversation_id
|
|
707
|
+
AND m2.role = 'user'
|
|
708
|
+
AND m2.content NOT LIKE '%"type":"tool\\_result"%' ESCAPE '\\'
|
|
709
|
+
AND m2.content NOT LIKE '%"type":"web\\_search\\_tool\\_result"%' ESCAPE '\\'
|
|
710
|
+
)
|
|
711
|
+
END AS turn_count
|
|
682
712
|
FROM llm_usage_events e
|
|
683
713
|
LEFT JOIN conversations c ON e.conversation_id = c.id
|
|
684
714
|
WHERE ${where.sql}
|
|
@@ -19,7 +19,7 @@ function createTestDb() {
|
|
|
19
19
|
}
|
|
20
20
|
|
|
21
21
|
describe("runMigrationSteps — checkpointing", () => {
|
|
22
|
-
test("does not re-execute a step that was already applied on a prior run", () => {
|
|
22
|
+
test("does not re-execute a step that was already applied on a prior run", async () => {
|
|
23
23
|
/**
|
|
24
24
|
* Booting an already-migrated database must not re-run forward migration
|
|
25
25
|
* steps. With true checkpointing each step's body executes at most once
|
|
@@ -43,16 +43,16 @@ describe("runMigrationSteps — checkpointing", () => {
|
|
|
43
43
|
|
|
44
44
|
// AND a database that has already been migrated once
|
|
45
45
|
const db = createTestDb();
|
|
46
|
-
runMigrationSteps(db, steps);
|
|
46
|
+
await runMigrationSteps(db, steps);
|
|
47
47
|
|
|
48
48
|
// WHEN the same steps run again against the already-migrated database
|
|
49
|
-
runMigrationSteps(db, steps);
|
|
49
|
+
await runMigrationSteps(db, steps);
|
|
50
50
|
|
|
51
51
|
// THEN no step body executes a second time
|
|
52
52
|
expect(calls).toEqual({ a: 1, b: 1, c: 1 });
|
|
53
53
|
});
|
|
54
54
|
|
|
55
|
-
test("records step completions in the shared memory_checkpoints ledger", () => {
|
|
55
|
+
test("records step completions in the shared memory_checkpoints ledger", async () => {
|
|
56
56
|
/**
|
|
57
57
|
* Step bookkeeping lives in the same memory_checkpoints table the registry
|
|
58
58
|
* uses, under the `step:` namespace — one ledger for all applied state.
|
|
@@ -60,7 +60,7 @@ describe("runMigrationSteps — checkpointing", () => {
|
|
|
60
60
|
|
|
61
61
|
// GIVEN a single named step
|
|
62
62
|
const db = createTestDb();
|
|
63
|
-
runMigrationSteps(db, [
|
|
63
|
+
await runMigrationSteps(db, [
|
|
64
64
|
function dummyMigrationA() {
|
|
65
65
|
// no-op
|
|
66
66
|
},
|
|
@@ -75,7 +75,7 @@ describe("runMigrationSteps — checkpointing", () => {
|
|
|
75
75
|
expect(row?.value).toBe("1");
|
|
76
76
|
});
|
|
77
77
|
|
|
78
|
-
test("runs a newly appended step on a later boot while skipping applied ones", () => {
|
|
78
|
+
test("runs a newly appended step on a later boot while skipping applied ones", async () => {
|
|
79
79
|
/**
|
|
80
80
|
* Checkpointing must not block migrations added in a later release: an
|
|
81
81
|
* already-applied step is skipped, but a brand-new step still runs.
|
|
@@ -90,7 +90,7 @@ describe("runMigrationSteps — checkpointing", () => {
|
|
|
90
90
|
calls.b++;
|
|
91
91
|
};
|
|
92
92
|
const db = createTestDb();
|
|
93
|
-
runMigrationSteps(db, [stepA, stepB]);
|
|
93
|
+
await runMigrationSteps(db, [stepA, stepB]);
|
|
94
94
|
|
|
95
95
|
// AND a third step appended to the list
|
|
96
96
|
const stepC: MigrationStep = function dummyMigrationC() {
|
|
@@ -98,13 +98,13 @@ describe("runMigrationSteps — checkpointing", () => {
|
|
|
98
98
|
};
|
|
99
99
|
|
|
100
100
|
// WHEN the expanded list runs against the already-migrated database
|
|
101
|
-
runMigrationSteps(db, [stepA, stepB, stepC]);
|
|
101
|
+
await runMigrationSteps(db, [stepA, stepB, stepC]);
|
|
102
102
|
|
|
103
103
|
// THEN only the newly appended step executes
|
|
104
104
|
expect(calls).toEqual({ a: 1, b: 1, c: 1 });
|
|
105
105
|
});
|
|
106
106
|
|
|
107
|
-
test("recovers crashed migrations before running steps", () => {
|
|
107
|
+
test("recovers crashed migrations before running steps", async () => {
|
|
108
108
|
/**
|
|
109
109
|
* runMigrationSteps clears stalled `started`/`rolling_back` checkpoints
|
|
110
110
|
* before the loop so a migration interrupted mid-flight re-runs this boot.
|
|
@@ -121,7 +121,7 @@ describe("runMigrationSteps — checkpointing", () => {
|
|
|
121
121
|
);
|
|
122
122
|
|
|
123
123
|
// WHEN the runner executes
|
|
124
|
-
runMigrationSteps(db, [
|
|
124
|
+
await runMigrationSteps(db, [
|
|
125
125
|
function dummyMigrationA() {
|
|
126
126
|
// no-op
|
|
127
127
|
},
|
|
@@ -136,7 +136,7 @@ describe("runMigrationSteps — checkpointing", () => {
|
|
|
136
136
|
expect(row).toBeNull();
|
|
137
137
|
});
|
|
138
138
|
|
|
139
|
-
test("does not checkpoint a failed step so it retries on the next boot", () => {
|
|
139
|
+
test("does not checkpoint a failed step so it retries on the next boot", async () => {
|
|
140
140
|
/**
|
|
141
141
|
* A step whose body throws is reported in `failed` and left uncheckpointed,
|
|
142
142
|
* so the next boot retries it instead of silently skipping it.
|
|
@@ -153,21 +153,21 @@ describe("runMigrationSteps — checkpointing", () => {
|
|
|
153
153
|
},
|
|
154
154
|
];
|
|
155
155
|
const db = createTestDb();
|
|
156
|
-
const first = runMigrationSteps(db, steps);
|
|
156
|
+
const first = await runMigrationSteps(db, steps);
|
|
157
157
|
|
|
158
158
|
// AND the first run reports the failure
|
|
159
159
|
expect(first.failed).toEqual(["flakyStep"]);
|
|
160
160
|
|
|
161
161
|
// WHEN the step runs again on the next boot
|
|
162
|
-
const second = runMigrationSteps(db, steps);
|
|
162
|
+
const second = await runMigrationSteps(db, steps);
|
|
163
163
|
|
|
164
164
|
// THEN it retries, succeeds, and is then checkpointed
|
|
165
165
|
expect(calls.flaky).toBe(2);
|
|
166
166
|
expect(second.failed).toEqual([]);
|
|
167
|
-
expect(runMigrationSteps(db, steps).skipped).toEqual(["flakyStep"]);
|
|
167
|
+
expect((await runMigrationSteps(db, steps)).skipped).toEqual(["flakyStep"]);
|
|
168
168
|
});
|
|
169
169
|
|
|
170
|
-
test("clearMigrationStepCheckpoints forces every step to re-run", () => {
|
|
170
|
+
test("clearMigrationStepCheckpoints forces every step to re-run", async () => {
|
|
171
171
|
/**
|
|
172
172
|
* Clearing the step namespace (as rollback does) makes the next run
|
|
173
173
|
* re-execute and re-record all steps.
|
|
@@ -181,14 +181,87 @@ describe("runMigrationSteps — checkpointing", () => {
|
|
|
181
181
|
},
|
|
182
182
|
];
|
|
183
183
|
const db = createTestDb();
|
|
184
|
-
runMigrationSteps(db, steps);
|
|
184
|
+
await runMigrationSteps(db, steps);
|
|
185
185
|
expect(calls.a).toBe(1);
|
|
186
186
|
|
|
187
187
|
// WHEN the step checkpoints are cleared
|
|
188
188
|
clearMigrationStepCheckpoints(db);
|
|
189
189
|
|
|
190
190
|
// THEN the next run re-executes the step
|
|
191
|
-
runMigrationSteps(db, steps);
|
|
191
|
+
await runMigrationSteps(db, steps);
|
|
192
192
|
expect(calls.a).toBe(2);
|
|
193
193
|
});
|
|
194
|
+
|
|
195
|
+
test("awaits an async step to completion before running or checkpointing the next", async () => {
|
|
196
|
+
/**
|
|
197
|
+
* An async step must be fully drained before the runner advances: ordering
|
|
198
|
+
* is the invariant later migrations rely on (step N+1 may assume N's result
|
|
199
|
+
* is true), and the step is checkpointed only after its promise resolves so
|
|
200
|
+
* a crash mid-drain leaves it uncheckpointed and retryable rather than
|
|
201
|
+
* recorded as done.
|
|
202
|
+
*/
|
|
203
|
+
|
|
204
|
+
// GIVEN an async step that records its completion order only after yielding,
|
|
205
|
+
// followed by a sync step that records when it starts
|
|
206
|
+
const order: string[] = [];
|
|
207
|
+
const steps: MigrationStep[] = [
|
|
208
|
+
async function asyncDrainStep() {
|
|
209
|
+
await Promise.resolve();
|
|
210
|
+
order.push("async-done");
|
|
211
|
+
},
|
|
212
|
+
function followingStep() {
|
|
213
|
+
order.push("following-start");
|
|
214
|
+
},
|
|
215
|
+
];
|
|
216
|
+
const db = createTestDb();
|
|
217
|
+
|
|
218
|
+
// WHEN the runner executes both steps
|
|
219
|
+
const result = await runMigrationSteps(db, steps);
|
|
220
|
+
|
|
221
|
+
// THEN the async step finishes before the next step starts
|
|
222
|
+
expect(order).toEqual(["async-done", "following-start"]);
|
|
223
|
+
|
|
224
|
+
// AND both steps are checkpointed, so a later boot skips them
|
|
225
|
+
expect(result.failed).toEqual([]);
|
|
226
|
+
expect((await runMigrationSteps(db, steps)).skipped).toEqual([
|
|
227
|
+
"asyncDrainStep",
|
|
228
|
+
"followingStep",
|
|
229
|
+
]);
|
|
230
|
+
});
|
|
231
|
+
|
|
232
|
+
test("a rejected async step is reported failed and left uncheckpointed", async () => {
|
|
233
|
+
/**
|
|
234
|
+
* A step whose promise rejects must be treated exactly like a synchronous
|
|
235
|
+
* throw: reported in `failed`, not checkpointed, and retried next boot.
|
|
236
|
+
*/
|
|
237
|
+
|
|
238
|
+
// GIVEN an async step that rejects on its first run and resolves afterwards
|
|
239
|
+
const calls = { flaky: 0 };
|
|
240
|
+
const steps: MigrationStep[] = [
|
|
241
|
+
async function flakyAsyncStep() {
|
|
242
|
+
calls.flaky++;
|
|
243
|
+
await Promise.resolve();
|
|
244
|
+
if (calls.flaky === 1) {
|
|
245
|
+
throw new Error("transient async failure");
|
|
246
|
+
}
|
|
247
|
+
},
|
|
248
|
+
];
|
|
249
|
+
const db = createTestDb();
|
|
250
|
+
|
|
251
|
+
// WHEN it runs and rejects
|
|
252
|
+
const first = await runMigrationSteps(db, steps);
|
|
253
|
+
|
|
254
|
+
// THEN the rejection is reported and the step is not checkpointed
|
|
255
|
+
expect(first.failed).toEqual(["flakyAsyncStep"]);
|
|
256
|
+
|
|
257
|
+
// WHEN it runs again on the next boot
|
|
258
|
+
const second = await runMigrationSteps(db, steps);
|
|
259
|
+
|
|
260
|
+
// THEN it retries, resolves, and is then checkpointed
|
|
261
|
+
expect(calls.flaky).toBe(2);
|
|
262
|
+
expect(second.failed).toEqual([]);
|
|
263
|
+
expect((await runMigrationSteps(db, steps)).skipped).toEqual([
|
|
264
|
+
"flakyAsyncStep",
|
|
265
|
+
]);
|
|
266
|
+
});
|
|
194
267
|
});
|
|
@@ -7,8 +7,16 @@ const log = getLogger("db-init");
|
|
|
7
7
|
/**
|
|
8
8
|
* A single forward migration step, identified for checkpointing and logging by
|
|
9
9
|
* its `.name`. Anonymous steps (empty `.name`) cannot be tracked and always run.
|
|
10
|
+
*
|
|
11
|
+
* A step may be synchronous or return a promise. The runner awaits an async
|
|
12
|
+
* step to completion before checkpointing it and moving on, so ordering is
|
|
13
|
+
* preserved exactly as for sync steps: step N+1 never starts — and is never
|
|
14
|
+
* skipped via checkpoint — until step N has fully finished. This lets a step
|
|
15
|
+
* that drains a large backfill in `await`ed batches run without blocking the
|
|
16
|
+
* thread between batches while still guaranteeing later migrations observe its
|
|
17
|
+
* completed result.
|
|
10
18
|
*/
|
|
11
|
-
export type MigrationStep = (database: DrizzleDb) => void
|
|
19
|
+
export type MigrationStep = (database: DrizzleDb) => void | Promise<void>;
|
|
12
20
|
|
|
13
21
|
export interface MigrationRunResult {
|
|
14
22
|
/** Steps whose body threw. */
|
|
@@ -103,7 +111,8 @@ export function recoverCrashedMigrations(database: DrizzleDb): string[] {
|
|
|
103
111
|
* Run the ordered list of forward migration steps against the database, each at
|
|
104
112
|
* most once across boots.
|
|
105
113
|
*
|
|
106
|
-
* A step's name is recorded in `memory_checkpoints` after its body completes
|
|
114
|
+
* A step's name is recorded in `memory_checkpoints` after its body completes —
|
|
115
|
+
* for an async step, after its returned promise resolves; on
|
|
107
116
|
* later boots an applied step is skipped instead of re-executed. This turns the
|
|
108
117
|
* unconditional ~200-step re-probe — which floors daemon startup at tens of
|
|
109
118
|
* seconds on a fully-migrated database — into a single bookkeeping read.
|
|
@@ -121,10 +130,10 @@ export function recoverCrashedMigrations(database: DrizzleDb): string[] {
|
|
|
121
130
|
* not prevent independent later ones from succeeding; a failed step is not
|
|
122
131
|
* checkpointed and is retried on the next boot.
|
|
123
132
|
*/
|
|
124
|
-
export function runMigrationSteps(
|
|
133
|
+
export async function runMigrationSteps(
|
|
125
134
|
database: DrizzleDb,
|
|
126
135
|
steps: MigrationStep[],
|
|
127
|
-
): MigrationRunResult {
|
|
136
|
+
): Promise<MigrationRunResult> {
|
|
128
137
|
const raw = getSqliteFrom(database);
|
|
129
138
|
|
|
130
139
|
ensureCheckpointsTable(raw);
|
|
@@ -158,7 +167,13 @@ export function runMigrationSteps(
|
|
|
158
167
|
|
|
159
168
|
try {
|
|
160
169
|
log.debug({ migration: name }, `Starting migration: ${name}`);
|
|
161
|
-
|
|
170
|
+
// Await only steps that actually return a promise, so a list of purely
|
|
171
|
+
// synchronous steps runs to completion without yielding the thread — and
|
|
172
|
+
// an async step is fully drained before it is checkpointed below.
|
|
173
|
+
const result = step(database);
|
|
174
|
+
if (result instanceof Promise) {
|
|
175
|
+
await result;
|
|
176
|
+
}
|
|
162
177
|
log.debug({ migration: name }, `Migration succeeded: ${name}`);
|
|
163
178
|
if (checkpointable) {
|
|
164
179
|
markApplied.run(`${STEP_CHECKPOINT_PREFIX}${name}`, Date.now());
|
|
@@ -65,6 +65,9 @@ const usageGroupBreakdownSchema = z.object({
|
|
|
65
65
|
totalCacheReadTokens: z.number(),
|
|
66
66
|
totalEstimatedCostUsd: z.number(),
|
|
67
67
|
eventCount: z.number(),
|
|
68
|
+
// Distinct conversation turns; populated only for the conversation grouping,
|
|
69
|
+
// null otherwise (and for the conversation "Other" bucket).
|
|
70
|
+
turnCount: z.number().nullable(),
|
|
68
71
|
});
|
|
69
72
|
|
|
70
73
|
const usageSeriesGroupValueSchema = z.object({
|