Skip to content

Conversation

@turip
Copy link
Member

@turip turip commented Jan 21, 2026

Overview

This patch introduces schema level 2 for billing. The difference is that detailed lines are stored in the billing_standard_invoice_detailed_lines table.

The attached SQL migration can convert a customer to the new schema level.

The migration flow is the following:

Step 1) This gets merged and deployed to all production environments

With this step we ensure that:

  • All services can read both schema level 1 and schema level 2 invoices
  • If the DefaultSchemaLevel is set to 2 then all customers doing a write (acquiring customer lock) will be using the new format
  • (The old records are kept intact)

Note: the QueryContext-based invoication is temporary for the time of the migration.

Step 2) #3799 gets merged

This PR sets the default schema level to 2, resulting all writes resulting the customers to be migrated to the new version.

The SQL Statement included will lock all the existing customers and perform an automated upgrade of the lines. Given we acquire the lock no parallelism can take place.

Any customers created during the upgrade will be using the schema level 2 already.

Step 3) Remove old tables and schema level field

Will be performed later.

Notes for reviewer

The tests are passing, so schemaLevel 1 works fine.

Given this #3799 passes too schemaLevel 2 is also operational.

Summary by CodeRabbit

  • New Features

    • Added schema level management for invoices, enabling support for multiple invoice format versions.
    • Introduced customer invoice migration workflow to upgrade existing invoices to newer schema formats.
  • Refactor

    • Renamed customer override mechanism to customer lock for improved clarity.
    • Enhanced invoice lines to include schema level tracking and customer association.
  • Tests

    • Added comprehensive schema migration test suite validating invoice format upgrades.

✏️ Tip: You can customize this high-level summary in your review settings.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jan 21, 2026

📝 Walkthrough

Walkthrough

Adds invoice schema versioning and write-time schema management, migrates customer invoices from schema level 1→2, propagates schema level through invoice creation/upserts, introduces schema-aware line mapping and V2 detailed-line paths, renames customer override to lock, and adds DB migration functions and tests.

Changes

Cohort / File(s) Summary
Repository config
\.gitignore
Added .gocache and .gomodcache ignore patterns.
Public type aliases & small API changes
openmeter/billing/lock.go, openmeter/billing/customeroverride.go, openmeter/billing/lock.go
Added LockCustomerForUpdateAdapterInput and UpsertCustomerLockAdapterInput aliases; removed old UpsertCustomerOverrideAdapterInput alias.
Billing adapter API
openmeter/billing/adapter.go
Added SchemaLevelAdapter interface (Get/Set default schema level) and embedded it in Adapter; renamed/upsert customer override → lock.
Invoice model & inputs
openmeter/billing/invoice.go, openmeter/billing/invoiceline.go
Added SchemaLevel to InvoiceBase; added SchemaLevel and InvoiceID to UpsertInvoiceLinesAdapterInput; added CustomerID to GetLinesForSubscriptionInput with validation.
Adapter: schema management
openmeter/billing/adapter/schemalevel.go
New implementation for reading/upserting default invoice write schema level and helper to fetch per-invoice schema levels; exports DefaultInvoiceWriteSchemaLevel.
Adapter: migration workflow
openmeter/billing/adapter/schemamigration.go
New migration detection (shouldInvoicesBeMigrated) and execution (migrateCustomerInvoices, migrateSchemaLevel1) invoking DB function to migrate invoices.
Adapter: invoice creation & propagation
openmeter/billing/adapter/invoice.go
Read default schema level during invoice creation and set SchemaLevel on created invoice; pass schema level into invoice-line upsert inputs.
Adapter: invoice line mapping
openmeter/billing/adapter/invoicelinemapper.go, openmeter/billing/adapter/invoicelines.go
Map lines using a per-invoice schema-level map; conditional V1/V2 detailed-line mapping (mapInvoiceDetailedLineV2FromDB, discount mapping); added V2 upsert paths and refetch changes (refetchInvoiceLinesInput).
Adapter: customer lock & integration
openmeter/billing/adapter/lock.go, openmeter/billing/service/service.go
Renamed internal call to UpsertCustomerLock; LockCustomerForUpdate now computes migration necessity and invokes migrateCustomerInvoices within the transaction when required.
Worker/service callsite update
openmeter/billing/worker/subscriptionsync/service/sync.go
Now supplies CustomerID when calling GetLinesForSubscription so line fetch is customer-scoped.
Database migrations
tools/migrate/migrations/20260121143838_detailed-lines-migration.up.sql, ...down.sql
Added om_func_migrate_customer_invoices_to_schema_level_2(p_customer_id TEXT) to copy detailed lines and discounts and update invoice schema_level; down script drops the function.
Tests & test infra
test/billing/schemamigration_test.go, test/billing/adapter_test.go, test/billing/invoice_test.go, test/billing/suite.go
Added end-to-end migration tests and helpers; updated tests to set SchemaLevel/InvoiceID; introduced SetupSuiteOptions with ForceAtlas control.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant BillingService
    participant Adapter
    participant DB
    rect rgba(0,128,0,0.5)
    Client->>BillingService: CreateInvoice(...)
    BillingService->>Adapter: CreateInvoice(ctx, input)
    Adapter->>Adapter: GetInvoiceDefaultSchemaLevel(ctx)
    Adapter->>DB: SELECT write_schema_level
    DB-->>Adapter: defaultSchemaLevel
    Adapter->>DB: INSERT invoice (schema_level = defaultSchemaLevel)
    DB-->>Adapter: invoiceID
    Adapter->>Adapter: UpsertInvoiceLines(SchemaLevel, InvoiceID, ...)
    Adapter->>DB: upsert lines (schema-aware)
    DB-->>Adapter: OK
    Adapter-->>BillingService: InvoiceCreated
    BillingService-->>Client: 201 Created
    end
Loading
sequenceDiagram
    participant Caller
    participant Service
    participant Adapter
    participant DB
    Caller->>Service: LockCustomerForUpdate(customerID)
    Service->>Adapter: LockCustomerForUpdate(ctx, customerID)
    Adapter->>DB: SELECT lock row FOR UPDATE
    DB-->>Adapter: lockRow
    Adapter->>Adapter: shouldInvoicesBeMigrated(customerID)
    Adapter->>DB: SELECT min(schema_level) FROM billing_invoices WHERE customer=...
    DB-->>Adapter: minSchemaLevel
    alt minSchemaLevel < defaultSchemaLevel
        Adapter->>Adapter: migrateCustomerInvoices(customerID, minSchemaLevel)
        Adapter->>DB: SELECT om_func_migrate_customer_invoices_to_schema_level_2(customerID)
        DB-->>Adapter: updatedCount
    end
    Adapter->>DB: UpsertCustomerLock(...)
    DB-->>Adapter: OK
    Adapter-->>Service: lock acquired
    Service-->>Caller: success
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Suggested reviewers

  • chrisgacsal
  • gergely-kurucz-konghq
🚥 Pre-merge checks | ✅ 2 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main change: introducing schema level 2 for detailed invoice lines, with migration logic as the primary focus of this PR.

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

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch chore/migrate-detailed-lines-pt1

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 and usage tips.

@turip turip marked this pull request as ready for review January 21, 2026 18:39
@turip turip requested a review from a team as a code owner January 21, 2026 18:39
@turip turip added release-note/misc Miscellaneous changes area/billing labels Jan 21, 2026
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
openmeter/billing/adapter/invoicelinemapper.go (1)

17-42: GetLinesForSubscription is missing detailed-line edge preloading.

At line 794, GetLinesForSubscription uses expandLineItems instead of expandLineItemsWithDetailedLines. This means DetailedLines and DetailedLinesV2 edges aren't preloaded. When mapInvoiceLineFromDB runs, dbLine.Edges.DetailedLinesV2 (schema level 2+) and dbLine.Edges.DetailedLines (schema level 1) will be nil, causing MapWithErr to silently return empty lists instead of the actual detailed lines—a data loss bug.

Change line 794 to use tx.expandLineItemsWithDetailedLines(query) instead of tx.expandLineItems(query). The other three call sites (lines 644, 767, 749) already do this correctly.

🤖 Fix all issues with AI agents
In `@openmeter/billing/adapter/invoicelines.go`:
- Around line 286-294: The refetch call can mis-map lines when input.Lines
contains lines from multiple invoices; before calling tx.refetchInvoiceLines
construct a guard that verifies every billing.Line in input.Lines has the same
InvoiceID as input.InvoiceID (or return an error), e.g. iterate input.Lines and
compare each line.ID's associated InvoiceID or the line.InvoiceID field and fail
early if any mismatch is found; update the caller to return a clear validation
error when lines span invoices so refetchInvoiceLinesInput.InvoiceID remains
authoritative.

In `@openmeter/billing/adapter/schemamigration.go`:
- Around line 69-83: The call in migrateSchemaLevel1 to the DB function
om_func_migrate_customer_invoices_to_schema_level_2 must include the tenant
namespace to avoid cross-namespace migrations: modify the tx.db.QueryContext
invocation in migrateSchemaLevel1 to pass the CustomerID's namespace value (from
the NamespacedID) as the first/appropriate argument and the customer ID as the
other argument, and update the DB function signature and migration SQL to accept
the namespace parameter and add a WHERE predicate that filters invoices by
namespace as well as customer ID.

In `@tools/migrate/migrations/20260121143838_detailed-lines-migration.up.sql`:
- Around line 16-147: The migration function
om_func_migrate_customer_invoices_to_schema_level_2 currently only accepts
p_customer_id and can cross-tenant migrate; change its signature to accept
p_namespace (e.g., p_namespace TEXT, p_customer_id TEXT) and add AND i.namespace
= p_namespace (or WHERE namespace = p_namespace in the UPDATE) to all three SQL
statements to scope by namespace; then update the Go caller in
openmeter/billing/adapter/schemamigration.go to call the function with
customerID.Namespace and customerID.ID (adjusting the QueryContext parameter
order and SQL argument count to match the new two-arg signature).
🧹 Nitpick comments (4)
openmeter/billing/adapter/schemamigration.go (1)

56-66: Fail fast on unsupported schema levels.
Right now a non‑1 minLevel silently no‑ops even if migration is required. Consider returning an explicit error so unsupported upgrades don’t slip by.

💡 Suggested guard
@@
 func (a *adapter) migrateCustomerInvoices(ctx context.Context, customerID customer.CustomerID, minLevel int) error {
 	return entutils.TransactingRepoWithNoValue(ctx, a, func(ctx context.Context, tx *adapter) error {
-		if minLevel == 1 {
-			err := tx.migrateSchemaLevel1(ctx, customerID)
-			if err != nil {
-				return err
-			}
-		}
-
-		return nil
+		switch minLevel {
+		case 1:
+			return tx.migrateSchemaLevel1(ctx, customerID)
+		default:
+			return fmt.Errorf("unsupported invoice schema level: %d", minLevel)
+		}
 	})
 }
@@
-import (
-	"context"
+import (
+	"context"
+	"fmt"
openmeter/billing/adapter/schemalevel.go (1)

36-44: Optional: validate schema level inputs.
If only specific schema levels are supported, consider guarding here to prevent persisting invalid values.

openmeter/billing/adapter/invoicelines.go (2)

689-698: Potential perf tweak: avoid loading both detailed-line variants.
expandLineItemsWithDetailedLines now always fetches both v1 and v2 detailed lines, which adds extra queries. If the schema level is known at the call site, consider branching to only load the relevant edge to trim DB work. As per coding guidelines, focusing on DB query efficiency is important.


801-810: Consider scoping schema lookup to just needed invoices.
getSchemaLevelPerInvoice uses the full customer set; for large customers this could be heavier than necessary. You already have the invoice IDs in dbLines, so narrowing the lookup to those IDs would reduce DB work. As per coding guidelines, DB-path performance is worth tightening.

@turip
Copy link
Member Author

turip commented Jan 21, 2026

Reviewed comments and nitpick comments and they are safe to ignore.

@turip turip enabled auto-merge (squash) January 21, 2026 18:57
@turip turip requested a review from chrisgacsal January 21, 2026 18:57
Copy link
Contributor

@gergely-kurucz-konghq gergely-kurucz-konghq left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor/nit comments, otherwise LGTM!


// Step 3: Let's create the detailed lines
if !lineDiffs.DetailedLine.IsEmpty() {
if input.SchemaLevel == 1 {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The IsEmpty check is not needed needed anymore?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It doesn't matter as the upsert is noop if the diff is empty.

@@ -52,7 +53,7 @@ type CustomerOverrideAdapter interface {
type CustomerSynchronizationAdapter interface {
// UpsertCustomerOverride upserts a customer override ignoring the transactional context, the override
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Update comment after method rename.

@turip turip merged commit 06d91ac into main Jan 22, 2026
27 checks passed
@turip turip deleted the chore/migrate-detailed-lines-pt1 branch January 22, 2026 14:07
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