Skip to content

feat: CustomerEntitlements - #3255

Merged
GAlexIHU merged 16 commits into
mainfrom
feat/entitlement-api-v2-3
Sep 1, 2025
Merged

GAlexIHU merged 16 commits into
mainfrom
feat/entitlement-api-v2-3

Conversation

@GAlexIHU

@GAlexIHU GAlexIHU commented Aug 21, 2025 •

Copy link
Copy Markdown
Contributor

DO NOT MERGE TO TARGET! Should be consolidated / merged with other "deploy-day" changes

Overview

Changes

  • keeps subjects
  • re-link entitlements to customers (try migration on dataset before running)
  • rewrite meteredentitlement.Connector, entitlement.Connector and entitlement.EntitlementRepo interface methods to use customer-like params (e.g. customerId) instead of subjectKey
  • introduce practice (not-documented) on how to handle publishing new event versions (e.g. openmeter/entitlement/events_v2)
  • add new event versions for entitlement events (lifecycle + snapshot events). register handlers for new versions + touch up service methods to support both versions for now

Implementation

  • old subject APIs resolve subjectKey to Customer in handlers then pass ID to new entitlement service methods
  • EntilementRepo loads Subject and Customer edges for all methods that return Entitlements (WithSubject & WithCustomer). Due to how ent works, these result in sequential SELECT * WHERE id IN (...) queries, which can have a performance impact. I suggest we address this if we see an issue.
  • OSS OpenMeter doesn't yet automatically provision Subjects for Customers and vice-versa (might change after branch collapse with @chrisgacsal), so tests were updated to provision both manually. Proper errors are returned if this expectation fails

On Event Versioning

  • events (system and otherwise) should strive to use literal values (composed of primitives) instead of embedding domain models
  • this allows incrementally migrating new versions (as two subsequent versions can always be compatible with the domain model & functionality)
  • apart from migration we should always strive to use a single version at a time
  • as we're OSS, we shouldn't get rid of old handlers without deprecation notice / migration guide (though realistically events drain fast, upgrade paths of our OSS users are unknown to us)
  • mapping methods between event literals & domain models will eventually become impossible, thats a good sign for deprecation notice

TODO

  • implement unimplemented CustomerEntitlement handlers in V2 httpdriver
  • prepare PR in openmeter/cloud that uses the new APIs

After the fact

  • Cleanup task after old event versions are drained: OM-1508

Summary by CodeRabbit

  • New Features

    • Customer-centric Entitlements V2: create/list/get/delete/override entitlements, paginated metered grants, entitlement history, grant creation, and usage reset endpoints; V1 customer entitlement value endpoint.
  • Documentation

    • API/JSDoc note: using featureKey resolves entitlement at the current timestamp.
  • Tests

    • New e2e suites and unit tests for V2 customer flows, parity checks vs V1, and updated helpers.
  • Refactor

    • Large migration from subject-key to customer-centric model (DB edges, APIs, events/v2, snapshots, notifications, handlers, and signatures).
  • Chores

    • Makefile target to run slow e2e tests (etoe-slow).

@coderabbitai

coderabbitai Bot commented Aug 21, 2025 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

Reorients entitlements from a subject-key model to a customer-centric model across schema, repo, services, drivers, balance-worker, events, notifications, OpenAPI/clients and tests; adds V2 customer entitlement HTTP handlers and many related API/type/signature changes.

Changes

Cohort / File(s) Summary
OpenAPI & Generated Clients
api/api.gen.go, api/client/go/client.gen.go, api/client/javascript/src/*, api/openapi.yaml, api/openapi.cloud.yaml, api/spec/src/entitlements/v2/customer.tsp
Regenerated embedded swagger/spec and clients; small JSDoc/OpenAPI description additions noting timestamp resolution when featureKey is used.
DB schema & ent codegen
openmeter/ent/schema/*, openmeter/ent/db/..., openmeter/ent/db/migrate/schema.go, openmeter/ent/db/runtime.go, openmeter/ent/db/*_{create,query,update}.go
Add customer_id column and customer↔entitlement edge; update FKs/indexes, predicates, ordering helpers, loaders, create/update edge wiring and generated mutation APIs.
Entitlement repo & model
openmeter/entitlement/*.go, openmeter/entitlement/repository.go, openmeter/entitlement/errors.go, openmeter/entitlement/uniqueness*.go
Shift create inputs from SubjectKey → UsageAttribution; add validation/error (ErrEntitlementCreatePropertyMismatch); rename repo methods to customer-centric variants and adapt uniqueness checks to customer IDs.
Adapters / connectors / services
openmeter/entitlement/adapter/*, openmeter/entitlement/*/connector.go, openmeter/entitlement/metered/*, openmeter/entitlement/service/*, openmeter/credit/*
Make entitlement/grant flows customer-scoped: resolve customer from subject where needed, change many connector signatures to accept customerID and UsageAttribution, update lock keys, scheduling, grant creation/listing and grant mapping.
HTTP drivers & v2 handlers
openmeter/entitlement/driver/*.go, openmeter/entitlement/driver/v2/*
v1 drivers now accept customer + subject services and resolve subject→customer; parser uses UsageAttribution; added exported error encoder; new v2 customer entitlement handlers, params and ParserV2 mapping implemented.
Balance worker, recalculator & jobs wiring
app/common/openmeter_balanceworker.go, cmd/balance-worker/wire_gen.go, cmd/jobs/*, openmeter/entitlement/balanceworker/*
Wire customerService into worker options and jobs; recalculator caches customer+subject composite; repo method renames (ListEntitlementsAffectedByIngestEvents) and handler changes to resolve customer+subject and emit unified snapshot events.
Credit grants & events
openmeter/credit/*, openmeter/entitlement/metered/*
Introduce versioned grant events (v2) and factories; owner now carries StreamingCustomer; GrantFromCreditGrant becomes time-aware; add ListGrantsV2 endpoint and customer-scoped grant flows.
Notifications & consumers
openmeter/notification/*, openmeter/notification/httpdriver/mapping.go
Payloads now include Customer as a value (non-pointer), add customer annotations, update consumers and mappings to include customer metadata.
Router, server & tests wiring
openmeter/server/router/*.go, openmeter/server/server_test.go, test/**, e2e/*
Add V2 customer entitlement routes and handler wiring; inject customer/subject services into handlers; extensive test/e2e refactors: CreateCustomerWithSubject helper, UsageAttribution usage, test dependency wiring and updated assertions.
Streaming, snapshot & utilities
openmeter/streaming/query_params.go, openmeter/entitlement/snapshot/*, openmeter/subscription/subscriptionspec.go
Add CustomerUsageAttribution.Equal; snapshots now carry Customer value and NewSnapshotEvent constructor; subscription spec uses UsageAttribution.
Entitlement migrations & tests
openmeter/ent/schema/entitlement.go, openmeter/entitlement/repository.go, tools/migrate/*.go
Entitlement schema adds customer_id, reorders fields/indexes and edge definition; migration tests added/expanded to backfill and validate customer_id.
Miscellaneous
app/common/customer.go, openmeter/customer/*, openmeter/notification/annotations.go, openmeter/entitlement/validators/customer/validator.go, Makefile
Add customer-related errors/annotations, adjust validators and constructor signatures, add Makefile target for slow e2e tests, small comment/import updates.

Estimated code review effort

🎯 5 (Critical) | ⏱️ ~120+ 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 feat/entitlement-api-v2-3

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 @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai 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:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai 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 @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore or @coderabbit ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @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.

@GAlexIHU
GAlexIHU changed the base branch from main to feat/entitlement-api-v2-wrappers August 26, 2025 09:36
@GAlexIHU
GAlexIHU force-pushed the feat/entitlement-api-v2-wrappers branch from 8b1aa47 to 8a16af5 Compare August 26, 2025 10:33
@GAlexIHU
GAlexIHU force-pushed the feat/entitlement-api-v2-3 branch 2 times, most recently from f8ebcb7 to d73146d Compare August 26, 2025 11:55
@GAlexIHU GAlexIHU added the release-note/feature Release note: Exciting New Features label Aug 26, 2025
@GAlexIHU
GAlexIHU force-pushed the feat/entitlement-api-v2-3 branch from d73146d to e4f1379 Compare August 26, 2025 12:21
@GAlexIHU GAlexIHU changed the title Entitlement - Customer rewrite feat: CustomerEntitlements Aug 26, 2025
@GAlexIHU
GAlexIHU marked this pull request as ready for review August 26, 2025 12:50
@GAlexIHU
GAlexIHU requested a review from a team as a code owner August 26, 2025 12:50
@GAlexIHU
GAlexIHU force-pushed the feat/entitlement-api-v2-wrappers branch from 8a16af5 to de2457d Compare August 26, 2025 14:55
@GAlexIHU
GAlexIHU force-pushed the feat/entitlement-api-v2-3 branch 2 times, most recently from 1e997f7 to 5b956f8 Compare August 27, 2025 13:12
@GAlexIHU
GAlexIHU force-pushed the feat/entitlement-api-v2-wrappers branch from e9626c4 to 00c563b Compare August 27, 2025 13:51
Base automatically changed from feat/entitlement-api-v2-wrappers to main August 27, 2025 14:01
@GAlexIHU
GAlexIHU force-pushed the feat/entitlement-api-v2-3 branch from 5b956f8 to 44f6589 Compare September 1, 2025 13:53

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

Caution

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

⚠️ Outside diff range comments (20)
openmeter/entitlement/uniqueness.go (1)

37-41: Nil-deref risk when grouping by e.Customer.ID; group by CustomerID and fix error text.

If e.Customer is nil, this panics. Prefer the scalar ID (doesn’t require the edge) and adjust the message to “customer”.

Apply:

- if grouped := lo.GroupBy(ents, func(e Entitlement) string { return e.Customer.ID }); len(grouped) > 1 {
+ if grouped := lo.GroupBy(ents, func(e Entitlement) string { return e.CustomerID }); len(grouped) > 1 {
   keys := lo.Keys(grouped)
   slices.Sort(keys)
-  return fmt.Errorf("entitlements must belong to the same subject, found %v", keys)
+  return fmt.Errorf("entitlements must belong to the same customer, found %v", keys)
 }

If Entitlement does not expose CustomerID, add a guard before grouping:

for _, e := range ents {
	if e.Customer == nil || e.Customer.ID == "" {
		return fmt.Errorf("entitlement %s must reference a customer", e.ID)
	}
}
openmeter/entitlement/metered/balance_test.go (2)

61-64: Use clock.Now() (not time.Now()) to respect frozen time

time.Now() ignores clock.SetTime and will flake periods when tests freeze time.

Apply this diff in both helpers:

- currentUsagePeriod, err := input.UsagePeriod.GetValue().GetPeriodAt(time.Now())
+ currentUsagePeriod, err := input.UsagePeriod.GetValue().GetPeriodAt(clock.Now())

Also applies to: 619-622


579-581: Parallel subtests mutate global clock — race/flaky

t.Parallel() + clock.SetTime/ResetTime across cases will interfere. Run these sequentially or gate parallelization.

Minimal fix:

-            t.Parallel()
+            // Avoid parallelization: tests below mutate global clock.

Alternative: add a shouldParallel flag per case and only call t.Parallel() when true.

Also applies to: 1190-1192, 235-237, 481-482, 348-349, 298-299

openmeter/entitlement/service/utils_test.go (1)

89-89: Rename test helper for correct spelling
Rename setupDependecies in openmeter/entitlement/service/utils_test.go to setupDependencies and update its usages in access_test.go and scheduling_test.go to match.

openmeter/notification/consumer/entitlementreset.go (1)

66-78: Bug: duplicate-prevention queries ignore event type

Currently any event in the period suppresses creating a reset event. Filter by EntitlementReset to avoid false positives.

Apply:

 lastEvents, err := b.Notification.ListEvents(ctx, notification.ListEventsInput{
   Page: pagination.Page{
     PageSize:   1,
     PageNumber: 1,
   },
   Namespaces: []string{event.Namespace.ID},
+  Types:      []notification.EventType{notification.EventTypeEntitlementReset},
   From: event.Entitlement.CurrentUsagePeriod.From,
   To:   event.Entitlement.CurrentUsagePeriod.To,
   OrderBy: notification.OrderByCreatedAt,
   Order:   sortx.OrderDesc,
 })

If ListEventsInput doesn’t support Types, add it or post-filter by type.

openmeter/entitlement/balanceworker/ingesthandler.go (1)

31-37: Avoid shadowing 'event' to prevent confusion and subtle bugs

The short var declaration reuses the identifier 'event', then immediately references 'event.StoredAt' and 'event.RawEvents' from the outer scope. It compiles but is easy to misread and error-prone.

Apply this refactor to make intent explicit and remove shadowing:

-func (w *Worker) handleBatchedIngestEvent(ctx context.Context, event ingestevents.EventBatchedIngest) error {
+func (w *Worker) handleBatchedIngestEvent(ctx context.Context, ingest ingestevents.EventBatchedIngest) error {
   affectedEntitlements, err := w.opts.Repo.ListEntitlementsAffectedByIngestEvents(ctx,
     []IngestEventQueryFilter{
       {
-        Namespace:    event.Namespace.ID,
-        EventSubject: event.SubjectKey,
-        MeterSlugs:   event.MeterSlugs,
+        Namespace:    ingest.Namespace.ID,
+        EventSubject: ingest.SubjectKey,
+        MeterSlugs:   ingest.MeterSlugs,
       },
     })
   if err != nil {
     return fmt.Errorf("failed to list affected entitlements: %w", err)
   }

   var errs []error

   for _, ent := range affectedEntitlements {
-    event, err := w.handleEntitlementEvent(
+    pubEvent, err := w.handleEntitlementEvent(
       ctx,
       pkgmodels.NamespacedID{Namespace: ent.Namespace, ID: ent.EntitlementID},
       WithSource(metadata.ComposeResourcePath(ent.Namespace, metadata.EntityEvent)),
-      WithEventAt(event.StoredAt),
-      WithRawIngestedEvents(event.RawEvents),
+      WithEventAt(ingest.StoredAt),
+      WithRawIngestedEvents(ingest.RawEvents),
     )
     if err != nil {
       errs = append(errs, fmt.Errorf("handling entitlement event for %s: %w", ent.EntitlementID, err))
       continue
     }

-    if err = w.opts.EventBus.Publish(ctx, event); err != nil {
-      errs = append(errs, fmt.Errorf("handling entitlement event for %s: %w", ent.EntitlementID, err))
+    if err = w.opts.EventBus.Publish(ctx, pubEvent); err != nil {
+      errs = append(errs, fmt.Errorf("publishing entitlement event for %s: %w", ent.EntitlementID, err))
     }
   }
openmeter/entitlement/snapshot/event.go (1)

91-106: Fix subject path when Customer.ID is empty (broken metadata).

Else-branch still uses e.Customer.ID even when it’s empty, yielding .../customer/ paths. Fall back to subject-only path (or no subject) when customer is unset.

Apply:

 func (e SnapshotEvent) EventMetadata() metadata.EventMetadata {
-	if e.Customer.ID != "" {
-		return metadata.EventMetadata{
-			Subject: metadata.ComposeResourcePath(
-				e.Namespace.ID,
-				metadata.EntityCustomer, e.Customer.ID,
-				metadata.EntitySubjectKey, e.Subject.Key,
-			),
-		}
-	}
-
-	return metadata.EventMetadata{
-		Source:  metadata.ComposeResourcePath(e.Namespace.ID, metadata.EntityEntitlement, e.Entitlement.ID),
-		Subject: metadata.ComposeResourcePath(e.Namespace.ID, metadata.EntityCustomer, e.Customer.ID),
-	}
+	if e.Customer.ID != "" {
+		return metadata.EventMetadata{
+			Subject: metadata.ComposeResourcePath(
+				e.Namespace.ID,
+				metadata.EntityCustomer, e.Customer.ID,
+				metadata.EntitySubjectKey, e.Subject.Key,
+			),
+		}
+	}
+	if e.Subject.Key != "" {
+		return metadata.EventMetadata{
+			Source:  metadata.ComposeResourcePath(e.Namespace.ID, metadata.EntityEntitlement, e.Entitlement.ID),
+			Subject: metadata.ComposeResourcePath(e.Namespace.ID, metadata.EntitySubjectKey, e.Subject.Key),
+		}
+	}
+	return metadata.EventMetadata{
+		Source: metadata.ComposeResourcePath(e.Namespace.ID, metadata.EntityEntitlement, e.Entitlement.ID),
+	}
 }
openmeter/entitlement/metered/lateevents_test.go (1)

251-254: Recompute CurrentUsagePeriod after modifying UsagePeriod

You change UsagePeriod to monthly after computing CurrentUsagePeriod (computed for yearly). This can desync persisted period boundaries and cause flaky results.

Apply after setting inp.UsagePeriod:

 inp.UsagePeriod = lo.ToPtr(entitlement.NewUsagePeriodInputFromRecurrence(timeutil.Recurrence{
   Anchor:   inp.UsagePeriod.GetValue().Anchor,
   Interval: timeutil.RecurrencePeriodMonth,
 }))
+// Recompute current period to match the updated UsagePeriod
+cp2, err := inp.UsagePeriod.GetValue().GetPeriodAt(clock.Now())
+require.NoError(t, err)
+inp.CurrentUsagePeriod = &cp2
openmeter/entitlement/metered/reset_test.go (3)

37-58: Use clock.Now() for deterministic CurrentUsagePeriod

time.Now() makes tests time-dependent and can misalign with other uses of clock. Use clock.Now().

- currentUsagePeriod, err := input.UsagePeriod.GetValue().GetPeriodAt(time.Now()) // This should be calculated properly when testing batch resets
+ currentUsagePeriod, err := input.UsagePeriod.GetValue().GetPeriodAt(clock.Now()) // Deterministic with test clock

949-973: Reset the test clock after time travel

This test sets the clock twice but never resets it. Add defer to avoid leaking state across cases.

   // Let's time-travel to the start time so resources have existed for a while
   clock.SetTime(entitlementTime)
+  defer clock.ResetTime()

692-693: Update ResetMaxRollover comment
In reset_test.go (line 692) ResetMaxRollover: 0 means no rollover (balance resets to zero), not “full amount can be rolled over”—update the comment accordingly.

openmeter/entitlement/driver/parser.go (1)

212-339: Update ParseAPICreateInput calls in entitlement.go to pass real usageAttribution

  • In openmeter/entitlement/driver/entitlement.go (lines 91 and 155), you’re still passing streaming.CustomerUsageAttribution{}. Replace these with the actual usageAttribution value (e.g. extracted from the subject key or handler context).
  • Calls in driver/v2/customer.go already provide cus.GetUsageAttribution() and require no change.
e2e/e2e_test.go (1)

1209-1211: Wrong response checked after OverrideEntitlement call.
You’re asserting on resp (create) instead of resp2 (override), masking failures.

Apply this diff:

-        require.Equal(t, http.StatusCreated, resp.StatusCode(), "Invalid status code [response_body=%s]", string(resp.Body))
+        require.Equal(t, http.StatusCreated, resp2.StatusCode(), "Invalid status code [response_body=%s]", string(resp2.Body))
openmeter/entitlement/balanceworker/entitlementhandler.go (1)

274-308: Use customer ID safely and default the event source when missing.

  • Guard against missing Customer edge before calling GetEntitlementValue.
  • If opts.source is empty, default to the entitlement resource path (mirrors delete path).
 func (w *Worker) createSnapshotEvent(ctx context.Context, entitlementEntity *entitlement.Entitlement, calculatedAt time.Time, opts handleEntitlementEventOptions) (marshaler.Event, error) {
   feat, err := w.opts.Entitlement.Feature.GetFeature(ctx, entitlementEntity.Namespace, entitlementEntity.FeatureID, feature.IncludeArchivedFeatureTrue)
   if err != nil {
     return nil, fmt.Errorf("failed to get feature: %w", err)
   }

   calculationStart := time.Now()

-  value, err := w.opts.Entitlement.Entitlement.GetEntitlementValue(ctx, entitlementEntity.Namespace, entitlementEntity.Customer.ID, entitlementEntity.ID, calculatedAt)
+  if entitlementEntity.Customer == nil || entitlementEntity.Customer.ID == "" {
+    return nil, fmt.Errorf("entitlement missing loaded Customer: expected Customer edge with ID")
+  }
+  value, err := w.opts.Entitlement.Entitlement.GetEntitlementValue(ctx, entitlementEntity.Namespace, entitlementEntity.Customer.ID, entitlementEntity.ID, calculatedAt)
   if err != nil {
     return nil, fmt.Errorf("failed to get entitlement value: %w", err)
   }
@@
-  return w.snapshotToEvent(ctx, snapshotToEventInput{
+  src := opts.source
+  if src == "" {
+    src = metadata.ComposeResourcePath(entitlementEntity.Namespace, metadata.EntityEntitlement, entitlementEntity.ID)
+  }
+  return w.snapshotToEvent(ctx, snapshotToEventInput{
     Entitlement:       entitlementEntity,
     Feature:           feat,
     Value:             convert.ToPointer((snapshot.EntitlementValue)(mappedValues)),
     CalculatedAt:      calculatedAt,
-    Source:            opts.source,
+    Source:            src,
     OverrideOperation: opts.sourceOperation,
   })
 }
openmeter/entitlement/entitlement.go (2)

193-205: Relax SubjectKeys requirement for non-metered types (avoid breaking static/boolean).

Only metered entitlements strictly need subject keys.

Apply this diff:

   if c.UsageAttribution.ID == "" {
     return fmt.Errorf("usage attribution must have an id")
   }
-
-  if len(c.UsageAttribution.SubjectKeys) == 0 {
-    return fmt.Errorf("usage attribution must have at least one subject key")
-  }
+  if c.EntitlementType == EntitlementTypeMetered && len(c.UsageAttribution.SubjectKeys) == 0 {
+    return fmt.Errorf("usage attribution must have at least one subject key for metered entitlements")
+  }

250-267: Avoid pointers to empty strings and potential nil-method call.

  • Don’t set FeatureID/FeatureKey when empty; use nil.
  • Guard UsagePeriod before calling GetOriginalValueAsUsagePeriodInput().

Apply this diff:

-  i := CreateEntitlementInputs{
-    Namespace:        e.Namespace,
-    FeatureID:        &e.FeatureID,
-    FeatureKey:       &e.FeatureKey,
-    UsageAttribution: e.Customer.GetUsageAttribution(),
-    EntitlementType:  e.EntitlementType,
-    Metadata:         e.Metadata,
-    ActiveFrom:       e.ActiveFrom,
-    ActiveTo:         e.ActiveTo,
-    // MeasureUsageFrom:        &MeasureUsageFromInput{ts: e.MeasureUsageFrom},
-    IssueAfterReset:         e.IssueAfterReset,
-    IssueAfterResetPriority: eIssueAfterResetPriority,
-    IsSoftLimit:             e.IsSoftLimit,
-    Config:                  e.Config,
-    UsagePeriod:             e.UsagePeriod.GetOriginalValueAsUsagePeriodInput(),
-    PreserveOverageAtReset:  e.PreserveOverageAtReset,
-    Annotations:             e.Annotations,
-  }
+  i := CreateEntitlementInputs{
+    Namespace:        e.Namespace,
+    UsageAttribution: e.Customer.GetUsageAttribution(),
+    EntitlementType:  e.EntitlementType,
+    Metadata:         e.Metadata,
+    ActiveFrom:       e.ActiveFrom,
+    ActiveTo:         e.ActiveTo,
+    // MeasureUsageFrom:        &MeasureUsageFromInput{ts: e.MeasureUsageFrom},
+    IssueAfterReset:         e.IssueAfterReset,
+    IssueAfterResetPriority: e.IssueAfterResetPriority,
+    IsSoftLimit:             e.IsSoftLimit,
+    Config:                  e.Config,
+    PreserveOverageAtReset:  e.PreserveOverageAtReset,
+    Annotations:             e.Annotations,
+  }
+  if e.FeatureID != "" {
+    i.FeatureID = &e.FeatureID
+  }
+  if e.FeatureKey != "" {
+    i.FeatureKey = &e.FeatureKey
+  }
@@
   if e.MeasureUsageFrom != nil {
     mu := &MeasureUsageFromInput{}
     // FIXME: manage error
     _ = mu.FromTime(*e.MeasureUsageFrom)
     i.MeasureUsageFrom = mu
   }
+  if e.UsagePeriod != nil {
+    i.UsagePeriod = e.UsagePeriod.GetOriginalValueAsUsagePeriodInput()
+  }

Also applies to: 269-276

openmeter/entitlement/connector.go (1)

52-66: Update NoopEntitlementConnector tests to use customerID parameter

  • openmeter/server/server_test.go:714 – change GetEntitlementValue(ctx, namespace, subjectKey string, …) to use customerID string
  • openmeter/server/server_test.go:718 – change GetEntitlementsOfCustomer(ctx, namespace, subjectKey string, …) to use customerID string
  • openmeter/server/server_test.go:730 – remove or revise the obsolete GetAccess(ctx, namespace, subjectKey) stub to align with the updated Connector interface
openmeter/server/router/entitlement.go (1)

70-75: Forward query params to ListEntitlementGrants handler.

Currently params are ignored. Pass them through.

 func (a *Router) ListEntitlementGrants(w http.ResponseWriter, r *http.Request, subjectIdOrKey string, entitlementIdOrFeatureKey string, params api.ListEntitlementGrantsParams) {
 	a.meteredEntitlementHandler.ListEntitlementGrants().With(entitlementdriver.ListEntitlementGrantsHandlerParams{
 		SubjectKey:                subjectIdOrKey,
 		EntitlementIdOrFeatureKey: entitlementIdOrFeatureKey,
+		Params:                    params,
 	}).ServeHTTP(w, r)
 }
openmeter/entitlement/adapter/entitlement.go (2)

87-126: Adapter method name/signature mismatch with driver + cannot resolve by ID or feature key

Driver calls GetEntitlementOfCustomerAt(idOrKey), but the adapter exposes GetActiveEntitlementOfCustomerAt(featureKey). This will break interface conformance and prevents resolving by entitlement ID. Update the method name/signature and allow matching by either ID or feature key.

Apply this diff:

-func (a *entitlementDBAdapter) GetActiveEntitlementOfCustomerAt(ctx context.Context, namespace string, customerID string, featureKey string, at time.Time) (*entitlement.Entitlement, error) {
+func (a *entitlementDBAdapter) GetEntitlementOfCustomerAt(ctx context.Context, namespace string, customerID string, entitlementIdOrFeatureKey string, at time.Time) (*entitlement.Entitlement, error) {
   return entutils.TransactingRepo(
     ctx,
     a,
     func(ctx context.Context, repo *entitlementDBAdapter) (*entitlement.Entitlement, error) {
       res, err := withAllUsageResets(repo.db.Entitlement.Query(), []string{namespace}).
         WithCustomer(func(q *db.CustomerQuery) {
           q.WithSubjects(func(csq *db.CustomerSubjectsQuery) {
             csq.Where(customersubjectsdb.DeletedAtIsNil())
           })
         }).
         WithSubject().
         Where(EntitlementActiveAt(at)...).
         Where(
           db_entitlement.Or(db_entitlement.DeletedAtGT(at), db_entitlement.DeletedAtIsNil()),
           db_entitlement.HasCustomerWith(
             customerdb.Namespace(namespace),
             customerNotDeletedAt(at),
             customerdb.ID(customerID),
           ),
           db_entitlement.Namespace(namespace),
-          db_entitlement.FeatureKey(featureKey),
+          db_entitlement.Or(
+            db_entitlement.ID(entitlementIdOrFeatureKey),
+            db_entitlement.FeatureKey(entitlementIdOrFeatureKey),
+          ),
         ).
         First(ctx) // FIXME: to better enforce consistency we should not use .First() but assert that there is only one result!
       if err != nil {
         if db.IsNotFound(err) {
           return nil, &entitlement.NotFoundError{
             EntitlementID: models.NamespacedID{
               Namespace: namespace,
-              ID:        featureKey,
+              ID:        entitlementIdOrFeatureKey,
             },
           }
         }
         return nil, err
       }

       return repo.mapEntitlementEntity(res)
     },
   )
 }

503-556: Do not swallow customer mapping errors; prevents nil deref downstream

mapEntitlementEntity ignores CustomerFromDBEntity errors, leaving ent.Customer nil. Several drivers dereference ent.Customer unconditionally, causing panics.

Apply this diff:

 func (a *entitlementDBAdapter) mapEntitlementEntity(e *db.Entitlement) (*entitlement.Entitlement, error) {
   if e.Edges.Subject == nil {
     return nil, fmt.Errorf("entitlement %s has no subject", e.ID)
   }

   if e.Edges.Customer == nil {
     return nil, fmt.Errorf("entitlement %s has no customer", e.ID)
   }

   if err := a.validateSubjectKeysMatch(e); err != nil {
     return nil, err
   }
@@
-  if mapped, mapErr := customeradapter.CustomerFromDBEntity(*e.Edges.Customer); mapErr == nil {
-    ent.Customer = mapped
-  }
+  mapped, mapErr := customeradapter.CustomerFromDBEntity(*e.Edges.Customer)
+  if mapErr != nil {
+    return nil, fmt.Errorf("failed to map customer for entitlement %s: %w", e.ID, mapErr)
+  }
+  ent.Customer = mapped

Comment thread e2e/config.yaml Resolved
Comment thread e2e/entitlement_test.go Resolved
Comment thread openmeter/credit/adapter/grant.go Resolved
Comment thread openmeter/credit/grant.go Resolved
Comment thread openmeter/credit/grant/events_2.go Resolved
Comment thread openmeter/streaming/query_params.go Resolved

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

♻️ Duplicate comments (1)
openmeter/entitlement/driver/v2/customer_metered.go (1)

50-55: Bug: request Params are dropped; client pagination/sorting ignored.
The builder doesn’t propagate params.Params, yet the handler reads request.Params. Same issue as previously flagged.

 			return ListCustomerEntitlementGrantsHandlerRequest{
 				CustomerIDOrKey:           params.CustomerIDOrKey,
 				EntitlementIdOrFeatureKey: params.EntitlementIdOrFeatureKey,
 				Namespace:                 ns,
+				Params:                    params.Params,
 			}, nil
🧹 Nitpick comments (6)
openmeter/entitlement/driver/v2/handler.go (1)

24-31: Add interface conformance check to catch wiring regressions at compile-time.
A lightweight assert helps detect missing method implementations if the interface changes.

 type customerEntitlementHandler struct {
 	namespaceDecoder namespacedriver.NamespaceDecoder
 	options          []httptransport.HandlerOption
 	connector        entitlement.Connector
 	balanceConnector meteredentitlement.Connector
 	customerService  customer.Service
 }
 
+// Ensure customerEntitlementHandler implements CustomerEntitlementHandler
+var _ CustomerEntitlementHandler = (*customerEntitlementHandler)(nil)
openmeter/entitlement/driver/v2/customer_metered.go (3)

70-76: Honor limit/offset when provided; otherwise fall back to page/pageSize.
Current code ignores Offset/Limit in API params. Prefer limit/offset if present to match client intent.

-				Page: pagination.NewPage(
-					lo.FromPtrOr(request.Params.Page, 1),
-					lo.FromPtrOr(request.Params.PageSize, 100),
-				),
+				Page: func() pagination.Page {
+					// Prefer limit/offset if either is set
+					if request.Params.Limit != nil || request.Params.Offset != nil {
+						limit := lo.FromPtrOr(request.Params.Limit, 100)
+						offset := lo.FromPtrOr(request.Params.Offset, 0)
+						// page is 1-based
+						return pagination.NewPage(offset/limit+1, limit)
+					}
+					return pagination.NewPage(
+						lo.FromPtrOr(request.Params.Page, 1),
+						lo.FromPtrOr(request.Params.PageSize, 100),
+					)
+				}(),

145-172: Default EffectiveAt to now to avoid zero-time grants; use same anchor default.
If EffectiveAt is omitted, zero time leaks into storage and recurrence anchor. Default to clock.Now().

-			grantInput := meteredentitlement.CreateEntitlementGrantInputs{
+			effectiveAt := defaultx.WithDefault(body.EffectiveAt, clock.Now())
+			grantInput := meteredentitlement.CreateEntitlementGrantInputs{
 				CreateGrantInput: credit.CreateGrantInput{
 					Amount:      body.Amount,
 					Priority:    defaultx.WithDefault(body.Priority, 0),
-					EffectiveAt: body.EffectiveAt,
+					EffectiveAt: effectiveAt,
 					Expiration: grant.ExpirationPeriod{
 						Count:    body.Expiration.Count,
 						Duration: grant.ExpirationPeriodDuration(body.Expiration.Duration),
 					},
 					ResetMaxRollover: defaultx.WithDefault(body.MaxRolloverAmount, 0),
 					ResetMinRollover: defaultx.WithDefault(body.MinRolloverAmount, 0),
 				},
 			}
@@
-				grantInput.Recurrence = &timeutil.Recurrence{
+				grantInput.Recurrence = &timeutil.Recurrence{
 					Interval: iv,
-					Anchor:   defaultx.WithDefault(body.Recurrence.Anchor, body.EffectiveAt),
+					Anchor:   defaultx.WithDefault(body.Recurrence.Anchor, effectiveAt),
 				}

325-327: Prefer struct{} for empty 204 responses.
Slightly clearer intent and avoids interface{} allocations.

-	ResetCustomerEntitlementUsageHandlerResponse = interface{}
+	ResetCustomerEntitlementUsageHandlerResponse = struct{}
openmeter/credit/driver/grant.go (2)

265-271: Pagination toggle logic is fine; document precedence.

When any of page/pageSize is set, limit/offset are ignored. Consider noting this in the API docs to avoid ambiguity.


299-312: Error mapping parity with v1 retained.

Optional: map customer-not-found errors to 404 if customer lookup fails during subject-key derivation.

-			httptransport.WithErrorEncoder(func(ctx context.Context, err error, w http.ResponseWriter, _ *http.Request) bool {
+			httptransport.WithErrorEncoder(func(ctx context.Context, err error, w http.ResponseWriter, _ *http.Request) bool {
 				if models.IsGenericValidationError(err) {
 					commonhttp.NewHTTPError(
 						http.StatusBadRequest,
 						err,
 					).EncodeError(ctx, w)
 					return true
 				}
+				// if errors.Is(err, customer.ErrCustomerNotFound) { // adjust to actual type
+				// 	commonhttp.NewHTTPError(http.StatusNotFound, err).EncodeError(ctx, w)
+				// 	return true
+				// }
 				return commonhttp.HandleErrorIfTypeMatches[*pagination.InvalidError](ctx, http.StatusBadRequest, err, w)
 			}),

Please confirm the concrete not-found error type in customer service.

📜 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 44f6589 and 3c57efd.

📒 Files selected for processing (6)
  • openmeter/credit/driver/grant.go (4 hunks)
  • openmeter/entitlement/driver/v2/customer_metered.go (1 hunks)
  • openmeter/entitlement/driver/v2/handler.go (1 hunks)
  • openmeter/server/router/credit.go (1 hunks)
  • openmeter/server/router/entitlement.go (4 hunks)
  • openmeter/server/router/router.go (5 hunks)
🧰 Additional context used
🧬 Code graph analysis (6)
openmeter/server/router/credit.go (1)
openmeter/credit/driver/grant.go (1)
  • ListGrantsV2HandlerParams (227-229)
openmeter/server/router/router.go (2)
openmeter/entitlement/driver/v2/handler.go (2)
  • CustomerEntitlementHandler (12-22)
  • NewCustomerEntitlementHandler (32-46)
pkg/framework/transport/httptransport/options.go (1)
  • WithErrorHandler (29-33)
openmeter/credit/driver/grant.go (7)
pkg/framework/transport/httptransport/options.go (3)
  • HandlerOption (19-21)
  • AppendOptions (81-83)
  • WithErrorEncoder (35-39)
openmeter/credit/grant/repo.go (3)
  • Repo (71-82)
  • ListParams (42-55)
  • OrderBy (15-15)
openmeter/entitlement/metered/entitlement_grant.go (2)
  • GrantFromCreditGrant (141-155)
  • EntitlementGrant (126-139)
pkg/clock/clock.go (1)
  • Now (14-21)
openmeter/entitlement/driver/metered.go (1)
  • MapEntitlementGrantToAPI (427-458)
openmeter/customer/customer.go (2)
  • GetCustomerInput (247-254)
  • CustomerIDOrKey (130-133)
pkg/convert/ptr.go (1)
  • DerefHeaderPtr (59-64)
openmeter/server/router/entitlement.go (5)
openmeter/server/router/router.go (1)
  • Router (218-244)
api/api.gen.go (3)
  • ULIDOrExternalKey (7218-7218)
  • ListCustomerEntitlementsV2Params (8606-8634)
  • ListCustomerEntitlementGrantsV2Params (8637-8665)
openmeter/entitlement/driver/entitlement.go (1)
  • GetEntitlementByIdHandlerParams (472-474)
openmeter/entitlement/driver/v2/customer.go (4)
  • ListCustomerEntitlementsHandlerParams (88-91)
  • GetCustomerEntitlementHandlerParams (184-187)
  • DeleteCustomerEntitlementHandlerParams (242-245)
  • OverrideCustomerEntitlementHandlerParams (299-302)
openmeter/entitlement/driver/v2/customer_metered.go (4)
  • ListCustomerEntitlementGrantsHandlerParams (27-31)
  • CreateCustomerEntitlementGrantHandlerParams (105-108)
  • GetCustomerEntitlementHistoryHandlerParams (201-205)
  • ResetCustomerEntitlementUsageHandlerParams (314-317)
openmeter/entitlement/driver/v2/handler.go (4)
openmeter/entitlement/driver/v2/customer.go (5)
  • CreateCustomerEntitlementHandler (26-26)
  • ListCustomerEntitlementsHandler (94-94)
  • GetCustomerEntitlementHandler (196-196)
  • DeleteCustomerEntitlementHandler (254-254)
  • OverrideCustomerEntitlementHandler (312-312)
openmeter/entitlement/driver/v2/customer_metered.go (4)
  • ListCustomerEntitlementGrantsHandler (39-39)
  • CreateCustomerEntitlementGrantHandler (116-116)
  • GetCustomerEntitlementHistoryHandler (213-213)
  • ResetCustomerEntitlementUsageHandler (326-326)
pkg/framework/transport/httptransport/options.go (1)
  • HandlerOption (19-21)
openmeter/entitlement/metered/connector.go (1)
  • Connector (33-45)
openmeter/entitlement/driver/v2/customer_metered.go (10)
openmeter/customer/customer.go (2)
  • CustomerIDOrKey (130-133)
  • GetCustomerInput (247-254)
api/api.gen.go (15)
  • ListCustomerEntitlementGrantsV2Params (8637-8665)
  • GrantPaginatedResponse (3551-3563)
  • ListEntitlementGrantsParams (8549-8552)
  • EntitlementGrant (2770-2825)
  • EntitlementGrantCreateInput (2828-2859)
  • ExpirationPeriod (3263-3269)
  • Metadata (4763-4763)
  • GetCustomerEntitlementHistoryV2Params (8668-8681)
  • WindowedBalanceHistory (7431-7440)
  • WindowSize (7428-7428)
  • BalanceHistoryWindow (1137-1146)
  • Period (5612-5618)
  • GrantBurnDownHistorySegment (3521-3545)
  • GrantUsageRecord (3566-3572)
  • ResetEntitlementUsageInput (6227-6240)
openmeter/entitlement/metered/entitlement_grant.go (3)
  • ListEntitlementGrantsParams (23-29)
  • EntitlementGrant (126-139)
  • CreateEntitlementGrantInputs (157-159)
openmeter/entitlement/driver/metered.go (1)
  • MapEntitlementGrantToAPI (427-458)
openmeter/credit/grant.go (1)
  • CreateGrantInput (23-32)
pkg/timeutil/recurrence.go (1)
  • Recurrence (13-18)
openmeter/entitlement/driver/parser.go (1)
  • MapAPIPeriodIntervalToRecurrence (341-361)
pkg/clock/clock.go (1)
  • Now (14-21)
openmeter/entitlement/metered/balance.go (1)
  • BalanceHistoryParams (47-52)
openmeter/entitlement/metered/connector.go (1)
  • ResetEntitlementUsageParams (27-31)
⏰ 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: Artifacts / Container image
  • GitHub Check: Test
  • GitHub Check: Code Generators
  • GitHub Check: Lint
  • GitHub Check: Build
  • GitHub Check: Analyze (go)
🔇 Additional comments (24)
openmeter/server/router/credit.go (1)

33-35: LGTM: V2 grants correctly delegates to credit handler.
Params are forwarded; aligns V1/V2 routing patterns.

openmeter/server/router/router.go (6)

33-33: Import of v2 entitlement driver looks correct.

Alias and path align with v2 handler usage below.


235-235: New Router field for v2 handler is appropriate.

Type matches the v2 constructor return.


281-287: Good: v2 CustomerEntitlement handler wiring.

Dependencies match the v2 constructor; error handler passed.


305-311: Good: v1 metered entitlement handler now receives Customer and SubjectService.

This aligns v1 with the new customer-centric internals.


317-319: Good: credit GrantHandler now receives Customer service.

Matches new ListGrantsV2 flow in credit driver.


272-279: EntitlementHandler constructor usage verified. Only call site in openmeter/server/router/router.go matches the updated signature—no further changes needed.

openmeter/credit/driver/grant.go (5)

29-30: Interface extension: ListGrantsV2 added.

Public API surface change looks consistent with router wiring.


37-38: Inject customerService into handler.

Constructor and struct updated consistently.

Also applies to: 44-45, 51-51


114-120: Mapping uses clock.Now() and new MapEntitlementGrantToAPI signature.

Looks correct and aligns with metered grant shape.


281-289: Grant mapping for v2 mirrors v1; OK.

Consistent time-based recurrence computation and API mapping.


291-296: Paged response fields sourced from repo.Page; OK.

Matches api.GrantPaginatedResponse shape.

openmeter/server/router/entitlement.go (12)

9-10: Import of v2 entitlement driver.

Matches router wiring.


121-124: Comment-only section: OK.

Clear separation of V1 customer surface.


154-159: ListCustomerEntitlementsV2 parameter struct usage matches v2 handler.

CustomerIdOrKey and Params mapping align with v2 definitions.


164-168: GetCustomerEntitlementV2 wiring is correct.

Using EntitlementIdOrFeatureKey matches v2 handler params.


171-177: DeleteCustomerEntitlementV2 wiring is correct.

Param names consistent with v2 handler.


181-186: OverrideCustomerEntitlementV2 wiring is correct.

Consistent with v2 handler params.


190-196: ListCustomerEntitlementGrantsV2 wiring is correct.

Includes params struct; OK.


200-205: CreateCustomerEntitlementGrantV2 wired, but implementation may be TODO.

If v2 driver method is unimplemented, expect 501/NotImplemented behavior until completed.


219-224: GetCustomerEntitlementHistoryV2 wiring is correct.

Params struct matches v2 handler.


229-233: ResetCustomerEntitlementUsageV2 wiring is correct.

Param names consistent with v2 handler.


148-150: ULIDOrExternalKey alias verified
ULIDOrExternalKey is defined as type ULIDOrExternalKey = string in api/api.gen.go; no action required.


12-20: Approved: Generated ServerInterface includes both ListEntitlements and GetEntitlementById.

Comment thread openmeter/credit/driver/grant.go Resolved
@GAlexIHU
GAlexIHU force-pushed the feat/entitlement-api-v2-3 branch from 3c57efd to 9a209a2 Compare September 1, 2025 15:39

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

Caution

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

⚠️ Outside diff range comments (4)
app/common/openmeter_balanceworker.go (1)

80-91: Regenerate Wire files to update NewBalanceWorkerOptions call sites
Run wire in each cmd/* directory (e.g. cmd/balance-worker) to refresh all wire_gen.go files so they use the new parameter order.

e2e/e2e_test.go (1)

1207-1211: Bug: asserting status on the wrong response variable

You create resp2 from OverrideEntitlementWithResponse but assert on resp. This can mask failures.

Fix:

-	require.Equal(t, http.StatusCreated, resp.StatusCode(), "Invalid status code [response_body=%s]", string(resp.Body))
+	require.Equal(t, http.StatusCreated, resp2.StatusCode(), "Invalid status code [response_body=%s]", string(resp2.Body))
openmeter/server/router/entitlement.go (1)

70-75: Pass through the 'params' to the ListEntitlementGrants handler.

The params received by the router are currently dropped.

 func (a *Router) ListEntitlementGrants(w http.ResponseWriter, r *http.Request, subjectIdOrKey string, entitlementIdOrFeatureKey string, params api.ListEntitlementGrantsParams) {
 	a.meteredEntitlementHandler.ListEntitlementGrants().With(entitlementdriver.ListEntitlementGrantsHandlerParams{
 		SubjectKey:                subjectIdOrKey,
 		EntitlementIdOrFeatureKey: entitlementIdOrFeatureKey,
+		Params:                    params,
 	}).ServeHTTP(w, r)
 }
openmeter/entitlement/adapter/entitlement.go (1)

92-110: Enforce uniqueness: replace First with Only and surface duplicates

Using First(ctx) can mask data errors. Prefer Only(ctx) and fail fast on duplicates.

-                .First(ctx) // FIXME: to better enforce consistency we should not use .First() but assert that there is only one result!
+                .Only(ctx)

And adjust error handling (lines 111-121):

-            if err != nil {
-                if db.IsNotFound(err) {
-                    return nil, &entitlement.NotFoundError{
-                        EntitlementID: models.NamespacedID{
-                            Namespace: namespace,
-                            ID:        featureKey,
-                        },
-                    }
-                }
-                return nil, err
-            }
+            if err != nil {
+                if db.IsNotFound(err) {
+                    return nil, &entitlement.NotFoundError{
+                        EntitlementID: models.NamespacedID{Namespace: namespace, ID: featureKey},
+                    }
+                }
+                if db.IsNotSingular(err) {
+                    return nil, fmt.Errorf("multiple active entitlements for customer %s feature %s at %s", customerID, featureKey, at.UTC())
+                }
+                return nil, err
+            }
♻️ Duplicate comments (17)
openmeter/credit/grant/events_2.go (1)

23-39: Flatten ManagedModel/NamespacedModel to avoid nested JSON in grant literal

Named fields produce { "grant": { "ManagedModel": {...}, "NamespacedModel": {...}, ... } }, which breaks the "primitive payload" guidance and likely consumers expecting flat fields. Embed them to flatten.

 type grantEventV2GrantLiteral struct {
-	ManagedModel    models.ManagedModel
-	NamespacedModel models.NamespacedModel
+	// Embed to flatten createdAt/updatedAt/deletedAt (+ namespace) into grant.
+	models.ManagedModel
+	models.NamespacedModel
openmeter/notification/consumer/entitlementreset.go (1)

123-129: Guard against nil dereference of in.Snapshot.Value before casting

Value: (api.EntitlementValue)(*in.Snapshot.Value) will panic if in.Snapshot.Value is nil. For reset ops, either assert non-nil or fail fast with a clear error.

+	if in.Snapshot.Value == nil {
+		return fmt.Errorf("invalid reset event: snapshot value is nil for reset operation")
+	}
+	val := api.EntitlementValue(*in.Snapshot.Value)
 	resetPayload := notification.EntitlementResetPayload{
 		Entitlement: *entitlementAPIEntity,
 		Feature:     productcatalogdriver.MapFeatureToResponse(in.Snapshot.Feature),
 		Subject:     subjecthttphandler.FromSubject(in.Snapshot.Subject),
-		Value:       (api.EntitlementValue)(*in.Snapshot.Value),
+		Value:       val,
 	}
e2e/config.yaml (1)

85-89: Fix v2 meter value path and scope aggregation per customer

The v2 payload doesn’t expose a top-level value field. Use the stable entitlement ID and group per customer to avoid cross-tenant cardinality.

-  - slug: entitlement_v2_meter
-    description: Meter for testing entitlements with unique count
-    eventType: entitlement_v2
-    valueProperty: $.value
-    aggregation: UNIQUE_COUNT
+  - slug: entitlement_v2_meter
+    description: Meter for testing entitlements with unique count
+    eventType: entitlement_v2
+    valueProperty: $.entitlement.id
+    aggregation: UNIQUE_COUNT
+    groupBy:
+      customerId: $.entitlement.customer.id
#!/bin/bash
# Verify v2 event payload shape to confirm paths
rg -nC3 -e 'type .*Entitlement.*EventV2' -e '"eventType"\s*:\s*"entitlement_v2"' --type go --type json --type yaml
rg -nC3 -e '"entitlement"\s*:\s*{' -e '"customer"\s*:\s*{' --type json e2e || true
openmeter/credit/grant/owner_connector.go (1)

19-20: Annotate and ensure StreamingCustomer is hydrated for v2 events

Add a clarifying comment and audit DescribeOwner implementations to populate StreamingCustomer so v2 events always carry customer context.

 type Owner struct {
   models.NamespacedID
   Meter              meter.Meter
   DefaultQueryParams streaming.QueryParams
   ResetBehavior      ResetBehavior
-  StreamingCustomer  streaming.Customer
+  // StreamingCustomer: required for v2 event payloads; may be nil only on legacy subject-key flows.
+  StreamingCustomer  streaming.Customer
 }
#!/bin/bash
# Ensure all DescribeOwner implementations set StreamingCustomer
rg -nPU '(?s)DescribeOwner\s*\(.*\)\s*\(Owner, error\)\s*\{.*?\}' -C3
rg -n 'StreamingCustomer' -C2
openmeter/entitlement/repository.go (2)

32-41: Stale method name in comment + wording fix

Comment still says “GetActiveEntitlementOfSubjectAt”. Also “become inactive after” reads like the opposite of “scheduled”. Align wording.

-	// GetActiveEntitlementOfSubjectAt returns the active entitlement of a customer at a given time by feature key
+	// GetActiveEntitlementOfCustomerAt returns the active entitlement of a customer at a given time by feature key
...
-	// GetScheduledEntitlements returns all scheduled entitlements for a given customer-feature pair that become inactive after the given time, sorted by the time they become active
+	// GetScheduledEntitlements returns all scheduled entitlements for a given customer–feature pair that become active after the given time, sorted by the time they become active

78-86: Make UsageAttribution optional and validate inputs

Encoding an empty struct can be misleading, and callers need guardrails (feature selector invariants, non-empty attribution).

 type CreateEntitlementRepoInputs struct {
 	Namespace        string                             `json:"namespace"`
 	FeatureID        string                             `json:"featureId"`
 	FeatureKey       string                             `json:"featureKey"`
-	UsageAttribution streaming.CustomerUsageAttribution `json:"usageAttribution"`
+	UsageAttribution *streaming.CustomerUsageAttribution `json:"usageAttribution,omitempty"`
 	EntitlementType  EntitlementType                    `json:"type"`
 	Metadata         map[string]string                  `json:"metadata,omitempty"`
 	ActiveFrom       *time.Time                         `json:"activeFrom,omitempty"`
 	ActiveTo         *time.Time                         `json:"activeTo,omitempty"`

Add validation near the type:

+func (in CreateEntitlementRepoInputs) Validate() error {
+	// exactly one of FeatureID or FeatureKey
+	if (in.FeatureID == "") == (in.FeatureKey == "") {
+		return fmt.Errorf("exactly one of featureId or featureKey must be set")
+	}
+	// optional usage attribution must be meaningful
+	if in.UsageAttribution != nil {
+		hasID := in.UsageAttribution.ID != ""
+		hasKey := in.UsageAttribution.Key != nil && *in.UsageAttribution.Key != ""
+		hasSubjects := len(in.UsageAttribution.SubjectKeys) > 0
+		if !hasID && !hasKey && !hasSubjects {
+			return fmt.Errorf("usageAttribution requires id, key, or subjectKeys")
+		}
+	}
+	return nil
+}

Optionally, document that server-side resolution prefers ID over Key over SubjectKeys.

openmeter/entitlement/driver/v2/customer_metered.go (3)

50-55: Bug: pagination/sort params are dropped in the request builder.

Copy params.Params into the request so the handler can honor client pagination/sorting.

 return ListCustomerEntitlementGrantsHandlerRequest{
   CustomerIDOrKey:           params.CustomerIDOrKey,
   EntitlementIdOrFeatureKey: params.EntitlementIdOrFeatureKey,
   Namespace:                 ns,
+  Params:                    params.Params,
 }, nil

239-242: Resolve entitlement at the requested history horizon, not “now”.

Use params.Params.To (or From) fallback; using clock.Now() can miss historical entitlements.

- ent, err := h.connector.GetEntitlementOfCustomerAt(ctx, ns, cus.ID, params.EntitlementIdOrFeatureKey, clock.Now())
+ at := lo.FromPtrOr(params.Params.To, lo.FromPtrOr(params.Params.From, clock.Now()))
+ ent, err := h.connector.GetEntitlementOfCustomerAt(ctx, ns, cus.ID, params.EntitlementIdOrFeatureKey, at)

361-367: Reset should resolve by EffectiveAt and reuse it for the request.

Compute effectiveAt once; use for entitlement resolution and Reset params.

- // Resolve entitlement
- ent, err := h.connector.GetEntitlementOfCustomerAt(ctx, ns, cus.ID, params.EntitlementIdOrFeatureKey, clock.Now())
+ effectiveAt := defaultx.WithDefault(body.EffectiveAt, clock.Now())
+ // Resolve entitlement at the reset time
+ ent, err := h.connector.GetEntitlementOfCustomerAt(ctx, ns, cus.ID, params.EntitlementIdOrFeatureKey, effectiveAt)
@@
- At:              defaultx.WithDefault(body.EffectiveAt, clock.Now()),
+ At:              effectiveAt,

Also applies to: 355-359

e2e/entitlement_test.go (1)

210-262: Create a customer-subject mapping and assert canonical CustomerId (not the subject key)

This subtest still calls the V2 customer endpoint with subject as customerIdOrKey and never creates a Customer mapping; this can 404 in clean envs. Also, the response returns the canonical CustomerId, which may not equal the key you passed.

Apply:

 t.Run("Create entitlement via Customer V2 API", func(t *testing.T) {
-		// Ensure subject exists and matches a customer mapping (use same subject)
-		{
-			resp, err := client.UpsertSubjectWithResponse(ctx, api.UpsertSubjectJSONRequestBody{api.SubjectUpsert{Key: subject}})
-			require.NoError(t, err)
-			require.Equal(t, http.StatusOK, resp.StatusCode())
-		}
+		// Ensure 1:1 customer<->subject mapping exists
+		cust := CreateCustomerWithSubject(t, client, subject, subject)
@@
-			// Use customerIdOrKey that maps 1:1 to subject
-			res, err := client.CreateCustomerEntitlementV2WithResponse(ctx, subject, createBody)
+			// Use the canonical customer ID
+			res, err := client.CreateCustomerEntitlementV2WithResponse(ctx, cust.Id, createBody)
@@
-			// CustomerKey may be nil if we resolved by customerId only; assert customerId presence
-			require.Equal(t, subject, v2.CustomerId)
+			// Assert canonical customer ID
+			require.Equal(t, cust.Id, v2.CustomerId)
openmeter/ent/db/entitlement_create.go (1)

464-469: Runtime validation is good; enforce DB constraints + backfill in migrations.

Requiring customer_id and subject_id at build-time is fine, but you still need NOT NULL + FK constraints and a backfill migration to prevent inconsistent rows.

Run to verify migrations exist:

#!/bin/bash
# Check schema for customer_id/subject_id NOT NULL + FK
rg -nP '(customer_id|subject_id)' openmeter/ent/schema/entitlement.go
rg -nP 'ALTER TABLE\s+entitlements.*(customer_id|subject_id).*NOT NULL' openmeter/ent/db/migrate -S
rg -nP 'FOREIGN KEY.*(customer_id|subject_id).*REFERENCES\s+customers|subjects' openmeter/ent/db/migrate -S
# Backfill scripts
rg -nP 'backfill|populate|customer_id|subject_id' openmeter/ent/db/migrate -n
openmeter/credit/driver/grant.go (1)

241-253: Critical: empty derived subjectKeys disables filtering → returns all grants. Add no-match guard and dedupe.

When p.Params.Customer is provided but yields zero subject keys, adapter applies no SubjectKeys filter (len==0), returning all grants. Dedupe keys as well.

Apply this minimal patch:

-			// Build subject keys from customers if provided
-			subjectKeys := []string{}
+			// Build subject keys from customers if provided
+			subjectKeySet := map[string]struct{}{}
 			if p.Params.Customer != nil {
 				for _, idOrKey := range *p.Params.Customer {
 					cus, err := h.customerService.GetCustomer(ctx, customer.GetCustomerInput{
 						CustomerIDOrKey: &customer.CustomerIDOrKey{Namespace: ns, IDOrKey: idOrKey},
 					})
 					if err != nil {
 						return ListGrantsV2HandlerRequest{}, err
 					}
-					subjectKeys = append(subjectKeys, cus.UsageAttribution.SubjectKeys...)
+					for _, sk := range cus.UsageAttribution.SubjectKeys {
+						subjectKeySet[sk] = struct{}{}
+					}
 				}
 			}
+			subjectKeys := make([]string, 0, len(subjectKeySet))
+			for sk := range subjectKeySet {
+				subjectKeys = append(subjectKeys, sk)
+			}
+
+			noMatch := p.Params.Customer != nil && len(subjectKeys) == 0

And propagate the no-match early return:

-			req := grant.ListParams{
+			req := grant.ListParams{
 				Namespace:        ns,
 				IncludeDeleted:   defaultx.WithDefault(p.Params.IncludeDeleted, false),
 				Order:            commonhttp.GetSortOrder(api.SortOrderASC, p.Params.Order),
 				OrderBy:          grant.OrderBy(strcase.CamelToSnake(defaultx.WithDefault((*string)(p.Params.OrderBy), string(grant.OrderByEffectiveAt)))),
 				FeatureIdsOrKeys: convert.DerefHeaderPtr[string](p.Params.Feature),
 				SubjectKeys:      subjectKeys,
 			}
 
 			// Pagination: support both page/pageSize and limit/offset
 			if p.Params.Page != nil || p.Params.PageSize != nil {
 				req.Page.PageNumber = defaultx.WithDefault(p.Params.Page, 1)
 				req.Page.PageSize = defaultx.WithDefault(p.Params.PageSize, 100)
 			} else {
 				req.Limit = defaultx.WithDefault(p.Params.Limit, 100)
 				req.Offset = defaultx.WithDefault(p.Params.Offset, 0)
 			}
 
-			return ListGrantsV2HandlerRequest{params: req}, nil
+			return ListGrantsV2HandlerRequest{params: req, /* signal early-exit */ noMatch: noMatch}, nil

And short-circuit in the executor:

-		func(ctx context.Context, request ListGrantsV2HandlerRequest) (ListGrantsV2HandlerResponse, error) {
+		func(ctx context.Context, request ListGrantsV2HandlerRequest) (ListGrantsV2HandlerResponse, error) {
+			if request.noMatch {
+				return api.GrantPaginatedResponse{
+					Items:      []api.EntitlementGrant{},
+					TotalCount: 0,
+					Page:       request.params.Page.PageNumber,
+					PageSize:   request.params.Page.PageSize,
+				}, nil
+			}

Also extend the request type:

 type (
 	ListGrantsV2HandlerRequest struct {
 		params grant.ListParams
+		noMatch bool
 	}
openmeter/entitlement/driver/entitlement.go (1)

255-259: Respect the time query param in GetEntitlementsOfSubject.

Propagate params.Params.Time instead of always using clock.Now().

 type (
-	GetEntitlementsOfSubjectHandlerRequest = struct {
-		Namespace      string
-		SubjectIdOrKey string
-	}
+	GetEntitlementsOfSubjectHandlerRequest = struct {
+		Namespace      string
+		SubjectIdOrKey string
+		At             time.Time
+	}
 		func(ctx context.Context, r *http.Request, params GetEntitlementsOfSubjectHandlerParams) (GetEntitlementsOfSubjectHandlerRequest, error) {
 			ns, err := h.resolveNamespace(ctx)
 			if err != nil {
 				return GetEntitlementsOfSubjectHandlerRequest{}, err
 			}
 
-			return GetEntitlementsOfSubjectHandlerRequest{
-				Namespace:      ns,
-				SubjectIdOrKey: params.SubjectIdOrKey,
-			}, nil
+			return GetEntitlementsOfSubjectHandlerRequest{
+				Namespace:      ns,
+				SubjectIdOrKey: params.SubjectIdOrKey,
+				At:             defaultx.WithDefault(params.Params.Time, clock.Now()),
+			}, nil
-			entitlements, err := h.connector.GetEntitlementsOfCustomer(ctx, id.Namespace, cust.ID, clock.Now())
+			entitlements, err := h.connector.GetEntitlementsOfCustomer(ctx, id.Namespace, cust.ID, id.At)

Also applies to: 269-279, 287-288

openmeter/entitlement/metered/entitlement_grant.go (1)

84-86: Fix nil-deref when mapping grant result.

GrantFromCreditGrant may return (nil, err); dereferencing eg in the return path can panic. Handle the error before dereferencing.

-	eg, err := GrantFromCreditGrant(*g, clock.Now())
-	return *eg, err
+	eg, err := GrantFromCreditGrant(*g, clock.Now())
+	if err != nil {
+		return EntitlementGrant{}, err
+	}
+	return *eg, nil
openmeter/entitlement/adapter/entitlement.go (1)

274-317: Guard empty MeterSlugs and avoid potential nil dereference on Feature

  • If pair.MeterSlugs is empty, db_feature.MeterSlugIn(...) can yield invalid/broad queries.
  • e.Edges.Feature can be nil; dereferencing MeterSlug risks a panic.

Apply:

-                entities, err := repo.db.Entitlement.Query().
-                    Where(
-                        db_entitlement.Namespace(pair.Namespace),
-                        db_entitlement.HasCustomerWith(
-                            customerdb.Namespace(pair.Namespace),
-                            customerNotDeletedAt(clock.Now()),
-                            customerdb.HasSubjectsWith(
-                                customersubjectsdb.SubjectKey(pair.EventSubject),
-                                customersubjectsdb.DeletedAtIsNil(),
-                            ),
-                        ),
-                        db_entitlement.HasFeatureWith(db_feature.MeterSlugIn(pair.MeterSlugs...)),
-                    ).
-                    WithFeature().
-                    WithCustomer().
-                    All(ctx)
+                q := repo.db.Entitlement.Query().
+                    Where(
+                        db_entitlement.Namespace(pair.Namespace),
+                        db_entitlement.HasCustomerWith(
+                            customerdb.Namespace(pair.Namespace),
+                            customerNotDeletedAt(clock.Now()),
+                            customerdb.HasSubjectsWith(
+                                customersubjectsdb.SubjectKey(pair.EventSubject),
+                                customersubjectsdb.DeletedAtIsNil(),
+                            ),
+                        ),
+                    )
+                if len(pair.MeterSlugs) > 0 {
+                    q = q.Where(db_entitlement.HasFeatureWith(db_feature.MeterSlugIn(pair.MeterSlugs...)))
+                }
+                entities, err := q.
+                    WithFeature().
+                    WithCustomer().
+                    All(ctx)
@@
-                    result = append(result, balanceworker.ListAffectedEntitlementsResponse{
+                    var meterSlug *string
+                    if e.Edges.Feature != nil {
+                        meterSlug = e.Edges.Feature.MeterSlug
+                    }
+                    result = append(result, balanceworker.ListAffectedEntitlementsResponse{
                         Namespace:     e.Namespace,
                         EntitlementID: e.ID,
                         SubjectKey:    pair.EventSubject,
                         CustomerID:    e.Edges.Customer.ID,
-                        MeterSlug:     e.Edges.Feature.MeterSlug,
+                        MeterSlug:     meterSlug,
                     })
openmeter/ent/db/mutation.go (2)

31104-31106: Bug: ClearEdge must call ClearEntitlements(), not ResetEntitlements()

Reset cancels the clear intent; ClearEdge should mark the edge cleared.

-	case customer.EdgeEntitlements:
-		m.ResetEntitlements()
-		return nil
+	case customer.EdgeEntitlements:
+		m.ClearEntitlements()
+		return nil

33247-33272: Bug: ResetCustomer should remove clearedFields entry; also ensure FK nullability

Without deleting clearedFields[customer_id], a prior ClearCustomer() will still null the FK after ResetCustomer(), causing unintended updates. Also, clearing requires customer_id to be nullable in the schema (not Required).

 func (m *EntitlementMutation) ResetCustomer() {
 	m.customer = nil
 	m.clearedcustomer = false
+	delete(m.clearedFields, entitlement.FieldCustomerID)
 }
🧹 Nitpick comments (62)
openmeter/server/server_test.go (3)

718-721: Use customer-centric param name

Rename subjectKey to customerID to align with the new customer-oriented API and avoid confusion.

-func (n NoopEntitlementConnector) GetEntitlementsOfCustomer(ctx context.Context, namespace string, subjectKey string, at time.Time) ([]entitlement.Entitlement, error) {
+func (n NoopEntitlementConnector) GetEntitlementsOfCustomer(ctx context.Context, namespace string, customerID string, at time.Time) ([]entitlement.Entitlement, error) {

726-728: Consistent naming for customer and entitlement identifiers

For clarity and consistency with params structs, prefer customerID and entitlementIDOrFeatureKey.

-func (n NoopEntitlementConnector) GetEntitlementOfCustomerAt(ctx context.Context, namespace string, subjectKey string, idOrFeatureKey string, at time.Time) (*entitlement.Entitlement, error) {
+func (n NoopEntitlementConnector) GetEntitlementOfCustomerAt(ctx context.Context, namespace string, customerID string, entitlementIDOrFeatureKey string, at time.Time) (*entitlement.Entitlement, error) {

760-762: Paging signature update looks good

Method now returns a paged response and accepts the new params struct; suitable for tests as a no-op. If this ever surfaces via JSON, ensure clients tolerate items: null vs items: [].

openmeter/entitlement/service/utils_test.go (1)

158-173: Share one mock Publisher and auto-clean resources.
Reuse a single event publisher across services to keep events coherent and reduce allocations; also mark the setup as a test helper and register Teardown with t.Cleanup.

Within this hunk:

-	customerService, err := customerservice.New(customerservice.Config{
-		Adapter:   customerAdapter,
-		Publisher: eventbus.NewMock(t),
-	})
+	customerService, err := customerservice.New(customerservice.Config{
+		Adapter:   customerAdapter,
+		Publisher: publisher,
+	})

Outside this hunk (illustrative):

 func setupDependecies(t *testing.T) (entitlement.Connector, *dependencies) {
-	testLogger := testutils.NewLogger(t)
+	testLogger := testutils.NewLogger(t)
+	t.Helper()
+	publisher := eventbus.NewMock(t)
   …
-		Publisher:          eventbus.NewMock(t),
+		Publisher:          publisher,
   …
-	return entitlementRegistry.Entitlement, deps
+	t.Cleanup(deps.Teardown)
+	return entitlementRegistry.Entitlement, deps
}
openmeter/entitlement/metered/lateevents_test.go (1)

203-208: Rename variable to reflect type (adapter, not service) and pass it consistently.

The value from customeradapter.New is an adapter. Renaming avoids confusion with a customer “service”.

Apply these diffs:

@@
-        customerService, err := customeradapter.New(customeradapter.Config{
+        customerAdapter, err := customeradapter.New(customeradapter.Config{
             Client: dbClient,
             Logger: testLogger,
         })
         require.NoError(t, err)
@@
-            subjectService,
-            customerService,
+            subjectService,
+            customerAdapter,
@@
-        // create customer and subject
-        cust := createCustomerAndSubject(t, deps.subjectService, deps.customerService, namespace, "subject1")
+        // create customer and subject (for usage attribution)
+        cust := createCustomerAndSubject(t, deps.subjectService, deps.customerAdapter, namespace, "subject1")

Also applies to: 223-225, 241-243

openmeter/credit/grant/events_2.go (3)

92-94: Use camelCase in error to match JSON field name

Align validation error with json:"customerId".

-		return errors.New("customer_id must be set")
+		return errors.New("customerId must be set")

68-85: Defensive copy of Metadata to avoid aliasing mutations

mapGrantToV2Literal returns the original map reference; later mutations to the domain Grant would leak into the event.

-func mapGrantToV2Literal(g Grant) grantEventV2GrantLiteral {
-	return grantEventV2GrantLiteral{
+func mapGrantToV2Literal(g Grant) grantEventV2GrantLiteral {
+	// Defensive copy to avoid aliasing after event creation.
+	var md map[string]string
+	if g.Metadata != nil {
+		md = make(map[string]string, len(g.Metadata))
+		for k, v := range g.Metadata {
+			md[k] = v
+		}
+	}
+	return grantEventV2GrantLiteral{
 		ManagedModel:     g.ManagedModel,
 		NamespacedModel:  g.NamespacedModel,
 		ID:               g.ID,
 		OwnerID:          g.OwnerID,
 		Amount:           g.Amount,
 		Priority:         g.Priority,
 		EffectiveAt:      g.EffectiveAt,
 		Expiration:       g.Expiration,
 		ExpiresAt:        g.ExpiresAt,
 		VoidedAt:         g.VoidedAt,
 		ResetMaxRollover: g.ResetMaxRollover,
 		ResetMinRollover: g.ResetMinRollover,
 		Recurrence:       g.Recurrence,
-		Metadata:         g.Metadata,
+		Metadata:         md,
 	}
 }

17-21: Optional: make Namespace a primitive string in the wire payload

To fully embrace “primitive payloads,” consider using string for Namespace in events, validating via eventmodels.NamespaceID, and updating call sites. This removes an extra nested object from the JSON.

 type grantEventV2 struct {
-	Namespace  eventmodels.NamespaceID  `json:"namespace"`
+	Namespace  string                   `json:"namespace"`
 	Grant      grantEventV2GrantLiteral `json:"grant"`
 	CustomerID string                   `json:"customerId"`
 }

-	if err := g.Namespace.Validate(); err != nil {
+	if err := (eventmodels.NamespaceID{ID: g.Namespace}).Validate(); err != nil {
 		return err
 	}

-		Source:  metadata.ComposeResourcePath(e.Namespace.ID, metadata.EntityEntitlement, e.Grant.OwnerID, metadata.EntityGrant, e.Grant.ID),
-		Subject: metadata.ComposeResourcePath(e.Namespace.ID, metadata.EntityCustomer, e.CustomerID),
+		Source:  metadata.ComposeResourcePath(e.Namespace, metadata.EntityEntitlement, e.Grant.OwnerID, metadata.EntityGrant, e.Grant.ID),
+		Subject: metadata.ComposeResourcePath(e.Namespace, metadata.EntityCustomer, e.CustomerID),
 	}

 func NewCreatedEventV2FromGrant(g Grant, streamingCustomer streaming.Customer) CreatedEventV2 {
 	return CreatedEventV2{
-		Namespace:  eventmodels.NamespaceID{ID: g.Namespace},
+		Namespace:  g.Namespace,
 		Grant:      mapGrantToV2Literal(g),
 		CustomerID: streamingCustomer.GetUsageAttribution().ID,
 	}
 }

 func NewVoidedEventV2FromGrant(g Grant, streamingCustomer streaming.Customer, voidedAt time.Time) VoidedEventV2 {
 	literal := mapGrantToV2Literal(g)
 	literal.VoidedAt = &voidedAt
 	return VoidedEventV2{
-		Namespace:  eventmodels.NamespaceID{ID: g.Namespace},
+		Namespace:  g.Namespace,
 		Grant:      literal,
 		CustomerID: streamingCustomer.GetUsageAttribution().ID,
 	}
 }

Also applies to: 96-101, 103-108, 146-152, 154-164

openmeter/entitlement/balanceworker/recalculate.go (5)

169-172: Fix error message to reflect the cache being created.

-    return nil, fmt.Errorf("failed to create subject ID cache: %w", err)
+    return nil, fmt.Errorf("failed to create customer-subject cache: %w", err)

290-297: Defensive check: fail fast when Customer ID is missing before cache lookup.

If EntitlementRepo ever omits the WithCustomer edge, this will produce unclear resolver errors. Add an explicit guard with actionable guidance.

 func (r *Recalculator) sendEntitlementDeletedEvent(ctx context.Context, ent entitlement.Entitlement) (sendEntitlementEventResult, error) {
     empty := sendEntitlementEventResult{}

+    if ent.Customer.ID == "" {
+        return empty, fmt.Errorf("entitlement [id=%s]: missing customer ID (ensure EntitlementRepo includes WithCustomer edge)", ent.ID)
+    }
     custSubj, err := r.customerSubjectCache.Get(ctx, pkgmodels.NamespacedID{
         Namespace: ent.Namespace,
         ID:        ent.Customer.ID,
     })
 func (r *Recalculator) sendEntitlementUpdatedEvent(ctx context.Context, ent entitlement.Entitlement) (sendEntitlementEventResult, error) {
     empty := sendEntitlementEventResult{}

+    if ent.Customer.ID == "" {
+        return empty, fmt.Errorf("entitlement [id=%s]: missing customer ID (ensure EntitlementRepo includes WithCustomer edge)", ent.ID)
+    }
     custSubj, err := r.customerSubjectCache.Get(ctx, pkgmodels.NamespacedID{
         Namespace: ent.Namespace,
         ID:        ent.Customer.ID,
     })

Also applies to: 343-349


41-46: Typo in metric attribute key: “Entitltement” → “Entitlement”.

Rename the constant and its usages for clarity and consistency.

-    metricAttributeKeyEntitltementType = "entitlement_type"
+    metricAttributeKeyEntitlementType = "entitlement_type"
-            attribute.String(metricAttributeKeyEntitltementType, string(ent.EntitlementType)),
+            attribute.String(metricAttributeKeyEntitlementType, string(ent.EntitlementType)),
-        attribute.String(metricAttributeKeyEntitltementType, string(ent.EntitlementType)),
+        attribute.String(metricAttributeKeyEntitlementType, string(ent.EntitlementType)),

Also applies to: 258-262, 359-362


381-385: Consistent pointer helper usage.

Use convert.ToPointer consistently for time pointers.

-            CalculatedAt: &calculatedAt,
+            CalculatedAt: convert.ToPointer(calculatedAt),

(No change needed in deleted-event path; it already uses convert.ToPointer.)

Also applies to: 321-323


116-118: Cache key semantics: verify determinism when multiple Subjects exist per Customer.

customerSubjectCache is keyed by (namespace, customerID) and returns a single Subject. Confirm resolveCustomerAndSubject is deterministic and aligns with event requirements when a Customer has multiple Subjects. If not, consider:

  • encoding Subject selection rules into resolveCustomerAndSubject (e.g., primary/preferred subject),
  • or including subject identity in the cache key if events must reflect subject-specific context.

Also applies to: 169-173, 393-403

openmeter/customer/httpdriver/customer.go (1)

383-387: Fix operation name for tracing/metrics

Handler is GetCustomerEntitlementValue but operation name is "getCustomer".

-    httptransport.WithOperationName("getCustomer"),
+    httptransport.WithOperationName("getCustomerEntitlementValue"),
e2e/entitlement_parity_test.go (4)

29-31: Harden key generation to avoid flakiness in parallel runs.

Use higher-entropy suffixes to prevent collisions when tests run concurrently.

-	customerKey := fmt.Sprintf("parity_cust_%d", time.Now().Unix())
+	customerKey := fmt.Sprintf("parity_cust_%d", time.Now().UnixNano())
@@
-		randKey := fmt.Sprintf("entitlement_parity_feature_1_%d", time.Now().Unix())
+		randKey := fmt.Sprintf("entitlement_parity_feature_1_%d", time.Now().UnixNano())
@@
-		randKey := fmt.Sprintf("entitlement_parity_feature_2_%d", time.Now().Unix())
+		randKey := fmt.Sprintf("entitlement_parity_feature_2_%d", time.Now().UnixNano())

Also applies to: 39-44, 52-57


116-119: Compare times semantically and assert interval parity.

Avoid string formatting for time equality; also assert the interval matches for full parity.

 			// Basic shape parity: same feature and usage period anchor
 			require.NotNil(t, v2.UsagePeriod)
-			require.Equal(t, anchor.Format(time.RFC3339), v2.UsagePeriod.Anchor.Format(time.RFC3339))
+			require.Equal(t, *month, v2.UsagePeriod.Interval)
+			require.True(t, v2.UsagePeriod.Anchor.Equal(*anchor))

87-91: Add v1 usage period parity checks for symmetry.

Mirror the v2 assertions to validate v1 response shape too.

 			m, err := resp.JSON201.AsEntitlementMetered()
 			require.NoError(t, err)
 			require.Equal(t, subjectKey, m.SubjectKey)
 			require.Equal(t, feature1ID, m.FeatureId)
-			subjectEntitlementID = m.Id
+			require.NotNil(t, m.UsagePeriod)
+			require.Equal(t, *month, m.UsagePeriod.Interval)
+			require.True(t, m.UsagePeriod.Anchor.Equal(*anchor))
+			subjectEntitlementID = m.Id

70-71: Remove unused subjectEntitlementID (or use it).

Dead variable adds noise; delete until you add parity checks that need it.

-		var subjectEntitlementID string
@@
-			subjectEntitlementID = m.Id
@@
-			_ = subjectEntitlementID // reserved for later parity checks (e.g., value/history)
+			// TODO(parity): add value/history parity checks using created IDs

Also applies to: 120-120

openmeter/entitlement/metered/utils_test.go (1)

207-227: Don’t conflate customer and subject identities in helpers.

Using subjectKey as both customer key and subject key is convenient but hides bugs; consider accepting a distinct customerKey.

test/entitlement/regression/scenario_test.go (3)

51-56: Specify either FeatureID or FeatureKey, not both.

Passing both can be ambiguous; prefer FeatureID in tests for stability.

-		FeatureID:        &feature.ID,
-		FeatureKey:       &feature.Key,
+		FeatureID:        &feature.ID,

Apply similarly to other entitlement creations in this file.

Also applies to: 201-207, 305-311, 408-414, 446-452, 595-600, 611-616


655-655: Use the resolved subject key instead of a hard-coded literal.

Keeps the test robust to helper changes.

-	value, err := deps.EntitlementConnector.GetEntitlementValue(ctx, ns, "subject-1", entID, clock.Now())
+	value, err := deps.EntitlementConnector.GetEntitlementValue(ctx, ns, subjKey, entID, clock.Now())

354-356: Fix typo in comment (“deducted”).

-	// Due to grant priority this usage should be deduceted from grant 2
+	// Due to grant priority this usage should be deducted from grant 2
e2e/e2e_test.go (2)

24-34: Align customerIOTA numbering with "customer-1" convention

iota starts at 0, so customer1.Key() -> "customer-0". Prefer 1-based to match the rest of the suite and avoid confusion/collisions.

Apply:

-const (
-	customer1 customerIOTA = iota
+const (
+	customer1 customerIOTA = iota + 1
 	customer2
 	customer3
 )

1223-1241: Comment/expectation mismatch

Comment says “should return 2 entitlements” but assertions expect 1. Align the comment to reduce confusion.

-		// should return 2 entitlements for subject for feature
+		// should return 1 entitlement for subject for feature
openmeter/entitlement/events.go (1)

48-50: Symmetry: consider ToDomainEntitlement on Created as well

You added ToDomainEntitlement on EntitlementDeletedEvent; having the same on EntitlementCreatedEvent can simplify handler code.

+func (e EntitlementCreatedEvent) ToDomainEntitlement() Entitlement {
+	return entitlementEventV1(e).ToDomainEntitlement()
+}
openmeter/entitlement/validators/customer/validator.go (1)

35-39: Fix stale comment; consider future-scheduled entitlements and lighter existence check.

  • Comment still says “for each subject”; update to “for the customer”.
  • Optional: also block delete if there are entitlements scheduled to become active in the future; otherwise deletes can orphan schedules.
  • Optional: repo-level Exists/COUNT(1) would avoid loading full rows.
- // Check for active entitlements for each subject
+ // Check for active entitlements of the customer
openmeter/entitlement/service/service.go (2)

67-71: Customer/usage-attribution mismatch validation is correct; add namespace guard.

Also verify input.UsageAttribution.Namespace matches input.Namespace to prevent cross-namespace overrides.

- if customerID != input.UsageAttribution.ID {
+ if customerID != input.UsageAttribution.ID || input.UsageAttribution.Namespace != input.Namespace {
   return nil, entitlement.
     ErrEntitlementCreatePropertyMismatch.
-      WithAttr("customer_id", customerID).WithAttr("usage_attribution_id", input.UsageAttribution.ID)
+      WithAttr("customer_id", customerID).
+      WithAttr("usage_attribution_id", input.UsageAttribution.ID).
+      WithAttr("usage_attribution_ns", input.UsageAttribution.Namespace).
+      WithAttr("namespace", input.Namespace)
 }

161-168: Avoid extra repo hits when computing access.

You already have ent in hand; calling GetEntitlementValue re-fetches it by ID. Use the subtype connector directly and check activity.

-            entValue, err := c.GetEntitlementValue(ctx, namespace, customerId, entit.ID, now)
+            if !entit.IsActive(now) {
+              result.Store(entit.FeatureKey, entitlement.EntitlementValueWithId{
+                Value: &entitlement.NoAccessValue{},
+                ID:    entit.ID,
+              })
+              return nil
+            }
+            connector, err := c.getTypeConnector(entit)
+            if err != nil {
+              return err
+            }
+            entValue, err := connector.GetValue(ctx, entit, now)

Also applies to: 173-181, 193-209

e2e/entitlement_test.go (3)

50-53: Nit: redundant subject upsert

Subject was upserted earlier in this test; this block is duplicate.

Apply:

-		{
-			resp, err := client.UpsertSubjectWithResponse(ctx, api.UpsertSubjectJSONRequestBody{api.SubjectUpsert{Key: v2Subject}})
-			require.NoError(t, err)
-			require.Equal(t, http.StatusOK, resp.StatusCode())
-		}

61-61: Use string(resp.Body) for readable failure output

Minor consistency/readability fix.

-			require.Equal(t, http.StatusCreated, resp.StatusCode(), "Invalid status code [response_body=%s]", resp.Body)
+			require.Equal(t, http.StatusCreated, resp.StatusCode(), "Invalid status code [response_body=%s]", string(resp.Body))

117-137: Optional: isolate 404 to “missing customer” by using a real feature

Right now both customer and feature can be missing; either can yield 404. To make this deterministic, create a real feature here and use FeatureId instead of a fake FeatureKey.

I can provide a small snippet to create a feature inline if you want this tightened.

openmeter/entitlement/metered/grant_owner_adapter_test.go (3)

28-42: Helper uses context.Background; consider threading test ctx for cancellation

Plumb a ctx param so cancellations/timeouts in subtests propagate to repo calls. Low impact, improves correctness under timeouts.

- createFeatureAndCustomer := func(t *testing.T, deps *dependencies) (feature.Feature, *customer.Customer) {
+ createFeatureAndCustomer := func(t *testing.T, ctx context.Context, deps *dependencies) (feature.Feature, *customer.Customer) {
   t.Helper()
-  f, err := deps.featureRepo.CreateFeature(context.Background(), feature.CreateFeatureInputs{
+  f, err := deps.featureRepo.CreateFeature(ctx, feature.CreateFeatureInputs{
     Name:      "f1",
     Key:       "f1",
     MeterSlug: lo.ToPtr(meterSlug),
     Namespace: namespace,
   })
   require.NoError(t, err)
   cust := createCustomerAndSubject(t, deps.subjectService, deps.customerService, namespace, "subject1")
   return f, cust
 }

Then call as: f, c := createFeatureAndCustomer(t, ctx, deps).


49-50: Stabilize tests by resetting the clock via t.Cleanup

Some subtests set the global clock but don’t reset it, which can leak state across tests. Prefer t.Cleanup for consistent teardown.

- clock.SetTime(now)
+ clock.SetTime(now)
+ t.Cleanup(clock.ResetTime)

Also applies to: 116-117, 173-175, 220-222, 293-294, 350-351, 393-395, 451-452, 507-509


567-571: Typos in comments (“vlaues”, “lets”)

Minor polish for readability.

- // First lets assert the 3 vlaues
+ // First let's assert the 3 values
openmeter/entitlement/metered/reset_test.go (3)

37-58: Use clock.Now for deterministic CurrentUsagePeriod

getEntitlement computes CurrentUsagePeriod using time.Now(), which can diverge from the mocked clock. Use clock.Now() for determinism.

- currentUsagePeriod, err := input.UsagePeriod.GetValue().GetPeriodAt(time.Now()) // This should be calculated properly when testing batch resets
+ currentUsagePeriod, err := input.UsagePeriod.GetValue().GetPeriodAt(clock.Now()) // Align with mocked clock for deterministic tests

785-786: Fix test names: “reseting” → “resetting”

Minor typo in test titles.

- name: "Should reseting without anchor update keeps the next reset time intact",
+ name: "Should resetting without anchor update keeps the next reset time intact",
- name: "Should reseting with anchor update updates the next reset time too",
+ name: "Should resetting with anchor update updates the next reset time too",

Also applies to: 829-830


685-694: Comment contradicts config

ResetMaxRollover is set to 0, but the comment says “full amount can be rolled over.” Suggest correcting the comment to avoid confusion.

- ResetMaxRollover: 0, // full amount can be rolled over
+ ResetMaxRollover: 0, // no rollover
openmeter/entitlement/driver/parser.go (2)

212-246: Normalize default anchors to minute granularity

Creation paths use clock.Now() as default anchors; other parts (and tests) rely on minute truncation. Normalize to minute to avoid subtle off-by-seconds boundaries.

- request = entitlement.CreateEntitlementInputs{
+ now := clock.Now().Truncate(time.Minute)
+ request = entitlement.CreateEntitlementInputs{
   Namespace:               ns,
   FeatureID:               v.FeatureId,
   FeatureKey:              v.FeatureKey,
   UsageAttribution:        usageAttribution,
   EntitlementType:         entitlement.EntitlementTypeMetered,
   IsSoftLimit:             v.IsSoftLimit,
   IssueAfterReset:         v.IssueAfterReset,
   IssueAfterResetPriority: v.IssueAfterResetPriority,
-  UsagePeriod: lo.ToPtr(timeutil.AsTimed(func(r timeutil.Recurrence) time.Time {
-    return defaultx.WithDefault(v.UsagePeriod.Anchor, clock.Now())
+  UsagePeriod: lo.ToPtr(timeutil.AsTimed(func(r timeutil.Recurrence) time.Time {
+    return defaultx.WithDefault(v.UsagePeriod.Anchor, now)
   })(timeutil.Recurrence{
-    Anchor:   defaultx.WithDefault(v.UsagePeriod.Anchor, clock.Now()), // TODO: shouldn't we truncate this?
+    Anchor:   defaultx.WithDefault(v.UsagePeriod.Anchor, now),
     Interval: iv,
   })),

Apply the same normalization in the Static and Boolean branches.


212-246: Guardrail: validate non-empty usageAttribution

To fail fast on invalid input, consider rejecting requests where usageAttribution is empty (no ID/Key/SubjectKeys).

Would you like me to add a minimal validation here, or is this enforced upstream (e.g., in the HTTP layer)? If upstream, point me to the validator and I’ll cross-check the cases.

Also applies to: 282-306, 307-330

openmeter/ent/db/entitlement/entitlement.go (1)

40-46: Generated changes for Customer edge look consistent

CustomerID field, EdgeCustomer, order helpers, and newCustomerStep mirror existing Feature/Subject patterns. Assuming the ent schema and migration add NOT NULL FK and the intended indexes, this looks good.

  • Please confirm the migration includes:
    • entitlements.customer_id NOT NULL with FK to customers.id
    • composite index on (namespace, customer_id[, feature_id]) to serve common queries.
  • If helpful, I can review the migrate/schema diff as well.

Also applies to: 78-82, 119-126, 148-151, 272-275, 400-406, 448-454

openmeter/entitlement/metered/connector.go (2)

43-45: Harden input validation for the new customer-centric grant APIs.

  • CreateGrant: reject empty namespace/customerID/entitlementIdOrFeatureKey; consider idempotency key support to avoid duplicate grants on retries.
  • ListEntitlementGrants: validate params.CustomerID and clamp Page.Limit to a sane max; default Order/OrderBy when zero-valued.

Would you like a small guard snippet for these methods?


191-209: Ensure UsageAttribution is validated before persisting.
BeforeCreate now forwards model.UsageAttribution; if upstream doesn’t call CreateEntitlementInputs.Validate, add a cheap check here to fail fast on missing ID/subject keys.

Confirm the service layer always invokes Validate() prior to BeforeCreate to avoid silent bad data.

openmeter/entitlement/entitlement.go (2)

198-205: Relax validation to support key-only attribution (optional).
Requiring at least one SubjectKey may block setups that attribute by customer key. Consider allowing either subjectKeys or key.

Apply this diff:

   if c.UsageAttribution.ID == "" {
     return fmt.Errorf("usage attribution must have an id")
   }
-  if len(c.UsageAttribution.SubjectKeys) == 0 {
-    return fmt.Errorf("usage attribution must have at least one subject key")
-  }
+  // Accept either subjectKeys or key (both empty is invalid).
+  if len(c.UsageAttribution.SubjectKeys) == 0 && c.UsageAttribution.Key == nil {
+    return fmt.Errorf("usage attribution must have at least one subject key or a key")
+  }

358-361: No-op GenericProperties.Validate is fine for interface compliance.
Consider adding basic invariants in a follow-up (e.g., FeatureID/FeatureKey non-empty).

openmeter/entitlement/adapter/entitlement_test.go (1)

91-117: Tighten helper ergonomics and simplify context.

  • Make customer Name unique to ease debugging (include subjectKey).
  • Use context.Background() (no need for cancel in a short-lived helper).

Apply this diff:

-  ctx, cancel := context.WithCancel(context.Background())
-  defer cancel()
+  ctx := context.Background()
@@
-      Name: "Customer 1",
+      Name: fmt.Sprintf("Customer for %s", subjectKey),
openmeter/entitlement/snapshot/event.go (2)

91-106: EventMetadata likely needs Source set consistently; branch may be always-true.

Customer is now non-pointer and NewSnapshotEvent always fills it, so the first branch will typically run and Source stays empty. If Source is relied upon for routing/correlation, set it unconditionally and keep Subject as the customer/subjectKey path.

Apply:

-func (e SnapshotEvent) EventMetadata() metadata.EventMetadata {
-	if e.Customer.ID != "" {
-		return metadata.EventMetadata{
-			Subject: metadata.ComposeResourcePath(
-				e.Namespace.ID,
-				metadata.EntityCustomer, e.Customer.ID,
-				metadata.EntitySubjectKey, e.Subject.Key,
-			),
-		}
-	}
-
-	return metadata.EventMetadata{
-		Source:  metadata.ComposeResourcePath(e.Namespace.ID, metadata.EntityEntitlement, e.Entitlement.ID),
-		Subject: metadata.ComposeResourcePath(e.Namespace.ID, metadata.EntityCustomer, e.Customer.ID),
-	}
-}
+func (e SnapshotEvent) EventMetadata() metadata.EventMetadata {
+	em := metadata.EventMetadata{
+		Source: metadata.ComposeResourcePath(e.Namespace.ID, metadata.EntityEntitlement, e.Entitlement.ID),
+	}
+	// Prefer customer/subjectKey path when subject key is available.
+	if e.Customer.ID != "" && e.Subject.Key != "" {
+		em.Subject = metadata.ComposeResourcePath(
+			e.Namespace.ID,
+			metadata.EntityCustomer, e.Customer.ID,
+			metadata.EntitySubjectKey, e.Subject.Key,
+		)
+	} else if e.Customer.ID != "" {
+		em.Subject = metadata.ComposeResourcePath(e.Namespace.ID, metadata.EntityCustomer, e.Customer.ID)
+	}
+	return em
+}

135-137: Trailing space in error text.

Minor polish.

-		errs = append(errs, errors.New("calculatedAt is required "))
+		errs = append(errs, errors.New("calculatedAt is required"))
openmeter/entitlement/driver/metered.go (2)

197-207: Pagination default (1,1000): confirm it meets API guarantees.

If clients expect all grants, surface pagination parameters or iterate until exhaustion.


260-267: SubjectID field is populated with a SubjectKey — rename or remove.

The request struct uses SubjectID but you assign SubjectKey; it’s also unused downstream. Rename to SubjectKey or drop it.

 type ResetEntitlementUsageHandlerRequest struct {
   EntitlementID   string
   Namespace       string
-  SubjectID       string
   At              time.Time
   RetainAnchor    bool
   PreserveOverage *bool
 }
@@
-        SubjectID:       params.SubjectKey,
openmeter/ent/db/entitlement.go (1)

477-485: Consider redacting subject_key in String() for logs.

If keys can be sensitive, omit or hash in String(). Optional.

openmeter/credit/driver/grant.go (1)

235-241: Validate OrderBy like v1 handler to reject invalid fields.

Mirror the v1 check to avoid accepting unknown order-by values.

 		func(ctx context.Context, r *http.Request, p ListGrantsV2HandlerParams) (ListGrantsV2HandlerRequest, error) {
 			ns, err := h.resolveNamespace(ctx)
 			if err != nil {
 				return ListGrantsV2HandlerRequest{}, err
 			}
 
+			// validate OrderBy (same as v1)
+			if p.Params.OrderBy != nil {
+				if !slices.Contains(grant.OrderBy("").StrValues(), strcase.CamelToSnake(string(*p.Params.OrderBy))) {
+					return ListGrantsV2HandlerRequest{}, commonhttp.NewHTTPError(http.StatusBadRequest, errors.New("invalid order by"))
+				}
+			}
openmeter/ent/db/migrate/schema.go (1)

1422-1450: Migration risk: adding non-null customer_id to entitlements with FKs and new indexes.

Adding customer_id (non-null) plus FKs/indexes can fail on populated tables. Recommend a 2-step, online-safe migration:

  • Phase 1: add customer_id NULLABLE; backfill in batches; create indexes concurrently; add FK NOT VALID.
  • Phase 2: validate FK; set column NOT NULL; swap or add new composite indexes; drop any obsolete indexes.

Document exact order for Postgres (CREATE INDEX CONCURRENTLY, ALTER TABLE ... VALIDATE CONSTRAINT) and ensure app code tolerates transient NULLs during rollout.

Also applies to: 1468-1491, 2575-2637

openmeter/entitlement/metered/entitlement_grant.go (2)

50-56: Capture a single 'now' for consistency across lookups and mapping.

Use one clock snapshot per request to avoid subtle time drift between repo lookups and NextRecurrence calculations.

 func (e *connector) CreateGrant(ctx context.Context, namespace string, customerID string, entitlementIdOrFeatureKey string, inputGrant CreateEntitlementGrantInputs) (EntitlementGrant, error) {
+	now := clock.Now()
 	// First we attempt to find the entitlement by ID, then by featureKey
 	ent, err := e.entitlementRepo.GetEntitlement(ctx, models.NamespacedID{Namespace: namespace, ID: entitlementIdOrFeatureKey})
 	if _, ok := lo.ErrorsAs[*entitlement.NotFoundError](err); ok {
-		ent, err = e.entitlementRepo.GetActiveEntitlementOfCustomerAt(ctx, namespace, customerID, entitlementIdOrFeatureKey, clock.Now())
+		ent, err = e.entitlementRepo.GetActiveEntitlementOfCustomerAt(ctx, namespace, customerID, entitlementIdOrFeatureKey, now)
 	}
@@
-	eg, err := GrantFromCreditGrant(*g, clock.Now())
+	eg, err := GrantFromCreditGrant(*g, now)
 	if err != nil {
 		return EntitlementGrant{}, err
 	}
 	return *eg, nil
 }
@@
 func (e *connector) ListEntitlementGrants(ctx context.Context, namespace string, params ListEntitlementGrantsParams) (pagination.PagedResponse[EntitlementGrant], error) {
 	var def pagination.PagedResponse[EntitlementGrant]
+	now := clock.Now()
 
 	if err := params.Validate(); err != nil {
 		return def, err
 	}
@@
 	ent, err := e.entitlementRepo.GetEntitlement(ctx, models.NamespacedID{Namespace: namespace, ID: params.EntitlementIDOrFeatureKey})
 	if _, ok := lo.ErrorsAs[*entitlement.NotFoundError](err); ok {
-		ent, err = e.entitlementRepo.GetActiveEntitlementOfCustomerAt(ctx, namespace, params.CustomerID, params.EntitlementIDOrFeatureKey, clock.Now())
+		ent, err = e.entitlementRepo.GetActiveEntitlementOfCustomerAt(ctx, namespace, params.CustomerID, params.EntitlementIDOrFeatureKey, now)
 	}
@@
-	return pagination.MapPagedResponseError(grants, func(grant grant.Grant) (EntitlementGrant, error) {
-		g, err := GrantFromCreditGrant(grant, clock.Now())
+	return pagination.MapPagedResponseError(grants, func(gr grant.Grant) (EntitlementGrant, error) {
+		g, err := GrantFromCreditGrant(gr, now)
 		if err != nil {
 			return EntitlementGrant{}, err
 		}
 		return *g, nil
 	})

Also applies to: 84-85, 96-103, 117-123


31-45: Consider validating/sanitizing Order and OrderBy.

Optional: enforce allowed OrderBy fields and default Order to ASC/DESC to prevent unexpected DB sorting.

If desired, I can add a tiny whitelist + defaulting in Validate() and update callers accordingly.

openmeter/server/router/entitlement.go (2)

146-159: Unify V2 customerIdOrKey parameter types for consistency.

Some V2 methods use api.ULIDOrExternalKey while others use string. Aligning them reduces confusion in the public surface.

Would you like a follow-up PR to switch all V2 Router methods to api.ULIDOrExternalKey where appropriate?

Also applies to: 161-168, 170-177, 181-186, 189-196, 200-205, 219-224, 229-233


121-124: Move GetCustomerAccess under the V2 block (nit).

Comment says /api/v2 but it sits inside the V1 grouping banner. Relocate for consistency or update the banner.

Also applies to: 134-141

openmeter/entitlement/adapter/entitlement.go (5)

324-346: Customer-scoped active entitlements — LGTM; consider DRYing edge-loading

Logic is solid. You could factor a tiny helper to attach WithCustomer(WithSubjects(DeletedAtIsNil)) to reduce repetition.


370-375: Edge loading in ListEntitlements — consider helper

Same WithCustomer().WithSubjects(...) pattern as elsewhere. Extracting a helper improves readability and consistency.


554-556: Propagate customer mapping error instead of silently skipping

Silently ignoring map errors can hide data issues; return a wrapped error.

-    if mapped, mapErr := customeradapter.CustomerFromDBEntity(*e.Edges.Customer); mapErr == nil {
-        ent.Customer = mapped
-    }
+    mapped, mapErr := customeradapter.CustomerFromDBEntity(*e.Edges.Customer)
+    if mapErr != nil {
+        return nil, fmt.Errorf("failed to map customer for entitlement %s: %w", e.ID, mapErr)
+    }
+    ent.Customer = mapped

633-654: Harden validation when customer subjects are not preloaded

If e.Edges.Customer.Edges.Subjects is nil, the loop yields a false negative. Assert preload to avoid silent mismatches.

 func (a *entitlementDBAdapter) validateSubjectKeysMatch(e *db.Entitlement) error {
@@
-    found := false
+    if e.Edges.Customer.Edges.Subjects == nil {
+        return fmt.Errorf("entitlement %s customer subjects not loaded; ensure WithCustomer().WithSubjects(...)", e.ID)
+    }
+    found := false

694-695: Remove unnecessary WithCustomer() from existence check

You don't use the customer edge later; drop it to reduce query cost.

-                ).
-                WithCustomer().
+                ).
openmeter/ent/db/mutation.go (1)

30375-30381: Nit: fix docstring to match function name

Update the comment to say “RemovedEntitlementsIDs returns …” to match the function.

-// RemovedEntitlements returns the removed IDs of the "entitlements" edge to the Entitlement entity.
+// RemovedEntitlementsIDs returns the removed IDs of the "entitlements" edge to the Entitlement entity.

Comment thread e2e/entitlement_test.go Resolved
Comment thread openmeter/notification/entitlements.go Resolved
Comment thread tools/migrate/entitlement_test.go Resolved
Comment thread tools/migrate/entitlement_test.go Resolved
Comment thread tools/migrate/entitlement_test.go Resolved

@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 (8)
e2e/entitlement_parity_test.go (8)

311-319: Make meter query window explicit to reduce flakiness

Without a From bound, server defaults may miss recent events. Set From to a safe window before To.

Apply:

-				resp, err := client.QueryMeterWithResponse(ctx, meterSlug, &api.QueryMeterParams{
-					To: convert.ToPointer(time.Now().Truncate(time.Minute)),
-				})
+				resp, err := client.QueryMeterWithResponse(ctx, meterSlug, &api.QueryMeterParams{
+					From: convert.ToPointer(time.Now().Add(-2 * time.Minute).Truncate(time.Minute)),
+					To:   convert.ToPointer(time.Now().Truncate(time.Minute)),
+				})

366-369: Use tolerant float comparison for cross-API equality

Minor numeric drift can fail strict equality. Use a small delta.

Apply:

-			assert.Equal(t, v1ValueForSubjectByID, v2ValueForV1ByKey, "v1(ID) vs v2(by feature1Key) should match")
-			assert.Equal(t, v1ValueForV2ByKey, v2ValueForV2ByKey, "v1(by feature2Key) vs v2(by feature2Key) should match")
+			assert.InDelta(t, v1ValueForSubjectByID, v2ValueForV1ByKey, 1e-9, "v1(ID) vs v2(by feature1Key) should match")
+			assert.InDelta(t, v1ValueForV2ByKey, v2ValueForV2ByKey, 1e-9, "v1(by feature2Key) vs v2(by feature2Key) should match")

156-158: Standardize pointer helper and drop unused dependency

Use the existing convert.ToPointer for consistency and remove lo import.

Apply:

-			resp, err := client.ListCustomerEntitlementsV2WithResponse(ctx, customerID, &api.ListCustomerEntitlementsV2Params{
-				Page:     lo.ToPtr(1),
-				PageSize: lo.ToPtr(100),
-			})
+			resp, err := client.ListCustomerEntitlementsV2WithResponse(ctx, customerID, &api.ListCustomerEntitlementsV2Params{
+				Page:     convert.ToPointer(1),
+				PageSize: convert.ToPointer(100),
+			})

And in imports:

-	"github.com/samber/lo"

Also applies to: 13-13


26-28: Prefer context timeout for E2E tests

Avoid hanging tests; bound the context.

Apply:

-	ctx, cancel := context.WithCancel(context.Background())
+	ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)

292-295: Check error from SetData

If marshalling fails, the ingest will later 4xx. Fail fast in test.

Apply:

-				_ = ev.SetData("application/json", map[string]string{
-					"value": value,
-				})
+				require.NoError(t, ev.SetData("application/json", map[string]string{
+					"value": value,
+				}))

32-34: Harden test key uniqueness

Using Unix seconds risks collisions in parallel/reruns. Switch to higher entropy to prevent 409s.

Apply:

-	customerKey := fmt.Sprintf("parity_cust_%d", time.Now().Unix())
+	customerKey := fmt.Sprintf("parity_cust_%d", time.Now().UnixNano())
-		randKey := fmt.Sprintf("entitlement_parity_feature_1_%d", time.Now().Unix())
+		randKey := fmt.Sprintf("entitlement_parity_feature_1_%d", time.Now().UnixNano())
-		randKey := fmt.Sprintf("entitlement_parity_feature_2_%d", time.Now().Unix())
+		randKey := fmt.Sprintf("entitlement_parity_feature_2_%d", time.Now().UnixNano())

Also applies to: 43-48, 58-63


127-130: Compare times using time.Equal

Avoid string formatting; compare time values directly.

Apply:

-			require.NotNil(t, v2.UsagePeriod)
-			require.Equal(t, anchor.Format(time.RFC3339), v2.UsagePeriod.Anchor.Format(time.RFC3339))
+			require.NotNil(t, v2.UsagePeriod)
+			require.True(t, v2.UsagePeriod.Anchor.Equal(*anchor), "usage period anchor mismatch")

301-308: Avoid fixed sleep before Eventually

The explicit sleep adds test time and may still be flaky. Rely on Eventually only, or gate the sleep behind a debug flag.

Example:

-			time.Sleep(5 * time.Second)
+			// Optionally keep but guard with an env flag if needed for CI flakiness:
+			// if os.Getenv("OPENMETER_E2E_DELAY") == "1" { time.Sleep(5 * time.Second) }
📜 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 9a209a2 and de657bd.

📒 Files selected for processing (2)
  • Makefile (1 hunks)
  • e2e/entitlement_parity_test.go (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
e2e/entitlement_parity_test.go (2)
e2e/helpers.go (1)
  • CreateCustomerWithSubject (16-48)
pkg/convert/ptr.go (1)
  • ToPointer (10-12)
⏰ 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). (7)
  • GitHub Check: Artifacts / Container image
  • GitHub Check: Code Generators
  • GitHub Check: Test
  • GitHub Check: Lint
  • GitHub Check: Migration Checks
  • GitHub Check: Build
  • GitHub Check: Analyze (go)
🔇 Additional comments (1)
e2e/entitlement_parity_test.go (1)

21-24: Nice end-to-end parity coverage

Good structure and clear cross-API assertions. This will catch real regressions between v1 (subject) and v2 (customer) paths.

Comment thread e2e/entitlement_parity_test.go Resolved
Comment thread Makefile Resolved
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