Skip to content
20 changes: 13 additions & 7 deletions docs/contributing/architecture/data-storage.md
Original file line number Diff line number Diff line change
Expand Up @@ -184,10 +184,11 @@ Durable Object export behavior:
hold application/job/service durable state and are the primary account
migration surface for Durable Object storage.
- `JobManager` exposes scheduler alarm/debug state through an export RPC.
- `RunLog` exports per-user execution history (runs + log lines) through the
account-export `run_records` section (`exportRuns` RPC). Retention is
self-enforced inside the DO (~30 days / 2,000 runs); see
[Run records](./run-records.md).
- `RunLog` exports per-user execution history (runs + log lines) and the keyed
package-invocation idempotency ledger through the account-export `run_records`
section (`exportRuns` RPC; one cursor pages runs first, then ledger rows).
Retention is self-enforced inside the DO (~30 days / 2,000 runs; ledger
terminal rows 90 days); see [Run records](./run-records.md).
- `RemoteConnectorSession` exposes persisted connector metadata and tool
descriptors through an export RPC.
- `PackageServiceInstance` uses its status RPC as the stable persisted service
Expand Down Expand Up @@ -922,9 +923,14 @@ documented exemption.

Current retention policies:

- `package_invocations`: keep terminal idempotency rows for 90 days. Rows with
`status = 'in_progress'` are never pruned so duplicate requests cannot bypass
the in-flight guard.
- `package_invocations`: **legacy dual-read window.** Keyed invocations now
claim and store replay responses in the per-user `RunLog` Durable Object
ledger (`package_invocation_ledger` table inside the DO), which self-enforces
the same 90-day terminal-row window; the keyed path only reads this D1 table
as a fallback for pre-migration keys and never writes it. The sweep keeps
draining pre-migration terminal rows (rows with `status = 'in_progress'` are
never pruned) until a follow-up drops the table, the fallback read, and this
policy entry.
- `mcp_memory_conversation_suppressions`: keep active suppressions and prune
expired rows only after they have not been seen for 90 days. The existing
request-time memory prune may remove expired rows sooner.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,13 @@ call, not about what user code does inside the call.
belongs in the keyed mode or off the hot path (`waitUntil`).
- **Keyed `packages.invoke`** deliberately pays for durability: a ledger claim,
eager run records, and a bounded response snapshot for replay. That cost is
the feature; it must never silently leak into the keyless mode.
the feature; it must never silently leak into the keyless mode. The ledger
lives in the per-user `RunLog` Durable Object (see
[Run records](./run-records.md)), so the durability cost is **one awaited DO
call for claim + run-record begin and one for terminal response + run-record
finish** — not D1 round trips. During the dual-read window the keyed path also
pays one awaited D1 **read** for pre-migration keys; a follow-up removes it
with the legacy `package_invocations` table.

## Watch the percentiles

Expand Down
34 changes: 34 additions & 0 deletions docs/contributing/architecture/run-records.md
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,40 @@ TTLs above. Reconciliation runs on the DO alarm, on retention passes, and **on
read** (`getRun`, keyed lookup, `listRuns`, `summarize`) so Activity and
keyed-execute recovery do not wait for an alarm.

## Keyed package-invocation idempotency ledger

The same per-user `RunLog` DO also hosts the **keyed package-invocation
idempotency ledger** (`package_invocation_ledger` table), migrated off the D1
`package_invocations` table. This is correctness state, not observability: it
holds the claims and bounded replay responses that keyed `packages.invoke`
dedupes against. Unlike run history it cannot be rebuilt — a lost terminal row
means a replayed delivery for that key re-executes instead of replaying.

- **Claim + run-record begin are one awaited DO RPC**
(`claimPackageInvocation`): lookup-then-insert is atomic because DO execution
is serialized — strictly better than the D1 `INSERT OR IGNORE` race it
replaced — and the eager `running` run row is written in the same call. Stale
`in_progress` claims (15 minutes, matching request hash) are reclaimed in
place.
- **Terminal response + run-record finish are one awaited DO RPC**
(`finishPackageInvocation`): the bounded replay response (same restore-safe
byte ceiling as before) and the terminal run row land together; the ledger
update is fenced on the claim timestamp so a competing reclaim cannot be
overwritten.
- **Ledger retention is DO-local**: terminal rows keep replay responses for 90
days (`packageInvocationLedgerRetentionDays`), pruned by the same retention
passes and alarm as run rows; `in_progress` rows are never pruned. The old D1
retention sweep remains only to drain pre-migration rows.
- **Dual-read window**: the keyed path reads the DO first and falls back to a
read-only D1 `package_invocations` lookup for keys claimed before the
migration. Writes go only to the DO. A follow-up removes the fallback, the D1
table, its sweep, and the legacy row shapes.
- Account export pages ledger rows through the same `run_records` section cursor
(runs first, then ledger rows); account deletion purges them with `clearAll`.
Disaster recovery deliberately does not stage the DO — losing it risks
duplicate execution of replayed webhooks (see
[disaster recovery](../disaster-recovery.md)).

## Invariant: state vs history

Entity rows hold **current state**. Run records hold **history**. Never derive
Expand Down
14 changes: 14 additions & 0 deletions docs/contributing/disaster-recovery.md
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,20 @@ Restore rebuilds these; do not treat them as recovery media:
Account export/deletion cover run records for user-facing portability and
purge; disaster recovery deliberately does not.

**Known risk — keyed invocation idempotency ledger:** the same `RunLog` DO
also holds the keyed package-invocation idempotency ledger (claims + 90-day
terminal replay responses; migrated off the D1 `package_invocations` table).
Losing the DO therefore loses idempotency/replay state, not just
observability: webhook providers and other keyed callers that retry deliveries
would **re-execute** invocations whose keys were already terminal, and
in-flight replays would return fresh executions instead of stored responses.
This is accepted with eyes open: lost rows are gone — later traffic
re-establishes claims only for keys used after the loss, it does not restore
protection for keys used before it. The blast radius is duplicate side effects
(a loss of correctness state) bounded by the 90-day retention window; no
stored user content is lost. Restores from a D1 backup restore the legacy
table only; the DO ledger is not part of DR media.

### Honest gaps

- **Artifacts Git history** is not mirrored. Only published source snapshots in
Expand Down
25 changes: 24 additions & 1 deletion packages/worker/src/account/export.node.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1383,6 +1383,23 @@ test('account export includes run_records section with runs and log lines', asyn
fields: { ok: true },
},
]
// Keyed package-invocation idempotency ledger row stored in the same
// RunLog DO; exported through the same run_records section.
const packageInvocation = {
id: 'invocation-export-1',
tokenId: 'token-1',
packageId: 'pkg-1',
packageKodyId: 'pkg-one',
exportName: './send-message',
idempotencyKey: 'evt-1',
requestHash: 'hash-1',
source: 'webhook',
topic: null,
status: 'completed' as const,
responseJson: '{"status":200,"body":{"ok":true}}',
createdAt: '2026-07-26T00:00:00.000Z',
updatedAt: '2026-07-26T00:00:01.000Z',
}
const env = {
APP_DB: db,
STORAGE_RUNNER: {
Expand All @@ -1402,6 +1419,7 @@ test('account export includes run_records section with runs and log lines', asyn
exportRuns: async () => ({
runs: [run],
logs,
packageInvocations: [packageInvocation],
nextStartAfter: null,
truncated: false,
}),
Expand All @@ -1428,10 +1446,12 @@ test('account export includes run_records section with runs and log lines', asyn
dbUserId: 1,
mcpUserId: 'user-aaa',
})
expect(accountExport.manifest.sections.run_records?.count).toBe(1)
// One run plus one invocation-ledger row exported through the section.
expect(accountExport.manifest.sections.run_records?.count).toBe(2)
expect(accountExport.durableObjects.runRecords).toEqual({
runs: [run],
logs,
packageInvocations: [packageInvocation],
nextStartAfter: null,
truncated: false,
})
Expand All @@ -1448,6 +1468,9 @@ test('account export includes run_records section with runs and log lines', asyn
run,
logs,
},
{
packageInvocation,
},
])
})

