Skip to content

feat: report overdue billing worker invoices - #4710

Merged
turip merged 2 commits into
mainfrom
feat/billing-worker-overdue-invoice-metrics
Jul 14, 2026
Merged

turip merged 2 commits into
mainfrom
feat/billing-worker-overdue-invoice-metrics

Conversation

@turip

@turip turip commented Jul 14, 2026 •

Copy link
Copy Markdown
Member

Summary

  • add a one-minute billing-worker gauge for invoices overdue for collection or advancement
  • centralize automatic advancement candidates behind dedicated standard-invoice list and count operations, including the worker processes
  • exclude lockdown namespaces and report collection and advancement independently

Summary by CodeRabbit

  • New Features

    • Added automatic invoice advancement tracking for invoices awaiting collection or advancement.
    • Added periodic overdue-invoice metrics, reported separately for collection and advancement.
    • Added lifecycle management so metrics start and stop with the billing worker.
  • Bug Fixes

    • Consolidated invoice advancement detection into a single, more consistent retrieval process.

Summary by CodeRabbit

  • New Features
    • Added automatic detection and listing of invoices ready for advancement.
    • Added periodic overdue-invoice metrics for collection and advancement workflows.
    • Metrics now start and stop with the billing worker.
  • Improvements
    • Streamlined invoice advancement processing through unified eligibility checks.
    • Added filtering by namespace, invoice ID, cutoff time, and minimum invoice age.
  • Bug Fixes
    • Improved handling of invoices awaiting collection or advancement, including fallback timing cases.

Greptile Summary

This PR adds overdue invoice reporting to the billing worker. The main changes are:

  • A new billing-worker metric for pending invoice counts.
  • Separate collection and advancement overdue counts.
  • Centralized standard-invoice advancement list and count paths.
  • Billing-worker wiring for the new metrics service.
  • Namespace lockdown exclusions for invoice metrics.

Confidence Score: 5/5

This looks safe to merge.

  • No blocking issues found in the changed code.

Important Files Changed

Filename Overview
app/common/openmeter_billingworker.go Wires the new invoice metrics adapter and service into the billing worker.
openmeter/billing/adapter/invoice_advancement.go Adds shared list and count queries for standard invoices pending advancement.
openmeter/billing/worker/advance/advance.go Routes automatic advancement candidate discovery through the shared billing service method.
openmeter/billing/worker/invoicemetrics/adapter/count.go Counts overdue invoices for collection and advancement.
openmeter/billing/worker/invoicemetrics/service/service.go Adds the periodic metrics loop that records overdue invoice counts.

Reviews (2): Last reviewed commit: "fix: validate invoice metrics configurat..." | Re-trigger Greptile

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 14, 2026 14:21
@coderabbitai

coderabbitai Bot commented Jul 14, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Changes

The billing worker now reports overdue collection and advancement invoice metrics. Standard invoice advancement filtering, listing, and counting were added; the auto-advancer uses the consolidated query, and the metrics service is wired into worker startup and shutdown.

Invoice advancement query and contract

Layer / File(s) Summary
Pending advancement query and service contract
openmeter/billing/stdinvoice.go, openmeter/billing/adapter/..., openmeter/billing/service.go, openmeter/billing/service/stdinvoice.go, openmeter/billing/worker/advance/advance.go, openmeter/server/server_test.go
Validated filters and adapter/service methods retrieve and count eligible invoices, while AutoAdvancer uses the consolidated listing operation.

Overdue invoice metrics

Layer / File(s) Summary
Overdue invoice counting adapter
openmeter/billing/worker/invoicemetrics/...
Counts overdue collection invoices transactionally and obtains advancement counts from the billing adapter.
Periodic overdue metrics service
openmeter/billing/worker/invoicemetrics/service/...
Periodically records collection and advancement counts in an OpenTelemetry gauge with start and stop lifecycle methods.

Billing worker integration

Layer / File(s) Summary
Billing worker wiring and lifecycle
app/common/openmeter_billingworker.go, cmd/billing-worker/wire_gen.go
Constructs the metrics components, passes them into the billing worker group, and manages their lifecycle.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant BillingWorker
  participant InvoiceMetricsService
  participant InvoiceMetricsAdapter
  participant BillingAdapter
  participant OpenTelemetry
  BillingWorker->>InvoiceMetricsService: Start(ctx)
  InvoiceMetricsService->>InvoiceMetricsAdapter: CountOverdueInvoices
  InvoiceMetricsAdapter->>BillingAdapter: CountStandardInvoicesPendingAdvancement
  BillingAdapter-->>InvoiceMetricsAdapter: Advancement count
  InvoiceMetricsAdapter-->>InvoiceMetricsService: Collection and advancement counts
  InvoiceMetricsService->>OpenTelemetry: Record gauge measurements
  BillingWorker->>InvoiceMetricsService: Stop()
Loading

Suggested labels: kind/feature, area/billing

Suggested reviewers: tothandras, galexihu, chrisgacsal

🚥 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: adding overdue invoice reporting to the billing worker.
✨ 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/billing-worker-overdue-invoice-metrics

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 release-note/feature Release note: Exciting New Features label Jul 14, 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.

Actionable comments posted: 1

🧹 Nitpick comments (2)
openmeter/billing/adapter/invoice_advancement.go (2)

26-40: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Same "collection window elapsed" predicate logic duplicated across two packages. Both sites independently implement CollectionAtLTE(cutoff) OR (CollectionAtIsNil() AND UpdatedAtLTE(cutoff)) against different statuses — one shared domain rule with two copies to keep in sync.

  • openmeter/billing/adapter/invoice_advancement.go#L26-L40: extract this Or(...) block into an exported helper (e.g., CollectionWindowElapsedPredicate(cutoff time.Time) predicate.BillingInvoice) in this package.
  • openmeter/billing/worker/invoicemetrics/adapter/count.go#L21-L32: import and reuse that same helper here instead of re-declaring the Or(...) block inline.
🤖 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 `@openmeter/billing/adapter/invoice_advancement.go` around lines 26 - 40,
Extract the shared collection-window predicate from
openmeter/billing/adapter/invoice_advancement.go lines 26-40 into an exported
helper such as CollectionWindowElapsedPredicate(cutoff time.Time), preserving
the CollectionAtLTE OR nil-CollectionAt plus UpdatedAtLTE logic. Update
openmeter/billing/worker/invoicemetrics/adapter/count.go lines 21-32 to import
and reuse this helper instead of defining the predicate inline; both sites
should retain their existing status filters.

16-53: 🚀 Performance & Scalability | 🔵 Trivial

Worth confirming index support now that this predicate runs from two periodic jobs.

This predicate (status/time filters + a JSONB availableActions containment check on status_details_cache) is now exercised both by the advance worker and, via CountStandardInvoicesPendingAdvancement, by the new one-minute overdue-invoice gauge. If billing_invoice doesn't have indexes covering status/collection_at/updated_at and a GIN index on status_details_cache, this query could turn into a table scan run every minute as the table grows. Not something visible from this diff alone (no migration files included), so flagging for a quick check.

🤖 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 `@openmeter/billing/adapter/invoice_advancement.go` around lines 16 - 53,
Verify that the database schema supporting invoicePendingAdvancementPredicate
includes indexes for the filtered status, collection_at, and updated_at columns,
plus a GIN index for status_details_cache JSONB lookups. If any are missing, add
the corresponding migration indexes and ensure they support both the advancement
worker and CountStandardInvoicesPendingAdvancement queries.
🤖 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.

Inline comments:
In `@openmeter/billing/worker/invoicemetrics/adapter/adapter.go`:
- Around line 21-31: Update Config.Validate in
openmeter/billing/worker/invoicemetrics/adapter/adapter.go to collect both
validation failures in an errs slice, import the models package, and return
errors.Join(errs...) wrapped with models.NewNillableGenericValidationError. In
openmeter/billing/worker/invoicemetrics/service/service.go, update
Config.Validate’s final return to use the same wrapper around
errors.Join(errs...).

---

Nitpick comments:
In `@openmeter/billing/adapter/invoice_advancement.go`:
- Around line 26-40: Extract the shared collection-window predicate from
openmeter/billing/adapter/invoice_advancement.go lines 26-40 into an exported
helper such as CollectionWindowElapsedPredicate(cutoff time.Time), preserving
the CollectionAtLTE OR nil-CollectionAt plus UpdatedAtLTE logic. Update
openmeter/billing/worker/invoicemetrics/adapter/count.go lines 21-32 to import
and reuse this helper instead of defining the predicate inline; both sites
should retain their existing status filters.
- Around line 16-53: Verify that the database schema supporting
invoicePendingAdvancementPredicate includes indexes for the filtered status,
collection_at, and updated_at columns, plus a GIN index for status_details_cache
JSONB lookups. If any are missing, add the corresponding migration indexes and
ensure they support both the advancement worker and
CountStandardInvoicesPendingAdvancement queries.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 86c20ed4-57d4-42e4-976e-d59d03585fae

📥 Commits

Reviewing files that changed from the base of the PR and between 9d0d3a4 and 8d86bbc.

📒 Files selected for processing (15)
  • app/common/openmeter_billingworker.go
  • cmd/billing-worker/wire_gen.go
  • openmeter/billing/adapter.go
  • openmeter/billing/adapter/invoice_advancement.go
  • openmeter/billing/service.go
  • openmeter/billing/service/stdinvoice.go
  • openmeter/billing/stdinvoice.go
  • openmeter/billing/worker/advance/advance.go
  • openmeter/billing/worker/invoicemetrics/adapter.go
  • openmeter/billing/worker/invoicemetrics/adapter/adapter.go
  • openmeter/billing/worker/invoicemetrics/adapter/count.go
  • openmeter/billing/worker/invoicemetrics/metrics.go
  • openmeter/billing/worker/invoicemetrics/service.go
  • openmeter/billing/worker/invoicemetrics/service/service.go
  • openmeter/server/server_test.go

@turip
turip enabled auto-merge (squash) July 14, 2026 14:59
@turip
turip merged commit 98e130f into main Jul 14, 2026
27 checks passed
@turip
turip deleted the feat/billing-worker-overdue-invoice-metrics branch July 14, 2026 16:48
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

release-note/feature Release note: Exciting New Features

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants