Skip to content

fix(billing): stop the plan-limit prune looping forever on a zero batch - #11079

Open
ayobamiseun wants to merge 1 commit into
koala73:mainfrom
ayobamiseun:fix/plan-limit-prune-zero-batch
Open

ayobamiseun wants to merge 1 commit into
koala73:mainfrom
ayobamiseun:fix/plan-limit-prune-zero-batch

Conversation

@ayobamiseun

@ayobamiseun ayobamiseun commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

Summary

pruneApiPlanLimitData takes its batch size straight from the caller with no floor:

const batch = args.limit ?? PRUNE_BATCH;

With limit: 0 (which v.optional(v.number()) accepts), both .take(0) calls return nothing, staleNotices.length >= batch reads 0 >= 0 as a full batch, and the mutation reschedules itself at runAfter(0) with the same zero. That is an unbounded chain of scheduled executions that deletes nothing, while the 90-day retention backlog is never touched.

limit is operator-callable by design — its own argument comment says it exists so tests can drive the drain-over-multiple-runs behaviour — and zero is a natural value to type when probing that. The cron passes {}, so only an operator reaches it.

Why this is a back-port rather than a new idea

The guard already exists, word for word, in both prunes that were modelled on this one, and in a third:

File Has the floor
convex/userPreferences.ts yes, with the same comment
convex/intelHistory.ts yes, and its header says it is "Modelled on pruneApiPlanLimitData"
convex/agentFeedback.ts yes
convex/apiPlanLimitNotices.ts no

The fix was applied to every derivative and never back-ported to the original they copied. This adds the same three lines, byte-identical to the siblings.

I deliberately did not also clamp retentionMs: convex/intelHistory.ts explains why that override stays shortening-capable, and the same reasoning holds here.

Tests

convex/__tests__/apiPlanLimitPrune.test.ts gains a table case over 0, -5, 0.5, NaN and Infinity. Each must delete something and the reschedule chain must terminate, driven the same way the existing backlog test drives it.

Red proof: with convex/apiPlanLimitNotices.ts reverted to its main version, all five fail.

Verification

  • apiPlanLimitPrune, intelHistory, userPreferences, agentFeedback convex suites — 229 pass, 0 fail
  • npm run typecheck:api, Biome, git diff --check — clean

Summary by CodeRabbit

  • Bug Fixes
    • Improved cleanup of aged API plan limit notices when batch limits are missing, invalid, or unusually small. Cleanup now uses a safe batch size and can continue across multiple batches, helping ensure older notices are removed.

pruneApiPlanLimitData took its batch size straight from the caller with
no floor. `take(0)` returns nothing, so `staleNotices.length >= batch`
reads 0 >= 0 as a full batch and the mutation reschedules itself at
runAfter(0) with the same zero. The result is an unbounded chain of
scheduled executions that deletes nothing while the retention backlog
is never touched.

`limit` is operator-callable by design — its own arg comment says it
exists so tests can drive the drain — and 0 is a natural value to type
when probing that. The cron passes {}, so only an operator trips it.

The guard already exists verbatim in both prunes that were modelled on
this one (convex/userPreferences.ts, convex/intelHistory.ts, whose
header names this function as its model) and in convex/agentFeedback.ts.
It was applied to every derivative and never back-ported to the
original. This adds the same three lines.

Tests: zero, negative, fractional, NaN and Infinity each make progress
and terminate. Red proof: with the handler reverted, all five fail.
@vercel

vercel Bot commented Nov 21, 2026

Copy link
Copy Markdown

@ayobamiseun is attempting to deploy a commit to the World Monitor Team on Vercel.

A member of the Team first needs to authorize it.

@strix-security

strix-security Bot commented Nov 21, 2026 •

Copy link
Copy Markdown

Strix Security Review

✅ No open security findings.

PR summary: Fixes the plan-limit retention prune so a caller-supplied batch size of zero (or a negative, fractional, NaN or infinite value) can no longer make the mutation reschedule itself forever without deleting anything; the batch is floored at one and non-finite values fall back to the default.

Review summary

The change adds a lower bound and a non-finite fallback to the caller-supplied batch size in pruneApiPlanLimitData, plus a table-driven test over zero, negative, fractional, NaN and infinite values. I traced the mutation end to end: both delete legs use the single bounded batch variable, each is scoped to rows older than the retention cutoff (current:false on notices, computedAt on rollups), and the self-reschedule carries the already-normalized batch forward. With the floor in place a reschedule implies at least one document was deleted in that run, so the drain chain terminates and no active or in-window record can be selected. The mutation is an internalMutation reached only by the daily cron with empty arguments and by its own scheduler call; no public query, mutation, HTTP route or MCP tool forwards a request-derived limit, now or retentionMs to it, so the fixed loop and the retention override remain operator-only. No security issue found in the changed code.

Ruled out (1)
  • Does the changed prune handler resolve a user identity, so a dev-only auth fallback in the module it imports could be reached through it?
    The changed handler is an internal mutation that only reads `args`, runs two indexed age-bounded queries and reschedules; the identity helper is called only by two public handlers in the same file that the diff does not touch.

Review 1 on this PR · fbb34a1 · requested Nov 21 09:18 UTC when the PR was opened


Reviewed by Strix
Re-run review · Configure security review settings · Try a deeper review with @strix-security /deep

@greptile-apps

greptile-apps Bot commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 5/5

[Low impact] The PR appears safe to merge.

Summary

pruneApiPlanLimitData now turns finite limits into whole numbers of at least one. Non-finite limits use the existing default.

  • The plan-limit prune always uses a usable batch size.

Reviews (1) · Last reviewed commit: "fix(billing): stop the plan-limit prune ..." · Reviewed by Greptile

@coderabbitai

coderabbitai Bot commented Nov 21, 2026 •

Copy link
Copy Markdown

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

pruneApiPlanLimitData now normalizes finite requested limits and uses PRUNE_BATCH for absent or non-finite limits. Regression tests cover zero, negative, fractional, NaN, and infinite limits.

Changes: API plan limit pruning

Layer / File(s) Summary
Normalize limits and verify pruning
convex/apiPlanLimitNotices.ts, convex/__tests__/apiPlanLimitPrune.test.ts
The mutation floors finite limits, clamps them to at least 1, and uses PRUNE_BATCH for absent or non-finite limits. Tests verify pruning completes for five nonstandard values.

Estimated code review effort: 2 (Simple) | ~10 minutes

Change: Bug fix

Suggested reviewers: koala73

Merge Risk: Minimal · up to fbb34

The change prevents the plan-limit prune job from looping without deleting data when given a zero or otherwise unusual batch size. Regression tests cover these cases, and no merge-blocking risk was identified.

Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title names the primary change: adding a floor to the batch size so the plan-limit prune no longer loops forever on a zero batch. The raw summary confirms the batch-size clamp in convex/apiPlanLim…
Description check Passed The description follows the repository template in its key content. It has a Summary that explains the bug and fix, and it covers the guard back-port rationale, the tests added, red-proof verification…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Title check

Explanation

The title names the primary change: adding a floor to the batch size so the plan-limit prune no longer loops forever on a zero batch. The raw summary confirms the batch-size clamp in convex/apiPlanLimitNotices.ts and the new zero-batch regression tests. The title is specific, follows a conventional format, and matches the PR objectives.

Full details: Description check

Explanation

The description follows the repository template in its key content. It has a Summary that explains the bug and fix, and it covers the guard back-port rationale, the tests added, red-proof verification, and the typecheck, Biome, and diff checks. The template's Type of change, Affected areas, and Checklist sections are not filled in. The Documentation Alignment and Bundle budget sections are not addressed, but they appear to be optional for this change. The Type of change and Checklist gaps are minor.

Finishing Touches

Generate unit tests (beta)

  • Create a new PR
Fix failing CI checks

  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

Recent review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: ca702d68-b6fa-4805-93ba-c518ea792388
Commits

Reviewing files that changed from the base of the PR and between f762da2 and fbb34a1.

Files selected for processing: 2

  • convex/__tests__/apiPlanLimitPrune.test.ts
  • convex/apiPlanLimitNotices.ts

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

@auditbenchaibot auditbenchaibot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Open in Audit Bench Ai

🤖 Automated review by Audit Bench Ai, not a personal review. It was posted through the GitHub account connected to Audit Bench Ai. Install the Audit Bench Ai GitHub App to have reviews posted by a separate bot account.

No actionable comments were generated in this review. 🎉

Merge risk: ⚪ Minimal · up to fbb34a1

The change adds defensive input validation mirroring existing patterns across other prune tasks, accompanied by comprehensive test coverage without changing default cron behavior.

Merge readiness: ⛔ Not ready to merge

Pre-merge checks: ✅ 9 · ❌ 1

❌ Failed checks: 1 error

Check name Status Explanation Resolution
CI checks ❌ 1 of 59 failing: Vercel. Open the failing runs on GitHub and fix them before merging.
✅ Passed checks: 9 passed
Check name Status Explanation
Merge conflicts ✅ Merges cleanly into main.
Secrets ✅ No keys, passwords or tokens in the changed code.
Blocking issues ✅ No critical or high-severity issues in the changed lines.
Tests ✅ Tests were changed alongside the code.
PR size ✅ 43 lines changed.
Title check ✅ The title clearly states that it fixes an infinite loop on zero batch sizes during plan-limit pruning.
Description check ✅ The description provides a thorough explanation of the bug, the fix, sibling implementations, and test coverage.
Linked issues check ✅ No issue links were referenced in the description.
Out of scope changes check ✅ All changes are strictly focused on sanitizing the prune limit argument and validating it with tests.
📝 Walkthrough

This pull request fixes an issue in pruneApiPlanLimitData where passing an invalid or zero batch limit caused an infinite rescheduling loop without deleting any records. It adds normalization to enforce a minimum batch size of 1 and falls back to the default prune batch for non-finite values, matching existing sibling cleanup routines. Tests have been added to verify that various edge-case limits successfully make progress and terminate.

File Changes
convex/__tests__/apiPlanLimitPrune.test.ts Adds parameterized tests ensuring invalid and non-positive limit arguments allow the prune to make progress and terminate.
convex/apiPlanLimitNotices.ts Sanitizes and enforces a minimum batch size of 1 for requested prune limits to prevent infinite rescheduling loops.
ℹ️ Review info
  • Commit: fbb34a1
  • Verdict: ✅ Pass
  • Findings: none
  • Review: local checks plus AI review of the changed lines
  • Scope: Reviewed 2/2 selected files (of 2 total): 2 reviewed by AI, 0 from cache, 0 passed local checks with nothing risky enough to send to AI. Found 0 finding(s), No secrets found.

💬 Reply to any inline comment and Audit Bench Ai will recheck that code and answer in the thread. Mention @auditbench in the conversation to ask about the whole PR.

🛠️ Open the full report and fix with AI

Thanks for using Audit Bench Ai! Free pull request reviews for open source: paste any public PR at auditbenchai.com/scan.

Reviewed by Audit Bench Ai · Build fast. Check what ships. · Review any public PR free

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants