Skip to content

fix(chat): refund a quota unit when a send's file window closes before its save - #842

Open
prisis wants to merge 1 commit into
mainfrom
t3/quota-refund-on-window-expiry
Open

prisis wants to merge 1 commit into
mainfrom
t3/quota-refund-on-window-expiry

Conversation

@prisis

@prisis prisis commented Nov 18, 2026

Copy link
Copy Markdown
Member

Summary

Follow-up to #831. A text send is charged one daily unit before its save. When the file attach's safe window closed between the charge and the save, the save was refused but the unit stayed charged. This gives the unit back on that refusal, for /chat/start and /chat/edit.

Changes

  • lib/rate-limiter-mutations.ts: refundLimitUnits writes the fixed window's remaining count back, capped at its rate, to the row the limiter reads (neore:<key>:<identifier>).
  • chat/daily-charge.ts: refundDailyCharge also releases a keyed charge's claim, so the retry is charged normally instead of being found already charged.
  • chat/lib/daily-limit.ts: refundDailyLimit, the send-side helper. Admins and tiers without the kind give nothing back.
  • chat/http.ts: the send's charge records a refund; the window refusal runs it before answering 409.

Testing

  • chat/daily-refund.test.ts: refund restores the unit; capped at the rate; a keyed refund frees the claim so a retry is charged once.
  • Chat, agent and lib suites pass (292 files, 3823 tests); types and lint pass.

Not covered

  • The refund is best-effort: if the refund mutation itself fails, the unit stays charged (logged by the caller's error path).

🤖 Generated with Claude Code

…fore its save

A text send is charged before its save. When the file attach's window closed in between, the save was refused and the unit stayed charged. The charge's unit is now refunded on that refusal, for /chat/start and /chat/edit.

- lib/rate-limiter-mutations: refundLimitUnits writes the window's remaining count back, capped at its rate, to the row the limiter reads.
- chat/daily-charge: refundDailyCharge also releases a keyed charge's claim, so the send's retry is charged normally.
- chat/lib/daily-limit: refundDailyLimit, the send-side helper; admins and tiers without the kind give nothing back.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
@qodo-code-review

Copy link
Copy Markdown

ⓘ Qodo did not review this PR because this workspace reached its daily trial limit of 100 reviews. Reviews start again at 00:00 UTC. Choose a plan to continue now.

@coderabbitai

coderabbitai Bot commented Nov 18, 2026

Copy link
Copy Markdown

Warning

Review limit reached

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Next included review available in 55 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available.

Learn how review limits work.

Review configuration:

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 7b623c0 and 393b3e3.

Files ignored due to path filters: 5

  • backend/lunora/_generated/advisor-procedures.json is excluded by !**/_generated/**, !backend/lunora/_generated/**
  • backend/lunora/_generated/companion/advisor-procedures.json is excluded by !**/_generated/**, !backend/lunora/_generated/**
  • backend/lunora/_generated/companion/src/worker.ts is excluded by !**/_generated/**, !backend/lunora/_generated/**
  • backend/lunora/_generated/functions.ts is excluded by !**/_generated/**, !backend/lunora/_generated/**
  • backend/lunora/_generated/internal.ts is excluded by !**/_generated/**, !backend/lunora/_generated/**
Files selected for processing: 5

  • backend/lunora/chat/daily-charge.ts
  • backend/lunora/chat/daily-refund.test.ts
  • backend/lunora/chat/http.ts
  • backend/lunora/chat/lib/daily-limit.ts
  • backend/lunora/lib/rate-limiter-mutations.ts
  • 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

@github-actions github-actions Bot added the size:L Size of the change, tests and generated files excluded. label Nov 18, 2026
@github-actions

Copy link
Copy Markdown

Thank you for following the naming conventions! 🙏

@github-actions github-actions Bot added the vouch:trusted PR author is a collaborator, a bot or on the VOUCHED list. label Nov 18, 2026
@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Nov 18, 2026 •

Copy link
Copy Markdown

PR Summary by Qodo

Refund chat quota when a file-attach window expires before save

🐞 Bug fix 🧪 Tests 🕐 20-40 Minutes

Grey Divider

AI Description

• Refund a text quota unit when file-window expiry prevents a charged start or edit from saving.
• Release keyed charge claims so a successful retry is charged normally.
• Add refund tests and register the new internal mutation in generated metadata.
Merge Risk 🟡 Medium

Blast radius 🟡 Medium 💥 2 capabilities

  • 2 affected capabilities within one bounded functional scope: chat_generation_quota.
  • The changed path charges a text send, catches attachment-window expiration, and refunds the same daily text limiter before returning a retryable response.
  • The generated mutation and limiter row are implementation hops of this single send-generation behavior, not independent capabilities.
  • The edit endpoint independently charges a text-generation unit and invokes the same refund behavior when the attachment window closes before saving the edited sibling.
  • This is a distinct user operation but remains within the same bounded chat-generation integration.
  • The send path is charged before the save and now conditionally restores the same daily text quota when the attach window expires; the affected outcome is whether a user can retry and how many generations the daily quota permits.
  • The edit path uses the same text quota but has its own save-and-regenerate outcome; an erroneous refund changes whether later edits or sends are allowed.
Behavioral complexity 🔴 High 🧩 Coordinated invariants, Concurrent ordering

  • Before: a charge either remained applied or, for a refused charge, released its claim before returning failure; attachment-window refusal occurred before the quota charge in the relevant send/edit paths.
  • After: a successful charge can be followed by a refusal, requiring two persistent states—the daily limiter units and, for keyed sends, the idempotency claim—to be restored consistently.
  • New correctness condition: claim release, limiter-row restoration, window rollover handling, and concurrent charge/refund operations must agree, and a failure in either half must not leave the user double-charged or over-credited.
  • The changed logic introduces a new cross-operation ordering and recovery protocol rather than merely reusing an existing mapping or validation helper.
Potential damage 🟡 Medium 🩹 Recoverable

  • If the claim is released but the limiter refund does not complete, a keyed send retry can be charged again while the original unit remains consumed, and an edit can lose a unit without producing a saved edit.
  • These are incorrect quota/accounting outcomes and temporary loss of generation capacity, not irreversible user-data loss.
  • Code rollback stops new divergence but does not automatically restore already-consumed limiter rows or reinstate claims; recovery may require a subsequent successful retry or manual/reset-based quota repair.
  • The consequences are grouped because both operations affect the same bounded chat-generation quota scope.
  • Usually recoverable through a successful retry or the next daily-window reset; a failed refund after claim release may require manual limiter/claim repair because no reachable automatic repair worker was established.
  • Reverting code does not repair already-written limiter state.
Assessed commit 393b3e3
Diagram

graph TD
    A["Start or edit"] --> B["Daily charge"] --> C{"Window valid?"}
    C -->|yes| D["Save message"]
    C -->|no| E["Refund helper"] --> F["Refund mutation"] --> G["Quota row"] --> H["Conflict 409"]
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Charge only after saving
  • ➕ Avoids compensating for file-window expiry.
  • ➖ A quota refusal could occur after the message is saved, requiring a different save-and-charge transaction design.

Recommendation: Keep the targeted refund: charging before save preserves quota enforcement, while compensation handles this specific intervening refusal. The remaining trade-off is best-effort behavior if the refund mutation fails.

Files changed (10) +224 / -11

Bug fix (4) +109 / -10
daily-charge.tsRefund charges and release keyed claims +19/-1

Refund charges and release keyed claims

• Introduces an internal mutation that releases an optional keyed charge claim and restores the charged units in the same mutation. Releasing the claim lets a retry take a fresh charge.

backend/lunora/chat/daily-charge.ts

http.tsRefund expired-window start and edit sends +38/-9

Refund expired-window start and edit sends

• Records a refund callback after a successful text charge in both routes. On file-attach window expiry before save, each path runs the callback before returning the retryable 409 response.

backend/lunora/chat/http.ts

daily-limit.tsAdd a send-side daily quota refund helper +29/-0

Add a send-side daily quota refund helper

• Resolves the user's quota key and invokes the refund mutation for one unit, passing through an optional keyed charge. Admins and tiers without the requested kind are skipped.

backend/lunora/chat/lib/daily-limit.ts

rate-limiter-mutations.tsRestore units in the fixed-window limiter row +23/-0

Restore units in the fixed-window limiter row

• Adds a helper that reads the limiter's stored window, increases its remaining units, and caps them at the configured rate. It writes to the same encoded row used by the limiter.

backend/lunora/lib/rate-limiter-mutations.ts

Tests (1) +58 / -0
daily-refund.test.tsTest quota restoration and keyed retries +58/-0

Test quota restoration and keyed retries

• Tests restoration of an unkeyed unit, capping at the configured daily rate, and charging again after a keyed refund.

backend/lunora/chat/daily-refund.test.ts

Other (5) +57 / -1
advisor-procedures.jsonRegister the refund mutation in advisor metadata +25/-0

Register the refund mutation in advisor metadata

• Adds refundDailyCharge as an internal mutation in the generated procedure list.

backend/lunora/_generated/advisor-procedures.json

advisor-procedures.jsonSync companion advisor metadata +25/-0

Sync companion advisor metadata

• Adds the same internal refund mutation to the companion's generated procedure list.

backend/lunora/_generated/companion/advisor-procedures.json

worker.tsSync embedded companion procedure metadata +1/-1

Sync embedded companion procedure metadata

• The generated worker contains the companion procedure list, including refundDailyCharge. The supplied diff shows no textual hunk for this file.

backend/lunora/_generated/companion/src/worker.ts

functions.tsExpose refundDailyCharge through generated callers +4/-0

Expose refundDailyCharge through generated callers

• Adds the mutation to the function manifest, registered functions, typed caller, and caller implementation.

backend/lunora/_generated/functions.ts

internal.tsGenerate the internal refund reference +2/-0

Generate the internal refund reference

• Adds the typed internal API reference used to invoke refundDailyCharge from HTTP actions.

backend/lunora/_generated/internal.ts

@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (2)

Grey Divider


Action required

1. Overlapping retries can bypass daily quota 🐞 Bug
Description
refundDailyCharge releases the shared charge claim and restores a unit even when a newer attempt
has already passed chargeDailyLimitOnce by reusing that claim. If the original /chat/start
attempt runs past its two-minute lease, its replacement can pass the charge check without taking
another unit; the original can then hit its expired file window and refund the only charge while the
replacement saves successfully.
Code

backend/lunora/chat/daily-charge.ts[R124-128]

+        if (chargeKey !== undefined) {
+            await releaseClaim(ctx, DAILY_CHARGE_SCOPE, chargeKey);
+        }
+
+        await refundLimitUnits(ctx, { count, identifier, key });
Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
An expired `/chat/start` attempt can refund a keyed charge after a replacement attempt has reused that charge, allowing the replacement to save without consuming quota.
## Fix Focus Areas
- backend/lunora/chat/daily-charge.ts[98-131]
- backend/lunora/chat/http.ts[768-773]
- backend/lunora/chat/http.ts[1490-1513]
- backend/lunora/chat/start-claim.ts[231-263]
## Recommended Fix
Track ownership or reuse of the keyed charge atomically with its claim. Permit the original attempt to refund only if no successor has adopted that charge; if the charge has already been refunded, require a successor to take a new unit before saving. Preserve the ordinary failed-attempt path in which a subsequent retry is charged normally.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Remediation recommended

2. A failed refund turns a retryable 409 into a 500 🐞 Bug
Description
Both new refusal paths await the refund inside the catch with no guard: await charge.refund?.()
in runChatStart and await holder.refundCharge?.() in editMessageAttached. If the
refundDailyCharge mutation throws, that error replaces the window-expired error, so the client
gets a 500 instead of the attachWindowExpiredResponse() 409 that tells it to send again; on
/chat/edit the error also skips the chatLogger.error call in that catch, because
editMessageHttpAction only has try/finally.
Code

backend/lunora/chat/http.ts[R769-773]

+                // The window closed after the charge: the unit is given back, and the send is answered as a retryable conflict.
+                if (isAttachWindowExpired(error)) {
+                    await charge.refund?.();
+
+                    return attachWindowExpiredResponse();
Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The refund on an attach-window refusal is awaited unguarded inside the catch. A failing refund mutation replaces the retryable 409 with a 500, and on /chat/edit the failure is not logged.

## Fix Focus Areas
- backend/lunora/chat/http.ts[769-773]
- backend/lunora/chat/http.ts[2147-2150]

## Recommended Fix
Wrap each refund call in try/catch, e.g. `try { await charge.refund?.(); } catch (refundError) { chatLogger.error("Could not refund a refused send's quota unit:", refundError); }`, and then return `attachWindowExpiredResponse()` regardless. Alternatively, make `refundDailyLimit` itself never throw, matching `releaseStartClaim`/`releaseGuestSend`.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

Tip of the day
💡 Did you know, you can type 'qodo, fix this' on a finding and the fix lands right on your PR

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Qodo Logo

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

🔴 Large blast radius size:L Size of the change, tests and generated files excluded. vouch:trusted PR author is a collaborator, a bot or on the VOUCHED list.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant