@vellumai/assistant 0.11.0-dev.202607290309.f1746d4 → 0.11.0-dev.202607290704.900b898
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/ARCHITECTURE.md +9 -5
- package/package.json +1 -1
- package/src/__tests__/add-message-skip-indexing.test.ts +3 -2
- package/src/__tests__/conversation-delete-schedule-cleanup.test.ts +3 -3
- package/src/__tests__/conversation-usage.test.ts +159 -0
- package/src/__tests__/image-recovery-hook.test.ts +3 -3
- package/src/__tests__/memory-upsert-concurrency.test.ts +19 -16
- package/src/__tests__/message-delete-segment-purge.test.ts +98 -0
- package/src/__tests__/persist-unsendable-image-downscale.test.ts +3 -3
- package/src/__tests__/persist-unsendable-image.test.ts +3 -3
- package/src/conversations/job-handlers/summarization.ts +6 -2
- package/src/daemon/conversation-usage.ts +82 -6
- package/src/persistence/conversation-crud.ts +234 -95
- package/src/persistence/job-handlers/cleanup.ts +7 -4
- package/src/persistence/job-utils.ts +22 -18
- package/src/persistence/migrations/340-sweep-orphaned-graph-node-vectors.test.ts +9 -0
- package/src/persistence/migrations/357-move-memory-segments-to-memory-db.ts +95 -0
- package/src/persistence/migrations/358-move-memory-embeddings-to-memory-db.ts +83 -0
- package/src/persistence/migrations/359-move-memory-summaries-to-memory-db.ts +86 -0
- package/src/persistence/steps.ts +56 -0
- package/src/plugins/defaults/memory/__tests__/capability-seed-embed-gate.test.ts +4 -4
- package/src/plugins/defaults/memory/__tests__/conversation-memory-purge.test.ts +1 -0
- package/src/plugins/defaults/memory/__tests__/conversation-row-batch-delete.test.ts +18 -34
- package/src/plugins/defaults/memory/__tests__/db-memory-attach.test.ts +3 -0
- package/src/plugins/defaults/memory/__tests__/embedding-cache.test.ts +10 -7
- package/src/plugins/defaults/memory/__tests__/indexer-tier-dispatch.test.ts +62 -2
- package/src/plugins/defaults/memory/__tests__/relocated-memory-test-rows.ts +16 -0
- package/src/plugins/defaults/memory/__tests__/table-relocation.test.ts +183 -0
- package/src/plugins/defaults/memory/conversation-memory-purge.ts +5 -0
- package/src/plugins/defaults/memory/graph/__tests__/conversation-graph-memory-recent-summaries.test.ts +142 -0
- package/src/plugins/defaults/memory/graph/conversation-graph-memory.ts +117 -45
- package/src/plugins/defaults/memory/indexer.ts +40 -3
- package/src/plugins/defaults/memory/jobs/__tests__/embed-concept-page.test.ts +2 -2
- package/src/plugins/defaults/memory/jobs/embed-concept-page.ts +20 -21
- package/src/plugins/defaults/memory/v1/graph/bootstrap.ts +3 -2
- package/src/plugins/defaults/memory/v1/job-handlers/embedding.ts +10 -3
- package/src/plugins/defaults/memory/v1/job-handlers/index-maintenance.ts +12 -12
- package/src/plugins/defaults/memory/v1/semantic-search.ts +6 -6
- package/src/plugins/defaults/memory/v3/__tests__/section-dense-store.test.ts +4 -0
- package/src/plugins/defaults/memory/v3/section-dense-store.ts +15 -13
package/ARCHITECTURE.md
CHANGED
|
@@ -820,14 +820,18 @@ graph LR
|
|
|
820
820
|
SL["logs/session-*.json<br/>───────────────<br/>Per-session JSON log<br/>task, start/end times, result<br/>Per-turn: AX tree, screenshot,<br/>action, token usage"]
|
|
821
821
|
end
|
|
822
822
|
|
|
823
|
+
subgraph "$VELLUM_WORKSPACE_DIR/data/db/assistant-memory.db (SQLite + WAL)"
|
|
824
|
+
direction TB
|
|
825
|
+
SEG["memory_segments<br/>───────────────<br/>Text chunks for retrieval<br/>Linked to messages<br/>token_estimate per segment"]
|
|
826
|
+
SUM["memory_summaries<br/>───────────────<br/>scope: conversation | weekly<br/>Compressed history for context<br/>window management"]
|
|
827
|
+
EMB["memory_embeddings<br/>───────────────<br/>target: segment | item | summary<br/>provider + model metadata<br/>vector_json (float array)<br/>Powers semantic search"]
|
|
828
|
+
end
|
|
829
|
+
|
|
823
830
|
subgraph "$VELLUM_WORKSPACE_DIR/data/db/assistant.db (SQLite + WAL)"
|
|
824
831
|
direction TB
|
|
825
832
|
CONV["conversations<br/>───────────────<br/>id, title, timestamps<br/>token counts, estimated cost<br/>context_summary (compaction)<br/>conversation_type: 'standard' | 'background' | 'scheduled'"]
|
|
826
833
|
MSG["messages<br/>───────────────<br/>id, conversation_id (FK)<br/>role: user | assistant<br/>content: JSON array<br/>created_at"]
|
|
827
834
|
TOOL["tool_invocations<br/>───────────────<br/>tool_name, input, result<br/>decision, risk_level<br/>duration_ms"]
|
|
828
|
-
SEG["memory_segments<br/>───────────────<br/>Text chunks for retrieval<br/>Linked to messages<br/>token_estimate per segment"]
|
|
829
|
-
SUM["memory_summaries<br/>───────────────<br/>scope: conversation | weekly<br/>Compressed history for context<br/>window management"]
|
|
830
|
-
EMB["memory_embeddings<br/>───────────────<br/>target: segment | item | summary<br/>provider + model metadata<br/>vector_json (float array)<br/>Powers semantic search"]
|
|
831
835
|
JOBS["memory_jobs<br/>───────────────<br/>Async task queue<br/>Types: embed, extract,<br/>summarize, backfill, cleanup<br/>Status: pending → running →<br/>completed | failed"]
|
|
832
836
|
ATT["attachments<br/>───────────────<br/>base64-encoded file data<br/>mime_type, size_bytes<br/>Linked to messages via<br/>message_attachments join"]
|
|
833
837
|
REM["reminders<br/>───────────────<br/>One-time scheduled reminders<br/>label, message, fireAt<br/>mode: notify | execute<br/>status: pending → fired | cancelled<br/>routing_intent: single_channel |<br/>multi_channel | all_channels<br/>routing_hints_json (free-form)"]
|
|
@@ -1967,9 +1971,9 @@ Connected channels are resolved at signal emission time: vellum is always includ
|
|
|
1967
1971
|
| User preferences | UserDefaults | plist | Foundation | Permanent |
|
|
1968
1972
|
| Session logs | `~/Library/.../logs/session-*.json` | JSON per session | Swift Codable | Unbounded |
|
|
1969
1973
|
| Conversations & messages | `$VELLUM_WORKSPACE_DIR/data/db/assistant.db` | SQLite + WAL | Drizzle ORM (Bun) | Permanent |
|
|
1970
|
-
| Memory segments | `$VELLUM_WORKSPACE_DIR/data/db/assistant.db`
|
|
1974
|
+
| Memory segments | `$VELLUM_WORKSPACE_DIR/data/db/assistant-memory.db` | SQLite | Drizzle ORM | Permanent |
|
|
1971
1975
|
| Extracted facts | `$VELLUM_WORKSPACE_DIR/data/db/assistant.db` | SQLite | Drizzle ORM | Permanent, deduped |
|
|
1972
|
-
| Embeddings | `$VELLUM_WORKSPACE_DIR/data/db/assistant.db`
|
|
1976
|
+
| Embeddings | `$VELLUM_WORKSPACE_DIR/data/db/assistant-memory.db` | JSON float arrays | Drizzle ORM | Permanent |
|
|
1973
1977
|
| Async job queue | `$VELLUM_WORKSPACE_DIR/data/db/assistant.db` | SQLite | Drizzle ORM | Completed jobs persist |
|
|
1974
1978
|
| Attachments | `$VELLUM_WORKSPACE_DIR/data/db/assistant.db` | Base64 in SQLite | Drizzle ORM | Permanent |
|
|
1975
1979
|
| Sandbox filesystem | `$VELLUM_WORKSPACE_DIR` | Real filesystem tree | Node FS APIs | Persistent across sessions |
|
package/package.json
CHANGED
|
@@ -56,7 +56,8 @@ const LONG_TEXT =
|
|
|
56
56
|
|
|
57
57
|
function resetTables(): void {
|
|
58
58
|
const db = getDb();
|
|
59
|
-
|
|
59
|
+
// memory_segments and memory_jobs live on the memory connection.
|
|
60
|
+
getMemoryDb()!.run("DELETE FROM memory_segments");
|
|
60
61
|
db.run("DELETE FROM messages");
|
|
61
62
|
db.run("DELETE FROM conversations");
|
|
62
63
|
getMemoryDb()!.run("DELETE FROM memory_jobs");
|
|
@@ -87,7 +88,7 @@ function messageRow(messageId: string) {
|
|
|
87
88
|
}
|
|
88
89
|
|
|
89
90
|
function segmentCountFor(messageId: string): number {
|
|
90
|
-
return
|
|
91
|
+
return getMemoryDb()!
|
|
91
92
|
.select()
|
|
92
93
|
.from(memorySegments)
|
|
93
94
|
.where(eq(memorySegments.messageId, messageId))
|
|
@@ -49,9 +49,9 @@ describe("DELETE /conversations/:id — schedule cleanup", () => {
|
|
|
49
49
|
getRawDb().run("DELETE FROM cron_runs");
|
|
50
50
|
getRawDb().run("DELETE FROM cron_jobs");
|
|
51
51
|
getMemorySqlite()!.run("DELETE FROM memory_graph_nodes");
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
52
|
+
getMemorySqlite()!.run("DELETE FROM memory_segments");
|
|
53
|
+
getMemorySqlite()!.run("DELETE FROM memory_summaries");
|
|
54
|
+
getMemorySqlite()!.run("DELETE FROM memory_embeddings");
|
|
55
55
|
getMemorySqlite()!.run("DELETE FROM memory_jobs");
|
|
56
56
|
getRawDb().run("DELETE FROM tool_invocations");
|
|
57
57
|
getLogsSqlite()!.run("DELETE FROM llm_request_logs");
|
|
@@ -7,6 +7,15 @@ const updateConversationUsageCalls: Array<{
|
|
|
7
7
|
estimatedCost: number;
|
|
8
8
|
}> = [];
|
|
9
9
|
|
|
10
|
+
let updateConversationUsageFailures = 0;
|
|
11
|
+
let updateConversationUsageFailureCode = "SQLITE_BUSY";
|
|
12
|
+
|
|
13
|
+
function sqliteError(code: string): Error {
|
|
14
|
+
const err = new Error("database is locked") as Error & { code: string };
|
|
15
|
+
err.code = code;
|
|
16
|
+
return err;
|
|
17
|
+
}
|
|
18
|
+
|
|
10
19
|
mock.module("../persistence/conversation-crud.js", () => ({
|
|
11
20
|
setConversationProcessingStartedAt: () => {},
|
|
12
21
|
isConversationProcessing: () => false,
|
|
@@ -16,6 +25,10 @@ mock.module("../persistence/conversation-crud.js", () => ({
|
|
|
16
25
|
outputTokens: number,
|
|
17
26
|
estimatedCost: number,
|
|
18
27
|
) => {
|
|
28
|
+
if (updateConversationUsageFailures > 0) {
|
|
29
|
+
updateConversationUsageFailures--;
|
|
30
|
+
throw sqliteError(updateConversationUsageFailureCode);
|
|
31
|
+
}
|
|
19
32
|
updateConversationUsageCalls.push({
|
|
20
33
|
conversationId,
|
|
21
34
|
inputTokens,
|
|
@@ -35,6 +48,7 @@ import { UsageTrackingProvider } from "../providers/usage-tracking.js";
|
|
|
35
48
|
import type { PricingUsage } from "../usage/types.js";
|
|
36
49
|
import { resolvePricingForUsageWithOverrides } from "../util/pricing.js";
|
|
37
50
|
import { setConfig } from "./helpers/set-config.js";
|
|
51
|
+
import { waitFor } from "./helpers/wait-for.js";
|
|
38
52
|
|
|
39
53
|
await initializeDb();
|
|
40
54
|
|
|
@@ -63,6 +77,8 @@ describe("recordUsage", () => {
|
|
|
63
77
|
const db = getDb();
|
|
64
78
|
db.run(`DELETE FROM llm_usage_events`);
|
|
65
79
|
updateConversationUsageCalls.length = 0;
|
|
80
|
+
updateConversationUsageFailures = 0;
|
|
81
|
+
updateConversationUsageFailureCode = "SQLITE_BUSY";
|
|
66
82
|
});
|
|
67
83
|
|
|
68
84
|
test("applies fast mode pricing when any response has speed: fast", () => {
|
|
@@ -424,6 +440,149 @@ describe("recordUsage", () => {
|
|
|
424
440
|
});
|
|
425
441
|
});
|
|
426
442
|
|
|
443
|
+
test("transient SQLITE_BUSY on the totals write never escapes and retries persist the totals", async () => {
|
|
444
|
+
const usageStats = { inputTokens: 0, outputTokens: 0, estimatedCost: 0 };
|
|
445
|
+
// Sync attempt fails, first background retry fails, second succeeds.
|
|
446
|
+
updateConversationUsageFailures = 2;
|
|
447
|
+
|
|
448
|
+
recordUsage(
|
|
449
|
+
{
|
|
450
|
+
conversationId: "conv-busy-1",
|
|
451
|
+
providerName: "openai",
|
|
452
|
+
usageStats,
|
|
453
|
+
},
|
|
454
|
+
100,
|
|
455
|
+
20,
|
|
456
|
+
"gpt-4o",
|
|
457
|
+
() => {},
|
|
458
|
+
"main_agent",
|
|
459
|
+
);
|
|
460
|
+
|
|
461
|
+
// The throwing write must not have escaped into the caller, and the
|
|
462
|
+
// in-memory accumulator must already reflect the event.
|
|
463
|
+
expect(usageStats.inputTokens).toBe(100);
|
|
464
|
+
expect(usageStats.outputTokens).toBe(20);
|
|
465
|
+
|
|
466
|
+
await waitFor(() => updateConversationUsageCalls.length === 1, {
|
|
467
|
+
timeoutMs: 3_000,
|
|
468
|
+
});
|
|
469
|
+
expect(updateConversationUsageCalls[0]).toMatchObject({
|
|
470
|
+
conversationId: "conv-busy-1",
|
|
471
|
+
inputTokens: 100,
|
|
472
|
+
outputTokens: 20,
|
|
473
|
+
});
|
|
474
|
+
});
|
|
475
|
+
|
|
476
|
+
test("exhausted retries are tolerated and the next usage event self-heals the totals", async () => {
|
|
477
|
+
const usageStats = { inputTokens: 0, outputTokens: 0, estimatedCost: 0 };
|
|
478
|
+
// More failures than the sync attempt (1) plus the retry chain's
|
|
479
|
+
// initial-plus-3-retries budget (4), so the first event's write is
|
|
480
|
+
// dropped entirely.
|
|
481
|
+
updateConversationUsageFailures = 100;
|
|
482
|
+
|
|
483
|
+
recordUsage(
|
|
484
|
+
{
|
|
485
|
+
conversationId: "conv-busy-2",
|
|
486
|
+
providerName: "openai",
|
|
487
|
+
usageStats,
|
|
488
|
+
},
|
|
489
|
+
100,
|
|
490
|
+
20,
|
|
491
|
+
"gpt-4o",
|
|
492
|
+
() => {},
|
|
493
|
+
"main_agent",
|
|
494
|
+
);
|
|
495
|
+
|
|
496
|
+
await waitFor(() => updateConversationUsageFailures === 95, {
|
|
497
|
+
timeoutMs: 3_000,
|
|
498
|
+
});
|
|
499
|
+
// Give the chain a beat to settle after its final failure.
|
|
500
|
+
await Bun.sleep(50);
|
|
501
|
+
expect(updateConversationUsageCalls).toHaveLength(0);
|
|
502
|
+
|
|
503
|
+
updateConversationUsageFailures = 0;
|
|
504
|
+
recordUsage(
|
|
505
|
+
{
|
|
506
|
+
conversationId: "conv-busy-2",
|
|
507
|
+
providerName: "openai",
|
|
508
|
+
usageStats,
|
|
509
|
+
},
|
|
510
|
+
50,
|
|
511
|
+
10,
|
|
512
|
+
"gpt-4o",
|
|
513
|
+
() => {},
|
|
514
|
+
"main_agent",
|
|
515
|
+
);
|
|
516
|
+
|
|
517
|
+
// The second event's write carries the cumulative totals, healing the
|
|
518
|
+
// dropped first write.
|
|
519
|
+
await waitFor(() => updateConversationUsageCalls.length === 1, {
|
|
520
|
+
timeoutMs: 3_000,
|
|
521
|
+
});
|
|
522
|
+
expect(updateConversationUsageCalls[0]).toMatchObject({
|
|
523
|
+
conversationId: "conv-busy-2",
|
|
524
|
+
inputTokens: 150,
|
|
525
|
+
outputTokens: 30,
|
|
526
|
+
});
|
|
527
|
+
});
|
|
528
|
+
|
|
529
|
+
test("a usage event landing mid-retry coalesces and stale totals never overwrite newer ones", async () => {
|
|
530
|
+
const usageStats = { inputTokens: 0, outputTokens: 0, estimatedCost: 0 };
|
|
531
|
+
// Sync attempt and the first two background attempts fail, leaving the
|
|
532
|
+
// chain alive in backoff while the second event lands.
|
|
533
|
+
updateConversationUsageFailures = 3;
|
|
534
|
+
|
|
535
|
+
const ctx = {
|
|
536
|
+
conversationId: "conv-busy-3",
|
|
537
|
+
providerName: "openai",
|
|
538
|
+
usageStats,
|
|
539
|
+
};
|
|
540
|
+
recordUsage(ctx, 100, 20, "gpt-4o", () => {}, "main_agent");
|
|
541
|
+
recordUsage(ctx, 50, 10, "gpt-4o", () => {}, "main_agent");
|
|
542
|
+
|
|
543
|
+
await waitFor(
|
|
544
|
+
() =>
|
|
545
|
+
updateConversationUsageCalls.some(
|
|
546
|
+
(call) => call.inputTokens === 150 && call.outputTokens === 30,
|
|
547
|
+
),
|
|
548
|
+
{ timeoutMs: 3_000 },
|
|
549
|
+
);
|
|
550
|
+
// Wait out any straggling coalesced write, then confirm nothing stale
|
|
551
|
+
// landed after the cumulative totals.
|
|
552
|
+
await Bun.sleep(300);
|
|
553
|
+
const last = updateConversationUsageCalls.at(-1);
|
|
554
|
+
expect(last).toMatchObject({
|
|
555
|
+
conversationId: "conv-busy-3",
|
|
556
|
+
inputTokens: 150,
|
|
557
|
+
outputTokens: 30,
|
|
558
|
+
});
|
|
559
|
+
});
|
|
560
|
+
|
|
561
|
+
test("a non-retryable write error is tolerated without retrying", async () => {
|
|
562
|
+
const usageStats = { inputTokens: 0, outputTokens: 0, estimatedCost: 0 };
|
|
563
|
+
updateConversationUsageFailures = 1;
|
|
564
|
+
updateConversationUsageFailureCode = "SQLITE_CORRUPT";
|
|
565
|
+
|
|
566
|
+
recordUsage(
|
|
567
|
+
{
|
|
568
|
+
conversationId: "conv-corrupt-1",
|
|
569
|
+
providerName: "openai",
|
|
570
|
+
usageStats,
|
|
571
|
+
},
|
|
572
|
+
100,
|
|
573
|
+
20,
|
|
574
|
+
"gpt-4o",
|
|
575
|
+
() => {},
|
|
576
|
+
"main_agent",
|
|
577
|
+
);
|
|
578
|
+
|
|
579
|
+
// No background chain: the failure budget is spent on the sync attempt
|
|
580
|
+
// and nothing retries afterwards.
|
|
581
|
+
await Bun.sleep(300);
|
|
582
|
+
expect(updateConversationUsageCalls).toHaveLength(0);
|
|
583
|
+
expect(usageStats.inputTokens).toBe(100);
|
|
584
|
+
});
|
|
585
|
+
|
|
427
586
|
test("NaN token counts never reach persistence and a poisoned total self-heals", () => {
|
|
428
587
|
const usageStats = {
|
|
429
588
|
inputTokens: Number.NaN,
|
|
@@ -27,7 +27,7 @@ import {
|
|
|
27
27
|
createConversation,
|
|
28
28
|
getMessages,
|
|
29
29
|
} from "../persistence/conversation-crud.js";
|
|
30
|
-
import { getDb } from "../persistence/db-connection.js";
|
|
30
|
+
import { getDb, getMemorySqlite } from "../persistence/db-connection.js";
|
|
31
31
|
import { initializeDb } from "../persistence/db-init.js";
|
|
32
32
|
import { HOOKS } from "../plugin-api/constants.js";
|
|
33
33
|
import type {
|
|
@@ -70,8 +70,8 @@ function resetTables(): void {
|
|
|
70
70
|
const db = getDb();
|
|
71
71
|
db.run("DELETE FROM message_attachments");
|
|
72
72
|
db.run("DELETE FROM attachments");
|
|
73
|
-
|
|
74
|
-
|
|
73
|
+
getMemorySqlite()?.run("DELETE FROM memory_segments");
|
|
74
|
+
getMemorySqlite()?.run("DELETE FROM memory_embeddings");
|
|
75
75
|
db.run("DELETE FROM messages");
|
|
76
76
|
db.run("DELETE FROM conversations");
|
|
77
77
|
}
|
|
@@ -32,7 +32,11 @@ mock.module("../persistence/embeddings/qdrant-client.js", () => ({
|
|
|
32
32
|
}));
|
|
33
33
|
|
|
34
34
|
import { getConfig } from "../config/loader.js";
|
|
35
|
-
import {
|
|
35
|
+
import {
|
|
36
|
+
getDb,
|
|
37
|
+
getMemoryDb,
|
|
38
|
+
getMemorySqlite,
|
|
39
|
+
} from "../persistence/db-connection.js";
|
|
36
40
|
import { initializeDb } from "../persistence/db-init.js";
|
|
37
41
|
import {
|
|
38
42
|
conversations,
|
|
@@ -51,10 +55,13 @@ await initializeDb();
|
|
|
51
55
|
|
|
52
56
|
function resetTables() {
|
|
53
57
|
const db = getDb();
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
+
// memory_embeddings and memory_segments live on the memory connection,
|
|
59
|
+
// alongside memory_graph_nodes and memory_jobs.
|
|
60
|
+
const memory = getMemorySqlite()!;
|
|
61
|
+
memory.run("DELETE FROM memory_embeddings");
|
|
62
|
+
memory.run("DELETE FROM memory_graph_nodes");
|
|
63
|
+
memory.run("DELETE FROM memory_segments");
|
|
64
|
+
memory.run("DELETE FROM memory_jobs");
|
|
58
65
|
db.run("DELETE FROM messages");
|
|
59
66
|
db.run("DELETE FROM conversations");
|
|
60
67
|
}
|
|
@@ -113,7 +120,6 @@ describe("segment UPSERT atomicity under repeated indexer invocations", () => {
|
|
|
113
120
|
|
|
114
121
|
seedConversationAndMessage(conversationId, messageId, text);
|
|
115
122
|
|
|
116
|
-
const db = getDb();
|
|
117
123
|
const config = getConfig().memory;
|
|
118
124
|
|
|
119
125
|
// Call indexMessageNow N times for the same messageId. Even though we use
|
|
@@ -138,7 +144,7 @@ describe("segment UPSERT atomicity under repeated indexer invocations", () => {
|
|
|
138
144
|
),
|
|
139
145
|
);
|
|
140
146
|
|
|
141
|
-
const segments =
|
|
147
|
+
const segments = getMemoryDb()!
|
|
142
148
|
.select()
|
|
143
149
|
.from(memorySegments)
|
|
144
150
|
.where(eq(memorySegments.messageId, messageId))
|
|
@@ -229,7 +235,7 @@ describe("segment UPSERT atomicity under repeated indexer invocations", () => {
|
|
|
229
235
|
// for the wrong messageId.
|
|
230
236
|
for (let i = 0; i < MSG_COUNT; i++) {
|
|
231
237
|
const msgId = `msg-distinct-${i}`;
|
|
232
|
-
const segs =
|
|
238
|
+
const segs = getMemoryDb()!
|
|
233
239
|
.select()
|
|
234
240
|
.from(memorySegments)
|
|
235
241
|
.where(eq(memorySegments.messageId, msgId))
|
|
@@ -271,8 +277,7 @@ describe("segment UPSERT atomicity under repeated indexer invocations", () => {
|
|
|
271
277
|
config,
|
|
272
278
|
);
|
|
273
279
|
|
|
274
|
-
const
|
|
275
|
-
const segmentsAfterFirst = db
|
|
280
|
+
const segmentsAfterFirst = getMemoryDb()!
|
|
276
281
|
.select()
|
|
277
282
|
.from(memorySegments)
|
|
278
283
|
.where(eq(memorySegments.messageId, messageId))
|
|
@@ -300,7 +305,7 @@ describe("segment UPSERT atomicity under repeated indexer invocations", () => {
|
|
|
300
305
|
config,
|
|
301
306
|
);
|
|
302
307
|
|
|
303
|
-
const segmentsAfterRehash =
|
|
308
|
+
const segmentsAfterRehash = getMemoryDb()!
|
|
304
309
|
.select()
|
|
305
310
|
.from(memorySegments)
|
|
306
311
|
.where(eq(memorySegments.messageId, messageId))
|
|
@@ -368,8 +373,7 @@ describe("segment UPSERT atomicity under repeated indexer invocations", () => {
|
|
|
368
373
|
),
|
|
369
374
|
]);
|
|
370
375
|
|
|
371
|
-
const
|
|
372
|
-
const segments = db
|
|
376
|
+
const segments = getMemoryDb()!
|
|
373
377
|
.select()
|
|
374
378
|
.from(memorySegments)
|
|
375
379
|
.where(eq(memorySegments.messageId, messageId))
|
|
@@ -467,7 +471,7 @@ describe("memory segment job atomicity under repeated indexer invocations", () =
|
|
|
467
471
|
// duplicates regardless of how many indexer calls ran.
|
|
468
472
|
for (let i = 0; i < MSG_COUNT; i++) {
|
|
469
473
|
const msgId = `msg-atomicity-${i}`;
|
|
470
|
-
const segs =
|
|
474
|
+
const segs = getMemoryDb()!
|
|
471
475
|
.select()
|
|
472
476
|
.from(memorySegments)
|
|
473
477
|
.where(eq(memorySegments.messageId, msgId))
|
|
@@ -514,8 +518,7 @@ describe("memory segment job atomicity under repeated indexer invocations", () =
|
|
|
514
518
|
),
|
|
515
519
|
);
|
|
516
520
|
|
|
517
|
-
const
|
|
518
|
-
const storedSegments = db
|
|
521
|
+
const storedSegments = getMemoryDb()!
|
|
519
522
|
.select()
|
|
520
523
|
.from(memorySegments)
|
|
521
524
|
.where(eq(memorySegments.messageId, messageId))
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Message-scoped segment/embedding purge. Deleting a single message (its
|
|
3
|
+
* conversation lives on) must remove that message's memory_segments and their
|
|
4
|
+
* embeddings on the memory connection, while a sibling message's rows survive.
|
|
5
|
+
* The conversation-keyed purge does not apply here, so this explicit delete is
|
|
6
|
+
* the sole cleanup for message-scoped rows. There is no orphan-sweep backstop.
|
|
7
|
+
*/
|
|
8
|
+
import { beforeEach, describe, expect, test } from "bun:test";
|
|
9
|
+
|
|
10
|
+
import { setConfig } from "./helpers/set-config.js";
|
|
11
|
+
|
|
12
|
+
// Disable memory so addMessage does not index into the real pipeline; the
|
|
13
|
+
// message-delete cleanup under test is not gated on the plugin being enabled.
|
|
14
|
+
setConfig("memory", { enabled: false, v2: { enabled: false } });
|
|
15
|
+
|
|
16
|
+
import {
|
|
17
|
+
addMessage,
|
|
18
|
+
createConversation,
|
|
19
|
+
deleteMessageById,
|
|
20
|
+
} from "../persistence/conversation-crud.js";
|
|
21
|
+
import { getMemorySqlite, getSqlite } from "../persistence/db-connection.js";
|
|
22
|
+
import { initializeDb } from "../persistence/db-init.js";
|
|
23
|
+
|
|
24
|
+
await initializeDb();
|
|
25
|
+
|
|
26
|
+
function seedSegment(
|
|
27
|
+
segmentId: string,
|
|
28
|
+
messageId: string,
|
|
29
|
+
conversationId: string,
|
|
30
|
+
): void {
|
|
31
|
+
const mem = getMemorySqlite()!;
|
|
32
|
+
mem.run(
|
|
33
|
+
`INSERT INTO memory_segments
|
|
34
|
+
(id, message_id, conversation_id, role, segment_index, text,
|
|
35
|
+
token_estimate, created_at, updated_at)
|
|
36
|
+
VALUES ('${segmentId}', '${messageId}', '${conversationId}', 'user', 0,
|
|
37
|
+
'text', 1, 0, 0)`,
|
|
38
|
+
);
|
|
39
|
+
mem.run(
|
|
40
|
+
`INSERT INTO memory_embeddings
|
|
41
|
+
(id, target_type, target_id, provider, model, dimensions,
|
|
42
|
+
created_at, updated_at)
|
|
43
|
+
VALUES ('emb-${segmentId}', 'segment', '${segmentId}', 'p', 'm', 3, 0, 0)`,
|
|
44
|
+
);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function memoryRows(table: string): string[] {
|
|
48
|
+
return (
|
|
49
|
+
getMemorySqlite()!
|
|
50
|
+
.query(`SELECT id FROM ${table} ORDER BY id`)
|
|
51
|
+
.all() as Array<{ id: string }>
|
|
52
|
+
).map((r) => r.id);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
beforeEach(() => {
|
|
56
|
+
const sqlite = getSqlite();
|
|
57
|
+
getMemorySqlite()!.run("DELETE FROM memory_embeddings");
|
|
58
|
+
getMemorySqlite()!.run("DELETE FROM memory_segments");
|
|
59
|
+
sqlite.run("DELETE FROM messages");
|
|
60
|
+
sqlite.run("DELETE FROM conversations");
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
describe("deleteMessageById segment purge", () => {
|
|
64
|
+
test("purges the deleted message's segments and embeddings, leaving a sibling's intact", async () => {
|
|
65
|
+
const conv = createConversation("conv");
|
|
66
|
+
const msgA = await addMessage(conv.id, "user", "a", { skipIndexing: true });
|
|
67
|
+
const msgB = await addMessage(conv.id, "user", "b", { skipIndexing: true });
|
|
68
|
+
seedSegment("seg-a", msgA.id, conv.id);
|
|
69
|
+
seedSegment("seg-b", msgB.id, conv.id);
|
|
70
|
+
|
|
71
|
+
const result = deleteMessageById(msgA.id);
|
|
72
|
+
|
|
73
|
+
// The deleted message's ids are returned for the caller's Qdrant purge.
|
|
74
|
+
expect(result.segmentIds).toEqual(["seg-a"]);
|
|
75
|
+
// Its segment and embedding are gone; the sibling message's survive.
|
|
76
|
+
expect(memoryRows("memory_segments")).toEqual(["seg-b"]);
|
|
77
|
+
expect(memoryRows("memory_embeddings")).toEqual(["emb-seg-b"]);
|
|
78
|
+
// The conversation and the sibling message live on.
|
|
79
|
+
expect(
|
|
80
|
+
getSqlite().query("SELECT COUNT(*) AS c FROM conversations").get(),
|
|
81
|
+
).toEqual({ c: 1 });
|
|
82
|
+
expect(getSqlite().query("SELECT id FROM messages").all()).toEqual([
|
|
83
|
+
{ id: msgB.id },
|
|
84
|
+
]);
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
test("returns no ids and no-ops when the message has no segments", async () => {
|
|
88
|
+
const conv = createConversation("conv");
|
|
89
|
+
const msg = await addMessage(conv.id, "user", "no segments", {
|
|
90
|
+
skipIndexing: true,
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
const result = deleteMessageById(msg.id);
|
|
94
|
+
|
|
95
|
+
expect(result.segmentIds).toEqual([]);
|
|
96
|
+
expect(memoryRows("memory_segments")).toEqual([]);
|
|
97
|
+
});
|
|
98
|
+
});
|
|
@@ -40,7 +40,7 @@ import {
|
|
|
40
40
|
createConversation,
|
|
41
41
|
getMessages,
|
|
42
42
|
} from "../persistence/conversation-crud.js";
|
|
43
|
-
import { getDb } from "../persistence/db-connection.js";
|
|
43
|
+
import { getDb, getMemorySqlite } from "../persistence/db-connection.js";
|
|
44
44
|
import { initializeDb } from "../persistence/db-init.js";
|
|
45
45
|
import { persistUnsendableImageDowngrades } from "../plugins/defaults/image-recovery/recover.js";
|
|
46
46
|
import { base64Source } from "../providers/media-resolve.js";
|
|
@@ -52,8 +52,8 @@ function resetTables(): void {
|
|
|
52
52
|
const db = getDb();
|
|
53
53
|
db.run("DELETE FROM message_attachments");
|
|
54
54
|
db.run("DELETE FROM attachments");
|
|
55
|
-
|
|
56
|
-
|
|
55
|
+
getMemorySqlite()?.run("DELETE FROM memory_segments");
|
|
56
|
+
getMemorySqlite()?.run("DELETE FROM memory_embeddings");
|
|
57
57
|
db.run("DELETE FROM messages");
|
|
58
58
|
db.run("DELETE FROM conversations");
|
|
59
59
|
}
|
|
@@ -20,7 +20,7 @@ import {
|
|
|
20
20
|
createConversation,
|
|
21
21
|
getMessages,
|
|
22
22
|
} from "../persistence/conversation-crud.js";
|
|
23
|
-
import { getDb } from "../persistence/db-connection.js";
|
|
23
|
+
import { getDb, getMemorySqlite } from "../persistence/db-connection.js";
|
|
24
24
|
import { initializeDb } from "../persistence/db-init.js";
|
|
25
25
|
import {
|
|
26
26
|
persistUnsendableImageDowngrades,
|
|
@@ -34,8 +34,8 @@ function resetTables(): void {
|
|
|
34
34
|
const db = getDb();
|
|
35
35
|
db.run("DELETE FROM message_attachments");
|
|
36
36
|
db.run("DELETE FROM attachments");
|
|
37
|
-
|
|
38
|
-
|
|
37
|
+
getMemorySqlite()?.run("DELETE FROM memory_segments");
|
|
38
|
+
getMemorySqlite()?.run("DELETE FROM memory_embeddings");
|
|
39
39
|
db.run("DELETE FROM messages");
|
|
40
40
|
db.run("DELETE FROM conversations");
|
|
41
41
|
}
|
|
@@ -3,7 +3,7 @@ import { v4 as uuid } from "uuid";
|
|
|
3
3
|
|
|
4
4
|
import type { AssistantConfig } from "../../config/types.js";
|
|
5
5
|
import { estimateTextTokens } from "../../context/token-estimator.js";
|
|
6
|
-
import {
|
|
6
|
+
import { getMemoryDb } from "../../persistence/db-connection.js";
|
|
7
7
|
import { asString, truncate } from "../../persistence/job-utils.js";
|
|
8
8
|
import {
|
|
9
9
|
enqueueMemoryJob,
|
|
@@ -53,7 +53,10 @@ export async function buildConversationSummaryJob(
|
|
|
53
53
|
if (!conversationId) {
|
|
54
54
|
return;
|
|
55
55
|
}
|
|
56
|
-
const db =
|
|
56
|
+
const db = getMemoryDb();
|
|
57
|
+
if (!db) {
|
|
58
|
+
return;
|
|
59
|
+
}
|
|
57
60
|
|
|
58
61
|
const existing = db
|
|
59
62
|
.select()
|
|
@@ -77,6 +80,7 @@ export async function buildConversationSummaryJob(
|
|
|
77
80
|
conditions.push(gt(memorySegments.createdAt, lastCoveredAt));
|
|
78
81
|
}
|
|
79
82
|
|
|
83
|
+
// memory_segments and memory_summaries both live on the memory connection.
|
|
80
84
|
const rows = db
|
|
81
85
|
.select()
|
|
82
86
|
.from(memorySegments)
|
|
@@ -17,6 +17,10 @@ import {
|
|
|
17
17
|
resolvePricingForUsageWithOverrides,
|
|
18
18
|
usesAnthropicPricingRules,
|
|
19
19
|
} from "../util/pricing.js";
|
|
20
|
+
import {
|
|
21
|
+
isRetryableSqliteError,
|
|
22
|
+
withSqliteRetry,
|
|
23
|
+
} from "../util/sqlite-retry.js";
|
|
20
24
|
import type { UsageStats } from "./message-protocol.js";
|
|
21
25
|
|
|
22
26
|
const log = getLogger("conversation-usage");
|
|
@@ -166,6 +170,83 @@ function resolveAttribution(
|
|
|
166
170
|
: resolveUsageAttribution(attribution);
|
|
167
171
|
}
|
|
168
172
|
|
|
173
|
+
interface PendingUsageWrite {
|
|
174
|
+
/** Most recent context for this conversation; every attempt persists it. */
|
|
175
|
+
latest: UsageContext;
|
|
176
|
+
/** A usage event arrived while the chain was draining; one trailing write owed. */
|
|
177
|
+
dirty: boolean;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
const pendingUsageWrites = new Map<string, PendingUsageWrite>();
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* Persist the conversation row's cumulative usage totals, tolerating SQLite
|
|
184
|
+
* write contention. Usage accounting is post-turn bookkeeping — a concurrent
|
|
185
|
+
* bulk writer (e.g. a retrospective fork copy) holding the write lock past
|
|
186
|
+
* `busy_timeout` must never surface as a failed turn, so no error escapes.
|
|
187
|
+
*
|
|
188
|
+
* The first attempt runs synchronously (the common, uncontended path). On a
|
|
189
|
+
* transient `SQLITE_BUSY`/`SQLITE_IOERR` it falls back to a background
|
|
190
|
+
* {@link withSqliteRetry} chain, single-flight per conversation: events that
|
|
191
|
+
* land mid-chain coalesce into one trailing write instead of racing it, so a
|
|
192
|
+
* delayed retry can never overwrite newer totals with older ones. Totals are
|
|
193
|
+
* absolute values read from the live {@link UsageStats} accumulator at
|
|
194
|
+
* statement time, which makes coalescing lossless and a fully dropped write
|
|
195
|
+
* self-healing on the next usage event.
|
|
196
|
+
*/
|
|
197
|
+
function persistUsageTotals(ctx: UsageContext): void {
|
|
198
|
+
const pending = pendingUsageWrites.get(ctx.conversationId);
|
|
199
|
+
if (pending) {
|
|
200
|
+
pending.latest = ctx;
|
|
201
|
+
pending.dirty = true;
|
|
202
|
+
return;
|
|
203
|
+
}
|
|
204
|
+
try {
|
|
205
|
+
writeUsageTotals(ctx);
|
|
206
|
+
return;
|
|
207
|
+
} catch (err) {
|
|
208
|
+
if (!isRetryableSqliteError(err)) {
|
|
209
|
+
log.warn(
|
|
210
|
+
{ err, conversationId: ctx.conversationId },
|
|
211
|
+
"Failed to persist conversation usage totals (non-fatal)",
|
|
212
|
+
);
|
|
213
|
+
return;
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
const entry: PendingUsageWrite = { latest: ctx, dirty: false };
|
|
217
|
+
pendingUsageWrites.set(ctx.conversationId, entry);
|
|
218
|
+
void retryUsageWrite(entry);
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
function writeUsageTotals(target: UsageContext): void {
|
|
222
|
+
updateConversationUsage(
|
|
223
|
+
target.conversationId,
|
|
224
|
+
target.usageStats.inputTokens,
|
|
225
|
+
target.usageStats.outputTokens,
|
|
226
|
+
target.usageStats.estimatedCost,
|
|
227
|
+
);
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
async function retryUsageWrite(entry: PendingUsageWrite): Promise<void> {
|
|
231
|
+
const conversationId = entry.latest.conversationId;
|
|
232
|
+
try {
|
|
233
|
+
await withSqliteRetry(() => writeUsageTotals(entry.latest), {
|
|
234
|
+
op: "conversation:updateUsage",
|
|
235
|
+
context: { conversationId },
|
|
236
|
+
});
|
|
237
|
+
} catch (err) {
|
|
238
|
+
log.warn(
|
|
239
|
+
{ err, conversationId },
|
|
240
|
+
"Failed to persist conversation usage totals after retries; totals self-heal on the next usage event (non-fatal)",
|
|
241
|
+
);
|
|
242
|
+
} finally {
|
|
243
|
+
pendingUsageWrites.delete(conversationId);
|
|
244
|
+
if (entry.dirty) {
|
|
245
|
+
persistUsageTotals(entry.latest);
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
|
|
169
250
|
export function recordUsage(
|
|
170
251
|
ctx: UsageContext,
|
|
171
252
|
inputTokens: number,
|
|
@@ -233,12 +314,7 @@ export function recordUsage(
|
|
|
233
314
|
? ctx.usageStats.estimatedCost
|
|
234
315
|
: 0) + estimatedCost;
|
|
235
316
|
|
|
236
|
-
|
|
237
|
-
ctx.conversationId,
|
|
238
|
-
ctx.usageStats.inputTokens,
|
|
239
|
-
ctx.usageStats.outputTokens,
|
|
240
|
-
ctx.usageStats.estimatedCost,
|
|
241
|
-
);
|
|
317
|
+
persistUsageTotals(ctx);
|
|
242
318
|
onEvent({
|
|
243
319
|
type: "usage_update",
|
|
244
320
|
conversationId: ctx.conversationId,
|