Repository navigation
perf(push): keep retention sweeps from overlapping without slowing the drain - #23001
Conversation
|
Navigate logical layers of code changes, visualize relationships, and explore their blast radius. No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Advanced Run ID: 📒 Files selected for processing (4)
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 7 remain after this review. 📝 WalkthroughWalkthrough
Priority: ➖ Normal Merge Risk: ⚪ Minimal · up to No actionable merge-blocking risk is established; the slower cleanup described for this change is an acknowledged trade-off. Security Architecture ReviewSecurity architecture risk: 🔵 Low · up to The new scheduling prevents cleanup sweeps from overlapping within a worker, while existing request controls remain in place. A sustained backlog can keep cleanup active for longer, but its effect on database capacity across the deployment is not established. Retained concerns Security review detailsSecurity Blast Radius
Trust Boundaries and Controls
Resilience and Maintainability Implications
Hardening Proposals
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
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. Comment |
There was a problem hiding this comment.
✅ No new issues found. The guard is correct, self-contained, and covered by tests that genuinely fail on the parent.
Reviewed changes
- Per-store sweep guard —
prune()incloud/apps/push/src/push-background.tsnow skips asetIntervaltick while the prior sweep is still in flight (runningflag), and releases the flag in a.finally, so failed sweeps recover on the next tick. Each pruner keeps its own closure, so schedules stay independent. - Regression tests — new
cloud/apps/push/src/push-background.test.tscovers the overlap guard, failure recovery, validation mode, and an integration claim-queue-delay test that drives the realDurablePushStorethroughreserveRequestConnection.
The change matches the existing DurablePushWorker.runDue() promise-guard pattern. The run() callbacks invoke async methods (prune, pruneExpired), so a synchronous throw can't wedge the flag, and each statement is bounded by the 5s pool statement_timeout, so promises settle. The author has called out the accepted trade-off (slower backlog drain, expired rows retained longer) and the pre-existing non-joining shutdown explicitly; neither is newly introduced here.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
…he tick
The overlap guard on the shared prune timer removed a side effect the sweeper had
been relying on: overlap was the only thing that let a backlog exceed the
50-batch-per-call cap inside one 60-second tick. With the guard, a sweep that
spent its whole budget went idle for the rest of the interval, so a large backlog
drained far slower exactly when retention matters most.
The timer is now a chained setTimeout rather than an interval. `deleteInBatches`
reports whether it exhausted its batch budget, `prune()` returns
`{ deleted, saturated }`, and a saturated sweep is rescheduled immediately. The
connection gate hands a freed slot to the longest waiter, so one serial sweeper
looping back to back still parks a single statement ahead of a worker claim: claim
latency keeps the value the guard bought while the maximum drain rate returns to
what it was before. The loop is self-limiting and stops once the backlog clears.
A sweep that has not settled a full interval after it started now logs
`orca_push_prune_overdue` with its target. Admission waits have no timeout, so a
lost slot release could previously wedge retention permanently and silently.
Chaining makes the overlap guard structural, so there is no flag to scope. The two
single-DELETE sweeps state through `unbatchedSweep` that they have no batch budget
to exhaust, which keeps the immediate-resume path readable as delivery-only.
Co-Authored-By: Claude <[email protected]>
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
Reviewed the delta since the prior pullfrog review at ceae8b5 (commit 1155e3f):
- Chained sweep scheduling —
prune()incloud/apps/push/src/push-background.tsreschedules viasetTimeoutafter each completion instead of a fixedsetInterval, so a sweep can never overlap itself and a saturated one resumes immediately instead of idling out the rest of the interval. - Saturation signal —
DurablePushStore.prune()anddeleteInBatches()returnPushPruneSweep { deleted, saturated }, withsaturatedtrue only when a table's 50-batch budget is exhausted on a full final batch.prune()OR-saturates across all four tables, so a backlog on any retention table keeps the drain going while empty tables return immediately. - Overdue watchdog — each sweep arms an
intervalMstimer that logsorca_push_prune_overdueif the sweep has not settled, surfacing an untimed admission wait that would otherwise stall retention silently. - Regression tests — the push-background suite was rewritten for the chained model (immediate resume on saturation, one-statement claim delay during a continuous drain, overdue reporting, failure recovery) and the claim tests assert the new return shape.
The chained chain catches rejections and still reschedules, and stop() sets stopped before clearing timers, so an in-flight sweep's .then won't reschedule after shutdown.
ℹ️ PR description predates the second commit
The "What Changed" and trade-off sections still describe the first commit's behavior ("skips timer ticks … the next scheduled tick runs normally" and "after a long sweep finishes, the next sweep waits for its next scheduled tick"). Commit 1155e3f deliberately removes that idle-after-saturated wait, so the description understates the fix. A one-line refresh would keep reviewers and future archaeology from being misled.
Technical details
# PR description is stale relative to `1155e3f`
## Affected sites
- PR body "What Changed" (`Each existing pruner now skips timer ticks…`) and "Negative user-facing trade-off" (`After a long sweep finishes, the next sweep waits for its next scheduled tick`) — both describe the `setInterval` + `running` guard from `ceae8b5`, not the chained scheduler now in `cloud/apps/push/src/push-background.ts`.
## Required outcome
- Description matches shipped behavior: chained reschedule, immediate resume while `saturated`, and the `orca_push_prune_overdue` watchdog.
## Open questions for the human (optional)
- None; drives no code change.DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

ELI5
When cleanup is still busy, its next alarm should not stack another cleanup job ahead of notifications — the current job should finish first. But cleanup also must not take a coffee break when there is still a pile of records waiting. So cleanup now runs one job at a time and, if a job hit its per-job work limit with rows still left, it starts the next job right away instead of waiting for the next alarm.
What Changed
Before: retention cleanup ran on a one-minute timer. A slow sweep was still running when the next minute arrived, so a second, third and tenth sweep piled on. Each parked a
DELETEin the database admission queue ahead of the notification worker's nextclaim(), and the worker waited up to 40 seconds to pick up a notification.The first attempt at this fix was a guard that made a timer tick return early while the previous sweep was still in flight. That fixed the delay but introduced a new problem: a sweep deletes at most 50 batches per call, and the overlapping sweeps had been the only reason a large backlog could exceed that cap within one minute. With the guard, a sweep that used its whole budget went idle for the rest of the minute, so a big backlog drained much slower — exactly when retention matters most.
After: cleanup is scheduled by a chained timer instead of a repeating one, so the next sweep is only scheduled once the current one finishes and sweeps can never overlap. A sweep now reports whether it ran out of batch budget with rows still matching. If it did, the next sweep starts immediately rather than waiting out the minute. The loop stops on its own as soon as the backlog clears.
The notification worker still only ever waits behind one cleanup statement. The admission gate hands a freed connection slot to the longest waiter, so a single sweeper looping back to back parks exactly one statement ahead of a
claim()— no matter how long the drain runs.A sweep that has not finished a full interval after it started now logs
orca_push_prune_overduewith the target it was sweeping, alongside the existingorca_push_prune_failed.Why
One sweep can run 200 SQL statements, so the five-second per-statement limit does not stop sweeps from overlapping; only the scheduler can. A chained timer is the smallest change that makes overlap impossible by construction rather than by a flag, and it gives the saturation signal somewhere to go:
schedule(0)on a saturated sweep restores the old maximum drain rate without restoring the queue pileup, because the throughput came from the sweeper continuing to work, not from several sweepers working at once.Alternatives considered:
while (saturated). Rejected: anawaitloop only yields microtasks, so a sweep that resolves without real I/O could starve the event loop. Rescheduling through a timer guarantees a return to the event loop between sweeps.Linked Issue
Fixes #23000
Visual Proof
N/A — headless cloud maintenance scheduler; no UI changes.
Performance proof
The regression test uses the production scheduler, delivery store, and background connection gate with controlled SQL responses, fake time, pool size 2 (admission capacity 1), and four-second full deletion batches. Measured over ten one-minute ticks:
Claim queue delay drops from ten statements to one, and the saturated drain no longer stops after one sweep per tick. These are fixture numbers from controlled SQL responses under fake time, not a live PostgreSQL benchmark or a claim about typical production latency.
Testing
resumes a saturated sweep at once rather than waiting out the interval: three saturated sweeps run within milliseconds of the first tick, then the sweeper returns to its normal cadence once the backlog clears.reports a sweep that is still running a full interval after it started, covering the neworca_push_prune_overduelog and that it fires once per sweep.durable-push-claim.test.tsto assert the new{ deleted, saturated }result, which covers both budget exhaustion and a drained predicate against real SQLite.tsc -p cloud/apps/push/tsconfig.json --noEmit) passes.cloud/**is excluded from the rootoxlintandoxfmtconfigs, so the package's own TypeScript check is the applicable gate.pnpm --dir cloud/apps/push exec vitest run src/push-background.test.ts src/durable-push-claim.test.ts.Review
Merge risk: low. The scheduler is a chained
setTimeoutwith the sameunrefand the same single teardown point as the interval it replaces; stopping sets a flag so an in-flight sweep cannot reschedule after shutdown. Review covered promise rejection, stop during a sweep, independent per-store cadence, connection admission ordering, and expiry enforcement.No known negative user-facing trade-off. The earlier revision of this PR traded slower retention for lower delivery latency; this revision keeps the latency win and returns the drain rate to its pre-PR maximum, so neither property regresses.
Residual behaviour worth knowing, neither of them regressions:
DELETEsweeps that is bounded by the five-second statement timeout.Notes
No retention ages, SQL predicates, schemas, provider calls, authentication checks, or wire contracts change.
prune()anddeleteInBatchesnow return{ deleted, saturated }instead of a row count; both are internal to the push app and every caller is updated in this PR. Node timers are platform-neutral; SSH and folder workspace identities are unaffected.The guard is kept for all three pruners. Chaining makes non-overlap structural rather than a per-pruner flag, so there is nothing extra to carry for the two sweeps that could never overlap anyway;
unbatchedSweepmarks them as having no batch budget, which keeps the immediate-resume path readable as delivery-only.Agent skill upstream boundary
Checklist