From 22a8405d28a95b326293bfe05789d72d3a7e2a93 Mon Sep 17 00:00:00 2001 From: iamtoruk Date: Wed, 19 Aug 2026 12:32:39 -0700 Subject: [PATCH] fix(cache): keep durable history when a bump meets an extant, pruned source MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A parse-version or env-fingerprint change rebuilds the provider section, and the durable carry-forward only kept entries whose source PATH had disappeared. A durable SQLite source does not disappear: copilot's agent-traces.db and session-store.db keep their file while the CLI prunes rows out of them. So "the path exists" was being read as "the source can re-derive this", and the bump deleted, permanently, exactly the history only the cache still held. Carry every durable entry forward. For a source still on disk, park an impossible fingerprint on it so the new parse version re-reads it in full; the durable union merge then appends only turns whose dedup keys are not already cached, which adds what the source still holds without duplicating it or deleting what it has lost. The persisted `durable` flag is carried too, so the orphan bootstrap does not have to wait for the section to be re-stamped. The contract this rests on is stated at the site: a parse-version bump must not re-key calls the source can still re-derive, or the union counts them twice. (f2) pins both directions on the reviewer's shape — a pruned-but-extant DB keeps its history across a bump, served AND persisted, and an intact DB re-read under the same bump does not double. --- src/parser.ts | 29 ++++++++++++---- tests/parser.test.ts | 79 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 102 insertions(+), 6 deletions(-) diff --git a/src/parser.ts b/src/parser.ts index 582e9a71..7597583d 100644 --- a/src/parser.ts +++ b/src/parser.ts @@ -2932,14 +2932,31 @@ function getOrCreateProviderSection(cache: SessionCache, provider: string): Prov const section: ProviderSection = { envFingerprint: envFp, files: {} } // A fingerprint change (env override or parse-version bump) must re-parse // every present source, but for durable providers the cache is the ONLY - // remaining record of usage whose source rows were already pruned (OTel - // orphans). Discarding those with the section would permanently erase - // month-to-date history that cannot be re-derived, so carry forward exactly - // the entries whose source no longer exists; everything present on disk is - // dropped and re-parsed under the new fingerprint. + // remaining record of usage whose source rows were already pruned. Dropping + // an entry because its FILE still exists is not the same question: a + // still-present OTel/session-store DB routinely keeps its file while the CLI + // prunes rows out of it, so "path exists" was being read as "the source can + // re-derive this", and the bump silently deleted history nothing could + // rebuild (#946 review). Present or absent, the entry is carried forward; + // a present source additionally gets an impossible fingerprint parked on it + // so the new parse version re-reads it in full. The durable union merge + // appends only turns whose dedup keys are not already cached, so the re-read + // ADDS whatever the source still holds without duplicating or deleting what + // it has already lost. + // + // The contract this rests on: a parse-version bump must not RE-KEY calls the + // source can still re-derive. Same event, same deduplicationKey, or the + // union counts it twice. Changing a provider's key shape is therefore a + // cache-version (CACHE_VERSION) change, not a parse-version change. if (existing && DURABLE_PROVIDER_NAMES.has(provider)) { + if (existing.durable) section.durable = true for (const [path, file] of Object.entries(existing.files)) { - if (!existsSync(path)) section.files[path] = file + if (!existsSync(path)) { + section.files[path] = file + continue + } + const { lastCompleteLineOffset: _resumeOffset, failed: _failed, ...rest } = file + section.files[path] = { ...rest, fingerprint: { dev: 0, ino: 0, mtimeMs: 0, sizeBytes: -1 } } } } cache.providers[provider] = section diff --git a/tests/parser.test.ts b/tests/parser.test.ts index 423fc4a4..8523b95c 100644 --- a/tests/parser.test.ts +++ b/tests/parser.test.ts @@ -617,6 +617,85 @@ describe('(f) durable orphans survive a parse-version bump', () => { }) }) +// ═══════════════════════════════════════════════════════════════════════════ +// (f2) Version-bump survival for an EXTANT-but-pruned durable DB. The orphan +// carry-forward in (f) keyed on "the source path is gone", but a durable +// SQLite source keeps its file forever while the CLI prunes rows out of +// it — so a parse-version bump was deleting exactly the history only the +// cache still held (#946 review, blocker 1). Also pins the other +// direction: an intact source re-read under the bump must not DOUBLE, +// which is the dedup-key-stability contract the union merge rests on. +// ═══════════════════════════════════════════════════════════════════════════ +describe.skipIf(!isSqliteAvailable())('(f2) durable history survives a bump on an extant, pruned DB', () => { + const stubOtelOnly = (dbPath: string): void => { + vi.stubEnv('CODEBURN_COPILOT_OTEL_DB', dbPath) + vi.stubEnv('CODEBURN_COPILOT_DISABLE_OTEL', '') + vi.stubEnv('CODEBURN_COPILOT_SESSION_STATE_DIR', join(tmpHome, 'no-jsonl')) + vi.stubEnv('CODEBURN_COPILOT_WS_STORAGE_DIR', join(tmpHome, 'no-ws')) + } + + // Take the same code path a real PROVIDER_PARSE_VERSIONS bump takes: any + // mismatching persisted envFingerprint rebuilds the provider section. + const simulateVersionBump = async (): Promise => { + clearSessionCache() + const disk = await readCacheOnDisk() + expect(disk.providers['copilot']).toBeDefined() + disk.providers['copilot']!.envFingerprint = '0000000000000000' + await writeCacheOnDisk(disk) + } + + it('keeps a pruned conversation whose DB file still exists', async () => { + const dbPath = join(tmpHome, 'agent-traces.db') + stubOtelOnly(dbPath) + + createOtelDb(dbPath) + insertOtelConv(dbPath, { spanId: 's1', traceId: 't1', convId: 'bump-c1', model: 'gpt-4.1', input: 500, output: 50 }) + insertOtelConv(dbPath, { spanId: 's2', traceId: 't2', convId: 'bump-c2', model: 'gpt-4.1', input: 1000, output: 100 }) + expect(totalOutput(await parseAllSessions(undefined, 'copilot'))).toBe(150) + + // The CLI prunes conv-1. The DB file is still there, still valid, just + // smaller — the shape that "carry forward only vanished paths" missed. + clearSessionCache() + await rm(dbPath) + createOtelDb(dbPath) + insertOtelConv(dbPath, { spanId: 's2', traceId: 't2', convId: 'bump-c2', model: 'gpt-4.1', input: 1000, output: 100 }) + expect(totalOutput(await parseAllSessions(undefined, 'copilot'))).toBe(150) + + await simulateVersionBump() + + // The bump re-reads the live DB (conv-2) and unions it with the cached + // conv-1 the DB can no longer produce. Nothing is lost, nothing doubles. + expect(totalOutput(await parseAllSessions(undefined, 'copilot'))).toBe(150) + + // And it is PERSISTED, not just served: a cold read of the rewritten + // cache still has it, otherwise the loss is merely deferred one run. + clearSessionCache() + expect(totalOutput(await parseAllSessions(undefined, 'copilot'))).toBe(150) + const disk = await readCacheOnDisk() + const keys = Object.values(disk.providers['copilot']?.files ?? {}) + .flatMap(f => f.turns).flatMap(t => t.calls).map(c => c.deduplicationKey) + expect(keys).toContain('copilot-otel:s1') + }) + + it('does not double an intact DB re-read under the bump', async () => { + const dbPath = join(tmpHome, 'agent-traces-intact.db') + stubOtelOnly(dbPath) + + createOtelDb(dbPath) + insertOtelConv(dbPath, { spanId: 's1', traceId: 't1', convId: 'intact-c1', model: 'gpt-4.1', input: 500, output: 50 }) + insertOtelConv(dbPath, { spanId: 's2', traceId: 't2', convId: 'intact-c2', model: 'gpt-4.1', input: 1000, output: 100 }) + expect(totalOutput(await parseAllSessions(undefined, 'copilot'))).toBe(150) + + await simulateVersionBump() + + // Every row is still derivable, so the union must recognise all of them + // by dedup key and append nothing. + expect(totalOutput(await parseAllSessions(undefined, 'copilot'))).toBe(150) + clearSessionCache() + expect(totalOutput(await parseAllSessions(undefined, 'copilot'))).toBe(150) + }) +}) + // ═══════════════════════════════════════════════════════════════════════════ // (g) Skill attribution is independent of turn category // ═══════════════════════════════════════════════════════════════════════════