Skip to content

fix(billing): support invoice delete source handling - #4554

Merged
turip merged 2 commits into
mainfrom
fix/invoice-manual-delete-support
Jun 23, 2026
Merged

turip merged 2 commits into
mainfrom
fix/invoice-manual-delete-support

Conversation

@turip

@turip turip commented Jun 23, 2026 •

Copy link
Copy Markdown
Member

Why

Charge-managed invoices need deletion to behave differently depending on who initiated the delete. A public API invoice delete should only delete the invoice, while a system delete produced by subscription or charge reconciliation must also notify line engines so charge-backed realization state and ledger cleanup can follow the same path as standard-line deletion.

This matters for empty charge-backed standard invoices: the invoice should remain inspectable with its historical lines, but charge engines still need a system deletion signal for every currently active standard line.

What Changed

  • Adds an explicit ChangeSource to DeleteInvoiceInput and persists it on standard invoices for audit.
  • Routes invoice delete through typed state-machine trigger input instead of using persisted state as control flow.
  • Treats DeleteFailed as retryable by calling DeleteInvoice again, so delete retry remains a delete action rather than a generic RetryInvoice action.
  • Dispatches OnMutableStandardLinesDeletedBySystem(...) only for non-deleted standard lines when the delete source is system.
  • Wires API deletes as api_request and charge/subscription empty-invoice deletes as system.
  • Adds the billing_invoices.deletion_source migration and generated Ent mapping.
  • Updates billing and charges skill guidance for the delete lifecycle and charge-originated system deletes.

Validation

  • direnv exec . make migrate-check-validate
  • direnv exec . go vet -tags=dynamic ./openmeter/billing/...
  • direnv exec . go test -tags=dynamic ./openmeter/billing/service -run 'Test(DeleteInvoice|DispatchSystemStandardLineDeletions)'
  • direnv exec . go test -tags=dynamic -run '^$' ./test/billing

Stacked on #4552.

Summary by CodeRabbit

  • New Features

    • Invoice deletion now records the source (system or API request) for improved audit trails and traceability.
  • Bug Fixes

    • Improved handling of system-initiated empty invoice deletions with better line deletion tracking and cleanup.
  • Documentation

    • Updated billing documentation to clarify invoice deletion behavior and source-specific handling.

@coderabbitai

coderabbitai Bot commented Jun 23, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 56f82d94-c1ab-4a53-aaec-029b9082fefa

📥 Commits

Reviewing files that changed from the base of the PR and between fb6e001 and d5b64d9.

⛔ Files ignored due to path filters (10)
  • openmeter/ent/db/billinginvoice.go is excluded by !**/ent/db/**
  • openmeter/ent/db/billinginvoice/billinginvoice.go is excluded by !**/ent/db/**
  • openmeter/ent/db/billinginvoice/where.go is excluded by !**/ent/db/**
  • openmeter/ent/db/billinginvoice_create.go is excluded by !**/ent/db/**
  • openmeter/ent/db/billinginvoice_update.go is excluded by !**/ent/db/**
  • openmeter/ent/db/migrate/schema.go is excluded by !**/ent/db/**
  • openmeter/ent/db/mutation.go is excluded by !**/ent/db/**
  • openmeter/ent/db/runtime.go is excluded by !**/ent/db/**
  • openmeter/ent/db/setorclear.go is excluded by !**/ent/db/**
  • tools/migrate/migrations/atlas.sum is excluded by !**/*.sum, !**/*.sum
📒 Files selected for processing (17)
  • .agents/skills/billing/SKILL.md
  • .agents/skills/charges/SKILL.md
  • openmeter/billing/adapter/invoice.go
  • openmeter/billing/charges/invoiceupdater/invoiceupdate.go
  • openmeter/billing/httpdriver/invoice.go
  • openmeter/billing/service/invoice.go
  • openmeter/billing/service/invoiceupdate.go
  • openmeter/billing/service/lineengine_test.go
  • openmeter/billing/service/stdinvoice.go
  • openmeter/billing/service/stdinvoicestate.go
  • openmeter/billing/stdinvoice.go
  • openmeter/billing/worker/subscriptionsync/service/reconciler/invoiceupdater/invoiceupdate.go
  • openmeter/ent/schema/billing.go
  • test/billing/discount_test.go
  • test/billing/invoice_test.go
  • tools/migrate/migrations/20260622142850_add_invoice_deletion_source.down.sql
  • tools/migrate/migrations/20260622142850_add_invoice_deletion_source.up.sql

📝 Walkthrough

Walkthrough

Adds a deletion_source field to invoices to track whether a deletion was initiated via an API request or the system. The DeleteInvoiceInput type changes from an InvoiceID alias to a struct. The state machine trigger mechanism is extended to carry typed args, and the delete handler is rewritten to use them. A new nullable DB column, adapter mapping, and callers are all updated accordingly.

Changes

Invoice Deletion Source

Layer / File(s) Summary
DeleteInvoiceInput struct and StandardInvoiceBase JSON tags
openmeter/billing/stdinvoice.go
DeleteInvoiceInput becomes a struct with Invoice and DeletionSource fields plus Validate(); DeleteInvoiceTriggerInput gets a models.Validator assertion; two StandardInvoiceBase timestamp fields gain explicit JSON tags.
DB migration and Ent schema
tools/migrate/migrations/20260622142850_add_invoice_deletion_source.*.sql, openmeter/ent/schema/billing.go
Up/down SQL migrations add/drop a nullable deletion_source varchar column; Ent schema registers it as an optional nullable enum field.
Adapter persistence and mapping
openmeter/billing/adapter/invoice.go
UpdateStandardInvoice sets/clears DeletionSource on the DB mutation; mapStandardInvoiceBaseFromDB populates DeletionSource on the domain object.
State machine trigger args and deleteInvoice rewrite
openmeter/billing/service/stdinvoicestate.go
CanFire/FireAndActivate accept variadic args forwarded to the underlying machine. deleteInvoice is rewritten to validate input, record DeletionSource, dispatch system line deletions only for ChangeSourceSystem, and recover delete-failed via TriggerDelete instead of TriggerRetry.
Service trigger args wiring and DeleteInvoice update
openmeter/billing/service/invoice.go
executeTriggerOnInvoiceOptions gains a triggerArgs field; ExecuteTriggerWithArgs option added; DeleteInvoice builds and passes DeleteInvoiceTriggerInput from input.DeletionSource.
dispatchSystemStandardLineDeletions signature refactor
openmeter/billing/service/invoiceupdate.go, openmeter/billing/service/stdinvoice.go
Method now takes []billing.GenericInvoiceLine directly; UpdateStandardInvoice passes only lineDiff.Deleted.
HTTP driver, charges updater, subscription sync updater
openmeter/billing/httpdriver/invoice.go, openmeter/billing/charges/invoiceupdater/invoiceupdate.go, openmeter/billing/worker/.../invoiceupdate.go
HTTP driver tags deletes with ChangeSourceAPIRequest; both system-side updaters tag deletes with ChangeSourceSystem.
Tests and docs
openmeter/billing/service/lineengine_test.go, test/billing/discount_test.go, test/billing/invoice_test.go, .agents/skills/billing/SKILL.md, .agents/skills/charges/SKILL.md
Existing dispatch tests updated to pass slices directly; two new state machine tests verify source-specific dispatch behavior; integration tests updated to use new DeleteInvoiceInput; agent skill docs updated with delete lifecycle and charge-side rules.

Sequence Diagram(s)

sequenceDiagram
  participant APIClient
  participant HTTPDriver
  participant BillingService
  participant InvoiceStateMachine
  participant BillingAdapter

  APIClient->>HTTPDriver: DELETE /invoice/{id}
  HTTPDriver->>BillingService: DeleteInvoice(DeleteInvoiceInput{Invoice, DeletionSource: APIRequest})
  BillingService->>BillingService: ExecuteTriggerWithArgs(DeleteInvoiceTriggerInput{Source: APIRequest})
  BillingService->>InvoiceStateMachine: FireAndActivate(TriggerDelete, args...)
  InvoiceStateMachine->>InvoiceStateMachine: deleteInvoice — record DeletionSource, skip system dispatch
  InvoiceStateMachine->>BillingAdapter: UpdateStandardInvoice (sets deletion_source)
  BillingAdapter-->>InvoiceStateMachine: updated invoice
  InvoiceStateMachine-->>BillingService: deleted
  BillingService-->>HTTPDriver: success
  HTTPDriver-->>APIClient: 204 No Content
Loading
sequenceDiagram
  participant ChargesUpdater
  participant BillingService
  participant InvoiceStateMachine
  participant LineEngine

  ChargesUpdater->>BillingService: DeleteInvoice(DeleteInvoiceInput{Invoice, DeletionSource: System})
  BillingService->>InvoiceStateMachine: FireAndActivate(TriggerDelete, DeleteInvoiceTriggerInput{Source: System})
  InvoiceStateMachine->>InvoiceStateMachine: deleteInvoice — ChangeSourceSystem branch
  InvoiceStateMachine->>LineEngine: dispatchSystemStandardLineDeletions(non-deleted lines only)
  LineEngine-->>InvoiceStateMachine: ok
  InvoiceStateMachine->>BillingService: invoice marked deleted
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • openmeterio/openmeter#4552: The earlier refactor that centralized system-deletion callbacks via OnMutableStandardLinesDeletedBySystem and line engine dispatch — this PR builds directly on that plumbing to conditionally invoke it based on DeletionSource.

Suggested labels

release-note/bug-fix, area/billing

Suggested reviewers

  • borosr
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 9.09% 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
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately captures the main change: adding support for invoice deletion source handling, which is the central feature across all modified files.
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.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ 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 fix/invoice-manual-delete-support

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 the kind/feature New feature or request label Jun 23, 2026
@turip
turip force-pushed the feat/invoice-line-engine-api-edits branch from e09d4a5 to 1aa2076 Compare June 23, 2026 10:24
Base automatically changed from feat/invoice-line-engine-api-edits to main June 23, 2026 10:34
@turip
turip force-pushed the fix/invoice-manual-delete-support branch from 61b8488 to d5b64d9 Compare June 23, 2026 12:05
@turip
turip marked this pull request as ready for review June 23, 2026 12:06
@turip
turip requested a review from a team as a code owner June 23, 2026 12:06
@greptile-apps

greptile-apps Bot commented Jun 23, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR adds an explicit DeletionSource (api_request vs system) to the invoice delete flow, persists it for audit, and routes delete-failure retries through TriggerDelete rather than TriggerRetry. deleteInvoice now fires as an OnEntry action with typed trigger parameters, and OnMutableStandardLinesDeletedBySystem is dispatched only for non-deleted lines on system-sourced deletes.

  • New DeleteInvoiceInput struct wraps InvoiceID + DeletionSource; HTTP handler sets api_request, charge/subscription updaters set system; service validates early and threads the source as a typed trigger arg.
  • State machine rerouting: DeleteFailed now permits TriggerDelete (not TriggerRetry), matching the semantic that delete failures should be retried as a delete, not a generic retry; StatusDetails uses a bare CanFireCtx for TriggerDelete to avoid running side-effects just to probe availability.
  • Ent migration: nullable deletion_source varchar column added to billing_invoices, consistent with the repo's existing enum-as-varchar pattern.

Confidence Score: 4/5

Safe to merge; the delete-lifecycle rerouting is logically sound, migration is backward-compatible, and both the unit and integration tests cover the key branching paths.

The core logic — typing the delete source through the trigger, guarding against double-dispatch via DeletedAt, and rerouting DeleteFailed through TriggerDelete — is correct and well-tested. The two findings are a slightly misleading comment about the dispatch-failure retry path and the Ent-generated validator using string literals instead of the billing constants; neither affects runtime behavior. No migration rollback issues, no missing validations.

openmeter/billing/service/stdinvoicestate.go (deleteInvoice guard comment) and openmeter/ent/db/billinginvoice/billinginvoice.go (DeletionSourceValidator literals) are the only files worth a second glance, both for documentation/maintainability rather than correctness.

Important Files Changed

Filename Overview
openmeter/billing/service/stdinvoicestate.go Key state-machine changes: OnActive→OnEntry with WithParameters for deleteInvoice, TriggerRetry→TriggerDelete for DeleteFailed, manual CanFireCtx for Delete action in StatusDetails, and deleteInvoice now receives typed trigger input. One comment slightly overstates what the DeletedAt guard covers.
openmeter/billing/stdinvoice.go Converts DeleteInvoiceInput from a type alias for InvoiceID to a struct carrying Invoice + DeletionSource, adds DeleteInvoiceTriggerInput with Validate(), and adds DeletionSource field to StandardInvoiceBase. Logic is clean.
openmeter/billing/service/invoice.go DeleteInvoice now validates DeleteInvoiceInput early, unpacks Invoice/DeletionSource correctly, and passes typed trigger args via ExecuteTriggerWithArgs. CanFire and FireAndActivate signatures extended with variadic args, correctly threaded.
openmeter/billing/service/invoiceupdate.go dispatchSystemStandardLineDeletions simplified to accept []GenericInvoiceLine directly instead of mutableInvoiceLineDiff; all callers updated consistently.
openmeter/billing/service/lineengine_test.go Two new unit tests added: TestDeleteInvoiceSystemDeletionSourceDispatchesOnlyNonDeletedLines and TestDeleteInvoiceAPIRequestDoesNotDispatchSystemLineDeletion. Both cover the core branching logic cleanly.
openmeter/billing/adapter/invoice.go SetOrClearDeletionSource wired via EmptyableToPtr for update, and lo.FromPtr used for DB→domain mapping; zero value (empty string) correctly becomes nil in the DB for pre-migration rows.
tools/migrate/migrations/20260622142850_add_invoice_deletion_source.up.sql Adds nullable deletion_source character varying column; consistent with the existing enum-as-varchar pattern used throughout this schema, validated at the application layer.

Sequence Diagram

%%{init: {'theme': 'neutral'}}%%
sequenceDiagram
    participant API as HTTP / Charge / Sub Reconciler
    participant Svc as billing.Service.DeleteInvoice
    participant SM as InvoiceStateMachine
    participant Eng as LineEngine(s)
    participant DB as DB / App

    API->>Svc: "DeleteInvoice(DeleteInvoiceInput{source})"
    Svc->>Svc: input.Validate()
    Svc->>DB: GetInvoiceType()
    Svc->>SM: "executeTriggerOnInvoice(TriggerDelete, DeleteInvoiceTriggerInput{source})"
    SM->>SM: CanFireCtx(TriggerDelete, args)
    SM->>SM: FireAndActivate(TriggerDelete, args)
    Note over SM: State → DeleteInProgress<br/>OnEntry fires deleteInvoice(input)
    SM->>SM: deleteInvoice: validate input
    SM->>SM: reset ValidationIssues
    alt DeletedAt already set (sync-failure retry)
        SM-->>SM: guard returns nil (skip re-dispatch)
    else First attempt
        SM->>SM: "set DeletionSource = input.Source"
        alt "source == system"
            SM->>Eng: dispatchSystemStandardLineDeletions(non-deleted lines)
            Eng-->>SM: ok / err
        else "source == api_request"
            Note over SM: no line-engine notification
        end
        SM->>SM: "set DeletedAt = now()"
    end
    SM->>SM: TriggerNext → DeleteSyncing
    SM->>DB: app.DeleteStandardInvoice (sync)
    alt sync ok
        SM->>SM: TriggerNext → Deleted
    else sync fails
        SM->>SM: TriggerFailed → DeleteFailed
        Note over API: Retry: call DeleteInvoice again<br/>(TriggerDelete from DeleteFailed)
    end
    SM-->>Svc: updated invoice
    Svc-->>API: StandardInvoice
Loading
%%{init: {'theme': 'base', 'themeVariables': {"darkMode": true, "background": "#0d1117", "primaryColor": "#21262d", "primaryTextColor": "#e6edf3", "primaryBorderColor": "#8b949e", "lineColor": "#8b949e", "textColor": "#e6edf3", "edgeLabelBackground": "#161b22", "actorBkg": "#21262d", "actorBorder": "#8b949e", "actorTextColor": "#e6edf3", "actorLineColor": "#8b949e", "signalColor": "#8b949e", "signalTextColor": "#e6edf3", "noteBkgColor": "#373320", "noteBorderColor": "#d4a72c", "noteTextColor": "#f0e6c0", "labelBoxBkgColor": "#21262d", "labelBoxBorderColor": "#8b949e", "labelTextColor": "#e6edf3", "loopTextColor": "#e6edf3", "activationBkgColor": "#30363d", "activationBorderColor": "#8b949e"}}}%%
sequenceDiagram
    participant API as HTTP / Charge / Sub Reconciler
    participant Svc as billing.Service.DeleteInvoice
    participant SM as InvoiceStateMachine
    participant Eng as LineEngine(s)
    participant DB as DB / App

    API->>Svc: "DeleteInvoice(DeleteInvoiceInput{source})"
    Svc->>Svc: input.Validate()
    Svc->>DB: GetInvoiceType()
    Svc->>SM: "executeTriggerOnInvoice(TriggerDelete, DeleteInvoiceTriggerInput{source})"
    SM->>SM: CanFireCtx(TriggerDelete, args)
    SM->>SM: FireAndActivate(TriggerDelete, args)
    Note over SM: State → DeleteInProgress<br/>OnEntry fires deleteInvoice(input)
    SM->>SM: deleteInvoice: validate input
    SM->>SM: reset ValidationIssues
    alt DeletedAt already set (sync-failure retry)
        SM-->>SM: guard returns nil (skip re-dispatch)
    else First attempt
        SM->>SM: "set DeletionSource = input.Source"
        alt "source == system"
            SM->>Eng: dispatchSystemStandardLineDeletions(non-deleted lines)
            Eng-->>SM: ok / err
        else "source == api_request"
            Note over SM: no line-engine notification
        end
        SM->>SM: "set DeletedAt = now()"
    end
    SM->>SM: TriggerNext → DeleteSyncing
    SM->>DB: app.DeleteStandardInvoice (sync)
    alt sync ok
        SM->>SM: TriggerNext → Deleted
    else sync fails
        SM->>SM: TriggerFailed → DeleteFailed
        Note over API: Retry: call DeleteInvoice again<br/>(TriggerDelete from DeleteFailed)
    end
    SM-->>Svc: updated invoice
    Svc-->>API: StandardInvoice
Loading

Comments Outside Diff (1)

  1. openmeter/ent/db/billinginvoice/billinginvoice.go, line 590-597 (link)

    P2 Enum validator uses string literals instead of billing.ChangeSource* constants

    DeletionSourceValidator compares against the hard-coded strings "system" and "api_request" rather than billing.ChangeSourceSystem / billing.ChangeSourceAPIRequest. Since this is generated code the divergence is low-risk today, but if a constant value ever changes the validator would silently accept stale values. Generating against the constants directly (or using billing.ChangeSource("").Values() like the domain's own Validate() does) would make them stay in sync automatically.

    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!

    Fix in Claude Code

Fix All in Claude Code

Reviews (1): Last reviewed commit: "fix(billing): avoid delete status side e..." | Re-trigger Greptile

Comment on lines +885 to +894
// Each delete attempt owns its validation result. This keeps a retry from
// being poisoned by a prior delete-sync failure.
m.Invoice.ValidationIssues = nil

// DeletedAt is persisted before delete syncing starts. If syncing later fails
// and delete is retried, the source-specific line-engine cleanup has already
// run and must not be dispatched again.
if m.Invoice.DeletedAt != nil {
return nil
}

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.

P2 Guard comment overstates coverage for dispatch-failure retries

The comment says "the source-specific line-engine cleanup has already run and must not be dispatched again," but that invariant only holds when DeletedAt != nil. If dispatchSystemStandardLineDeletions returns an error, DeletedAt is never set (the assignment is two lines below the error return), so the guard will not fire on the next retry and the dispatch will run a second time. The behavior on that path is actually correct — retrying a failed dispatch is desirable — but the comment implies the guard covers all retry scenarios when it only covers the sync-failure-after-successful-dispatch path. Consider tightening the comment to reflect that DeletedAt == nil means the first dispatch attempt did not complete, so a re-dispatch on retry is intentional.

Fix in Claude Code

@turip
turip merged commit a8cd4ec into main Jun 23, 2026
25 of 26 checks passed
@turip
turip deleted the fix/invoice-manual-delete-support branch June 23, 2026 12:16
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

kind/feature New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants