Skip to content
Merged
Show file tree
Hide file tree
Changes from 11 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion src/main/host/electron-journal-reader-host.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand All @@ -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({
Expand Down
Original file line number Diff line number Diff line change
@@ -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'
Expand Down Expand Up @@ -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)
}
Expand Down
Original file line number Diff line number Diff line change
@@ -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([])
})
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
import { createHash } from 'node:crypto'
import type { JournalSqlReaderOperation } from './journal-sql-reader-protocol'
import type { ReaderSlot } from './journal-sql-reader-slot'
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<JournalReaderRunningRequest, 'operation' | 'chat'> {
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)
}
Loading
Loading