Skip to content

fix: customer lookup by usage attribution - #3292

Merged
chrisgacsal merged 2 commits into
mainfrom
fix/customer-lookup
Aug 29, 2025
Merged

chrisgacsal merged 2 commits into
mainfrom
fix/customer-lookup

Conversation

@chrisgacsal

@chrisgacsal chrisgacsal commented Aug 29, 2025 •

Copy link
Copy Markdown
Collaborator

Overview

Fix Customer lookup by usgae attribution where Customer was returned even if the Subject assignement was already deleted.
Also make sure to return Customer if the assignement is deleted in the future which is mostly useful for "time-travel" in testing.

Summary by CodeRabbit

  • New Features

    • Time-aware filtering so customers, subjects, and subscriptions reflect their state at a specific moment.
  • Bug Fixes

    • More accurate handling of deleted subjects and subscription active periods to reduce inconsistent results.
    • Consistent inclusion of plan details with active subscriptions.
    • Unified time context across customer listing and retrieval for predictable outcomes.
  • Refactor

    • Streamlined subscription filtering for consistent, time-based query behavior.

@chrisgacsal chrisgacsal self-assigned this Aug 29, 2025
@chrisgacsal chrisgacsal added the release-note/bug-fix Release note: Bug Fixes label Aug 29, 2025
@chrisgacsal
chrisgacsal requested a review from a team as a code owner August 29, 2025 12:16
@coderabbitai

coderabbitai Bot commented Aug 29, 2025 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

Adds time-aware subject and subscription filtering to the customer adapter: subject filters now accept a timestamp and consider soft-deletes relative to that time; withActiveSubscription is replaced by withSubscription(at) which applies time-based subscription predicates and loads plan; query call sites capture a single UTC timestamp and pass it through.

Changes

Cohort / File(s) Change summary
Customer adapter: main logic changes
openmeter/customer/adapter/customer.go
- withSubjects now accepts at time.Time and filters subjects with Or(DeletedAtIsNil(), DeletedAtGT(at)).
- Removed withActiveSubscription; added withSubscription(query, at) which applies time-based active-subscription predicates (ActiveFromLTE/ActiveToIsNil/ActiveToGT, DeletedAt checks, CreatedAtLTE) and always loads the plan (query.WithPlan()).
- ListCustomers, GetCustomer, and GetCustomerByUsageAttribution capture now := clock.Now().UTC() and pass it to withSubjects/withSubscription.
- GetCustomerByUsageAttribution predicate updated to allow subjects not deleted or deleted after now and ensures customer DeletedAtIsNil().
- Internal helper signatures updated to accept at; exported/public function signatures unchanged.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/customer-lookup

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbit in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbit in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbit gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbit read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbit help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbit ignore or @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbit summary or @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbit or @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@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: 2

🧹 Nitpick comments (2)
openmeter/customer/adapter/customer.go (2)

375-385: Add supporting index for subject lookups

To keep this predicate fast at scale, add a composite/partial index on customersubjects(namespace, subject_key, deleted_at) (and ensure an index supports deleted_at IS NULL).


660-665: DRY up “subject alive at time” predicate

The DeletedAt guard is duplicated (here and in GetCustomerByUsageAttribution). Centralize it.

 func withSubjects(query *entdb.CustomerQuery, at time.Time) *entdb.CustomerQuery {
     return query.WithSubjects(func(query *entdb.CustomerSubjectsQuery) {
-        query.Where(customersubjectsdb.Or(
-            customersubjectsdb.DeletedAtIsNil(),
-            customersubjectsdb.DeletedAtGT(at),
-        ))
+        query.Where(subjectAliveAt(at))
     })
 }
+
+// subjectAliveAt returns a time-aware predicate for CustomerSubjects.
+func subjectAliveAt(at time.Time) predicate.CustomerSubjects {
+    return customersubjectsdb.Or(
+        customersubjectsdb.DeletedAtIsNil(),
+        customersubjectsdb.DeletedAtGT(at),
+    )
+}

And in GetCustomerByUsageAttribution (Lines 379-385):

-            Where(customerdb.HasSubjectsWith(
-                customersubjectsdb.SubjectKey(input.SubjectKey),
-                customersubjectsdb.Or(
-                    customersubjectsdb.DeletedAtIsNil(),
-                    customersubjectsdb.DeletedAtGT(now),
-                ),
-            )).
+            Where(customerdb.HasSubjectsWith(
+                customersubjectsdb.SubjectKey(input.SubjectKey),
+                subjectAliveAt(now),
+            )).
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled
  • Linear integration is disabled

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 38012fb and a791cb2.

📒 Files selected for processing (1)
  • openmeter/customer/adapter/customer.go (4 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
openmeter/customer/adapter/customer.go (4)
pkg/clock/clock.go (1)
  • Now (14-21)
openmeter/ent/db/customer/where.go (4)
  • HasSubjectsWith (1330-1339)
  • Or (1416-1418)
  • DeletedAtIsNil (348-350)
  • DeletedAtGT (328-330)
openmeter/ent/db/customersubjects/where.go (4)
  • SubjectKey (69-71)
  • Or (397-399)
  • DeletedAtIsNil (359-361)
  • DeletedAtGT (339-341)
openmeter/ent/db/customer_query.go (1)
  • CustomerQuery (26-41)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (8)
  • GitHub Check: Quickstart
  • GitHub Check: E2E
  • GitHub Check: Build
  • GitHub Check: Lint
  • GitHub Check: Test
  • GitHub Check: Code Generators
  • GitHub Check: Migration Checks
  • GitHub Check: Analyze (go)
🔇 Additional comments (3)
openmeter/customer/adapter/customer.go (3)

375-389: Time-aware usage-attribution lookup is correct

Subject predicate guards against past deletions while allowing future-dated deletions; aligns with PR goal.


63-64: PlanKey filtering is now time-consistent

Passing the captured now into applyActiveSubscriptionFilterWithPlanKey avoids temporal skew.


309-314: Good: single captured time across predicates

Capturing clock.Now().UTC() once and passing to withSubjects/withSubscription removes TOCTOU-style drift.

Comment thread openmeter/customer/adapter/customer.go Resolved
Comment thread openmeter/customer/adapter/customer.go Resolved
@chrisgacsal
chrisgacsal merged commit 04a70a6 into main Aug 29, 2025
@chrisgacsal
chrisgacsal deleted the fix/customer-lookup branch August 29, 2025 12:35

@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: 0

Caution

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

⚠️ Outside diff range comments (2)
openmeter/customer/adapter/customer.go (2)

153-160: Bug: uniqueness check ignores “scheduled future delete”, allowing overlapping subject keys now

Using DeletedAtIsNil() alone treats rows with DeletedAt in the future as “deleted”, so CreateCustomer can accept a new customer whose key equals an alive subject assignment on another customer until that future time. That reintroduces double attribution.

Apply:

-        if input.Key != nil {
+        if input.Key != nil {
+            now := clock.Now().UTC()
             conflictingCustomerIDs, err := repo.db.CustomerSubjects.Query().
                 Select(customersubjectsdb.FieldCustomerID).
                 Where(customersubjectsdb.Namespace(input.Namespace)).
                 Where(customersubjectsdb.SubjectKey(*input.Key)).
-                Where(customersubjectsdb.DeletedAtIsNil()).
+                Where(customersubjectsdb.Or(
+                    customersubjectsdb.DeletedAtIsNil(),
+                    customersubjectsdb.DeletedAtGT(now),
+                )).
                 All(ctx)

This matches the “alive at now” semantics used elsewhere.


441-449: Same uniqueness-hole on update path

Updating a customer’s key checks only DeletedAtIsNil(), permitting conflicts with subject assignments scheduled to be deleted later.

Apply:

-        if input.Key != nil {
+        if input.Key != nil {
+            now := clock.Now().UTC()
             conflictingCustomerIDs, err := repo.db.CustomerSubjects.Query().
                 Select(customersubjectsdb.FieldCustomerID).
                 Where(customersubjectsdb.Namespace(input.CustomerID.Namespace)).
                 Where(customersubjectsdb.CustomerIDNEQ(input.CustomerID.ID)).
                 Where(customersubjectsdb.SubjectKey(*input.Key)).
-                Where(customersubjectsdb.DeletedAtIsNil()).
+                Where(customersubjectsdb.Or(
+                    customersubjectsdb.DeletedAtIsNil(),
+                    customersubjectsdb.DeletedAtGT(now),
+                )).
                 All(ctx)
♻️ Duplicate comments (2)
openmeter/customer/adapter/customer.go (2)

59-65: Subject filter is now time-aware (alive at now) — resolves prior gap

Adding Or(DeletedAtIsNil(), DeletedAtGT(now)) aligns manual HasSubjectsWith with the edge loader semantics.


381-395: Usage-attribution lookup fixed and transactional client used

  • The alive-at-now check on CustomerSubjects closes the original bug.
  • Switching to repo.db within the transaction fixes the earlier “a.db inside tx” issue.
🧹 Nitpick comments (2)
openmeter/customer/adapter/customer.go (2)

666-671: DRY the "alive subject" predicate to avoid divergence

The same Or(DeletedAtIsNil(), DeletedAtGT(at)) logic now appears here and in two HasSubjectsWith sites. Factor it to a helper so future tweaks (e.g., adding CreatedAtLTE(at)) remain consistent.

Apply:

+// subjectAliveAt returns predicates that consider a subject assignment alive at `at`.
+func subjectAliveAt(at time.Time) []predicate.CustomerSubjects {
+	return []predicate.CustomerSubjects{
+		customersubjectsdb.Or(
+			customersubjectsdb.DeletedAtIsNil(),
+			customersubjectsdb.DeletedAtGT(at),
+		),
+	}
+}
+
-func withSubjects(query *entdb.CustomerQuery, at time.Time) *entdb.CustomerQuery {
+func withSubjects(query *entdb.CustomerQuery, at time.Time) *entdb.CustomerQuery {
 	return query.WithSubjects(func(query *entdb.CustomerSubjectsQuery) {
-		query.Where(customersubjectsdb.Or(
-			customersubjectsdb.DeletedAtIsNil(),
-			customersubjectsdb.DeletedAtGT(at),
-		))
+		query.Where(subjectAliveAt(at)...)
 	})
 }

Then reuse in callers:

- query = query.Where(customerdb.HasSubjectsWith(
-   customersubjectsdb.SubjectKeyContainsFold(*input.Subject),
-   customersubjectsdb.Or(customersubjectsdb.DeletedAtIsNil(), customersubjectsdb.DeletedAtGT(now)),
- ))
+ query = query.Where(customerdb.HasSubjectsWith(
+   customersubjectsdb.SubjectKeyContainsFold(*input.Subject),
+   subjectAliveAt(now)...,
+ ))

471-472: Use one frozen timestamp in UpdateCustomer for consistency

UpdateCustomer calls clock.Now() three times (SetUpdatedAt, SetDeletedAt for subjects, fetching subscription). Capture now once to avoid micro-drifts and to align with your new “single now per request” pattern.

Apply:

-    query := repo.db.Customer.UpdateOneID(previousCustomer.ID).
-        Where(customerdb.Namespace(previousCustomer.Namespace)).
-        SetUpdatedAt(clock.Now().UTC()).
+    now := clock.Now().UTC()
+    query := repo.db.Customer.UpdateOneID(previousCustomer.ID).
+        Where(customerdb.Namespace(previousCustomer.Namespace)).
+        SetUpdatedAt(now).
...
-    SetDeletedAt(clock.Now().UTC()).
+    SetDeletedAt(now).
...
-    subsQuery := repo.db.Subscription.Query()
-    applyActiveSubscriptionFilter(subsQuery, clock.Now().UTC())
+    subsQuery := repo.db.Subscription.Query()
+    applyActiveSubscriptionFilter(subsQuery, now)

Also applies to: 596-597, 613-616

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled
  • Linear integration is disabled

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between a791cb2 and 5231840.

📒 Files selected for processing (1)
  • openmeter/customer/adapter/customer.go (5 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
openmeter/customer/adapter/customer.go (4)
openmeter/ent/db/customer/where.go (4)
  • HasSubjectsWith (1330-1339)
  • Or (1416-1418)
  • DeletedAtIsNil (348-350)
  • DeletedAtGT (328-330)
openmeter/ent/db/customersubjects/where.go (5)
  • SubjectKeyContainsFold (274-276)
  • Or (397-399)
  • DeletedAtIsNil (359-361)
  • DeletedAtGT (339-341)
  • SubjectKey (69-71)
pkg/clock/clock.go (1)
  • Now (14-21)
openmeter/ent/db/customer_query.go (1)
  • CustomerQuery (26-41)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (6)
  • GitHub Check: E2E
  • GitHub Check: Quickstart
  • GitHub Check: Test
  • GitHub Check: Code Generators
  • GitHub Check: Lint
  • GitHub Check: Analyze (go)
🔇 Additional comments (3)
openmeter/customer/adapter/customer.go (3)

37-38: Good: single time anchor passed through subject/subscription loaders

Capturing now once and threading it into withSubjects/withSubscription prevents TOCTOU drift during a request.


315-320: GetCustomer adopts the unified time context

Using now := clock.Now().UTC() and passing it to withSubjects/withSubscription keeps results consistent.


68-70: PlanKey filter may not match the loaded subscription edge

When PlanKey is provided, you filter customers by having an active subscription with that plan, but withSubscription(query, now) still loads “any” active subscription. If more than one active subscription can exist (even transiently), the loaded edge may not correspond to the filtered plan.

  • If DB constraints guarantee at most one active subscription per customer at any time: fine.
  • Otherwise, load the subscription edge with the same plan predicate:
- query = withSubscription(query, now)
+ if input.PlanKey != nil {
+   query = query.WithSubscription(func(q *entdb.SubscriptionQuery) {
+     applyActiveSubscriptionFilter(q, now)
+     q.Where(subscriptiondb.HasPlanWith(plandb.Key(*input.PlanKey)))
+     q.WithPlan()
+   })
+ } else {
+   query = withSubscription(query, now)
+ }

Also applies to: 37-39

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

release-note/bug-fix Release note: Bug Fixes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants