Repository navigation
fix: customer lookup by usage attribution - #3292
Conversation
📝 WalkthroughWalkthroughAdds 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
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related PRs
✨ Finishing Touches
🧪 Generate unit tests
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. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. CodeRabbit Commands (Invoked using PR/Issue comments)Type Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (2)
openmeter/customer/adapter/customer.go (2)
375-385: Add supporting index for subject lookupsTo 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” predicateThe 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.
📒 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 correctSubject predicate guards against past deletions while allowing future-dated deletions; aligns with PR goal.
63-64: PlanKey filtering is now time-consistentPassing the captured now into applyActiveSubscriptionFilterWithPlanKey avoids temporal skew.
309-314: Good: single captured time across predicatesCapturing clock.Now().UTC() once and passing to withSubjects/withSubscription removes TOCTOU-style drift.
a791cb2 to
5231840
Compare
There was a problem hiding this comment.
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 nowUsing 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 pathUpdating 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 gapAdding 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 divergenceThe 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 consistencyUpdateCustomer 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.
📒 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 loadersCapturing now once and threading it into withSubjects/withSubscription prevents TOCTOU drift during a request.
315-320: GetCustomer adopts the unified time contextUsing now := clock.Now().UTC() and passing it to withSubjects/withSubscription keeps results consistent.
68-70: PlanKey filter may not match the loaded subscription edgeWhen 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
Overview
Fix
Customerlookup by usgae attribution whereCustomerwas returned even if theSubjectassignement was already deleted.Also make sure to return
Customerif the assignement is deleted in the future which is mostly useful for "time-travel" in testing.Summary by CodeRabbit
New Features
Bug Fixes
Refactor