mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-05 06:03:51 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Public MCP cloud sync runs two delivery workers: `mcp-client-mirror` and `mcp-revocation-index` > - Both workers retry every 5 seconds indefinitely when the Cloud connector broker returns HTTP 404/501 or fails repeatedly, and `delivery-work-coordinator` caps error retries at fixed `task.retryMs` > - Each failed tick executes PostgreSQL locks and queries, local secret derivation, Ed25519 request signing, and an HTTPS request while logging full error stacks roughly 20 times per minute > - In `client-mirror-sync`, a failed `begin` also sets `reserveFullRevision = true`, causing extra revision bumps and self-notifications that immediately re-trigger failed runs > - This pull request adds an opt-in `retryAtOnError` hook to `delivery-work-coordinator`, adds bounded exponential backoff to both MCP cloud sync workers, prevents self-wakes from bypassing backoff, and avoids unnecessary `reserveFullRevision` churn on unsupported HTTP 404/501 `begin` rejections > - The benefit is a >94% reduction in repeated failure load during broker outages or unsupported endpoint responses while preserving immediate recovery on broker return and all sleep-safety and revocation invariants ## Linked Issues or Issue Description No matching public GitHub issue or duplicate pull request exists. **What happened?** When the Cloud connector broker returns HTTP 404 (`UNKNOWN_BROKER_ERROR`), HTTP 501, or repeated transient errors, `mcp-client-mirror` (`server/src/services/public-mcp/client-mirror-sync.ts`) and `mcp-revocation-index` (`server/src/services/public-mcp/revocation-index-sync.ts`) retry every 5 seconds without backoff. Both workers log `Delivery reconciliation failed` continuously and repeat PostgreSQL advisory locks, queries, local key derivation, and signed HTTP requests. In `client-mirror-sync`, a failed tick also triggers `prepareMcpClientMutation`, which bumps `mcp_oauth_client_mirror_state.revision` and self-notifies `mcpClientMirror`, immediately re-running the worker and bypassing retry delays. **Expected behavior** Both MCP cloud sync workers must apply bounded exponential backoff on consecutive failures, ramp faster on HTTP 404/501 unsupported broker endpoints, avoid unnecessary revision bumps on unsupported `begin` rejections, ignore self-wakes while backed off, recover cleanly and reset backoff when the broker succeeds, and stay quiet once synchronized. **Steps to reproduce** 1. Configure a managed Paperclip instance with `startMcpClientMirrorSync` and `startMcpRevocationIndexSync` registered on `createDeliveryWorkCoordinator`. 2. Make the Cloud connector broker return HTTP 404 (`PaperclipCloudConnectorError` with status `404` and reason `UNKNOWN_BROKER_ERROR`) or HTTP 503 for 10 minutes. 3. Observe ~121-122 failed ticks per worker in 10 minutes (every 5 seconds, plus immediate self-wake ticks in `client-mirror-sync`) and repeated `Delivery reconciliation failed` errors. **Paperclip version or commit** Reproduced on `master` (`306437a2a5` / rebased on latest `origin/master`). **Deployment mode** Other (managed Cloud connector runtime; reproduced deterministically with unit tests and fake timers). ## What Changed - **`server/src/services/delivery-work-coordinator.ts`** (shared contract update): - Keep `scheduledAt` unmodified if `scheduler.schedule` throws on a non-finite deadline. - Add an opt-in `retryAtOnError?: () => number | null` callback on registered tasks. When `task.run` fails (`runFailed === true`), `input.canRun()` is true, and `task.retryAtOnError()` returns a finite deadline, schedule `Math.max(Date.now(), backoffAt)` directly instead of capping the retry at `task.retryMs`. - Keep `nextRunAtOnError` and all existing consumers (`scoped-deadline-work.ts`, `receiver-work.ts`, `createScheduledBoardPostsWorker`, `createClaimLeaseExpiryWorker`, and all workers without `retryAtOnError`) unchanged on the `task.retryMs` fallback. - Fall back to `task.retryMs` whenever `retryAtOnError` is absent, returns `null`, throws, returns a non-finite value, `!input.canRun()`, `!runFailed`, or `databaseWorkPending(input.owner, queue)` is true. - **`server/src/services/public-mcp/client-mirror-sync.ts`**: - Add bounded exponential backoff on consecutive failures: - Transient errors: `5s -> 10s -> 20s -> 40s -> 80s -> 160s -> 300s` (5-minute cap). - HTTP 404/501 unsupported broker endpoints: `5s -> 20s -> 80s -> 320s -> 900s` (15-minute cap). - Respect finite broker `Retry-After` (`PaperclipCloudConnectorError.retryAt`) up to the active cap. - Register `retryAtOnError: () => retryAt` so the coordinator schedules the computed backoff deadline directly. - Guard `run()` at entry against active `retryAt` so self-notifications from `prepareMcpClientMutation` and mutation bursts during a broker outage do not bypass backoff or execute database/network work early; preserve explicit `worker.wake()` to clear `retryAt` for immediate manual/recovery wake. - Avoid setting `fullRecovery = true; reserveFullRevision = true` when `begin` itself fails with HTTP 404/501 before acceptance; for failures after `begin` or non-404/501 failures, reserve at most one full-recovery revision per failure episode until recovery succeeds. - Reset `consecutiveFailures = 0` and `retryAt = null` immediately upon successful synchronization, disable ACK, or unmanaged/unconfigured state. - **`server/src/services/public-mcp/revocation-index-sync.ts`**: - Add the same bounded exponential backoff (`5s` doubling to `5m` on transient errors, `5s` quadrupling to `15m` on HTTP 404/501, respecting broker `Retry-After`), `retryAtOnError: () => retryAt`, early backoff guard in `run()`, explicit `worker.wake()` bypass, and immediate backoff reset upon grant sync progress or empty/synchronized state. - **Background work lifecycle contract (`rules/sleep-aware-background-work.mdc`)**: - **Trigger**: Startup check plus transaction-aware `notifyDeliveryWork` settlements (`mcp-client-mirror`, `mcp-revocation-index`) and explicit `worker.wake()`. - **Durable source of truth**: `mcp_oauth_client_mirror_state` / `mcp_oauth_clients` / `mcp_oauth_client_changes` / `mcp_oauth_device_requests` for client mirror; `mcp_oauth_grants` and `mcp_oauth_tokens` for revocation index. - **Pending-work predicate**: Unacknowledged revision/deviceStatus/issuer mismatch in `mcp_oauth_client_mirror_state` (`idle-client-mirror.ts` continues to report `blocked: true` until acknowledged); unrevoked grants whose `revocation_index_receipt` revision or `keyId` differs from current `revocation_revision` / `keyId`. - **Next deadline/retry**: `null` when synchronized, disabled, or unmanaged; `Date.now() + 5_000` when a follow-up batch/revision is queued without error; bounded exponential `retryAt` on failure. - **Quiet condition**: Zero scheduled timers, zero SQL queries, and zero network requests once synchronized, unconfigured, or unmanaged; bounded retries only while an unacknowledged obligation remains failed. - **Tests**: - Added `server/src/services/public-mcp/client-mirror-sync.test.ts` (fake timers, real `createDeliveryWorkCoordinator` + `installDatabaseWorkSignals`, covering HTTP 404, HTTP 501, HTTP 503, HTTP 429 `Retry-After`, `reserveFullRevision` churn, self-wake suppression, `readIdleMcpClientMirror` sleep-safety invariants, drain pause/resume, explicit `worker.wake()`, and quiet post-recovery state). - Extended `server/src/services/public-mcp/revocation-index-sync.test.ts` with fake-timer backoff, 404/503/429 coverage, mutation-during-backoff quietness, explicit `worker.wake()`, and post-recovery reset/quietness. - Extended `server/src/__tests__/work-scheduler.test.ts` for coordinator `retryAtOnError` backoff deadlines, `retryMs` fallbacks (`null`, `NaN`, and pending database work), and regression coverage confirming `nextRunAtOnError` remains capped at `retryMs`. ## Verification Tested on commit `c53a4a0bdf2ca3723f6a446e85f54bf2255a3223`: - **Red/green before-vs-after (fake timers over 10 minutes / `600_000 ms`)**: - `mcp-client-mirror` under HTTP 404: **122 failed ticks** before fix (`0, 0, 1, 5001, ...`, with immediate self-wakes and extra revision bump) -> **5 failed ticks** after fix (`0, 5s, 25s, 105s, 425s`, next wake `1_325s`; **95.9% reduction**, zero extra `reserveFullRevision` bumps). - `mcp-revocation-index` under HTTP 404: **121 failed ticks** before fix (`0, 5s, 10s, ..., 600s`) -> **5 failed ticks** after fix (`0, 5s, 25s, 105s, 425s`, next wake `1_325s`; **95.9% reduction**). - Both workers under transient HTTP 503: **121 failed ticks** -> **7 failed ticks** (`0, 5s, 15s, 35s, 75s, 155s, 315s`, next wake `615s`; **94.2% reduction**). - After broker returns HTTP 200: both workers save receipts, reset backoff (`nextWakeAt() === null`), and execute 0 queries and 0 publishes across a subsequent 10-minute idle window. - Commands run (all passed): - `pnpm --filter @paperclipai/server exec vitest run src/services/public-mcp/revocation-index-sync.test.ts src/services/public-mcp/client-mirror-sync.test.ts src/services/public-mcp/client-mirror-ack.test.ts src/__tests__/work-scheduler.test.ts` (4 files, 16 tests passed; full 7-file public-mcp + work-scheduler suite: 33/33 passed) - `pnpm check:module-boundaries` (passed) - `node scripts/check-test-budget.mjs --files server/src/services/public-mcp/client-mirror-sync.test.ts server/src/services/public-mcp/revocation-index-sync.test.ts server/src/__tests__/work-scheduler.test.ts` (passed: 113 nightly suites validated, 3 test files checked) - `pnpm --filter @paperclipai/server typecheck` (all 7 layers passed) - Scope note: Verification uses deterministic fake-timer unit suites and local typecheck/boundary checks; this does not claim live deployed Cloud host suspension or external wake behavior. ## Risks - Low risk. During an active broker outage, new local client or grant mutations wait until the active backoff deadline (capped at 5 minutes for transient errors and 15 minutes for HTTP 404/501) rather than immediately retrying the failing broker, while preserving durable pending state and `idle-client-mirror` sleep blocks until acknowledged. - Existing `delivery-work-coordinator` consumers (including `nextRunAtOnError` callers) keep their exact `retryMs`-capped fallback behavior. Only workers opting into `retryAtOnError` schedule error retries beyond `retryMs`, with `null`, thrown errors, non-finite values, drain/standby states, and pending database transactions still falling back safely to `task.retryMs`. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - Gemini 4 Neon (Google DeepMind, XHigh reasoning, with tool use and code execution) ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing>