diff --git a/docs/HOT-SYNC.md b/docs/HOT-SYNC.md index 3369a89..524688f 100644 --- a/docs/HOT-SYNC.md +++ b/docs/HOT-SYNC.md @@ -63,6 +63,18 @@ 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 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 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..7e3ea16 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,64 @@ 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); + // 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; +} + +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..0a02bba 100644 --- a/src/runtime/lifecycle-engine.ts +++ b/src/runtime/lifecycle-engine.ts @@ -1,9 +1,10 @@ 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"; -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"; @@ -1567,6 +1568,10 @@ export class RuntimeLifecycleManager { private readonly maxQueueAttempts: number; private timer: NodeJS.Timeout | null = null; 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(); @@ -1617,6 +1622,7 @@ export class RuntimeLifecycleManager { finally { if (this.backgroundOperation === operation) this.backgroundOperation = null; await this.detachedFlush; + await Promise.allSettled([...this.recallRevalidations.values()]); await this.mutation; } } @@ -2302,22 +2308,77 @@ 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 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 = 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; + } + 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); + 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: { cachedPackId: cached.packId, verifiedArchiveRecall: true, cachedArchiveRecall: true }, + })); + } catch { + response.warnings.push("Could not record the hosted archive recall result locally."); + } + 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); + } + /** + * 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 : []; + const generation = this.recallCacheGenerations.get(approval.sha256) ?? 0; + 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 +2409,47 @@ 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; + // 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. */ } } } - 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) { + 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. */ } + } 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..8a7bd9e 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,15 @@ 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"); + // 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 }); + // 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 +415,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 +436,33 @@ 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; }); + 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")); + // 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); + // 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); + await approve(await preview("--host", runtime), "--host", runtime); + release = undefined; whenRequested = () => new Promise(resolve => { release = resolve; }); const inFlight = prepare("in-flight"); try {