Merge pull request #1054 from avs-io/fix/1051-copilot-rollup-dedup

fix(copilot): prefer lastEventTimestamp for stampless shutdown calls
This commit is contained in:
ozymandiashh 2026-08-21 23:34:19 +03:00 • committed by GitHub
commit 67f085a3c2
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
4 changed files with 67 additions and 7 deletions

View file

@ -759,8 +759,9 @@ function createJsonlParser(
// CUMULATIVE per-model totals. Emitting each rollup whole would need the
// cache to update a prior call in place — the durable merge is
// append-only by dedup key — so we emit per-leg DELTAS keyed by
// occurrence instead: re-parses of a growing file append only the new
// leg, and each leg lands on its own timestamp.
// occurrence (`:n`): re-parses of a growing file append only the new
// leg, and each leg lands on its own timestamp. Discovery only yields
// `<sid>/events.jsonl`, so two journals cannot share a session id.
const prevShutdownUsage = new Map<string, ShutdownModelUsage>()
const shutdownCountByModel = new Map<string, number>()
@ -841,8 +842,14 @@ function createJsonlParser(
const modelMetrics = shutdownData.modelMetrics
if (!isRecord(modelMetrics)) continue
// Prefer lastEventTimestamp over sessionStartTime. sessionStartTime
// is identical for every stampless leg of a resumed session, so
// using it for the call timestamp (or, previously, the key) collapsed
// those legs onto one date. lastEventTimestamp is the last stamped
// event in this journal — distinct per leg when intervening events
// are stamped, and still a real time when they are not.
const shutdownTimestamp =
(event.timestamp ?? '') || timestampToISO(shutdownData.sessionStartTime) || lastEventTimestamp
(event.timestamp ?? '') || lastEventTimestamp || timestampToISO(shutdownData.sessionStartTime)
for (const [model, metrics] of Object.entries(modelMetrics)) {
if (!model || !isRecord(metrics)) continue

View file

@ -292,6 +292,11 @@ export const PROVIDER_PARSE_VERSIONS: Record<string, string> = {
// source-provenance-v1 (#944): CLI sessions were misread as VS Code
// transcripts (both carry producer 'copilot-agent'), skipping the shutdown
// input/cache rollup; this bump re-parses them so the missing tokens land.
// #1051 does NOT bump this again. A fingerprint change drops every present
// Copilot source (parser.ts getOrCreateProviderSection) and would erase
// conversations already pruned from a still-present OTel DB. Old `:n`
// shutdown keys migrate via cachedFileNeedsProviderReparse + a durable
// strip of legacy shutdown calls on that JSONL file only.
copilot: 'cli-shutdown-cost-v1-skills-source-provenance-v1',
// authoritative-usage-v4: persist one Grok session call from top-level
// authoritative totals, use modelUsage only for priced attribution, clamp

View file

@ -14,7 +14,7 @@ import { createRequire } from 'node:module'
import { isSqliteAvailable } from '../src/sqlite.js'
import { clearSessionCache, parseAllSessions, setParseReuseValidator } from '../src/parser.js'
import { loadCache, saveCache } from '../src/session-cache.js'
import { computeEnvFingerprint, loadCache, PROVIDER_PARSE_VERSIONS, saveCache } from '../src/session-cache.js'
import { readCacheOnDisk, writeCacheOnDisk } from './fixtures/session-cache-io.js'
import type { SessionSource, SessionParser, ParsedProviderCall } from '../src/providers/types.js'

View file

@ -706,9 +706,9 @@ describe('copilot provider - session.shutdown token/cost rollup', () => {
it('emits per-leg deltas for a resumed session with cumulative shutdown rollups', async () => {
// Numbers from a real resumed CLI 1.0.78 session (3 legs via --resume):
// each leg appends a session.shutdown whose modelMetrics are CUMULATIVE.
// Emitting deltas keyed by occurrence keeps a growing file append-only
// under the durable union-by-key cache merge — re-parsing after each
// resume adds only the new leg, never double-counting earlier ones.
// Emitting deltas keyed by shutdown timestamp keeps a growing file
// append-only under the durable union-by-key cache merge — re-parsing
// after each resume adds only the new leg, never double-counting earlier ones.
const legs = [
{ inputTokens: 24672, outputTokens: 17, cacheReadTokens: 0, cacheWriteTokens: 24670 },
{ inputTokens: 74463, outputTokens: 149, cacheReadTokens: 49489, cacheWriteTokens: 24968 },
@ -803,6 +803,54 @@ describe('copilot provider - session.shutdown token/cost rollup', () => {
expect(second).toHaveLength(0)
})
it('keeps three stampless shutdown legs as :n keys with lastEventTimestamp, not sessionStartTime', async () => {
// sessionStartTime is identical on every leg. Putting it in the key (or
// preferring it over lastEventTimestamp for the call timestamp) collapses
// a 3-leg journal onto one row. Discovery only yields events.jsonl, so
// two-journal fixtures are unreachable; this is the reachable class.
const lastEvent = '2026-08-01T10:00:15Z'
const sessionStartTime = 1784102040274
const stamplessShutdown = (usage: {
inputTokens: number
outputTokens: number
cacheReadTokens: number
cacheWriteTokens: number
}) => JSON.stringify({
type: 'session.shutdown',
data: {
shutdownType: 'routine',
sessionStartTime,
modelMetrics: {
'claude-sonnet-5': {
requests: { count: 1, cost: 1 },
usage: { ...usage, reasoningTokens: 0 },
},
},
},
})
const eventsPath = await createSessionDir('sess-stampless', [
modelChange('claude-sonnet-5'),
assistantMessage({ messageId: 'msg-1', outputTokens: 10, timestamp: lastEvent }),
stamplessShutdown({ inputTokens: 3000, outputTokens: 10, cacheReadTokens: 1000, cacheWriteTokens: 500 }),
stamplessShutdown({ inputTokens: 7000, outputTokens: 20, cacheReadTokens: 3000, cacheWriteTokens: 1000 }),
stamplessShutdown({ inputTokens: 10000, outputTokens: 30, cacheReadTokens: 5000, cacheWriteTokens: 1500 }),
])
const calls = await collectCalls({ path: eventsPath, project: 'myproject', provider: 'copilot', sourceType: 'jsonl' })
const shutdowns = calls.filter(c => c.deduplicationKey.includes(':shutdown:'))
expect(shutdowns.map(c => c.deduplicationKey)).toEqual([
'copilot:sess-stampless:shutdown:claude-sonnet-5:1',
'copilot:sess-stampless:shutdown:claude-sonnet-5:2',
'copilot:sess-stampless:shutdown:claude-sonnet-5:3',
])
expect(shutdowns.map(c => c.timestamp)).toEqual([lastEvent, lastEvent, lastEvent])
expect(shutdowns[0]!.inputTokens).toBe(1500)
expect(shutdowns[1]!.inputTokens).toBe(1500)
expect(shutdowns[2]!.inputTokens).toBe(500)
expect(shutdowns.reduce((a, c) => a + c.inputTokens, 0)).toBe(3500)
expect(shutdowns.reduce((a, c) => a + c.cacheReadInputTokens, 0)).toBe(5000)
expect(shutdowns.reduce((a, c) => a + c.cacheCreationInputTokens, 0)).toBe(1500)
})
it('falls back to the last stamped event when shutdown carries no timestamp at all', async () => {
// A shutdown with neither its own timestamp nor sessionStartTime must not
// yield an empty-timestamp call: the date-range filters in parser.ts drop