Skip to content
Original file line number Diff line number Diff line change
Expand Up @@ -60,11 +60,27 @@ export class JournalHostDatabase {
return connection
}

/** One IMMEDIATE transaction; see `runJournalTransaction`. */
transaction<T>(run: (db: Database.Database) => T): T {
return runJournalTransaction(this.db, run, () => {
this.stranded = true
})
/** One IMMEDIATE transaction; see `runJournalTransaction`. `streamed` commits without the per-commit
* fsync: only for rows an OS crash may lose (`isJournalStreamedTextRevision`); the next FULL
* commit makes them durable, so a crash can only lose a suffix of them. */
transaction<T>(run: (db: Database.Database) => T, streamed = false): T {
const db = this.db
if (!streamed) {
return runJournalTransaction(db, run, () => {
this.stranded = true
})
}
// The level can change only outside a transaction; a stranded one restores FULL on recovery.
db.pragma('synchronous = NORMAL')
try {
return runJournalTransaction(db, run, () => {
this.stranded = true
})
} finally {
if (!db.isTransaction) {
db.pragma('synchronous = FULL')
}
}
}

/** Last, after every store has drained. A close that fails keeps the handle, so the retried
Expand All @@ -87,6 +103,7 @@ export class JournalHostDatabase {
throw journalOpenRefusalError(error)
}
}
connection.pragma('synchronous = FULL')
this.stranded = false
}
}
40 changes: 27 additions & 13 deletions src/main/native-chat/agent-session-journal/journal-row-writer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,9 @@ export type JournalRowWriterDeps = {
inTransaction?: JournalRowTransactionHook
/** After any rollback, so a cache filled inside the transaction cannot outlive it. */
rolledBack?: () => void
/** Rows an OS crash may lose without losing anything but streamed text; they commit without
* the per-commit fsync (`isJournalStreamedTextRevision`). */
streamedTextRevision?: (row: JournalRow) => boolean
}

const BOOKKEEPING_SAVEPOINT = 'journal_row_bookkeeping'
Expand All @@ -77,12 +80,15 @@ export class JournalRowWriter {
assertJournalFence(row.fence, this.deps.highestFence())
try {
// One INSERT: the chat's epoch pointer moves only when the epoch does.
this.deps.database().transaction((db) => {
insertJournalRow(db, this.deps.sessionId, row, savedAt)
hook?.(db, row)
receipt?.write(db, row)
this.runBookkeeping(db, row)
})
this.deps.database().transaction(
(db) => {
insertJournalRow(db, this.deps.sessionId, row, savedAt)
hook?.(db, row)
receipt?.write(db, row)
this.runBookkeeping(db, row)
},
!hook && !receipt && this.streamed([row])
)
} catch (error) {
this.deps.rolledBack?.()
throw error
Expand Down Expand Up @@ -124,13 +130,16 @@ export class JournalRowWriter {
assertJournalFence(row.fence, this.deps.highestFence())
}
try {
this.deps.database().transaction((db) => {
for (const row of rows) {
insertJournalRow(db, this.deps.sessionId, row, ts)
this.runBookkeeping(db, row)
}
receipt?.write(db, receiptRow?.(rows))
})
this.deps.database().transaction(
(db) => {
for (const row of rows) {
insertJournalRow(db, this.deps.sessionId, row, ts)
this.runBookkeeping(db, row)
}
receipt?.write(db, receiptRow?.(rows))
},
!receipt && this.streamed(rows)
)
} catch (error) {
this.deps.rolledBack?.()
throw error
Expand All @@ -153,6 +162,11 @@ export class JournalRowWriter {
}))
}

private streamed(rows: readonly JournalRow[]): boolean {
const { streamedTextRevision } = this.deps
return streamedTextRevision !== undefined && rows.every((row) => streamedTextRevision(row))
}

