Skip to content

perf(push): keep retention sweeps from overlapping without slowing the drain - #23001

Merged
nwparker merged 2 commits into
mainfrom
nwparker/perf-09-25-push-prune-overlap
Sep 27, 2026
Merged

nwparker merged 2 commits into
mainfrom
nwparker/perf-09-25-push-prune-overlap

Conversation

@nwparker

@nwparker nwparker commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

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 DELETE in the database admission queue ahead of the notification worker's next claim(), 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_overdue with the target it was sweeping, alongside the existing orca_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:

  • Keep the early-return guard alone. Rejected: it trades a delivery-latency bug for a retention-durability bug. Expired records linger longer and a backlog drains slower, which is a real user-visible regression, not a neutral one.
  • Raise the 50-batch cap. Rejected: the cap is what keeps a single sweep's statement count bounded and its lock footprint small. A saturated sweep resuming immediately achieves the same throughput while each statement stays bounded.
  • Loop inside the sweep with while (saturated). Rejected: an await loop 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.
  • Add an admission timeout so a stuck sweep cannot wedge retention. Deferred: a timeout changes what a failed sweep means for correctness. The overdue log makes the condition visible first, which is what was actually missing.

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:

Measurement Before this PR's branch point Guard only (first attempt) This PR
Cleanup statements a notification claim waits behind 10 1 1
Concurrent delivery sweeps 10 1 1
Sweeps completed while a backlog remains unbounded 1 per tick back to back until drained

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

  • Automated regression tests added and updated.
  • Rewrote the overlap test so it asserts the invariant that actually matters — exactly one cleanup statement completes while a claim waits, and at most one sweep is ever in flight — instead of a total sweep count, which had encoded the reduced drain rate as intended behaviour.
  • Added 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.
  • Added reports a sweep that is still running a full interval after it started, covering the new orca_push_prune_overdue log and that it fires once per sweep.
  • Updated durable-push-claim.test.ts to assert the new { deleted, saturated } result, which covers both budget exhaustion and a drained predicate against real SQLite.
  • Full push suite: 155 tests pass, 10 PostgreSQL-dependent tests skip, across 31 files (~0.7s).
  • Push package typecheck (tsc -p cloud/apps/push/tsconfig.json --noEmit) passes. cloud/** is excluded from the root oxlint and oxfmt configs, so the package's own TypeScript check is the applicable gate.
  • Reproduce: pnpm --dir cloud/apps/push exec vitest run src/push-background.test.ts src/durable-push-claim.test.ts.
  • macOS Node tests; no live PostgreSQL, Windows/Linux run, app launch, or cloud deployment.

Review

Merge risk: low. The scheduler is a chained setTimeout with the same unref and 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:

  • Each store's cadence is now "one interval after the previous sweep finished" rather than a fixed wall-clock period, so it drifts by the sweep's duration. For the two single-DELETE sweeps that is bounded by the five-second statement timeout.
  • Shutdown still does not join a running sweep. Unchanged by this PR.

Notes

No retention ages, SQL predicates, schemas, provider calls, authentication checks, or wire contracts change. prune() and deleteInBatches now 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; unbatchedSweep marks them as having no batch budget, which keeps the immediate-resume path readable as delivery-only.

Agent skill upstream boundary

  • Not applicable; no agent skill source changed.

Checklist

  • Small focused change with before/after, mechanism, ELI5, proof, risk, and alternatives.
  • Visual proof marked N/A with reason.
  • Reviewed concurrency, cleanup, compatibility, and expiry behavior.
  • Full cloud/platform matrix; targeted checks above passed locally.

@nwparker
nwparker requested a review from Jinwoo-H as a code owner September 26, 2026 02:21
@coderabbitai

coderabbitai Bot commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

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 configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 6205c9ce-10b1-48aa-ab26-fecc288c111c

📥 Commits

Reviewing files that changed from the base of the PR and between ceae8b5 and 1155e3f.

📒 Files selected for processing (4)
  • cloud/apps/push/src/durable-push-claim.test.ts
  • cloud/apps/push/src/durable-push-store.ts
  • cloud/apps/push/src/push-background.test.ts
  • cloud/apps/push/src/push-background.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 7 remain after this review.


📝 Walkthrough

Walkthrough

DurablePushStore.prune() now returns a deletion count and a saturation flag. The background worker schedules another sweep after the current sweep settles. It schedules saturated sweeps immediately and other sweeps after an interval. Failures trigger a warning and a retry after an interval. The worker also warns when a sweep remains pending for an interval and stops future scheduling during shutdown. Tests cover sweep cadence, failure recovery, backlog draining during notification claims, and validation mode.

Priority: ➖ Normal

Merge Risk: ⚪ Minimal · up to 1155e

No actionable merge-blocking risk is established; the slower cleanup described for this change is an acknowledged trade-off.

Security Architecture Review

Security architecture risk: 🔵 Low · up to 1155e

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
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — Authenticated senders can contribute rows that eventually require retention cleanup, but cannot directly trigger a prune call. A sustained saturated backlog can keep one background operation active per instance; aggregate database exposure depends on deployment capacity not shown here.

Trust Boundaries and Controls

  • observed — The request path retains bearer-session, rate-limit, device-ownership, and store quota checks. The changed prune result does not confer deletion authority on those callers.

Resilience and Maintainability Implications

  • observed — Next-run scheduling follows completion or failure, preserving single-flight behavior within one scheduler instance. Failed sweeps retry after an interval, while an overdue sweep emits a warning.

Hardening Proposals

  • proposed — Monitor sustained saturated sweeps and shared database contention after rollout; if fleet-wide contention appears, consider a bounded immediate-drain budget or backoff without restoring overlapping sweeps.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 20.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 5 functions across 4 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Issue #23000 is closed and supplies historical context only. No active linked-issue coding requirements apply. The reviewed changes remain related to that context: they chain retention sweeps, report …
Out of Scope Changes check ✅ Passed The production changes update push retention scheduling and pruning results. The tests cover sweep saturation, overdue logging, retry behavior, claim contention, shutdown, and validation mode. These c…
Title check ✅ Passed The title clearly summarizes the main change: retention sweeps do not overlap, and saturated sweeps continue without slowing backlog draining.
Description check ✅ Passed The description is detailed and covers the required sections, including the change, rationale, linked issue, visual proof, testing, review, and checklist. It also states the limits of the testing perf…
  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR

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.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ 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() in cloud/apps/push/src/push-background.ts now skips a setInterval tick while the prior sweep is still in flight (running flag), 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.ts covers the overlap guard, failure recovery, validation mode, and an integration claim-queue-delay test that drives the real DurablePushStore through reserveRequestConnection.

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.

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@nwparker nwparker added the perf:high-impact-review Large measured gain in a specific workload; review trade-offs before merging. label Sep 27, 2026
…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]>
@nwparker nwparker changed the title perf(push): prevent overlapping retention sweeps [trade-off] perf(push): keep retention sweeps from overlapping without slowing the drain Sep 27, 2026

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ No new issues found.

Reviewed changes

Reviewed the delta since the prior pullfrog review at ceae8b5 (commit 1155e3f):

  • Chained sweep scheduling — prune() in cloud/apps/push/src/push-background.ts reschedules via setTimeout after each completion instead of a fixed setInterval, 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() and deleteInBatches() return PushPruneSweep { deleted, saturated }, with saturated true 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 intervalMs timer that logs orca_push_prune_overdue if 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.

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@nwparker
nwparker merged commit da95225 into main Sep 27, 2026
25 checks passed
@nwparker
nwparker deleted the nwparker/perf-09-25-push-prune-overlap branch September 27, 2026 03:40
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

perf:high-impact-review Large measured gain in a specific workload; review trade-offs before merging.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Push retention sweeps can overlap and delay notification claims

1 participant