Repository navigation
feat(llmcost): add - #3905
feat(llmcost): add#3905
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughAdds a feature-cost subsystem: domain interfaces, adapter and compute pipeline, service wiring, HTTP handler and router wiring, product-catalog UnitCost model and validations, DB migrations, tests, and seed changes to expose and use a CostService. Changes
Sequence Diagram(s)sequenceDiagram
participant Client as Client/HTTP
participant Handler as CostHandler
participant Service as CostService
participant Adapter as CostAdapter
participant Feature as FeatureConnector
participant Streaming as Streaming
participant LLMCost as LLMCostService
Client->>Handler: QueryFeatureCost(featureID, params)
Handler->>Handler: Resolve namespace & build query params
Handler->>Service: QueryFeatureCost(input)
Service->>Adapter: QueryFeatureCost(input)
Adapter->>Feature: Load feature metadata
Feature-->>Adapter: Feature data
Adapter->>Streaming: Query usage rows
Streaming-->>Adapter: Usage rows
Adapter->>LLMCost: Pre-resolve model pricing (if LLM)
LLMCost-->>Adapter: Model pricing
Adapter->>Adapter: Resolve unit costs & compute/aggregate rows
Adapter-->>Service: CostQueryResult
Service-->>Handler: CostQueryResult
Handler-->>Client: HTTP 200 + mapped API response
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Suggested labels
Suggested reviewers
🚥 Pre-merge checks | ✅ 1 | ❌ 2❌ Failed checks (1 warning, 1 inconclusive)
✅ Passed checks (1 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
02b31ad to
dbf54de
Compare
89aca40 to
62650d7
Compare
There was a problem hiding this comment.
Actionable comments posted: 8
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
openmeter/server/router/router.go (1)
133-239:⚠️ Potential issue | 🟠 Major
CostServiceis wired but never validated.
NewRouteralways buildscostHandlerfromconfig.CostService, butConfig.Validate()doesn’t require it. A nil service can slip through and fail at request time.✅ Minimal fix
func (c Config) Validate() error { + if c.CostService == nil { + return errors.New("cost service is required") + } + if c.NamespaceManager == nil { return errors.New("namespace manager is required") }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/server/router/router.go` around lines 133 - 239, Config.Validate currently omits checking CostService so NewRouter can build costHandler from a nil config.CostService and panic at request time; update Config.Validate to return an error when c.CostService == nil (similar to the other checks) so the router construction fails fast, referencing the Config.Validate method and the NewRouter/costHandler usage of config.CostService.
🧹 Nitpick comments (9)
etc/seed/seed.yaml (1)
17-21: Optional cleanup: remove the legacy commented mapping line.The old commented
timeassignment at Line 17 is a bit distracting now that selection logic changed. Dropping it would keep the seed mapping easier to scan.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@etc/seed/seed.yaml` around lines 17 - 21, Remove the legacy commented mapping line starting with "let time = (now().ts_sub_iso8601..." from the seed YAML to clean up the file; keep the active selection logic using let idx, let selection, let provider, and let model untouched, and verify there are no lingering references to the commented time variable elsewhere before committing.openmeter/productcatalog/feature/connector.go (1)
139-141: Tiny cleanup: remove the unreachableerrcheck.After the earlier early-returns, this
if err != nilblock is redundant and can be removed for clarity.🧹 Suggested cleanup
- if err != nil { - return Feature{}, err - }As per coding guidelines
**/*.go: In general when reviewing the Golang code make readability and maintainability a priority.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/productcatalog/feature/connector.go` around lines 139 - 141, Remove the redundant unreachable error check: inside the function handling feature creation in connector.go (locate the block that currently does "if err != nil { return Feature{}, err }" after prior early returns), delete that if-statement since all error paths already returned earlier, and simplify the flow to directly return the constructed Feature (or the existing return statement) without checking err again.openmeter/productcatalog/adapter/feature.go (1)
55-73: Consider extracting unit-cost mapping into small helpers.Both write-side and read-side now carry parallel
switchblocks for manual/LLM mapping. A helper pair would reduce drift risk and keep this adapter easier to maintain.As per coding guidelines
**/*.go: In general when reviewing the Golang code make readability and maintainability a priority.Also applies to: 295-321
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/productcatalog/adapter/feature.go` around lines 55 - 73, The unit-cost mapping in the write-side switch (handling feat.UnitCost with cases feature.UnitCostTypeManual and feature.UnitCostTypeLLM, calling SetUnitCostType, SetUnitCostManualAmount and the chain of SetNillableUnitCostLlm* methods) should be extracted into a small helper like mapUnitCostToQuery(query, unitCost) to centralize logic (handle nil, set type, manual amount, and use lo.EmptyableToPtr for LLM fields); do the symmetric extraction on the read-side (the parallel switch around lines 295-321) into a helper like mapQueryToUnitCost(entity) so both sides share clear, testable mapping and reduce drift risk.openmeter/ent/schema/feature.go (1)
36-45: Add schema-level constraints forunit_cost_typeand companion fields.Right now this can persist inconsistent combinations (for example, unknown
unit_cost_type, ormanualtype withoutunit_cost_manual_amount) and fail later at runtime. Consider makingunit_cost_typean enum and enforcing type-specific field presence via DB checks/hooks.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/ent/schema/feature.go` around lines 36 - 45, The Feature schema allows inconsistent unit cost data; make unit_cost_type an enum and add DB-level constraints or Ent hooks to enforce type-specific companion fields: restrict unit_cost_type to allowed values (e.g., "manual","llm", etc.) and ensure when unit_cost_type == "manual" that unit_cost_manual_amount (field unit_cost_manual_amount) is non-null, and when unit_cost_type == "llm" that the LLM-related fields (unit_cost_llm_provider, unit_cost_llm_model, unit_cost_llm_token_type and their _property counterparts) are present as required; implement this by changing the Feature Ent schema field definition for unit_cost_type to use an enum/constraints and adding either a SQL CHECK constraint or an Ent mutate/validation hook on the Feature schema to validate these conditional presence rules before persist.openmeter/cost/adapter/adapter.go (1)
146-194: Nice dedupe — next step is batchingResolvePricecalls for high-cardinality queries.This still performs one lookup per unique
(provider, model)in-request. On larger result sets, a batch resolve API would reduce latency and keep this endpoint more predictable.As per coding guidelines: "Performance should be a priority in critical code paths... database operations... should be vetted for potential performance bottlenecks."
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/cost/adapter/adapter.go` around lines 146 - 194, Collect unique (provider, model) pairs first in getLLMPrices, build a slice of llmcost.ResolvePriceInput for those keys, and call a batched API on the llmcostService (e.g., add and use llmcostService.ResolvePrices(ctx, []ResolvePriceInput) that returns a map[(provider,model)] -> (price,error) or a slice you can map back). Then populate cache (llmPriceKey -> llmPriceResult) from the batched response and keep skipping unresolved pairs as before; ensure you reference getLLMPrices, llmPriceKey, llmPriceResult and llmcost.ResolvePriceInput and update error handling to attach the per-key errors from the batch response into the cache.openmeter/cost/adapter/compute_test.go (1)
34-675: Great unit coverage — consider one integration-level test for the query path too.This suite is strong. I’d add one lightweight integration test through service/HTTP handler to protect wiring + contract behavior end-to-end (especially internal group-by stripping and unresolved detail propagation).
As per coding guidelines: "
**/*_test.go: Make sure the tests are comprehensive and cover the changes... When appropriate, recommend e2e tests for critical changes."🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/cost/adapter/compute_test.go` around lines 34 - 675, Add a lightweight integration test that exercises the cost HTTP handler end-to-end (so wiring + computeCostRows are exercised) by starting the handler (e.g., CostHandler or the package's registered cost route), sending a request containing meter rows that include internal keys and one unresolved price, and asserting the JSON response: aggregated row(s) have internal group-by keys stripped and the Detail field contains the unresolved pricing message; this test should reuse computeCostRows semantics (so reference computeCostRows) and the same resolver behavior used in unit tests to verify unresolved-detail propagation and aggregation over internal keys.openmeter/cost/adapter/compute.go (1)
190-193: Nice to optimize exclude-key lookup here (hot path).
filterGroupBydoesslices.Containsper key, per row. Precomputing a set once will make this cheaper under large result sets.As per coding guidelines: "Performance should be a priority in critical code paths. Anything related to ... database operations ... should be vetted for potential performance bottlenecks."
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/cost/adapter/compute.go` around lines 190 - 193, filterGroupBy currently calls slices.Contains(excludeKeys, k) inside the loop which is O(n) per key; precompute a set (map[string]struct{}) from excludeKeys once before iterating and replace slices.Contains with a constant-time lookup (e.g., _, excluded := excludeSet[k]) to improve hot-path performance; ensure you still initialize and populate the returned maps (filtered and values) the same way and reference the function name filterGroupBy and the excludeKeys parameter when making the change.api/spec/src/productcatalog/features.tsp (1)
153-159: Consider a dedicated enum fortokenTypeinstead of plainstring.Backend logic validates a fixed set of token types, but the API schema currently allows any string. Modeling this as an enum improves parity and client-side validation.
Suggested fix
+@friendlyName("FeatureLLMTokenType") +enum FeatureLLMTokenType { + input: "input", + output: "output", + cacheRead: "cache_read", + reasoning: "reasoning", + cacheWrite: "cache_write", +} @@ - tokenType?: string; + tokenType?: FeatureLLMTokenType;As per coding guidelines: "The declared API should be accurate, in parity with the actual implementation, and easy to understand for the user."
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@api/spec/src/productcatalog/features.tsp` around lines 153 - 159, The schema exposes tokenType as a free-form string but backend accepts a fixed set; change tokenType to a dedicated enum and use it where currently referenced (tokenType) and ensure it remains mutually exclusive with tokenTypeProperty; define an enum (TokenType) with values input, output, cache_read, reasoning, cache_write, replace tokenType?: string with tokenType?: TokenType (or the equivalent union type), update the `@summary/doc` comment accordingly, and ensure any validators or types that consume tokenType are updated to the new enum type.openmeter/cost/httpdriver/handler.go (1)
223-226: Tiny perf win: dedupecustomerIDsbeforeListCustomers.If the request contains duplicates, this does extra DB work and extra not-found checks for no benefit.
Suggested fix
- customers, err := h.customerService.ListCustomers(ctx, customer.ListCustomersInput{ + uniqueCustomerIDs := lo.Uniq(customerIDs) + + customers, err := h.customerService.ListCustomers(ctx, customer.ListCustomersInput{ Namespace: namespace, - CustomerIDs: customerIDs, + CustomerIDs: uniqueCustomerIDs, }) @@ - for _, id := range customerIDs { + for _, id := range uniqueCustomerIDs { if _, ok := customersById[id]; !ok { return nil, models.NewGenericNotFoundError(fmt.Errorf("customer with id %s not found", id)) } }As per coding guidelines: "Performance should be a priority in critical code paths ... database operations ... should be vetted for potential performance bottlenecks."
Also applies to: 235-239
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/cost/httpdriver/handler.go` around lines 223 - 226, Dedupe the customerIDs slice before calling h.customerService.ListCustomers to avoid duplicate DB work: create a small utility (or inline) that iterates customerIDs into a map/set to filter duplicates while preserving order, then pass the deduped slice to h.customerService.ListCustomers (the initial call using variable customerIDs) and to the later ListCustomers invocation referenced in the same handler; ensure the deduped slice type matches the original (e.g., []string or []UUID) and reuse the deduped variable for both calls.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@CLAUDE.md`:
- Around line 106-118: The fenced code block in CLAUDE.md is missing a language
identifier causing MD040 lint failures; update the opening triple-backtick for
the directory listing block in CLAUDE.md (the fenced code block containing the
project folder list) to include a language tag such as text (e.g., ```text) so
the linter recognizes the block as plain text and the MD040 warning is resolved.
In `@openmeter/cost/adapter/adapter.go`:
- Around line 89-99: The merge logic in adapter.go currently keeps request-level
params.FilterGroupBy values when keys collide with feat.MeterGroupByFilters;
change it so feature-level filters take precedence: build the merged map from
params.FilterGroupBy as now, then copy all entries from feat.MeterGroupByFilters
into merged unconditionally (overwrite any existing keys) so
feat.MeterGroupByFilters wins; update the block that creates merged and assigns
params.FilterGroupBy accordingly (remove the exists check) to ensure feature
filters cannot be overridden by caller filters.
In `@openmeter/productcatalog/driver/parser.go`:
- Around line 100-140: The apiUnitCostToDomain function currently swallows
errors from u.Discriminator(), u.AsFeatureManualUnitCost(),
u.AsFeatureLLMUnitCost(), and alpacadecimal.NewFromString; change its signature
to return (*feature.UnitCost, error), return errors instead of nil on failures,
validate and propagate decimal parse errors (from alpacadecimal.NewFromString)
and the AsFeature* conversion errors, and update the single caller in feature.go
to handle the error (fail-fast on conversion). Locate apiUnitCostToDomain, the
Discriminator/AsFeatureManualUnitCost/AsFeatureLLMUnitCost calls, and the
NewFromString usage to implement these changes and propagate the error up.
In `@openmeter/productcatalog/feature/feature.go`:
- Around line 135-136: Feature.Validate() currently skips validating the new
UnitCost field; update the Feature.Validate method to validate UnitCost when
non-nil by invoking the UnitCost's validation routine (e.g., call
UnitCost.Validate() or equivalent) and return a descriptive error if that
validation fails so invalid unit-cost configs cannot be accepted; ensure you
reference the Feature struct's UnitCost pointer and propagate the error from
Feature.Validate() to callers.
In `@openmeter/productcatalog/feature/unitcost.go`:
- Around line 75-89: The validator currently checks presence and non-negativity
for Manual and presence for LLM but doesn't enforce exclusivity; update the
validation branch for UnitCostTypeManual to also return an error if u.LLM !=
nil, and update the UnitCostTypeLLM branch to return an error if u.Manual != nil
(also apply the same exclusivity checks noted around the other occurrence at the
130-132 area); locate the branches using the symbols UnitCostTypeManual,
UnitCostTypeLLM, u.Manual and u.LLM and add explicit errors like "manual type
must not include llm configuration" / "llm type must not include manual
configuration" to reject ambiguous configs.
In `@openmeter/server/server_test.go`:
- Line 517: Add a focused test in the existing TestRoutes (or the test that
constructs the router using NoopCostService) that issues an HTTP GET to the new
path "/api/v1/features/{featureId}/cost" (use a sample featureId) against the
same router instance wired with &NoopCostService{}; assert the handler responds
with the expected HTTP status (e.g., 200) and the expected JSON structure/body
the NoopCostService returns, and verify Content-Type is application/json to
catch encoding/wiring regressions; locate the router setup in TestRoutes and the
NoopCostService type to add this case.
In `@tools/migrate/migrations/20260303205801_llmcost_add.up.sql`:
- Around line 24-27: The migration adds a redundant unique index: after PRIMARY
KEY ("id") on table "llm_cost_prices" the explicit statement CREATE UNIQUE INDEX
"llmcostprice_id" ON "llm_cost_prices" ("id") should be removed; edit the
migration to drop the CREATE UNIQUE INDEX "llmcostprice_id" line (or omit
creating that index) so only the primary key remains, avoiding duplicate indexes
and extra storage/write overhead.
---
Outside diff comments:
In `@openmeter/server/router/router.go`:
- Around line 133-239: Config.Validate currently omits checking CostService so
NewRouter can build costHandler from a nil config.CostService and panic at
request time; update Config.Validate to return an error when c.CostService ==
nil (similar to the other checks) so the router construction fails fast,
referencing the Config.Validate method and the NewRouter/costHandler usage of
config.CostService.
---
Nitpick comments:
In `@api/spec/src/productcatalog/features.tsp`:
- Around line 153-159: The schema exposes tokenType as a free-form string but
backend accepts a fixed set; change tokenType to a dedicated enum and use it
where currently referenced (tokenType) and ensure it remains mutually exclusive
with tokenTypeProperty; define an enum (TokenType) with values input, output,
cache_read, reasoning, cache_write, replace tokenType?: string with tokenType?:
TokenType (or the equivalent union type), update the `@summary/doc` comment
accordingly, and ensure any validators or types that consume tokenType are
updated to the new enum type.
In `@etc/seed/seed.yaml`:
- Around line 17-21: Remove the legacy commented mapping line starting with "let
time = (now().ts_sub_iso8601..." from the seed YAML to clean up the file; keep
the active selection logic using let idx, let selection, let provider, and let
model untouched, and verify there are no lingering references to the commented
time variable elsewhere before committing.
In `@openmeter/cost/adapter/adapter.go`:
- Around line 146-194: Collect unique (provider, model) pairs first in
getLLMPrices, build a slice of llmcost.ResolvePriceInput for those keys, and
call a batched API on the llmcostService (e.g., add and use
llmcostService.ResolvePrices(ctx, []ResolvePriceInput) that returns a
map[(provider,model)] -> (price,error) or a slice you can map back). Then
populate cache (llmPriceKey -> llmPriceResult) from the batched response and
keep skipping unresolved pairs as before; ensure you reference getLLMPrices,
llmPriceKey, llmPriceResult and llmcost.ResolvePriceInput and update error
handling to attach the per-key errors from the batch response into the cache.
In `@openmeter/cost/adapter/compute_test.go`:
- Around line 34-675: Add a lightweight integration test that exercises the cost
HTTP handler end-to-end (so wiring + computeCostRows are exercised) by starting
the handler (e.g., CostHandler or the package's registered cost route), sending
a request containing meter rows that include internal keys and one unresolved
price, and asserting the JSON response: aggregated row(s) have internal group-by
keys stripped and the Detail field contains the unresolved pricing message; this
test should reuse computeCostRows semantics (so reference computeCostRows) and
the same resolver behavior used in unit tests to verify unresolved-detail
propagation and aggregation over internal keys.
In `@openmeter/cost/adapter/compute.go`:
- Around line 190-193: filterGroupBy currently calls
slices.Contains(excludeKeys, k) inside the loop which is O(n) per key;
precompute a set (map[string]struct{}) from excludeKeys once before iterating
and replace slices.Contains with a constant-time lookup (e.g., _, excluded :=
excludeSet[k]) to improve hot-path performance; ensure you still initialize and
populate the returned maps (filtered and values) the same way and reference the
function name filterGroupBy and the excludeKeys parameter when making the
change.
In `@openmeter/cost/httpdriver/handler.go`:
- Around line 223-226: Dedupe the customerIDs slice before calling
h.customerService.ListCustomers to avoid duplicate DB work: create a small
utility (or inline) that iterates customerIDs into a map/set to filter
duplicates while preserving order, then pass the deduped slice to
h.customerService.ListCustomers (the initial call using variable customerIDs)
and to the later ListCustomers invocation referenced in the same handler; ensure
the deduped slice type matches the original (e.g., []string or []UUID) and reuse
the deduped variable for both calls.
In `@openmeter/ent/schema/feature.go`:
- Around line 36-45: The Feature schema allows inconsistent unit cost data; make
unit_cost_type an enum and add DB-level constraints or Ent hooks to enforce
type-specific companion fields: restrict unit_cost_type to allowed values (e.g.,
"manual","llm", etc.) and ensure when unit_cost_type == "manual" that
unit_cost_manual_amount (field unit_cost_manual_amount) is non-null, and when
unit_cost_type == "llm" that the LLM-related fields (unit_cost_llm_provider,
unit_cost_llm_model, unit_cost_llm_token_type and their _property counterparts)
are present as required; implement this by changing the Feature Ent schema field
definition for unit_cost_type to use an enum/constraints and adding either a SQL
CHECK constraint or an Ent mutate/validation hook on the Feature schema to
validate these conditional presence rules before persist.
In `@openmeter/productcatalog/adapter/feature.go`:
- Around line 55-73: The unit-cost mapping in the write-side switch (handling
feat.UnitCost with cases feature.UnitCostTypeManual and feature.UnitCostTypeLLM,
calling SetUnitCostType, SetUnitCostManualAmount and the chain of
SetNillableUnitCostLlm* methods) should be extracted into a small helper like
mapUnitCostToQuery(query, unitCost) to centralize logic (handle nil, set type,
manual amount, and use lo.EmptyableToPtr for LLM fields); do the symmetric
extraction on the read-side (the parallel switch around lines 295-321) into a
helper like mapQueryToUnitCost(entity) so both sides share clear, testable
mapping and reduce drift risk.
In `@openmeter/productcatalog/feature/connector.go`:
- Around line 139-141: Remove the redundant unreachable error check: inside the
function handling feature creation in connector.go (locate the block that
currently does "if err != nil { return Feature{}, err }" after prior early
returns), delete that if-statement since all error paths already returned
earlier, and simplify the flow to directly return the constructed Feature (or
the existing return statement) without checking err again.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 7dd40b68-f007-4e8b-8bbf-c33904d0dd96
⛔ Files ignored due to path filters (19)
api/client/go/client.gen.gois excluded by!api/client/**api/client/javascript/src/client/schemas.tsis excluded by!api/client/**api/client/javascript/src/zod/index.tsis excluded by!api/client/**api/client/python/openmeter/_generated/aio/operations/_operations.pyis excluded by!**/_generated/**,!api/client/**api/client/python/openmeter/_generated/models/__init__.pyis excluded by!**/_generated/**,!api/client/**api/client/python/openmeter/_generated/models/_enums.pyis excluded by!**/_generated/**,!api/client/**api/client/python/openmeter/_generated/models/_models.pyis excluded by!**/_generated/**,!api/client/**api/client/python/openmeter/_generated/operations/_operations.pyis excluded by!**/_generated/**,!api/client/**api/client/python/openmeter/_types.pyis excluded by!api/client/**api/openapi.cloud.yamlis excluded by!**/openapi.cloud.yamlapi/openapi.yamlis excluded by!**/openapi.yamlopenmeter/ent/db/feature.gois excluded by!**/ent/db/**openmeter/ent/db/feature/feature.gois excluded by!**/ent/db/**openmeter/ent/db/feature/where.gois excluded by!**/ent/db/**openmeter/ent/db/feature_create.gois excluded by!**/ent/db/**openmeter/ent/db/feature_update.gois excluded by!**/ent/db/**openmeter/ent/db/migrate/schema.gois excluded by!**/ent/db/**openmeter/ent/db/mutation.gois excluded by!**/ent/db/**openmeter/ent/db/setorclear.gois excluded by!**/ent/db/**
📒 Files selected for processing (29)
CLAUDE.mdapi/api.gen.goapi/spec/src/productcatalog/features.tspapi/spec/src/productcatalog/routes.tspapp/common/productcatalog.gocmd/jobs/quickstart/cronjobs.gocmd/server/main.gocmd/server/wire.gocmd/server/wire_gen.goetc/seed/seed.yamlopenmeter/cost/adapter.goopenmeter/cost/adapter/adapter.goopenmeter/cost/adapter/compute.goopenmeter/cost/adapter/compute_test.goopenmeter/cost/httpdriver/handler.goopenmeter/cost/service.goopenmeter/cost/service/service.goopenmeter/ent/schema/feature.goopenmeter/productcatalog/adapter/feature.goopenmeter/productcatalog/driver/feature.goopenmeter/productcatalog/driver/parser.goopenmeter/productcatalog/feature/connector.goopenmeter/productcatalog/feature/feature.goopenmeter/productcatalog/feature/unitcost.goopenmeter/server/router/product_catalog.goopenmeter/server/router/router.goopenmeter/server/server_test.gotools/migrate/migrations/20260303205801_llmcost_add.down.sqltools/migrate/migrations/20260303205801_llmcost_add.up.sql
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (3)
openmeter/productcatalog/driver/parser.go (2)
160-198: Silent nil return on pricing resolution errors.
resolveLLMPricingreturnsnilon error (line 193-195), which means failed pricing lookups are silently skipped. This seems intentional for graceful degradation, but it might make debugging pricing issues harder.If this is the intended behavior (best-effort enrichment), it's fine as-is. If you want visibility into failures, consider logging the error before returning nil.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/productcatalog/driver/parser.go` around lines 160 - 198, The resolveLLMPricing function currently drops errors from svc.ResolvePrice and returns nil silently; change the error branch in resolveLLMPricing to log the failure before returning (e.g., use the package's logger or a contextual logger available in scope) and include helpful fields: feat.Namespace, provider, model (or llmConf.Model/ModelProperty), and err so pricing lookup failures are visible for debugging while preserving the graceful nil return behavior.
244-246: Ignored error fromFromFeatureLLMUnitCost.The error from
resp.UnitCost.FromFeatureLLMUnitCost(llmCost)is discarded with a blank identifier. While this function is already past the discriminator check (so failures are unlikely), silently ignoring errors can make debugging tricky if something does go wrong.Consider at least logging the error:
💡 Suggested improvement
llmCost.Pricing = &apiPricing - _ = resp.UnitCost.FromFeatureLLMUnitCost(llmCost) + if err := resp.UnitCost.FromFeatureLLMUnitCost(llmCost); err != nil { + // Log but don't fail - enrichment is best-effort + // Consider: slog.WarnContext(ctx, "failed to enrich LLM cost with pricing", "error", err) + } }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/productcatalog/driver/parser.go` around lines 244 - 246, The call to resp.UnitCost.FromFeatureLLMUnitCost(llmCost) currently discards its error; capture and handle it instead by assigning the result to an error variable (e.g., err := resp.UnitCost.FromFeatureLLMUnitCost(llmCost)) and then either log the error via the module logger or return it up the call stack (e.g., if err != nil { return fmt.Errorf("FromFeatureLLMUnitCost failed: %w", err) } or log and continue), keeping the surrounding code that sets llmCost.Pricing = &apiPricing and ensuring the error path provides useful context for debugging.openmeter/cost/adapter/adapter.go (1)
144-146: Worth prioritizing the batching TODO before high-volume usage.Line 144 is a likely latency hotspot: resolving prices one-by-one per unique
(provider, model)can get expensive on large grouped result sets. A bulk API (or bounded parallelism) would keep this endpoint snappy.As per coding guidelines, performance should be a priority in critical code paths, especially around data/query-heavy operations.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/cost/adapter/adapter.go` around lines 144 - 146, The getLLMPrices function currently resolves prices serially for each unique (provider, model) and must be changed to batch requests: modify adapter.getLLMPrices to collect all unique llmPriceKey entries then call a new batch resolution method (e.g., adapter.resolveLLMPricesBatch) that accepts a slice of llmPriceKey and returns a map[llmPriceKey]llmPriceResult; implement the batch method to call the LLM Cost Service with a bulk API (or perform bounded parallelism using a worker pool/goroutine semaphore) and merge results back into the map, preserving error handling and timeouts from the original per-key logic. Ensure to update any callers of getLLMPrices to handle the same return type and keep llmPriceKey and llmPriceResult as the canonical identifiers for mapping results.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@etc/seed/seed.yaml`:
- Around line 10-13: The provider_models array contains fictional model names
(e.g., "gpt-5.2", "claude-opus-4-6") that will fail cost lookups; replace them
with real, supported model identifiers in the provider_models definition (e.g.,
for OpenAI use "gpt-4", "gpt-4o", "gpt-4-turbo", "gpt-3.5-turbo"; for Anthropic
use "claude-3-5-sonnet" or other actual Claude names) so the normalizer and cost
lookup logic can match them correctly; update the models list inside the
provider_models variable accordingly.
In `@openmeter/cost/adapter/adapter.go`:
- Around line 146-189: The getLLMPrices method calls
a.llmcostService.ResolvePrice without checking a.llmcostService for nil and can
panic; before calling ResolvePrice (in adapter.getLLMPrices) add a guard that
a.llmcostService != nil and handle the missing service by skipping resolution
(continue) or inserting a sensible llmPriceResult error into the cache so the
rest of the code (e.g., resolveLLMUnitCost) can handle it gracefully; ensure you
reference llmcostService.ResolvePrice, llmPriceKey and llmPriceResult when
updating the logic so the cache behavior remains consistent.
---
Nitpick comments:
In `@openmeter/cost/adapter/adapter.go`:
- Around line 144-146: The getLLMPrices function currently resolves prices
serially for each unique (provider, model) and must be changed to batch
requests: modify adapter.getLLMPrices to collect all unique llmPriceKey entries
then call a new batch resolution method (e.g., adapter.resolveLLMPricesBatch)
that accepts a slice of llmPriceKey and returns a
map[llmPriceKey]llmPriceResult; implement the batch method to call the LLM Cost
Service with a bulk API (or perform bounded parallelism using a worker
pool/goroutine semaphore) and merge results back into the map, preserving error
handling and timeouts from the original per-key logic. Ensure to update any
callers of getLLMPrices to handle the same return type and keep llmPriceKey and
llmPriceResult as the canonical identifiers for mapping results.
In `@openmeter/productcatalog/driver/parser.go`:
- Around line 160-198: The resolveLLMPricing function currently drops errors
from svc.ResolvePrice and returns nil silently; change the error branch in
resolveLLMPricing to log the failure before returning (e.g., use the package's
logger or a contextual logger available in scope) and include helpful fields:
feat.Namespace, provider, model (or llmConf.Model/ModelProperty), and err so
pricing lookup failures are visible for debugging while preserving the graceful
nil return behavior.
- Around line 244-246: The call to resp.UnitCost.FromFeatureLLMUnitCost(llmCost)
currently discards its error; capture and handle it instead by assigning the
result to an error variable (e.g., err :=
resp.UnitCost.FromFeatureLLMUnitCost(llmCost)) and then either log the error via
the module logger or return it up the call stack (e.g., if err != nil { return
fmt.Errorf("FromFeatureLLMUnitCost failed: %w", err) } or log and continue),
keeping the surrounding code that sets llmCost.Pricing = &apiPricing and
ensuring the error path provides useful context for debugging.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: b52b43ae-8b78-46e1-871f-19ed9ea1fc6f
⛔ Files ignored due to path filters (9)
openmeter/ent/db/feature.gois excluded by!**/ent/db/**openmeter/ent/db/feature/feature.gois excluded by!**/ent/db/**openmeter/ent/db/feature/where.gois excluded by!**/ent/db/**openmeter/ent/db/feature_create.gois excluded by!**/ent/db/**openmeter/ent/db/feature_update.gois excluded by!**/ent/db/**openmeter/ent/db/migrate/schema.gois excluded by!**/ent/db/**openmeter/ent/db/mutation.gois excluded by!**/ent/db/**openmeter/ent/db/setorclear.gois excluded by!**/ent/db/**tools/migrate/migrations/atlas.sumis excluded by!**/*.sum,!**/*.sum
📒 Files selected for processing (27)
app/common/productcatalog.gocmd/server/main.gocmd/server/wire.gocmd/server/wire_gen.goetc/seed/seed.yamlopenmeter/cost/adapter.goopenmeter/cost/adapter/adapter.goopenmeter/cost/adapter/compute.goopenmeter/cost/adapter/compute_test.goopenmeter/cost/httpdriver/handler.goopenmeter/cost/service.goopenmeter/cost/service/service.goopenmeter/ent/schema/feature.goopenmeter/notification/consumer/entitlementbalancethreshold.goopenmeter/notification/consumer/entitlementreset.goopenmeter/productcatalog/adapter/feature.goopenmeter/productcatalog/driver/feature.goopenmeter/productcatalog/driver/parser.goopenmeter/productcatalog/feature/connector.goopenmeter/productcatalog/feature/feature.goopenmeter/productcatalog/feature/unitcost.goopenmeter/productcatalog/subscription/http/mapping.goopenmeter/server/router/product_catalog.goopenmeter/server/router/router.goopenmeter/server/server_test.gotools/migrate/migrations/20260305173559_feature_cost_add.down.sqltools/migrate/migrations/20260305173559_feature_cost_add.up.sql
🚧 Files skipped from review as they are similar to previous changes (10)
- openmeter/cost/adapter.go
- openmeter/productcatalog/feature/feature.go
- openmeter/productcatalog/adapter/feature.go
- cmd/server/wire.go
- openmeter/cost/adapter/compute_test.go
- openmeter/server/router/router.go
- openmeter/server/router/product_catalog.go
- openmeter/productcatalog/feature/connector.go
- openmeter/productcatalog/feature/unitcost.go
- openmeter/ent/schema/feature.go
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
openmeter/cost/httpdriver/handler.go (1)
117-153: Mapping looks correct, but empty currency could slip through.The mapping handles optional fields well. One edge case: if
row.Currencyis empty (due to unresolved costs in the compute layer), the API response will have an emptyCurrencystring for that row, which might not be ideal for clients expecting a valid currency code.💡 Optional: Add a fallback or validation
apiRow := api.FeatureCostQueryRow{ Usage: row.Usage.String(), - Currency: string(row.Currency), + Currency: lo.Ternary(row.Currency != "", string(row.Currency), string(result.Currency)), WindowStart: row.WindowStart, WindowEnd: row.WindowEnd,This would fall back to the result-level currency when the row doesn't have one.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/cost/httpdriver/handler.go` around lines 117 - 153, The mapping can emit empty per-row currencies; update mapCostQueryResultToAPI so that when iterating result.Rows you set apiRow.Currency to row.Currency if non-empty, otherwise fall back to result.Currency (e.g. if row.Currency == "" use result.Currency) before assigning to apiRow.Currency; ensure you reference row.Currency, result.Currency and apiRow.Currency when making the fallback so rows always carry a valid currency code.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@openmeter/cost/adapter/compute.go`:
- Around line 88-89: The cache key generation uses fmt.Sprint(groupByValues)
which is non-deterministic for Go maps; replace this with a deterministic
serializer: iterate the keys of groupByValues, sort them, then build cacheKey by
concatenating key=value pairs in sorted order (or marshal into a stable encoding
using the sorted key order) so identical map contents always produce the same
cacheKey; update the code around the existing cacheKey variable (currently set
with fmt.Sprint) to use this deterministic key generation.
---
Nitpick comments:
In `@openmeter/cost/httpdriver/handler.go`:
- Around line 117-153: The mapping can emit empty per-row currencies; update
mapCostQueryResultToAPI so that when iterating result.Rows you set
apiRow.Currency to row.Currency if non-empty, otherwise fall back to
result.Currency (e.g. if row.Currency == "" use result.Currency) before
assigning to apiRow.Currency; ensure you reference row.Currency, result.Currency
and apiRow.Currency when making the fallback so rows always carry a valid
currency code.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: a4b96ac4-76c3-409a-8613-ffb5f61c7128
📒 Files selected for processing (6)
etc/seed/seed.yamlopenmeter/cost/adapter/adapter.goopenmeter/cost/adapter/compute.goopenmeter/cost/adapter/compute_test.goopenmeter/cost/httpdriver/handler.goopenmeter/cost/service.go
🚧 Files skipped from review as they are similar to previous changes (2)
- openmeter/cost/adapter/compute_test.go
- openmeter/cost/adapter/adapter.go
There was a problem hiding this comment.
Actionable comments posted: 1
♻️ Duplicate comments (1)
openmeter/cost/adapter/compute.go (1)
37-40:⚠️ Potential issue | 🟠 MajorGuard against mixed-currency accumulation before summing costs.
Line 39 and Line 113 overwrite currency without consistency checks. If resolver outputs multiple currencies, totals can be summed across currencies and mislabeled with the last one seen.
🔧 Suggested fix
if resolved != nil { + if currency != "" && currency != resolved.Currency { + return nil, "", fmt.Errorf("mixed currencies in cost rows: %s and %s", currency, resolved.Currency) + } currency = resolved.Currency }Also applies to: 112-114
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/cost/adapter/compute.go` around lines 37 - 40, The code currently overwrites acc.row.Currency and adds amounts without checking currency consistency (identifiers: resolved, acc.hasCost, acc.row.Currency, acc.totalCost, usage, resolved.Amount); update the accumulation logic to guard against mixed currencies by: if acc.hasCost is false, set acc.row.Currency = resolved.Currency and acc.totalCost = usage.Mul(resolved.Amount) and set acc.hasCost = true; otherwise verify resolved.Currency == acc.row.Currency before doing acc.totalCost = acc.totalCost.Add(usage.Mul(resolved.Amount)), and if they differ either skip accumulation and log/return an error or normalize/convert currencies via a dedicated converter; ensure the same guard is applied in both places referenced (the blocks around identifiers above and the duplicate at lines 112-114).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@openmeter/cost/adapter/compute.go`:
- Around line 75-76: The aggregation currently builds aggKey by concatenating
dynamic fields and storing rows in aggregated (map[string]*costRowAccumulator),
which can cause collisions; instead define a dedicated aggregation key type
(e.g., aggregationKey struct with the exact fields used to group: projectID,
region, instanceType, sku, usageType, etc.) and use
map[aggregationKey]*costRowAccumulator (or compute a collision-safe hash of a
length-prefixed/JSON-encoded key) wherever aggKey is constructed (references:
aggKey, aggregated, costRowAccumulator in compute.go, lines around the current
aggKey construction and the other occurrences at the noted spots) so
lookups/aggregations use that safe key type and update code that creates and
accesses aggregated entries accordingly.
---
Duplicate comments:
In `@openmeter/cost/adapter/compute.go`:
- Around line 37-40: The code currently overwrites acc.row.Currency and adds
amounts without checking currency consistency (identifiers: resolved,
acc.hasCost, acc.row.Currency, acc.totalCost, usage, resolved.Amount); update
the accumulation logic to guard against mixed currencies by: if acc.hasCost is
false, set acc.row.Currency = resolved.Currency and acc.totalCost =
usage.Mul(resolved.Amount) and set acc.hasCost = true; otherwise verify
resolved.Currency == acc.row.Currency before doing acc.totalCost =
acc.totalCost.Add(usage.Mul(resolved.Amount)), and if they differ either skip
accumulation and log/return an error or normalize/convert currencies via a
dedicated converter; ensure the same guard is applied in both places referenced
(the blocks around identifiers above and the duplicate at lines 112-114).
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: f9cf2878-1e61-4cfd-b52a-d79e022bb475
📒 Files selected for processing (2)
openmeter/cost/adapter/compute.goopenmeter/cost/adapter/compute_test.go
Add LLM Cost database and feature cost.
Summary by CodeRabbit
New Features
Tests