Skip to content

Cut sequential D1/KV round trips from the execute hot path - #1035

Merged
kody-bot merged 2 commits into
mainfrom
cursor/execute-perf-hot-path-c7fa
Jul 30, 2026
Merged

kody-bot merged 2 commits into
mainfrom
cursor/execute-perf-hot-path-c7fa

Conversation

@kentcdodds

@kentcdodds kentcdodds commented Jul 30, 2026 •

Copy link
Copy Markdown
Member

Execute performance: root-cause analysis and hot-path fixes

What production data shows

Queried kody_usage_events (Analytics Engine) for execute sandbox durations:

Window p50 p90 p99
Jul 16–23 190–350ms 1.4–3.6s 5–29s
Jul 24–29 1.7–3.6s 7–47s pegged at the 90s timeout

Two distinct findings:

  1. The daily p50 jump at 17:00 UTC Jul 23 is mostly a composition change, not a code regression. No deploy landed between 09:13 and 19:58 UTC that day. At 17:00 UTC a high-frequency workload (~150 sub-500ms successes/hr plus ~35 instant-error runs/hr) stopped entirely; the pre-existing slow population (~100/hr at ≥1s) stayed flat, so the median moved onto the slow class. The pre-exec typecheck flag (Add feature-flagged pre-exec TypeScript checks #1029, merged Jul 29) postdates the shift and is not the cause.
  2. The slow class is genuinely bad and got worse: ≥15s runs doubled in rate after Jul 23–24. Live probes against production show why: every kody.* capability dispatch is fine warm (~40–105ms) but the first dispatch in a cold isolate costs ~1.5s, every sandbox fetch pays a D1 plan read + counter write in the gateway (Add bad-actor abuse controls: suspension, outbound-email pause, compute quotas, delivery insights #911, Jul 24), and one warm packages.invokeChecked of a trivial export costs ~950ms–1.9s — it is a long chain of sequential D1/KV/DO round trips. Agent workflows chain package invocations (github, discord), so tool calls stack multiple seconds of platform overhead on top of real API time.

Measured warm packages.invokeChecked breakdown (before this PR): check phase resolves the package + manifest + artifact and loads the full package source for a projection that invokeChecked discards; the invoke phase then re-resolves the package, re-loads manifest + artifact, acquires a second account write lease (~5 D1 statements — the MCP call already holds one), inserts/updates idempotency rows, and awaits run-record Durable Object writes before responding.

Changes

  • Reentrant account write leases (account/deletion-state.ts): nested withAccountWriteLease calls for the same user inside the same async context reuse the outer lease. The MCP request boundary, app requests, and job runs all take a lease, so every nested package invocation previously paid a full extra acquire/release (~5 D1 statements, 4 of them writes). Deletion remains blocked for exactly the outer lease's span.
  • Short-TTL (60s) plan/account lookup caches (entitlements/service.ts): getCachedUserPlan and findCachedUserAccountByStableUserId, keyed by the D1Database binding, used by consumeDailyEntitlement (every execute call and every sandbox outbound fetch) and the fetch gateway's email reverse-resolution. The atomic daily counter upsert stays uncached; only plan-limit resolution tolerates ≤60s staleness. Failures are never cached.
  • packages.invokeChecked resolves its package once (package-invocations/*): the check phase skips the full-source export projection it discards, and hands its saved-package row + manifest + prepared bundle artifact to the invoke phase, which no longer re-resolves or re-loads them. Bare packages.check behavior is unchanged.
  • Reuse the loaded source row: skip the getEntitySourceById re-query when the artifact's sourceId matches the row already loaded with the manifest.
  • Thread the MCP Durable Object's waitUntil through the execute tool (mcp/index.ts, tools/execute.ts): terminal run-record writes, nested-invocation run records, and error-subscription dispatch now ride ctx.waitUntil instead of serializing the response (the options and never-block contract already existed; the public execute tool just never passed it).

Testing

  • npm run validate passes (1578 unit tests across 463 files, 20 Playwright e2e, MCP e2e, lint/format/typecheck/structure checks).
  • New unit tests: nested lease reuse (same user reuses, different user acquires, sequential siblings re-acquire), plan cache behavior (per-binding isolation, staleness bound, failure non-caching), cached account reverse-resolution.

Follow-ups (not this PR)

  • The ~1.5s first-capability-dispatch cost in a cold isolate.
  • A companion agent is adding Server-Timing-style phase instrumentation to the execute response on a separate branch.
  • Identify what the sub-500ms workload was that stopped at 17:00 UTC Jul 23 (its instant-error twin stopped at the same moment — likely a job/polling flow that broke or was turned off).
System recap — extends existing primitives (medium risk)

Mode: recap · Base: main @ 7ebea332 · Head: fa6d87e4

Classification: extends — no new primitives; changes the account write-lease contract (reentrant per async context), entitlement plan resolution (60s cached for quota checks), and the package-invocation check/invoke contract (single load).

Primitives touched

Primitive Group Impact
mcp-server surfaces extends — execute tool hands run-record writes to DO waitUntil; fetch gateway uses cached account resolve
entitlements auth extends — consumeDailyEntitlement resolves plan limits through a 60s per-binding cache; counter writes unchanged
package-invocations (unmatched paths) runtime extends — invokeChecked passes check-phase loads into the invoke phase; nested lease reuse

System map

The MCP execute tool's nested package invocations now reuse the request's account write lease and the check phase's package loads instead of re-reading D1/KV.

Legend: green = composes (wiring only) · amber = extended by this PR · red = new primitive · gray = context (unchanged, included only when an edge crosses it).

flowchart LR
	mcpServer["mcp-server<br/>MCP endpoint (/mcp)"]:::extended
	entitlements["entitlements<br/>Plans & entitlements"]:::extended
	pkgInvocations["package-invocations<br/>Package invocation runtime"]:::extended
	d1AppDb["d1-app-db<br/>D1 app database"]:::untouched
	runLog["run-records<br/>RunLog Durable Object"]:::untouched
	mcpServer -->|"execute tool passes ctx.waitUntil"| runLog
	mcpServer -->|"per-fetch quota via cached plan"| entitlements
	entitlements -->|"counter upsert only (plan read cached 60s)"| d1AppDb
	pkgInvocations -->|"nested withAccountWriteLease reuses outer lease"| d1AppDb
	mcpServer -->|"invokeChecked: check loads reused by invoke"| pkgInvocations
	classDef touched fill:#1a7f37,color:#fff
	classDef extended fill:#9a6700,color:#fff
	classDef added fill:#cf222e,color:#fff
	classDef untouched fill:#57606a,color:#fff
Loading

Invariants

Per-user isolation is preserved: lease reentrancy is keyed by stableUserId within one async context; plan caches are keyed by user id + email per D1Database binding; preloaded package artifacts come from the same user-scoped check call.

Open in Web Open in Cursor 

Summary by CodeRabbit

  • Performance
    • Faster entitlement and plan/account resolution via short-lived caching.
    • Faster package invocation checks/invocations by reusing preloaded artifacts to reduce repeated loading.
  • Reliability
    • Improved account write lease handling for nested, concurrent, and detached async work to prevent incorrect lease reuse.
    • Durable Object MCP agents can defer background work with waitUntil.
  • Compatibility
    • Package invocation check results and error messages are more consistent, with clearer failure context (including export details).

- Reentrant account write leases: nested withAccountWriteLease calls for
  the same user reuse the outer lease (MCP call -> package invocation
  previously paid ~5 extra D1 statements per invoke)
- Short-TTL (60s) per-binding caches for quota plan resolution and the
  fetch gateway's account reverse-resolution; the atomic daily counter
  write stays uncached
- packages.invokeChecked resolves the package once: the check phase skips
  the full-source export projection it discards and hands its saved
  package + manifest + bundle artifact to the invoke phase
- Reuse the already-loaded entity source row instead of re-querying when
  the artifact's sourceId matches
- Thread the MCP Durable Object's waitUntil through the execute tool so
  terminal run-record writes and error-subscription dispatch no longer
  serialize the response
@coderabbitai

coderabbitai Bot commented Jul 30, 2026 •

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 8ede16e5-9f2c-49b3-87d8-0868ad91372a

📥 Commits

Reviewing files that changed from the base of the PR and between fa6d87e and daf4cab.

📒 Files selected for processing (3)
  • packages/worker/src/account/deletion-state.node.test.ts
  • packages/worker/src/account/deletion-state.ts
  • packages/worker/src/package-invocations/idempotent-module-invocation.ts

📝 Walkthrough

Walkthrough

The changes add async-local account lease tracking, per-D1 entitlement caching, reusable package-invocation preloads, user-scoped source resolution, and Durable Object waitUntil propagation through MCP execution.

Changes

Account write lease reuse

Layer / File(s) Summary
Async-local lease tracking and validation
packages/worker/src/account/deletion-state.ts, packages/worker/src/account/deletion-state.node.test.ts
Lease frames distinguish active scopes from detached work. Tests cover nested reuse, independent users, detached re-acquisition, sequential leases, and cleanup.

Entitlement lookup caching

Layer / File(s) Summary
Cached entitlement lookups and consumers
packages/worker/src/entitlements/service.ts, packages/worker/src/entitlements/entitlements.node.test.ts, packages/worker/src/mcp/fetch-gateway.ts
Plan and stable-user account lookups use per-D1 TTL caching, validation, and failure eviction. Entitlement consumption and gateway reverse resolution use cached helpers.

Preloaded package execution and background work

Layer / File(s) Summary
Check outcomes and preload construction
packages/worker/src/package-invocations/invoke-check.ts
Package checks return structured results with reusable saved-package and module-artifact preloads.
Preload threading through runtime invocation
packages/worker/src/package-invocations/runtime-tool-factories.ts, packages/worker/src/package-invocations/http-invoke.ts, packages/worker/src/package-invocations/idempotent-module-invocation.ts
Checked invocations forward preloads through runtime and execute paths, reusing prepared artifacts and applying user-scoped source lookup when needed.
Durable Object waitUntil propagation
packages/worker/src/mcp/index.ts, packages/worker/src/mcp/mcp-registration-agent.ts, packages/worker/src/mcp/tools/execute.ts
MCP execution exposes and forwards the bound Durable Object waitUntil method to nested operations.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant invokeChecked
  participant checkPackageInvokeForRuntimeWithPreloads
  participant invokePackageExportForExecuteRuntime
  participant invokeSavedPackageModule
  invokeChecked->>checkPackageInvokeForRuntimeWithPreloads: check and preload package artifacts
  checkPackageInvokeForRuntimeWithPreloads-->>invokeChecked: result and preloads
  invokeChecked->>invokePackageExportForExecuteRuntime: invoke with preloads
  invokePackageExportForExecuteRuntime->>invokeSavedPackageModule: pass preloaded module artifact
  invokeSavedPackageModule-->>invokeChecked: execute package export
Loading

Possibly related PRs

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main performance-focused change in the execute hot path.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch cursor/execute-perf-hot-path-c7fa

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@kody-bot
kody-bot marked this pull request as ready for review July 30, 2026 01:55
@github-actions

github-actions Bot commented Jul 30, 2026 •

Copy link
Copy Markdown
Contributor

🔎 Preview deployed: https://kody-pr-1035.kody-a99.workers.dev

Worker: kody-pr-1035
D1: kody-pr-1035-db
KV: kody-pr-1035-oauth-kv

Mocks:

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🤖 Prompt for all review comments with 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.

Inline comments:
In `@packages/worker/src/account/deletion-state.ts`:
- Around line 94-112: Update withAccountWriteLease and
heldAccountWriteLeaseStorage so the AsyncLocalStorage state reflects lease
lifetime, preventing child or detached async work created by write from treating
a released lease as active. Track and invalidate each user’s active lease state
(or equivalent nested-call guard) when the outer acquisition completes, while
preserving synchronous nested writes during the active lease; add a regression
test where a child spawned inside write calls withAccountWriteLease only after
the outer call resolves.

In `@packages/worker/src/package-invocations/idempotent-module-invocation.ts`:
- Around line 296-303: Update the repoSource resolution around
getEntitySourceById so the artifact source lookup is scoped to
input.actor.userId. Pass the user ID to the existing helper or extend
getEntitySourceById to require and apply that user constraint, while preserving
the current sourceRow path and source-ID matching behavior.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 69f9b29c-fbcf-4c5e-83a7-277cd0bd4155

📥 Commits

Reviewing files that changed from the base of the PR and between e1f3d83 and fa6d87e.

📒 Files selected for processing (12)
  • packages/worker/src/account/deletion-state.node.test.ts
  • packages/worker/src/account/deletion-state.ts
  • packages/worker/src/entitlements/entitlements.node.test.ts
  • packages/worker/src/entitlements/service.ts
  • packages/worker/src/mcp/fetch-gateway.ts
  • packages/worker/src/mcp/index.ts
  • packages/worker/src/mcp/mcp-registration-agent.ts
  • packages/worker/src/mcp/tools/execute.ts
  • packages/worker/src/package-invocations/http-invoke.ts
  • packages/worker/src/package-invocations/idempotent-module-invocation.ts
  • packages/worker/src/package-invocations/invoke-check.ts
  • packages/worker/src/package-invocations/runtime-tool-factories.ts

Comment on lines +94 to +112
const heldAccountWriteLeaseStorage = new AsyncLocalStorage<
ReadonlySet<string>
>()

export async function withAccountWriteLease<T>(input: {
db: D1Database
stableUserId: string
holder?: string
write: () => Promise<T>
}) {
const heldLeases = heldAccountWriteLeaseStorage.getStore()
if (heldLeases?.has(input.stableUserId)) {
return await input.write()
}
const nextHeldLeases = new Set(heldLeases)
nextHeldLeases.add(input.stableUserId)
return await heldAccountWriteLeaseStorage.run(nextHeldLeases, async () =>
acquireAccountWriteLeaseAndWrite(input),
)

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 | 🟠 Major | 🏗️ Heavy lift

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Inspect lease callers for detached work that can inherit AsyncLocalStorage context.
ast-grep outline packages/worker/src/account/deletion-state.ts --items all
rg -n -C3 --type=ts '\bwithAccountWriteLease\s*\(' packages/worker/src
rg -n -C3 --type=ts '\bvoid\s+|\bwaitUntil\s*\(' \
  packages/worker/src/package-invocations packages/worker/src/mcp

Repository: kentcdodds/kody

Length of output: 41280


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== deletion-state outline/sections =="
wc -l packages/worker/src/account/deletion-state.ts
sed -n '1,280p' packages/worker/src/account/deletion-state.ts

echo "== related test sections =="
wc -l packages/worker/src/account/deletion-state.node.test.ts
sed -n '1,240p' packages/worker/src/account/deletion-state.node.test.ts

echo "== package invocation common/invoker waitUntil context candidates =="
sed -n '75,140p' packages/worker/src/package-invocations/common.ts
rg -n -C4 --type=ts 'waitForCompletion|waitUntilFrom|waitUntil|ctx=|executionContext|executor|run' packages/worker/src/package-invocations packages/worker/src/mcp/src packages/worker/src/mcp 2>/dev/null || true

Repository: kentcdodds/kody

Length of output: 50372


Prevent detached async work from reusing a released lease.

withAccountWriteLease puts the user in heldAccountWriteLeaseStorage, and that AsyncLocalStorage context is captured by child promises spawned in write. If a void/waitUntil callback invokes this function after the outer finally removes the user, the nested call believes the lease is still held and can run a write while the lease row was released. Track lease lifetime/active count per user or explicitly invalidate nested calls in detached work; add a regression test for a child created inside the outer callback that calls withAccountWriteLease only after the outer call resolves.

🤖 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/account/deletion-state.ts` around lines 94 - 112, Update
withAccountWriteLease and heldAccountWriteLeaseStorage so the AsyncLocalStorage
state reflects lease lifetime, preventing child or detached async work created
by write from treating a released lease as active. Track and invalidate each
user’s active lease state (or equivalent nested-call guard) when the outer
acquisition completes, while preserving synchronous nested writes during the
active lease; add a regression test where a child spawned inside write calls
withAccountWriteLease only after the outer call resolves.

Comment thread packages/worker/src/package-invocations/idempotent-module-invocation.ts Outdated
…lookup by user

- Lease reentrancy now tracks per-user frames that deactivate at release,
  so detached waitUntil work inheriting the async context re-acquires its
  own lease instead of reusing a released one (with regression test)
- Package invocation repo-source fallback uses the user-scoped
  getEntitySourceByIdForUser lookup
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants