Skip to content

fix(billing): make line engine lifecycle steps atomic - #5247

Merged
turip merged 4 commits into
mainfrom
feat/atomic-line-engine-steps
Oct 5, 2026
Merged

turip merged 4 commits into
mainfrom
feat/atomic-line-engine-steps

Conversation

@turip

@turip turip commented Oct 5, 2026 •

Copy link
Copy Markdown
Member

Overview

Line-engine lifecycle callbacks could commit earlier line or engine writes before a later callback returned a critical validation issue. This change runs each invoice-issued, payment-authorized, and payment-settled attempt in one billing-owned transaction across all live lines and engines.

Warning-only validation results still commit and are returned to the invoice. Critical validation issues roll back the line-engine writes before the retryable invoice failure is persisted, while system errors abort the operation. Direct-paid invoices run authorization and settlement in the same attempt.

The existing retry coverage remains for historical partial database state written before this atomicity guarantee, and the relevant billing documentation now describes the transaction boundary.

Notes for reviewer

  • Added unit and integration coverage for warning handling, rollback behavior, cross-engine attempts, direct-paid invoices, and recovery from historical partial state.
  • make test-nocache passes with 9156 tests and 9 skips.
  • Scoped fast lint and go vet pass for the affected billing code.

Summary by CodeRabbit

  • Bug Fixes
    • Invoice issuance and payment processing no longer retain partial charge or payment updates from an attempt interrupted by a critical validation issue or system error.
    • Validation warnings are preserved on the invoice while processing completes. Critical validation issues leave the invoice in a retryable failed state; system errors abort the operation.
    • Direct-paid transactions now save authorization and settlement together, so a settlement failure also rolls back authorization. Facts committed by earlier attempts remain available during retries.

RetriggerConfidence Score: 4/5

The transactional change has no newly identified defect, but the outstanding repository test-comment requirement must be satisfied before merging.

Fix All in Claude CodeFindings

  1. P2 Missing lifecycle test intent ▶
Fix with agent prompt
### Issue 1
test/credits/credit_then_invoice_retry_test.go:114-116
The new historical-booking subtest explains why it creates partial state, but does not include the concise `given`, `when`, and `then` intent comments required for non-trivial lifecycle subtests. The usage-based and credit-purchase historical-booking subtests follow the same pattern. This repository requirement must be satisfied before merging.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Summary

The PR makes invoice-issued and payment callbacks transactional across live lines and engines, preserving warning-only results while rolling back failed attempts. It also adds rollback and historical-retry coverage and updates billing documentation.

Diagram
%%{init: {'theme': 'neutral'}}%%
flowchart TD
  A[Start line-engine attempt] --> B[Run callbacks in billing transaction]
  B --> C{Result}
  C -->|Success or warnings| D[Commit and retain warnings]
  C -->|Critical validation issue| E[Roll back line-engine writes]
  E --> F[Persist retryable failed invoice state]
  C -->|System error| G[Roll back and abort operation]
Loading

Reviews (4) · Last reviewed commit: "chore: fix lo.Empty"

@turip
turip requested a review from a team as a code owner October 5, 2026 11:57
@coderabbitai

coderabbitai Bot commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

Note

Currently processing new changes in this PR. This may take a few minutes, please wait...

⚙️ Run configuration
  • Configuration used: Repository: openmeterio/openmeter/.coderabbit.yaml
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: c3db1b05-2453-4c84-a9e6-f393e0f9c138
📥 Commits

Reviewing files that changed from the base of the PR and between b54b405 and 670635f.

📒 Files selected for processing (1)
  • openmeter/billing/service/lineengine.go
 ______________________________________________________________
< Security by obscurity? I'm about to become very 'unobscure'. >
 --------------------------------------------------------------
  \
   \   \
        \ /\
        ( )
      .( o ).

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Repository: openmeterio/openmeter/.coderabbit.yaml
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 7287bfe1-00c1-4da4-a980-208f01aac680
📥 Commits

Reviewing files that changed from the base of the PR and between d0e0e7b and b54b405.

📒 Files selected for processing (1)
  • openmeter/billing/service/lineengine_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • openmeter/billing/service/lineengine_test.go

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


📝 Walkthrough

Walkthrough

Billing runs invoice and payment line-engine callbacks in transaction attempts. Warning-only validation results can commit, while critical validation issues and system errors roll back. Direct-paid authorization and settlement share an attempt. Tests cover rollback, retries, and historical partial state.

Changes

Billing transaction attempts

Layer / File(s) Summary
Transaction helper and result handling
openmeter/billing/service/lineengine.go, openmeter/billing/service/lineengine_test.go
A shared helper runs callbacks through a transaction. It returns warning-only validation results and propagates other errors. Tests cover callback outcomes and failures during savepoint, commit, and rollback.
Invoice and payment callback orchestration
openmeter/billing/service/stdinvoicestate.go, test/billing/lineengine_test.go
Invoice-issued and payment callbacks use a shared runner. Authorization and settlement run as ordered steps. Tests cover warning retention and system-error and critical-validation behavior.
Rollback, retry, and documented behavior
test/credits/credit_then_invoice_retry_test.go, openmeter/billing/README.md, openmeter/billing/charges/README.md
Tests verify rollback of new partial bookings and ledger writes, plus retries with historical partial state. The Billing documentation describes these transaction behaviors.

Priority: ➖ Normal

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

Change: Bug fix

Sequence Diagram(s)

sequenceDiagram
  participant InvoiceState
  participant StepRunner as runLineEngineInvoiceSteps
  participant Tx as transaction.Run
  participant LineEngines
  InvoiceState->>StepRunner: invoice and ordered callback steps
  StepRunner->>Tx: execute grouped line-engine steps
  Tx->>LineEngines: invoke callbacks
  LineEngines-->>Tx: callback result or validation error
  Tx-->>StepRunner: result, warnings, or transaction error
  StepRunner-->>InvoiceState: assign invoice after successful attempt
Loading

Suggested reviewers: galexihu, borosr

Merge Risk: ⚪ Minimal · up to b54b4

No concrete merge-blocking issue was identified in the reviewed changes. Normal CI checks should still confirm that the billing service package compiles.

Security Architecture Review

Security architecture risk: 🔵 Low · up to d0e0e

The change strengthens financial-state consistency by rolling back failed booking attempts across all participating lines and engines. No new authorization bypass or financial-integrity weakness was established in the reviewed paths. Deployment-specific behavior and engine extensions remain incompletely verified.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — The changed rollback unit encompasses all participating live lines and engine groups in one invoice attempt. Its financial effects include charge payment state and ledger bookings; inspected direct-paid and cross-engine tests assert that later failure leaves those effects unchanged.

Trust Boundaries and Controls

  • observed — Warning acceptance does not extend to critical validation or ordinary system errors. A rollback failure joined with a validation error remains a system error, and the transaction driver records rollback failure so a later commit cannot succeed through that driver.

Resilience and Maintainability Implications

  • observed — The attempt clones line objects, credits, discounts, and validation issues before execution, then replaces the state-machine invoice only on success. This isolates the reviewed mutable financial fields; it is not a guarantee that every invoice field is deeply copied, and database snapshots are explicitly shared as immutable state.
🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the main change: making billing line-engine lifecycle steps atomic.
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.
✨ Finishing Touches
📝 Generate docstrings
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR
  • Autopilot · 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

Comment @coderabbitai help to get the list of available commands.

@turip turip added release-note/bug-fix Release note: Bug Fixes area/billing labels Oct 5, 2026
Comment thread openmeter/billing/service/lineengine.go Resolved
Comment thread openmeter/billing/service/lineengine.go Resolved
@turip
turip enabled auto-merge (squash) October 5, 2026 12:30
@turip
turip merged commit 24a8712 into main Oct 5, 2026
@turip
turip deleted the feat/atomic-line-engine-steps branch October 5, 2026 12:34
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