Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
@@ -0,0 +1,111 @@
import { mkdtempSync, rmSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it } from 'vitest'
import { OrchestrationDb } from '../runtime/orchestration/db/orchestration-db'
import { MUTATION_RECEIPT_MAX_ROWS } from '../runtime/orchestration/mutation-receipt-capacity'
import {
CONNECTOR_PENDING_RECEIPT_LIMIT,
DeliveryReceipts
} from './external-conversation-delivery-receipts'
import type { ConversationKey, Delivery } from './external-conversation-types'

const KEY: ConversationKey = { source: 'dev', externalId: 'thread' }
const ORDINARY = {
callerFingerprint: 'ordinary-user',
requestId: 'send',
method: 'orchestration.send',
payloadHash: 'hash'
}
const never = (): Promise<Delivery> => new Promise(() => {})

const directories: string[] = []
function fileDb(): { path: string; db: OrchestrationDb } {
const directory = mkdtempSync(join(tmpdir(), 'connector-receipts-'))
directories.push(directory)
const path = join(directory, 'orchestration.db')
return { path, db: new OrchestrationDb(path) }
}

afterEach(() => {
for (const directory of directories.splice(0)) {
rmSync(directory, { recursive: true, force: true })
}
})

describe('DeliveryReceipts ledger capacity', () => {
it('cannot fill orchestration’s ledger with a backlog that outlives the process', async () => {
const { path, db } = fileDb()
const receipts = new DeliveryReceipts(() => db)
const answers: Promise<Delivery>[] = []
for (let i = 0; i < MUTATION_RECEIPT_MAX_ROWS; i++) {
answers.push(receipts.run(KEY, String(i), 'connector.send', ['hello'], never))
}
await expect(answers[CONNECTOR_PENDING_RECEIPT_LIMIT]).resolves.toEqual({
outcome: 'refused',
reason: 'delivery_backlog_full'
})
expect(db.countPendingMutationReceipts(['connector:dev'])).toBe(CONNECTOR_PENDING_RECEIPT_LIMIT)
db.close()

// Process loss, then a restart that never starts connectors.
const reopened = new OrchestrationDb(path)
expect(reopened.beginMutationReceipt(ORDINARY).disposition).toBe('started')
reopened.close()
})

it('answers a recorded delivery even when the backlog is full', async () => {
const { db } = fileDb()
const receipts = new DeliveryReceipts(() => db)
for (let i = 0; i < CONNECTOR_PENDING_RECEIPT_LIMIT; i++) {
void receipts.run(KEY, String(i), 'connector.send', ['hello'], never)
}
const joined = receipts.run(KEY, '0', 'connector.send', ['hello'], never)
const raced = await Promise.race([joined, Promise.resolve('waiting')])
expect(raced).toBe('waiting')
db.close()
})

it('settles a previous process’s pending deliveries as unknown, without replaying them', async () => {
const { path, db } = fileDb()
const before = new DeliveryReceipts(() => db)
for (let i = 0; i < CONNECTOR_PENDING_RECEIPT_LIMIT; i++) {
void before.run(KEY, String(i), 'connector.send', ['hello'], never)
}
db.close()

const reopened = new OrchestrationDb(path)
const after = new DeliveryReceipts(() => reopened)
let executed = 0
const execute = async (): Promise<Delivery> => {
executed++
return { outcome: 'accepted' }
}
await expect(after.run(KEY, '0', 'connector.send', ['hello'], execute)).resolves.toEqual({
outcome: 'unknown',
reason: 'replayed_after_restart'
})
expect(
reopened.getMutationReceipt('connector:dev', JSON.stringify(['thread', '0']))?.state
).toBe('completed')
// The settled rows no longer hold the connector's budget.
await expect(after.run(KEY, 'new', 'connector.send', ['hello'], execute)).resolves.toEqual({
outcome: 'accepted'
})
expect(executed).toBe(1)
expect(reopened.countPendingMutationReceipts(['connector:dev'])).toBe(0)
reopened.close()
})

it('leaves other callers’ pending receipts alone', async () => {
const { db } = fileDb()
db.beginMutationReceipt(ORDINARY)
await new DeliveryReceipts(() => db).run(KEY, 'd1', 'connector.send', ['hello'], async () => ({
outcome: 'accepted'
}))
expect(db.getMutationReceipt(ORDINARY.callerFingerprint, ORDINARY.requestId)?.state).toBe(
'pending'
)
db.close()
})
})
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { z } from 'zod'
import { CONNECTOR_SOURCES, type ConnectorSource } from '../../shared/external-conversation-link'
import type { OrchestrationDb } from '../runtime/orchestration/db/orchestration-db'
import { OrchestrationError } from '../runtime/orchestration/orchestration-error'
import { hashCanonical } from '../runtime/rpc/orchestration-mutation-receipt'
Expand All @@ -16,14 +17,22 @@ const RecordedDelivery = z.discriminatedUnion('outcome', [

const LOST: Delivery = { outcome: 'unknown', reason: 'replayed_after_restart' }

/** Unsettled connector deliveries the shared ledger holds at once, so orchestration keeps the rest. */
export const CONNECTOR_PENDING_RECEIPT_LIMIT = 1_000

const callerFingerprint = (source: ConnectorSource): string => `connector:${source}`
const CONNECTOR_FINGERPRINTS = CONNECTOR_SOURCES.map(callerFingerprint)

/**
* A connector's delivery ids on orchestration's durable mutation receipts, under one caller
* identity per source: the same id and payload share one answer, across restarts too, and another
* payload is refused. A duplicate of one still running waits for it; a running one a restart
* interrupted reads `unknown`. Refusals and throws wrote nothing, so they leave no receipt.
* A new delivery past `CONNECTOR_PENDING_RECEIPT_LIMIT` unsettled ones is refused unrecorded.
*/
export class DeliveryReceipts {
private readonly inFlight = new Map<string, Promise<Delivery>>()
private leftoversSettled = false

constructor(private readonly db: () => DeliveryReceiptDb) {}

Expand All @@ -35,13 +44,25 @@ export class DeliveryReceipts {
execute: () => Promise<Delivery>
): Promise<Delivery> {
const identity = {
callerFingerprint: `connector:${key.source}`,
callerFingerprint: callerFingerprint(key.source),
requestId: JSON.stringify([key.externalId, deliveryId]),
method,
payloadHash: hashCanonical(payload)
}
const flightKey = JSON.stringify([identity.callerFingerprint, identity.requestId])
const db = this.db()
if (!this.leftoversSettled) {
// Pending rows from before this seam already answer only unknown; record that, never delete
// (they may have written), so the ledger can prune them and they leave the limit.
db.settlePendingMutationReceipts(CONNECTOR_FINGERPRINTS, JSON.stringify(LOST))
this.leftoversSettled = true
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
if (
!db.getMutationReceipt(identity.callerFingerprint, identity.requestId) &&
db.countPendingMutationReceipts(CONNECTOR_FINGERPRINTS) >= CONNECTOR_PENDING_RECEIPT_LIMIT
) {
return Promise.resolve(refused('delivery_backlog_full'))
}
let begun: ReturnType<DeliveryReceiptDb['beginMutationReceipt']>
try {
begun = db.beginMutationReceipt(identity)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ export type ConnectorRefusal =
| 'agent_not_reachable'
| 'unsupported_agent'
| 'delivery_id_reused'
| 'delivery_backlog_full'

/**
* The connector's own answer, weaker than a `WriteSettlement`: `accepted` means the writer
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,34 @@ export function discardPendingMutationReceipt(
.run(callerFingerprint, requestId)
}

export function countPendingMutationReceipts(
this: OrchestrationDb,
callerFingerprints: readonly string[]
): number {
const count = this.db
.prepare(
`SELECT COUNT(*) AS count FROM mutation_receipts
WHERE caller_fingerprint IN (SELECT value FROM json_each(?)) AND state = 'pending'`
)
.get(JSON.stringify(callerFingerprints))?.count
return Number(count ?? 0)
}

/** Completes these callers' pending rows with `receipt`, for operations no running work owns. */
export function settlePendingMutationReceipts(
this: OrchestrationDb,
callerFingerprints: readonly string[],
receipt: string
): void {
this.db
.prepare(
`UPDATE mutation_receipts
SET state = 'completed', receipt = ?, updated_at = datetime('now')
WHERE caller_fingerprint IN (SELECT value FROM json_each(?)) AND state = 'pending'`
)
.run(receipt, JSON.stringify(callerFingerprints))
}

export function getMutationReceipt(
this: OrchestrationDb,
callerFingerprint: string,
Expand All @@ -176,6 +204,8 @@ export type MutationReceiptStoreMethods = {
completeMutationReceipt: typeof completeMutationReceipt
checkpointPendingMutationReceipt: typeof checkpointPendingMutationReceipt
discardPendingMutationReceipt: typeof discardPendingMutationReceipt
countPendingMutationReceipts: typeof countPendingMutationReceipts
settlePendingMutationReceipts: typeof settlePendingMutationReceipts
getMutationReceipt: typeof getMutationReceipt
}

Expand All @@ -186,6 +216,8 @@ export function attachMutationReceiptStore(ctor: { prototype: object }): void {
completeMutationReceipt,
checkpointPendingMutationReceipt,
discardPendingMutationReceipt,
countPendingMutationReceipts,
settlePendingMutationReceipts,
getMutationReceipt
})
}
Loading