From 6ff7204e347da4f16c385501cb44d3fbbed30c26 Mon Sep 17 00:00:00 2001 From: Resham Joshi <65915470+iamtoruk@users.noreply.github.com> Date: Thu, 5 Nov 2026 22:55:40 +0100 Subject: [PATCH] fix(desktop): keep the sessions answer under the pipe cap (#1889) The Sessions drill-through asks for contribution segments over the whole population, and over all time that answer is 28MB, past the 16MiB cap: the request failed and the resident child was killed with it. The CLI now answers one of n fixed slices with --part i/n, keyed by session identity so a re-derived report never duplicates or drops a row, and the bridge fetches eight slices in turn and restores the report order. The renderer receives the same rows in the same order as before. --- app/electron/bridge-handlers.ts | 31 ++++++++++++++++---- app/electron/main.test.ts | 44 ++++++++++++++++++++++------- src/main.ts | 11 ++++++-- src/serve.ts | 2 +- src/session-contributions.ts | 24 ++++++++++++++++ tests/session-contributions.test.ts | 28 +++++++++++++++++- 6 files changed, 120 insertions(+), 20 deletions(-) diff --git a/app/electron/bridge-handlers.ts b/app/electron/bridge-handlers.ts index f5ec0b4e..aea09444 100644 --- a/app/electron/bridge-handlers.ts +++ b/app/electron/bridge-handlers.ts @@ -462,6 +462,11 @@ export type Deps = { export type Handler = (...args: any[]) => Promise +// Measured on a 23GB corpus, the all-time drill-through report is 28MB and its +// largest single row 4.3MB, which no slicing can split; eight slices keep the +// largest answer near 7MB, under half the 16MiB cap. +const CONTRIBUTION_PARTS = 8 + /** * Maps every CodeburnBridge channel to its `codeburn` argv (plain args, no * shell) and returns a result envelope. Pure + injectable so the wiring is @@ -740,12 +745,26 @@ export function createBridgeHandlers(deps: Deps): Record { // Drill-through report: plain session rows plus per-turn contribution // segments (day/category/branch/model/PR). Same filtering semantics as // getSessions — one filtering mechanism, additive payload fields only. - 'codeburn:getSessionsContributions': run((period: string, provider: string, range?: DateRange) => [ - 'sessions', '--format', 'json', '--contributions', '--period', vPeriod(period), - ...providerArgs(vProvider(provider)), - ...projectArgs(), - ...rangeArgs(vRange(range)), - ], 3), + // The renderer computes every selection over the whole population, which + // over all time is ~28MB, past the pipe cap. So it is fetched in fixed + // slices, one after another (in parallel they would be parallel spawns on + // the fallback path), and put back in report order here. + 'codeburn:getSessionsContributions': async (period: string, provider: string, range?: DateRange, background?: boolean) => { + const entries: Array<{ index: number; row: unknown }> = [] + for (let part = 0; part < CONTRIBUTION_PARTS; part++) { + const slice = await run((p: string, pv: string, r?: DateRange) => [ + 'sessions', '--format', 'json', '--contributions', '--period', vPeriod(p), + ...providerArgs(vProvider(pv)), + ...projectArgs(), + ...rangeArgs(vRange(r)), + '--part', `${part}/${CONTRIBUTION_PARTS}`, + ], 3)(period, provider, range, background) + if (!slice.ok) return slice + if (!Array.isArray(slice.value)) return { ok: false, error: { kind: 'bad-json', message: 'codeburn sessions --part did not answer a list' } } + entries.push(...slice.value as typeof entries) + } + return { ok: true, value: entries.sort((a, b) => a.index - b.index).map(entry => entry.row) } + }, // One session's cost diagnosis. Reads that transcript's content on demand; // never routed through serve (its output memo would hold the text). 'codeburn:getSessionWhy': run((id: string) => ['sessions', '--id', vToken(id), '--why', '--format', 'json']), diff --git a/app/electron/main.test.ts b/app/electron/main.test.ts index 30475dc7..9c2a551c 100644 --- a/app/electron/main.test.ts +++ b/app/electron/main.test.ts @@ -130,8 +130,8 @@ const ARGV_CASES: Array<{ channel: string; args: unknown[]; argv: string[] }> = { channel: 'codeburn:getModels', args: ['week', 'all', false], argv: ['models', '--format', 'json', '--period', 'week', '--min-cost', '0'] }, { channel: 'codeburn:getSessions', args: ['week', 'all'], argv: ['sessions', '--format', 'json', '--period', 'week'] }, { channel: 'codeburn:getSessions', args: ['30days', 'claude', { from: '2026-07-01', to: '2026-07-11' }], argv: ['sessions', '--format', 'json', '--period', '30days', '--provider', 'claude', '--from', '2026-07-01', '--to', '2026-07-11'] }, - { channel: 'codeburn:getSessionsContributions', args: ['week', 'all'], argv: ['sessions', '--format', 'json', '--contributions', '--period', 'week'] }, - { channel: 'codeburn:getSessionsContributions', args: ['30days', 'claude', { from: '2026-07-01', to: '2026-07-11' }], argv: ['sessions', '--format', 'json', '--contributions', '--period', '30days', '--provider', 'claude', '--from', '2026-07-01', '--to', '2026-07-11'] }, + { channel: 'codeburn:getSessionsContributions', args: ['week', 'all'], argv: ['sessions', '--format', 'json', '--contributions', '--period', 'week', '--part', '0/8'] }, + { channel: 'codeburn:getSessionsContributions', args: ['30days', 'claude', { from: '2026-07-01', to: '2026-07-11' }], argv: ['sessions', '--format', 'json', '--contributions', '--period', '30days', '--provider', 'claude', '--from', '2026-07-01', '--to', '2026-07-11', '--part', '0/8'] }, { channel: 'codeburn:getSessionWhy', args: ['7f3c2a91-4be0'], argv: ['sessions', '--id', '7f3c2a91-4be0', '--why', '--format', 'json'] }, { channel: 'codeburn:getCompareModels', args: ['month', 'codex'], argv: ['compare', '--format', 'json', '--period', 'month', '--provider', 'codex'] }, { channel: 'codeburn:getCompare', args: ['month', 'all', 'model-a', 'model-b'], argv: ['compare', '--format', 'json', '--period', 'month', '--model-a', 'model-a', '--model-b', 'model-b'] }, @@ -215,13 +215,37 @@ describe('createBridgeHandlers (channel → argv for all channels)', () => { }) it.each(ARGV_CASES)('$channel with $args spawns the expected argv', async ({ channel, args, argv }) => { - const { spawnCli, spawnCliAction, calls } = fakeSpawn() + const { spawnCli, spawnCliAction, calls } = fakeSpawn(channel === 'codeburn:getSessionsContributions' ? [] : undefined) const handlers = createBridgeHandlers(deps({ spawnCli, spawnCliAction, resolveCodeburnPath: () => '/bin/codeburn' })) const res = await handlers[channel]!(...args) expect(calls[0]).toEqual(argv) expect(res).toMatchObject({ ok: true }) }) + it('codeburn:getSessionsContributions joins its slices back into report order', async () => { + const slices: Record = { + '0/8': [{ index: 2, row: { sessionId: 'c' } }], + '2/8': [{ index: 0, row: { sessionId: 'a' } }, { index: 3, row: { sessionId: 'd' } }], + '7/8': [{ index: 1, row: { sessionId: 'b' } }], + } + const spawnCli = vi.fn(async (args: string[]) => slices[args[args.length - 1]!] ?? []) + const handlers = createBridgeHandlers(deps({ spawnCli })) + const res = await handlers['codeburn:getSessionsContributions']!('all', 'all') + expect(spawnCli).toHaveBeenCalledTimes(8) + expect(res).toEqual({ ok: true, value: [{ sessionId: 'a' }, { sessionId: 'b' }, { sessionId: 'c' }, { sessionId: 'd' }] }) + }) + + it('codeburn:getSessionsContributions fails whole when one slice fails', async () => { + const spawnCli = vi.fn(async (args: string[]) => { + if (args.includes('1/8')) throw new CliError('timeout', 'slow') + return [] + }) + const handlers = createBridgeHandlers(deps({ spawnCli })) + const res = await handlers['codeburn:getSessionsContributions']!('all', 'all') + expect(res).toMatchObject({ ok: false }) + expect(spawnCli).toHaveBeenCalledTimes(2) + }) + it('codeburn:cliStatus resolves from resolveCodeburnPath without spawning', async () => { const spawnCli = vi.fn() const handlers = createBridgeHandlers(deps({ spawnCli, resolveCodeburnPath: () => '/opt/homebrew/bin/codeburn' })) @@ -996,27 +1020,27 @@ describe('project filter', () => { .toEqual({ project: ['my-company'], exclude: ['scratch'] }) expect(readProjectFilter()).toEqual({ project: ['my-company'], exclude: ['scratch'] }) - const { spawnCli, spawnCliAction, calls } = fakeSpawn() + const { spawnCli, spawnCliAction, calls } = fakeSpawn([]) const handlers = createBridgeHandlers(deps({ spawnCli, spawnCliAction, resolveCodeburnPath: () => '/bin/codeburn' })) await handlers['codeburn:getSessions']!('week', 'all') expect(calls[0]).toEqual(['sessions', '--format', 'json', '--period', 'week', '--project=my-company', '--exclude=scratch']) await handlers['codeburn:getSessionsContributions']!('week', 'all') - expect(calls[1]).toEqual(['sessions', '--format', 'json', '--contributions', '--period', 'week', '--project=my-company', '--exclude=scratch']) + expect(calls.slice(1, 9)).toEqual([0, 1, 2, 3, 4, 5, 6, 7].map(part => ['sessions', '--format', 'json', '--contributions', '--period', 'week', '--project=my-company', '--exclude=scratch', '--part', `${part}/8`])) await handlers['codeburn:getBranchSpend']!('week', 'all') - expect(calls[2]).toEqual(['spend', '--format', 'branch-json', '--period', 'week', '--project=my-company', '--exclude=scratch']) + expect(calls[9]).toEqual(['spend', '--format', 'branch-json', '--period', 'week', '--project=my-company', '--exclude=scratch']) const rangeA = { from: '2026-07-01', to: '2026-07-07' } const rangeB = { from: '2026-07-08', to: '2026-07-14' } await handlers['codeburn:getPeriodCompare']!(rangeA, rangeB, 'all') - expect(calls[3]).toEqual(['compare-periods', '--format', 'json', '--from-a', '2026-07-01', '--to-a', '2026-07-07', '--from-b', '2026-07-08', '--to-b', '2026-07-14', '--project=my-company', '--exclude=scratch']) + expect(calls[10]).toEqual(['compare-periods', '--format', 'json', '--from-a', '2026-07-01', '--to-a', '2026-07-07', '--from-b', '2026-07-08', '--to-b', '2026-07-14', '--project=my-company', '--exclude=scratch']) // The drill-down too: a filtered-out project must not surface behind a // contribution row either. await handlers['codeburn:getPeriodCompareSessions']!(rangeA, rangeB, 'all', 'model', 'sonnet') - expect(calls[4]).toEqual(['compare-periods', '--format', 'sessions', '--from-a', '2026-07-01', '--to-a', '2026-07-07', '--from-b', '2026-07-08', '--to-b', '2026-07-14', '--project=my-company', '--exclude=scratch', '--dimension', 'model', '--key', 'sonnet']) + expect(calls[11]).toEqual(['compare-periods', '--format', 'sessions', '--from-a', '2026-07-01', '--to-a', '2026-07-07', '--from-b', '2026-07-08', '--to-b', '2026-07-14', '--project=my-company', '--exclude=scratch', '--dimension', 'model', '--key', 'sonnet']) await handlers['codeburn:getCompareCohortModels']!('week', 'all') - expect(calls[5]).toEqual(['compare', '--format', 'cohort-json', '--period', 'week', '--project=my-company', '--exclude=scratch']) + expect(calls[12]).toEqual(['compare', '--format', 'cohort-json', '--period', 'week', '--project=my-company', '--exclude=scratch']) // --project-id narrows WITHIN the saved filter; it never replaces it. await handlers['codeburn:getCompareCohort']!('week', 'all', 'model-a', 'model-b', undefined, ['/Users/gone/alpha']) - expect(calls[6]).toEqual([ + expect(calls[13]).toEqual([ 'compare', '--format', 'cohort-json', '--period', 'week', '--project=my-company', '--exclude=scratch', '--model-a', 'model-a', '--model-b', 'model-b', '--project-id=/Users/gone/alpha', ]) diff --git a/src/main.ts b/src/main.ts index 0376493f..e9e07f43 100644 --- a/src/main.ts +++ b/src/main.ts @@ -3192,6 +3192,7 @@ program .option('--by-pr', 'Group spend by the pull requests each session referenced') .option('--by-work-unit', 'Group sessions into provider-recorded work units: one row per orchestration root with its delegated children folded beneath') .option('--contributions', 'JSON only: attach per-session contribution segments (day, category, branch, model, PR) to each row') + .option('--part ', 'With --contributions: only slice i of n (0-based), as {index, row} entries in report order') .option('--id ', 'With --why: the Claude Code session to explain') .option('--why', 'Explain why one session cost what it did: findings, spend by prompt, steps (needs --id; Claude Code only)') .option('--no-pager', 'Print the complete table directly instead of opening the interactive browser') @@ -3222,6 +3223,11 @@ program process.stderr.write('codeburn: --contributions requires plain --format json (no --by-pr/--by-work-unit)\n') process.exit(1) } + const part = opts.part === undefined ? null : (await import('./session-contributions.js')).parseContributionPart(opts.part) + if (opts.part !== undefined && (!opts.contributions || !part)) { + process.stderr.write('codeburn: --part takes i/n (0 <= i < n <= 64) and requires --contributions\n') + process.exit(1) + } const { aggregateSessions, buildPrAttribution, foldSubagentRows, renderJson, renderTable, renderWorkUnitJson, renderWorkUnitTable } = await import('./sessions-report.js') const wantsInteractive = opts.format === 'table' && !opts.byPr && !opts.byWorkUnit && opts.pager !== false && process.stdin.isTTY === true && process.stdout.isTTY === true if (wantsInteractive) setInteractiveScanUI() @@ -3304,8 +3310,9 @@ program lineage: session.lineage, })))) if (opts.contributions) { - const { foldContributionRows, withContributions } = await import('./session-contributions.js') - process.stdout.write(JSON.stringify(foldContributionRows(withContributions(rows, projects), resolution), null, 2) + '\n') + const { foldContributionRows, selectContributionPart, withContributions } = await import('./session-contributions.js') + const report = foldContributionRows(withContributions(rows, projects), resolution) + process.stdout.write(JSON.stringify(part ? selectContributionPart(report, part) : report, null, 2) + '\n') return } if (opts.byWorkUnit) { diff --git a/src/serve.ts b/src/serve.ts index 07608561..8cae97d1 100644 --- a/src/serve.ts +++ b/src/serve.ts @@ -273,7 +273,7 @@ const SERVE_OPTIONS: Readonly= 1 && count <= 64 && index < count ? { index, count } : null +} + +export function contributionPart(row: SessionRow, count: number): number { + return createHash('sha1').update(JSON.stringify([row.provider, row.project, row.sessionId])).digest().readUInt32BE(0) % count +} + +export function selectContributionPart(rows: SessionDrillRow[], part: { index: number; count: number }): Array<{ index: number; row: SessionDrillRow }> { + return rows.flatMap((row, index) => contributionPart(row, part.count) === part.index ? [{ index, row }] : []) +} diff --git a/tests/session-contributions.test.ts b/tests/session-contributions.test.ts index e8fb8f58..59d66f33 100644 --- a/tests/session-contributions.test.ts +++ b/tests/session-contributions.test.ts @@ -5,7 +5,8 @@ import { join } from 'node:path' import { describe, expect, it } from 'vitest' -import { buildSessionContributions, withContributions } from '../src/session-contributions.js' +import { buildSessionContributions, parseContributionPart, selectContributionPart, withContributions } from '../src/session-contributions.js' +import type { SessionDrillRow } from '../src/session-contributions.js' import { aggregateSessions } from '../src/sessions-report.js' import { dateKey } from '../src/day-aggregator.js' import { aggregateProjectsIntoDays } from '../src/day-aggregator.js' @@ -328,6 +329,31 @@ describe('withContributions', () => { }) }) +describe('contributions report slices (--part)', () => { + const row = (sessionId: string, cost: number) => ({ provider: 'claude', project: 'p', sessionId, cost }) as unknown as SessionDrillRow + + it('partitions the report by identity and keeps each row\'s report position', () => { + const report = Array.from({ length: 200 }, (_, i) => row(`s${i}`, i)) + const slices = [0, 1, 2, 3].map(index => selectContributionPart(report, { index, count: 4 })) + expect(slices.every(slice => slice.length > 0)).toBe(true) + const joined = slices.flat().sort((a, b) => a.index - b.index) + expect(joined.map(entry => entry.row)).toEqual(report) + }) + + it('keeps a session in its slice when the report is re-derived in another order', () => { + const report = Array.from({ length: 50 }, (_, i) => row(`s${i}`, i)) + const reordered = [...report].reverse() + const ids = (rows: SessionDrillRow[]) => new Set(selectContributionPart(rows, { index: 1, count: 4 }).map(entry => entry.row.sessionId)) + expect(ids(reordered)).toEqual(ids(report)) + }) + + it('accepts only i/n with 0 <= i < n <= 64', () => { + expect(parseContributionPart('0/4')).toEqual({ index: 0, count: 4 }) + expect(parseContributionPart('3/4')).toEqual({ index: 3, count: 4 }) + for (const bad of ['4/4', '0/0', '1/65', '-1/4', '1', 'a/b', '1/4/2']) expect(parseContributionPart(bad)).toBeNull() + }) +}) + describe('sessions --contributions CLI flag', () => { it('emits drill rows whose segments reconcile to the session cost', async () => { const home = await mkdtemp(join(tmpdir(), 'codeburn-contributions-'))