Repository navigation
Reduce idle Worker maintenance CPU and cursor contention - #57
Conversation
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
OpenRouter review posted ( |
There was a problem hiding this comment.
OpenRouter pull-request review
Verdict: issues
Scope: full-pr (full-pr)
Mode: initial
Commit: dfcb48525e72f75cc0e3e5951929a5f631b71d29
Judge: openai/gpt-5.6-luna
Cost: $0.3100 (lanes $0.3036 + judge $0.0065)
Lanes
meta/muse-spark-1.2: ok (6 finding(s), 134.7s, 203619+9123 tokens (51170 cached), 4 tool round(s), via Meta, $0.24)z-ai/glm-5.3-flash: ok (8 finding(s), 292.6s, 1041387+46532 tokens (933312 cached), 23 tool round(s), via CoreWeave, $0.0665)
Warning
z-ai/glm-5.3-flash: coverage claims 0 finding(s) in 'worker/wrangler.jsonc' but 1 were reported
Findings
🟠 Issue 1 — cleanupLaneAt negative modulo returns undefined lane
worker/src/maintenance-schedule.ts:39 · risk · identified by meta/muse-spark-1.2
Concrete failure: cleanupLaneAt called with a scheduledTime whose UTC minute is 0 computes tick = -1. In JavaScript -1 % 14 === -1, so CLEANUP_LANES[-1] is undefined and the subsequent destructuring in index.ts (cleanup.task) throws TypeError: Cannot read properties of undefined. This can happen on delayed delivery, manual invocation, or if a future change calls the helper for validation at minute 0.
Evidence: worker/src/maintenance-schedule.ts:35-40 const tick = minute - Math.floor(minute/60) - 1; return CLEANUP_LANES[tick % CLEANUP_LANES.length]!. Current dispatcher guards minute 0 by only calling on 1-59 * * * *, so production cron avoids it, but the utility itself is not robust.
Checked: worker/src/index.ts:420-425, maintenance-schedule.test.ts skips minute 0 explicitly. No test covers cleanupLaneAt at minute 0.
Fix gap: normalize with ((tick % len)+len)%len or guard tick <0 and explicitly handle minute 0.
🟠 Issue 2 — Out-of-range limiterIndex silently becomes no-op
worker/src/identity-maintenance.ts:173 · risk · identified by meta/muse-spark-1.2
Concrete failure: runIdentityMaintenance and runSupportMaintenance implement per-policy rotation via limiters.slice(limiterIndex, limiterIndex+1). If limiterIndex is >= limiters.length (e.g., configuration drift reduces limiters, or CLEANUP_LANES is edited without updating runtime), slice returns [], Promise.all([]) resolves immediately, no sweep is performed, no error is logged, and the cron reports success while expired rate-limit rows accumulate forever.
Evidence: worker/src/identity-maintenance.ts:172-180 and worker/src/support-maintenance.ts:102-109. maintenance-schedule.ts:19-34 hard-codes indexes 0..3 assuming 4 identity and 4 support/Admin limiters. Runtime actually provides Object.freeze([4]) in identity-runtime.ts:222 and Object.freeze([2])+2 admin in index.ts:455-464 – tightly coupled.
Checked: no validation or maintenance_failed log for empty slice. Tests in identity-maintenance.test.ts:187-211 only cover in-range index.
Fix gap: validate limiterIndex against limiters.length and log maintenance_failed or fall back to full sweep when out of range.
🟠 Issue 3 — Concurrent mail and cleanup invocations contend on same D1 row
worker/src/index.ts:413 · risk · identified by meta/muse-spark-1.2
Concrete failure: At minutes 1-59 Cloudflare now fires two separate invocations: * * * * * (mail) and 1-59 * * * * (one cleanup lane). Both read/modify pegma-dev-maintenance/identity (MAIL_SEND/RECONCILE cursors vs challenges/email_operations/mail_retention etc). The new code merges per-invocation but still does a single conditional update per invocation. If the two invocations overlap, the second update sees a stale current version and the underlying storage-cloudflare-d1 conditional write can throw a version-conflict error, which bubbles to index.ts:447 / 485 as identity.maintenance_unavailable/support.maintenance_unavailable and the successful cursor advance of the losing invocation is lost (it will be retried next rotation, but mail cursor progress is delayed by ~14 minutes).
Evidence: worker/src/index.ts:412-470 schedules both crons simultaneously; identity-maintenance.ts:102-124 single saveCursors conditional write. Prior code had 5 concurrent writers inside one invocation with retries; new design reduces writers to 1 per invocation but introduces cross-invocation race.
Checked: maintenance-cursors.d1.test.ts verifies single-invocation merging and unchanged-bookmark skipping, but no test covers overlapping mail+cleanup D1 contention. No retry logic documented.
Fix gap: document expected contention rate, consider retry or separate last-write-wins handling, or explicitly note that overlapping invocation loss is acceptable.
🔵 Issue 4 — Stale cron description in docs/securityscan.md
docs/SUPPORT_COMPOSITION.md:198 · nit · identified by meta/muse-spark-1.2
Concrete failure: After the cron split, operational docs still describe the old cadence. Readers following docs/securityscan.md will mis-configure monitors/alerts expecting "1-minute identity/support maintenance".
Evidence: docs/securityscan.md:17 states 1-minute identity/support maintenance, 6-hour GitHub release reconciliation and line 236 mentions the 1-minute/6-hour cron cadence is in the public worker/wrangler.jsonc. worker/wrangler.jsonc:22-23 and worker/README.md:255-261 now document three crons (* * * * *, 1-59 * * * *, 0 */6 * * *) and rotating 14-lane cleanup.
Checked via grep for wrangler/maintenance. SUPPORT_COMPOSITION.md and worker/README.md were updated in this PR, but docs/securityscan.md was not.
Fix: update securityscan and any runbooks that inventory schedules.
🔵 Issue 5 — Idle mail run still performs one D1 get
worker/src/identity-maintenance.ts:147 · nit · identified by meta/muse-spark-1.2
Concrete failure: The PR goal is "no D1 requests" on idle mail workers, but the minute mail path still performs one get of pegma-dev-maintenance:identity even when only mail_send/mail_reconcile are selected and both pages are empty. On an idle site this is 1 D1 read per minute (1440/day) that the "no writes" optimization does not eliminate. The optimization correctly skips the update (action:'keep'), but read cost remains.
Evidence: worker/src/identity-maintenance.ts:147-154 reads when any selected task needs a cursor; mail_send/mail_reconcile need cursors, so reads is 1. Test identity-maintenance.test.ts:129-158 asserts expect(reads).toHaveBeenCalledTimes(1) and writes.not.toHaveBeenCalled, confirming the read persists. maintenance-cursors.d1.test.ts:82-113 asserts zero rows but still via D1 count query after the read.
Checked: worker/README.md:165-170 claims "reads its cursor record once … and skips unchanged cursors (including empty pages)" – wording implies at least one read is expected, so documentation is accurate, but the PR body claim of reducing D1 requests should clarify "writes" vs "reads".
Fix gap: if further reduction is desired, consider caching null cursor (no record) locally or skipping read when prior runs established empty state.
🔵 Issue 6 — Support rate-limit maintenance test gap for bookmark-read failure
worker/src/support-maintenance.ts:61 · nit · identified by meta/muse-spark-1.2
Concrete failure: runIdentityMaintenance has an explicit regression test for bookmark-read failure preserving cursor-independent hygiene (identity-maintenance.test.ts:128-146), but runSupportMaintenance has no equivalent. A D1 get failure on pegma-dev-support-maintenance would cause both queue_repair and queue_inactive_sweep to log support.maintenance_failed, but without a test the invariant that rate_limits still runs on Support (analogous to Identity) is not pinned and could regress.
Evidence: worker/src/support-maintenance.ts:61-72 implements same snapshot-then-fallback pattern as Identity, but worker/src/support-api.test.ts:490-515 only tests rate-limit isolation, not failure path. worker/src/maintenance-cursors.d1.test.ts covers empty-page skip but not read failure.
Checked via read_file of all three test files and grep for maintenance_failed.
Fix: add mirror test for Support read failure.
🟠 Issue 7 — New D1 test omits the transaction-guard schema that every sibling D1 test replicates from migration 0001
worker/src/maintenance-cursors.d1.test.ts:14 · risk · identified by z-ai/glm-5.3-flash
If the D1 adapter's conditional-update path relies on the guard mechanism, the first cursor write in this suite throws no such table: PEGMA_STORAGE_D1_TX_GUARD and the very tests meant to prove this PR's consolidated-write behavior are red; if the adapter tolerates the missing objects, the suite is green but it validates the merge/CAS behavior against a schema that no longer matches production.
Both existing D1 suites inline the full migration and label it "Semantically matches worker/migrations/0001_pegma_storage.sql": worker/src/support-desk.d1.test.ts and worker/src/webhooks-ledger.d1.test.ts each create RECORDS plus PEGMA_STORAGE_D1_TX_GUARD and its three PEGMA_STORAGE_D1_TX_ABORT_* triggers (a classic D1 atomic-batch CAS pattern — triggers that RAISE(ABORT, ...) on exists/missing/changed). The new maintenance-cursors.d1.test.ts creates only RECORDS and runs with createSchemaIfMissing: false, so nothing seeds the guard objects.
The new tests exercise exactly the write path this PR changes (update with { action: 'keep' } / merged conditional writes), so this suite is the one place where adapter interaction matters most. Proof gap: @pegma/storage-cloudflare-d1@0.4.1 is an external package not present in this checkout, so I could not inspect whether update requires the guard table; the fix either way is to reuse the sibling SCHEMA_STATEMENTS block.
🟠 Issue 8 — Rate-limit lanes silently sweep nothing when limiterIndex does not match the runtime's limiter array, and no test pins the real counts
worker/src/maintenance-schedule.ts:31 · risk · identified by z-ai/glm-5.3-flash
If a fifth durable limiter policy is ever added to createProductionIdentityRuntime (or a third to createSupportRuntime), its expired counters are never swept again and nothing fails: CLEANUP_LANES hardcodes exactly [0, 1, 2, 3] per kind, and runtime.limiters.slice(limiterIndex, limiterIndex + 1) in identity-maintenance.ts / support-maintenance.ts returns [] for an out-of-range index, so the lane completes successfully as a silent no-op. Expired rate-limit rows then accumulate in D1 forever — the exact decay the existing comment about pegma.admin.role.mutate warns against.
The inverse also silently no-ops: removing a limiter leaves a lane that sweeps nothing each hour.
What I checked: today the counts line up (identity runtime freezes exactly 4 limiters in identity-runtime.ts; support dispatch passes [...supportRuntime.limiters, adminMutation, adminLookup] = 4), so this is not a live bug. But no test pins the real runtime limiter counts to the lane count — maintenance-schedule.test.ts mocks the identity runtime with no limiters at all and support with [{}, {}] — so a future count drift ships green. A cheap guard (log/throw when slice yields empty) or a test asserting createProductionIdentityRuntime(...).limiters.length === 4 and the support dispatch array length === 4 would mechanize it.
🟠 Issue 9 — Consolidated cursor save makes cursor advancement all-or-nothing per invocation, discarding partial progress the old per-lane saves preserved
worker/src/identity-maintenance.ts:240 · risk · identified by z-ai/glm-5.3-flash
On an invocation where lanes succeed but the single final saveCursors write fails or the invocation is killed first, every lane's cursor advance is lost and all of them re-process their pages on the next run. The old code called saveCursor inside each task, so a crash after lane 3 still kept lanes 1–3's bookmarks; now the window between the first lane completing and the one write spans the whole invocation.
This matters most in exactly the environment this PR targets: on Workers Free an invocation that exceeds the 10 ms CPU allowance is terminated mid-flight, and with the merged write that termination now discards all lanes' advances instead of only the unfinished lane's. Cost: repeated D1 page reads and provider calls (guarded by leases/idempotency, so safe but wasted — the resource this PR optimizes), plus on the minute mail path a re-run of the same send/reconcile page.
Related attribution change: when the final write throws, index.ts logs identity.maintenance_unavailable (and support.maintenance_unavailable for the support path) even though every lane itself succeeded — previously a cursor-write failure was logged as identity.maintenance_failed with the task name, which is more precise for operators.
What I checked: the merged callback correctly spreads changes over the fresh current row, so concurrent mail/cleanup writers on disjoint fields are preserved; the regression is only the failure granularity, not the merge correctness. Same mechanism applies to saveSupportCursors in support-maintenance.ts.
🔵 Issue 10 — Minute mail path still reads the cursor bookmark even when mailWorker is null
worker/src/identity-maintenance.ts:152 · nit · identified by z-ai/glm-5.3-flash
On a deployment with mail delivery disabled, the minute cron performs one wasted D1 read every minute: selected.some(needsCursor) is true for ['mail_send', 'mail_reconcile'] regardless of runtime.mailWorker, so the snapshot get runs, then both tasks return early at if (mailWorker === null) return; and the value is discarded (~1440 dead reads/day).
Worse in the failure path: if that bookmark read fails, both mail lanes throw snapshot.error and log identity.maintenance_failed twice per minute for lanes that would have been no-ops. The old code never pushed the mail tasks when mailWorker === null, so a disabled-mail deployment did zero maintenance reads and logged nothing.
Production currently has mail enabled, so this only affects disabled-mail configurations or a future mail-off rollback; still, gating the snapshot read on runtime.mailWorker !== null when only mail tasks are selected restores the old idle behavior.
🔵 Issue 11 — SUPPORT_COMPOSITION.md still claims all four rate-limit policies are swept by the same run
docs/SUPPORT_COMPOSITION.md:187 · nit · identified by z-ai/glm-5.3-flash
"All four are swept by the same scheduled maintenance run." is now false: under the new design each Support/Admin policy is swept in its own rotating cleanup invocation (4 separate lanes), never together in one run. The sentence sits directly above the paragraph this PR rewrote, so the document now contradicts itself — a reader of the policy list concludes one invocation covers all four, while the new paragraph one screen below says one lane per invocation.
Rephrasing to e.g. "all four are swept by the same rotating cleanup schedule (one policy per invocation)" resolves it.
🔵 Issue 12 — GITHUB_RELEASE_WEBHOOK_PLAN.md still lists the deployed cron set as two expressions
docs/GITHUB_RELEASE_WEBHOOK_PLAN.md:61 · nit · identified by z-ai/glm-5.3-flash
The plan doc states the deployed worker runs "with crons * * * * * and 0 */6 * * *", which no longer matches wrangler.jsonc after this PR adds 1-59 * * * *. An operator reconciling the documented deployment configuration against the live one sees a mismatch.
I treated this as low priority since the file is a dated phase plan rather than a living ops doc, but the sentence describes current deployment state, not just history, so it should either be updated or marked historical.
🔵 Issue 13 — worker-configuration.d.ts regeneration pulls in unrelated env var additions
worker/worker-configuration.d.ts:6 · nit · identified by z-ai/glm-5.3-flash
The regenerated types now declare GITHUB_ORGANIZATION_ID and GITHUB_ALLOWED_REPOSITORY_IDS on Cloudflare.Env and NodeJS.ProcessEnv. Those vars were already present in wrangler.jsonc before this PR; the committed generated file was simply stale, and the cron change forced a regeneration that caught them up.
No functional risk (types only, and parseAllowedRepositoryIds already consumed the values), but it is unexplained scope: a reviewer diffing this file may wrongly conclude the PR introduced the env vars, and the PR body does not mention the regeneration.
🔵 Issue 14 — Cron trigger count reaches the documented Workers Free per-Worker cap
worker/wrangler.jsonc:23 · nit · identified by z-ai/glm-5.3-flash
The trigger list grows from two to three cron expressions on a deployment the README itself identifies as Workers Free ("Workers Free 10 ms limit"). Cloudflare's documented cap is 3 cron triggers per Worker on the Free plan (5 on Paid), so this deploy sits exactly at the cap: any future trigger (e.g. a fourth maintenance schedule) requires plan changes or restructuring, and if that cap figure is outdated and the Free limit is actually lower, wrangler deploy would fail at trigger registration.
Concrete cost today is nil — three is deployable — so this is a headroom note rather than a defect. Proof gap: the limit figure comes from Cloudflare's published limits page, which I cannot verify from this repository; the deploy dry run the PR author ran would have surfaced a hard failure already.
|
Addressed all 14 findings from the initial automated review in b9f375a:
The two findings present only in the review summary are also addressed:
Validation: |
There was a problem hiding this comment.
OpenRouter pull-request review
Verdict: clean
Scope: latest-commit (commit-range)
Mode: verify
Commit: b9f375a1c8442c6cc8bbcc662f8b2e743c573b03
Judge: openai/gpt-5.6-luna
Cost: $0.2152 (lanes $0.2151 + judge $0.0001)
Lanes
meta/muse-spark-1.2: ok (0 finding(s), 44.3s, 137788+3770 tokens (10067 cached), 5 tool round(s), via Meta, $0.18)z-ai/glm-5.3-flash: ok (0 finding(s), 178.1s, 470945+29048 tokens (390528 cached), 12 tool round(s), via CoreWeave, $0.0379)
Round 2 resolution
- ✅
r1-1fixed correctly — cleanupLaneAt negative modulo returns undefined lane: Fixed in worker/src/maintenance-schedule.ts:44-45 — now((tick % length)+length)% lengthnormalizes negative ticks after flooring; minute 0 tick -1 resolves to index 13 instead of -1/undefined. New testmaintenance-schedule.test.ts:57-73pins minute 0 and epoch-negative timestamps. - ✅
r1-2fixed correctly — Out-of-range limiterIndex silently becomes no-op: Fixed via new worker/src/maintenance-limiters.tsselectMaintenanceLimiterswhich throws RangeError for out-of-range index;identity-maintenance.ts:176-182andsupport-maintenance.ts:103-109now call it insiderate_limitstask so invalid indices are caught byrunTaskand logged asidentity.maintenance_failed/support.maintenance_failedRangeError instead of silentslice([]). Tests pi… - ✅
r1-3fixed correctly — Concurrent mail and cleanup invocations contend on same D1 row: Contention now documented and verified: worker/README.md notes D1 adapter retries conditional updates up to 3 times re-reading current record when mail (mail_send/mail_reconcile) and cleanup contend onpegma-dev-maintenance/identity. New D1 testmaintenance-cursors.d1.test.ts:155-214runs overlapping identity maintenances concurrently with a blockingupdatespy and asserts 3 decisions, versi… - ✅
r1-7fixed correctly — New D1 test omits the transaction-guard schema that every sibling D1 test replicates from migration 0001: Fixed in worker/src/maintenance-cursors.d1.test.ts:28-65 — SCHEMA_STATEMENTS now replicates productionmigrations/0001_pegma_storage.sqlverbatim includingPEGMA_STORAGE_D1_TX_GUARDtable and 3PEGMA_STORAGE_D1_TX_ABORT_*triggers, plus per-test DELETE of guard table; matches sibling suites support-desk.d1.test.ts / webhooks-ledger.d1.test.ts. - ✅
r1-8fixed correctly — Rate-limit lanes silently sweep nothing when limiterIndex does not match the runtime's limiter array, and no test pins the real counts: Fixed by rejecting drift and pinning counts:selectMaintenanceLimitersthrows on -1, 0.5, NaN, Infinity, >=length (maintenance-limiters.test.ts:20-26); callers log RangeError instead of no-op. New D1 testmaintenance-cursors.d1.test.ts:121-143builds real production runtimes (identity + support with admin mutation/lookup limiters) and assertsCLEANUP_LANESrate_limits indices exactly equal `… - 🤝
r1-9disputed — Consolidated cursor save makes cursor advancement all-or-nothing per invocation, discarding partial progress the old per-lane saves preserved: The consolidated save is the PR's deliberate tradeoff and the round-1 premise no longer holds in production: index.ts dispatches exactly one cleanup task per1-59 * * * *invocation and only the mail pair (send + reconcile) on* * * * *, so a crash can lose at most the two mail bookmarks — not 'lanes 1–3'. That residual is bounded and safe: mail pages are 5 items with 30 s leases, idempotency … - 8 nit finding(s) from earlier rounds retired (severity floor for follow-up rounds is
risk). - Open findings after this round: 0 (0 bug-severity).
No structured findings from the successful lane(s).
The minute cron currently runs every Identity and Support cleanup task alongside Mail delivery. Five Identity cursor writers and two Support cursor writers contend on shared rows and rewrite unchanged bookmarks, adding CPU, D1 requests, retries, and per-task logging even on an idle site.
This change keeps Mail send/reconciliation every minute and gives cleanup a separate invocation (
1-59 * * * *). That invocation rotates through one of 14 tasks, including individual rate-limit policies; each cleanup task runs every 14–15 minutes. Authentication and rate limiting continue to enforce expiration on access.Cursor-based runs read their bookmark once, merge successful lane results in one conditional update, and skip unchanged values. Failed or unselected lanes retain their bookmarks. Routine per-lane success logs are removed while invocation, failure, and terminal Mail logs remain. Existing cursor records work without a migration.
Validation passed on Node 22.23.3 and Node 24.18.0:
pnpm run checkpnpm test: 259 tests, including real local D1 regression tests for consolidated cursor writes, unchanged bookmarks, failed-lane preservation, and idle published Mail workers.pnpm run buildgit diff --check, and source control-byte verification.Dispatch tests cover all 14 cleanup tasks across UTC midnight, all eight rate-limit policies, minute Mail isolation, and independent release reconciliation.
Production CPU usage still needs verification after deployment: local D1 tests do not enforce Cloudflare's 10 ms free-tier CPU allowance. Larger active pages may require further page-size tuning. This PR does not deploy or change the Cloudflare plan.
Review follow-up (
b9f375a) validates limiter indexes, checks cleanup coverage against the real production compositions, skips disabled Mail lanes before bookmark I/O, handles pre-epoch timestamps, and logs cursor-save failures explicitly. D1 tests force an overlapping Mail/cleanup conditional-write conflict and prove that the existing adapter retry preserves both updates. Tests now use the complete deployment schema.Enabled Mail polling intentionally reads one durable bookmark plus Mail page scans; the idle optimization removes writes, redundant bookmark reads, contention, and per-lane success logs. The regenerated
worker-configuration.d.tsalso catches up two GitHub variables already present inwrangler.jsonc; this PR introduces no GitHub variable values.