Expand Down
26 changes: 19 additions & 7 deletions packages/worker/src/account/export.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1456,10 +1456,14 @@ function buildManifest(input: {
discovery: { section: 'job_manager' },
}
sections.run_records = {
// The section carries runs plus the RunLog DO's package-invocation
// idempotency ledger rows, so count both when the export payload is
// present. The inventory fallback comes from `summarize` (runs only).
count:
input.durableObjects?.runRecords?.runs.length ??
input.inventoryCounts?.runRecords ??
0,
input.durableObjects?.runRecords == null
? (input.inventoryCounts?.runRecords ?? 0)
: input.durableObjects.runRecords.runs.length +
input.durableObjects.runRecords.packageInvocations.length,
warnings: input.warnings.filter((warning) =>
warning.startsWith('Run records '),
),
Expand Down Expand Up @@ -1772,10 +1776,18 @@ export async function readAccountExportSection(input: {
})
return {
section: input.section,
items: page.runs.map((run) => ({
run,
logs: page.logs.filter((log) => log.runId === run.id),
})),
// Runs page first; once runs are exhausted the same cursor continues
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
// through the keyed package-invocation idempotency ledger rows that
// live in the same per-user RunLog Durable Object.
items: [
...page.runs.map((run) => ({
run,
logs: page.logs.filter((log) => log.runId === run.id),
})),
...page.packageInvocations.map((packageInvocation) => ({
packageInvocation,
})),
],
truncated: page.truncated,
nextStartAfter: page.nextStartAfter,
pageSize,
Expand Down
2 changes: 1 addition & 1 deletion packages/worker/src/account/user-owned-surfaces.ts
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ export const accountUserOwnedDurableObjectSurfaces: ReadonlyArray<UserOwnedDurab
deletionResultKey: 'runLogs',
export: 'include',
notes:
'Execution history and captured logs across every runtime surface. Self-prunes inside the DO rather than through a retention cron lane.',
'Execution history and captured logs across every runtime surface, plus the keyed package-invocation idempotency ledger (terminal replay responses, 90-day window). Self-prunes inside the DO rather than through a retention cron lane; account deletion clearAll purges ledger rows with the run history, and account export pages both through the run_records section.',
},
{
id: 'mcp',
Expand Down
2 changes: 1 addition & 1 deletion packages/worker/src/app/retention.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ export const retentionPolicies: ReadonlyArray<RetentionPolicy> = [
retentionDays: packageInvocationRetentionDays,
batchSize: retentionDefaultBatchSize,
description:
'Package invocation idempotency rows keep terminal responses for 90 days; in-progress rows are never pruned.',
'LEGACY (dual-read window): keyed invocations now claim and store responses in the per-user RunLog Durable Object ledger, which self-enforces the same 90-day terminal-row window. This sweep only drains pre-migration terminal rows; in-progress rows are never pruned. Remove with the follow-up that drops the table and the D1 fallback read.',
},
{
table: 'mcp_memory_conversation_suppressions',
Expand Down
52 changes: 32 additions & 20 deletions packages/worker/src/email/inbound.workers.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ import {
} from './service.ts'
import { createForwardableEmailMessage } from './test-fixtures.ts'
import { ensureEmailTestSchema } from './test-schema.ts'
import { exportRunRecords } from '#worker/run-records/service.ts'
import { ensureUsageRollupsTestSchema } from '#worker/usage/test-schema.ts'
import { buildPublishedSourceManifestSnapshotKvKey } from '#worker/package-runtime/published-runtime-artifacts.ts'
import {
Expand Down Expand Up @@ -3380,38 +3381,49 @@ export default async function main(input = {}) {
}
}

const invocations = await db
.prepare(
`SELECT export_name, topic, source, response_json
FROM package_invocations
WHERE package_id = ?
ORDER BY created_at ASC, id ASC`,
// The keyed idempotency ledger lives in the owner's RunLog DO now.
const invocations = (
await exportRunRecords({ env, userId, pageSize: 100 })
).packageInvocations.filter((row) => row.packageId === packageId)
expect(invocations).toHaveLength(2)
// Anchor each stored response to its message body instead of relying
// on ledger ordering. Rows without a replay cache (oversized) would
// simply not match and fail the assertions below.
const responseBodies = invocations.flatMap((row) =>
row.responseJson == null
? []
: [
(
JSON.parse(row.responseJson) as {
status: number
body: Record<string, unknown>
}
).body,
],
)
const responseForTextBody = (textBody: string) =>
responseBodies.find(
(body) =>
(body['result'] as Record<string, unknown> | undefined)?.[
'textBody'
] === textBody,
)
.bind(packageId)
.all<Record<string, unknown>>()
expect(invocations.results).toHaveLength(2)
const responses = (invocations.results ?? []).map((row) =>
JSON.parse(String(row['response_json'])),
) as Array<{ status: number; body: Record<string, unknown> }>
const outboundMessages = await listEmailMessages({
db: env.APP_DB,
userId,
direction: 'outbound',
limit: 10,
})
expect(invocations.results?.map((row) => row['export_name'])).toEqual([
expect(invocations.map((row) => row.exportName)).toEqual([
'subscription:email.message.received',
'subscription:email.message.received',
])
expect(invocations.results?.map((row) => row['topic'])).toEqual([
expect(invocations.map((row) => row.topic)).toEqual([
'email.message.received',
'email.message.received',
])
expect(invocations.results?.map((row) => row['source'])).toEqual([
'email',
'email',
])
expect(responses[0]?.body).toMatchObject({
expect(invocations.map((row) => row.source)).toEqual(['email', 'email'])
expect(responseForTextBody('Stored body.\n')).toMatchObject({
ok: true,
result: {
eventType: 'received',
Expand All @@ -3421,7 +3433,7 @@ export default async function main(input = {}) {
replyDirection: 'outbound',
},
})
expect(responses[1]?.body).toMatchObject({
expect(responseForTextBody('Approved body.\n')).toMatchObject({
ok: true,
result: {
eventType: 'received',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import { ensureEmailTestSchema } from './test-schema.ts'
import { ensureUsageRollupsTestSchema } from '#worker/usage/test-schema.ts'
import { buildPublishedSourceManifestSnapshotKvKey } from '#worker/package-runtime/published-runtime-artifacts.ts'
import { exportRunRecords } from '#worker/run-records/service.ts'
import { silenceIncidentalRuntimeWarnings } from '#worker/test-support/incidental-runtime-warnings.ts'
import { createStableUserIdFromEmail } from '#worker/user-id.ts'

Expand Down Expand Up @@ -310,7 +311,7 @@
})
// A non-admin saving the identical subscription must never receive
// operator system mail.
const regularPackage = await seedSubscribedPackage({

Check warning on line 314 in packages/worker/src/email/system-email-subscriptions.workers.test.ts

View workflow job for this annotation

GitHub Actions / 🧹 Static

eslint(no-unused-vars)

Variable 'regularPackage' is declared but never used. Unused variables should match /^(_|ignored)/.
bundleKv,
userId: regularStableId,
scope: 'sysuser',
Expand Down Expand Up @@ -369,23 +370,24 @@
expect(stored).toBeDefined()
if (!stored) throw new Error('Expected stored system message')

const invocations = await env.APP_DB.prepare(
`SELECT package_id, export_name, topic, source, idempotency_key, response_json
FROM package_invocations
WHERE package_id IN (?, ?)`,
)
.bind(adminPackage.packageId, regularPackage.packageId)
.all<Record<string, unknown>>()
expect(invocations.results).toHaveLength(1)
const invocation = invocations.results?.[0]
// The keyed idempotency ledger lives in each owner's RunLog DO now.
const adminInvocations = (
await exportRunRecords({ env, userId: adminStableId, pageSize: 100 })
).packageInvocations
const regularInvocations = (
await exportRunRecords({ env, userId: regularStableId, pageSize: 100 })
).packageInvocations
expect(regularInvocations).toHaveLength(0)
expect(adminInvocations).toHaveLength(1)
const invocation = adminInvocations[0]
expect(invocation).toMatchObject({
package_id: adminPackage.packageId,
export_name: `subscription:${systemTopic}`,
packageId: adminPackage.packageId,
exportName: `subscription:${systemTopic}`,
topic: systemTopic,
source: 'email',
idempotency_key: `email:${stored.id}:${adminPackage.packageId}:${systemTopic}`,
idempotencyKey: `email:${stored.id}:${adminPackage.packageId}:${systemTopic}`,
})
const response = JSON.parse(String(invocation?.['response_json'])) as {
const response = JSON.parse(String(invocation?.responseJson)) as {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Nullable responseJson coerced with String(...) before JSON.parse in both migrated subscription tests. PackageInvocationLedgerRecord.responseJson is string | null (oversized responses drop the replay cache), so String(null) parses to null and the following property reads throw instead of producing a meaningful assertion failure. The equivalent pattern was already replaced with an explicit guard in packages/worker/src/email/inbound.workers.test.ts.

  • packages/worker/src/email/system-email-subscriptions.workers.test.ts#L390-L390: throw or fail explicitly when invocation?.responseJson == null, then JSON.parse(responseJson) on the narrowed string.
  • packages/worker/src/platform-feedback/platform-feedback-subscriptions.workers.test.ts#L367-L367: apply the same guard inside the per-package loop before parsing the found invocation's responseJson.
📍 Affects 2 files
  • packages/worker/src/email/system-email-subscriptions.workers.test.ts#L390-L390 (this comment)
  • packages/worker/src/platform-feedback/platform-feedback-subscriptions.workers.test.ts#L367-L367
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/worker/src/email/system-email-subscriptions.workers.test.ts` at line
390, Replace String(...) coercion with an explicit null/undefined guard before
JSON.parse in both migrated subscription tests:
packages/worker/src/email/system-email-subscriptions.workers.test.ts:390-390 and
packages/worker/src/platform-feedback/platform-feedback-subscriptions.workers.test.ts:367-367.
Fail or throw when responseJson is absent, then parse the narrowed responseJson
string within each test and per-package loop.

body: Record<string, unknown>
}
expect(response.body).toMatchObject({
Expand Down
19 changes: 13 additions & 6 deletions packages/worker/src/package-invocations/idempotency.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,17 @@
import { canonicalJsonStringify } from '@kody-internal/shared/canonical-json.ts'
import { toHex } from '@kody-internal/shared/hex.ts'
import { buildJsonErrorResponse } from './responses.ts'
import {
type getPackageInvocationByKey,
type PackageInvocationStoredResponse,
} from './repo.ts'
import { type PackageInvocationStoredResponse } from './repo.ts'

/**
* Store-agnostic view of an idempotency row: the RunLog DO ledger record and
* the legacy D1 `package_invocations` row (dual-read window) both map into it.
*/
export type ResolvableInvocationRecord = {
requestHash: string
status: string
storedResponse: PackageInvocationStoredResponse | null
}

export function markStoredResponseAsReplayed(
response: PackageInvocationStoredResponse,
Expand Down Expand Up @@ -54,11 +61,11 @@ function buildIdempotencyResponseUnavailable(input: {
}

export function resolveExistingInvocation(input: {
record: NonNullable<Awaited<ReturnType<typeof getPackageInvocationByKey>>>
record: ResolvableInvocationRecord
requestHash: string
idempotencyKey: string
}): PackageInvocationStoredResponse {
if (input.record.request_hash !== input.requestHash) {
if (input.record.requestHash !== input.requestHash) {
return buildJsonErrorResponse({
status: 409,
code: 'idempotency_mismatch',
Expand Down
Loading
Loading