From 40d8eeb8a5fba4563e6facdf7e3f8c148ac26507 Mon Sep 17 00:00:00 2001 From: Thiago Mota Soares Date: Wed, 3 Jun 2026 17:48:41 -0400 Subject: [PATCH] fix: write stats file in chunks to avoid Electron UTF-8 abort (#4571) * fix: write stats file in chunks to avoid Electron UTF-8 abort orca-stats.json gains an event on every agent start/stop. After about a month of use mine had grown to ~3.6k events / ~608 KB, and the app started hard-crashing a few seconds after every launch (SIGTRAP, no catchable JS stack): Assertion failed: (length + 1) <= (capacity()) node::MaybeStackBuffer::SetLengthAndZeroTerminate <- node::Utf8Value The crash is in StatsCollector.writeToDiskSync(), which saves the whole file in one writeFileSync(JSON.stringify(data)). Electron 42.3.2's bundled Node aborts when encoding a string that large to UTF-8 in a single write; stock Node 24 handles the same file fine and the data is well-formed, so it's an Electron/Node encoding limit, not bad data. The save runs on a debounce after agent_start, which restored agents fire on launch -- so it crashed right after opening. Write the JSON in 64 KB slices through one fd instead (never splitting a surrogate pair), and lower MAX_EVENTS 10k -> 1k so the file can't grow back this large. Lifetime aggregates are unaffected. Verified by reproducing the abort standalone with the real 608 KB file under ELECTRON_RUN_AS_NODE, confirming the chunked writer round-trips it byte-for-byte with no crash, and running a patched build that loads the file without crashing. The underlying encode abort is an Electron/Node bug to report upstream. * fix: harden stats JSON writes --------- Co-authored-by: thiagomsoares <5190162+thiagomsoares@users.noreply.github.com> Co-authored-by: Neil <4138956+nwparker@users.noreply.github.com> --- src/main/stats/collector.test.ts | 77 ++++++++++++++++++++++++ src/main/stats/collector.ts | 29 ++++++--- src/main/stats/stats-json-writer.test.ts | 61 +++++++++++++++++++ src/main/stats/stats-json-writer.ts | 47 +++++++++++++++ src/main/stats/types.ts | 2 +- 5 files changed, 206 insertions(+), 10 deletions(-) create mode 100644 src/main/stats/collector.test.ts create mode 100644 src/main/stats/stats-json-writer.test.ts create mode 100644 src/main/stats/stats-json-writer.ts 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