Repository navigation
Reduce per-invocation maintenance CPU work - #58
Conversation
|
OpenRouter review posted ( |
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. |
There was a problem hiding this comment.
OpenRouter pull-request review
Verdict: issues
Scope: full-pr (full-pr)
Mode: initial
Commit: 42808669def9065259dcc98e38deca139ba212eb
Judge: skipped (one successful review lane; no merge needed)
Cost: $0.30 + at least $0.0360 (incomplete)
Lanes
meta/muse-spark-1.2: ok (8 finding(s), 103.2s, 262850+10482 tokens (62946 cached), 5 tool round(s), via Meta, $0.30)z-ai/glm-5.3-flash: failed-open (at least $0.0360 spent, incomplete) — OpenRouter lane wall-clock deadline exhausted; lane transport history (includes recovered errors): transport_timeouts=2, elapsed_deadlines=2
Findings
🔴 Issue 1 — Deferred EmailCodeProtector proxies only three methods
worker/src/identity-runtime.ts:96 · bug · identified by meta/muse-spark-1.2
A request that exercises an EmailCodeProtector method not proxied by the deferred wrapper throws TypeError: get(...).<method> is not a function and fails closed for email-code verification or code generation.
worker/src/identity-runtime.ts:96 builds deferredEmailCodeProtector that only forwards deriveCode, verifier, and matches. If @pegma/identity's EmailCodeProtector exposes additional members (e.g., hash, create, verify, or future rotation helpers), createIdentity will receive an incomplete implementation. The current test identity-runtime.test.ts:42 only exercises deriveCode via account/options, so a missing method is not caught.
Checked worker/src/identity-runtime.ts, recipes/cf-passkey-accounts/composition.ts:83 (type is ReturnType<typeof createHmacEmailCodeProtector> with no inline shape), and grep for EmailCodeProtector — the exact interface is in the external @pegma/identity package and could not be read from this checkout. Proof gap: could not list the canonical method names, so kept as bug/risk rather than nit.
🟠 Issue 2 — One-record pages bound CPU but can starve mail and retention
worker/src/identity-maintenance.ts:59 · risk · identified by meta/muse-spark-1.2
With PAGE_LIMIT = 1 and separate 1-minute triggers, a burst of >60 sends or >59 reconciliations per hour plus retained terminal records keeps the scan cursor on terminal rows, extending time-to-drain beyond the email-code lifetime and turning a transient spike into expired codes and dead-letter growth.
worker/src/identity-maintenance.ts:59 and worker/src/support-maintenance.ts:23 cap every sweep and runSendPage/runReconciliationPage to 1. Mail still retains terminal records for operator inspection until sweepMail deletes after 7 days (worker/src/identity-maintenance.ts:232), and worker/README.md:294 itself notes scanning "at most 60 send and 59 reconciliation operation records per hour, including retained terminal records." Support queue repair has the same cap while repairQueueProjectionPage can touch multiple rows per ticket.
Checked worker/src/identity-maintenance.ts:187, worker/src/maintenance-cursors.d1.test.ts:122 (drains 3 jobs over 6 ticks), and worker/README.md:292. No adaptive back-pressure or batch acknowledgement exists.
🟠 Issue 3 — Negative or zero scheduledTime accepted for release reconciliation
worker/src/release-reconciliation.ts:306 · risk · identified by meta/muse-spark-1.2
A scheduledTime of 0 or negative epoch values passes the scheduledTime < 0 guard only for negatives, but 0 is a valid epoch timestamp (1970-01-01) that maps to slot 0 and certifies a cycle, potentially polluting health after a mis-configured manual invocation.
worker/src/release-reconciliation.ts:306 checks scheduledTime < 0 and !Number.isFinite, but 0 yields slot = 0 and cycleStart = 0, then mergeReleaseRepositoryEtagUpdates stores reconciled[repo] = max(0,0) and can advance lastSuccessfulReconciliationAt to 1970-01-01T00:00:00.000Z. The maintenance dispatch test maintenance-schedule.test.ts:69 explicitly exercises negative minutes (-60_000) for cleanupLaneAt, confirming negative times are plausible inputs.
Checked worker/src/release-ops-state.ts:261 (Math.max(reconciled[id] ?? 0, scheduledTime)) which treats 0 as a real timestamp.
🟠 Issue 4 — Release reconciliation slot ignores hour window
worker/src/release-reconciliation.ts:316 · risk · identified by meta/muse-spark-1.2
An invocation whose scheduledTime is not on a */6 hour still selects a repository by getUTCMinutes(), records repositoryReconciledAt for the wrong 6-hour cycle, and can falsely certify lastSuccessfulReconciliationAt for a cycle that was not fully scanned.
worker/src/release-reconciliation.ts:316 derives slot = new Date(scheduledTime).getUTCMinutes() and cycleStart = floor(scheduledTime/6h)*6h. The only validation is Number.isFinite and >=0 (305), not hour % 6 === 0. A manually-triggered or drifted cron at e.g., 07:05 would map minute 5 to catalog[5], mark it succeeded in the 06:00 window, and count toward that window's full-catalog quorum.
Checked worker/src/release-reconciliation.ts:285, worker/wrangler.jsonc:22 (0-59 */6 * * *), and worker/src/index.ts:383 (passes controller.scheduledTime directly). No hour guard exists in code or tests.
🔵 Issue 5 — README cron documentation contains corrupted characters
worker/README.md:273 · nit · identified by meta/muse-spark-1.2
Operators copying the documented window see "0�12" and "14�15" with replacement characters instead of dashes, breaking search and rendering and undermining the intended run-book precision.
worker/README.md:273 and worker/README.md:295 contain 0�12 and 14�15 where the diff intended 0-12/14-15 or 0–12/14–15. The file is otherwise the source for schedule run-books (docs/securityscan.md:8, docs/GITHUB_RELEASE_WEBHOOK_PLAN.md). The deployed wrangler.jsonc is correct, so functionality is unaffected.
Checked worker/README.md:260 and worker/wrangler.jsonc:22 for the authoritative cron list.
🔵 Issue 6 — Unknown cron logs warn but still evaluates cleanup lane
worker/src/index.ts:407 · nit · identified by meta/muse-spark-1.2
An unknown controller.cron value logs maintenance.unknown_cron and returns, but the earlier cleanupLaneAt call is still evaluated for every non-release cron, doing unnecessary Math.floor work and risking an exception from a malformed scheduledTime before the guard.
worker/src/index.ts:407 computes cleanup = controller.cron === CLEANUP_CRON ? cleanupLaneAt(controller.scheduledTime) : null before checking if (cron !== MAIL_CRON && cron !== MAIL_RECONCILE_CRON && cleanup === null) (412). If controller.scheduledTime is NaN, cleanupLaneAt(NaN) yields NaN tick and ultimately CLEANUP_LANES[NaN % length] which is undefined and then throws on access, bypassing the intended unknown_cron warn path.
Checked worker/src/index.ts:383 (release branch returns early without lane calc) and worker/src/maintenance-schedule.ts:40 (no NaN guard).
🔵 Issue 7 — Cleanup lane rotation duplicates minute 59 but comment and test drift
worker/src/maintenance-schedule.ts:42 · nit · identified by meta/muse-spark-1.2
If a future edit restores skipping minute 0 while the code still skips 59, cleanupLaneAt will silently assign two different lanes to the same minute, causing one of the 14 hygiene lanes to run every ~28 minutes and another to be skipped for an hour.
worker/src/maintenance-schedule.ts:42 computes tick = minute - floor((minute+1)/60) with comment "skipping minute 59 never skips a lane." The previous implementation skipped minute 0 and the test maintenance-schedule.test.ts:77 was updated to assert 11:59 equals 11:58. The correctness relies entirely on the +1 offset matching CLEANUP_CRON = 0-58 * * * * (worker/src/maintenance-schedule.ts:8). No assertion ties the cron string to the offset, so drift is not caught except by the integration test maintenance-schedule.test.ts:86 that checks the cron array order.
Checked worker/src/maintenance-schedule.ts:6, worker/wrangler.jsonc:22, and worker/src/maintenance-schedule.test.ts:125 (covers lanes but not the cron/offset invariant).
🔵 Issue 8 — Removed repository leaves orphaned reconciledAt entries
worker/src/release-ops-state.ts:242 · nit · identified by meta/muse-spark-1.2
Removing a repository from GITHUB_ALLOWED_REPOSITORY_IDS never deletes its repositoryReconciledAt entry, leaving unbounded growth of the JSON map and stale keys that are decoded on every read.
worker/src/release-ops-state.ts:260 merges repositoryReconciledAt by adding succeeded ids but never prunes keys absent from the current allowedRepositoryIds. decodeEpochMap (worker/src/release-ops-state.ts:81) accepts any string keys, and mergeReleaseRepositoryEtagUpdates (worker/src/release-ops-state.ts:242) retains them via {...base.repositoryReconciledAt}. Health certification correctly checks only the current catalog (246), but storage bloat and cold-start decode cost grow with every rotation.
Checked worker/src/release-ops-state.test.ts (no pruning test) and worker/src/release-reconciliation.test.ts (no allowlist-shrink scenario).
| } | ||
|
|
||
| /** Keep key validation eager, but import HMAC only when code work needs it. */ | ||
| function deferredEmailCodeProtector(secret: Uint8Array): EmailCodeProtector { |
There was a problem hiding this comment.
🔴 Deferred EmailCodeProtector proxies only three methods (bug)
A request that exercises an EmailCodeProtector method not proxied by the deferred wrapper throws TypeError: get(...).<method> is not a function and fails closed for email-code verification or code generation.
worker/src/identity-runtime.ts:96 builds deferredEmailCodeProtector that only forwards deriveCode, verifier, and matches. If @pegma/identity's EmailCodeProtector exposes additional members (e.g., hash, create, verify, or future rotation helpers), createIdentity will receive an incomplete implementation. The current test identity-runtime.test.ts:42 only exercises deriveCode via account/options, so a missing method is not caught.
Checked worker/src/identity-runtime.ts, recipes/cf-passkey-accounts/composition.ts:83 (type is ReturnType<typeof createHmacEmailCodeProtector> with no inline shape), and grep for EmailCodeProtector — the exact interface is in the external @pegma/identity package and could not be read from this checkout. Proof gap: could not list the canonical method names, so kept as bug/risk rather than nit.
There was a problem hiding this comment.
Not applicable to the pinned dependency. The installed @pegma/identity@0.1.2 canonical dist/crypto.d.ts declares exactly deriveCode(handleHash), verifier(handleHash, code), and matches(expectedVerifier, handleHash, candidateCode) on EmailCodeProtector; all three are forwarded here. The helper explicitly returns that imported interface, so adding a required member in a future dependency update fails tsc rather than silently deploying an incomplete wrapper. The suggested hash/create/verify methods do not exist on this interface. No code change needed.
| // and far below Cloudflare's scheduled-handler wall limit. | ||
| const MAIL_PROVIDER_PAGE_LIMIT = 5; | ||
| // A record can require several conditional writes and a provider call. Bound | ||
| // CPU work as well as I/O; durable cursors continue the scan on the next tick. |
There was a problem hiding this comment.
🟠 One-record pages bound CPU but can starve mail and retention (risk)
With PAGE_LIMIT = 1 and separate 1-minute triggers, a burst of >60 sends or >59 reconciliations per hour plus retained terminal records keeps the scan cursor on terminal rows, extending time-to-drain beyond the email-code lifetime and turning a transient spike into expired codes and dead-letter growth.
worker/src/identity-maintenance.ts:59 and worker/src/support-maintenance.ts:23 cap every sweep and runSendPage/runReconciliationPage to 1. Mail still retains terminal records for operator inspection until sweepMail deletes after 7 days (worker/src/identity-maintenance.ts:232), and worker/README.md:294 itself notes scanning "at most 60 send and 59 reconciliation operation records per hour, including retained terminal records." Support queue repair has the same cap while repairQueueProjectionPage can touch multiple rows per ticket.
Checked worker/src/identity-maintenance.ts:187, worker/src/maintenance-cursors.d1.test.ts:122 (drains 3 jobs over 6 ticks), and worker/README.md:292. No adaptive back-pressure or batch acknowledgement exists.
There was a problem hiding this comment.
This is a real, intentionally documented capacity tradeoff, rather than an unacknowledged throughput guarantee. The request is to reduce per-invocation work for this low-traffic Worker; the README explicitly states 60 send / 59 reconciliation scanned records per hour (including retained records), requires a full scan comfortably below the ten-minute code lifetime, and calls for indexed discovery / paginated component APIs or a larger CPU allowance as backlog grows. Raising the page size or processing several pages in one invocation would remove the CPU bound this change introduces. The cursors make bounded progress; retained rows increase scan latency rather than pinning a cursor permanently. I am leaving this unresolved for a maintainer's capacity/design decision. A larger-traffic queue-discovery redesign is outside this CPU-reduction patch.
| return { examined: 0, upserted: 0, cleared: 0, notModified: 0, failed: 0 }; | ||
| // Epoch-conditioned ETag updates so a concurrent webhook invalidation wins. | ||
| const etagUpdates: ConditionalEtagUpdate[] = []; | ||
| const succeeded: string[] = []; |
There was a problem hiding this comment.
🟠 Negative or zero scheduledTime accepted for release reconciliation (risk)
A scheduledTime of 0 or negative epoch values passes the scheduledTime < 0 guard only for negatives, but 0 is a valid epoch timestamp (1970-01-01) that maps to slot 0 and certifies a cycle, potentially polluting health after a mis-configured manual invocation.
worker/src/release-reconciliation.ts:306 checks scheduledTime < 0 and !Number.isFinite, but 0 yields slot = 0 and cycleStart = 0, then mergeReleaseRepositoryEtagUpdates stores reconciled[repo] = max(0,0) and can advance lastSuccessfulReconciliationAt to 1970-01-01T00:00:00.000Z. The maintenance dispatch test maintenance-schedule.test.ts:69 explicitly exercises negative minutes (-60_000) for cleanupLaneAt, confirming negative times are plausible inputs.
Checked worker/src/release-ops-state.ts:261 (Math.max(reconciled[id] ?? 0, scheduledTime)) which treats 0 as a real timestamp.
There was a problem hiding this comment.
The negative-time claim is contradicted by the < 0 guard: negative values are rejected. Epoch zero is a valid timestamp, and storing a successful observation at 1970 does not make current health fresh: isReconciliationStale compares the recorded timestamp with the current time and flags it stale. A delayed old observation also cannot regress an existing newer success (Math.max on per-repository progress and oldest > Date.parse(completedAt) on global success). The cleanup timestamp-normalization test is a deterministic unit test, not an externally accessible production invocation path. Rejecting epoch zero would not fix a demonstrated health bug.
|
Addressing the two findings delivered only in the review body: Issue 4 (release hour window): not a false-success path. Production passes Cloudflare's scheduled timestamp for the configured Issue 6 (unknown cron evaluates cleanup): not applicable. The expression is |
There was a problem hiding this comment.
OpenRouter pull-request review
Verdict: clean
Scope: latest-commit (commit-range)
Mode: verify
Commit: 7c24043ea2540de706b144dca2006f1f6189bbef
Judge: openai/gpt-5.6-luna
Cost: $0.2416 (lanes $0.2415 + judge $0.0001)
Lanes
meta/muse-spark-1.2: ok (0 finding(s), 45.1s, 189644+4211 tokens (37316 cached), 6 tool round(s), via Meta, $0.21)z-ai/glm-5.3-flash: ok (0 finding(s), 179.4s, 234106+9466 tokens (77312 cached), 11 tool round(s), via BaseTen, $0.0276)
Round 2 resolution
- 🤝
r1-1disputed — Deferred EmailCodeProtector proxies only three methods: Deferred wrapper still forwards only three methods, but pinned@pegma/identity@0.1.2declares exactlyderiveCode,verifier,matchesonEmailCodeProtector.deferredEmailCodeProtectorexplicitly returns that imported interface (worker/src/identity-runtime.ts:96), so adding a required member in a future publish failstscrather than silently deploying an incomplete proxy; suggested `h… - 🤝
r1-2disputed — One-record pages bound CPU but can starve mail and retention: PAGE_LIMIT=1 (worker/src/identity-maintenance.ts:59,worker/src/support-maintenance.ts:23) still bounds throughput to ~60 send/59 reconcile per hour including retained terminal rows. Intentionally documented capacity tradeoff for Workers Free 10 ms headroom:worker/README.mdnow explicitly states the limits, requires full scan << ten-minute code lifetime and calls for indexed discovery/pagin… - 🤝
r1-3disputed — Negative or zero scheduledTime accepted for release reconciliation:worker/src/release-reconciliation.ts:291-293already rejects negatives (scheduledTime < 0) and non-finite times. Epoch 0 is a valid timestamp and does not make health fresh:isReconciliationStaleinworker/src/release-ops-state.tscompares recorded time to now (>7h => stale), andmergeReleaseRepositoryEtagUpdatesusesMath.maxper-repo andoldest > Date.parse(completedAt)for global … - 🤝
r1-4disputed — Release reconciliation slot ignores hour window:worker/src/release-reconciliation.ts:297-299derivesslot = getUTCMinutes()andcycleStart = floor(scheduledTime/6h)*6h. Production cron is0-59 */6 * * *; delayed delivery retains intended slot/window. Off-hour manual call (e.g. 07:05 => cycleStart 06:00) still fetches that slot's repository before recordingrepositoryReconciledAt, andworker/src/release-ops-state.ts:257-270advances … - 4 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).
Scheduled mail still combined send and reconciliation scans, and release reconciliation processed the entire catalog in one invocation. This reduces work per scheduled invocation to create headroom under the Workers Free 10 ms CPU allowance.
Validation:
check, all 266 tests, and static build passed on Node 22.23.3 and 24.18.0; Worker types regenerated; Wrangler deploy dry-run, diff checks, and source control-byte checks passed. New regressions cover real D1 mail progress across small pages and cursor wraparound, lazy key import, isolated dispatch, failed/incomplete release cycles, concurrent shards, and webhook invalidation.Production verification remains required after merge/deployment: local CPU sampling includes local runtime/I/O overhead and does not establish a Cloudflare CPU ceiling. Inspect CPU distributions and termination outcomes for all four triggers, including populated mail work and release 200/304 paths. The published Sessions and rate-limit APIs still sweep whole partitions; larger workloads need paginated component APIs or a larger CPU allowance. One-record pages also reduce throughput (60 send / 59 reconciliation records per hour, including retained operations), so scan backlog must remain comfortably below the email-code lifetime. No D1 migration is needed.