diff --git a/src/main/host/electron-journal-reader-host.ts b/src/main/host/electron-journal-reader-host.ts index db1ac38b844b..b6f170d1d9e7 100644 --- a/src/main/host/electron-journal-reader-host.ts +++ b/src/main/host/electron-journal-reader-host.ts @@ -5,6 +5,10 @@ import { } from '../worker-threads/worker-thread-entry-path' import { JOURNAL_SQL_READER_HOST_NAME } from '../native-chat/agent-session-journal/journal-sql-reader-host-name' import { setJournalSqlReaderSpawner } from '../native-chat/agent-session-journal/journal-sql-reader-spawn' +import { + journalReaderRequestData, + readJournalReaderRequests +} from '../native-chat/agent-session-journal/journal-sql-reader-requests' import { join } from 'node:path' import { spawnWorkerThread } from '../worker-threads/worker-thread-spawn' import { resolveObservabilityConsent } from '../observability' @@ -21,7 +25,8 @@ export function installElectronJournalReaderHost(): void { 'utility-worker-host-entry.js' ), ({ filename, name, workerData }) => - spawnWorkerThread(filename, { name, workerData, execArgv: [] }) + spawnWorkerThread(filename, { name, workerData, execArgv: [] }), + (workers) => journalReaderRequestData(readJournalReaderRequests(workers)) ) setJournalSqlReaderSpawner((filename, workerData) => host.spawn({ diff --git a/src/main/native-chat/agent-session-journal/journal-sql-reader-pool.ts b/src/main/native-chat/agent-session-journal/journal-sql-reader-pool.ts index eeabc0726241..2541050eb6c8 100644 --- a/src/main/native-chat/agent-session-journal/journal-sql-reader-pool.ts +++ b/src/main/native-chat/agent-session-journal/journal-sql-reader-pool.ts @@ -1,5 +1,6 @@ import type { JournalSqlForkReader, JournalSqlConversionReader } from './journal-sql-reader-slot' import { ReaderSlot } from './journal-sql-reader-slot' +import { JOURNAL_SQL_READERS } from './journal-sql-reader-requests' import type { JournalForkPreparationInput } from './journal-fork-preparation' import { throwIfSignalAborted } from '../../../shared/concurrency/abort-signal-reason' import type { JournalOutlineCache } from './journal-domain-outline' @@ -172,7 +173,7 @@ export class JournalSqlReaderPool { let slot = this.slots .filter((slot) => slot !== this.forkSlot && (!forFork || slot !== this.conversionSlot)) .toSorted((a, b) => a.pendingCount - b.pendingCount)[0] - if ((!slot || slot.pendingCount > 0) && this.slots.length < 4) { + if ((!slot || slot.pendingCount > 0) && this.slots.length < JOURNAL_SQL_READERS) { slot = new ReaderSlot(this.filename, this.originalFilename, this.workerPath) this.slots.push(slot) } diff --git a/src/main/native-chat/agent-session-journal/journal-sql-reader-requests.test.ts b/src/main/native-chat/agent-session-journal/journal-sql-reader-requests.test.ts new file mode 100644 index 000000000000..53e65aad2349 --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-sql-reader-requests.test.ts @@ -0,0 +1,47 @@ +import { mkdtemp, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, expect, it } from 'vitest' +import { ReaderSlot } from './journal-sql-reader-slot' +import { readJournalReaderRequests } from './journal-sql-reader-requests' + +const roots: string[] = [] +afterEach(async () => { + await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true }))) +}) + +it('names the read a reader is running before it replies, and the next one once it does', async () => { + const root = await mkdtemp(join(tmpdir(), 'journal-reader-requests-')) + roots.push(root) + const workerPath = join(root, 'held-reader.cjs') + // Holds every request; answers only the first, once a third arrives. + await writeFile( + workerPath, + `const { parentPort } = require('node:worker_threads') +const held = [] +parentPort.on('message', (request) => { + held.push(request) + if (held.length === 3) parentPort.postMessage({ type: 'import-state', id: held[0].id, state: null }) +}) +parentPort.postMessage({ type: 'ready' })` + ) + const slot = new ReaderSlot(join(root, 'db'), join(root, 'db'), workerPath) + try { + const first = slot.request({ kind: 'import-state', sessionId: 'session' }) + const rest = [ + slot.request({ kind: 'database', operation: { kind: 'epoch', sessionId: 'other' } }), + slot.request({ kind: 'database', operation: { kind: 'sessions', after: null } }) + ] + rest.forEach((request) => request.catch(() => {})) + expect(readJournalReaderRequests()).toMatchObject([ + { reader: 0, operation: 'import-state', chat: '3f3af1ec', queued: 2 } + ]) + await first + expect(readJournalReaderRequests()).toMatchObject([ + { reader: 0, operation: 'database:epoch', chat: 'd9298a10', queued: 1 } + ]) + } finally { + await slot.close() + } + expect(readJournalReaderRequests()).toEqual([]) +}) diff --git a/src/main/native-chat/agent-session-journal/journal-sql-reader-requests.ts b/src/main/native-chat/agent-session-journal/journal-sql-reader-requests.ts new file mode 100644 index 000000000000..07d67e7a3e77 --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-sql-reader-requests.ts @@ -0,0 +1,125 @@ +import { createHash } from 'node:crypto' +import type { JournalSqlReaderOperation } from './journal-sql-reader-protocol' +import type { ReaderSlot } from './journal-sql-reader-slot' +import type { JournalSqlReaderWorker } from './journal-sql-reader-spawn' +import type { CrashReportBreadcrumbData } from '../../../shared/crash-reporting/crash-reporting' + +/** + * Each journal reader's oldest unanswered read, recorded on main before the reader gets it. A + * reader that runs out of memory mid-read never replies, so its last reply can't name the read. + */ +export type JournalReaderRunningRequest = { + operation: string + /** A hash of the chat id: matches a local journal without putting the id in a crash report. */ + chat: string | null + startedAt: number + /** Requests waiting behind this one on the same reader, kept current. */ + queued: number + /** Null while the reader runs inside the utility process. */ + threadId: number | null +} + +type RunningRequestSink = (reader: number, request: JournalReaderRunningRequest | null) => void + +/** The pool's reader limit; a closing reader frees its record before its replacement claims one. */ +export const JOURNAL_SQL_READERS = 4 +const owners: (ReaderSlot | undefined)[] = Array.from({ length: JOURNAL_SQL_READERS }) +const running: (JournalReaderRunningRequest | null)[] = Array.from( + { length: JOURNAL_SQL_READERS }, + () => null +) +let sink: RunningRequestSink | undefined + +export function claimJournalReaderRecord(owner: ReaderSlot): number | undefined { + const index = owners.indexOf(undefined) + if (index === -1) { + return undefined + } + owners[index] = owner + return index +} + +export function releaseJournalReaderRecord(owner: ReaderSlot): void { + const index = owners.indexOf(owner) + if (index !== -1) { + recordJournalReaderRequest(index, null) + owners[index] = undefined + } +} + +export function recordJournalReaderRequest( + reader: number, + request: JournalReaderRunningRequest | null +): void { + running[reader] = request + try { + sink?.(reader, request) + } catch { + // Diagnostics only. + } +} + +export function readJournalReaderRequests( + onWorkers?: readonly unknown[] +): (JournalReaderRunningRequest & { reader: number })[] { + return running.flatMap((request, reader) => + request && (!onWorkers || owners[reader]?.runsOn(onWorkers)) ? [{ ...request, reader }] : [] + ) +} + +/** Breadcrumb fields naming each reader's oldest unanswered read. */ +export function journalReaderRequestData( + requests: readonly (JournalReaderRunningRequest & { reader: number })[] +): CrashReportBreadcrumbData { + const data: CrashReportBreadcrumbData = {} + for (const request of requests) { + data[`r${request.reader}_readOp`] = request.operation + data[`r${request.reader}_readChat`] = request.chat + data[`r${request.reader}_readQueued`] = request.queued + data[`r${request.reader}_readAgeMs`] = Date.now() - request.startedAt + } + return data +} + +/** Main's crash diagnostics: called synchronously, before the reader receives the request. */ +export function onJournalReaderRequest(next: RunningRequestSink): void { + sink = next +} + +export function describeJournalReaderOperation( + operation: JournalSqlReaderOperation +): Pick { + switch (operation.kind) { + case 'point': + return { + operation: `point:${operation.request.operation.kind}`, + chat: chatHash(operation.request.sessionId) + } + case 'domain-history': + return { operation: operation.kind, chat: chatHash(operation.request.sessionId) } + case 'database': + return { + operation: `database:${operation.operation.kind}`, + chat: 'sessionId' in operation.operation ? chatHash(operation.operation.sessionId) : null + } + case 'fork-prepare': + return { operation: operation.kind, chat: chatHash(operation.input.source.sessionId) } + case 'conversion-prepare': + case 'import-state': + return { operation: operation.kind, chat: chatHash(operation.sessionId) } + case 'fork-next': + case 'fork-release': + case 'conversion-page': + case 'conversion-release': + return { operation: operation.kind, chat: null } + } +} + +function chatHash(sessionId: string): string { + return createHash('sha256').update(sessionId).digest('hex').slice(0, 8) +} + +/** A thread's id, including a hosted reader moved in-process; null inside the utility process. */ +export function journalReaderThreadId(worker: JournalSqlReaderWorker): number | null { + return 'threadId' in worker && typeof worker.threadId === 'number' ? worker.threadId : null +} diff --git a/src/main/native-chat/agent-session-journal/journal-sql-reader-slot.ts b/src/main/native-chat/agent-session-journal/journal-sql-reader-slot.ts index d0b645a22ce5..58412102992b 100644 --- a/src/main/native-chat/agent-session-journal/journal-sql-reader-slot.ts +++ b/src/main/native-chat/agent-session-journal/journal-sql-reader-slot.ts @@ -7,6 +7,14 @@ import { spawnJournalSqlReader, type JournalSqlReaderWorker } from './journal-sq import { restoreJournalSqlFailure } from './journal-sql-failure' import { AgentSessionJournalError } from './writing/journal-write-guards' +import { + claimJournalReaderRecord, + describeJournalReaderOperation, + journalReaderThreadId, + recordJournalReaderRequest, + type JournalReaderRunningRequest, + releaseJournalReaderRecord +} from './journal-sql-reader-requests' import type { JournalSqlReaderOperation, @@ -22,13 +30,14 @@ export class JournalSqlForkReader { constructor( private readonly slot: ReaderSlot, private readonly preparationId: number, - private readonly release: () => void + private readonly release: () => void, + private readonly chat: string | null ) {} async next(): Promise { - const response = await this.slot.request({ - kind: 'fork-next', - preparationId: this.preparationId - }) + const response = await this.slot.request( + { kind: 'fork-next', preparationId: this.preparationId }, + this.chat + ) if (response.type !== 'fork-next') { throw new Error('fork reader returned no preparation step') } @@ -36,7 +45,7 @@ export class JournalSqlForkReader { } close(): Promise { return (this.closing ??= this.slot - .request({ kind: 'fork-release', preparationId: this.preparationId }) + .request({ kind: 'fork-release', preparationId: this.preparationId }, this.chat) .then(() => {}) .finally(this.release)) } @@ -50,14 +59,15 @@ export class JournalSqlConversionReader { readonly header: JournalDomainImportHeader, private readonly slot: ReaderSlot, private readonly conversionId: number, - private readonly release: () => void + private readonly release: () => void, + private readonly chat: string | null ) {} async next(): Promise { - const response = await this.slot.request({ - kind: 'conversion-page', - conversionId: this.conversionId - }) + const response = await this.slot.request( + { kind: 'conversion-page', conversionId: this.conversionId }, + this.chat + ) if (response.type !== 'rows') { throw new Error('journal reader returned no conversion page') } @@ -66,7 +76,7 @@ export class JournalSqlConversionReader { close(): Promise { return (this.closing ??= this.slot - .request({ kind: 'conversion-release', conversionId: this.conversionId }) + .request({ kind: 'conversion-release', conversionId: this.conversionId }, this.chat) .then(() => {}) .finally(this.release)) } @@ -75,13 +85,19 @@ export class JournalSqlConversionReader { export class ReaderSlot { private readonly worker: JournalSqlReaderWorker private nextId = 0 + /** Ids only grow, so the oldest pending id only moves forward. */ + private oldestId = 1 private readonly pending = new Map< number, { + operation: JournalSqlReaderOperation + chat?: string | null resolve: (response: JournalSqlReaderResult) => void reject: (error: Error) => void } >() + private record?: number + private running?: { id: number; queued: number; request: JournalReaderRunningRequest } failed = false private failure?: Error private conversions = 0 @@ -95,6 +111,7 @@ export class ReaderSlot { constructor(filename: string, originalFilename: string, workerPath: string) { this.worker = spawnJournalSqlReader(workerPath, { filename, originalFilename }) + this.record = claimJournalReaderRecord(this) const startup = setTimeout(() => { this.fail(new Error('journal SQL reader did not open within 10000 ms')) void this.close() @@ -103,6 +120,8 @@ export class ReaderSlot { this.worker.on('message', (reply: JournalSqlReaderReply) => { if (reply.type === 'ready') { this.ready.resolve() + // A hosted reader that moved in-process now has a thread id. + this.recordRunning() if (this.pending.size === 0) { this.worker.unref() } @@ -111,6 +130,7 @@ export class ReaderSlot { const pending = reply.id === undefined ? undefined : this.pending.get(reply.id) if (reply.id !== undefined) { this.pending.delete(reply.id) + this.recordRunning() } if (this.pending.size === 0) { this.worker.unref() @@ -140,17 +160,20 @@ export class ReaderSlot { input: JournalForkPreparationInput, release: () => void ): Promise { - const request = this.send({ kind: 'fork-prepare', input }) + const operation = { kind: 'fork-prepare', input } as const + const request = this.send(operation) const result = await request.result if (result.type !== 'fork-prepared') { throw new Error('fork reader returned no preparation') } - return new JournalSqlForkReader(this, request.id, release) + const { chat } = describeJournalReaderOperation(operation) + return new JournalSqlForkReader(this, request.id, release, chat) } async prepareConversion(sessionId: string): Promise { this.conversions++ - const request = this.send({ kind: 'conversion-prepare', sessionId }) + const operation = { kind: 'conversion-prepare', sessionId } as const + const request = this.send(operation) try { const response = await request.result if (response.type !== 'prepared') { @@ -160,20 +183,33 @@ export class ReaderSlot { this.conversions-- return null } - return new JournalSqlConversionReader(response.conversion, this, request.id, () => { + const { chat } = describeJournalReaderOperation(operation) + const release = () => { this.conversions-- - }) + } + return new JournalSqlConversionReader(response.conversion, this, request.id, release, chat) } catch (error) { this.conversions-- throw error } } - request(operation: JournalSqlReaderOperation): Promise { - return this.send(operation).result + runsOn(workers: readonly unknown[]): boolean { + return workers.includes(this.worker) + } + + /** `chat` names a reservation step's chat, which its operation doesn't carry. */ + request( + operation: JournalSqlReaderOperation, + chat?: string | null + ): Promise { + return this.send(operation, chat).result } - private send(operation: JournalSqlReaderOperation): { + private send( + operation: JournalSqlReaderOperation, + chat?: string | null + ): { id: number result: Promise } { @@ -191,7 +227,8 @@ export class ReaderSlot { } this.worker.ref() const result = new Promise((resolve, reject) => { - this.pending.set(id, { resolve, reject }) + this.pending.set(id, { operation, chat, resolve, reject }) + this.recordRunning() void this.ready.promise .then(() => { if (this.pending.has(id)) { @@ -200,6 +237,7 @@ export class ReaderSlot { }) .catch((error: unknown) => { this.pending.delete(id) + this.recordRunning() if (this.pending.size === 0) { this.worker.unref() } @@ -210,6 +248,8 @@ export class ReaderSlot { } close(): Promise { + releaseJournalReaderRecord(this) + this.record = undefined return (this.closing ??= Promise.resolve() .then(() => { const error = new AgentSessionJournalError('journal_closed', 'journal SQL reader is closed') @@ -235,5 +275,55 @@ export class ReaderSlot { pending.reject(error) } this.pending.clear() + this.recordRunning() + } + + // A Map's first entry walks over deleted ones, so draining a long queue that way is quadratic. + private oldestPending() { + while (this.oldestId <= this.nextId && !this.pending.has(this.oldestId)) { + this.oldestId++ + } + const pending = this.pending.get(this.oldestId) + return pending && ([this.oldestId, pending] as const) + } + + /** Replies are FIFO: the oldest unanswered request is running, or answered but not yet read. */ + private recordRunning(): void { + if (this.record === undefined) { + return + } + const oldest = this.oldestPending() + const queued = this.pending.size - 1 + const threadId = journalReaderThreadId(this.worker) + if ( + oldest?.[0] === this.running?.id && + queued === this.running?.queued && + threadId === this.running?.request.threadId + ) { + return + } + if (!oldest) { + if (this.running) { + this.running = undefined + recordJournalReaderRequest(this.record, null) + } + return + } + const [id, { operation, chat }] = oldest + let request: JournalReaderRunningRequest + if (id === this.running?.id) { + request = { ...this.running.request, queued, threadId } + } else { + const described = describeJournalReaderOperation(operation) + request = { + operation: described.operation, + chat: chat === undefined ? described.chat : chat, + startedAt: Date.now(), + queued, + threadId + } + } + this.running = { id, queued, request } + recordJournalReaderRequest(this.record, request) } } diff --git a/src/main/utility-worker-host/hosted-worker.ts b/src/main/utility-worker-host/hosted-worker.ts index 2d5b1d834095..db245a39ac79 100644 --- a/src/main/utility-worker-host/hosted-worker.ts +++ b/src/main/utility-worker-host/hosted-worker.ts @@ -39,6 +39,11 @@ export class HostedWorker extends EventEmitter { super() } + /** Null while the worker runs in the utility process. */ + get threadId(): number | null { + return this.local?.threadId ?? null + } + postMessage(message: unknown): void { if (this.local) { this.local.postMessage(message) diff --git a/src/main/utility-worker-host/utility-worker-host.ts b/src/main/utility-worker-host/utility-worker-host.ts index c4adb68bf05b..48d29042a2f3 100644 --- a/src/main/utility-worker-host/utility-worker-host.ts +++ b/src/main/utility-worker-host/utility-worker-host.ts @@ -53,7 +53,11 @@ export class UtilityWorkerHost { constructor( private readonly serviceName: string, private readonly entryPath: () => string, - private readonly spawnInProcess: (spawn: UtilityWorkerSpawn) => Worker + private readonly spawnInProcess: (spawn: UtilityWorkerSpawn) => Worker, + /** The owner's account of what this host's workers were doing, for the exit breadcrumb. */ + private readonly exitContext?: ( + workers: readonly HostedWorkerThread[] + ) => CrashReportBreadcrumbData ) { app.once('will-quit', () => { quitting = true @@ -225,6 +229,8 @@ export class UtilityWorkerHost { data[`w${index}_lastReply`] = worker.lastReplyType data[`w${index}_receivedMB`] = Math.round(worker.receivedBytes / 2 ** 20) }) + // Before the workers fail, which ends what their owners were waiting on. + Object.assign(data, this.exitContext?.(workers)) recordDurableCrashBreadcrumb('utility_worker_host_exited', data) } const error = new Error(`${this.serviceName} exited (${code})`) diff --git a/src/main/worker-threads/worker-thread-diagnostics.ts b/src/main/worker-threads/worker-thread-diagnostics.ts index fcbda3e3204c..8771b56c8fb5 100644 --- a/src/main/worker-threads/worker-thread-diagnostics.ts +++ b/src/main/worker-threads/worker-thread-diagnostics.ts @@ -15,6 +15,12 @@ import { type WorkerSendLedgerEntry } from './worker-send-ledger' import type { WorkerThreadRole } from './worker-thread-roles' +import { + journalReaderRequestData, + onJournalReaderRequest, + readJournalReaderRequests, + type JournalReaderRunningRequest +} from '../native-chat/agent-session-journal/journal-sql-reader-requests' import { observeWorkerThreads } from './worker-thread-spawn' import { noteMainCageHeap } from '../crash-reporting/memory/main-heap-allocation-profile' @@ -42,6 +48,7 @@ type WorkerHeap = { entry: LiveWorker; heap: number } export function installWorkerThreadDiagnostics(): void { const live = new Set() let largeSendLogSet = false + onJournalReaderRequest(annotateReaderRequest) let sampling: ReturnType | undefined const schedule = (delayMs: number): void => { sampling = setTimeout(() => { @@ -69,6 +76,9 @@ export function installWorkerThreadDiagnostics(): void { role, code: typeof error?.code === 'string' ? error.code : null, ...(ledger ? ledgerData('', ledger) : {}), + ...journalReaderRequestData( + readJournalReaderRequests().filter((request) => request.threadId === entry.threadId) + ), mainHeapMB: Math.round(getHeapStatistics().total_heap_size / MB) }) }) @@ -108,6 +118,7 @@ async function sampleHeaps(live: Set): Promise { ...mainHeapSpaces(), workers: heaps.length } + Object.assign(data, journalReaderRequestData(readJournalReaderRequests())) heaps.slice(0, REPORTED_WORKERS).forEach(({ entry, heap }, index) => { const slot = ledger.get(entry.threadId) Object.assign(data, { @@ -180,6 +191,23 @@ function workerAnnotation(sample: WorkerHeap, slot: WorkerSendLedgerEntry | unde return `${heap} last=${slot.lastKind}/${slot.lastItems}/${lastKB}KB max=${slot.maxKind}/${maxKB}KB` } +/** Written before the reader gets the request, so an abort mid-read still names it. */ +function annotateReaderRequest(reader: number, request: JournalReaderRunningRequest | null): void { + const key = `orca-reader-${reader}` + try { + if (request) { + const value = + `${request.operation} chat=${request.chat ?? '-'} queued=${request.queued} ` + + `tid=${request.threadId ?? '-'} at=${new Date(request.startedAt).toISOString()}` + crashReporter.addExtraParameter(key, value.slice(0, ANNOTATION_MAX_LENGTH)) + } else { + crashReporter.removeExtraParameter(key) + } + } catch { + // Crash reporting may be off; diagnostics only. + } +} + function workerHeap(worker: Worker): Promise { let timer: ReturnType | undefined const timeout = new Promise((_, reject) => {