diff --git a/src/main/stats/collector.test.ts b/src/main/stats/collector.test.ts new file mode 100644 index 000000000..e794b35cd --- /dev/null +++ b/src/main/stats/collector.test.ts @@ -0,0 +1,77 @@ +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs' +import { tmpdir } from 'os' +import { join } from 'path' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { StatsEvent } from './types' + +const { getPathMock } = vi.hoisted(() => ({ + getPathMock: vi.fn<() => string>() +})) + +vi.mock('electron', () => ({ + app: { + getPath: getPathMock + } +})) + +let tempRoot: string + +async function loadCollectorModule() { + vi.resetModules() + return await import('./collector') +} + +function getStatsFile(): string { + return join(tempRoot, 'orca-stats.json') +} + +beforeEach(() => { + tempRoot = mkdtempSync(join(tmpdir(), 'orca-stats-collector-')) + getPathMock.mockReturnValue(tempRoot) +}) + +afterEach(() => { + vi.useRealTimers() + vi.restoreAllMocks() + rmSync(tempRoot, { recursive: true, force: true }) +}) + +describe('StatsCollector persistence', () => { + it('trims the event log while preserving lifetime aggregates', async () => { + const { StatsCollector, initStatsPath } = await loadCollectorModule() + initStatsPath() + const collector = new StatsCollector() + + for (let index = 0; index < 1205; index++) { + collector.record({ + type: 'agent_start', + at: 1760000000000 + index, + meta: { ptyId: `pty-${index}`, note: index === 700 ? 'é漢字😀'.repeat(128) : 'plain' } + } satisfies StatsEvent) + } + + collector.flush() + + const stats = JSON.parse(readFileSync(getStatsFile(), 'utf8')) + expect(stats.events).toHaveLength(1000) + expect(stats.events[0].meta.ptyId).toBe('pty-205') + expect(stats.events.at(-1).meta.ptyId).toBe('pty-1204') + expect(stats.aggregates.totalAgentsSpawned).toBe(1205) + expect(stats.aggregates.firstEventAt).toBe(1760000000000) + }) + + it('does not throw from flush when stats cannot be written', async () => { + const blockedUserDataPath = join(tempRoot, 'not-a-directory') + writeFileSync(blockedUserDataPath, 'file blocks directory creation') + getPathMock.mockReturnValue(blockedUserDataPath) + const { StatsCollector, initStatsPath } = await loadCollectorModule() + initStatsPath() + const collector = new StatsCollector() + const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) + + collector.record({ type: 'agent_start', at: 1760000000000, meta: { ptyId: 'pty-1' } }) + + expect(() => collector.flush()).not.toThrow() + expect(errorSpy).toHaveBeenCalledWith('[stats] Failed to write stats:', expect.anything()) + }) +}) diff --git a/src/main/stats/collector.ts b/src/main/stats/collector.ts index 7b7891add..7c5e67c6f 100644 --- a/src/main/stats/collector.ts +++ b/src/main/stats/collector.ts @@ -1,11 +1,16 @@ import { app } from 'electron' -import { readFileSync, writeFileSync, mkdirSync, existsSync, renameSync } from 'fs' +import { readFileSync, mkdirSync, existsSync, renameSync } from 'fs' import { join, dirname } from 'path' import type { StatsSummary } from '../../shared/types' +import { writeJsonInChunks } from './stats-json-writer' import type { StatsEvent, StatsAggregates, StatsFile } from './types' const STATS_SCHEMA_VERSION = 1 -const MAX_EVENTS = 10_000 +// Why 1000 (was 10000): the events array is a bounded "fun stats" log. A smaller +// cap bounds the JSON written on each save which, together with the chunked write +// in writeToDiskSync, keeps Orca clear of an Electron/Node abort when encoding a +// very large string to UTF-8 (see writeJsonInChunks). +const MAX_EVENTS = 1_000 // Why: countedPRs is a deduplication registry that grows with every PR created // through Orca. Without a cap, a heavily-used instance accumulates thousands of // URL strings across months. 2000 entries is about 6-12 months of active use @@ -149,7 +154,7 @@ export class StatsCollector { this.onAgentStop(ptyId, now) } this.cancelPendingSave() - this.writeToDiskSync() + this.writeToDiskBestEffort() } // ── Persistence ─────────────────────────────────────────────────── @@ -226,11 +231,7 @@ export class StatsCollector { } this.writeTimer = setTimeout(() => { this.writeTimer = null - try { - this.writeToDiskSync() - } catch (err) { - console.error('[stats] Failed to write stats:', err) - } + this.writeToDiskBestEffort() }, DEBOUNCE_MS) } @@ -241,6 +242,16 @@ export class StatsCollector { } } + private writeToDiskBestEffort(): void { + try { + this.writeToDiskSync() + } catch (err) { + // Why best-effort: stats are non-critical. Catchable disk errors should + // not crash shutdown; native Electron CHECK aborts are avoided upstream. + console.error('[stats] Failed to write stats:', err) + } + } + private writeToDiskSync(): void { const statsFile = getStatsFile() const dir = dirname(statsFile) @@ -262,7 +273,7 @@ export class StatsCollector { // Why unique temp file: same race-safe pattern as persistence.ts:120 — // synchronous flushes can race the debounced writer during shutdown. const tmpFile = `${statsFile}.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp` - writeFileSync(tmpFile, JSON.stringify(data), 'utf-8') + writeJsonInChunks(tmpFile, JSON.stringify(data)) renameSync(tmpFile, statsFile) } } diff --git a/src/main/stats/stats-json-writer.test.ts b/src/main/stats/stats-json-writer.test.ts new file mode 100644 index 000000000..5a5637a07 --- /dev/null +++ b/src/main/stats/stats-json-writer.test.ts @@ -0,0 +1,61 @@ +import { mkdtempSync, readFileSync, rmSync } from 'fs' +import { tmpdir } from 'os' +import { join } from 'path' +import { afterEach, describe, expect, it } from 'vitest' +import { writeJsonInChunks } from './stats-json-writer' + +let tempDirs: string[] = [] + +afterEach(() => { + for (const dir of tempDirs) { + rmSync(dir, { recursive: true, force: true }) + } + tempDirs = [] +}) + +function getTempFile(name: string): string { + const dir = mkdtempSync(join(tmpdir(), 'orca-stats-json-writer-')) + tempDirs.push(dir) + return join(dir, name) +} + +function expectChunkedWriteToPreserveBytes(name: string, json: string): void { + const file = getTempFile(name) + writeJsonInChunks(file, json) + expect(readFileSync(file)).toEqual(Buffer.from(json, 'utf8')) +} + +describe('writeJsonInChunks', () => { + it('writes large JSON byte-identically', () => { + const json = JSON.stringify({ + schemaVersion: 1, + events: Array.from({ length: 2000 }, (_, index) => ({ + type: index % 2 === 0 ? 'agent_start' : 'agent_stop', + at: 1760000000000 + index, + meta: { + ptyId: `pty-${index}`, + note: 'plain stats payload '.repeat(8) + } + })), + aggregates: { + totalAgentsSpawned: 1000, + totalPRsCreated: 0, + totalAgentTimeMs: 0, + countedPRs: [], + firstEventAt: 1760000000000 + } + }) + + expect(Buffer.byteLength(json, 'utf8')).toBeGreaterThan(200_000) + expectChunkedWriteToPreserveBytes('large.json', json) + }) + + it('preserves multibyte content and surrogate pairs at chunk boundaries', () => { + const boundaryAstral = `${'a'.repeat(16_383)}😀${'b'.repeat(512)}` + const multibyteJson = JSON.stringify({ + note: `${boundaryAstral}${'é漢字'.repeat(20_000)}` + }) + + expectChunkedWriteToPreserveBytes('multibyte.json', multibyteJson) + }) +}) diff --git a/src/main/stats/stats-json-writer.ts b/src/main/stats/stats-json-writer.ts new file mode 100644 index 000000000..93359f405 --- /dev/null +++ b/src/main/stats/stats-json-writer.ts @@ -0,0 +1,47 @@ +import { closeSync, openSync, writeSync } from 'fs' + +// Why 16K code units: JS string slicing is code-unit based. This keeps each +// UTF-8 Buffer comfortably below 64KiB even for non-ASCII JSON content. +const JSON_WRITE_CHUNK_CODE_UNITS = 16_384 + +/** + * Write `json` to `path` in small slices via a single file descriptor. + * + * Why not writeFileSync(path, json): Electron's bundled Node can abort the + * process when encoding a large string to UTF-8 in one filesystem write. Each + * slice is encoded to a small Buffer first, so fs.writeSync never receives a + * large string and surrogate pairs stay intact. + */ +export function writeJsonInChunks(path: string, json: string): void { + const fd = openSync(path, 'w') + try { + let index = 0 + while (index < json.length) { + const end = getNextChunkEnd(json, index) + writeBufferFully(fd, Buffer.from(json.slice(index, end), 'utf8')) + index = end + } + } finally { + closeSync(fd) + } +} + +function getNextChunkEnd(json: string, index: number): number { + let end = Math.min(index + JSON_WRITE_CHUNK_CODE_UNITS, json.length) + const lastUnit = json.charCodeAt(end - 1) + if (end < json.length && lastUnit >= 0xd800 && lastUnit <= 0xdbff) { + end -= 1 + } + return end +} + +function writeBufferFully(fd: number, buffer: Buffer): void { + let offset = 0 + while (offset < buffer.byteLength) { + const bytesWritten = writeSync(fd, buffer, offset, buffer.byteLength - offset) + if (bytesWritten === 0) { + throw new Error('Failed to write stats JSON chunk') + } + offset += bytesWritten + } +} diff --git a/src/main/stats/types.ts b/src/main/stats/types.ts index 8a5485a8b..8ea76ca1a 100644 --- a/src/main/stats/types.ts +++ b/src/main/stats/types.ts @@ -29,7 +29,7 @@ export type StatsAggregates = { // Bounded in practice (a few hundred at most). countedPRs: string[] // Why persisted here instead of derived from events[0].at: - // The event log is bounded to 10K entries. Once trimmed, events[0].at + // The event log is bounded before writes. Once trimmed, events[0].at // would jump forward, making "tracking since..." inaccurate. This field // is set once on the very first event and never updated. firstEventAt: number | null