Skip to content

fix: settle usage beyond available balance#477

Merged
chenyme merged 1 commit into
DEEIX-AI:devfrom
hrx114514x:agent/issue-471-billing
Jul 14, 2026
Merged

fix: settle usage beyond available balance#477
chenyme merged 1 commit into
DEEIX-AI:devfrom
hrx114514x:agent/issue-471-billing

Conversation

@hrx114514x

Copy link
Copy Markdown
Contributor

Summary

  • persist billable usage even when the final charge exceeds the available balance
  • allow usage and period-overage settlement to produce a negative balance
  • preserve reservation reconciliation and block later paid requests through the existing balance check

Fixes #471.

Root cause

The final settlement transactions returned ErrInsufficientBalance when the actual charge exceeded the remaining balance after reservation. That rolled back both the usage ledger and the balance update. The HTTP layer then treated settlement as failed and released the reservation, restoring the account to a usable balance even though the upstream request had already consumed tokens.

Changes

  • treat completed upstream usage as authoritative and settle the full amount in the existing account-row transaction
  • record negative balances instead of rolling back usage and balance transactions
  • apply the same behavior to usage billing and period-plan overage settlement
  • retain normal refunds when actual usage is lower than the reservation
  • add coverage for settlement without a reservation, settlement beyond a reservation, reservation refunds, free models, period overage debt, and rejection of later calls from a negative-balance account

No API, schema, configuration, or frontend changes are included.

Concurrency and behavior

The existing account row lock remains the serialization point for balance updates and period-credit recalculation. Requests that are already in flight can still complete and are charged in commit order, potentially increasing the negative balance; once a settlement records debt, subsequent paid-model access is rejected by the existing balance check.

This pull request intentionally does not add per-model maximum-cost estimation or change the prepaid amount configuration.

Testing

  • cd backend && go test ./...
  • cd backend && go test -race ./internal/infra/persistence/postgres/billing ./internal/application/billing
  • git diff --check

@hrx114514x
hrx114514x marked this pull request as ready for review July 14, 2026 03:19
@chenyme
chenyme self-requested a review July 14, 2026 03:22
@chenyme chenyme self-assigned this Jul 14, 2026
@chenyme
chenyme merged commit c5897bf into DEEIX-AI:dev Jul 14, 2026
18 checks passed
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.

[Bug]: 计费问题

2 participants