mirror of
https://github.com/stablyai/orca.git
synced 2026-11-19 04:23:57 +00:00
Retain streamed text durability and bound SQL writer batches
This commit is contained in:
@@ -1,6 +1,8 @@
|
||||
import { afterEach, expect, it, vi } from 'vitest'
|
||||
import Database from '../../sqlite/sync-database'
|
||||
import { JournalSqlBatch, JournalSqlBatchError } from './journal-sql-batch'
|
||||
import { takeJournalSqlReadyBatch } from './journal-sql-ready-batch'
|
||||
import type { JournalSqlRequest } from './journal-sql-protocol'
|
||||
|
||||
const databases: Database.Database[] = []
|
||||
afterEach(() => {
|
||||
@@ -89,6 +91,45 @@ it('leaves newly admitted work for a new drain with its own durability', async (
|
||||
])
|
||||
})
|
||||
|
||||
it('commits a control receipt before later streamed work with its own durability', async () => {
|
||||
const { db, batch } = fixture()
|
||||
const stream = (id: number): JournalSqlRequest => ({
|
||||
id,
|
||||
command: {
|
||||
type: 'write',
|
||||
command: {
|
||||
target: { sessionId: 'session', epoch: 'epoch', ownerToken: 'owner' },
|
||||
operation: {
|
||||
kind: 'item',
|
||||
identity: { provider: 'orca', clientMessageId: 'output' },
|
||||
body: { kind: 'message', role: 'assistant', blocks: [{ type: 'text', text: 'output' }] },
|
||||
options: { fence: 1, turnScope: { kind: 'thread' } }
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
const queue: JournalSqlRequest[] = [
|
||||
stream(1),
|
||||
{ id: 2, command: { type: 'effects', effects: [] } },
|
||||
stream(3)
|
||||
]
|
||||
const commit = async () =>
|
||||
batch.run(
|
||||
takeJournalSqlReadyBatch(queue, () => true).map(({ request, normal }) => ({
|
||||
command: request,
|
||||
normal
|
||||
})),
|
||||
(request) => {
|
||||
db.prepare('INSERT INTO writes VALUES (?, ?)').run(request.id, 'written')
|
||||
return { id: request.id, durability: db.pragma('synchronous', { simple: true }) }
|
||||
}
|
||||
)
|
||||
expect((await commit()).outcomes).toEqual([{ committed: true, value: { id: 1, durability: 1 } }])
|
||||
expect((await commit()).outcomes).toEqual([{ committed: true, value: { id: 2, durability: 2 } }])
|
||||
expect(db.prepare('SELECT id FROM writes ORDER BY id').all()).toEqual([{ id: 1 }, { id: 2 }])
|
||||
expect((await commit()).outcomes).toEqual([{ committed: true, value: { id: 3, durability: 1 } }])
|
||||
})
|
||||
|
||||
it.each([false, true])(
|
||||
'treats a lost COMMIT answer as indeterminate, whether the commit took effect: %s',
|
||||
async (committed) => {
|
||||
|
||||
@@ -272,9 +272,29 @@ it('chooses NORMAL only for proven text revisions and retains FULL for settlemen
|
||||
engine.apply(entry, 100)
|
||||
)
|
||||
const revision = command(item('next'))
|
||||
const textStep: JournalWriterStep = {
|
||||
kind: 'resolved-item',
|
||||
reservedBytes: 4096,
|
||||
resolution: {
|
||||
kind: 'text-snapshot',
|
||||
identity,
|
||||
body: { kind: 'message', role: 'assistant', blocks: [{ type: 'text', text: 'streamed' }] }
|
||||
},
|
||||
options: { fence: 1, turnScope: { kind: 'thread' } }
|
||||
}
|
||||
const steps = command({ kind: 'steps', steps: [textStep] })
|
||||
db.pragma('query_only = ON')
|
||||
try {
|
||||
expect(engine.streamed(revision)).toBe(true)
|
||||
expect(engine.streamed(steps)).toBe(true)
|
||||
expect(
|
||||
engine.streamed(
|
||||
command({
|
||||
kind: 'steps',
|
||||
steps: [{ ...textStep, options: { ...textStep.options, executionOwner: 2 } }]
|
||||
})
|
||||
)
|
||||
).toBe(false)
|
||||
} finally {
|
||||
db.pragma('query_only = OFF')
|
||||
}
|
||||
@@ -286,7 +306,7 @@ it('chooses NORMAL only for proven text revisions and retains FULL for settlemen
|
||||
).toBe(false)
|
||||
expect(engine.streamed(command({ kind: 'queue-resume', fence: 1 }))).toBe(false)
|
||||
let synchronous = -1
|
||||
await batch.run([{ command: revision, normal: engine.streamed(revision) }], (entry) => {
|
||||
await batch.run([{ command: steps, normal: engine.streamed(steps) }], (entry) => {
|
||||
synchronous = Number(db.pragma('synchronous', { simple: true }))
|
||||
return engine.apply(entry, 100)
|
||||
})
|
||||
|
||||
@@ -9,6 +9,7 @@ import { planJournalWriterRows } from './journal-writer-plan'
|
||||
import type { JournalOperationReceipt } from './writing/journal-row-writer'
|
||||
import { runJournalSqlSteps } from './journal-sql-steps'
|
||||
import { isJournalStreamedTextRevision } from './writing/journal-streamed-text-revision'
|
||||
import { planJournalWriterStep } from './writing/journal-writer-step-plan'
|
||||
import {
|
||||
claimJournalSqlProjection,
|
||||
journalLogNeedsFounding,
|
||||
@@ -23,13 +24,32 @@ export class JournalSqlCommand {
|
||||
|
||||
/** Conservative preflight only; all authority and revision assignment are repeated in apply(). */
|
||||
streamed(command: JournalWriterCommand): boolean {
|
||||
if (command.effects || command.operation.kind !== 'item') {
|
||||
if (command.effects) {
|
||||
return false
|
||||
}
|
||||
try {
|
||||
const { state } = this.session(command, 0)
|
||||
const row = planJournalWriterRows(state, command.operation)[0]!(state.lastSequence + 1, 0)
|
||||
return isJournalStreamedTextRevision(state, row)
|
||||
const { operation } = command
|
||||
if (operation.kind === 'steps') {
|
||||
return operation.steps.every((step) => {
|
||||
if (step.kind === 'settlement' || step.kind === 'creation-fact') {
|
||||
return false
|
||||
}
|
||||
const planned = planJournalWriterStep(state, step, () => {})
|
||||
return (
|
||||
planned === null ||
|
||||
planned.every((build) =>
|
||||
isJournalStreamedTextRevision(state, build(state.lastSequence + 1, 0))
|
||||
)
|
||||
)
|
||||
})
|
||||
}
|
||||
if (operation.kind !== 'item') {
|
||||
return false
|
||||
}
|
||||
return planJournalWriterRows(state, operation).every((build) =>
|
||||
isJournalStreamedTextRevision(state, build(state.lastSequence + 1, 0))
|
||||
)
|
||||
} catch {
|
||||
// A stale/invalid command fails its own SAVEPOINT; it must not downgrade the batch.
|
||||
return false
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
import type { JournalSqlRequest } from './journal-sql-protocol'
|
||||
import type { JournalWriterCommand } from './journal-writer-command'
|
||||
import { journalSqlMaintenanceIsNormal } from './journal-sql-maintenance'
|
||||
|
||||
const MAX_EVENTS = 64
|
||||
const MAX_BYTES = 1024 * 1024
|
||||
|
||||
/** Control commands keep their own boundary; an oversized atomic command runs alone. */
|
||||
export function takeJournalSqlReadyBatch(
|
||||
queue: JournalSqlRequest[],
|
||||
streamed: (command: JournalWriterCommand) => boolean
|
||||
): { request: JournalSqlRequest; normal: boolean }[] {
|
||||
const batch: { request: JournalSqlRequest; normal: boolean }[] = []
|
||||
let events = 0
|
||||
let bytes = 0
|
||||
for (const request of queue) {
|
||||
const { command } = request
|
||||
const normal = command.type === 'write' && streamed(command.command)
|
||||
if (!normal) {
|
||||
if (batch.length === 0) {
|
||||
batch.push({
|
||||
request,
|
||||
normal: command.type === 'maintenance' && journalSqlMaintenanceIsNormal(command.operation)
|
||||
})
|
||||
}
|
||||
break
|
||||
}
|
||||
const count =
|
||||
command.command.operation.kind === 'steps'
|
||||
? Math.max(1, command.command.operation.steps.length)
|
||||
: 1
|
||||
let size: number
|
||||
try {
|
||||
size = Buffer.byteLength(JSON.stringify(command.command), 'utf8')
|
||||
} catch {
|
||||
if (batch.length === 0) {
|
||||
batch.push({ request, normal: false })
|
||||
}
|
||||
break
|
||||
}
|
||||
if (batch.length > 0 && (events + count > MAX_EVENTS || bytes + size > MAX_BYTES)) {
|
||||
break
|
||||
}
|
||||
batch.push({ request, normal: true })
|
||||
events += count
|
||||
bytes += size
|
||||
if (events >= MAX_EVENTS || bytes >= MAX_BYTES) {
|
||||
break
|
||||
}
|
||||
}
|
||||
queue.splice(0, batch.length)
|
||||
return batch
|
||||
}
|
||||
@@ -6,14 +6,12 @@ import { openJournalDatabase } from './database/journal-database'
|
||||
import { JournalCheckpointOwner } from './database/journal-checkpoint-owner'
|
||||
import { JournalSqlBatch, JournalSqlBatchError } from './journal-sql-batch'
|
||||
import { JournalSqlCommand } from './journal-sql-command'
|
||||
import { takeJournalSqlReadyBatch } from './journal-sql-ready-batch'
|
||||
import { applyJournalWriterEffect } from './journal-writer-effects'
|
||||
import { journalSqlFailure, type JournalSqlFailure } from './journal-sql-failure'
|
||||
import type { JournalSqlRequest, JournalSqlResponse } from './journal-sql-protocol'
|
||||
import { assertJournalWritable } from './writing/journal-write-guards'
|
||||
import {
|
||||
applyJournalSqlMaintenance,
|
||||
journalSqlMaintenanceIsNormal
|
||||
} from './journal-sql-maintenance'
|
||||
import { applyJournalSqlMaintenance } from './journal-sql-maintenance'
|
||||
import { initializeJournalSqlProjection } from './journal-sql-schema-migration'
|
||||
|
||||
if (
|
||||
@@ -87,13 +85,14 @@ type WriteRequest = {
|
||||
}
|
||||
type CommitResponse = Extract<JournalSqlResponse, { type: 'committed' | 'effects' | 'maintenance' }>
|
||||
|
||||
/** Capture once, then yield: a continuing stream cannot extend this transaction past its drain. */
|
||||
/** Bound ready work before opening a transaction, then yield after its acknowledgements. */
|
||||
async function drain(): Promise<void> {
|
||||
const pending = queue.splice(0)
|
||||
const pending = takeJournalSqlReadyBatch(queue, (command) => commands?.streamed(command) === true)
|
||||
const writes = pending.filter(
|
||||
(request): request is WriteRequest => request.command.type !== 'close'
|
||||
(entry): entry is { request: WriteRequest; normal: boolean } =>
|
||||
entry.request.command.type !== 'close'
|
||||
)
|
||||
const close = pending.find((request) => request.command.type === 'close')
|
||||
const close = pending.find(({ request }) => request.command.type === 'close')?.request
|
||||
const database = db
|
||||
if (writes.length > 0 && database && batch && commands) {
|
||||
const executor = commands
|
||||
@@ -105,12 +104,9 @@ async function drain(): Promise<void> {
|
||||
}
|
||||
assertJournalWritable(readOnly, 'database')
|
||||
const result = await batch.run<WriteRequest, CommitResponse>(
|
||||
writes.map((request) => ({
|
||||
writes.map(({ request, normal }) => ({
|
||||
command: request,
|
||||
normal:
|
||||
request.command.type === 'maintenance'
|
||||
? journalSqlMaintenanceIsNormal(request.command.operation)
|
||||
: request.command.type === 'write' && executor.streamed(request.command.command)
|
||||
normal
|
||||
})),
|
||||
async (request) => {
|
||||
const { command, id } = request
|
||||
@@ -144,7 +140,7 @@ async function drain(): Promise<void> {
|
||||
? outcome.value
|
||||
: {
|
||||
type: 'failed',
|
||||
id: writes[index]!.id,
|
||||
id: writes[index]!.request.id,
|
||||
outcome: 'rolled-back',
|
||||
error: journalSqlFailure(outcome.error)
|
||||
}
|
||||
@@ -155,7 +151,7 @@ async function drain(): Promise<void> {
|
||||
} catch (error) {
|
||||
const outcome = error instanceof JournalSqlBatchError ? error.outcome : 'not-dispatched'
|
||||
fault ??= batch.fault
|
||||
responses = writes.map((request) => ({
|
||||
responses = writes.map(({ request }) => ({
|
||||
type: 'failed',
|
||||
id: request.id,
|
||||
outcome,
|
||||
|
||||
Reference in New Issue
Block a user