From 79165be8498dcb14b07c8164eda1a5d6a618fc76 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Tue, 17 Nov 2026 11:56:35 -0800 Subject: [PATCH 01/11] fix(diagnostics): name the chat read a journal reader is running before it runs A reader that runs out of memory mid-read never replies, so the send ledger's last reply could not say which read was in flight. Main now records each reader's running request (operation kind, hashed chat id, queue depth, start time) in a crash annotation before the reader receives it, and adds it to the heap-pressure and worker-failure breadcrumbs. --- .../journal-sql-reader-requests.test.ts | 47 ++++++++++ .../journal-sql-reader-requests.ts | 90 +++++++++++++++++++ .../journal-sql-reader-slot.ts | 40 ++++++++- .../worker-thread-diagnostics.ts | 44 +++++++++ 4 files changed, 220 insertions(+), 1 deletion(-) create mode 100644 src/main/native-chat/agent-session-journal/journal-sql-reader-requests.test.ts create mode 100644 src/main/native-chat/agent-session-journal/journal-sql-reader-requests.ts 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..b6dba912676c --- /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: 0 } + ]) + 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..4b533f5ed200 --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-sql-reader-requests.ts @@ -0,0 +1,90 @@ +import { createHash } from 'node:crypto' +import type { JournalSqlReaderOperation } from './journal-sql-reader-protocol' + +/** + * The read each journal reader is running, 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; this can. + */ +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. */ + queued: number + threadId: number +} + +type RunningRequestSink = (reader: number, request: JournalReaderRunningRequest | null) => void + +/** The pool runs at most four readers; a fifth (only while one retires) goes unrecorded. */ +const READERS = 4 +const owners: (object | undefined)[] = Array.from({ length: READERS }) +const running: (JournalReaderRunningRequest | null)[] = Array.from({ length: READERS }, () => null) +let sink: RunningRequestSink | undefined + +export function claimJournalReaderRecord(owner: object): number | undefined { + const index = owners.indexOf(undefined) + if (index === -1) { + return undefined + } + owners[index] = owner + return index +} + +export function releaseJournalReaderRecord(owner: object): 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(): (JournalReaderRunningRequest & { reader: number })[] { + return running.flatMap((request, reader) => (request ? [{ ...request, reader }] : [])) +} + +/** 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 'conversion-prepare': + case 'import-state': + return { operation: operation.kind, chat: chatHash(operation.sessionId) } + default: + return { operation: operation.kind, chat: null } + } +} + +function chatHash(sessionId: string): string { + return createHash('sha256').update(sessionId).digest('hex').slice(0, 8) +} 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 f06ecf589109..1709ed5ede14 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 @@ -9,6 +9,12 @@ import { spawnWorkerThread } from '../../worker-threads/worker-thread-spawn' import { restoreJournalSqlFailure } from './journal-sql-failure' import { AgentSessionJournalError } from './writing/journal-write-guards' +import { + claimJournalReaderRecord, + describeJournalReaderOperation, + recordJournalReaderRequest, + releaseJournalReaderRecord +} from './journal-sql-reader-requests' import type { JournalSqlReaderOperation, @@ -80,10 +86,13 @@ export class ReaderSlot { private readonly pending = new Map< number, { + operation: JournalSqlReaderOperation resolve: (response: JournalSqlReaderResult) => void reject: (error: Error) => void } >() + private record = claimJournalReaderRecord(this) + private runningId?: number failed = false private failure?: Error private conversions = 0 @@ -117,6 +126,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() @@ -197,7 +207,8 @@ export class ReaderSlot { } this.worker.ref() const result = new Promise((resolve, reject) => { - this.pending.set(id, { resolve, reject }) + this.pending.set(id, { operation, resolve, reject }) + this.recordRunning() void this.ready.promise .then(() => { if (this.pending.has(id)) { @@ -206,6 +217,7 @@ export class ReaderSlot { }) .catch((error: unknown) => { this.pending.delete(id) + this.recordRunning() if (this.pending.size === 0) { this.worker.unref() } @@ -216,6 +228,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') @@ -241,5 +255,29 @@ export class ReaderSlot { pending.reject(error) } this.pending.clear() + this.recordRunning() + } + + /** Replies are FIFO, so the oldest unanswered request is the one this reader is running. */ + private recordRunning(): void { + if (this.record === undefined) { + return + } + const oldest = this.pending.entries().next().value + if (oldest?.[0] === this.runningId) { + return + } + this.runningId = oldest?.[0] + recordJournalReaderRequest( + this.record, + oldest + ? { + ...describeJournalReaderOperation(oldest[1].operation), + startedAt: Date.now(), + queued: this.pending.size - 1, + threadId: this.worker.threadId + } + : null + ) } } diff --git a/src/main/worker-threads/worker-thread-diagnostics.ts b/src/main/worker-threads/worker-thread-diagnostics.ts index bbd9b2a2d151..696611c742a1 100644 --- a/src/main/worker-threads/worker-thread-diagnostics.ts +++ b/src/main/worker-threads/worker-thread-diagnostics.ts @@ -15,6 +15,11 @@ import { type WorkerSendLedgerEntry } from './worker-send-ledger' import type { WorkerThreadRole } from './worker-thread-roles' +import { + onJournalReaderRequest, + readJournalReaderRequests, + type JournalReaderRunningRequest +} from '../native-chat/agent-session-journal/journal-sql-reader-requests' import { observeWorkerThreads } from './worker-thread-spawn' /** @@ -41,6 +46,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(() => { @@ -68,6 +74,10 @@ export function installWorkerThreadDiagnostics(): void { role, code: typeof error?.code === 'string' ? error.code : null, ...(ledger ? ledgerData('', ledger) : {}), + ...readerRequestData( + '', + readJournalReaderRequests().find((request) => request.threadId === entry.threadId) + ), mainHeapMB: Math.round(getHeapStatistics().total_heap_size / MB) }) }) @@ -105,6 +115,9 @@ async function sampleHeaps(live: Set): Promise { ...mainHeapSpaces(), workers: heaps.length } + readJournalReaderRequests().forEach((request) => + Object.assign(data, readerRequestData(`r${request.reader}_`, request)) + ) heaps.slice(0, REPORTED_WORKERS).forEach(({ entry, heap }, index) => { const slot = ledger.get(entry.threadId) Object.assign(data, { @@ -177,6 +190,37 @@ 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 readerRequestData( + prefix: string, + request: JournalReaderRunningRequest | undefined +): CrashReportBreadcrumbData { + return request + ? { + [`${prefix}readOp`]: request.operation, + [`${prefix}readChat`]: request.chat, + [`${prefix}readQueued`]: request.queued, + [`${prefix}readAgeMs`]: Date.now() - request.startedAt + } + : {} +} + function workerHeap(worker: Worker): Promise { let timer: ReturnType | undefined const timeout = new Promise((_, reject) => { From e2ee6ac09ad80714dec364186964c612203dab1c Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Tue, 17 Nov 2026 12:02:59 -0800 Subject: [PATCH 02/11] fix(diagnostics): keep a reader's queue count current and name the chat for fork and conversion steps Claim the diagnostic record only after the reader worker exists. --- .../journal-sql-reader-requests.test.ts | 2 +- .../journal-sql-reader-requests.ts | 6 +- .../journal-sql-reader-slot.ts | 68 +++++++++++++++---- 3 files changed, 61 insertions(+), 15 deletions(-) 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 index b6dba912676c..53e65aad2349 100644 --- 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 @@ -34,7 +34,7 @@ parentPort.postMessage({ type: 'ready' })` ] rest.forEach((request) => request.catch(() => {})) expect(readJournalReaderRequests()).toMatchObject([ - { reader: 0, operation: 'import-state', chat: '3f3af1ec', queued: 0 } + { reader: 0, operation: 'import-state', chat: '3f3af1ec', queued: 2 } ]) await first expect(readJournalReaderRequests()).toMatchObject([ 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 index 4b533f5ed200..3984e8f236d3 100644 --- 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 @@ -10,14 +10,14 @@ export type JournalReaderRunningRequest = { /** 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. */ + /** Requests waiting behind this one on the same reader, kept current. */ queued: number threadId: number } type RunningRequestSink = (reader: number, request: JournalReaderRunningRequest | null) => void -/** The pool runs at most four readers; a fifth (only while one retires) goes unrecorded. */ +/** The pool runs at most four readers; a closing reader frees its record first. */ const READERS = 4 const owners: (object | undefined)[] = Array.from({ length: READERS }) const running: (JournalReaderRunningRequest | null)[] = Array.from({ length: READERS }, () => null) @@ -77,6 +77,8 @@ export function describeJournalReaderOperation( 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) } 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 1709ed5ede14..b99feaa50f4e 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 @@ -13,6 +13,7 @@ import { claimJournalReaderRecord, describeJournalReaderOperation, recordJournalReaderRequest, + type JournalReaderRunningRequest, releaseJournalReaderRecord } from './journal-sql-reader-requests' @@ -91,8 +92,10 @@ export class ReaderSlot { reject: (error: Error) => void } >() - private record = claimJournalReaderRecord(this) - private runningId?: number + private record?: number + private running?: { id: number; queued: number; request: JournalReaderRunningRequest } + /** A fork or conversion reservation's later steps name the chat its first step opened. */ + private readonly reservedChats = new Map() failed = false private failure?: Error private conversions = 0 @@ -110,6 +113,7 @@ export class ReaderSlot { workerData: { filename, originalFilename }, execArgv: [] }) + this.record = claimJournalReaderRecord(this) const startup = setTimeout(() => { this.fail(new Error('journal SQL reader did not open within 10000 ms')) void this.close() @@ -264,20 +268,60 @@ export class ReaderSlot { return } const oldest = this.pending.entries().next().value - if (oldest?.[0] === this.runningId) { + const queued = this.pending.size - 1 + if (oldest?.[0] === this.running?.id && queued === this.running?.queued) { return } - this.runningId = oldest?.[0] - recordJournalReaderRequest( - this.record, - oldest - ? { - ...describeJournalReaderOperation(oldest[1].operation), + if (!oldest) { + this.running = undefined + recordJournalReaderRequest(this.record, null) + return + } + const [id, { operation }] = oldest + const request: JournalReaderRunningRequest = + id === this.running?.id + ? { ...this.running.request, queued } + : { + ...this.describe(id, operation), startedAt: Date.now(), - queued: this.pending.size - 1, + queued, threadId: this.worker.threadId } - : null - ) + this.running = { id, queued, request } + recordJournalReaderRequest(this.record, request) + } + + private describe( + id: number, + operation: JournalSqlReaderOperation + ): Pick { + const described = describeJournalReaderOperation(operation) + switch (operation.kind) { + case 'fork-prepare': + case 'conversion-prepare': + this.reservedChats.set(id, described.chat) + return described + case 'fork-next': + case 'conversion-page': + return { ...described, chat: this.reservedChat(operation) } + case 'fork-release': + case 'conversion-release': { + const chat = this.reservedChat(operation) + this.reservedChats.delete(reservationId(operation)) + return { ...described, chat } + } + default: + return described + } + } + + private reservedChat( + operation: { preparationId: number } | { conversionId: number } + ): string | null { + return this.reservedChats.get(reservationId(operation)) ?? null } } + +function reservationId(operation: { preparationId: number } | { conversionId: number }): number { + return 'preparationId' in operation ? operation.preparationId : operation.conversionId +} From ce8a52de129e3bd19fadf843eb2a61b3e125ba34 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Tue, 17 Nov 2026 13:43:14 -0800 Subject: [PATCH 03/11] chore(diagnostics): name the reader record owner and make operation switches exhaustive --- .../journal-sql-reader-requests.ts | 12 ++++++++---- .../agent-session-journal/journal-sql-reader-slot.ts | 5 ++++- 2 files changed, 12 insertions(+), 5 deletions(-) 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 index 3984e8f236d3..92f1afcfad1d 100644 --- 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 @@ -1,5 +1,6 @@ import { createHash } from 'node:crypto' import type { JournalSqlReaderOperation } from './journal-sql-reader-protocol' +import type { ReaderSlot } from './journal-sql-reader-slot' /** * The read each journal reader is running, recorded on main before the reader gets it. A reader @@ -19,11 +20,11 @@ type RunningRequestSink = (reader: number, request: JournalReaderRunningRequest /** The pool runs at most four readers; a closing reader frees its record first. */ const READERS = 4 -const owners: (object | undefined)[] = Array.from({ length: READERS }) +const owners: (ReaderSlot | undefined)[] = Array.from({ length: READERS }) const running: (JournalReaderRunningRequest | null)[] = Array.from({ length: READERS }, () => null) let sink: RunningRequestSink | undefined -export function claimJournalReaderRecord(owner: object): number | undefined { +export function claimJournalReaderRecord(owner: ReaderSlot): number | undefined { const index = owners.indexOf(undefined) if (index === -1) { return undefined @@ -32,7 +33,7 @@ export function claimJournalReaderRecord(owner: object): number | undefined { return index } -export function releaseJournalReaderRecord(owner: object): void { +export function releaseJournalReaderRecord(owner: ReaderSlot): void { const index = owners.indexOf(owner) if (index !== -1) { recordJournalReaderRequest(index, null) @@ -82,7 +83,10 @@ export function describeJournalReaderOperation( case 'conversion-prepare': case 'import-state': return { operation: operation.kind, chat: chatHash(operation.sessionId) } - default: + case 'fork-next': + case 'fork-release': + case 'conversion-page': + case 'conversion-release': return { operation: operation.kind, chat: 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 b99feaa50f4e..6e9e9fa4943c 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 @@ -310,7 +310,10 @@ export class ReaderSlot { this.reservedChats.delete(reservationId(operation)) return { ...described, chat } } - default: + case 'domain-history': + case 'database': + case 'point': + case 'import-state': return described } } From d3ecee039c1e4f8d171feedcc03150928bdeb3d3 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Tue, 17 Nov 2026 14:48:23 -0800 Subject: [PATCH 04/11] docs(diagnostics): the reader record is the oldest unanswered read --- .../agent-session-journal/journal-sql-reader-requests.ts | 4 ++-- .../agent-session-journal/journal-sql-reader-slot.ts | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) 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 index 92f1afcfad1d..dd3a5ecf8a9e 100644 --- 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 @@ -3,8 +3,8 @@ import type { JournalSqlReaderOperation } from './journal-sql-reader-protocol' import type { ReaderSlot } from './journal-sql-reader-slot' /** - * The read each journal reader is running, 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; this can. + * 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 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 6e9e9fa4943c..54f4f9b2c44a 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 @@ -262,7 +262,7 @@ export class ReaderSlot { this.recordRunning() } - /** Replies are FIFO, so the oldest unanswered request is the one this reader is running. */ + /** Replies are FIFO: the oldest unanswered request is running, or answered but not yet read. */ private recordRunning(): void { if (this.record === undefined) { return From 65c0efb9d01f025602ce403f0ea858055acfd50e Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Tue, 17 Nov 2026 15:46:19 -0800 Subject: [PATCH 05/11] refactor(diagnostics): keep reservation chat tracking beside the reader records --- .../journal-sql-reader-requests.ts | 36 +++++++++++++++ .../journal-sql-reader-slot.ts | 44 ++----------------- 2 files changed, 39 insertions(+), 41 deletions(-) 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 index dd3a5ecf8a9e..f2ab388e65d9 100644 --- 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 @@ -91,6 +91,42 @@ export function describeJournalReaderOperation( } } +/** A fork or conversion reservation's later steps name the chat its first step opened. */ +export class JournalReaderReservedChats { + private readonly chats = new Map() + + describe( + id: number, + operation: JournalSqlReaderOperation + ): Pick { + const described = describeJournalReaderOperation(operation) + switch (operation.kind) { + case 'fork-prepare': + case 'conversion-prepare': + this.chats.set(id, described.chat) + return described + case 'fork-next': + case 'conversion-page': + return { ...described, chat: this.chats.get(reservationId(operation)) ?? null } + case 'fork-release': + case 'conversion-release': { + const chat = this.chats.get(reservationId(operation)) ?? null + this.chats.delete(reservationId(operation)) + return { ...described, chat } + } + case 'domain-history': + case 'database': + case 'point': + case 'import-state': + return described + } + } +} + +function reservationId(operation: { preparationId: number } | { conversionId: number }): number { + return 'preparationId' in operation ? operation.preparationId : operation.conversionId +} + function chatHash(sessionId: string): string { return createHash('sha256').update(sessionId).digest('hex').slice(0, 8) } 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 54f4f9b2c44a..2d03672d7896 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 @@ -11,7 +11,7 @@ import { restoreJournalSqlFailure } from './journal-sql-failure' import { AgentSessionJournalError } from './writing/journal-write-guards' import { claimJournalReaderRecord, - describeJournalReaderOperation, + JournalReaderReservedChats, recordJournalReaderRequest, type JournalReaderRunningRequest, releaseJournalReaderRecord @@ -94,8 +94,7 @@ export class ReaderSlot { >() private record?: number private running?: { id: number; queued: number; request: JournalReaderRunningRequest } - /** A fork or conversion reservation's later steps name the chat its first step opened. */ - private readonly reservedChats = new Map() + private readonly reservedChats = new JournalReaderReservedChats() failed = false private failure?: Error private conversions = 0 @@ -282,7 +281,7 @@ export class ReaderSlot { id === this.running?.id ? { ...this.running.request, queued } : { - ...this.describe(id, operation), + ...this.reservedChats.describe(id, operation), startedAt: Date.now(), queued, threadId: this.worker.threadId @@ -290,41 +289,4 @@ export class ReaderSlot { this.running = { id, queued, request } recordJournalReaderRequest(this.record, request) } - - private describe( - id: number, - operation: JournalSqlReaderOperation - ): Pick { - const described = describeJournalReaderOperation(operation) - switch (operation.kind) { - case 'fork-prepare': - case 'conversion-prepare': - this.reservedChats.set(id, described.chat) - return described - case 'fork-next': - case 'conversion-page': - return { ...described, chat: this.reservedChat(operation) } - case 'fork-release': - case 'conversion-release': { - const chat = this.reservedChat(operation) - this.reservedChats.delete(reservationId(operation)) - return { ...described, chat } - } - case 'domain-history': - case 'database': - case 'point': - case 'import-state': - return described - } - } - - private reservedChat( - operation: { preparationId: number } | { conversionId: number } - ): string | null { - return this.reservedChats.get(reservationId(operation)) ?? null - } -} - -function reservationId(operation: { preparationId: number } | { conversionId: number }): number { - return 'preparationId' in operation ? operation.preparationId : operation.conversionId } From 4dab3e08b66497996aaa4f9e3facd8593d403321 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Tue, 17 Nov 2026 15:53:16 -0800 Subject: [PATCH 06/11] fix(diagnostics): carry a reservation's chat on its reader handle instead of a slot map A preparation that returned no reader or failed left its entry behind. --- .../journal-sql-reader-requests.ts | 36 -------- .../journal-sql-reader-slot.ts | 84 +++++++++++-------- 2 files changed, 51 insertions(+), 69 deletions(-) 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 index f2ab388e65d9..dd3a5ecf8a9e 100644 --- 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 @@ -91,42 +91,6 @@ export function describeJournalReaderOperation( } } -/** A fork or conversion reservation's later steps name the chat its first step opened. */ -export class JournalReaderReservedChats { - private readonly chats = new Map() - - describe( - id: number, - operation: JournalSqlReaderOperation - ): Pick { - const described = describeJournalReaderOperation(operation) - switch (operation.kind) { - case 'fork-prepare': - case 'conversion-prepare': - this.chats.set(id, described.chat) - return described - case 'fork-next': - case 'conversion-page': - return { ...described, chat: this.chats.get(reservationId(operation)) ?? null } - case 'fork-release': - case 'conversion-release': { - const chat = this.chats.get(reservationId(operation)) ?? null - this.chats.delete(reservationId(operation)) - return { ...described, chat } - } - case 'domain-history': - case 'database': - case 'point': - case 'import-state': - return described - } - } -} - -function reservationId(operation: { preparationId: number } | { conversionId: number }): number { - return 'preparationId' in operation ? operation.preparationId : operation.conversionId -} - function chatHash(sessionId: string): string { return createHash('sha256').update(sessionId).digest('hex').slice(0, 8) } 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 2d03672d7896..5c37505653da 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 @@ -11,7 +11,7 @@ import { restoreJournalSqlFailure } from './journal-sql-failure' import { AgentSessionJournalError } from './writing/journal-write-guards' import { claimJournalReaderRecord, - JournalReaderReservedChats, + describeJournalReaderOperation, recordJournalReaderRequest, type JournalReaderRunningRequest, releaseJournalReaderRecord @@ -31,13 +31,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') } @@ -45,7 +46,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)) } @@ -59,14 +60,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') } @@ -75,7 +77,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)) } @@ -88,13 +90,13 @@ export class ReaderSlot { 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 } - private readonly reservedChats = new JournalReaderReservedChats() failed = false private failure?: Error private conversions = 0 @@ -159,17 +161,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') { @@ -179,20 +184,29 @@ 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 + /** `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 } { @@ -210,7 +224,7 @@ export class ReaderSlot { } this.worker.ref() const result = new Promise((resolve, reject) => { - this.pending.set(id, { operation, resolve, reject }) + this.pending.set(id, { operation, chat, resolve, reject }) this.recordRunning() void this.ready.promise .then(() => { @@ -276,16 +290,20 @@ export class ReaderSlot { recordJournalReaderRequest(this.record, null) return } - const [id, { operation }] = oldest - const request: JournalReaderRunningRequest = - id === this.running?.id - ? { ...this.running.request, queued } - : { - ...this.reservedChats.describe(id, operation), - startedAt: Date.now(), - queued, - threadId: this.worker.threadId - } + const [id, { operation, chat }] = oldest + let request: JournalReaderRunningRequest + if (id === this.running?.id) { + request = { ...this.running.request, queued } + } else { + const described = describeJournalReaderOperation(operation) + request = { + operation: described.operation, + chat: chat === undefined ? described.chat : chat, + startedAt: Date.now(), + queued, + threadId: this.worker.threadId + } + } this.running = { id, queued, request } recordJournalReaderRequest(this.record, request) } From e0a028f0fe5bf64d724c54310601908994aa0415 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Tue, 17 Nov 2026 15:56:46 -0800 Subject: [PATCH 07/11] refactor(diagnostics): the reader pool and its records share one reader limit --- .../agent-session-journal/journal-sql-reader-pool.ts | 3 ++- .../journal-sql-reader-requests.ts | 11 +++++++---- 2 files changed, 9 insertions(+), 5 deletions(-) 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.ts b/src/main/native-chat/agent-session-journal/journal-sql-reader-requests.ts index dd3a5ecf8a9e..0b572c74f3bf 100644 --- 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 @@ -18,10 +18,13 @@ export type JournalReaderRunningRequest = { type RunningRequestSink = (reader: number, request: JournalReaderRunningRequest | null) => void -/** The pool runs at most four readers; a closing reader frees its record first. */ -const READERS = 4 -const owners: (ReaderSlot | undefined)[] = Array.from({ length: READERS }) -const running: (JournalReaderRunningRequest | null)[] = Array.from({ length: READERS }, () => null) +/** 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 { From 1ab54972a83b42293f41f3fb53982b63f0cff17a Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Tue, 17 Nov 2026 19:09:06 -0800 Subject: [PATCH 08/11] fix(diagnostics): a reader host's exit names only its own readers' reads; an in-process fallback reader keeps its thread id The generic utility worker host takes its exit context from its owner instead of importing chat reader state. --- src/main/host/electron-journal-reader-host.ts | 7 ++++++- .../journal-sql-reader-requests.ts | 10 +++++++--- .../journal-sql-reader-slot.ts | 11 ++++++++++- src/main/utility-worker-host/hosted-worker.ts | 5 +++++ .../utility-worker-host/utility-worker-host.ts | 14 +++++++------- 5 files changed, 35 insertions(+), 12 deletions(-) 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-requests.ts b/src/main/native-chat/agent-session-journal/journal-sql-reader-requests.ts index c30fb994f198..5a94ebd438d8 100644 --- 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 @@ -14,7 +14,7 @@ export type JournalReaderRunningRequest = { startedAt: number /** Requests waiting behind this one on the same reader, kept current. */ queued: number - /** Null for a reader hosted in the utility process. */ + /** Null while the reader runs inside the utility process. */ threadId: number | null } @@ -58,8 +58,12 @@ export function recordJournalReaderRequest( } } -export function readJournalReaderRequests(): (JournalReaderRunningRequest & { reader: number })[] { - return running.flatMap((request, reader) => (request ? [{ ...request, reader }] : [])) +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. */ 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 db905d2bea26..52d4b6ba5521 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 @@ -190,6 +190,10 @@ export class ReaderSlot { } /** `chat` names a reservation step's chat, which its operation doesn't carry. */ + runsOn(workers: readonly unknown[]): boolean { + return workers.includes(this.worker) + } + request( operation: JournalSqlReaderOperation, chat?: string | null @@ -295,10 +299,15 @@ export class ReaderSlot { chat: chat === undefined ? described.chat : chat, startedAt: Date.now(), queued, - threadId: 'threadId' in this.worker ? Number(this.worker.threadId) : null + threadId: workerThreadId(this.worker) } } this.running = { id, queued, request } recordJournalReaderRequest(this.record, request) } } + +/** A thread's id, including a hosted reader moved in-process; null inside the utility process. */ +function workerThreadId(worker: JournalSqlReaderWorker): number | null { + return 'threadId' in worker && typeof worker.threadId === 'number' ? worker.threadId : null +} 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 e77ac31f5ec7..48d29042a2f3 100644 --- a/src/main/utility-worker-host/utility-worker-host.ts +++ b/src/main/utility-worker-host/utility-worker-host.ts @@ -3,10 +3,6 @@ import { app, utilityProcess, type UtilityProcess } from 'electron' import type { CrashReportBreadcrumbData } from '../../shared/crash-reporting/crash-reporting' import { recordDurableCrashBreadcrumb } from '../crash-reporting/breadcrumbs/durable-crash-breadcrumb' import { HostedWorker } from './hosted-worker' -import { - journalReaderRequestData, - readJournalReaderRequests -} from '../native-chat/agent-session-journal/journal-sql-reader-requests' import type { HostedWorkerThread, UtilityWorkerHostEvent, @@ -57,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 @@ -229,8 +229,8 @@ export class UtilityWorkerHost { data[`w${index}_lastReply`] = worker.lastReplyType data[`w${index}_receivedMB`] = Math.round(worker.receivedBytes / 2 ** 20) }) - // Before the readers fail their pending reads, which clears these records. - Object.assign(data, journalReaderRequestData(readJournalReaderRequests())) + // 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})`) From cf9da3e3f2ea2d57aeca965499465cc30d080259 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Tue, 17 Nov 2026 19:11:46 -0800 Subject: [PATCH 09/11] fix(diagnostics): refresh a reader's record once it moves in-process --- .../journal-sql-reader-slot.ts | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) 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 52d4b6ba5521..8888b1dc3ef8 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 @@ -117,6 +117,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() } @@ -189,11 +191,11 @@ export class ReaderSlot { } } - /** `chat` names a reservation step's chat, which its operation doesn't carry. */ 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 @@ -280,7 +282,12 @@ export class ReaderSlot { } const oldest = this.pending.entries().next().value const queued = this.pending.size - 1 - if (oldest?.[0] === this.running?.id && queued === this.running?.queued) { + const threadId = workerThreadId(this.worker) + if ( + oldest?.[0] === this.running?.id && + queued === this.running?.queued && + threadId === this.running?.request.threadId + ) { return } if (!oldest) { @@ -291,7 +298,7 @@ export class ReaderSlot { const [id, { operation, chat }] = oldest let request: JournalReaderRunningRequest if (id === this.running?.id) { - request = { ...this.running.request, queued } + request = { ...this.running.request, queued, threadId } } else { const described = describeJournalReaderOperation(operation) request = { @@ -299,7 +306,7 @@ export class ReaderSlot { chat: chat === undefined ? described.chat : chat, startedAt: Date.now(), queued, - threadId: workerThreadId(this.worker) + threadId } } this.running = { id, queued, request } From d5f657ba0f04685c4d044ba444c430a3db545d95 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Tue, 17 Nov 2026 19:21:54 -0800 Subject: [PATCH 10/11] perf(diagnostics): clear a reader's record only when one is set --- .../agent-session-journal/journal-sql-reader-slot.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) 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 8888b1dc3ef8..80ea1c7e474d 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 @@ -291,8 +291,10 @@ export class ReaderSlot { return } if (!oldest) { - this.running = undefined - recordJournalReaderRequest(this.record, null) + if (this.running) { + this.running = undefined + recordJournalReaderRequest(this.record, null) + } return } const [id, { operation, chat }] = oldest From 94369241f7b0e1cc853c454401d02eb921a63e34 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Tue, 17 Nov 2026 21:56:22 -0800 Subject: [PATCH 11/11] perf(diagnostics): find a reader's oldest pending request without rescanning deleted entries --- .../journal-sql-reader-requests.ts | 6 ++++++ .../journal-sql-reader-slot.ts | 21 ++++++++++++------- 2 files changed, 20 insertions(+), 7 deletions(-) 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 index 5a94ebd438d8..07d67e7a3e77 100644 --- 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 @@ -1,6 +1,7 @@ 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' /** @@ -117,3 +118,8 @@ export function describeJournalReaderOperation( 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 80ea1c7e474d..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 @@ -10,6 +10,7 @@ import { AgentSessionJournalError } from './writing/journal-write-guards' import { claimJournalReaderRecord, describeJournalReaderOperation, + journalReaderThreadId, recordJournalReaderRequest, type JournalReaderRunningRequest, releaseJournalReaderRecord @@ -84,6 +85,8 @@ 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, { @@ -275,14 +278,23 @@ export class ReaderSlot { 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.pending.entries().next().value + const oldest = this.oldestPending() const queued = this.pending.size - 1 - const threadId = workerThreadId(this.worker) + const threadId = journalReaderThreadId(this.worker) if ( oldest?.[0] === this.running?.id && queued === this.running?.queued && @@ -315,8 +327,3 @@ export class ReaderSlot { recordJournalReaderRequest(this.record, request) } } - -/** A thread's id, including a hosted reader moved in-process; null inside the utility process. */ -function workerThreadId(worker: JournalSqlReaderWorker): number | null { - return 'threadId' in worker && typeof worker.threadId === 'number' ? worker.threadId : null -}