Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import { setImmediate, setTimeout as delay } from 'node:timers/promises'
import type { OrchestrationDb } from '../orchestration-db'
import { pruneSettledChatOutputCopies } from './settled-chat-output-copy-prune'
import { checkpointOffMainThread } from './orchestration-pass-checkpointer'
import {
deleteExpiredOrchestrationRows,
deleteRetiredRun,
EXPIRED_ROW_SWEEPS,
listRetiredRunCandidates,
type RunPartyLiveness
listRetiredRunCandidates
} from './settled-run-retention'
import { retireSettledRun, type RunPartyLiveness } from './settled-run-retirement'

const MINUTE = 60_000
const PRUNE_INTERVAL_MS = 60 * MINUTE
Expand Down Expand Up @@ -59,31 +59,14 @@ export class OrchestrationDbMaintenance {

private async pass(): Promise<void> {
if (this.pruneIsDue()) {
const settledRuns = new Map<string, boolean>()
for (let after: string | null = ''; after !== null;) {
const page = await this.slice(() =>
pruneSettledChatOutputCopies(
this.orchestrationDb,
after!,
this.chatIsReadable,
settledRuns
)
)
if (!page) {
return
}
after = page.next
}
const restoreCheckpoints = checkpointOffMainThread(this.orchestrationDb)
try {
if (!(await this.retireSettledRuns())) {
if (!(await this.prune())) {
return
}
} catch (error) {
// Recorded anyway, so a lasting failure is retried hourly, not every minute.
console.warn('[orchestration] settled Run retention failed', error)
} finally {
restoreCheckpoints()
Comment thread
brennanb2025 marked this conversation as resolved.
Resolved
}
// Persisted so a restart does not rescan before the interval.
this.recordPrune()
}
// Only incremental files can return pages; others reuse them as they are freed.
if (Number(this.orchestrationDb.db.pragma('auto_vacuum', { simple: true })) === 2) {
Expand All @@ -95,6 +78,31 @@ export class OrchestrationDbMaintenance {
}
}

/** False when stopped mid-way. */
private async prune(): Promise<boolean> {
const settledRuns = new Map<string, boolean>()
for (let after: string | null = ''; after !== null;) {
const page = await this.slice(() =>
pruneSettledChatOutputCopies(this.orchestrationDb, after!, this.chatIsReadable, settledRuns)
)
if (!page) {
return false
}
after = page.next
}
try {
if (!(await this.retireSettledRuns())) {
return false
}
} catch (error) {
// Recorded anyway, so a lasting failure is retried hourly, not every minute.
console.warn('[orchestration] settled Run retention failed', error)
}
// Persisted so a restart does not rescan before the interval.
this.recordPrune()
return true
}

/** False when stopped mid-way. */
private async retireSettledRuns(): Promise<boolean> {
const db = this.orchestrationDb
Expand All @@ -104,18 +112,22 @@ export class OrchestrationDbMaintenance {
if (!page) {
return false
}
for (const runId of page.retired) {
const step = await this.slice(() => {
try {
deleteRetiredRun(db, runId, this.runPartyLiveness)
} catch (error) {
// One Run that cannot go must not hold back the others; the next pass retries it.
console.warn('[orchestration] settled Run retention failed', { runId, error })
for (const runId of page.candidates) {
const steps = retireSettledRun(db, runId, this.runPartyLiveness)
for (let done = false; !done;) {
const step = await this.slice(() => {
try {
return steps.next().done === true
} catch (error) {
// One Run that cannot go must not hold back the others; the next pass retries it.
console.warn('[orchestration] settled Run retention failed', { runId, error })
return true
}
})
if (step === undefined) {
return false
}
return true
})
if (!step) {
return false
done = step
}
}
after = page.next
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import { spawnWorkerThread } from '../../../../worker-threads/worker-thread-spawn'
import type { OrchestrationDb } from '../orchestration-db'

const CHECKPOINT_INTERVAL_MS = 250

// Evaluated source, as the chat journal's checkpoint worker: a passive checkpoint never blocks the writer.
const checkpointWorkerSource = `
const { workerData } = require('node:worker_threads');
const { DatabaseSync } = require('node:sqlite');
const db = new DatabaseSync(workerData.filename);
if (db.prepare('PRAGMA journal_mode').get().journal_mode !== 'wal') {
throw new Error('orchestration database is not in WAL mode');
}
db.exec('PRAGMA busy_timeout = 1000;');
const checkpoint = db.prepare('PRAGMA wal_checkpoint(PASSIVE)');
let failures = 0;
setInterval(() => {
try {
checkpoint.get();
failures = 0;
} catch (error) {
// Exiting hands checkpoints back to main rather than letting the WAL grow.
if (++failures >= 3) throw error;
}
}, workerData.intervalMs);
`

/**
* While a maintenance pass writes, checkpoints the WAL on a worker thread instead of in main's commits:
* an auto-checkpointing commit fsyncs the whole file and blocked main for up to 934 ms on a busy disk.
* Returns the undo; a worker that fails or exits hands checkpoints back to main at once.
*/
export function checkpointOffMainThread({ db }: OrchestrationDb): () => void {
const main = db
.prepare('PRAGMA database_list')
.all()
.find((row) => row.name === 'main')
const filename = typeof main?.file === 'string' ? main.file : ''
if (!filename) {
return () => {}
}
const previous = Number(db.pragma('wal_autocheckpoint', { simple: true }))
let worker: ReturnType<typeof spawnWorkerThread>
try {
worker = spawnWorkerThread(checkpointWorkerSource, {
name: 'orca-orchestration-checkpoint',
eval: true,
workerData: { filename, intervalMs: CHECKPOINT_INTERVAL_MS }
})
} catch {
return () => {}
}
let restored = false
const restore = (): void => {
if (!restored) {
restored = true
try {
db.pragma(`wal_autocheckpoint = ${previous}`)
} catch {
// A closed database has no threshold left to restore.
}
}
}
worker.on('error', restore)
worker.on('exit', restore)
worker.unref()
db.pragma('wal_autocheckpoint = 0')
return () => {
worker.terminate().catch(() => {})
restore()
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,9 @@ import { OrchestrationDb } from '../orchestration-db'
import {
deleteExpiredOrchestrationRows,
EXPIRED_ROW_SWEEPS,
deleteRetiredRun,
listRetiredRunCandidates,
type RunPartyLiveness
listRetiredRunCandidates
} from './settled-run-retention'
import { deleteRetiredRun, retireSettledRun, type RunPartyLiveness } from './settled-run-retirement'
import '../contract-constants'
import '../messages/mailbox-routing-page'
import '../dispatch-row-writer'
Expand Down Expand Up @@ -133,7 +132,7 @@ describe('settled Run retention', () => {
settle(settled.run.id)
ageEveryTimestamp()

expect(listRetiredRunCandidates(db!, '', 10).retired).toEqual([settled.run.id])
expect(listRetiredRunCandidates(db!, '', 10).candidates).toContain(settled.run.id)
expect(deleteRetiredRun(db!, live.run.id, nobodyIsLive)).toBe(false)
expect(deleteRetiredRun(db!, settled.run.id, nobodyIsLive)).toBe(true)

Expand All @@ -160,6 +159,125 @@ describe('settled Run retention', () => {
expect(count('worker_terminal_resources WHERE owner_dispatch_id = ?', live.dispatchId)).toBe(1)
})

it('deletes a large settled Run a bounded page at a time, its Run row last', () => {
const { run } = createRunWithWorker('large')
for (let n = 0; n < 1_000; n++) {
db!.insertMessage({
runId: run.id,
from: 'term_large',
to: `run:${run.id}`,
subject: `m${n}`
})
}
for (let n = 0; n < 300; n++) {
db!.createTask({ spec: `task ${n}`, runId: run.id })
}
const insertDelivery = db!.db.prepare(
`INSERT INTO deliveries (id, run_id, consumer_generation, message_ids, status)
VALUES (?, ?, 1, '[]', 'acknowledged')`
)
for (let n = 0; n < 300; n++) {
insertDelivery.run(`delivery_${n}`, run.id)
}
settle(run.id)
ageEveryTimestamp()
const totalChanges = (): number =>
Number(db!.db.prepare('SELECT total_changes() AS n').get()?.n)

// A quit midway leaves the Run, with fewer settled rows, for the next pass to finish.
const interrupted = retireSettledRun(db!, run.id, nobodyIsLive)
for (let step = 0; step < 12; step++) {
expect(interrupted.next().done).toBe(false)
}
expect(db!.getRun(run.id)).toBeDefined()

const steps = retireSettledRun(db!, run.id, nobodyIsLive)
let maxStepChanges = 0
for (;;) {
const before = totalChanges()
const step = steps.next()
maxStepChanges = Math.max(maxStepChanges, totalChanges() - before)
if (step.done) {
expect(step.value).toBe(true)
break
}
expect(db!.getRun(run.id)).toBeDefined()
}
// One table page of 128 rows, plus the removed-work record each Task delete writes.
expect(maxStepChanges).toBeLessThanOrEqual(256)
expect(db!.getRun(run.id)).toBeUndefined()
expect(count('messages WHERE run_id = ?', run.id)).toBe(0)
expect(count('tasks WHERE run_id = ?', run.id)).toBe(0)
expect(count('deliveries WHERE run_id = ?', run.id)).toBe(0)
expect(count('removed_orchestration_work')).toBe(0)
})

it('stops retiring a Run whose coordinator pane comes back between pages', () => {
const { run } = createRunWithWorker('reattached')
for (let n = 0; n < 200; n++) {
db!.insertMessage({ runId: run.id, from: 'worker', to: `run:${run.id}`, subject: `m${n}` })
}
settle(run.id)
ageEveryTimestamp()
let paneLive = false
const steps = retireSettledRun(db!, run.id, {
isLiveHandle: () => false,
isLivePane: (paneKey) => paneLive && paneKey === `tab_reattached:${PANE_LEAF}`
})
let step = steps.next()
while (!step.done && count('messages WHERE run_id = ?', run.id) === 201) {
step = steps.next()
}
paneLive = true
while (!step.done) {
step = steps.next()
}

expect(step.value).toBe(false)
expect(db!.getRun(run.id)).toBeDefined()
expect(count('messages WHERE run_id = ?', run.id)).toBeGreaterThan(0)
})

it('keeps a Run and its new gate when a gate opens between pages', () => {
const { run, task } = createRunWithWorker('gated')
for (let n = 0; n < 200; n++) {
db!.insertMessage({ runId: run.id, from: 'worker', to: `run:${run.id}`, subject: `m${n}` })
}
settle(run.id)
ageEveryTimestamp()
const steps = retireSettledRun(db!, run.id, nobodyIsLive)
let step = steps.next()
while (!step.done && count("worker_terminal_resources WHERE id = 'resource_gated'") === 1) {
step = steps.next()
}
db!.createGate({ taskId: task.id, question: 'Ship it?' })
while (!step.done) {
step = steps.next()
}

expect(step.value).toBe(false)
expect(db!.getRun(run.id)).toBeDefined()
expect(count("decision_gates WHERE run_id = ? AND status = 'pending'", run.id)).toBe(1)
})

it('keeps a Run whose Task is reopened between pages', () => {
const { run, task } = createRunWithWorker('reopened')
settle(run.id)
ageEveryTimestamp()
const steps = retireSettledRun(db!, run.id, nobodyIsLive)
let step = steps.next()
while (!step.done && count("worker_terminal_resources WHERE id = 'resource_reopened'") === 1) {
step = steps.next()
}
db!.db.prepare("UPDATE tasks SET status = 'ready' WHERE id = ?").run(task.id)
while (!step.done) {
step = steps.next()
}

expect(step.value).toBe(false)
expect(count("tasks WHERE id = ? AND status = 'ready'", task.id)).toBe(1)
})

it('keeps a settled Run while its coordinator, a reader of its unread mail or its worker terminal is live', () => {
const { run } = createRunWithWorker('bound')
db!.insertMessage({ runId: run.id, from: 'worker', to: 'term_reader', subject: 'note' })
Expand All @@ -184,7 +302,7 @@ describe('settled Run retention', () => {
const { run } = createRunWithWorker('recent')
settle(run.id)

expect(listRetiredRunCandidates(db!, '', 10).retired).toEqual([])
expect(listRetiredRunCandidates(db!, '', 10).candidates).toEqual([])
expect(deleteRetiredRun(db!, run.id, nobodyIsLive)).toBe(false)
expect(db!.getRun(run.id)).toBeDefined()
})
Expand Down
Loading
Loading