Revert "fix(memory): bound OOM-prone accumulators (#10179)" (#10255)

Co-authored-by: Orca <help@stably.ai>
This commit is contained in:
Neil
2026-07-23 18:35:31 -07:00
committed by GitHub
co-authored by Orca
parent 6eb70d8370
commit aab112933e
1577 changed files with 15167 additions and 91655 deletions
@@ -4,7 +4,6 @@ import type { RpcRequest } from '../core'
import { OrcaRuntimeService } from '../../orca-runtime'
import type { AiVaultListResult, AiVaultSession } from '../../../../shared/ai-vault-types'
import type { AiVaultScanOptions } from '../../../ai-vault/session-scanner-types'
import { AI_VAULT_SESSION_ID_MAX_UTF8_BYTES } from '../../../ai-vault/session-list-retention'
const { scanAiVaultSessions } = vi.hoisted(() => ({
scanAiVaultSessions: vi.fn()
@@ -182,24 +181,6 @@ describe('aiVault.listSessions handler + shared cache', () => {
expect(scanAiVaultSessions).toHaveBeenCalledTimes(1)
})
it('bounds a pathological result before retaining it in the shared cache', async () => {
const oversized = makeSession()
oversized.sessionId = 'x'.repeat(AI_VAULT_SESSION_ID_MAX_UTF8_BYTES + 1)
scanAiVaultSessions.mockResolvedValue({
sessions: [oversized],
issues: [],
scannedAt: SCANNED_AT
})
const first = await listAiVaultSessions({ limit: 500 })
const second = await listAiVaultSessions({ limit: 500 })
expect(first.sessions).toEqual([])
expect(first.issues.at(-1)?.message).toContain('AI Vault omitted')
expect(second).toBe(first)
expect(scanAiVaultSessions).toHaveBeenCalledTimes(1)
})
it('keeps a newer different-key scan dedupable after an older scan resolves', async () => {
// Why: the resolving scan's cleanup must not clear tracking a concurrent
// different-key scan replaced, or re-requests start a duplicate rescan.
@@ -1,121 +0,0 @@
const BASE64_PADDING_BYTE = '='.charCodeAt(0)
function isBase64DataByte(byte: number): boolean {
return (
(byte >= 65 && byte <= 90) ||
(byte >= 97 && byte <= 122) ||
(byte >= 48 && byte <= 57) ||
byte === 43 ||
byte === 47
)
}
export class ClipboardImageUploadBuffer {
private readonly segments: Buffer[] = []
private retainedLength = 0
constructor(
private readonly expectedLength: number,
private readonly segmentLength: number
) {}
get length(): number {
return this.retainedLength
}
append(contentBase64: string): void {
if (contentBase64.length > this.expectedLength - this.retainedLength) {
throw new Error('Clipboard image upload exceeded expected size')
}
const source = Buffer.from(contentBase64, 'ascii')
const originalLength = this.retainedLength
const originalSegmentCount = this.segments.length
let sourceOffset = 0
try {
while (sourceOffset < source.length) {
const segmentIndex = Math.floor(this.retainedLength / this.segmentLength)
const segmentOffset = this.retainedLength % this.segmentLength
let segment = this.segments[segmentIndex]
if (!segment) {
const segmentStart = segmentIndex * this.segmentLength
segment = Buffer.allocUnsafe(
Math.min(this.segmentLength, this.expectedLength - segmentStart)
)
this.segments.push(segment)
}
const copyLength = Math.min(source.length - sourceOffset, segment.length - segmentOffset)
source.copy(segment, segmentOffset, sourceOffset, sourceOffset + copyLength)
sourceOffset += copyLength
this.retainedLength += copyLength
}
} catch (error) {
this.retainedLength = originalLength
this.segments.length = originalSegmentCount
throw error
}
}
clear(): void {
this.retainedLength = 0
this.segments.length = 0
}
decode(): Buffer {
const dataLength = this.validateAndGetDataLength()
const decoded = Buffer.allocUnsafe(Math.floor((dataLength * 3) / 4))
let carry = ''
let remainingData = dataLength
let written = 0
for (const segment of this.segments) {
if (remainingData === 0) {
break
}
const segmentDataLength = Math.min(segment.length, remainingData)
const data = segment.subarray(0, segmentDataLength).toString('ascii')
const combined = carry.length > 0 ? carry + data : data
const completeLength = combined.length - (combined.length % 4)
if (completeLength > 0) {
const complete =
completeLength === combined.length ? combined : combined.slice(0, completeLength)
written += decoded.write(complete, written, 'base64')
}
carry = completeLength === combined.length ? '' : combined.slice(completeLength)
remainingData -= segmentDataLength
}
if (carry.length > 0) {
written += decoded.write(carry, written, 'base64')
}
if (written !== decoded.length) {
throw new Error('Clipboard image content must be base64')
}
return decoded
}
private validateAndGetDataLength(): number {
if (this.retainedLength % 4 === 1) {
throw new Error('Clipboard image content must be base64')
}
let dataLength = 0
let paddingLength = 0
let remaining = this.retainedLength
for (const segment of this.segments) {
const usedLength = Math.min(segment.length, remaining)
for (let index = 0; index < usedLength; index++) {
const byte = segment[index]
if (byte === BASE64_PADDING_BYTE) {
paddingLength += 1
continue
}
if (paddingLength > 0 || !isBase64DataByte(byte)) {
throw new Error('Clipboard image content must be base64')
}
dataLength += 1
}
remaining -= usedLength
}
if (paddingLength > 2) {
throw new Error('Clipboard image content must be base64')
}
return dataLength
}
}
+13 -147
View File
@@ -4,7 +4,6 @@ import type { RpcRequest } from '../core'
import type { OrcaRuntimeService } from '../../orca-runtime'
import {
CLIPBOARD_IMAGE_MAX_BASE64_CHARS,
CLIPBOARD_IMAGE_MAX_SOURCE_BYTES,
CLIPBOARD_IMAGE_TOO_LARGE_ERROR
} from '../../../../shared/clipboard-image'
@@ -19,9 +18,7 @@ vi.mock('../../../window/clipboard-image-temp-file', () => ({
import {
CLIPBOARD_IMAGE_UPLOAD_CHUNK_BASE64_CHARS,
CLIPBOARD_IMAGE_UPLOAD_MAX_CONCURRENT,
CLIPBOARD_IMAGE_UPLOAD_MAX_RETAINED_BASE64_CHARS,
CLIPBOARD_METHODS,
getRetainedClipboardImageUploadBase64CharsForTest,
resetClipboardImageUploadsForTest
} from './clipboard'
@@ -103,7 +100,7 @@ describe('clipboard RPC methods', () => {
it('accepts chunked uploads and forwards the recorded connectionId on commit', async () => {
saveClipboardImageBufferAsTempFile.mockResolvedValue('/tmp/orca-paste-image.png')
const dispatcher = makeDispatcher()
const contentBase64 = Buffer.from('png-byte').toString('base64')
const contentBase64 = Buffer.from('png-bytes').toString('base64')
const start = await dispatcher.dispatch(
makeRequest('clipboard.startImageUpload', {
@@ -114,8 +111,8 @@ describe('clipboard RPC methods', () => {
expect(start.ok).toBe(true)
const uploadId = (start.ok ? start.result : null) as { uploadId: string }
const firstChunk = contentBase64.slice(0, 2)
const secondChunk = contentBase64.slice(2)
const firstChunk = contentBase64.slice(0, 4)
const secondChunk = contentBase64.slice(4)
await expect(
dispatcher.dispatch(
makeRequest('clipboard.appendImageUploadChunk', {
@@ -124,7 +121,7 @@ describe('clipboard RPC methods', () => {
contentBase64: firstChunk
})
)
).resolves.toMatchObject({ ok: true, result: { receivedBase64Length: 2 } })
).resolves.toMatchObject({ ok: true, result: { receivedBase64Length: 4 } })
await expect(
dispatcher.dispatch(
makeRequest('clipboard.appendImageUploadChunk', {
@@ -134,15 +131,13 @@ describe('clipboard RPC methods', () => {
})
)
).resolves.toMatchObject({ ok: true, result: { receivedBase64Length: contentBase64.length } })
expect(getRetainedClipboardImageUploadBase64CharsForTest()).toBe(contentBase64.length)
await expect(
dispatcher.dispatch(
makeRequest('clipboard.commitImageUpload', { uploadId: uploadId.uploadId })
)
).resolves.toMatchObject({ ok: true, result: '/tmp/orca-paste-image.png' })
expect(getRetainedClipboardImageUploadBase64CharsForTest()).toBe(0)
expect(saveClipboardImageBufferAsTempFile).toHaveBeenCalledWith(Buffer.from('png-byte'), {
expect(saveClipboardImageBufferAsTempFile).toHaveBeenCalledWith(Buffer.from('png-bytes'), {
connectionId: 'ssh-1'
})
})
@@ -166,7 +161,6 @@ describe('clipboard RPC methods', () => {
)
expect(response.ok).toBe(false)
expect(getRetainedClipboardImageUploadBase64CharsForTest()).toBe(0)
expect(saveClipboardImageBufferAsTempFile).not.toHaveBeenCalled()
})
@@ -189,7 +183,6 @@ describe('clipboard RPC methods', () => {
})
)
).resolves.toMatchObject({ ok: false })
expect(getRetainedClipboardImageUploadBase64CharsForTest()).toBe(0)
await expect(
dispatcher.dispatch(
makeRequest('clipboard.appendImageUploadChunk', {
@@ -265,7 +258,6 @@ describe('clipboard RPC methods', () => {
)
expect(response.ok).toBe(false)
expect(getRetainedClipboardImageUploadBase64CharsForTest()).toBe(0)
expect(saveClipboardImageBufferAsTempFile).not.toHaveBeenCalled()
})
@@ -298,7 +290,6 @@ describe('clipboard RPC methods', () => {
)
expect(response.ok).toBe(false)
expect(getRetainedClipboardImageUploadBase64CharsForTest()).toBe(0)
expect(saveClipboardImageBufferAsTempFile).not.toHaveBeenCalled()
})
@@ -311,21 +302,12 @@ describe('clipboard RPC methods', () => {
})
)
const uploadId = (start.ok ? start.result : null) as { uploadId: string }
await dispatcher.dispatch(
makeRequest('clipboard.appendImageUploadChunk', {
uploadId: uploadId.uploadId,
offset: 0,
contentBase64: 'AAAA'
})
)
expect(getRetainedClipboardImageUploadBase64CharsForTest()).toBe(4)
await expect(
dispatcher.dispatch(
makeRequest('clipboard.abortImageUpload', { uploadId: uploadId.uploadId })
)
).resolves.toMatchObject({ ok: true, result: { aborted: true } })
expect(getRetainedClipboardImageUploadBase64CharsForTest()).toBe(0)
await expect(
dispatcher.dispatch(
makeRequest('clipboard.abortImageUpload', { uploadId: uploadId.uploadId })
@@ -367,137 +349,22 @@ describe('clipboard RPC methods', () => {
makeRequest('clipboard.commitImageUpload', { uploadId: uploadId.uploadId })
)
).resolves.toMatchObject({ ok: false })
expect(getRetainedClipboardImageUploadBase64CharsForTest()).toBe(0)
expect(saveClipboardImageBufferAsTempFile).toHaveBeenCalledTimes(1)
})
it('caps retained chunks process-wide and keeps commit memory charged until save completes', async () => {
let releaseSave!: () => void
const saveGate = new Promise<void>((resolve) => {
releaseSave = resolve
})
saveClipboardImageBufferAsTempFile.mockImplementation(async (content: Buffer) => {
expect(content).toHaveLength(CLIPBOARD_IMAGE_MAX_SOURCE_BYTES)
await saveGate
return '/tmp/orca-paste-image.png'
})
const dispatcher = makeDispatcher()
const firstStart = await dispatcher.dispatch(
makeRequest('clipboard.startImageUpload', {
expectedBase64Length: CLIPBOARD_IMAGE_UPLOAD_MAX_RETAINED_BASE64_CHARS,
connectionId: 'ssh-1'
})
)
const secondStart = await dispatcher.dispatch(
makeRequest('clipboard.startImageUpload', {
expectedBase64Length: 4,
connectionId: 'ssh-2'
})
)
const firstUpload = (firstStart.ok ? firstStart.result : null) as { uploadId: string }
const secondUpload = (secondStart.ok ? secondStart.result : null) as { uploadId: string }
const fullChunk = 'A'.repeat(CLIPBOARD_IMAGE_UPLOAD_CHUNK_BASE64_CHARS)
for (
let offset = 0;
offset < CLIPBOARD_IMAGE_UPLOAD_MAX_RETAINED_BASE64_CHARS;
offset += fullChunk.length
) {
await expect(
dispatcher.dispatch(
makeRequest('clipboard.appendImageUploadChunk', {
uploadId: firstUpload.uploadId,
offset,
contentBase64: fullChunk
})
)
).resolves.toMatchObject({ ok: true })
}
expect(getRetainedClipboardImageUploadBase64CharsForTest()).toBe(
CLIPBOARD_IMAGE_UPLOAD_MAX_RETAINED_BASE64_CHARS
)
await expect(
dispatcher.dispatch(
makeRequest('clipboard.appendImageUploadChunk', {
uploadId: secondUpload.uploadId,
offset: 0,
contentBase64: 'AAAA'
})
)
).resolves.toMatchObject({ ok: false })
expect(getRetainedClipboardImageUploadBase64CharsForTest()).toBe(
CLIPBOARD_IMAGE_UPLOAD_MAX_RETAINED_BASE64_CHARS
)
const commit = dispatcher.dispatch(
makeRequest('clipboard.commitImageUpload', { uploadId: firstUpload.uploadId })
)
await vi.waitFor(() => expect(saveClipboardImageBufferAsTempFile).toHaveBeenCalledTimes(1))
expect(getRetainedClipboardImageUploadBase64CharsForTest()).toBe(
CLIPBOARD_IMAGE_UPLOAD_MAX_RETAINED_BASE64_CHARS
)
releaseSave()
await expect(commit).resolves.toMatchObject({ ok: true })
expect(getRetainedClipboardImageUploadBase64CharsForTest()).toBe(0)
await expect(
dispatcher.dispatch(
makeRequest('clipboard.appendImageUploadChunk', {
uploadId: secondUpload.uploadId,
offset: 0,
contentBase64: 'AAAA'
})
)
).resolves.toMatchObject({ ok: true, result: { receivedBase64Length: 4 } })
})
it('releases retained chunks when test state is reset', async () => {
const dispatcher = makeDispatcher()
const start = await dispatcher.dispatch(
makeRequest('clipboard.startImageUpload', {
expectedBase64Length: 4,
connectionId: null
})
)
const uploadId = (start.ok ? start.result : null) as { uploadId: string }
await dispatcher.dispatch(
makeRequest('clipboard.appendImageUploadChunk', {
uploadId: uploadId.uploadId,
offset: 0,
contentBase64: 'AAAA'
})
)
expect(getRetainedClipboardImageUploadBase64CharsForTest()).toBe(4)
resetClipboardImageUploadsForTest()
expect(getRetainedClipboardImageUploadBase64CharsForTest()).toBe(0)
})
it('bounds concurrent uploads and releases slots through TTL cleanup', async () => {
vi.useFakeTimers()
const dispatcher = makeDispatcher()
for (let index = 0; index < CLIPBOARD_IMAGE_UPLOAD_MAX_CONCURRENT; index++) {
const start = await dispatcher.dispatch(
makeRequest('clipboard.startImageUpload', {
expectedBase64Length: 4,
connectionId: null
})
)
expect(start).toMatchObject({ ok: true })
const uploadId = (start.ok ? start.result : null) as { uploadId: string }
await dispatcher.dispatch(
makeRequest('clipboard.appendImageUploadChunk', {
uploadId: uploadId.uploadId,
offset: 0,
contentBase64: 'AAAA'
})
)
await expect(
dispatcher.dispatch(
makeRequest('clipboard.startImageUpload', {
expectedBase64Length: 4,
connectionId: null
})
)
).resolves.toMatchObject({ ok: true })
}
expect(getRetainedClipboardImageUploadBase64CharsForTest()).toBe(
CLIPBOARD_IMAGE_UPLOAD_MAX_CONCURRENT * 4
)
await expect(
dispatcher.dispatch(
makeRequest('clipboard.startImageUpload', {
@@ -508,7 +375,6 @@ describe('clipboard RPC methods', () => {
).resolves.toMatchObject({ ok: false })
vi.advanceTimersByTime(5 * 60 * 1000 + 1)
expect(getRetainedClipboardImageUploadBase64CharsForTest()).toBe(0)
await expect(
dispatcher.dispatch(
+26 -70
View File
@@ -6,28 +6,23 @@ import {
CLIPBOARD_IMAGE_MAX_BASE64_CHARS,
CLIPBOARD_IMAGE_TOO_LARGE_ERROR
} from '../../../../shared/clipboard-image'
import { ClipboardImageUploadBuffer } from './clipboard-image-upload-buffer'
const MAX_CLIPBOARD_IMAGE_BASE64_CHARS = CLIPBOARD_IMAGE_MAX_BASE64_CHARS
export const CLIPBOARD_IMAGE_UPLOAD_CHUNK_BASE64_CHARS = 512 * 1024
export const CLIPBOARD_IMAGE_UPLOAD_MAX_CONCURRENT = 8
export const CLIPBOARD_IMAGE_UPLOAD_MAX_RETAINED_BASE64_CHARS = CLIPBOARD_IMAGE_MAX_BASE64_CHARS
const CLIPBOARD_IMAGE_UPLOAD_TTL_MS = 5 * 60 * 1000
const CLIPBOARD_IMAGE_UPLOAD_MEMORY_ERROR = 'Too much clipboard image upload data is in progress'
const BASE64_PATTERN = /^[A-Za-z0-9+/]*={0,2}$/
type ClipboardImageUpload = {
expectedBase64Length: number
connectionId?: string | null
content: ClipboardImageUploadBuffer
reservedBase64Length: number
chunks: string[]
receivedBase64Length: number
expiresAt: number
ttlTimer: ReturnType<typeof setTimeout>
committing: boolean
}
const clipboardImageUploads = new Map<string, ClipboardImageUpload>()
let retainedClipboardImageUploadBase64Chars = 0
function isValidBase64(value: string): boolean {
return value.length % 4 !== 1 && BASE64_PATTERN.test(value)
@@ -43,7 +38,7 @@ function pruneExpiredUploads(now = Date.now()): void {
function scheduleUploadExpiry(uploadId: string): ReturnType<typeof setTimeout> {
const timer = setTimeout(() => {
deleteUpload(uploadId)
clipboardImageUploads.delete(uploadId)
}, CLIPBOARD_IMAGE_UPLOAD_TTL_MS)
if (typeof timer === 'object' && 'unref' in timer) {
timer.unref()
@@ -57,26 +52,12 @@ function refreshUploadExpiry(uploadId: string, upload: ClipboardImageUpload): vo
upload.ttlTimer = scheduleUploadExpiry(uploadId)
}
function releaseUploadRetention(upload: ClipboardImageUpload): void {
retainedClipboardImageUploadBase64Chars -= upload.reservedBase64Length
upload.reservedBase64Length = 0
upload.content.clear()
}
function finishUpload(uploadId: string, upload: ClipboardImageUpload): void {
clearTimeout(upload.ttlTimer)
if (clipboardImageUploads.get(uploadId) === upload) {
clipboardImageUploads.delete(uploadId)
}
releaseUploadRetention(upload)
}
function deleteUpload(uploadId: string): void {
const upload = clipboardImageUploads.get(uploadId)
if (!upload || upload.committing) {
return
if (upload) {
clearTimeout(upload.ttlTimer)
}
finishUpload(uploadId, upload)
clipboardImageUploads.delete(uploadId)
}
function getUpload(uploadId: string): ClipboardImageUpload {
@@ -85,21 +66,13 @@ function getUpload(uploadId: string): ClipboardImageUpload {
if (!upload) {
throw new Error('Clipboard image upload was not found')
}
if (upload.committing) {
throw new Error('Clipboard image upload is already committing')
}
return upload
}
function reserveUploadBase64(chars: number): boolean {
if (
chars >
CLIPBOARD_IMAGE_UPLOAD_MAX_RETAINED_BASE64_CHARS - retainedClipboardImageUploadBase64Chars
) {
return false
function assertValidBase64Content(value: string): void {
if (!isValidBase64(value)) {
throw new Error('Clipboard image content must be base64')
}
retainedClipboardImageUploadBase64Chars += chars
return true
}
function clipboardImageBase64Payload(maxChars: number, tooLargeMessage: string) {
@@ -175,14 +148,10 @@ export const CLIPBOARD_METHODS: RpcMethod[] = [
clipboardImageUploads.set(uploadId, {
expectedBase64Length: params.expectedBase64Length,
connectionId: params.connectionId,
content: new ClipboardImageUploadBuffer(
params.expectedBase64Length,
CLIPBOARD_IMAGE_UPLOAD_CHUNK_BASE64_CHARS
),
reservedBase64Length: 0,
chunks: [],
receivedBase64Length: 0,
expiresAt: Date.now() + CLIPBOARD_IMAGE_UPLOAD_TTL_MS,
ttlTimer: scheduleUploadExpiry(uploadId),
committing: false
ttlTimer: scheduleUploadExpiry(uploadId)
})
return { uploadId }
}
@@ -192,25 +161,17 @@ export const CLIPBOARD_METHODS: RpcMethod[] = [
params: AppendImageUploadChunk,
handler: (params) => {
const upload = getUpload(params.uploadId)
if (params.offset !== upload.content.length) {
if (params.offset !== upload.receivedBase64Length) {
throw new Error('Clipboard image chunk offset is out of order')
}
const nextLength = upload.content.length + params.contentBase64.length
const nextLength = upload.receivedBase64Length + params.contentBase64.length
if (nextLength > upload.expectedBase64Length) {
throw new Error('Clipboard image upload exceeded expected size')
}
if (!reserveUploadBase64(params.contentBase64.length)) {
throw new Error(CLIPBOARD_IMAGE_UPLOAD_MEMORY_ERROR)
}
try {
upload.content.append(params.contentBase64)
} catch (error) {
retainedClipboardImageUploadBase64Chars -= params.contentBase64.length
throw error
}
upload.reservedBase64Length += params.contentBase64.length
upload.chunks.push(params.contentBase64)
upload.receivedBase64Length = nextLength
refreshUploadExpiry(params.uploadId, upload)
return { receivedBase64Length: upload.content.length }
return { receivedBase64Length: upload.receivedBase64Length }
}
}),
defineMethod({
@@ -218,19 +179,19 @@ export const CLIPBOARD_METHODS: RpcMethod[] = [
params: CommitImageUpload,
handler: async (params) => {
const upload = getUpload(params.uploadId)
upload.committing = true
clearTimeout(upload.ttlTimer)
try {
if (upload.content.length !== upload.expectedBase64Length) {
if (upload.receivedBase64Length !== upload.expectedBase64Length) {
throw new Error('Clipboard image upload is incomplete')
}
const content = upload.content.decode()
upload.content.clear()
return await saveClipboardImageBufferAsTempFile(content, {
const contentBase64 = upload.chunks.join('')
assertValidBase64Content(contentBase64)
return await saveClipboardImageBufferAsTempFile(Buffer.from(contentBase64, 'base64'), {
connectionId: upload.connectionId
})
} finally {
finishUpload(params.uploadId, upload)
// Why: failed SSH or filesystem commits must not leave bounded upload
// memory pinned until TTL cleanup.
deleteUpload(params.uploadId)
}
}
}),
@@ -245,12 +206,7 @@ export const CLIPBOARD_METHODS: RpcMethod[] = [
]
export function resetClipboardImageUploadsForTest(): void {
for (const [uploadId, upload] of clipboardImageUploads) {
finishUpload(uploadId, upload)
for (const uploadId of clipboardImageUploads.keys()) {
deleteUpload(uploadId)
}
retainedClipboardImageUploadBase64Chars = 0
}
export function getRetainedClipboardImageUploadBase64CharsForTest(): number {
return retainedClipboardImageUploadBase64Chars
}
@@ -3,10 +3,6 @@ import { defineMethod, type RpcMethod } from '../core'
import { OptionalFiniteNumber, OptionalString, requiredString } from '../schemas'
import type { GateStatus } from '../../orchestration/db'
import { Coordinator } from '../../orchestration/coordinator'
import {
assertOrchestrationStringListFits,
assertOrchestrationWriteFits
} from '../../orchestration/query-retention'
// Why: the coordinator instance is stored at module scope so orchestration.runStop
// can signal it to halt. Only one coordinator can run at a time (enforced by
@@ -112,12 +108,10 @@ export const ORCHESTRATION_GATE_METHODS: RpcMethod[] = [
let options: string[] | undefined
if (params.options) {
try {
assertOrchestrationWriteFits('Decision gate options', [params.options])
const parsed = JSON.parse(params.options)
if (!Array.isArray(parsed) || !parsed.every((option) => typeof option === 'string')) {
throw new Error('not an array of strings')
}
assertOrchestrationStringListFits('Decision gate options', parsed)
options = parsed
} catch {
throw new Error('Invalid --options: must be a JSON array of strings')
@@ -150,17 +144,11 @@ export const ORCHESTRATION_GATE_METHODS: RpcMethod[] = [
params: GateListParams,
handler: (params, { runtime }) => {
const db = runtime.getOrchestrationDb()
const filter = {
const gates = db.listGates({
taskId: params.task,
status: params.status as GateStatus
}
const gates = db.listGates(filter)
const total = db.countGates(filter)
return {
gates,
count: gates.length,
...(total > gates.length ? { total, truncated: true as const } : {})
}
})
return { gates, count: gates.length }
}
})
]
@@ -1,185 +0,0 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import type Database from '../../../sqlite/sync-database'
import { OrchestrationDb } from '../../orchestration/db'
import {
ORCHESTRATION_QUERY_MAX_ROWS,
ORCHESTRATION_QUERY_MAX_ROW_UTF8_BYTES,
ORCHESTRATION_WAIT_TYPE_FILTER_MAX_UTF8_BYTES
} from '../../orchestration/query-retention'
import { OrcaRuntimeService } from '../../orca-runtime'
import type { RpcContext } from '../core'
import { ORCHESTRATION_METHODS } from './orchestration'
function sqliteFor(db: OrchestrationDb): Database.Database {
return (db as unknown as { db: Database.Database }).db
}
describe('orchestration RPC query retention', () => {
let db: OrchestrationDb | undefined
afterEach(() => {
db?.close()
})
async function call(name: string, params: Record<string, unknown>): Promise<unknown> {
db ??= new OrchestrationDb(':memory:')
const runtime = new OrcaRuntimeService()
runtime.setOrchestrationDb(db)
return callWithRuntime(runtime, name, params)
}
async function callWithRuntime(
runtime: OrcaRuntimeService,
name: string,
params: Record<string, unknown>
): Promise<unknown> {
const ctx: RpcContext = { runtime }
const method = ORCHESTRATION_METHODS.find((candidate) => candidate.name === name)
if (!method) {
throw new Error(`Method not found: ${name}`)
}
const parsed = method.params ? method.params.parse(params) : undefined
return method.handler(parsed, ctx)
}
function createDb(): OrchestrationDb {
db = new OrchestrationDb(':memory:')
return db
}
it('reports remaining unread messages while successive checks drain the queue', async () => {
const d = createDb()
for (let index = 0; index < ORCHESTRATION_QUERY_MAX_ROWS + 1; index += 1) {
d.insertMessage({ from: 'sender', to: 'worker', subject: `message-${index}` })
}
const first = (await call('orchestration.check', { terminal: 'worker' })) as {
count: number
truncated?: boolean
remaining?: number
}
expect(first).toMatchObject({
count: ORCHESTRATION_QUERY_MAX_ROWS,
truncated: true,
remaining: 1
})
const second = (await call('orchestration.check', { terminal: 'worker' })) as {
count: number
truncated?: boolean
}
expect(second).toMatchObject({ count: 1 })
expect(second.truncated).toBeUndefined()
})
it('returns truncation instead of waiting forever on an oversized legacy row', async () => {
const d = createDb()
sqliteFor(d)
.prepare(
`INSERT INTO messages (id, from_handle, to_handle, subject, body)
VALUES ('msg_oversized', 'sender', 'worker', 'oversized', ?)`
)
.run('x'.repeat(ORCHESTRATION_QUERY_MAX_ROW_UTF8_BYTES + 1))
const runtime = new OrcaRuntimeService()
runtime.setOrchestrationDb(d)
const waitForMessage = vi.spyOn(runtime, 'waitForMessage')
const result = await callWithRuntime(runtime, 'orchestration.check', {
terminal: 'worker',
wait: true,
timeoutMs: 60_000
})
expect(result).toMatchObject({
count: 0,
truncated: true,
remaining: 1
})
expect(waitForMessage).not.toHaveBeenCalled()
})
it('rejects oversized waiting type filters before retaining the request', async () => {
const d = createDb()
const runtime = new OrcaRuntimeService()
runtime.setOrchestrationDb(d)
const waitForMessage = vi.spyOn(runtime, 'waitForMessage')
const types = 'status,'.repeat(
Math.ceil(ORCHESTRATION_WAIT_TYPE_FILTER_MAX_UTF8_BYTES / 'status,'.length) + 1
)
await expect(
callWithRuntime(runtime, 'orchestration.check', {
terminal: 'worker',
wait: true,
types
})
).rejects.toThrow(
`${ORCHESTRATION_WAIT_TYPE_FILTER_MAX_UTF8_BYTES}-byte orchestration wait limit`
)
expect(waitForMessage).not.toHaveBeenCalled()
})
it('preserves normal waiting type filters while removing duplicate retention', async () => {
const d = createDb()
const runtime = new OrcaRuntimeService()
runtime.setOrchestrationDb(d)
const waitForMessage = vi.spyOn(runtime, 'waitForMessage').mockResolvedValue()
await expect(
callWithRuntime(runtime, 'orchestration.check', {
terminal: 'worker',
wait: true,
timeoutMs: 100,
types: 'status,status,worker_done,escalation,decision_gate'
})
).resolves.toMatchObject({ count: 0, messages: [] })
expect(waitForMessage).toHaveBeenCalledWith('worker', {
typeFilter: ['status', 'worker_done', 'escalation', 'decision_gate'],
timeoutMs: 100,
signal: undefined
})
})
it('reports exact totals when task and gate lists are capped', async () => {
const d = createDb()
const task = d.createTask({ spec: 'gated' })
for (let index = 0; index < ORCHESTRATION_QUERY_MAX_ROWS + 1; index += 1) {
d.createTask({ spec: `task-${index}` })
d.createGate({ taskId: task.id, question: `question-${index}` })
}
const tasks = (await call('orchestration.taskList', {})) as {
count: number
total?: number
truncated?: boolean
}
expect(tasks).toMatchObject({
count: ORCHESTRATION_QUERY_MAX_ROWS,
total: ORCHESTRATION_QUERY_MAX_ROWS + 2,
truncated: true
})
const gates = (await call('orchestration.gateList', {})) as {
count: number
total?: number
truncated?: boolean
}
expect(gates).toMatchObject({
count: ORCHESTRATION_QUERY_MAX_ROWS,
total: ORCHESTRATION_QUERY_MAX_ROWS + 1,
truncated: true
})
})
it('reports the exact inbox total when a requested page omits rows', async () => {
const d = createDb()
d.insertMessage({ from: 'a', to: 'b', subject: 'one' })
d.insertMessage({ from: 'a', to: 'b', subject: 'two' })
await expect(call('orchestration.inbox', { limit: 1 })).resolves.toMatchObject({
count: 1,
total: 2,
truncated: true
})
})
})
+17 -58
View File
@@ -7,11 +7,6 @@ import { buildDispatchPreamble } from '../../orchestration/preamble'
import { formatMessageBanner } from '../../orchestration/formatter'
import { isGroupAddress, resolveGroupAddress } from '../../orchestration/groups'
import { reconcileLifecycleMessage } from '../../orchestration/lifecycle-reconciliation'
import {
assertOrchestrationStringListFits,
assertOrchestrationWaitTypeFilterFits,
assertOrchestrationWriteFits
} from '../../orchestration/query-retention'
import { abbreviateOrchestrationTasks } from '../../../../shared/orchestration-task-summary'
import { ORCHESTRATION_GATE_METHODS } from './orchestration-gates'
@@ -26,21 +21,6 @@ const MESSAGE_TYPES: MessageType[] = [
'heartbeat'
]
function parseMessageTypeFilter(types: string | undefined): MessageType[] | undefined {
if (!types) {
return undefined
}
const parsed = types
.split(',')
.map((type) => type.trim())
.filter(Boolean) as MessageType[]
const invalidTypes = parsed.filter((type) => !MESSAGE_TYPES.includes(type))
if (invalidTypes.length > 0) {
throw new Error(`Invalid --types: ${invalidTypes.join(',')}`)
}
return Array.from(new Set(parsed))
}
const TASK_STATUSES: TaskStatus[] = [
'pending',
'ready',
@@ -292,20 +272,22 @@ export const ORCHESTRATION_METHODS: RpcMethod[] = [
handler: async (params, { runtime, signal }) => {
const db = runtime.getOrchestrationDb()
const handle = params.terminal ?? 'unknown'
if (params.wait) {
assertOrchestrationWaitTypeFilterFits(params.types)
const typeFilter = params.types
? (params.types
.split(',')
.map((t) => t.trim())
.filter(Boolean) as MessageType[])
: undefined
const invalidTypes = typeFilter?.filter((t) => !MESSAGE_TYPES.includes(t))
if (invalidTypes && invalidTypes.length > 0) {
throw new Error(`Invalid --types: ${invalidTypes.join(',')}`)
}
assertOrchestrationWriteFits('Message type filter', [params.types])
const typeFilter = parseMessageTypeFilter(params.types)
// Why: unread:false is honored for one release as a compat shim so in-flight callers don't break (design doc §5).
const showAll = params.all === true || (params.unread === false && params.peek !== true)
const consumeUnread = !showAll && params.peek !== true
const readAndReturn = () => {
const totalBeforeRead = showAll
? db.countAllMessagesForHandle(handle, typeFilter)
: db.countUnreadMessages(handle, typeFilter)
const messages = showAll
? db.getAllMessagesForHandle(handle, undefined, typeFilter)
: db.getUnreadMessages(handle, typeFilter)
@@ -322,28 +304,19 @@ export const ORCHESTRATION_METHODS: RpcMethod[] = [
db.markAsRead(messages.map((m) => m.id))
}
const remaining = consumeUnread
? db.countUnreadMessages(handle, typeFilter)
: Math.max(0, totalBeforeRead - messages.length)
const saturation = remaining > 0 ? { truncated: true as const, remaining } : {}
if (params.inject) {
const formatted = visibleMessages.map(formatMessageBanner).join('\n\n')
return {
messages: visibleMessages,
formatted,
count: visibleMessages.length,
...saturation
}
return { messages: visibleMessages, formatted, count: visibleMessages.length }
}
return { messages: visibleMessages, count: visibleMessages.length, ...saturation }
return { messages: visibleMessages, count: visibleMessages.length }
}
if (signal?.aborted) {
return { messages: [], count: 0 }
}
const result = readAndReturn()
if (result.count > 0 || result.truncated || !params.wait) {
if (result.count > 0 || !params.wait) {
return result
}
@@ -394,14 +367,7 @@ export const ORCHESTRATION_METHODS: RpcMethod[] = [
const messages = params.terminal
? db.getAllMessagesForHandle(params.terminal, params.limit)
: db.getInbox(params.limit)
const total = params.terminal
? db.countAllMessagesForHandle(params.terminal)
: db.countInbox()
return {
messages,
count: messages.length,
...(total > messages.length ? { total, truncated: true as const } : {})
}
return { messages, count: messages.length }
}
}),
@@ -413,12 +379,10 @@ export const ORCHESTRATION_METHODS: RpcMethod[] = [
let deps: string[] | undefined
if (params.deps) {
try {
assertOrchestrationWriteFits('Task dependencies', [params.deps])
const parsed = JSON.parse(params.deps)
if (!Array.isArray(parsed) || !parsed.every((d) => typeof d === 'string')) {
throw new Error('not an array of strings')
}
assertOrchestrationStringListFits('Task dependencies', parsed)
deps = parsed
} catch {
throw new Error('Invalid --deps: must be a JSON array of task IDs')
@@ -441,12 +405,11 @@ export const ORCHESTRATION_METHODS: RpcMethod[] = [
params: TaskListParams,
handler: (params, { runtime }) => {
const db = runtime.getOrchestrationDb()
const filter = {
// Why: listTasksWithDispatch adds assignee_handle + dispatch_id (NULL for non-dispatched), so legacy-shape consumers are unaffected.
const joined = db.listTasksWithDispatch({
status: params.status as TaskStatus,
ready: params.ready
}
// Why: listTasksWithDispatch adds assignee_handle + dispatch_id (NULL for non-dispatched), so legacy-shape consumers are unaffected.
const joined = db.listTasksWithDispatch(filter)
})
const tasks = joined.map((row) => {
const { assignee_handle, dispatch_id, ...base } = row
if (base.status === 'dispatched') {
@@ -454,11 +417,9 @@ export const ORCHESTRATION_METHODS: RpcMethod[] = [
}
return base
})
const total = db.countTasks(filter)
return {
tasks: params.brief ? abbreviateOrchestrationTasks(tasks) : tasks,
count: tasks.length,
...(total > tasks.length ? { total, truncated: true as const } : {})
count: tasks.length
}
}
}),
@@ -607,13 +568,11 @@ export const ORCHESTRATION_METHODS: RpcMethod[] = [
const db = runtime.getOrchestrationDb()
const from = params.from ?? 'unknown'
const timeoutMs = params.timeoutMs ?? 600_000
assertOrchestrationWriteFits('Decision gate options', [params.options])
const options =
params.options
?.split(',')
.map((s) => s.trim())
.filter(Boolean) ?? []
assertOrchestrationStringListFits('Decision gate options', options)
const payload = JSON.stringify({ question: params.question, options })
const outbound = db.insertMessage({
+1 -2
View File
@@ -53,7 +53,6 @@ import {
TERMINAL_STREAM_CHUNK_BYTES
} from '../../../../shared/terminal-multiplex-flow-control'
import { drainTerminalMultiplexRoundRobin } from '../terminal-multiplex-round-robin'
import { appendCompactedStringChunk } from '../../../../shared/string-chunk-compaction'
const REQUESTED_SNAPSHOT_BYTE_BUDGET = 2 * 1024 * 1024
const TERMINAL_OUTPUT_FLUSH_MS = 5
@@ -209,7 +208,7 @@ function createTerminalOutputBatcher(onFlush: (data: string, meta?: TerminalOutp
flush()
pendingCwd = meta.cwd
}
appendCompactedStringChunk(chunks, data)
chunks.push(data)
pendingRawLength += rawLength
const remainingBudget = Math.max(1, TERMINAL_OUTPUT_BATCH_MAX_BYTES - bytes)
const measurement = measureTerminalStreamByteLength(data, {