Skip to content

fix: repair usage-based deleted invoice runs - #4673

Merged
turip merged 2 commits into
mainfrom
feat/repair-api-deleted-invoice-lines
Jul 9, 2026
Merged

turip merged 2 commits into
mainfrom
feat/repair-api-deleted-invoice-lines

Conversation

@turip

@turip turip commented Jul 9, 2026 •

Copy link
Copy Markdown
Member

Overview

Soft delete charges that are belonging to deleted standard invoices. This corrects any inconsistencies before the usagebased delete was implemented.

Notes for reviewer

Summary by CodeRabbit

  • Bug Fixes
    • Added a corrective database migration to repair “usage-based realization runs” that could incorrectly remain active after related invoices were deleted.
    • Improved consistency of related billing records by properly marking affected runs, invoice lines, and gathering invoices as deleted and clearing stale references.
  • Tests
    • Added migration coverage to validate expected repair behavior across multiple invoice/run scenarios.

Greptile Summary

This PR adds a data repair for usage-based runs left active after invoice deletion. The main changes are:

  • New irreversible migration for affected zero-credit usage-based runs.
  • Cleanup of repaired runs, gathering lines, and empty gathering invoices.
  • Override tombstones for final realization charges.
  • Migration test coverage for repaired and ignored cases.

Confidence Score: 4/5

This is close, but the repair can still leave affected charges out of normal billing advancement.

  • The migration preserves the base intent field, but still marks the base charge row deleted.
  • Billing advancement paths can filter that row out before future usage-based runs are created.
  • The affected charges can stop billing after the repair runs.

tools/migrate/migrations/20260709132435_repair_usagebased_deleted_invoice_runs.up.sql

Important Files Changed

Filename Overview
tools/migrate/migrations/20260709132435_repair_usagebased_deleted_invoice_runs.up.sql Adds the repair migration, but the final base charge update can still hide repaired charges from normal billing advancement.
tools/migrate/repair_usagebased_deleted_invoice_runs_test.go Adds migration coverage for affected runs, ignored runs, override handling, and gathering cleanup.
tools/migrate/migrations/20260709132435_repair_usagebased_deleted_invoice_runs.down.sql Documents the data repair as intentionally irreversible.
tools/migrate/migrations/atlas.sum Updates the migration checksum for the new repair migration.

Fix All in Claude Code Fix All in Codex

Prompt To Fix All With AI
Fix the following 1 code review issue. Work through them one at a time, proposing concise fixes.

---

### Issue 1 of 1
tools/migrate/migrations/20260709132435_repair_usagebased_deleted_invoice_runs.up.sql:152-165
**Base Charge Still Hidden**

This update keeps `intent_deleted_at` unset on the base row, but it still sets `charge_usage_based.deleted_at` and `status = 'deleted'`. Subscription sync can use the base-intent filter to see the row, but the normal billing advancement discovery path filters out deleted rows and deleted statuses. After the migration repairs a final realization charge, future advancement can skip that charge and stop creating new usage-based runs or invoices for it, even though the subscription-owned base intent is meant to remain visible.

Reviews (2): Last reviewed commit: "test: cover usage-based deleted invoice ..." | Re-trigger Greptile

Greptile also left 1 inline comment on this PR.

Context used (3)

  • Context used - CLAUDE.md (source)
  • Context used - AGENTS.md (source)
  • Context used - api/spec/AGENTS.md (source)

@turip
turip requested a review from a team as a code owner July 9, 2026 11:36
@coderabbitai

coderabbitai Bot commented Jul 9, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Adds a transactional SQL repair migration for deleted usage-based invoice runs and a Go test that seeds multiple scenarios and checks the resulting deletions, overrides, and charge state.

Changes

Usage-based run repair migration

Layer / File(s) Summary
Select and mark affected runs
tools/migrate/migrations/20260709132435_repair_usagebased_deleted_invoice_runs.up.sql
Builds a temporary candidate set from deleted invoice lines and invoices, then soft-deletes matching usage-based runs and clears current realization pointers.
Invoice and override cleanup
tools/migrate/migrations/20260709132435_repair_usagebased_deleted_invoice_runs.up.sql
Soft-deletes gathering invoice lines and invoices, upserts charge usage-based overrides, and marks final realization charge rows deleted.
Irreversible down migration
tools/migrate/migrations/20260709132435_repair_usagebased_deleted_invoice_runs.down.sql
Adds a comment-only down migration marked as intentionally irreversible.
Migration test coverage
tools/migrate/repair_usagebased_deleted_invoice_runs_test.go
Loads the repair migration, seeds billing and usage-based scenarios, and verifies deletion, override, and status outcomes across cases.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Possibly related PRs

  • openmeterio/openmeter#4567: Touches the same usage-based override and deletion model, including charge_usage_based_overrides and related billing fields.
  • openmeterio/openmeter#4663: Covers the same usage-based deletion semantics around gathering-line handling and realization behavior.

Suggested labels: kind/bug

Suggested reviewers: tothandras, GAlexIHU

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
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.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly matches the main change: repairing usage-based deleted invoice runs.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/repair-api-deleted-invoice-lines

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.

@turip
turip force-pushed the feat/repair-api-deleted-invoice-lines branch from fd26c67 to e4542f3 Compare July 9, 2026 11:59
@turip turip added area/billing release-note/bug-fix Release note: Bug Fixes labels Jul 9, 2026

@coderabbitai coderabbitai 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.

🧹 Nitpick comments (1)
tools/migrate/migrations/20260709132435_repair_usagebased_deleted_invoice_runs.up.sql (1)

12-167: 🚀 Performance & Scalability | 🔵 Trivial

Heads-up on lock footprint for the prod run.

Everything's inside one BEGIN/COMMIT, which is exactly right for atomicity. Just flagging for the operational side: the billing_invoice_lines update joins on (namespace, charge_id) and the empty-invoice cleanup does a per-invoice NOT EXISTS scan. The affected set should be small, so this is likely a non-issue, but on large billing tables it's worth confirming there's index support for the charge_id lookups and running it during a low-traffic window to keep lock contention friendly. No code change needed.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@tools/migrate/migrations/20260709132435_repair_usagebased_deleted_invoice_runs.up.sql`
around lines 12 - 167, This is an operational review note rather than a code
defect: the migration in repair_usagebased_deleted_invoice_runs.up.sql already
has the right atomic BEGIN/COMMIT behavior, so no code changes are needed. Keep
the current logic in the migration, but if you touch the related
billing_invoice_lines or billing_invoices cleanup paths later, verify supporting
indexes for the charge_id/namespace lookups and consider running the migration
during a low-traffic window.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In
`@tools/migrate/migrations/20260709132435_repair_usagebased_deleted_invoice_runs.up.sql`:
- Around line 12-167: This is an operational review note rather than a code
defect: the migration in repair_usagebased_deleted_invoice_runs.up.sql already
has the right atomic BEGIN/COMMIT behavior, so no code changes are needed. Keep
the current logic in the migration, but if you touch the related
billing_invoice_lines or billing_invoices cleanup paths later, verify supporting
indexes for the charge_id/namespace lookups and consider running the migration
during a low-traffic window.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 1f4ffaf4-af0d-4922-b321-187f39e06e23

📥 Commits

Reviewing files that changed from the base of the PR and between fd26c67 and e4542f3.

⛔ Files ignored due to path filters (1)
  • tools/migrate/migrations/atlas.sum is excluded by !**/*.sum, !**/*.sum
📒 Files selected for processing (3)
  • tools/migrate/migrations/20260709132435_repair_usagebased_deleted_invoice_runs.down.sql
  • tools/migrate/migrations/20260709132435_repair_usagebased_deleted_invoice_runs.up.sql
  • tools/migrate/repair_usagebased_deleted_invoice_runs_test.go
✅ Files skipped from review due to trivial changes (1)
  • tools/migrate/migrations/20260709132435_repair_usagebased_deleted_invoice_runs.down.sql

@turip
turip merged commit 479e431 into main Jul 9, 2026
27 of 30 checks passed
@turip
turip deleted the feat/repair-api-deleted-invoice-lines branch July 9, 2026 12:15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants