Skip to content

feat(llmcost): service - #3917

Merged
hekike merged 7 commits into
mainfrom
feat/llm-cost-service
Mar 4, 2026
Merged

hekike merged 7 commits into
mainfrom
feat/llm-cost-service

Conversation

@hekike

@hekike hekike commented Mar 3, 2026 •

Copy link
Copy Markdown
Contributor
  • Adapter
  • Service
  • Job

Summary by CodeRabbit

  • New Features

    • Full LLM cost pricing system: list/get/resolve prices, paginated/filtered queries, and per-namespace overrides via new API endpoints.
    • Background sync job and CLI command to fetch, normalize, reconcile, and upsert external pricing sources.
    • Database schema and persistence for canonical and override prices.
  • Tests

    • Extensive unit tests covering pricing validation, sync, reconciliation, normalization, adapters, and handlers.
  • Chores

    • Added Makefile target to run the LLM cost sync job.

@hekike
hekike requested a review from a team as a code owner March 3, 2026 22:39
@hekike hekike added the release-note/ignore Ignore this change when generating release notes label Mar 3, 2026
@coderabbitai

coderabbitai Bot commented Mar 3, 2026 •

Copy link
Copy Markdown
Contributor

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds a full LLM cost subsystem: domain models, validation and errors, persistence (Ent schema + adapter), service layer, sync/reconcile job with fetchers and normalizer, CLI + Make target, v3 HTTP handlers and routing, DI wiring, DB migrations, and comprehensive tests.

Changes

Cohort / File(s) Summary
Build & CLI
Makefile, cmd/jobs/llmcost/llmcost.go, cmd/jobs/main.go
Add .PHONY: llm-cost-sync Make target and a llm-cost sync Cobra command that runs the SyncJob.
Wiring / DI
app/common/llmcost.go, cmd/jobs/internal/wire.go, cmd/jobs/internal/wire_gen.go, cmd/server/wire.go, cmd/server/wire_gen.go, cmd/server/main.go
Wire LLMCost service and SyncJob into application DI; expose fields on Application structs and add initialization/cleanup logic.
Server & Routing
api/v3/server/routes.go, api/v3/server/server.go, openmeter/server/router/router.go, openmeter/server/server.go, cmd/server/main.go
Inject LLMCostService into router/server configs and route prices & overrides endpoints to the new llmcost handler implementations.
API Handlers & Conversion
api/v3/filters/filter.go, api/v3/handlers/llmcost/handler.go, api/v3/handlers/llmcost/*.go, api/v3/handlers/llmcost/convert.go
Add StringFilter, full llmcost HTTP handler (List/Get/ListOverrides/CreateOverride/DeleteOverride) and domain↔API conversion utilities with validation and error mapping.
Domain Models & Errors
openmeter/llmcost/llmcost.go, openmeter/llmcost/errors.go, openmeter/llmcost/llmcost_test.go
Introduce Price, ModelPricing, PriceSource, SourcePrice types with validation, error codes, and unit tests.
Persistence Schema & Migrations
openmeter/ent/schema/llmcostprice.go, tools/migrate/migrations/20260303233513_llmcost_add.up.sql, ...down.sql
Add llm_cost_prices Ent schema and SQL migrations (up/down) with indexes for global/namespace lookups and active-price uniqueness.
Adapter & Persistence Implementation
openmeter/llmcost/adapter.go, openmeter/llmcost/adapter/adapter.go, openmeter/llmcost/adapter/mapping.go, openmeter/llmcost/adapter/price.go
Define Adapter interface and implement adapter with transactional operations: list/get/resolve prices, create/delete/list overrides, and UpsertGlobalPrice; include entity→domain mapping and string-filter helpers.
Service Layer
openmeter/llmcost/service.go, openmeter/llmcost/service/service.go
Add Service interface, input types with validation, and service implementation that wraps adapter calls transactionally and applies namespace override resolution/substitution.
Sync: Fetchers & Normalizer
openmeter/llmcost/sync/fetcher.go, openmeter/llmcost/sync/fetcher_modelsdev.go, openmeter/llmcost/sync/normalizer.go, openmeter/llmcost/sync/normalizer_test.go
Fetcher contract and models.dev fetcher; normalizer that canonicalizes provider/model IDs (lowercase, strip date suffix, alias mapping) with tests.
Sync: Reconciler & Job
openmeter/llmcost/sync/reconciler.go, openmeter/llmcost/sync/reconciler_test.go, openmeter/llmcost/sync/sync.go, openmeter/llmcost/sync/sync_test.go
Reconciler finds source agreement within tolerance and upserts averaged global prices; SyncJob orchestrates fetch → normalize → filter → reconcile; comprehensive tests.
Filters & Utilities
api/v3/filters/filter.go, adapter helpers
Add reusable StringFilter and applyStringFilter helper used across API and persistence layers.
Tests & Utilities
multiple *_test.go files
Extensive unit tests covering domain validation, normalization, reconciliation, sync job, and adapter mapping.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Handler
    participant Service
    participant Adapter
    participant DB

    Client->>Handler: GET /v3/prices/{id} (with namespace)
    Handler->>Handler: resolve namespace
    Handler->>Service: GetPrice(ctx, id, namespace)
    Service->>Adapter: Tx().GetPrice(ctx, id)
    Adapter->>DB: SELECT price by id
    DB-->>Adapter: price row
    alt namespace provided
        Service->>Adapter: Tx().ResolvePrice(ctx, namespace, provider, modelID, at)
        Adapter->>DB: query namespace overrides
        DB-->>Adapter: override rows
        alt manual override found
            Service-->>Handler: override price
        else
            Service-->>Handler: global price
        end
    else
        Service-->>Handler: global price
    end
    Handler->>Handler: convert domain -> API
    Handler-->>Client: 200 JSON
Loading
sequenceDiagram
    participant CLI
    participant SyncJob
    participant Fetcher
    participant Normalizer
    participant Reconciler
    participant Adapter
    participant DB

    CLI->>SyncJob: Run(ctx)
    SyncJob->>Fetcher: Fetch() (each source)
    Fetcher-->>SyncJob: []SourcePrice
    SyncJob->>Normalizer: Normalize(provider, modelID)
    Normalizer-->>SyncJob: normalized prices
    alt Filter provided
        SyncJob->>SyncJob: apply filter
    end
    SyncJob->>Reconciler: Reconcile(ctx, prices)
    Reconciler->>Reconciler: group by provider+modelID
    Reconciler->>Reconciler: find agreeing sources within tolerance
    Reconciler->>Adapter: UpsertGlobalPrice(ctx, averaged price)
    Adapter->>DB: INSERT/UPDATE llm_cost_prices
    DB-->>Adapter: success
    Adapter-->>Reconciler: OK
    Reconciler-->>SyncJob: done
    SyncJob-->>CLI: success
Loading

Estimated code review effort

🎯 5 (Critical) | ⏱️ ~150 minutes

Suggested reviewers

  • tothandras
🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 20.69% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'feat(llmcost): service' clearly identifies the main change—adding an LLM cost service—and aligns with the changeset's primary objective of introducing the service component.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/llm-cost-service

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

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

🧹 Nitpick comments (7)
openmeter/llmcost/errors.go (1)

24-92: Consider a tiny helper to remove repeated validation-issue boilerplate.

This file is nicely consistent already; extracting the shared BadRequest + critical + field pattern would make future additions safer and shorter.

Refactor sketch
+func newBadRequestIssue(code models.ErrorCode, message, field string) models.ValidationIssue {
+	return models.NewValidationIssue(
+		code,
+		message,
+		models.WithFieldString(field),
+		models.WithCriticalSeverity(),
+		commonhttp.WithHTTPStatusCodeAttribute(http.StatusBadRequest),
+	)
+}
+
 var ErrProviderEmpty = models.NewValidationIssue(
-	ErrCodeProviderEmpty,
-	"provider must not be empty",
-	models.WithFieldString("provider"),
-	models.WithCriticalSeverity(),
-	commonhttp.WithHTTPStatusCodeAttribute(http.StatusBadRequest),
+	ErrCodeProviderEmpty,
+	"provider must not be empty",
+	models.WithFieldString("provider"),
+	models.WithCriticalSeverity(),
+	commonhttp.WithHTTPStatusCodeAttribute(http.StatusBadRequest),
 )

You can then migrate the other BadRequest entries to newBadRequestIssue(...).

As per coding guidelines `**/*.go`: "In general when reviewing the Golang code make readability and maintainability a priority, even potentially suggest restructuring the code to improve them."
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openmeter/llmcost/errors.go` around lines 24 - 92, Create a small constructor
helper (e.g., newBadRequestIssue(code models.ErrorCode, message, field string)
*models.ValidationIssue) that wraps models.NewValidationIssue with
models.WithFieldString(field), models.WithCriticalSeverity(), and
commonhttp.WithHTTPStatusCodeAttribute(http.StatusBadRequest); then replace the
repeated models.NewValidationIssue calls for ErrProviderEmpty, ErrModelIDEmpty,
ErrNamespaceEmpty, ErrPriceIDEmpty, ErrPriceMustBeNonNegative,
ErrEffectiveFromAfterTo, and ErrInvalidPriceSource to call newBadRequestIssue
with the appropriate code, message and field names to remove boilerplate and
centralize the BadRequest+critical+field pattern.
openmeter/llmcost/llmcost_test.go (1)

27-56: Please add optional-token validation cases in TestModelPricingValidate.

Current cases only assert input/output negatives. Adding coverage for CacheReadPerToken, CacheWritePerToken, and ReasoningPerToken (negative, zero, nil) would better protect this pricing model.

As per coding guidelines **/*_test.go: "Make sure the tests are comprehensive and cover the changes. Keep a strong focus on unit tests and in-code integration tests."

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openmeter/llmcost/llmcost_test.go` around lines 27 - 56,
TestModelPricingValidate lacks cases for the optional fields CacheReadPerToken,
CacheWritePerToken, and ReasoningPerToken; add subtests in
TestModelPricingValidate that cover negative values (expecting Validate() to
return an error), zero values (expecting no error), and nil/omitted fields
(expecting no error) for each of ModelPricing.CacheReadPerToken,
ModelPricing.CacheWritePerToken and ModelPricing.ReasoningPerToken, mirroring
the style of the existing subtests for InputPerToken and OutputPerToken and
using alpacadecimal.NewFromFloat for non-nil values.
api/v3/handlers/llmcost/convert.go (1)

84-106: Optional decimal parsing is repetitive—consider a tiny helper.

Line 84 through Line 106 repeat the same parse/error pattern three times; extracting one helper will reduce drift when pricing fields evolve.

♻️ Refactor sketch
 func apiPricingToDomain(p api.LLMCostModelPricing) (llmcost.ModelPricing, error) {
@@
-	if p.CacheReadPerToken != nil {
-		d, err := decimalFromString(*p.CacheReadPerToken)
-		if err != nil {
-			return llmcost.ModelPricing{}, fmt.Errorf("invalid cache_read_per_token: %w", err)
-		}
-		out.CacheReadPerToken = &d
-	}
-
-	if p.ReasoningPerToken != nil {
-		d, err := decimalFromString(*p.ReasoningPerToken)
-		if err != nil {
-			return llmcost.ModelPricing{}, fmt.Errorf("invalid reasoning_per_token: %w", err)
-		}
-		out.ReasoningPerToken = &d
-	}
-
-	if p.CacheWritePerToken != nil {
-		d, err := decimalFromString(*p.CacheWritePerToken)
-		if err != nil {
-			return llmcost.ModelPricing{}, fmt.Errorf("invalid cache_write_per_token: %w", err)
-		}
-		out.CacheWritePerToken = &d
-	}
+	cacheRead, err := parseOptionalDecimal("cache_read_per_token", p.CacheReadPerToken)
+	if err != nil {
+		return llmcost.ModelPricing{}, err
+	}
+	out.CacheReadPerToken = cacheRead
+
+	reasoning, err := parseOptionalDecimal("reasoning_per_token", p.ReasoningPerToken)
+	if err != nil {
+		return llmcost.ModelPricing{}, err
+	}
+	out.ReasoningPerToken = reasoning
+
+	cacheWrite, err := parseOptionalDecimal("cache_write_per_token", p.CacheWritePerToken)
+	if err != nil {
+		return llmcost.ModelPricing{}, err
+	}
+	out.CacheWritePerToken = cacheWrite
 
 	return out, nil
 }
+
+func parseOptionalDecimal(field string, v *string) (*alpacadecimal.Decimal, error) {
+	if v == nil {
+		return nil, nil
+	}
+	d, err := decimalFromString(*v)
+	if err != nil {
+		return nil, fmt.Errorf("invalid %s: %w", field, err)
+	}
+	return &d, nil
+}
As per coding guidelines: `**/*.go`: “make readability and maintainability a priority”.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@api/v3/handlers/llmcost/convert.go` around lines 84 - 106, Extract the
repeated parse-and-assign logic into a small helper (e.g.,
parseOptionalDecimal(fieldName string, src *string) (*decimal.Decimal, error))
and use it for CacheReadPerToken, ReasoningPerToken, and CacheWritePerToken; the
helper should return nil if the source pointer is nil, call decimalFromString
when non-nil, and wrap errors using the same field-specific message ("invalid
<field>: %w") so you can replace the three blocks that set
out.CacheReadPerToken, out.ReasoningPerToken, and out.CacheWritePerToken with
three concise calls to the helper and assign its result to the corresponding
out.* fields.
openmeter/llmcost/sync/reconciler_test.go (1)

73-181: Add one subtest for upsert failure propagation.

mockAdapter.upsertErr is defined but never exercised; adding this locks in Reconcile error handling for DB failures.

🧪 Suggested test addition
 import (
 	"context"
+	"errors"
 	"log/slog"
 	"testing"
 	"time"
@@
 	t.Run("averages agreeing prices", func(t *testing.T) {
@@
 		assert.True(t, upserted.Pricing.InputPerToken.Equal(expectedInput))
 	})
+
+	t.Run("propagates upsert error", func(t *testing.T) {
+		adapter.upsertedPrices = nil
+		adapter.upsertErr = errors.New("upsert failed")
+		t.Cleanup(func() { adapter.upsertErr = nil })
+
+		r := NewReconciler(adapter, logger, 2, 0.01)
+		prices := []llmcost.SourcePrice{
+			makePrice("source_a", "openai", "gpt-4", 0.01, 0.03),
+			makePrice("source_b", "openai", "gpt-4", 0.01, 0.03),
+		}
+
+		err := r.Reconcile(context.Background(), prices)
+		require.Error(t, err)
+		assert.ErrorContains(t, err, "upsert failed")
+		assert.Empty(t, adapter.upsertedPrices)
+	})
 }
As per coding guidelines: `**/*_test.go`: “Make sure the tests are comprehensive and cover the changes. Keep a strong focus on unit tests and in-code integration tests.”
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openmeter/llmcost/sync/reconciler_test.go` around lines 73 - 181, Add a
subtest to TestReconcileAgreement that sets mockAdapter.upsertErr to a non-nil
error and verifies that Reconciler.Reconcile returns that error and does not
populate adapter.upsertedPrices; use NewReconciler(...) to create the
reconciler, call r.Reconcile with a valid agreeing prices slice (e.g., two
matching makePrice entries) and assert the returned error equals the injected
mockAdapter.upsertErr and that adapter.upsertedPrices remains empty to lock in
DB upsert failure propagation for the mockAdapter.
openmeter/llmcost/adapter/price.go (1)

242-244: Use deterministic tie-breakers in paginated ordering.

Sorting only by provider/model can make page boundaries unstable when rows share those values. Add effective_from and a stable final key (for example id) to the order.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openmeter/llmcost/adapter/price.go` around lines 242 - 244, The current query
orders only by pricedb.ByProvider() and pricedb.ByModelID(), which can make
pagination unstable; update the ordering before calling query.Paginate to append
deterministic tie-breakers such as effective_from (ascending or descending to
match intended semantics) and a stable unique key like id (pricedb.ByID() or the
model's primary key) so the final order is provider, model_id, effective_from,
id; ensure the same order is used everywhere pagination is applied (i.e., in the
code path that builds the query prior to calling query.Paginate(ctx,
input.Page)).
api/v3/handlers/llmcost/list_overrides.go (1)

28-61: Consider extracting shared list-request parsing to avoid drift.

This decoder is almost identical to Line 28-Line 61 in api/v3/handlers/llmcost/list_prices.go. A shared helper for namespace/page/filter parsing would make future changes safer.

As per coding guidelines "In general when reviewing the Golang code make readability and maintainability a priority, even potentially suggest restructuring the code to improve them."

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@api/v3/handlers/llmcost/list_overrides.go` around lines 28 - 61, Extract the
duplicated namespace/page/filter parsing into a shared helper (e.g.,
decodeListParams or parseListRequest) and use it from the anonymous handler for
ListOverrides (the function using resolveNamespace, ListOverridesParams, and
building ListOverridesRequest) and the similar handler in list_prices.go; the
helper should accept context and the generated params type (or a small
interface) and return the resolved namespace, a validated pagination.Page, and
the parsed filter fields (provider, modelId, modelName, currency) or an error so
the handler only assigns to
ListOverridesRequest.Namespace/Page/Provider/ModelID/ModelName/Currency and
returns any validation errors via apierrors.NewBadRequestError; keep
resolveNamespace usage and validation logic (Page.Validate) but move duplicated
logic into the new helper and replace the inline parsing in both handlers to
call it.
openmeter/llmcost/service.go (1)

129-129: Currency field is not validated.

The Currency field is present but the Validate() method doesn't check it. Based on the Price struct documentation mentioning "Currency is the currency code (always 'USD' for now)", you might want to either:

  1. Validate it's not empty
  2. Validate it's a supported currency code

If it's truly optional or has a default, that's fine - just wanted to flag it in case it was missed.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openmeter/llmcost/service.go` at line 129, The Price struct's Currency field
is not being validated; update the Price.Validate() method to ensure Currency is
present and valid (at minimum check non-empty and equals "USD", or validate
against your supported currency list), returning a descriptive error when
invalid; modify any callers of Price.Validate() if needed to handle the new
error and include references to the Price type and Price.Validate() method in
the change.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@api/v3/filters/filter.go`:
- Around line 4-19: The StringFilter currently allows multiple operators despite
the “Exactly one” contract; add an enforcement method (e.g., func (f
StringFilter) Validate() error) that returns an error unless exactly one of Eq,
Neq, or Contains is non-nil, update IsEmpty to remain as-is or call Validate as
needed, and wire this Validate() into deserialization/usage paths (or implement
UnmarshalJSON on StringFilter to call Validate()) so callers cannot construct
ambiguous filters; reference the StringFilter type and IsEmpty when adding the
new Validate/UnmarshalJSON enforcement.

In `@api/v3/server/server.go`:
- Around line 190-193: The llmcostH variable can remain nil when
config.LLMCostService is nil and later cause panics; ensure llmcostH is always a
non-nil implementation of llmcosthandler.Handler by either (A) creating and
assigning a safe no-op/stub handler that implements llmcosthandler.Handler
(returns sensible errors or 404s) when config.LLMCostService is nil, or (B)
skip/guard route registration so methods that use llmcostH are not called when
config.LLMCostService is nil; reference llmcostH, llmcosthandler.New,
resolveNamespace, config.LLMCostService and
httptransport.WithErrorHandler(config.ErrorHandler) to locate the instantiation
and adjust it to produce a non-nil handler in all cases.

In `@app/common/llmcost.go`:
- Around line 43-45: The HTTP client passed into llmcostsync.NewSyncJob (via
SyncJobConfig.HTTPClient) lacks a request timeout; update the creation of the
http.Client used for the sync job to include a sensible Timeout (e.g.,
time.Second * 10 or a configurable value) so external calls to models.dev cannot
hang indefinitely, and ensure the Timeout is applied when constructing the
SyncJobConfig for llmcostsync.NewSyncJob.

In `@cmd/jobs/internal/wire.go`:
- Line 82: The global provider list currently includes common.LLMCost which
forces LLMCost initialization for every jobs subcommand; remove common.LLMCost
from the global wire and instead add its provider wiring only within the llmcost
command setup (where llmcost.Cmd and LLMCostSyncJob are initialized). Locate the
global wiring that references common.LLMCost and delete that entry, then add the
LLMCost-related providers to the llmcost command's initialization/constructor so
only llmcost.Cmd triggers LLMCost initialization and other subcommands (migrate,
billing, entitlement, etc.) remain unaffected.

In `@openmeter/ent/schema/llmcostprice.go`:
- Around line 84-93: The UNIQUE index on index.Fields("provider", "model_id",
"namespace", "effective_from") doesn't prevent duplicate global rows where
namespace IS NULL; change to two partial unique indexes: one unique index over
("provider","model_id","namespace","effective_from") with
entsql.IndexWhere("deleted_at IS NULL AND namespace IS NOT NULL") and a separate
unique index over ("provider","model_id","effective_from") with
entsql.IndexWhere("deleted_at IS NULL AND namespace IS NULL"); update the schema
in llmcostprice.go where the indexes are defined (the index.Fields(...) entries)
to implement these two partial unique indexes so both NULL and non-NULL
namespace cases are enforced.

In `@openmeter/llmcost/adapter/adapter.go`:
- Around line 72-74: The WithTx method on adapter currently dereferences
tx.GetConfig() which can panic if tx or tx.GetConfig() is nil; update
adapter.WithTx to first guard against nil by checking if tx == nil ||
tx.GetConfig() == nil and return the receiver (a) immediately (or otherwise
handle the error) before calling entdb.NewTxClientFromRawConfig; reference
symbols: adapter.WithTx, entutils.TxDriver, GetConfig, and
entdb.NewTxClientFromRawConfig.

In `@openmeter/llmcost/adapter/mapping.go`:
- Around line 42-53: The mapping currently treats numeric zero as “not set” by
checking entity.CacheReadPerToken.IsZero() (and
CacheWritePerToken/ReasoningPerToken) and skipping assignment, which drops
explicit zero prices; change the logic in mapping.go so you do not use IsZero as
the presence check — instead always set price.Pricing.CacheReadPerToken =
lo.ToPtr(entity.CacheReadPerToken) (and likewise for CacheWritePerToken and
ReasoningPerToken) so explicit 0 values round-trip correctly (or, if the domain
uses pointer/nullable types for presence, use the pointer presence check rather
than IsZero).

In `@openmeter/llmcost/adapter/price.go`:
- Around line 257-303: The read-then-create pattern in UpsertGlobalPrice (using
a.db.LLMCostPrice.Query() then Create()/UpdateOneID()) is race-prone; replace it
with an atomic upsert: use the Ent upsert/OnConflict API on
a.db.LLMCostPrice.Create().OnConflict(...) (or the DB-specific ON
CONFLICT/UPSERT equivalent) to perform a single
Create().OnConflict(...).Update(...) that sets ModelName, InputPerToken,
OutputPerToken, CacheReadPerToken, CacheWritePerToken, ReasoningPerToken,
Currency, Source, SourcePrices and EffectiveFrom so concurrent workers cannot
both insert duplicates; if your Ent version lacks OnConflict, wrap the logic in
a transaction (a.db.Tx(ctx)), re-query the row with a SELECT ... FOR UPDATE
lock, then create or UpdateOneID() inside that tx and commit, and add a small
retry on serialization errors.

In `@openmeter/llmcost/llmcost.go`:
- Around line 53-65: The Validate method on ModelPricing must also reject
negative values for optional token price fields; update ModelPricing.Validate to
check each optional price field (e.g., any fields like OptionalInputPerToken,
OptionalOutputPerToken or other nullable token price fields on the ModelPricing
struct) and if the field is present/set and IsNegative() append
ErrPriceMustBeNonNegative to errs before returning; keep using
models.NewNillableGenericValidationError(errors.Join(errs...)) and reference
ModelPricing.Validate, InputPerToken, OutputPerToken and the specific optional
field names in your changes.

In `@openmeter/llmcost/service.go`:
- Line 130: Add a check that EffectiveFrom is not the zero time by calling
EffectiveFrom.IsZero() as part of the existing validation logic (the same place
you validate EffectiveTo) and return a clear validation error if it is zero;
update any function performing range checks (e.g., the struct's Validate method
or the routine that currently compares EffectiveFrom and EffectiveTo) to reject
a zero EffectiveFrom before comparing it to EffectiveTo so the zero default
cannot slip through.

In `@openmeter/llmcost/service/service.go`:
- Around line 90-93: The current code in the ResolvePrice call swallows every
error and returns the global price; change it to only treat a "not found"
sentinel as non-fatal and return the global price, while propagating all other
errors. Concretely, after calling ResolvePrice check the error with the
appropriate sentinel or predicate (e.g., errors.Is(err, ErrPriceNotFound) or a
resolver.IsNotFound(err) helper); if it's a not-found error return price, nil,
otherwise return the error (e.g., return 0, err or return price, err per the
function contract). Update the branch around ResolvePrice to implement this
logic (referencing ResolvePrice and the not-found sentinel like
ErrPriceNotFound/IsNotFound).
- Around line 37-43: The call to s.adapter.ListOverrides with
llmcost.ListOverridesInput (using Namespace, Provider, ModelID, ModelName,
Currency) can return an unbounded set and must be limited to the requested page;
change the ListOverrides invocation to accept and pass explicit pagination
controls (limit/offset or pageToken/nextCursor) derived from the service
request/page parameters and/or add tighter filters scoped to the page (e.g.,
include requested page's keys or time range) so the adapter only materializes
the subset needed for the response—update s.adapter.ListOverrides
signature/use-site and the llmcost.ListOverridesInput to carry those pagination
fields and ensure the calling code (in service.go) forwards them.

In `@openmeter/llmcost/sync/fetcher_modelsdev.go`:
- Around line 45-47: The constructor NewModelsDevFetcher should guard against a
nil *http.Client to avoid a panic in Fetch when calling f.client.Do; update
NewModelsDevFetcher to check if client == nil and assign http.DefaultClient (or
another sane default) before returning &modelsDevFetcher{client: client}, so
Fetch and any call to f.client.Do(...) are safe even if the caller passed nil.

In `@openmeter/llmcost/sync/reconciler.go`:
- Around line 114-121: The current reconciliation swallows Upsert errors by
logging and continuing; change the logic in the function containing
r.repo.UpsertGlobalPrice so that when r.repo.UpsertGlobalPrice(ctx, price)
returns an error you return that error (or a wrapped error with context
including key.Provider and key.ModelID) instead of continue; apply the same
change to the other similar block around the second r.repo.UpsertGlobalPrice
call (lines referenced 126-132) so callers receive a non-nil error on partial
sync failures.
- Around line 162-165: The pricesAgree function and the reconciled-price
averaging logic only consider InputPerToken and OutputPerToken, causing cache_*
and reasoning_* dimensions to be taken from the first source; update pricesAgree
(and the averaging/reconciliation block that constructs the reconciled
llmcost.ModelPricing) to include all optional pricing dimensions (cache_* and
reasoning_* fields) in the equality check using decimalsAgree and to compute
their averaged value when both sources are present (handling nil/absent values
consistently — e.g., treat missing as absent and prefer the present value or
average when both exist). Make these changes against the ModelPricing type and
the code paths that call pricesAgree/perform averaging so the reconciled
ModelPricing contains proper averaged cache_* and reasoning_* decimals rather
than always using the first source.

In `@openmeter/llmcost/sync/sync.go`:
- Around line 49-56: DefaultFetchers currently falls back to http.DefaultClient
(no timeout), which can hang sync; in the DefaultFetchers function, when client
== nil create and use a new *http.Client with a sensible Timeout set (e.g.,
5–30s) instead of using http.DefaultClient so that NewModelsDevFetcher and any
other Fetcher calls time out reliably; update DefaultFetchers to instantiate a
timed client before returning the slice.
- Around line 60-74: NewSyncJob can receive a nil SyncJobConfig.Logger which
causes panics when Run dereferences j.logger; update NewSyncJob to guard against
a nil config.Logger by assigning a default no-op logger that implements the same
Logger interface (or use log.New(io.Discard, "", 0) if the interface is
compatible) before constructing the SyncJob so j.logger is always non-nil;
ensure the fix references NewSyncJob, SyncJobConfig.Logger, SyncJob.Run and
j.logger so all subsequent calls on j.logger in Run are safe.

In `@openmeter/server/router/router.go`:
- Line 107: Config.Validate() currently doesn't check the new required
dependency LLMCostService, so add a nil-check for the LLMCostService field
inside the Config.Validate() method and return an error if it's nil;
specifically, update Config.Validate() to validate that c.LLMCostService (or the
receiver name used in Validate) is not nil and return a descriptive error (e.g.,
"LLMCostService is required") so startup fails fast when the llmcost.Service
dependency is missing.

In `@tools/migrate/migrations/20260303205801_llmcost_add.up.sql`:
- Line 33: The current unique index
llmcostprice_provider_model_id_namespace_effective_from on table llm_cost_prices
allows duplicate global prices because namespace is nullable; replace the single
index with two partial unique indexes: one for global prices (namespace IS NULL)
covering (provider, model_id, effective_from) and one for namespaced prices
(namespace IS NOT NULL) covering (provider, model_id, namespace,
effective_from), both constrained with deleted_at IS NULL, and remove the
original combined index so duplicates for (provider, model_id, NULL,
effective_from) are prevented.

---

Nitpick comments:
In `@api/v3/handlers/llmcost/convert.go`:
- Around line 84-106: Extract the repeated parse-and-assign logic into a small
helper (e.g., parseOptionalDecimal(fieldName string, src *string)
(*decimal.Decimal, error)) and use it for CacheReadPerToken, ReasoningPerToken,
and CacheWritePerToken; the helper should return nil if the source pointer is
nil, call decimalFromString when non-nil, and wrap errors using the same
field-specific message ("invalid <field>: %w") so you can replace the three
blocks that set out.CacheReadPerToken, out.ReasoningPerToken, and
out.CacheWritePerToken with three concise calls to the helper and assign its
result to the corresponding out.* fields.

In `@api/v3/handlers/llmcost/list_overrides.go`:
- Around line 28-61: Extract the duplicated namespace/page/filter parsing into a
shared helper (e.g., decodeListParams or parseListRequest) and use it from the
anonymous handler for ListOverrides (the function using resolveNamespace,
ListOverridesParams, and building ListOverridesRequest) and the similar handler
in list_prices.go; the helper should accept context and the generated params
type (or a small interface) and return the resolved namespace, a validated
pagination.Page, and the parsed filter fields (provider, modelId, modelName,
currency) or an error so the handler only assigns to
ListOverridesRequest.Namespace/Page/Provider/ModelID/ModelName/Currency and
returns any validation errors via apierrors.NewBadRequestError; keep
resolveNamespace usage and validation logic (Page.Validate) but move duplicated
logic into the new helper and replace the inline parsing in both handlers to
call it.

In `@openmeter/llmcost/adapter/price.go`:
- Around line 242-244: The current query orders only by pricedb.ByProvider() and
pricedb.ByModelID(), which can make pagination unstable; update the ordering
before calling query.Paginate to append deterministic tie-breakers such as
effective_from (ascending or descending to match intended semantics) and a
stable unique key like id (pricedb.ByID() or the model's primary key) so the
final order is provider, model_id, effective_from, id; ensure the same order is
used everywhere pagination is applied (i.e., in the code path that builds the
query prior to calling query.Paginate(ctx, input.Page)).

In `@openmeter/llmcost/errors.go`:
- Around line 24-92: Create a small constructor helper (e.g.,
newBadRequestIssue(code models.ErrorCode, message, field string)
*models.ValidationIssue) that wraps models.NewValidationIssue with
models.WithFieldString(field), models.WithCriticalSeverity(), and
commonhttp.WithHTTPStatusCodeAttribute(http.StatusBadRequest); then replace the
repeated models.NewValidationIssue calls for ErrProviderEmpty, ErrModelIDEmpty,
ErrNamespaceEmpty, ErrPriceIDEmpty, ErrPriceMustBeNonNegative,
ErrEffectiveFromAfterTo, and ErrInvalidPriceSource to call newBadRequestIssue
with the appropriate code, message and field names to remove boilerplate and
centralize the BadRequest+critical+field pattern.

In `@openmeter/llmcost/llmcost_test.go`:
- Around line 27-56: TestModelPricingValidate lacks cases for the optional
fields CacheReadPerToken, CacheWritePerToken, and ReasoningPerToken; add
subtests in TestModelPricingValidate that cover negative values (expecting
Validate() to return an error), zero values (expecting no error), and
nil/omitted fields (expecting no error) for each of
ModelPricing.CacheReadPerToken, ModelPricing.CacheWritePerToken and
ModelPricing.ReasoningPerToken, mirroring the style of the existing subtests for
InputPerToken and OutputPerToken and using alpacadecimal.NewFromFloat for
non-nil values.

In `@openmeter/llmcost/service.go`:
- Line 129: The Price struct's Currency field is not being validated; update the
Price.Validate() method to ensure Currency is present and valid (at minimum
check non-empty and equals "USD", or validate against your supported currency
list), returning a descriptive error when invalid; modify any callers of
Price.Validate() if needed to handle the new error and include references to the
Price type and Price.Validate() method in the change.

In `@openmeter/llmcost/sync/reconciler_test.go`:
- Around line 73-181: Add a subtest to TestReconcileAgreement that sets
mockAdapter.upsertErr to a non-nil error and verifies that Reconciler.Reconcile
returns that error and does not populate adapter.upsertedPrices; use
NewReconciler(...) to create the reconciler, call r.Reconcile with a valid
agreeing prices slice (e.g., two matching makePrice entries) and assert the
returned error equals the injected mockAdapter.upsertErr and that
adapter.upsertedPrices remains empty to lock in DB upsert failure propagation
for the mockAdapter.

ℹ️ Review info

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 57478c6 and 6ebfae1.

⛔ Files ignored due to path filters (19)
  • openmeter/ent/db/client.go is excluded by !**/ent/db/**
  • openmeter/ent/db/ent.go is excluded by !**/ent/db/**
  • openmeter/ent/db/expose.go is excluded by !**/ent/db/**
  • openmeter/ent/db/hook/hook.go is excluded by !**/ent/db/**
  • openmeter/ent/db/llmcostprice.go is excluded by !**/ent/db/**
  • openmeter/ent/db/llmcostprice/llmcostprice.go is excluded by !**/ent/db/**
  • openmeter/ent/db/llmcostprice/where.go is excluded by !**/ent/db/**
  • openmeter/ent/db/llmcostprice_create.go is excluded by !**/ent/db/**
  • openmeter/ent/db/llmcostprice_delete.go is excluded by !**/ent/db/**
  • openmeter/ent/db/llmcostprice_query.go is excluded by !**/ent/db/**
  • openmeter/ent/db/llmcostprice_update.go is excluded by !**/ent/db/**
  • openmeter/ent/db/migrate/schema.go is excluded by !**/ent/db/**
  • openmeter/ent/db/mutation.go is excluded by !**/ent/db/**
  • openmeter/ent/db/paginate.go is excluded by !**/ent/db/**
  • openmeter/ent/db/predicate/predicate.go is excluded by !**/ent/db/**
  • openmeter/ent/db/runtime.go is excluded by !**/ent/db/**
  • openmeter/ent/db/setorclear.go is excluded by !**/ent/db/**
  • openmeter/ent/db/tx.go is excluded by !**/ent/db/**
  • tools/migrate/migrations/atlas.sum is excluded by !**/*.sum, !**/*.sum
📒 Files selected for processing (41)
  • Makefile
  • api/v3/filters/filter.go
  • api/v3/handlers/llmcost/convert.go
  • api/v3/handlers/llmcost/create_override.go
  • api/v3/handlers/llmcost/delete_override.go
  • api/v3/handlers/llmcost/get_price.go
  • api/v3/handlers/llmcost/handler.go
  • api/v3/handlers/llmcost/list_overrides.go
  • api/v3/handlers/llmcost/list_prices.go
  • api/v3/server/routes.go
  • api/v3/server/server.go
  • app/common/llmcost.go
  • cmd/jobs/internal/wire.go
  • cmd/jobs/internal/wire_gen.go
  • cmd/jobs/llmcost/llmcost.go
  • cmd/jobs/main.go
  • cmd/server/main.go
  • cmd/server/wire.go
  • cmd/server/wire_gen.go
  • openmeter/ent/schema/llmcostprice.go
  • openmeter/llmcost/adapter.go
  • openmeter/llmcost/adapter/adapter.go
  • openmeter/llmcost/adapter/mapping.go
  • openmeter/llmcost/adapter/price.go
  • openmeter/llmcost/errors.go
  • openmeter/llmcost/llmcost.go
  • openmeter/llmcost/llmcost_test.go
  • openmeter/llmcost/service.go
  • openmeter/llmcost/service/service.go
  • openmeter/llmcost/sync/fetcher.go
  • openmeter/llmcost/sync/fetcher_modelsdev.go
  • openmeter/llmcost/sync/normalizer.go
  • openmeter/llmcost/sync/normalizer_test.go
  • openmeter/llmcost/sync/reconciler.go
  • openmeter/llmcost/sync/reconciler_test.go
  • openmeter/llmcost/sync/sync.go
  • openmeter/llmcost/sync/sync_test.go
  • openmeter/server/router/router.go
  • openmeter/server/server.go
  • tools/migrate/migrations/20260303205801_llmcost_add.down.sql
  • tools/migrate/migrations/20260303205801_llmcost_add.up.sql

Comment thread api/v3/filters/filter.go Resolved
Comment thread api/v3/server/server.go Resolved
Comment thread app/common/llmcost.go Resolved
Comment thread cmd/jobs/internal/wire.go Resolved
Comment thread openmeter/ent/schema/llmcostprice.go Resolved
Comment thread openmeter/llmcost/sync/reconciler.go Resolved
Comment thread openmeter/llmcost/sync/sync.go Resolved
Comment thread openmeter/llmcost/sync/sync.go Resolved
Comment thread openmeter/server/router/router.go Resolved
@hekike
hekike force-pushed the feat/llm-cost-service branch from 6ebfae1 to 55da997 Compare March 3, 2026 23:37

@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.

♻️ Duplicate comments (13)
openmeter/llmcost/service/service.go (2)

37-43: ⚠️ Potential issue | 🟠 Major

Scope override lookup to the requested page.

Lines 37-43 can fetch/materialize a large override set even when ListPrices only needs one page. Please pass pagination constraints (or query only override keys present in result.Items) so this stays bounded.

As per coding guidelines "Performance should be a priority in critical code paths. Anything related to event ingestion, message processing, database operations (regardless of database) 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/llmcost/service/service.go` around lines 37 - 43, The call to
s.adapter.ListOverrides using llmcost.ListOverridesInput in the ListPrices path
can materialize a large override set; limit the scope by passing pagination
parameters (e.g., page/token and pageSize) from the ListPrices request into
ListOverridesInput or, alternatively, fetch only the override keys that appear
in result.Items and then call ListOverrides with those keys to restrict the
query; update the ListPrices flow to propagate pagination (or compute a short
key list from result.Items) when invoking s.adapter.ListOverrides so the
override lookup stays bounded and avoids full scans.

90-93: ⚠️ Potential issue | 🟠 Major

Don’t suppress all ResolvePrice errors.

Lines 90-93 currently fall back to global price for every error, including unexpected backend failures. Please only ignore the not-found case and propagate everything else.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openmeter/llmcost/service/service.go` around lines 90 - 93, The current code
in the ResolvePrice call in service.go incorrectly treats all errors as "not
found" and returns the global price; update the error handling in the block
around ResolvePrice so that you only swallow the specific not-found error (e.g.,
using errors.Is(err, ErrPriceNotFound) or the repository/provider's IsNotFound
helper) and return the global price in that case, but for any other error return
nil, err (propagate the error). Locate the ResolvePrice invocation and replace
the blanket if err != nil { return price, nil } with a conditional that checks
for the not-found sentinel and otherwise returns the error.
api/v3/filters/filter.go (1)

4-14: ⚠️ Potential issue | 🟡 Minor

Please enforce StringFilter’s one-operator contract.

Line 4 says only one operator should be set, but Lines 5-14 currently allow multiple operators with no guard. That can make downstream filter semantics ambiguous. Please add validation (Validate() or JSON unmarshal-time validation) and reject invalid combinations.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@api/v3/filters/filter.go` around lines 4 - 14, Add enforcement that exactly
one of Eq, Neq, or Contains is set on StringFilter: implement a Validate()
method on StringFilter that counts non-nil fields (Eq, Neq, Contains) and
returns an error if the count is not exactly 1 with a descriptive message;
either call StringFilter.Validate() wherever filters are created/used
(deserialization entry points) or implement UnmarshalJSON on StringFilter to
call Validate() after decoding so invalid JSON is rejected at parse time.
openmeter/llmcost/adapter/mapping.go (1)

42-53: ⚠️ Potential issue | 🟠 Major

Optional pricing currently conflates nil and explicit zero.

Line 42-53 treats zero as “not set,” while Line 59-64 converts nil to zero. Together, explicit 0 values for optional token prices can’t round-trip correctly. Please switch presence detection to nullable/pointer-backed persistence semantics instead of numeric zero checks.

Also applies to: 59-64

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openmeter/llmcost/adapter/mapping.go` around lines 42 - 53, The mapping
currently treats numeric zero as "not set" causing explicit zeros to be lost;
change presence detection to nullable pointers: stop using IsZero on
entity.CacheReadPerToken/CacheWritePerToken/ReasoningPerToken and instead make
those fields pointer types (or check their pointer-ness) and only set
price.Pricing.CacheReadPerToken/CacheWritePerToken/ReasoningPerToken when the
entity pointer is non-nil (using lo.ToPtr on the dereferenced value), and in the
reverse mapping (the block that currently converts nil to zero around the 59-64
logic) restore pointer semantics by setting the entity fields to nil if
price.Pricing.* is nil and to a pointer to the value when present so explicit 0
values round-trip correctly.
app/common/llmcost.go (1)

43-47: ⚠️ Potential issue | 🟠 Major

Add a timeout to the HTTP client.

The HTTP client here has no timeout, which means external API calls (like fetching from models.dev) could hang indefinitely if the upstream is slow or unresponsive.

⏱️ Suggested fix
+import (
+	"time"
+	// ... existing imports
+)
+
 return llmcostsync.NewSyncJob(llmcostsync.SyncJobConfig{
-	HTTPClient: &http.Client{},
+	HTTPClient: &http.Client{Timeout: 30 * time.Second},
 	Repo:       adapter,
 	Logger:     logger.With("subsystem", "llmcost.sync"),
 }), nil
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@app/common/llmcost.go` around lines 43 - 47, The HTTP client passed into
llmcostsync.NewSyncJob (SyncJobConfig.HTTPClient) has no timeout and can hang;
update the HTTPClient from &http.Client{} to an instance with a sensible Timeout
(e.g. Timeout: 10*time.Second) and add the time import; ensure the change is
applied where llmcostsync.NewSyncJob is called so SyncJobConfig.HTTPClient uses
the timed http.Client.
openmeter/llmcost/adapter/adapter.go (1)

72-79: ⚠️ Potential issue | 🟡 Minor

Add a nil guard for tx and tx.GetConfig().

If tx is nil or tx.GetConfig() returns nil, this will panic. While callers should pass valid values, a defensive check here prevents obscure runtime crashes.

🛡️ Suggested fix
 func (a *adapter) WithTx(ctx context.Context, tx *entutils.TxDriver) *adapter {
+	if tx == nil || tx.GetConfig() == nil {
+		return a
+	}
 	txClient := entdb.NewTxClientFromRawConfig(ctx, *tx.GetConfig())

 	return &adapter{
 		db:     txClient.Client(),
 		logger: a.logger,
 	}
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openmeter/llmcost/adapter/adapter.go` around lines 72 - 79, In WithTx, add
defensive nil checks for the incoming tx and for tx.GetConfig() before
dereferencing: if tx == nil or cfg := tx.GetConfig(); cfg == nil then return the
receiver adapter (a) unchanged (and optionally log the unexpected nil);
otherwise call entdb.NewTxClientFromRawConfig(ctx, *cfg) and proceed as before.
This prevents panics in adapter.WithTx when tx or tx.GetConfig() is nil.
openmeter/llmcost/sync/reconciler.go (2)

114-121: ⚠️ Potential issue | 🟠 Major

Don’t swallow upsert failures in reconciliation.

Right now failed upserts are only logged and the method still returns nil, so callers can’t detect partial sync failure.

Please return an aggregated error (or fail fast) when any UpsertGlobalPrice call fails.

Also applies to: 131-132

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openmeter/llmcost/sync/reconciler.go` around lines 114 - 121, The reconciler
currently logs errors from r.repo.UpsertGlobalPrice in Reconcile (e.g., the
block around r.repo.UpsertGlobalPrice(ctx, price)) but swallows them and returns
nil; change the function to propagate failures by returning an aggregated error
(or failing fast) instead of continuing: collect errors from each failed
r.repo.UpsertGlobalPrice call (and the other similar upsert at the 131-132
region) and return a combined error at the end (or immediately return the error)
so callers can detect partial sync failures.

162-165: ⚠️ Potential issue | 🟠 Major

Agreement/averaging should include optional pricing dimensions too.

cache_read_per_token, cache_write_per_token, and reasoning_per_token are currently excluded, so reconciled pricing can drift from the actual agreed set.

Include optional fields in both agreement checks and averaging logic (with consistent nil-handling rules).

Also applies to: 195-207

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openmeter/llmcost/sync/reconciler.go` around lines 162 - 165, pricesAgree
currently only compares InputPerToken and OutputPerToken; extend it to also
compare optional fields cache_read_per_token, cache_write_per_token, and
reasoning_per_token using the same decimalsAgree helper and tolerance; update
the averaging logic referenced around the reconciler's averaging functions (the
code handling model price reconciliation / averaging) to include these three
optional fields as well, applying the same nil-handling rules used for
InputPerToken/OutputPerToken (e.g., treat nil vs nil as equal, nil vs non-nil as
disagreement or handle by ignoring per the existing convention) so both
agreement checks (pricesAgree) and averaging produce consistent results for all
pricing dimensions (reference functions: pricesAgree, decimalsAgree and the
averaging/reconcile functions in the same file).
openmeter/llmcost/sync/sync.go (2)

68-74: ⚠️ Potential issue | 🔴 Critical

Guard Logger in constructor to prevent nil panic in Run.

Run assumes j.logger is non-nil. Passing nil in config will panic on log calls.

Set a default logger inside NewSyncJob when config.Logger is nil.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openmeter/llmcost/sync/sync.go` around lines 68 - 74, NewSyncJob currently
assigns config.Logger directly to SyncJob.logger causing Run (which calls
j.logger) to panic if nil; update NewSyncJob to guard against a nil logger by
replacing config.Logger with a default (e.g., a no-op or standard logger) when
config.Logger == nil before constructing and returning the SyncJob (references:
NewSyncJob, SyncJob, Run, j.logger, config.Logger, NewReconciler).

49-52: ⚠️ Potential issue | 🟠 Major

Avoid http.DefaultClient here; use a timeouted client.

If the passed client is nil, fetch can block indefinitely on slow/unresponsive upstreams.

Use a dedicated client with a sensible timeout when client == nil.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openmeter/llmcost/sync/sync.go` around lines 49 - 52, DefaultFetchers
currently falls back to http.DefaultClient which can block indefinitely; when
client == nil replace that fallback with a dedicated *http.Client instance that
includes a sensible Timeout (e.g., 5–30s) so requests won't hang. Update the
DefaultFetchers function to construct a timeouted client (instead of using
http.DefaultClient) before using it to build and return the []Fetcher so all
fetchers use the new client.
openmeter/llmcost/adapter/price.go (1)

253-303: ⚠️ Potential issue | 🟠 Major

UpsertGlobalPrice is race-prone under concurrent syncs.

The read-then-create/update pattern is non-atomic, so two workers can observe “no current row” and both proceed to create/update paths.

A safer fix is to make this atomic (DB upsert / conflict-update) or lock the target row key inside one transaction before deciding create vs update.

As per coding guidelines "Performance should be a priority in critical code paths. Anything related to event ingestion, message processing, database operations (regardless of database) 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/llmcost/adapter/price.go` around lines 253 - 303, UpsertGlobalPrice
is race-prone because it does a read-then-create/update (see UpsertGlobalPrice,
a.db.LLMCostPrice.Query(), UpdateOneID and Create) outside of an atomic upsert;
fix it by making the operation atomic: either perform a DB-level
upsert/conflict-update (use your ORM's OnConflict/Upsert support to update the
existing row when provider+model conflict) or inside the existing transaction
acquire a row lock for the target key (SELECT ... FOR UPDATE or the ORM
equivalent before deciding create vs update) so only one worker can
create/update the current global price; update the code paths currently using
UpdateOneID and Create to use the chosen atomic mechanism and remove the
non-atomic read-then-create race.
openmeter/llmcost/llmcost.go (1)

53-64: ⚠️ Potential issue | 🟠 Major

Validate optional token prices as non-negative too.

Right now only required fields are validated. Negative values in optional dimensions can still pass.

Suggested fix
 func (p ModelPricing) Validate() error {
 	var errs []error

 	if p.InputPerToken.IsNegative() {
 		errs = append(errs, ErrPriceMustBeNonNegative)
 	}

 	if p.OutputPerToken.IsNegative() {
 		errs = append(errs, ErrPriceMustBeNonNegative)
 	}
+
+	if p.CacheReadPerToken != nil && p.CacheReadPerToken.IsNegative() {
+		errs = append(errs, ErrPriceMustBeNonNegative)
+	}
+
+	if p.CacheWritePerToken != nil && p.CacheWritePerToken.IsNegative() {
+		errs = append(errs, ErrPriceMustBeNonNegative)
+	}
+
+	if p.ReasoningPerToken != nil && p.ReasoningPerToken.IsNegative() {
+		errs = append(errs, ErrPriceMustBeNonNegative)
+	}

 	return models.NewNillableGenericValidationError(errors.Join(errs...))
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openmeter/llmcost/llmcost.go` around lines 53 - 64, The Validate method on
ModelPricing currently only rejects negative values for required fields but
misses optional token-price fields; update ModelPricing.Validate to check each
optional price field (e.g., InputPerToken, OutputPerToken and any other optional
token price fields on ModelPricing) for negativity only if they are set/present,
and append ErrPriceMustBeNonNegative to errs when any such optional
field.IsNegative() returns true; keep using errors.Join(errs...) and return
models.NewNillableGenericValidationError(...) so all collected errors are
reported.
openmeter/llmcost/service.go (1)

134-158: ⚠️ Potential issue | 🟡 Minor

Validate non-zero EffectiveFrom for overrides.

A zero EffectiveFrom currently passes unless EffectiveTo is also set and earlier, which can let accidental zero-time values through.

Add an i.EffectiveFrom.IsZero() check before the range comparison.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openmeter/llmcost/service.go` around lines 134 - 158, The
CreateOverrideInput.Validate method currently allows a zero EffectiveFrom unless
EffectiveTo makes the range invalid; add a check using i.EffectiveFrom.IsZero()
before the range comparison and append a descriptive error (e.g.,
ErrEffectiveFromZero or ErrEffectiveFromEmpty — create that error constant if it
doesn't exist) to errs so zero-valued EffectiveFrom is rejected; keep the new
check before the existing i.EffectiveFrom.After(*i.EffectiveTo) comparison to
avoid nil/invalid range logic.
🧹 Nitpick comments (6)
openmeter/llmcost/llmcost_test.go (2)

105-131: Consider testing boundary condition where EffectiveFrom equals EffectiveTo.

You test effective_from after effective_to (error) and before (valid), but the edge case where they're equal might be worth explicitly documenting behavior for.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openmeter/llmcost/llmcost_test.go` around lines 105 - 131, Add a test that
covers the boundary where EffectiveFrom equals EffectiveTo to document expected
behavior: within the existing llmcost_test.go tests add a case (e.g.,
t.Run("effective_from equals effective_to", ...)) that constructs a Price with
EffectiveFrom and EffectiveTo set to the same time and asserts whether
Price.Validate() should return an error or not according to the intended
contract; reference the Price struct fields EffectiveFrom/EffectiveTo and the
Validate() method to locate where to add this test and ensure the assertion
matches the desired policy (either require.Error or require.NoError).

27-56: Good validation coverage, consider adding tests for optional pricing fields.

The ModelPricing validation tests cover InputPerToken and OutputPerToken well. You might want to add test cases for negative values in the optional fields (CacheReadPerToken, CacheWritePerToken, ReasoningPerToken) if the validation logic handles those too.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openmeter/llmcost/llmcost_test.go` around lines 27 - 56, Add tests to
TestModelPricingValidate that assert validation fails when optional per-token
fields are negative: create subtests in TestModelPricingValidate (e.g.,
"negative cache read", "negative cache write", "negative reasoning") that
construct ModelPricing with CacheReadPerToken, CacheWritePerToken, and
ReasoningPerToken set to negative alpacadecimal values and call p.Validate()
expecting an error; keep the existing valid/zero cases and use
require.Error/NoError consistent with the other cases so the tests exercise
Validate() for those optional fields.
openmeter/llmcost/sync/fetcher_modelsdev.go (1)

49-51: Deduplicate the source identifier string.

"models_dev" appears both in Source() (line 50) and when constructing SourcePrice (line 102). Consider using a constant or calling f.Source() to keep them in sync.

Suggested fix
+const modelsDevSource llmcost.PriceSource = "models_dev"
+
 func (f *modelsDevFetcher) Source() llmcost.PriceSource {
-	return "models_dev"
+	return modelsDevSource
 }

Then use modelsDevSource or f.Source() at line 102.

Also applies to: 101-103

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openmeter/llmcost/sync/fetcher_modelsdev.go` around lines 49 - 51, The string
literal "models_dev" is duplicated in modelsDevFetcher.Source() and where a
llmcost.SourcePrice is constructed; replace the duplication by exposing a single
source identifier: either add a package-level constant (e.g., modelsDevSource)
and use it in both modelsDevFetcher.Source() and when building SourcePrice, or
have the SourcePrice construction call f.Source() instead of the hard-coded
string; update references around the modelsDevFetcher.Source() method and the
SourcePrice creation to use that single symbol so they remain in sync.
openmeter/llmcost/sync/reconciler_test.go (1)

18-58: Good mock adapter setup.

The mock captures upserted prices and supports error injection via upsertErr. Consider adding a test case that exercises the error path to verify Reconcile propagates adapter errors correctly.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openmeter/llmcost/sync/reconciler_test.go` around lines 18 - 58, Add a unit
test that injects an error into the mockAdapter by setting mockAdapter.upsertErr
and then calls Reconcile to ensure the adapter error is propagated;
specifically, instantiate mockAdapter, set up any required inputs for Reconcile,
call Reconcile, assert it returns the injected error, and verify
mockAdapter.upsertedPrices was not modified (or only contains expected entries)
to confirm failure short-circuits UpsertGlobalPrice; reference mockAdapter and
its UpsertGlobalPrice method and the Reconcile function when adding the test.
tools/migrate/migrations/20260303233513_llmcost_add.up.sql (1)

24-25: Redundant unique index on primary key.

The id column is already the PRIMARY KEY (line 22), which implicitly creates a unique index. The explicit unique index on line 25 is unnecessary overhead.

Suggested fix
--- create index "llmcostprice_id" to table: "llm_cost_prices"
-CREATE UNIQUE INDEX "llmcostprice_id" ON "llm_cost_prices" ("id");
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tools/migrate/migrations/20260303233513_llmcost_add.up.sql` around lines 24 -
25, The migration creates a redundant unique index "llmcostprice_id" on
"llm_cost_prices"."id" even though "id" is already the PRIMARY KEY; remove the
CREATE UNIQUE INDEX "llmcostprice_id" ON "llm_cost_prices" ("id"); line so the
migration does not create an unnecessary duplicate unique index, leaving the
primary key to provide uniqueness for "id".
api/v3/handlers/llmcost/list_prices.go (1)

38-51: Minor: Consider extracting pagination defaults.

The default values (page 1, size 20) are repeated in both branches. You could simplify this slightly:

♻️ Optional simplification
-		if params.Page != nil {
-			req.Page = pagination.NewPage(
-				lo.FromPtrOr(params.Page.Number, 1),
-				lo.FromPtrOr(params.Page.Size, 20),
-			)
-
-			if err := req.Page.Validate(); err != nil {
-				return req, apierrors.NewBadRequestError(ctx, err, apierrors.InvalidParameters{
-					{Field: "page", Reason: err.Error(), Source: apierrors.InvalidParamSourceQuery},
-				})
-			}
-		} else {
-			req.Page = pagination.NewPage(1, 20)
-		}
+		pageNum := 1
+		pageSize := 20
+		if params.Page != nil {
+			pageNum = lo.FromPtrOr(params.Page.Number, pageNum)
+			pageSize = lo.FromPtrOr(params.Page.Size, pageSize)
+		}
+		req.Page = pagination.NewPage(pageNum, pageSize)
+
+		if err := req.Page.Validate(); err != nil {
+			return req, apierrors.NewBadRequestError(ctx, err, apierrors.InvalidParameters{
+				{Field: "page", Reason: err.Error(), Source: apierrors.InvalidParamSourceQuery},
+			})
+		}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@api/v3/handlers/llmcost/list_prices.go` around lines 38 - 51, The pagination
default values (page 1, size 20) are duplicated in the if/else branch around
params.Page; extract them into a single place and use them when constructing
req.Page and when calling pagination.NewPage to avoid duplication. Specifically,
introduce local default variables (e.g., defaultNum := 1, defaultSize := 20) or
compute num := lo.FromPtrOr(params.Page.Number, defaultNum) and size :=
lo.FromPtrOr(params.Page.Size, defaultSize) before creating req.Page, then call
req.Page = pagination.NewPage(num, size) and keep the existing
req.Page.Validate() logic (referencing params.Page, req.Page,
pagination.NewPage, and req.Page.Validate) so behavior remains identical.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Duplicate comments:
In `@api/v3/filters/filter.go`:
- Around line 4-14: Add enforcement that exactly one of Eq, Neq, or Contains is
set on StringFilter: implement a Validate() method on StringFilter that counts
non-nil fields (Eq, Neq, Contains) and returns an error if the count is not
exactly 1 with a descriptive message; either call StringFilter.Validate()
wherever filters are created/used (deserialization entry points) or implement
UnmarshalJSON on StringFilter to call Validate() after decoding so invalid JSON
is rejected at parse time.

In `@app/common/llmcost.go`:
- Around line 43-47: The HTTP client passed into llmcostsync.NewSyncJob
(SyncJobConfig.HTTPClient) has no timeout and can hang; update the HTTPClient
from &http.Client{} to an instance with a sensible Timeout (e.g. Timeout:
10*time.Second) and add the time import; ensure the change is applied where
llmcostsync.NewSyncJob is called so SyncJobConfig.HTTPClient uses the timed
http.Client.

In `@openmeter/llmcost/adapter/adapter.go`:
- Around line 72-79: In WithTx, add defensive nil checks for the incoming tx and
for tx.GetConfig() before dereferencing: if tx == nil or cfg := tx.GetConfig();
cfg == nil then return the receiver adapter (a) unchanged (and optionally log
the unexpected nil); otherwise call entdb.NewTxClientFromRawConfig(ctx, *cfg)
and proceed as before. This prevents panics in adapter.WithTx when tx or
tx.GetConfig() is nil.

In `@openmeter/llmcost/adapter/mapping.go`:
- Around line 42-53: The mapping currently treats numeric zero as "not set"
causing explicit zeros to be lost; change presence detection to nullable
pointers: stop using IsZero on
entity.CacheReadPerToken/CacheWritePerToken/ReasoningPerToken and instead make
those fields pointer types (or check their pointer-ness) and only set
price.Pricing.CacheReadPerToken/CacheWritePerToken/ReasoningPerToken when the
entity pointer is non-nil (using lo.ToPtr on the dereferenced value), and in the
reverse mapping (the block that currently converts nil to zero around the 59-64
logic) restore pointer semantics by setting the entity fields to nil if
price.Pricing.* is nil and to a pointer to the value when present so explicit 0
values round-trip correctly.

In `@openmeter/llmcost/adapter/price.go`:
- Around line 253-303: UpsertGlobalPrice is race-prone because it does a
read-then-create/update (see UpsertGlobalPrice, a.db.LLMCostPrice.Query(),
UpdateOneID and Create) outside of an atomic upsert; fix it by making the
operation atomic: either perform a DB-level upsert/conflict-update (use your
ORM's OnConflict/Upsert support to update the existing row when provider+model
conflict) or inside the existing transaction acquire a row lock for the target
key (SELECT ... FOR UPDATE or the ORM equivalent before deciding create vs
update) so only one worker can create/update the current global price; update
the code paths currently using UpdateOneID and Create to use the chosen atomic
mechanism and remove the non-atomic read-then-create race.

In `@openmeter/llmcost/llmcost.go`:
- Around line 53-64: The Validate method on ModelPricing currently only rejects
negative values for required fields but misses optional token-price fields;
update ModelPricing.Validate to check each optional price field (e.g.,
InputPerToken, OutputPerToken and any other optional token price fields on
ModelPricing) for negativity only if they are set/present, and append
ErrPriceMustBeNonNegative to errs when any such optional field.IsNegative()
returns true; keep using errors.Join(errs...) and return
models.NewNillableGenericValidationError(...) so all collected errors are
reported.

In `@openmeter/llmcost/service.go`:
- Around line 134-158: The CreateOverrideInput.Validate method currently allows
a zero EffectiveFrom unless EffectiveTo makes the range invalid; add a check
using i.EffectiveFrom.IsZero() before the range comparison and append a
descriptive error (e.g., ErrEffectiveFromZero or ErrEffectiveFromEmpty — create
that error constant if it doesn't exist) to errs so zero-valued EffectiveFrom is
rejected; keep the new check before the existing
i.EffectiveFrom.After(*i.EffectiveTo) comparison to avoid nil/invalid range
logic.

In `@openmeter/llmcost/service/service.go`:
- Around line 37-43: The call to s.adapter.ListOverrides using
llmcost.ListOverridesInput in the ListPrices path can materialize a large
override set; limit the scope by passing pagination parameters (e.g., page/token
and pageSize) from the ListPrices request into ListOverridesInput or,
alternatively, fetch only the override keys that appear in result.Items and then
call ListOverrides with those keys to restrict the query; update the ListPrices
flow to propagate pagination (or compute a short key list from result.Items)
when invoking s.adapter.ListOverrides so the override lookup stays bounded and
avoids full scans.
- Around line 90-93: The current code in the ResolvePrice call in service.go
incorrectly treats all errors as "not found" and returns the global price;
update the error handling in the block around ResolvePrice so that you only
swallow the specific not-found error (e.g., using errors.Is(err,
ErrPriceNotFound) or the repository/provider's IsNotFound helper) and return the
global price in that case, but for any other error return nil, err (propagate
the error). Locate the ResolvePrice invocation and replace the blanket if err !=
nil { return price, nil } with a conditional that checks for the not-found
sentinel and otherwise returns the error.

In `@openmeter/llmcost/sync/reconciler.go`:
- Around line 114-121: The reconciler currently logs errors from
r.repo.UpsertGlobalPrice in Reconcile (e.g., the block around
r.repo.UpsertGlobalPrice(ctx, price)) but swallows them and returns nil; change
the function to propagate failures by returning an aggregated error (or failing
fast) instead of continuing: collect errors from each failed
r.repo.UpsertGlobalPrice call (and the other similar upsert at the 131-132
region) and return a combined error at the end (or immediately return the error)
so callers can detect partial sync failures.
- Around line 162-165: pricesAgree currently only compares InputPerToken and
OutputPerToken; extend it to also compare optional fields cache_read_per_token,
cache_write_per_token, and reasoning_per_token using the same decimalsAgree
helper and tolerance; update the averaging logic referenced around the
reconciler's averaging functions (the code handling model price reconciliation /
averaging) to include these three optional fields as well, applying the same
nil-handling rules used for InputPerToken/OutputPerToken (e.g., treat nil vs nil
as equal, nil vs non-nil as disagreement or handle by ignoring per the existing
convention) so both agreement checks (pricesAgree) and averaging produce
consistent results for all pricing dimensions (reference functions: pricesAgree,
decimalsAgree and the averaging/reconcile functions in the same file).

In `@openmeter/llmcost/sync/sync.go`:
- Around line 68-74: NewSyncJob currently assigns config.Logger directly to
SyncJob.logger causing Run (which calls j.logger) to panic if nil; update
NewSyncJob to guard against a nil logger by replacing config.Logger with a
default (e.g., a no-op or standard logger) when config.Logger == nil before
constructing and returning the SyncJob (references: NewSyncJob, SyncJob, Run,
j.logger, config.Logger, NewReconciler).
- Around line 49-52: DefaultFetchers currently falls back to http.DefaultClient
which can block indefinitely; when client == nil replace that fallback with a
dedicated *http.Client instance that includes a sensible Timeout (e.g., 5–30s)
so requests won't hang. Update the DefaultFetchers function to construct a
timeouted client (instead of using http.DefaultClient) before using it to build
and return the []Fetcher so all fetchers use the new client.

---

Nitpick comments:
In `@api/v3/handlers/llmcost/list_prices.go`:
- Around line 38-51: The pagination default values (page 1, size 20) are
duplicated in the if/else branch around params.Page; extract them into a single
place and use them when constructing req.Page and when calling
pagination.NewPage to avoid duplication. Specifically, introduce local default
variables (e.g., defaultNum := 1, defaultSize := 20) or compute num :=
lo.FromPtrOr(params.Page.Number, defaultNum) and size :=
lo.FromPtrOr(params.Page.Size, defaultSize) before creating req.Page, then call
req.Page = pagination.NewPage(num, size) and keep the existing
req.Page.Validate() logic (referencing params.Page, req.Page,
pagination.NewPage, and req.Page.Validate) so behavior remains identical.

In `@openmeter/llmcost/llmcost_test.go`:
- Around line 105-131: Add a test that covers the boundary where EffectiveFrom
equals EffectiveTo to document expected behavior: within the existing
llmcost_test.go tests add a case (e.g., t.Run("effective_from equals
effective_to", ...)) that constructs a Price with EffectiveFrom and EffectiveTo
set to the same time and asserts whether Price.Validate() should return an error
or not according to the intended contract; reference the Price struct fields
EffectiveFrom/EffectiveTo and the Validate() method to locate where to add this
test and ensure the assertion matches the desired policy (either require.Error
or require.NoError).
- Around line 27-56: Add tests to TestModelPricingValidate that assert
validation fails when optional per-token fields are negative: create subtests in
TestModelPricingValidate (e.g., "negative cache read", "negative cache write",
"negative reasoning") that construct ModelPricing with CacheReadPerToken,
CacheWritePerToken, and ReasoningPerToken set to negative alpacadecimal values
and call p.Validate() expecting an error; keep the existing valid/zero cases and
use require.Error/NoError consistent with the other cases so the tests exercise
Validate() for those optional fields.

In `@openmeter/llmcost/sync/fetcher_modelsdev.go`:
- Around line 49-51: The string literal "models_dev" is duplicated in
modelsDevFetcher.Source() and where a llmcost.SourcePrice is constructed;
replace the duplication by exposing a single source identifier: either add a
package-level constant (e.g., modelsDevSource) and use it in both
modelsDevFetcher.Source() and when building SourcePrice, or have the SourcePrice
construction call f.Source() instead of the hard-coded string; update references
around the modelsDevFetcher.Source() method and the SourcePrice creation to use
that single symbol so they remain in sync.

In `@openmeter/llmcost/sync/reconciler_test.go`:
- Around line 18-58: Add a unit test that injects an error into the mockAdapter
by setting mockAdapter.upsertErr and then calls Reconcile to ensure the adapter
error is propagated; specifically, instantiate mockAdapter, set up any required
inputs for Reconcile, call Reconcile, assert it returns the injected error, and
verify mockAdapter.upsertedPrices was not modified (or only contains expected
entries) to confirm failure short-circuits UpsertGlobalPrice; reference
mockAdapter and its UpsertGlobalPrice method and the Reconcile function when
adding the test.

In `@tools/migrate/migrations/20260303233513_llmcost_add.up.sql`:
- Around line 24-25: The migration creates a redundant unique index
"llmcostprice_id" on "llm_cost_prices"."id" even though "id" is already the
PRIMARY KEY; remove the CREATE UNIQUE INDEX "llmcostprice_id" ON
"llm_cost_prices" ("id"); line so the migration does not create an unnecessary
duplicate unique index, leaving the primary key to provide uniqueness for "id".

ℹ️ Review info

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6ebfae1 and 55da997.

⛔ Files ignored due to path filters (20)
  • go.sum is excluded by !**/*.sum, !**/*.sum
  • openmeter/ent/db/client.go is excluded by !**/ent/db/**
  • openmeter/ent/db/ent.go is excluded by !**/ent/db/**
  • openmeter/ent/db/expose.go is excluded by !**/ent/db/**
  • openmeter/ent/db/hook/hook.go is excluded by !**/ent/db/**
  • openmeter/ent/db/llmcostprice.go is excluded by !**/ent/db/**
  • openmeter/ent/db/llmcostprice/llmcostprice.go is excluded by !**/ent/db/**
  • openmeter/ent/db/llmcostprice/where.go is excluded by !**/ent/db/**
  • openmeter/ent/db/llmcostprice_create.go is excluded by !**/ent/db/**
  • openmeter/ent/db/llmcostprice_delete.go is excluded by !**/ent/db/**
  • openmeter/ent/db/llmcostprice_query.go is excluded by !**/ent/db/**
  • openmeter/ent/db/llmcostprice_update.go is excluded by !**/ent/db/**
  • openmeter/ent/db/migrate/schema.go is excluded by !**/ent/db/**
  • openmeter/ent/db/mutation.go is excluded by !**/ent/db/**
  • openmeter/ent/db/paginate.go is excluded by !**/ent/db/**
  • openmeter/ent/db/predicate/predicate.go is excluded by !**/ent/db/**
  • openmeter/ent/db/runtime.go is excluded by !**/ent/db/**
  • openmeter/ent/db/setorclear.go is excluded by !**/ent/db/**
  • openmeter/ent/db/tx.go is excluded by !**/ent/db/**
  • tools/migrate/migrations/atlas.sum is excluded by !**/*.sum, !**/*.sum
📒 Files selected for processing (41)
  • Makefile
  • api/v3/filters/filter.go
  • api/v3/handlers/llmcost/convert.go
  • api/v3/handlers/llmcost/create_override.go
  • api/v3/handlers/llmcost/delete_override.go
  • api/v3/handlers/llmcost/get_price.go
  • api/v3/handlers/llmcost/handler.go
  • api/v3/handlers/llmcost/list_overrides.go
  • api/v3/handlers/llmcost/list_prices.go
  • api/v3/server/routes.go
  • api/v3/server/server.go
  • app/common/llmcost.go
  • cmd/jobs/internal/wire.go
  • cmd/jobs/internal/wire_gen.go
  • cmd/jobs/llmcost/llmcost.go
  • cmd/jobs/main.go
  • cmd/server/main.go
  • cmd/server/wire.go
  • cmd/server/wire_gen.go
  • openmeter/ent/schema/llmcostprice.go
  • openmeter/llmcost/adapter.go
  • openmeter/llmcost/adapter/adapter.go
  • openmeter/llmcost/adapter/mapping.go
  • openmeter/llmcost/adapter/price.go
  • openmeter/llmcost/errors.go
  • openmeter/llmcost/llmcost.go
  • openmeter/llmcost/llmcost_test.go
  • openmeter/llmcost/service.go
  • openmeter/llmcost/service/service.go
  • openmeter/llmcost/sync/fetcher.go
  • openmeter/llmcost/sync/fetcher_modelsdev.go
  • openmeter/llmcost/sync/normalizer.go
  • openmeter/llmcost/sync/normalizer_test.go
  • openmeter/llmcost/sync/reconciler.go
  • openmeter/llmcost/sync/reconciler_test.go
  • openmeter/llmcost/sync/sync.go
  • openmeter/llmcost/sync/sync_test.go
  • openmeter/server/router/router.go
  • openmeter/server/server.go
  • tools/migrate/migrations/20260303233513_llmcost_add.down.sql
  • tools/migrate/migrations/20260303233513_llmcost_add.up.sql
✅ Files skipped from review due to trivial changes (1)
  • tools/migrate/migrations/20260303233513_llmcost_add.down.sql
🚧 Files skipped from review as they are similar to previous changes (10)
  • api/v3/handlers/llmcost/delete_override.go
  • cmd/jobs/internal/wire.go
  • cmd/server/main.go
  • openmeter/llmcost/adapter.go
  • cmd/jobs/main.go
  • openmeter/server/router/router.go
  • openmeter/server/server.go
  • Makefile
  • openmeter/llmcost/sync/sync_test.go
  • openmeter/llmcost/sync/normalizer.go

@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 (3)
openmeter/llmcost/service/service.go (2)

119-123: Same note as CreateOverride - transaction wrapper may be redundant for single adapter calls.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openmeter/llmcost/service/service.go` around lines 119 - 123, The
DeleteOverride method currently wraps a single adapter call in
transaction.RunWithNoValue which is redundant (same as CreateOverride note);
change service.DeleteOverride to call s.adapter.DeleteOverride(ctx, input)
directly instead of using transaction.RunWithNoValue, remove the transaction
wrapper and any now-unused transaction import, and mirror the same adjustment
you made for CreateOverride so both service.DeleteOverride and
service.CreateOverride consistently call the adapter directly.

113-117: Transaction wrapper may be redundant here.

The adapter's CreateOverride already wraps itself in TransactingRepo. Since this service method just delegates to a single adapter call, the outer transaction.Run creates an extra layer (savepoints). This is functionally correct but adds minor overhead.

If future service logic won't require multiple adapter calls in one transaction, consider removing the wrapper for simplicity.

♻️ Optional simplification
 func (s *service) CreateOverride(ctx context.Context, input llmcost.CreateOverrideInput) (llmcost.Price, error) {
-	return transaction.Run(ctx, s.adapter, func(ctx context.Context) (llmcost.Price, error) {
-		return s.adapter.CreateOverride(ctx, input)
-	})
+	return s.adapter.CreateOverride(ctx, input)
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openmeter/llmcost/service/service.go` around lines 113 - 117, The
CreateOverride service method currently wraps a single adapter call in
transaction.Run causing an unnecessary transaction/savepoint layer; remove the
outer transaction.Run in service.CreateOverride and directly call
s.adapter.CreateOverride(ctx, input) since the adapter's CreateOverride already
uses TransactingRepo, or keep the wrapper only if you plan to add multiple
adapter calls that must be atomic.
openmeter/llmcost/adapter/price.go (1)

194-205: Consider adding DeletedAtIsNil() to the query for consistency.

The query fetches the entity without filtering out soft-deleted records. While you check entity.DeletedAt == nil afterwards (line 207), other methods in this file filter out deleted records in the query itself. Adding the filter here would be more consistent and avoid fetching tombstoned records.

♻️ Suggested change
 		entity, err := a.db.LLMCostPrice.Query().
+			Where(pricedb.DeletedAtIsNil()).
 			Where(pricedb.ID(input.ID)).
 			Where(pricedb.NamespaceEQ(input.Namespace)).
 			Where(pricedb.SourceEQ(string(llmcost.PriceSourceManual))).
 			Only(ctx)

Then you can simplify lines 207-215 by removing the DeletedAt == nil check.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openmeter/llmcost/adapter/price.go` around lines 194 - 205, The query
building in the a.db.LLMCostPrice.Query() call for fetching an override should
include the DeletedAtIsNil() predicate to exclude soft-deleted records (add
.Where(pricedb.DeletedAtIsNil()) into the chain), and then remove the subsequent
runtime check of entity.DeletedAt == nil and its related error return logic so
the method relies on the query to filter tombstoned records; update the query
chain around the call to Only(ctx) and delete the post-query DeletedAt
check/return.
🤖 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/llmcost/adapter/price.go`:
- Around line 110-114: The current branch incorrectly wraps any non-NotFound
error from the namespace override query as models.NewGenericNotFoundError;
instead, check entdb.IsNotFound(err) and only return
models.NewGenericNotFoundError when that check is true, but for any other err
return or wrap the original error (e.g., as an internal/unknown error) so
callers see the real failure; update the code around entdb.IsNotFound(err) in
price resolution (references: entdb.IsNotFound, models.NewGenericNotFoundError,
llmcost.Price) to propagate the actual err when it's not a NotFound case.

In `@openmeter/llmcost/service/service.go`:
- Around line 91-98: The not-found error type is inconsistent:
IsGenericNotFoundError checks for *GenericNotFoundError but some code (e.g.,
places that call NewPriceNotFoundError / PriceNotFoundError in this file)
constructs a different ValidationIssue, so the fallback in ResolvePrice (the
block returning price when models.IsGenericNotFoundError(err)) never triggers.
Fix by returning the generic not-found type everywhere ResolvePrice and related
helpers report "price not found"—replace calls that create a
PriceNotFoundError/ValidationIssue with models.NewGenericNotFoundError (or
ensure they return *models.GenericNotFoundError) so
models.IsGenericNotFoundError(...) will succeed and the global price fallback is
used.

---

Nitpick comments:
In `@openmeter/llmcost/adapter/price.go`:
- Around line 194-205: The query building in the a.db.LLMCostPrice.Query() call
for fetching an override should include the DeletedAtIsNil() predicate to
exclude soft-deleted records (add .Where(pricedb.DeletedAtIsNil()) into the
chain), and then remove the subsequent runtime check of entity.DeletedAt == nil
and its related error return logic so the method relies on the query to filter
tombstoned records; update the query chain around the call to Only(ctx) and
delete the post-query DeletedAt check/return.

In `@openmeter/llmcost/service/service.go`:
- Around line 119-123: The DeleteOverride method currently wraps a single
adapter call in transaction.RunWithNoValue which is redundant (same as
CreateOverride note); change service.DeleteOverride to call
s.adapter.DeleteOverride(ctx, input) directly instead of using
transaction.RunWithNoValue, remove the transaction wrapper and any now-unused
transaction import, and mirror the same adjustment you made for CreateOverride
so both service.DeleteOverride and service.CreateOverride consistently call the
adapter directly.
- Around line 113-117: The CreateOverride service method currently wraps a
single adapter call in transaction.Run causing an unnecessary
transaction/savepoint layer; remove the outer transaction.Run in
service.CreateOverride and directly call s.adapter.CreateOverride(ctx, input)
since the adapter's CreateOverride already uses TransactingRepo, or keep the
wrapper only if you plan to add multiple adapter calls that must be atomic.

ℹ️ Review info

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 1c65ba7c-2049-47bb-9be3-26c733918afc

📥 Commits

Reviewing files that changed from the base of the PR and between 55da997 and f973d81.

📒 Files selected for processing (2)
  • openmeter/llmcost/adapter/price.go
  • openmeter/llmcost/service/service.go

Comment thread openmeter/llmcost/adapter/price.go Resolved
Comment thread openmeter/llmcost/service/service.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

🤖 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/llmcost/sync/reconciler.go`:
- Around line 149-156: The current inner loop only tests prices[j] against the
anchor prices[i], which can admit members that disagree with other members;
change the append logic so that before adding prices[j] to agreeing you verify
pairwise agreement between prices[j].Pricing and every member in the current
agreeing slice (iterate over agreeing and call pricesAgree for each, and only
append if all calls return true), ensuring the selected subset is mutually
agreeing rather than just agreeing with the anchor.
- Around line 71-97: The code currently uses raw rows (`sourcePrices` from
`groups`) so duplicates from the same `Source` can inflate counts and averages;
update the logic so you first deduplicate `sourcePrices` by the `Source` field
to produce a map of unique-source entries (use the same llmcost.Source
identification used in the persisted `llmcost.SourcePricesMap`), then use the
size of that unique-source set to enforce `r.minAgreement`, pass the
deduplicated slice/map into `r.findAgreement` (or adjust `findAgreement` to
accept/operate on unique sources), and finally build `sourcePricesMap` from
those unique agreeing sources so the agreement count, averaging and persisted
provenance are all computed from the same unique-source inputs.

ℹ️ Review info

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: acbd6f30-fcb8-4ba5-9507-f732bf1641a4

📥 Commits

Reviewing files that changed from the base of the PR and between f973d81 and 67c8c00.

📒 Files selected for processing (2)
  • openmeter/llmcost/sync/reconciler.go
  • openmeter/llmcost/sync/reconciler_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • openmeter/llmcost/sync/reconciler_test.go

Comment thread openmeter/llmcost/sync/reconciler.go Resolved
Comment thread openmeter/llmcost/sync/reconciler.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: 1

♻️ Duplicate comments (1)
openmeter/llmcost/adapter/price.go (1)

262-307: ⚠️ Potential issue | 🟠 Major

UpsertGlobalPrice is still race-prone under concurrent writers.

Line 262 to Line 307 still does read-then-write. Two workers can both miss existing and both attempt create/update paths. Since uniqueness is keyed by (provider, model_id, namespace, effective_from), this can still yield conflicting inserts or multiple “current” global rows (effective_to IS NULL) with different effective_from.

Please make this path atomic (single-statement upsert or lock+recheck in-tx) and enforce a DB invariant for one current global row per provider/model.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openmeter/llmcost/adapter/price.go` around lines 262 - 307, UpsertGlobalPrice
currently does a read-then-write using a plain Query/Create/UpdateOneID
(LLMCostPrice.Query, LLMCostPrice.Create, LLMCostPrice.UpdateOneID) which is
race-prone under concurrent writers; wrap the logic in a DB transaction and
either perform a SELECT ... FOR UPDATE on the candidate existing row to recheck
after acquiring the lock or use a single-statement upsert if your DB/ORM
supports it, then run the Update or Create inside that transaction and commit;
additionally add/ensure a database-level invariant (e.g., a partial unique index
for provider+model_id+(namespace IS NULL)+effective_to IS NULL or equivalent) so
the DB enforces “one current global row” and surface unique-constraint errors to
convert them into a retry path in UpsertGlobalPrice.
🧹 Nitpick comments (1)
openmeter/llmcost/adapter/price.go (1)

90-103: Consider a time-aware index for resolve lookups.

Both resolve queries filter by namespace/provider/model plus effective window and then sort by effective_from DESC. If version history grows, this can become a hot-path sort/scan. A composite/partial index that includes the effective-time access pattern would help keep this fast.

As per coding guidelines "Performance should be a priority in critical code paths. Anything related to event ingestion, message processing, database operations (regardless of database) should be vetted for potential performance bottlenecks."

Also applies to: 118-131

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openmeter/llmcost/adapter/price.go` around lines 90 - 103, The resolve query
built in a.db.LLMCostPrice.Query() (using pricedb.EffectiveFromLTE,
EffectiveToIsNil/EffectiveToGT and
Order(pricedb.ByEffectiveFrom(sql.OrderDesc()))) needs a time-aware
composite/partial index to avoid hot-path sorts; add a DB migration that creates
a composite index on (namespace, provider, model_id, effective_from DESC) and a
partial predicate to cover current-window rows (e.g. effective_to IS NULL OR
effective_to > now()) so the planner can seek the latest effective_from
directly; apply the same migration and index use for the other resolve query
path around the code referenced at lines 118-131 and update any ent/schema or
raw SQL migration artifacts accordingly.
🤖 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/llmcost/adapter/price.go`:
- Around line 152-160: The current update call (a.db.LLMCostPrice.Update() with
filters pricedb.DeletedAtIsNil(), NamespaceEQ, ProviderEQ, ModelIDEQ, SourceEQ)
soft-deletes all manual overrides; change it to only soft-delete the currently
active override by adding time-window predicates: require StartsAt <=
clock.Now() and (EndsAt is nil OR EndsAt >= clock.Now()) so only entries active
now are marked deleted; keep SetDeletedAt(clock.Now()) and Save(ctx) unchanged
and use the same clock reference (clock.Now()) as in other parts of the code.

---

Duplicate comments:
In `@openmeter/llmcost/adapter/price.go`:
- Around line 262-307: UpsertGlobalPrice currently does a read-then-write using
a plain Query/Create/UpdateOneID (LLMCostPrice.Query, LLMCostPrice.Create,
LLMCostPrice.UpdateOneID) which is race-prone under concurrent writers; wrap the
logic in a DB transaction and either perform a SELECT ... FOR UPDATE on the
candidate existing row to recheck after acquiring the lock or use a
single-statement upsert if your DB/ORM supports it, then run the Update or
Create inside that transaction and commit; additionally add/ensure a
database-level invariant (e.g., a partial unique index for
provider+model_id+(namespace IS NULL)+effective_to IS NULL or equivalent) so the
DB enforces “one current global row” and surface unique-constraint errors to
convert them into a retry path in UpsertGlobalPrice.

---

Nitpick comments:
In `@openmeter/llmcost/adapter/price.go`:
- Around line 90-103: The resolve query built in a.db.LLMCostPrice.Query()
(using pricedb.EffectiveFromLTE, EffectiveToIsNil/EffectiveToGT and
Order(pricedb.ByEffectiveFrom(sql.OrderDesc()))) needs a time-aware
composite/partial index to avoid hot-path sorts; add a DB migration that creates
a composite index on (namespace, provider, model_id, effective_from DESC) and a
partial predicate to cover current-window rows (e.g. effective_to IS NULL OR
effective_to > now()) so the planner can seek the latest effective_from
directly; apply the same migration and index use for the other resolve query
path around the code referenced at lines 118-131 and update any ent/schema or
raw SQL migration artifacts accordingly.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 952b34e3-27af-40b2-916c-e298c409decc

📥 Commits

Reviewing files that changed from the base of the PR and between 67c8c00 and b8e5a4b.

📒 Files selected for processing (1)
  • openmeter/llmcost/adapter/price.go

Comment thread openmeter/llmcost/adapter/price.go Resolved
@hekike
hekike force-pushed the feat/llm-cost-service branch from d08a485 to b40b2c7 Compare March 4, 2026 14:30
Comment thread openmeter/ent/schema/llmcostprice.go Resolved
Comment thread api/v3/handlers/llmcost/convert.go Resolved
Comment thread api/v3/handlers/llmcost/convert.go Resolved
Comment thread api/v3/handlers/llmcost/convert.go Resolved
Comment thread api/v3/handlers/llmcost/list_prices.go Resolved
Comment thread openmeter/llmcost/adapter/mapping.go Resolved
@hekike
hekike enabled auto-merge (squash) March 4, 2026 18:22
@hekike
hekike merged commit 80c840d into main Mar 4, 2026
24 checks passed
@hekike
hekike deleted the feat/llm-cost-service branch March 4, 2026 18:27
@coderabbitai coderabbitai Bot mentioned this pull request Mar 4, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

release-note/ignore Ignore this change when generating release notes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants