@vellumai/assistant 0.10.12-dev.202607251930.d09ff97 → 0.10.12-dev.202607252122.6e65db7
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/package.json +1 -1
- package/src/cli/commands/memory/memory-retrospective.ts +5 -0
- package/src/config/schemas/memory-retrospective.ts +13 -0
- package/src/persistence/jobs-store.ts +27 -0
- package/src/plugins/defaults/memory/__tests__/memory-retrospective-job.test.ts +31 -0
- package/src/plugins/defaults/memory/__tests__/memory-retrospective-sweep.test.ts +150 -9
- package/src/plugins/defaults/memory/memory-retrospective-job.ts +38 -1
- package/src/plugins/defaults/memory/memory-retrospective-sweep.ts +98 -10
package/package.json
CHANGED
|
@@ -135,6 +135,11 @@ function renderOutcome(outcome: MemoryRetrospectiveOutcome): void {
|
|
|
135
135
|
case "no_new_messages":
|
|
136
136
|
log.info("No new messages to review since the last retrospective.");
|
|
137
137
|
break;
|
|
138
|
+
case "source_dormant":
|
|
139
|
+
log.info(
|
|
140
|
+
"Source conversation is dormant beyond the sweep lookback; skipping.",
|
|
141
|
+
);
|
|
142
|
+
break;
|
|
138
143
|
case "source_processing":
|
|
139
144
|
log.info(
|
|
140
145
|
"Source conversation is mid-turn; skipping (will retry next trigger).",
|
|
@@ -52,6 +52,19 @@ export const MemoryRetrospectiveConfigSchema = z
|
|
|
52
52
|
"Cadence of the scheduled retrospective sweep, the timer-driven backstop that re-scans conversations for unprocessed messages the event-driven triggers missed (e.g. a turn that ended in a crash or IPC drop before the post-turn hooks ran). A conversation is only swept when its last retrospective attempt is at least this old, so the sweep never competes with the responsive interval/message_count triggers on active conversations.",
|
|
53
53
|
),
|
|
54
54
|
|
|
55
|
+
sweepLookbackMs: z
|
|
56
|
+
.number({
|
|
57
|
+
error: "memory.retrospective.sweepLookbackMs must be a number",
|
|
58
|
+
})
|
|
59
|
+
.int("memory.retrospective.sweepLookbackMs must be an integer")
|
|
60
|
+
.positive(
|
|
61
|
+
"memory.retrospective.sweepLookbackMs must be a positive integer",
|
|
62
|
+
)
|
|
63
|
+
.default(7 * 24 * 60 * 60 * 1000)
|
|
64
|
+
.describe(
|
|
65
|
+
"How far back the scheduled retrospective sweep looks for stalled work. The sweep backstops turns that ended abnormally (crash / IPC drop), and such turns are by definition recent — so only conversations whose last message falls inside this window are scanned, and the retrospective job re-applies the same window at execution time so a stale queued backlog is skipped instead of run. Conversations dormant beyond the window are outside the sweep's scope entirely: their unprocessed tails are ordinary end-of-conversation remainders, not stalled work. Values below twice memory.retrospective.sweepIntervalMs are clamped up to that floor — scheduler and queue delay stretch the gap between consecutive scans past the nominal cadence, so a window at or under one interval would leave a permanent blind span between passes.",
|
|
66
|
+
),
|
|
67
|
+
|
|
55
68
|
keepSupersededRuns: z
|
|
56
69
|
.boolean({
|
|
57
70
|
error: "memory.retrospective.keepSupersededRuns must be a boolean",
|
|
@@ -374,6 +374,33 @@ function mergeSkillCardEntries(
|
|
|
374
374
|
return merged;
|
|
375
375
|
}
|
|
376
376
|
|
|
377
|
+
/**
|
|
378
|
+
* Source-conversation ids of every PENDING `memory_retrospective` job. The
|
|
379
|
+
* retrospective sweep skips these up front: a pending row already covers the
|
|
380
|
+
* source's unprocessed span, and a coalescing upsert against it must not
|
|
381
|
+
* consume the sweep's per-pass enqueue cap. Deliberately excludes `running`
|
|
382
|
+
* rows — a running job's fork and cursor are pre-run snapshots, so messages
|
|
383
|
+
* arriving mid-run need a follow-up row behind it, and the sweep must be able
|
|
384
|
+
* to create that follow-up. Mirrors `upsertMemoryRetrospectiveJob`'s
|
|
385
|
+
* pending-only coalescing.
|
|
386
|
+
*/
|
|
387
|
+
export function listPendingMemoryRetrospectiveSourceConversationIds(): string[] {
|
|
388
|
+
return memoryDb()
|
|
389
|
+
.select({
|
|
390
|
+
conversationId: sql<string>`json_extract(${memoryJobs.payload}, '$.conversationId')`,
|
|
391
|
+
})
|
|
392
|
+
.from(memoryJobs)
|
|
393
|
+
.where(
|
|
394
|
+
and(
|
|
395
|
+
eq(memoryJobs.type, "memory_retrospective"),
|
|
396
|
+
eq(memoryJobs.status, "pending"),
|
|
397
|
+
),
|
|
398
|
+
)
|
|
399
|
+
.all()
|
|
400
|
+
.map((row) => row.conversationId)
|
|
401
|
+
.filter((id): id is string => typeof id === "string" && id.length > 0);
|
|
402
|
+
}
|
|
403
|
+
|
|
377
404
|
/**
|
|
378
405
|
* Check whether a pending or running job of the given type already exists.
|
|
379
406
|
* Used to prevent duplicate enqueues for long-running maintenance jobs.
|
|
@@ -78,6 +78,7 @@ type ConversationStub = {
|
|
|
78
78
|
inferenceProfileExpiresAt?: number | null;
|
|
79
79
|
originChannel?: string | null;
|
|
80
80
|
originInterface?: string | null;
|
|
81
|
+
lastMessageAt?: number | null;
|
|
81
82
|
};
|
|
82
83
|
let conversationOverrides: Record<string, ConversationStub> = {};
|
|
83
84
|
|
|
@@ -342,6 +343,8 @@ function makeConfig(
|
|
|
342
343
|
keepSupersededRuns: overrides.keepSupersededRuns ?? false,
|
|
343
344
|
matchConversationProfile: overrides.matchConversationProfile ?? false,
|
|
344
345
|
promptPath: overrides.promptPath ?? null,
|
|
346
|
+
sweepIntervalMs: 8 * 60 * 60 * 1000,
|
|
347
|
+
sweepLookbackMs: 7 * 24 * 60 * 60 * 1000,
|
|
345
348
|
},
|
|
346
349
|
},
|
|
347
350
|
ui: {
|
|
@@ -448,6 +451,34 @@ describe("memoryRetrospectiveJob", () => {
|
|
|
448
451
|
expect(forkCalls[0]!.conversationId).toBe("src-conv-1");
|
|
449
452
|
});
|
|
450
453
|
|
|
454
|
+
test("dormant source beyond the sweep lookback: completed as a no-op, both pointers untouched", async () => {
|
|
455
|
+
conversationOverrides["src-conv-1"] = {
|
|
456
|
+
source: "user",
|
|
457
|
+
forkParentMessageId: null,
|
|
458
|
+
lastMessageAt: Date.now() - 8 * 24 * 60 * 60 * 1000,
|
|
459
|
+
};
|
|
460
|
+
|
|
461
|
+
const outcome = await memoryRetrospectiveJob(makeJob(), stubConfig);
|
|
462
|
+
|
|
463
|
+
expect(outcome.kind).toBe("source_dormant");
|
|
464
|
+
expect(stateUpserts).toHaveLength(0);
|
|
465
|
+
expect(lastRunAtBumps).toHaveLength(0);
|
|
466
|
+
expect(wakeCalls).toHaveLength(0);
|
|
467
|
+
expect(forkCalls).toHaveLength(0);
|
|
468
|
+
});
|
|
469
|
+
|
|
470
|
+
test("recent source inside the sweep lookback runs normally", async () => {
|
|
471
|
+
conversationOverrides["src-conv-1"] = {
|
|
472
|
+
source: "user",
|
|
473
|
+
forkParentMessageId: null,
|
|
474
|
+
lastMessageAt: Date.now() - 60_000,
|
|
475
|
+
};
|
|
476
|
+
|
|
477
|
+
const outcome = await memoryRetrospectiveJob(makeJob(), stubConfig);
|
|
478
|
+
|
|
479
|
+
expect(outcome.kind).toBe("invoked");
|
|
480
|
+
});
|
|
481
|
+
|
|
451
482
|
test("no-new-messages early return: neither field changes, no wake, no fork", async () => {
|
|
452
483
|
newMessages = [];
|
|
453
484
|
const outcome = await memoryRetrospectiveJob(makeJob(), stubConfig);
|
|
@@ -13,6 +13,8 @@ mock.module("../memory-retrospective-enqueue.js", () => ({
|
|
|
13
13
|
},
|
|
14
14
|
}));
|
|
15
15
|
|
|
16
|
+
import { eq } from "drizzle-orm";
|
|
17
|
+
|
|
16
18
|
import type { AssistantConfig } from "../../../../config/types.js";
|
|
17
19
|
import { AUTO_ANALYSIS_SOURCE } from "../../../../persistence/auto-analysis-constants.js";
|
|
18
20
|
import { createConversation } from "../../../../persistence/conversation-crud.js";
|
|
@@ -21,7 +23,11 @@ import {
|
|
|
21
23
|
getMemorySqlite,
|
|
22
24
|
} from "../../../../persistence/db-connection.js";
|
|
23
25
|
import { initializeDb } from "../../../../persistence/db-init.js";
|
|
24
|
-
import {
|
|
26
|
+
import { upsertMemoryRetrospectiveJob } from "../../../../persistence/jobs-store.js";
|
|
27
|
+
import {
|
|
28
|
+
conversations,
|
|
29
|
+
messages,
|
|
30
|
+
} from "../../../../persistence/schema/index.js";
|
|
25
31
|
import {
|
|
26
32
|
MEMORY_RETROSPECTIVE_SOURCE,
|
|
27
33
|
SKILL_CARD_MESSAGE_KIND,
|
|
@@ -30,23 +36,37 @@ import { upsertRetrospectiveState } from "../memory-retrospective-state.js";
|
|
|
30
36
|
import {
|
|
31
37
|
listSweepCandidateConversationIds,
|
|
32
38
|
runRetrospectiveSweep,
|
|
39
|
+
SWEEP_MAX_ENQUEUES_PER_PASS,
|
|
33
40
|
} from "../memory-retrospective-sweep.js";
|
|
34
41
|
import { MEMORY_V2_CONSOLIDATION_SOURCE } from "../v3/substrate/constants.js";
|
|
35
42
|
|
|
36
43
|
await initializeDb();
|
|
37
44
|
|
|
38
45
|
const SWEEP_INTERVAL_MS = 8 * 60 * 60 * 1000; // 8h
|
|
46
|
+
const SWEEP_LOOKBACK_MS = 7 * 24 * 60 * 60 * 1000; // 7d
|
|
39
47
|
|
|
40
|
-
function makeConfig(
|
|
48
|
+
function makeConfig(
|
|
49
|
+
sweepIntervalMs = SWEEP_INTERVAL_MS,
|
|
50
|
+
sweepLookbackMs = SWEEP_LOOKBACK_MS,
|
|
51
|
+
): AssistantConfig {
|
|
41
52
|
return {
|
|
42
|
-
memory: { retrospective: { sweepIntervalMs } },
|
|
53
|
+
memory: { retrospective: { sweepIntervalMs, sweepLookbackMs } },
|
|
43
54
|
} as unknown as AssistantConfig;
|
|
44
55
|
}
|
|
45
56
|
|
|
57
|
+
function setLastMessageAt(conversationId: string, ts: number | null): void {
|
|
58
|
+
getDb()
|
|
59
|
+
.update(conversations)
|
|
60
|
+
.set({ lastMessageAt: ts })
|
|
61
|
+
.where(eq(conversations.id, conversationId))
|
|
62
|
+
.run();
|
|
63
|
+
}
|
|
64
|
+
|
|
46
65
|
function resetTables(): void {
|
|
47
66
|
const db = getDb();
|
|
48
67
|
db.run(`DELETE FROM messages`);
|
|
49
68
|
getMemorySqlite()!.exec(`DELETE FROM memory_retrospective_state`);
|
|
69
|
+
getMemorySqlite()!.exec(`DELETE FROM memory_jobs`);
|
|
50
70
|
db.run(`DELETE FROM conversations`);
|
|
51
71
|
}
|
|
52
72
|
|
|
@@ -71,6 +91,12 @@ function insertMessage(
|
|
|
71
91
|
metadata: opts.metadata ? JSON.stringify(opts.metadata) : null,
|
|
72
92
|
})
|
|
73
93
|
.run();
|
|
94
|
+
// Mirrors `addMessage`'s conversation-stamp bump so seeded conversations
|
|
95
|
+
// sit inside the sweep lookback window. The stamp is wall-clock (like
|
|
96
|
+
// production), independent of the message's logical `createdAt`, which the
|
|
97
|
+
// cursor accounting reads from the message rows. Dormancy tests override
|
|
98
|
+
// via `setLastMessageAt`.
|
|
99
|
+
setLastMessageAt(conversationId, Date.now());
|
|
74
100
|
return id;
|
|
75
101
|
}
|
|
76
102
|
|
|
@@ -211,6 +237,97 @@ describe("runRetrospectiveSweep", () => {
|
|
|
211
237
|
{ conversationId: conv.id, trigger: "sweep" },
|
|
212
238
|
]);
|
|
213
239
|
});
|
|
240
|
+
|
|
241
|
+
test("conversation dormant beyond the lookback is not swept — a cold start over deep history enqueues nothing", async () => {
|
|
242
|
+
const conv = createConversation({ id: "conv-a" });
|
|
243
|
+
// Unprocessed tail exists (no state row at all), which is the shape of
|
|
244
|
+
// every historical conversation on a first sweep — but the conversation
|
|
245
|
+
// has been dormant past the lookback, so its tail is an ordinary
|
|
246
|
+
// end-of-conversation remainder, not stalled work.
|
|
247
|
+
insertMessage(conv.id, { createdAt: 1_000 });
|
|
248
|
+
setLastMessageAt(conv.id, Date.now() - SWEEP_LOOKBACK_MS - 60_000);
|
|
249
|
+
|
|
250
|
+
const result = await runRetrospectiveSweep(makeConfig());
|
|
251
|
+
|
|
252
|
+
expect(enqueueCalls).toEqual([]);
|
|
253
|
+
expect(result).toEqual({ scanned: 0, enqueued: 0 });
|
|
254
|
+
});
|
|
255
|
+
|
|
256
|
+
test("source with an already-pending job is skipped and does not consume the cap", async () => {
|
|
257
|
+
// Three stalled sources already have pending rows (e.g. the worker is
|
|
258
|
+
// backed up); one fresh source has none. The pending ones must be skipped
|
|
259
|
+
// outright — counting their coalescing upserts toward the cap would
|
|
260
|
+
// starve later ids across passes.
|
|
261
|
+
for (const id of ["conv-a", "conv-b", "conv-c"]) {
|
|
262
|
+
const conv = createConversation({ id });
|
|
263
|
+
insertMessage(conv.id, { createdAt: 1_000 });
|
|
264
|
+
upsertMemoryRetrospectiveJob({ conversationId: conv.id });
|
|
265
|
+
}
|
|
266
|
+
const fresh = createConversation({ id: "conv-d" });
|
|
267
|
+
insertMessage(fresh.id, { createdAt: 1_000 });
|
|
268
|
+
|
|
269
|
+
const result = await runRetrospectiveSweep(makeConfig());
|
|
270
|
+
|
|
271
|
+
expect(enqueueCalls).toEqual([
|
|
272
|
+
{ conversationId: fresh.id, trigger: "sweep" },
|
|
273
|
+
]);
|
|
274
|
+
expect(result).toEqual({ scanned: 4, enqueued: 1 });
|
|
275
|
+
});
|
|
276
|
+
|
|
277
|
+
test("a running retrospective does not suppress the sweep — a mid-run arrival needs a follow-up row", async () => {
|
|
278
|
+
// The running job's fork and cursor are pre-run snapshots; the sweep must
|
|
279
|
+
// still be able to enqueue the follow-up behind it (the upsert's
|
|
280
|
+
// pending-only coalescing creates a fresh pending row).
|
|
281
|
+
const conv = createConversation({ id: "conv-a" });
|
|
282
|
+
insertMessage(conv.id, { createdAt: 1_000 });
|
|
283
|
+
upsertMemoryRetrospectiveJob({ conversationId: conv.id });
|
|
284
|
+
getMemorySqlite()!.exec(
|
|
285
|
+
`UPDATE memory_jobs SET status = 'running' WHERE type = 'memory_retrospective'`,
|
|
286
|
+
);
|
|
287
|
+
|
|
288
|
+
const result = await runRetrospectiveSweep(makeConfig());
|
|
289
|
+
|
|
290
|
+
expect(enqueueCalls).toEqual([
|
|
291
|
+
{ conversationId: conv.id, trigger: "sweep" },
|
|
292
|
+
]);
|
|
293
|
+
expect(result).toEqual({ scanned: 1, enqueued: 1 });
|
|
294
|
+
});
|
|
295
|
+
|
|
296
|
+
test("a lookback below the sweep cadence is clamped to twice the interval", async () => {
|
|
297
|
+
// lookback 1 minute, interval 8h → effective window 16h. The doubled
|
|
298
|
+
// floor covers work that lands in the scheduler/queue skew right after a
|
|
299
|
+
// pass (older than one interval by the time the next pass executes)
|
|
300
|
+
// while staying bounded across extended downtime.
|
|
301
|
+
const seen = createConversation({ id: "conv-seen" });
|
|
302
|
+
insertMessage(seen.id, { createdAt: 1_000 });
|
|
303
|
+
setLastMessageAt(seen.id, Date.now() - 10 * 60 * 60 * 1000); // 10h: past one interval
|
|
304
|
+
const beyond = createConversation({ id: "conv-beyond" });
|
|
305
|
+
insertMessage(beyond.id, { createdAt: 1_000 });
|
|
306
|
+
setLastMessageAt(beyond.id, Date.now() - 17 * 60 * 60 * 1000); // 17h: past the floor
|
|
307
|
+
|
|
308
|
+
const result = await runRetrospectiveSweep(
|
|
309
|
+
makeConfig(SWEEP_INTERVAL_MS, 60_000),
|
|
310
|
+
);
|
|
311
|
+
|
|
312
|
+
expect(enqueueCalls).toEqual([
|
|
313
|
+
{ conversationId: seen.id, trigger: "sweep" },
|
|
314
|
+
]);
|
|
315
|
+
expect(result).toEqual({ scanned: 1, enqueued: 1 });
|
|
316
|
+
});
|
|
317
|
+
|
|
318
|
+
test("enqueues clamp at the per-pass cap and defer the remainder", async () => {
|
|
319
|
+
for (let i = 0; i < SWEEP_MAX_ENQUEUES_PER_PASS + 5; i++) {
|
|
320
|
+
const conv = createConversation({
|
|
321
|
+
id: `conv-${String(i).padStart(3, "0")}`,
|
|
322
|
+
});
|
|
323
|
+
insertMessage(conv.id, { createdAt: 1_000 });
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
const result = await runRetrospectiveSweep(makeConfig());
|
|
327
|
+
|
|
328
|
+
expect(result.enqueued).toBe(SWEEP_MAX_ENQUEUES_PER_PASS);
|
|
329
|
+
expect(enqueueCalls.length).toBe(SWEEP_MAX_ENQUEUES_PER_PASS);
|
|
330
|
+
});
|
|
214
331
|
});
|
|
215
332
|
|
|
216
333
|
describe("listSweepCandidateConversationIds", () => {
|
|
@@ -231,21 +348,45 @@ describe("listSweepCandidateConversationIds", () => {
|
|
|
231
348
|
});
|
|
232
349
|
createConversation({ id: "conv-auto", source: AUTO_ANALYSIS_SOURCE });
|
|
233
350
|
createConversation({ id: "conv-scheduled", conversationType: "scheduled" });
|
|
351
|
+
for (const id of [
|
|
352
|
+
"conv-a",
|
|
353
|
+
"conv-b",
|
|
354
|
+
"conv-retro",
|
|
355
|
+
"conv-consolidate",
|
|
356
|
+
"conv-auto",
|
|
357
|
+
"conv-scheduled",
|
|
358
|
+
]) {
|
|
359
|
+
setLastMessageAt(id, 5_000);
|
|
360
|
+
}
|
|
234
361
|
|
|
235
|
-
const ids = listSweepCandidateConversationIds("", 100);
|
|
362
|
+
const ids = listSweepCandidateConversationIds("", 100, 0);
|
|
236
363
|
|
|
237
364
|
expect(ids).toEqual(["conv-a", "conv-b"]);
|
|
238
365
|
});
|
|
239
366
|
|
|
240
367
|
test("keyset cursor resumes past the given id", () => {
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
368
|
+
for (const id of ["conv-a", "conv-b", "conv-c"]) {
|
|
369
|
+
createConversation({ id });
|
|
370
|
+
setLastMessageAt(id, 5_000);
|
|
371
|
+
}
|
|
244
372
|
|
|
245
|
-
expect(listSweepCandidateConversationIds("conv-a", 100)).toEqual([
|
|
373
|
+
expect(listSweepCandidateConversationIds("conv-a", 100, 0)).toEqual([
|
|
246
374
|
"conv-b",
|
|
247
375
|
"conv-c",
|
|
248
376
|
]);
|
|
249
|
-
expect(listSweepCandidateConversationIds("", 1)).toEqual(["conv-a"]);
|
|
377
|
+
expect(listSweepCandidateConversationIds("", 1, 0)).toEqual(["conv-a"]);
|
|
378
|
+
});
|
|
379
|
+
|
|
380
|
+
test("lookback cutoff excludes dormant and never-stamped conversations", () => {
|
|
381
|
+
createConversation({ id: "conv-recent" });
|
|
382
|
+
setLastMessageAt("conv-recent", 5_000);
|
|
383
|
+
createConversation({ id: "conv-dormant" });
|
|
384
|
+
setLastMessageAt("conv-dormant", 1_000);
|
|
385
|
+
// No message stamp at all — `gt` NULL semantics exclude it.
|
|
386
|
+
createConversation({ id: "conv-unstamped" });
|
|
387
|
+
|
|
388
|
+
expect(listSweepCandidateConversationIds("", 100, 2_000)).toEqual([
|
|
389
|
+
"conv-recent",
|
|
390
|
+
]);
|
|
250
391
|
});
|
|
251
392
|
});
|
|
@@ -97,6 +97,7 @@ import {
|
|
|
97
97
|
getRetrospectiveState,
|
|
98
98
|
upsertRetrospectiveState,
|
|
99
99
|
} from "./memory-retrospective-state.js";
|
|
100
|
+
import { effectiveSweepLookbackMs } from "./memory-retrospective-sweep.js";
|
|
100
101
|
|
|
101
102
|
const log = getLogger("memory-retrospective-job");
|
|
102
103
|
|
|
@@ -124,6 +125,7 @@ const MEMORY_RETROSPECTIVE_RUN_CHECK_NAME = "memory_retrospective_run";
|
|
|
124
125
|
export type MemoryRetrospectiveOutcome =
|
|
125
126
|
| { kind: "disabled" }
|
|
126
127
|
| { kind: "no_new_messages" }
|
|
128
|
+
| { kind: "source_dormant" }
|
|
127
129
|
| { kind: "source_processing" }
|
|
128
130
|
| { kind: "wake_failed"; reason?: string; conversationId?: string }
|
|
129
131
|
| {
|
|
@@ -170,7 +172,9 @@ export async function memoryRetrospectiveJob(
|
|
|
170
172
|
|
|
171
173
|
let outcome: MemoryRetrospectiveOutcome;
|
|
172
174
|
try {
|
|
173
|
-
outcome = await runForkBasedRetrospective(sourceConversationId, config
|
|
175
|
+
outcome = await runForkBasedRetrospective(sourceConversationId, config, {
|
|
176
|
+
enforceSweepLookback: true,
|
|
177
|
+
});
|
|
174
178
|
} catch (err) {
|
|
175
179
|
emitRunOutcome("error", err instanceof Error ? err.message : String(err));
|
|
176
180
|
throw err;
|
|
@@ -196,6 +200,16 @@ export async function memoryRetrospectiveJob(
|
|
|
196
200
|
export async function runForkBasedRetrospective(
|
|
197
201
|
sourceConversationId: string,
|
|
198
202
|
config: AssistantConfig,
|
|
203
|
+
opts?: {
|
|
204
|
+
/**
|
|
205
|
+
* Skip the run when the source's last message is older than
|
|
206
|
+
* `memory.retrospective.sweepLookbackMs`. The queue handler passes this so
|
|
207
|
+
* a stale pending backlog is completed as no-ops instead of run; the CLI's
|
|
208
|
+
* manual command omits it — an operator's explicit request overrides the
|
|
209
|
+
* window.
|
|
210
|
+
*/
|
|
211
|
+
enforceSweepLookback?: boolean;
|
|
212
|
+
},
|
|
199
213
|
): Promise<MemoryRetrospectiveOutcome> {
|
|
200
214
|
// Start stamp for the retrospective's end-to-end wall time, surfaced as
|
|
201
215
|
// `durationMs` on the "invoked" log (start → invoked).
|
|
@@ -209,6 +223,29 @@ export async function runForkBasedRetrospective(
|
|
|
209
223
|
return { kind: "no_new_messages" };
|
|
210
224
|
}
|
|
211
225
|
|
|
226
|
+
// Execution-time twin of the sweep's lookback window (see
|
|
227
|
+
// memory-retrospective-sweep.ts). Event triggers enqueue in response to a
|
|
228
|
+
// just-persisted message, so a legitimately-enqueued job's source sits
|
|
229
|
+
// inside the window when the job runs; a numeric stamp older than the
|
|
230
|
+
// window means the row is stale backlog, and running it would burn an
|
|
231
|
+
// inference pass on a conversation the sweep no longer considers stalled.
|
|
232
|
+
// A missing stamp is NOT dormancy here — the enqueue itself evidences
|
|
233
|
+
// activity, unlike the sweep's scan where the stamp is the only signal.
|
|
234
|
+
// Both state pointers stay untouched.
|
|
235
|
+
if (opts?.enforceSweepLookback === true) {
|
|
236
|
+
const lastMessageAt = sourceConversation.lastMessageAt;
|
|
237
|
+
if (
|
|
238
|
+
typeof lastMessageAt === "number" &&
|
|
239
|
+
startedAtMs - lastMessageAt > effectiveSweepLookbackMs(config)
|
|
240
|
+
) {
|
|
241
|
+
log.info(
|
|
242
|
+
{ sourceConversationId, lastMessageAt },
|
|
243
|
+
"memory-retrospective (fork): source dormant beyond the sweep lookback; skipping",
|
|
244
|
+
);
|
|
245
|
+
return { kind: "source_dormant" };
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
|
|
212
249
|
// Forking mid-turn would capture a half-finished display turn — incremental
|
|
213
250
|
// checkpoint persistence writes complete tool turns to the DB while the
|
|
214
251
|
// agent loop is still running. Check the persisted `processing_started_at`
|
|
@@ -27,6 +27,14 @@
|
|
|
27
27
|
// (filtered in `EXCLUDED_SOURCES`).
|
|
28
28
|
//
|
|
29
29
|
// Cost discipline:
|
|
30
|
+
// - The scan is bounded to conversations whose last message falls inside
|
|
31
|
+
// `memory.retrospective.sweepLookbackMs`. A crash-orphaned turn is by
|
|
32
|
+
// definition recent, so a conversation dormant beyond the window is not
|
|
33
|
+
// stalled work — its unprocessed tail is an ordinary end-of-conversation
|
|
34
|
+
// remainder. Without this bound, the scan degenerates into a full-history
|
|
35
|
+
// backfill: nearly every conversation ever carries a tail past its final
|
|
36
|
+
// retrospective cursor, so a cold start would enqueue an inference pass
|
|
37
|
+
// per conversation across the entire history.
|
|
30
38
|
// - The per-conversation gate skips any conversation whose last retrospective
|
|
31
39
|
// attempt is newer than the sweep interval, so the sweep never competes
|
|
32
40
|
// with the responsive event triggers on active conversations — it only
|
|
@@ -35,11 +43,22 @@
|
|
|
35
43
|
// `upsertMemoryRetrospectiveJob` coalesces against any already-pending job,
|
|
36
44
|
// so a conversation already queued by an event trigger is never
|
|
37
45
|
// double-processed.
|
|
46
|
+
// - Enqueues are capped at `SWEEP_MAX_ENQUEUES_PER_PASS` per pass. Inside
|
|
47
|
+
// the lookback window, organic stalled work is a handful of conversations;
|
|
48
|
+
// a pass wanting more signals an anomalous backlog. Each pass re-scans
|
|
49
|
+
// from the start, so the deferred remainder is picked up by later passes.
|
|
50
|
+
// Sources with an already-pending retrospective job are skipped before
|
|
51
|
+
// the cap, so coalescing no-ops never consume it; a running job does not
|
|
52
|
+
// suppress the sweep (its cursor is a pre-run snapshot — a mid-run
|
|
53
|
+
// arrival needs a follow-up row behind it).
|
|
38
54
|
// - The scan is keyset-paginated in bounded batches with a yield between
|
|
39
55
|
// pages (mirrors `conversation-memory-orphan-sweep.ts`), so a large history
|
|
40
|
-
// never materializes all ids at once or holds the event loop.
|
|
41
|
-
//
|
|
42
|
-
//
|
|
56
|
+
// never materializes all ids at once or holds the event loop.
|
|
57
|
+
//
|
|
58
|
+
// The retrospective job re-applies the lookback window at execution time
|
|
59
|
+
// (`runForkBasedRetrospective`'s `enforceSweepLookback` gate), so pending rows
|
|
60
|
+
// that outlive the window — e.g. a backlog drained long after enqueue — are
|
|
61
|
+
// completed as no-ops instead of run.
|
|
43
62
|
|
|
44
63
|
import { and, asc, gt, ne, notInArray } from "drizzle-orm";
|
|
45
64
|
|
|
@@ -48,7 +67,10 @@ import { AUTO_ANALYSIS_SOURCE } from "../../../persistence/auto-analysis-constan
|
|
|
48
67
|
import { getConversationRecentProvenanceTrustClass } from "../../../persistence/conversation-crud.js";
|
|
49
68
|
import { getDb } from "../../../persistence/db-connection.js";
|
|
50
69
|
import type { MemoryJob } from "../../../persistence/jobs-store.js";
|
|
51
|
-
import {
|
|
70
|
+
import {
|
|
71
|
+
isMemoryEnabled,
|
|
72
|
+
listPendingMemoryRetrospectiveSourceConversationIds,
|
|
73
|
+
} from "../../../persistence/jobs-store.js";
|
|
52
74
|
import { conversations } from "../../../persistence/schema/index.js";
|
|
53
75
|
import { getLogger } from "./logging.js";
|
|
54
76
|
import { countRetrospectiveMessagesAfter } from "./memory-retrospective-accounting.js";
|
|
@@ -62,6 +84,15 @@ const log = getLogger("memory-retrospective-sweep");
|
|
|
62
84
|
/** Rows per keyset-paginated page — bounds each statement and the id set held. */
|
|
63
85
|
const SWEEP_BATCH = 200;
|
|
64
86
|
|
|
87
|
+
/**
|
|
88
|
+
* Hard ceiling on retrospectives enqueued by a single sweep pass. Each
|
|
89
|
+
* enqueue fans out an LLM inference pass, so a pass that wants more than this
|
|
90
|
+
* many is anomalous (organic in-window stalled work is a handful of
|
|
91
|
+
* conversations at most) and gets clamped with a warning. Safe to defer: every
|
|
92
|
+
* pass re-scans from the start, so the remainder is enqueued by later passes.
|
|
93
|
+
*/
|
|
94
|
+
export const SWEEP_MAX_ENQUEUES_PER_PASS = 50;
|
|
95
|
+
|
|
65
96
|
/**
|
|
66
97
|
* Conversation `source` values excluded from the sweep up front:
|
|
67
98
|
* - retrospective background conversations — recursion guard (never run a
|
|
@@ -107,15 +138,44 @@ function breathe(): Promise<void> {
|
|
|
107
138
|
return Bun.sleep(0);
|
|
108
139
|
}
|
|
109
140
|
|
|
141
|
+
/**
|
|
142
|
+
* The lookback window the sweep actually applies: never smaller than TWICE
|
|
143
|
+
* `sweepIntervalMs`. One interval is not enough — the pass checkpoint is
|
|
144
|
+
* stamped at enqueue but the cutoff is computed at execution, so tick, queue,
|
|
145
|
+
* and runtime delay stretch the gap between consecutive executions past the
|
|
146
|
+
* nominal cadence, and a message landing in that skew right after a pass
|
|
147
|
+
* would sit permanently outside an exact-interval window. The doubled floor
|
|
148
|
+
* absorbs the skew while staying BOUNDED: deriving the window from elapsed
|
|
149
|
+
* time since the previous pass would cover arbitrary gaps, but after
|
|
150
|
+
* extended downtime it would recreate the cold-start backfill this window
|
|
151
|
+
* exists to prevent. Outages longer than a full interval can therefore still
|
|
152
|
+
* leave tails outside the window — accepted by design, like the cold start.
|
|
153
|
+
* Shared by the sweep scan and the retrospective job's execution-time gate;
|
|
154
|
+
* the two must agree or the gate would kill jobs the scan legitimately
|
|
155
|
+
* enqueued.
|
|
156
|
+
*/
|
|
157
|
+
export function effectiveSweepLookbackMs(config: AssistantConfig): number {
|
|
158
|
+
return Math.max(
|
|
159
|
+
config.memory.retrospective.sweepLookbackMs,
|
|
160
|
+
2 * config.memory.retrospective.sweepIntervalMs,
|
|
161
|
+
);
|
|
162
|
+
}
|
|
163
|
+
|
|
110
164
|
/**
|
|
111
165
|
* One keyset page of sweep-eligible conversation ids past `cursor`. The empty
|
|
112
166
|
* string sorts before any real id, so the first page starts at the beginning.
|
|
113
167
|
* `scheduled`-type conversations are filtered here (low-yield, matching the
|
|
114
168
|
* enqueue guard); other low-yield cases are caught by the enqueue itself.
|
|
169
|
+
*
|
|
170
|
+
* `lastMessageAtCutoff` bounds the scan to the sweep's lookback window
|
|
171
|
+
* (indexed via `idx_conversations_last_message_at`). `gt` NULL semantics
|
|
172
|
+
* exclude rows with no recorded message stamp: absent any evidence of recent
|
|
173
|
+
* activity, a conversation is not sweepable.
|
|
115
174
|
*/
|
|
116
175
|
export function listSweepCandidateConversationIds(
|
|
117
176
|
cursor: string,
|
|
118
177
|
limit: number,
|
|
178
|
+
lastMessageAtCutoff: number,
|
|
119
179
|
): string[] {
|
|
120
180
|
return getDb()
|
|
121
181
|
.select({ id: conversations.id })
|
|
@@ -123,6 +183,7 @@ export function listSweepCandidateConversationIds(
|
|
|
123
183
|
.where(
|
|
124
184
|
and(
|
|
125
185
|
gt(conversations.id, cursor),
|
|
186
|
+
gt(conversations.lastMessageAt, lastMessageAtCutoff),
|
|
126
187
|
notInArray(conversations.source, EXCLUDED_SOURCES),
|
|
127
188
|
ne(conversations.conversationType, "scheduled"),
|
|
128
189
|
),
|
|
@@ -141,11 +202,12 @@ export interface RetrospectiveSweepResult {
|
|
|
141
202
|
}
|
|
142
203
|
|
|
143
204
|
/**
|
|
144
|
-
* Scan
|
|
145
|
-
* retrospective for any with unprocessed
|
|
146
|
-
* than `sweepIntervalMs
|
|
147
|
-
*
|
|
148
|
-
*
|
|
205
|
+
* Scan sweep-eligible conversations with activity inside the lookback window
|
|
206
|
+
* and enqueue a `sweep`-triggered retrospective for any with unprocessed
|
|
207
|
+
* messages whose last attempt is older than `sweepIntervalMs`, up to
|
|
208
|
+
* {@link SWEEP_MAX_ENQUEUES_PER_PASS} per pass. Idempotent and best-effort:
|
|
209
|
+
* enqueue coalescing prevents duplicates, and the scan degrades to a no-op
|
|
210
|
+
* when memory is disabled.
|
|
149
211
|
*/
|
|
150
212
|
export async function runRetrospectiveSweep(
|
|
151
213
|
config: AssistantConfig,
|
|
@@ -155,12 +217,20 @@ export async function runRetrospectiveSweep(
|
|
|
155
217
|
return { scanned: 0, enqueued: 0 };
|
|
156
218
|
}
|
|
157
219
|
const sweepIntervalMs = config.memory.retrospective.sweepIntervalMs;
|
|
220
|
+
const lookbackCutoff = now - effectiveSweepLookbackMs(config);
|
|
221
|
+
const pendingSourceIds = new Set(
|
|
222
|
+
listPendingMemoryRetrospectiveSourceConversationIds(),
|
|
223
|
+
);
|
|
158
224
|
|
|
159
225
|
let scanned = 0;
|
|
160
226
|
let enqueued = 0;
|
|
161
227
|
let cursor = "";
|
|
162
228
|
for (;;) {
|
|
163
|
-
const page = listSweepCandidateConversationIds(
|
|
229
|
+
const page = listSweepCandidateConversationIds(
|
|
230
|
+
cursor,
|
|
231
|
+
SWEEP_BATCH,
|
|
232
|
+
lookbackCutoff,
|
|
233
|
+
);
|
|
164
234
|
if (page.length === 0) {
|
|
165
235
|
break;
|
|
166
236
|
}
|
|
@@ -169,6 +239,17 @@ export async function runRetrospectiveSweep(
|
|
|
169
239
|
for (const conversationId of page) {
|
|
170
240
|
scanned += 1;
|
|
171
241
|
|
|
242
|
+
// A source with a pending row has nothing for the sweep to add — the
|
|
243
|
+
// row runs on its own. Skipping it up front keeps coalescing upserts
|
|
244
|
+
// from consuming the per-pass enqueue cap: counted no-ops would starve
|
|
245
|
+
// conversations later in id order across passes (every pass restarts
|
|
246
|
+
// from the lowest id). A RUNNING job does not suppress the sweep — its
|
|
247
|
+
// cursor is a pre-run snapshot, so a mid-run arrival needs a follow-up
|
|
248
|
+
// row, and the upsert's pending-only coalescing creates exactly that.
|
|
249
|
+
if (pendingSourceIds.has(conversationId)) {
|
|
250
|
+
continue;
|
|
251
|
+
}
|
|
252
|
+
|
|
172
253
|
// Memory trust boundary: never enqueue a retrospective (which runs under
|
|
173
254
|
// guardian trust with `remember`) for a conversation whose actor isn't
|
|
174
255
|
// memory-trusted. This is the sweep's equivalent of the per-message
|
|
@@ -198,6 +279,13 @@ export async function runRetrospectiveSweep(
|
|
|
198
279
|
|
|
199
280
|
enqueueMemoryRetrospectiveIfEnabled({ conversationId, trigger: "sweep" });
|
|
200
281
|
enqueued += 1;
|
|
282
|
+
if (enqueued >= SWEEP_MAX_ENQUEUES_PER_PASS) {
|
|
283
|
+
log.warn(
|
|
284
|
+
{ scanned, enqueued },
|
|
285
|
+
"Memory retrospective sweep hit the per-pass enqueue cap; deferring the remainder to the next pass",
|
|
286
|
+
);
|
|
287
|
+
return { scanned, enqueued };
|
|
288
|
+
}
|
|
201
289
|
}
|
|
202
290
|
|
|
203
291
|
await breathe();
|