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<char>::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>
This commit is contained in:
Thiago Mota Soares
2026-06-03 14:48:41 -07:00
committed by GitHub
co-authored by thiagomsoares Neil
parent 0a679e992c
commit 40d8eeb8a5
5 changed files with 206 additions and 10 deletions
+77
View File
@@ -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())
})
})
+20 -9
View File
@@ -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)
}
}
+61
View File
@@ -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)
})
})
+47
View File
@@ -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
}
}
+1 -1
View File
@@ -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