From 2095ce608bf68a883bf63e6a5a9db839d108f02e Mon Sep 17 00:00:00 2001 From: Josh Winters Date: Mon, 23 Nov 2026 18:28:29 -0500 Subject: [PATCH 1/3] Serve approved archive recall from a verified local cache; revalidate in the background An approved turn waited up to 4 s on the hosted recall call even though the approval already pins the snapshot by sha256. - After a turn verifies, the snapshot is cached beside the approval. - The next matching turn is served from it at once when it still matches the approval digest (and is under 7 days old). The same paid hosted request then runs in the background, so billing is unchanged (the server charges per delivered pack). - If that request does not verify (superseded or missing record, payment failure, deadline), the cache entry is dropped and the next turn waits for a live answer as before. A changed record can be served once more before it is withheld. - Revocation discards the cache. stop() waits for pending revalidations. Task Master 167. --- docs/HOT-SYNC.md | 9 ++ src/runtime/archive-recall.ts | 58 ++++++++++- src/runtime/lifecycle-engine.ts | 99 +++++++++++++++---- tests/runtime/archive-recall-cache.test.ts | 43 ++++++++ .../runtime/hosted-lifecycle-security.test.ts | 35 ++++++- 5 files changed, 221 insertions(+), 23 deletions(-) create mode 100644 tests/runtime/archive-recall-cache.test.ts diff --git a/docs/HOT-SYNC.md b/docs/HOT-SYNC.md index 3369a89..b62a6e0 100644 --- a/docs/HOT-SYNC.md +++ b/docs/HOT-SYNC.md @@ -63,6 +63,15 @@ current local approval, including after the request returns. A missing correction, a changed source, denial by local policy, payment failure or a request deadline leaves the turn with its ordinary hot context. +After a turn verifies, the snapshot is kept locally (`recall-cache.json` in the +approval directory). The next matching turn is served from it at once if it +still matches the approval digest and is under seven days old, and the paid +recall request runs in the background, so billing is unchanged. If that request +does not verify (a superseded or missing record, payment failure, deadline), the +cached snapshot is dropped and the following turn waits for a live answer, as +before. A changed record can therefore be served once more before it is +withheld. Revoking an approval discards the cache. + ## Multiple machines and commands Use the same identity and profile name on both machines. Keep the private key in diff --git a/src/runtime/archive-recall.ts b/src/runtime/archive-recall.ts index 525eead..c04b83d 100644 --- a/src/runtime/archive-recall.ts +++ b/src/runtime/archive-recall.ts @@ -98,7 +98,7 @@ export function readArchiveRecallSnapshot( } const ownerKey = ({ name, apiBase, npub }: ArchiveRecallOwner) => [name, apiBase, npub]; -const archiveRecallDigest = ( +export const archiveRecallDigest = ( owner: ArchiveRecallOwner, snapshot: ArchiveRecallSnapshot, runtimeHost: ArchiveRecallHost | null ): string => digest(runtimeHost ? [ownerKey(owner), snapshot, runtimeHost] : [ownerKey(owner), snapshot]); @@ -213,6 +213,8 @@ export async function revokeArchiveRecall( stateDir: string, owner: ArchiveRecallOwner, workspaceId: string, taskId: string | null ): Promise { await editApprovalState(approvalDirectory(stateDir, owner, workspaceId), state => { + // Revocation also discards cached snapshots; a later approval caches again. + rmSync(path.join(approvalDirectory(stateDir, owner, workspaceId), CACHE_FILE), { force: true }); if (taskId === null) return; const revoked = state.approvals.filter(item => item.taskId === taskId); state.approvals = state.approvals.filter(item => item.taskId !== taskId); @@ -247,3 +249,57 @@ export function archiveApprovalFitsScope(approval: Approval, scope: Record { + try { + const value = object(JSON.parse(readFileSync(path.join(directory, CACHE_FILE), "utf8"))); + if (value?.version !== CACHE_VERSION || !Array.isArray(value.entries)) return []; + return value.entries.flatMap((raw: unknown) => { + const entry = object(raw), snapshot = object(entry?.snapshot); + return entry && snapshot && typeof entry.sha256 === "string" && SHA256.test(entry.sha256) && archivePackId(entry.packId) && + Number.isFinite(entry.verifiedAt) && snapshot.version === VERSION && typeof snapshot.workspaceId === "string" && + typeof snapshot.taskId === "string" && Array.isArray(snapshot.sources) && snapshot.sources.every((source: unknown) => { + const item = object(source); + return item && typeof item.id === "string" && SOURCE_ID.test(item.id) && typeof item.content === "string" && + (item.kind === "warm_memory" || item.kind === "cold_memory"); + }) ? [entry as unknown as CachedRecall] : []; + }); + } catch { return []; } +}; + +/** The cached snapshot for an approval, if it still verifies against it and is within the preview window. */ +export function readCachedArchiveRecall( + stateDir: string, owner: ArchiveRecallOwner, workspaceId: string, approval: Approval +): { packId: string; snapshot: ArchiveRecallSnapshot } | null { + const entry = readCache(approvalDirectory(stateDir, owner, workspaceId)).find(item => item.sha256 === approval.sha256); + if (!entry || entry.snapshot.workspaceId !== workspaceId || Date.now() - entry.verifiedAt > PREVIEW_TTL_MS) return null; + return verifyArchiveRecall(owner, approval, entry.snapshot) ? { packId: entry.packId, snapshot: entry.snapshot } : null; +} + +export function writeCachedArchiveRecall( + stateDir: string, owner: ArchiveRecallOwner, approval: Approval, snapshot: ArchiveRecallSnapshot, packId: string +): void { + const directory = approvalDirectory(stateDir, owner, snapshot.workspaceId); + const entries = [...readCache(directory).filter(item => item.sha256 !== approval.sha256), + { sha256: approval.sha256, packId, snapshot, verifiedAt: Date.now() }].slice(-MAX_CACHED); + writeJsonFile(path.join(directory, CACHE_FILE), { version: CACHE_VERSION, entries }); +} + +export function dropCachedArchiveRecall(stateDir: string, owner: ArchiveRecallOwner, workspaceId: string, sha256: string): void { + const directory = approvalDirectory(stateDir, owner, workspaceId); + const entries = readCache(directory); + if (entries.some(item => item.sha256 === sha256)) { + writeJsonFile(path.join(directory, CACHE_FILE), { version: CACHE_VERSION, entries: entries.filter(item => item.sha256 !== sha256) }); + } +} diff --git a/src/runtime/lifecycle-engine.ts b/src/runtime/lifecycle-engine.ts index 58b987c..3dfbf44 100644 --- a/src/runtime/lifecycle-engine.ts +++ b/src/runtime/lifecycle-engine.ts @@ -1,5 +1,6 @@ import { - ARCHIVE_RECALL_BUDGET, archiveApprovalFitsScope, archivePackId, findArchiveRecallApproval, readArchiveRecallSnapshot, + ARCHIVE_RECALL_BUDGET, archiveApprovalFitsScope, archivePackId, dropCachedArchiveRecall, findArchiveRecallApproval, readArchiveRecallSnapshot, + readCachedArchiveRecall, writeCachedArchiveRecall, renderArchiveRecall, verifyArchiveRecall, } from "./archive-recall"; import { getHotSyncManager, hotSyncEnabled, tickHotSyncManagers } from "./hot-sync-manager"; @@ -1567,6 +1568,8 @@ export class RuntimeLifecycleManager { private readonly maxQueueAttempts: number; private timer: NodeJS.Timeout | null = null; private backgroundOperation: Promise | null = null; + /** Background revalidations of cached archive recall; stop() waits for them. */ + private readonly pendingRecalls = new Set>(); private mutation: Promise = Promise.resolve(); private detachedFlush: Promise | null = null; private readonly claimedQueueItems = new Set(); @@ -1617,6 +1620,7 @@ export class RuntimeLifecycleManager { finally { if (this.backgroundOperation === operation) this.backgroundOperation = null; await this.detachedFlush; + await Promise.allSettled([...this.pendingRecalls]); await this.mutation; } } @@ -2302,22 +2306,68 @@ export class RuntimeLifecycleManager { const { event } = response; const workspaceId = event.workspaceId; if (!workspaceId) return; - - let attemptedProfile: string | null = null; - let packId: string | null = null; - let verified = false; - let failure: ReturnType | undefined; + let resolved: ReturnType; + let goal: string | null, scope: Record | null; + let approval: ReturnType; + let cached: ReturnType = null; try { - const { profileName, profile, secret } = this.resolveProfile(event.profileName); - if (isLocalOnlyRuntimeProfile(profile)) return; + resolved = this.resolveProfile(event.profileName); + if (isLocalOnlyRuntimeProfile(resolved.profile)) return; const governor = this.deps.loadContinuityGovernorState(); const request = buildPackRequest(event, governor.memoryScope); - const goal = asString(request?.goal); - const scope = asRecord(request?.allowedScope); + goal = asString(request?.goal); + scope = asRecord(request?.allowedScope); if (!goal || !scope || governor.paused || (!scope.includeWarmMemory && !scope.includeColdMemory)) return; - const approval = findArchiveRecallApproval(this.deps.paths.state, profile, workspaceId, goal, event.runtime); + approval = findArchiveRecallApproval(this.deps.paths.state, resolved.profile, workspaceId, goal, event.runtime); if (!approval || !archiveApprovalFitsScope(approval, scope)) return; + // A snapshot verified on an earlier turn is served now; the hosted call + // (which bills and reports superseded records) runs off the critical path. + cached = readCachedArchiveRecall(this.deps.paths.state, resolved.profile, workspaceId, approval); + } catch (error) { + response.warnings.push(describeBoundedRecallFallback(error)); + return; + } + const { profileName } = resolved; + if (cached && cached.snapshot.sources.every(source => source.kind === "warm_memory" + ? scope.includeWarmMemory === true : scope.includeColdMemory === true)) { + contextPack.verifiedArchiveContext = renderArchiveRecall(cached.snapshot); + contextPack.packId = cached.packId; + try { + response.actions.push(this.recordAction({ + eventId: event.eventId, profileName, type: "context_pack", status: "completed", mode: response.mode, + reason: "Served verified archive recall from the local cache; revalidating", queueItemId: null, + details: { packId: cached.packId, verifiedArchiveRecall: true, cachedArchiveRecall: true }, + })); + } catch { + response.warnings.push("Could not record the hosted archive recall result locally."); + } + const revalidation = this.liveArchiveRecall(response, null, resolved, goal, scope, approval) + .catch(() => undefined).finally(() => { this.pendingRecalls.delete(revalidation); }); + this.pendingRecalls.add(revalidation); + return; + } + await this.liveArchiveRecall(response, contextPack, resolved, goal, scope, approval); + } + /** + * The hosted recall call and its verification. With a target pack, the + * verified snapshot is delivered on this turn; without one (background + * revalidation) it only refreshes or drops the local cache. + */ + private async liveArchiveRecall( + response: RuntimeLifecycleEventResponse, target: Record | null, + resolved: ReturnType, goal: string, scope: Record, + approval: NonNullable>, + ): Promise { + const { event } = response; + const workspaceId = event.workspaceId!; + const warnings = target ? response.warnings : []; + let attemptedProfile: string | null = null; + let packId: string | null = null; + let verified = false; + let failure: ReturnType | undefined; + try { + const { profileName, profile, secret } = resolved; const client = this.buildClient(profile, secret); attemptedProfile = profileName; const hosted = await client.requestArchiveRecall({ @@ -2348,34 +2398,45 @@ export class RuntimeLifecycleManager { verifyArchiveRecall(currentProfile, currentApproval, snapshot) && snapshot.sources.every(source => source.kind === "warm_memory" ? currentScope.includeWarmMemory === true : currentScope.includeColdMemory === true)) { - contextPack.verifiedArchiveContext = renderArchiveRecall(snapshot); - contextPack.packId = packId; + if (target) { + target.verifiedArchiveContext = renderArchiveRecall(snapshot); + target.packId = packId; + } verified = true; + try { writeCachedArchiveRecall(this.deps.paths.state, currentProfile, currentApproval, snapshot, packId); } + catch { /* Without a cache entry the next turn waits for the live call, as before. */ } } } - if (!verified) response.warnings.push("Hosted archive recall was withheld. Only hot context was delivered."); + if (!verified) warnings.push("Hosted archive recall was withheld. Only hot context was delivered."); } catch (error) { failure = describeHostedFailure(error); - response.warnings.push(describeBoundedRecallFallback(error)); + warnings.push(describeBoundedRecallFallback(error)); } finally { + // A cached snapshot that did not verify live is not served again. + if (!verified) { + try { dropCachedArchiveRecall(this.deps.paths.state, resolved.profile, workspaceId, approval.sha256); } + catch { /* The approval digest still guards any later use. */ } + } if (attemptedProfile) { try { - response.actions.push(this.recordAction({ + const action = this.recordAction({ eventId: event.eventId, profileName: attemptedProfile, type: "context_pack", status: failure ? "failed" : "completed", mode: response.mode, - reason: verified ? "Verified archive recall against a local approval" : "Hosted archive recall withheld", + reason: verified ? (target ? "Verified archive recall against a local approval" : "Revalidated cached archive recall") : (target ? "Hosted archive recall withheld" : "Cached archive recall failed revalidation; withheld from later turns"), queueItemId: null, details: { ...(packId ? { packId } : {}), verifiedArchiveRecall: verified, ...(failure ? { failure } : {}), + ...(target ? {} : { cachedArchiveRecall: true, revalidation: true }), }, - })); + }); + if (target) response.actions.push(action); } catch { - response.warnings.push("Could not record the hosted archive recall result locally."); + warnings.push("Could not record the hosted archive recall result locally."); } } } diff --git a/tests/runtime/archive-recall-cache.test.ts b/tests/runtime/archive-recall-cache.test.ts new file mode 100644 index 0000000..89fca2f --- /dev/null +++ b/tests/runtime/archive-recall-cache.test.ts @@ -0,0 +1,43 @@ +import { mkdtempSync, readFileSync, rmSync, writeFileSync, readdirSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { afterEach, describe, expect, it, vi } from "vitest"; + +import { + archiveRecallDigest, dropCachedArchiveRecall, readCachedArchiveRecall, writeCachedArchiveRecall, type ArchiveRecallSnapshot, +} from "../../src/runtime/archive-recall"; + +const dirs: string[] = []; +afterEach(() => { vi.useRealTimers(); for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); }); +const owner = { name: "default", apiBase: "https://crosshead.sh", npub: "npub1example" }; +const snapshot: ArchiveRecallSnapshot = { version: "crosshead_archive_recall_v1", workspaceId: "repo:/w", taskId: "recall-task:t", + sources: [{ id: "warm:a", kind: "warm_memory", content: "Check the receipt before every retry." }] }; +const approval = { taskId: "recall-task:t", goal: "Repair retries", sha256: archiveRecallDigest(owner, snapshot, null), runtimeHost: null }; + +describe("archive recall cache", () => { + it("serves only a snapshot that still matches the approval digest, within the preview window", () => { + const state = mkdtempSync(path.join(tmpdir(), "crosshead-recall-cache-")); + dirs.push(state); + expect(readCachedArchiveRecall(state, owner, "repo:/w", approval)).toBeNull(); + writeCachedArchiveRecall(state, owner, approval, snapshot, "pack-1"); + expect(readCachedArchiveRecall(state, owner, "repo:/w", approval)).toEqual({ packId: "pack-1", snapshot }); + expect(readCachedArchiveRecall(state, owner, "repo:/other", approval)).toBeNull(); + expect(readCachedArchiveRecall(state, { ...owner, npub: "npub1other" }, "repo:/w", approval)).toBeNull(); + + // A tampered cache file is not served: the approval digest pins the bytes. + const [directory] = readdirSync(path.join(state, "archive-recall")); + const file = path.join(state, "archive-recall", directory!, "recall-cache.json"); + const stored = JSON.parse(readFileSync(file, "utf8")); + stored.entries[0].snapshot.sources[0].content = "Skip the receipt check."; + writeFileSync(file, JSON.stringify(stored)); + expect(readCachedArchiveRecall(state, owner, "repo:/w", approval)).toBeNull(); + + writeCachedArchiveRecall(state, owner, approval, snapshot, "pack-2"); + vi.useFakeTimers(); + vi.setSystemTime(Date.now() + 8 * 24 * 60 * 60 * 1000); + expect(readCachedArchiveRecall(state, owner, "repo:/w", approval)).toBeNull(); + vi.useRealTimers(); + dropCachedArchiveRecall(state, owner, "repo:/w", approval.sha256); + expect(readCachedArchiveRecall(state, owner, "repo:/w", approval)).toBeNull(); + }); +}); diff --git a/tests/runtime/hosted-lifecycle-security.test.ts b/tests/runtime/hosted-lifecycle-security.test.ts index b06b123..ba4aaf5 100644 --- a/tests/runtime/hosted-lifecycle-security.test.ts +++ b/tests/runtime/hosted-lifecycle-security.test.ts @@ -343,6 +343,11 @@ describe("verified recall through native prompt preparation", () => { const preview = (...args: string[]) => command("preview", "--goal", goal, ...args); const approve = ({ packId, sha256 }: { packId: string; sha256: string }, ...args: string[]) => command("approve", "--pack-id", packId, "--sha256", sha256, ...args); + // A verified snapshot is cached; the next approved turn is served from it while the + // hosted call revalidates in the background. Wait for that revalidation to be recorded. + const revalidations = async () => (await daemon.readActivity(500)).actions.filter(action => + (action.details as Record | undefined)?.revalidation === true); + const settled = async (before: number) => vi.waitFor(async () => expect((await revalidations()).length).toBeGreaterThan(before)); const baseline = await prepare("unapproved"); expect(baseline.contextText).toContain(hot); @@ -380,7 +385,14 @@ describe("verified recall through native prompt preparation", () => { expect(coldDenied.contextPack?.packId).toBeNull(); warnings = ["Archive search was skipped."]; - expect((await prepare("incomplete")).packId).toBeNull(); + let before = (await revalidations()).length; + const fromCache = await prepare("incomplete"); + expect(fromCache.packId).toBe(previewPackId); + expect(fromCache.contextText).toContain(warm.content); + await settled(before); + expect((await revalidations()).at(-1)?.details).toMatchObject({ verifiedArchiveRecall: false, cachedArchiveRecall: true }); + // The failed revalidation withholds from the following turn. + expect((await prepare("incomplete-next")).packId).toBeNull(); warnings = []; sources = [cold]; // An internally consistent response that omits the approved correction. const withheld = await prepare("omits-correction"); @@ -402,7 +414,11 @@ describe("verified recall through native prompt preparation", () => { expect((await prepare("new-revision")).contextText).toContain(sources[1]!.content); taskId = previousTaskId; sources = [cold, warm]; - expect((await prepare("replayed-revision")).contextText).toBe(baseline.contextText); + before = (await revalidations()).length; + // Served from the v2 snapshot cached on the previous turn; the replayed v1 answer fails revalidation. + expect((await prepare("replayed-revision")).contextText).toContain("Check the receipt and verify that the payer matches."); + await settled(before); + expect((await prepare("replayed-revision-next")).contextText).toBe(baseline.contextText); responseStatus = 402; expect((await prepare("unfunded")).contextText).toBe(baseline.contextText); @@ -419,7 +435,20 @@ describe("verified recall through native prompt preparation", () => { await approve(hostPreview, "--host", runtime); expect((await prepare("host-scoped")).contextText).toContain(warm.content); expect(requestHosts.slice(-2)).toEqual([runtime, runtime]); - let release!: () => void; + // With a cached snapshot the turn does not wait for the hosted call. + before = (await revalidations()).length; + let release: (() => void) | undefined; + whenRequested = () => new Promise(resolve => { release = resolve; }); + const cachedTurn = await Promise.race([prepare("cached-in-flight"), new Promise(resolve => setTimeout(() => resolve(null), 2000))]); + expect(cachedTurn?.contextText).toContain(warm.content); + await vi.waitFor(() => expect(release).toBeTypeOf("function")); + release!(); + await settled(before); + // Revocation discards the cache, so the next approved turn waits for the live call again. + whenRequested = undefined; + await command("revoke", "--task", taskId); + await approve(await preview("--host", runtime), "--host", runtime); + release = undefined; whenRequested = () => new Promise(resolve => { release = resolve; }); const inFlight = prepare("in-flight"); try { From 420214edca53e9691d39b87914396ad726bad120 Mon Sep 17 00:00:00 2001 From: Josh Winters Date: Mon, 23 Nov 2026 18:35:25 -0500 Subject: [PATCH 2/3] Recall cache review fixes: serialize revalidation, no stale pack id, one-hour window From an independent review: - A turn that overlaps a pending revalidation for the same approval waits for it (within the 4 s deadline) instead of serving the cache again; this also prevents a late verified write from restoring an entry a newer revalidation dropped. - A cached turn carries no pack id, so outcomes are not attributed to the earlier pack; the cached pack id is in the activity record. - The cache serves only within an hour of a live verification, and a timestamp from a clock far ahead is not trusted. - The cached path also checks the profile's memory mode. - Documented: a failed payment or superseded record can let one cached turn through before it is withheld. --- docs/HOT-SYNC.md | 15 ++++++---- src/runtime/archive-recall.ts | 11 ++++++-- src/runtime/lifecycle-engine.ts | 28 ++++++++++++------- .../runtime/hosted-lifecycle-security.test.ts | 13 ++++++++- 4 files changed, 48 insertions(+), 19 deletions(-) diff --git a/docs/HOT-SYNC.md b/docs/HOT-SYNC.md index b62a6e0..524688f 100644 --- a/docs/HOT-SYNC.md +++ b/docs/HOT-SYNC.md @@ -65,12 +65,15 @@ a request deadline leaves the turn with its ordinary hot context. After a turn verifies, the snapshot is kept locally (`recall-cache.json` in the approval directory). The next matching turn is served from it at once if it -still matches the approval digest and is under seven days old, and the paid -recall request runs in the background, so billing is unchanged. If that request -does not verify (a superseded or missing record, payment failure, deadline), the -cached snapshot is dropped and the following turn waits for a live answer, as -before. A changed record can therefore be served once more before it is -withheld. Revoking an approval discards the cache. +still matches the approval digest and was verified live within the last hour, +and the paid recall request runs in the background, so each served turn still +makes one billed request. If that request does not verify (a superseded or +missing record, payment failure, deadline), the cached snapshot is dropped and +the following turn waits for a live answer, as before; a turn that overlaps a +pending revalidation waits for it. So a changed record, or a failed payment, +can let one cached turn through before it is withheld. A cached turn carries no +pack id; the background pack is recorded in the activity log. Revoking an +approval discards the cache. ## Multiple machines and commands diff --git a/src/runtime/archive-recall.ts b/src/runtime/archive-recall.ts index c04b83d..7e3ea16 100644 --- a/src/runtime/archive-recall.ts +++ b/src/runtime/archive-recall.ts @@ -255,10 +255,15 @@ export function verifyArchiveRecall(owner: ArchiveRecallOwner, approval: Approva // cached snapshot is used only while it still matches the current approval. // The hosted call still runs for every served turn (billing and supersession // are decided there); if it does not verify, the entry is dropped and the next -// turn waits for a live answer. +// turn waits for a live answer. A turn served from the cache whose own request +// then fails (payment, network, superseded record) was delivered without a +// billed pack: at most one such turn per approval, within an hour of the last +// live verification. const CACHE_FILE = "recall-cache.json"; const CACHE_VERSION = "crosshead_archive_recall_cache_v1"; const MAX_CACHED = 16; +const CACHE_MAX_AGE_MS = 60 * 60 * 1_000; +const CACHE_SKEW_MS = 5 * 60 * 1_000; type CachedRecall = { sha256: string; packId: string; snapshot: ArchiveRecallSnapshot; verifiedAt: number }; const readCache = (directory: string): CachedRecall[] => { @@ -283,7 +288,9 @@ export function readCachedArchiveRecall( stateDir: string, owner: ArchiveRecallOwner, workspaceId: string, approval: Approval ): { packId: string; snapshot: ArchiveRecallSnapshot } | null { const entry = readCache(approvalDirectory(stateDir, owner, workspaceId)).find(item => item.sha256 === approval.sha256); - if (!entry || entry.snapshot.workspaceId !== workspaceId || Date.now() - entry.verifiedAt > PREVIEW_TTL_MS) return null; + // Served only shortly after a live verification; a clock far ahead is not trusted. + const age = Date.now() - (entry?.verifiedAt ?? 0); + if (!entry || entry.snapshot.workspaceId !== workspaceId || age > CACHE_MAX_AGE_MS || age < -CACHE_SKEW_MS) return null; return verifyArchiveRecall(owner, approval, entry.snapshot) ? { packId: entry.packId, snapshot: entry.snapshot } : null; } diff --git a/src/runtime/lifecycle-engine.ts b/src/runtime/lifecycle-engine.ts index 3dfbf44..e0da0e9 100644 --- a/src/runtime/lifecycle-engine.ts +++ b/src/runtime/lifecycle-engine.ts @@ -4,7 +4,7 @@ import { renderArchiveRecall, verifyArchiveRecall, } from "./archive-recall"; import { getHotSyncManager, hotSyncEnabled, tickHotSyncManagers } from "./hot-sync-manager"; -import { encodeArchivedTurn } from "./continuity-recall"; +import { encodeArchivedTurn, RECALL_TIMEOUT_MS } from "./continuity-recall"; import { existsSync, readFileSync } from "fs"; import path from "path"; import { createHash, randomUUID } from "crypto"; @@ -1568,8 +1568,8 @@ export class RuntimeLifecycleManager { private readonly maxQueueAttempts: number; private timer: NodeJS.Timeout | null = null; private backgroundOperation: Promise | null = null; - /** Background revalidations of cached archive recall; stop() waits for them. */ - private readonly pendingRecalls = new Set>(); + /** Background revalidations of cached archive recall, by approval digest; stop() waits for them. */ + private readonly recallRevalidations = new Map>(); private mutation: Promise = Promise.resolve(); private detachedFlush: Promise | null = null; private readonly claimedQueueItems = new Set(); @@ -1620,7 +1620,7 @@ export class RuntimeLifecycleManager { finally { if (this.backgroundOperation === operation) this.backgroundOperation = null; await this.detachedFlush; - await Promise.allSettled([...this.pendingRecalls]); + await Promise.allSettled([...this.recallRevalidations.values()]); await this.mutation; } } @@ -2320,9 +2320,15 @@ export class RuntimeLifecycleManager { if (!goal || !scope || governor.paused || (!scope.includeWarmMemory && !scope.includeColdMemory)) return; approval = findArchiveRecallApproval(this.deps.paths.state, resolved.profile, workspaceId, goal, event.runtime); if (!approval || !archiveApprovalFitsScope(approval, scope)) return; + // A turn that overlaps the previous turn's revalidation waits for its outcome + // (within the normal deadline), so a refused snapshot is never served twice. + const pending = this.recallRevalidations.get(approval.sha256); + if (pending) await Promise.race([pending, new Promise(resolve => setTimeout(resolve, RECALL_TIMEOUT_MS).unref?.())]); // A snapshot verified on an earlier turn is served now; the hosted call // (which bills and reports superseded records) runs off the critical path. - cached = readCachedArchiveRecall(this.deps.paths.state, resolved.profile, workspaceId, approval); + cached = this.recallRevalidations.has(approval.sha256) || + (resolved.profile.memoryMode !== "assist" && resolved.profile.memoryMode !== "auto") + ? null : readCachedArchiveRecall(this.deps.paths.state, resolved.profile, workspaceId, approval); } catch (error) { response.warnings.push(describeBoundedRecallFallback(error)); return; @@ -2330,20 +2336,22 @@ export class RuntimeLifecycleManager { const { profileName } = resolved; if (cached && cached.snapshot.sources.every(source => source.kind === "warm_memory" ? scope.includeWarmMemory === true : scope.includeColdMemory === true)) { + // The pack billed for this turn is created by the background request; outcomes + // must not be attributed to the earlier pack, so this turn carries no pack id. contextPack.verifiedArchiveContext = renderArchiveRecall(cached.snapshot); - contextPack.packId = cached.packId; try { response.actions.push(this.recordAction({ eventId: event.eventId, profileName, type: "context_pack", status: "completed", mode: response.mode, reason: "Served verified archive recall from the local cache; revalidating", queueItemId: null, - details: { packId: cached.packId, verifiedArchiveRecall: true, cachedArchiveRecall: true }, + details: { cachedPackId: cached.packId, verifiedArchiveRecall: true, cachedArchiveRecall: true }, })); } catch { response.warnings.push("Could not record the hosted archive recall result locally."); } - const revalidation = this.liveArchiveRecall(response, null, resolved, goal, scope, approval) - .catch(() => undefined).finally(() => { this.pendingRecalls.delete(revalidation); }); - this.pendingRecalls.add(revalidation); + const key = approval.sha256; + const revalidation: Promise = this.liveArchiveRecall(response, null, resolved, goal!, scope!, approval) + .catch(() => undefined).finally(() => { if (this.recallRevalidations.get(key) === revalidation) this.recallRevalidations.delete(key); }); + this.recallRevalidations.set(key, revalidation); return; } await this.liveArchiveRecall(response, contextPack, resolved, goal, scope, approval); diff --git a/tests/runtime/hosted-lifecycle-security.test.ts b/tests/runtime/hosted-lifecycle-security.test.ts index ba4aaf5..b05695d 100644 --- a/tests/runtime/hosted-lifecycle-security.test.ts +++ b/tests/runtime/hosted-lifecycle-security.test.ts @@ -387,7 +387,8 @@ describe("verified recall through native prompt preparation", () => { warnings = ["Archive search was skipped."]; let before = (await revalidations()).length; const fromCache = await prepare("incomplete"); - expect(fromCache.packId).toBe(previewPackId); + // Served from the cache; the turn carries no pack id (the billed pack is the background one). + expect(fromCache.packId).toBeNull(); expect(fromCache.contextText).toContain(warm.content); await settled(before); expect((await revalidations()).at(-1)?.details).toMatchObject({ verifiedArchiveRecall: false, cachedArchiveRecall: true }); @@ -439,10 +440,20 @@ describe("verified recall through native prompt preparation", () => { before = (await revalidations()).length; let release: (() => void) | undefined; whenRequested = () => new Promise(resolve => { release = resolve; }); + sources = [cold]; // The server now omits the correction; the cached turn is answered before it knows. const cachedTurn = await Promise.race([prepare("cached-in-flight"), new Promise(resolve => setTimeout(() => resolve(null), 2000))]); expect(cachedTurn?.contextText).toContain(warm.content); await vi.waitFor(() => expect(release).toBeTypeOf("function")); + // An overlapping turn waits for that revalidation instead of serving the cache again. + const firstRelease = release!; + release = undefined; + const overlapping = prepare("overlapping"); + await new Promise(resolve => setTimeout(resolve, 100)); + firstRelease(); + await vi.waitFor(() => expect(release).toBeTypeOf("function")); release!(); + expect((await overlapping).contextText).toBe(baseline.contextText); + sources = [cold, warm]; await settled(before); // Revocation discards the cache, so the next approved turn waits for the live call again. whenRequested = undefined; From 1b68e2ff9379ad41caf29861ef4e99283f82a09b Mon Sep 17 00:00:00 2001 From: Josh Winters Date: Mon, 23 Nov 2026 19:18:50 -0500 Subject: [PATCH 3/3] Recall cache: a recall started before a drop cannot restore the entry; count billed requests From the completion review: - After the 4 s wait times out, a foreground recall can run beside the background revalidation. A per-approval generation, bumped on every drop, stops a late verified result from restoring an entry a newer recall dropped. - The lifecycle test now asserts each served turn made exactly one hosted (billed) request. Known limit: if the daemon stops abruptly mid-revalidation, the entry remains and can serve one more turn within its one-hour window. --- src/runtime/lifecycle-engine.ts | 7 ++++++- tests/runtime/hosted-lifecycle-security.test.ts | 3 +++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/src/runtime/lifecycle-engine.ts b/src/runtime/lifecycle-engine.ts index e0da0e9..0a02bba 100644 --- a/src/runtime/lifecycle-engine.ts +++ b/src/runtime/lifecycle-engine.ts @@ -1570,6 +1570,8 @@ export class RuntimeLifecycleManager { private backgroundOperation: Promise | null = null; /** Background revalidations of cached archive recall, by approval digest; stop() waits for them. */ private readonly recallRevalidations = new Map>(); + /** Bumped whenever a cached snapshot is dropped; a recall started before that may not restore it. */ + private readonly recallCacheGenerations = new Map(); private mutation: Promise = Promise.resolve(); private detachedFlush: Promise | null = null; private readonly claimedQueueItems = new Set(); @@ -2370,6 +2372,7 @@ export class RuntimeLifecycleManager { const { event } = response; const workspaceId = event.workspaceId!; const warnings = target ? response.warnings : []; + const generation = this.recallCacheGenerations.get(approval.sha256) ?? 0; let attemptedProfile: string | null = null; let packId: string | null = null; let verified = false; @@ -2411,7 +2414,8 @@ export class RuntimeLifecycleManager { target.packId = packId; } verified = true; - try { writeCachedArchiveRecall(this.deps.paths.state, currentProfile, currentApproval, snapshot, packId); } + // A concurrent recall that dropped the entry since this one started wins. + try { if ((this.recallCacheGenerations.get(approval.sha256) ?? 0) === generation) writeCachedArchiveRecall(this.deps.paths.state, currentProfile, currentApproval, snapshot, packId); } catch { /* Without a cache entry the next turn waits for the live call, as before. */ } } } @@ -2422,6 +2426,7 @@ export class RuntimeLifecycleManager { } finally { // A cached snapshot that did not verify live is not served again. if (!verified) { + this.recallCacheGenerations.set(approval.sha256, (this.recallCacheGenerations.get(approval.sha256) ?? 0) + 1); try { dropCachedArchiveRecall(this.deps.paths.state, resolved.profile, workspaceId, approval.sha256); } catch { /* The approval digest still guards any later use. */ } } diff --git a/tests/runtime/hosted-lifecycle-security.test.ts b/tests/runtime/hosted-lifecycle-security.test.ts index b05695d..8a7bd9e 100644 --- a/tests/runtime/hosted-lifecycle-security.test.ts +++ b/tests/runtime/hosted-lifecycle-security.test.ts @@ -441,6 +441,7 @@ describe("verified recall through native prompt preparation", () => { let release: (() => void) | undefined; whenRequested = () => new Promise(resolve => { release = resolve; }); sources = [cold]; // The server now omits the correction; the cached turn is answered before it knows. + const requestsBefore = fetcher.mock.calls.length; const cachedTurn = await Promise.race([prepare("cached-in-flight"), new Promise(resolve => setTimeout(() => resolve(null), 2000))]); expect(cachedTurn?.contextText).toContain(warm.content); await vi.waitFor(() => expect(release).toBeTypeOf("function")); @@ -455,6 +456,8 @@ describe("verified recall through native prompt preparation", () => { expect((await overlapping).contextText).toBe(baseline.contextText); sources = [cold, warm]; await settled(before); + // Billing: each served turn made exactly one hosted request (the cached turn in the background, the overlapping one live). + expect(fetcher.mock.calls.length - requestsBefore).toBe(2); // Revocation discards the cache, so the next approved turn waits for the live call again. whenRequested = undefined; await command("revoke", "--task", taskId);