private runBookkeeping(db: Database.Database, row: JournalRow): void {
const hook = this.deps.inTransaction
if (!hook) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import type { AgentSessionJournal } from './journal-store'
import type { JournalWriteBody } from './journal-write-queue'
import type { JournalAttachmentClaim } from './journal-submission-hook'
import { claimAgentSessionAttachmentsInTransaction } from '../agent-session-attachments/agent-session-attachment-claims'
import { isJournalStreamedTextRevision } from './journal-streamed-text-revision'

export type JournalStoreHost = {
/** Fires the journal's commit listener for a durable change that appended no
Expand Down Expand Up @@ -117,7 +118,8 @@ export function createJournalStoreCollaborators(host: JournalStoreHost): Journal
// Every rejection is a dispatch row through this one writer; the draft
// returned-transition rides it so no path can bypass the hook.
inTransaction: (db, row) => queuedMessages.onRowInTransaction(db, row),
rolledBack: () => queuedMessages.invalidate()
rolledBack: () => queuedMessages.invalidate(),
streamedTextRevision: (row) => isJournalStreamedTextRevision(host.state(), row)
})
const lifecycleBatchAppender = new JournalLifecycleBatchAppender({
state: host.state,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
import type { AgentJournalItemBody } from '../../../shared/agent-session-journal-types'
import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types'
import { codexImageItemBody } from '../../codex/codex-image-item-translation'
import { journalPragmaNumber } from './journal-database'
import {
closeTestJournalHostDatabases,
openTestJournalHostDatabase
} from './journal-host-database-test-support'
import { openAgentSessionJournal } from './journal-store-factory'

let root: string

beforeEach(async () => {
root = await mkdtemp(join(tmpdir(), 'orca-streamed-revision-'))
})
afterEach(async () => {
vi.restoreAllMocks()
closeTestJournalHostDatabases()
await rm(root, { recursive: true, force: true })
})

const text = (role: 'assistant' | 'user', value: string): AgentJournalItemBody => ({
kind: 'message',
role,
blocks: [{ type: 'text', text: value }]
})

it('commits streamed text at NORMAL, Codex image transitions at FULL, and restores FULL', async () => {
const database = openTestJournalHostDatabase(root)
const levels: number[] = []
database.transaction((db) => levels.push(journalPragmaNumber(db, 'synchronous')), true)
levels.push(journalPragmaNumber(database.db, 'synchronous'))
database.transaction((db) => levels.push(journalPragmaNumber(db, 'synchronous')))
expect(() =>
database.transaction(() => {
throw new Error('rolled back')
}, true)
).toThrow('rolled back')
levels.push(journalPragmaNumber(database.db, 'synchronous'))
expect(levels).toEqual([1, 2, 2, 2])
const journal = await openAgentSessionJournal({
database,
identity: {
sessionId: 'chat',
workspaceId: 'workspace',
hostId: 'host',
agent: 'codex',
providerHandle: null
}
})
levels.length = 0
const exec = database.db.exec.bind(database.db)
vi.spyOn(database.db, 'exec').mockImplementation((sql) => {
if (sql === 'COMMIT') {
levels.push(journalPragmaNumber(database.db, 'synchronous'))
}
exec(sql)
})
const image = { id: 'image', type: 'imageGeneration' }
for (const body of [
text('assistant', 'Generating image'),
codexImageItemBody({ ...image, status: 'inProgress' }),
codexImageItemBody({ ...image, status: 'completed', result: 'AAAA' }),
text('assistant', 'Image preview unavailable')
]) {
await journal.appendItem(
{ provider: 'codex', threadId: 'thread', turnId: 'turn', ordinal: 1 },
body,
{ fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE }
)
}
expect(levels).toEqual([2, 1, 2, 2])
expect(journalPragmaNumber(database.db, 'synchronous')).toBe(2)
await journal.close()
})
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { isDeepStrictEqual } from 'node:util'
import { agentJournalLinkageFields } from '../../../shared/agent-session-journal-producer'
import type { JournalReducerState } from './journal-reducer'
import type { JournalRow } from './journal-row-schema'

/**
* A later revision of an assistant message that changes only its content. An OS crash that loses
* it loses streamed text and nothing else: no send, approval, stop, ownership or turn fact rides
* it, and a turn's settlement is written FULL after it, which makes it durable. Everything else
* keeps the per-commit fsync.
*/
export function isJournalStreamedTextRevision(
state: JournalReducerState,
row: JournalRow
): boolean {
if (row.kind !== 'item' || row.recovered) {
return false
}
const { body } = row
const previous = state.items.get(row.itemId)
if (
body.kind !== 'message' ||
body.role !== 'assistant' ||
!body.blocks.every((block) => block.type === 'text') ||
body.sentAs !== undefined ||
body.command !== undefined ||
body.from !== undefined ||
Comment thread
brennanb2025 marked this conversation as resolved.
Resolved
previous?.body.kind !== 'message' ||
previous.body.role !== 'assistant' ||
!previous.body.blocks.every((block) => block.type === 'text')
) {
return false
}
const ownerFence = state.itemFences.get(row.itemId)
return (
(row.ownerFence ?? ownerFence) === ownerFence &&
(row.executionOwner === undefined ||
row.executionOwner === state.itemExecutionOwners.get(row.itemId)) &&
Comment thread
brennanb2025 marked this conversation as resolved.
Resolved
(row.turnScope === undefined || isDeepStrictEqual(row.turnScope, previous.turnScope)) &&
isDeepStrictEqual(agentJournalLinkageFields(row), agentJournalLinkageFields(previous))
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
)
}
Loading