Skip to content

fix(ai): a partial pricing snapshot replaces the whole catalog and never expires #793

Closed

Description

@dan-petty

Problem

ed6428f (#676, which closed #661) added a persisted pricing snapshot. Line numbers are at 9c879ae (release/v0.2.25), with genai-prices pinned at 0.1.6.

A partial snapshot replaces the whole catalog.

  • devops ai cost update-pricing --source <file> reads the file (src/devops_cli/ai/spend/pricing.py:458-461). It installs the file as genai-prices' process-wide snapshot and writes it unchanged to <data>/ai/pricing_snapshot.json (:492-497). Every later PricingRegistry loads that file when it starts (:228-247).
  • genai-prices uses a custom snapshot instead of its bundled data. It does not layer one on top of the other (genai_prices/data_snapshot.py:18-21). A model missing from the file has no price. _calc_exact_genai_cost returns None (pricing.py:328-358), and get_pricing then falls back to $0 with source unknown (:303-307). Nothing warns.
  • Reproduced offline at 9c879ae. Before the update, a 20K/2K-token gpt-4o call (provider openai) costs $0.07. After update_from_remote(source_url=<file with one model>), the same call costs $0.0, both in that process and in a new one. list_all_pricing() then holds 1 entry.
  • The snapshot applies to the whole process. pydantic-ai's own calc_price, which EmbeddingResult.cost tries first (src/devops_cli/ai/agents/embeddings.py:166), also sees the partial data.
  • A partial snapshot also zeroes token counts. pydantic-ai 2.35.0 reads the token usage of an OpenAI-compatible response through the snapshot (pydantic_ai/models/openai.py:5020-5026, pydantic_ai/usage.py:327-334). It looks for a provider by base URL, then by provider name, then by the fallback openai, and parses the response with that provider's extractors. A local Ollama endpoint matches nothing in the bundled data until the openai fallback. If the snapshot has no openai entry, or has one without extractors, every lookup fails and RequestUsage.extract returns 0 input and 0 output tokens. direct_model_request_sync and direct_model_request record resp.usage.input_tokens in the ledger (src/devops_cli/ai/direct.py:122, :168), so those calls are recorded with 0 tokens.
  • The reference model, gpt-4o by default (src/devops_cli/config/defaults.py:67), is priced with no provider (ledger.py:378, :604). genai-prices then finds the provider through its model_match. With a one-model file that names another provider, the reference model costs $0 with source unknown, so the report's counterfactual and the per-call local cost equivalent both drop to $0.
  • Both effects reproduce offline at 9c879ae through PricingRegistry(data_dir=...) and RequestUsage.extract. Without the file, gpt-4o costs $2.50 / $10.00 per million and a 20K/2K-token chat response yields 20000/2000 tokens. With a one-model file in <data>/ai/pricing_snapshot.json, gpt-4o costs $0 (source unknown) and the same response yields 0/0 tokens.

The snapshot cannot be cleared and never expires.

  • update-pricing has only --source and --timeout (src/devops_cli/commands/ai_cost.py:566-594). devops ai cost reset clears the ledger only (:691). The only way to remove the snapshot is to delete the file by hand.
  • The file is a bare provider list. It records neither a fetch time nor a genai-prices version (pricing.py:497). The loader stamps it with the load time, because DataSnapshot.timestamp defaults to now (genai_prices/data_snapshot.py:50; pricing.py:243-245). After genai-prices is upgraded, the old snapshot still overrides the newer bundled data.
  • A file that fails to parse is silently ignored (pricing.py:246-247).

Smaller leftovers of #661

  • list-pricing prints per-million rates derived from a 1K/1K-token call at the current time (pricing.py:427, :435). The column headings are Prompt USD / 1M and Completion USD / 1M (ai_cost.py:641-642), and nothing says these are base-tier rates. The command offers --format yaml (:612) but prints a table, because only json is handled (:634).
  • SpendGuard.record_usage (src/devops_cli/ai/agents/spend.py:55-63) prices a call with get_pricing(model). That is a flat base-tier rate with no request time. For claude-sonnet-4-5 at 250K input and 1K output tokens it records $0.765, while calculate_request_cost gives $1.5225. The registry lookup also runs on every call, because it is the dict.get default argument (:57-59). SpendGuard has no caller in src/; it is exported from devops_cli.ai.agents (src/devops_cli/ai/agents/__init__.py:285-291, :959-960).
  • The embeddings cost fallback (embeddings.py:163-172) prices input tokens with get_pricing(self.model_name). That applies no tier and no request time. It also passes no provider, so a local provider is not recognized as local.
  • update_from_remote has a branch for a fetched DataSnapshot, and that branch persists nothing (pricing.py:482-487). Real runs never reach it. UpdatePrices always has a url (genai_prices/update_prices.py:72), and the code fetches that URL itself (pricing.py:469-473). Only the mock in test_pricing_registry_remote_catalog_update (tests/test_ai_spend_pricing.py:154-201) reaches the branch. As a result, the default update path, which does write the file, has no test.

Tests that pass on the old code

  • test_pricing_registry_update_from_file_and_persistence (tests/test_ai_spend_pricing.py:224-266) builds the second registry while the first registry's snapshot is still installed for the whole process. The test passes with _load_persisted_snapshot stubbed out (checked at 9c879ae).
  • fix(ai): spend ledger overprices tiered models and prices calls at lookup time #661 items 4 to 8 are fixed in the code. Their tests pass on the code from before fix: harden sandbox, pricing ledger, cloudflare public IP bypass, and k8s network security (#661, #662, #663, #666, #667) #676:
    • Item 4: overrides resolve through resolve_data_path (pricing.py:219). No test covers this.
    • Item 5: roi divides by the observed span (src/devops_cli/ai/spend/payoff.py:14-22). test_calculate_days_active_branches (tests/test_ai_spend_payoff.py:12-33) never passes a --days window longer than the data.
    • Item 6: the cutoff is now in ISO format (src/devops_cli/ai/spend/ledger.py:324-329). test_spend_ledger_iso_date_filtering (tests/test_ai_spend_ledger.py:452) uses records 2 and 12 days old, which the old text comparison also sorted correctly. The defect affected a record earlier on the cutoff's calendar day.
    • Item 7: a duplicate column is now tolerated (_add_column, ledger.py:207-213). test_spend_ledger_init_db_duplicate_column_tolerance (:567-578) runs _init_db when every column already exists, so ALTER never runs.
    • Item 8: --format prometheus now passes the report through (ai_cost.py:343, :418). test_spend_ledger_export_prometheus_with_report (tests/test_ai_spend_ledger.py:581) fails on the old code only because the report= parameter is new. No test checks that --days, --reference-model or --hardware-cost change the Prometheus output.

What changed since this issue was written

Acceptance criteria

Snapshot

  • A snapshot is merged onto the bundled data of the installed genai-prices. This applies to a snapshot from --source, from the default remote update, and from the load at start-up. For its own model ids the snapshot's prices win; every other bundled model keeps its price. Test: call update_from_remote(source_url=<file with one provider that genai-prices does not bundle, and one model>), clear the process-wide snapshot, and build a new registry. A 20K/2K-token gpt-4o call (provider openai, request time pinned) costs the same as with no snapshot. get_pricing("gpt-4o") with no provider returns the bundled price with source genai_prices:openai. The file's model, looked up with the file's provider id, has the file's price.
  • Provider fields merge one at a time. A field the file leaves out (None) keeps the bundled value; this covers pricing_urls, description, price_comments, model_match, provider_match, extractors and fallback_model_providers. Test with a file whose only provider is openai, carrying only id, name, api_pattern and a gpt-4o model at a new price, after reload:
    • gpt-4o has the file's price both with provider openai and through get_pricing("gpt-4o") with no provider, which returns source genai_prices:openai.
    • gpt-4o-mini keeps its bundled price both with provider openai and with no provider.
  • Token extraction survives a partial snapshot. Test, for both files above: pydantic_ai.usage.RequestUsage.extract({"model": "gpt-4o", "usage": {"prompt_tokens": 20000, "completion_tokens": 2000, "total_tokens": 22000}}, provider="ollama", provider_url="http://localhost:11434/v1", provider_fallback="openai", api_flavor="chat") returns 20000 input and 2000 output tokens. The test fails on the old code.
  • The snapshot file records the genai-prices version and the fetch time next to the provider list. The snapshot is not loaded, and prices come from the bundled data, when its recorded version differs from the installed one or when it has no version (the format 9c879ae writes). Test with the installed version monkeypatched.
  • A loaded snapshot passes its recorded fetch time to genai-prices as auto_update_timestamp, not the load time.
  • When a snapshot is ignored (stale, old format or unreadable), one warning is logged. It names the file, the reason, and devops ai cost update-pricing --reset.
  • devops ai cost update-pricing --reset deletes <data>/ai/pricing_snapshot.json and clears the process-wide snapshot and the registry caches. It exits 0 when there is no file. Passing --reset with --source is a usage error.
  • update-pricing reports how many models the source supplied and how many the merged catalog holds.
  • A full snapshot loaded with --source keeps working offline: a later registry prices from it with no network access.
  • The DataSnapshot branch in update_from_remote (pricing.py:482-487) is removed. The default update path is tested with httpx2.get stubbed, and the test checks that the file is written and then reloaded.

Labels and per-call pricing

  • The list-pricing table headings and caption state that the rates are base-tier rates for a small call at the current time, and that each call is priced from its own usage and request time. The command help says the same. --format yaml prints YAML with the same content as --json.
  • SpendGuard.record_usage prices a call with calculate_request_cost at the request time, taken from an optional request_timestamp that defaults to now. The exception is a model with an entry in the caller's pricing mapping, which keeps its flat rate, and in that case the registry is not queried. Test: a claude-sonnet-4-5 call at 250K/1K tokens records the same cost as calculate_request_cost (1.5225 at genai-prices 0.1.6). The test fails on the old code.
  • The embeddings cost fallback prices with calculate_request_cost(model, input_tokens, 0, provider=<provider_name>, request_timestamp=<result timestamp>). Test: a time-windowed model gets the price for the request time, and a local provider costs 0 unless overridden.

Tests for #661 that fail on the old code

  • The persistence test clears the process-wide snapshot before it builds the second registry. It fails when _load_persisted_snapshot is stubbed out. An autouse fixture resets genai-prices' process-wide snapshot after every pricing test.
  • Item 4: PricingRegistry(), created from a subdirectory of a linked worktree with a relative data.dir, reads overrides from the main worktree's data directory. It uses the same fixture as test_the_spend_ledger_is_shared_from_any_directory (tests/test_data_dir_worktrees.py:276-289).
  • Item 5: _calculate_days_active with two days of data and days_filter=30 returns 2.0.
  • Item 6: with the clock pinned, --days excludes a record from earlier on the cutoff's calendar day than the cutoff.
  • Item 7: _add_column does not raise for a column that already exists, and _init_db succeeds when its column check is stale.
  • Item 8: the ledger holds one record from today and one from three days ago, for a different model. devops ai cost report --format prometheus --days 1 --hardware-cost 1000 prints no devops_cli_ai_requests_total line for the older model and prints devops_cli_ai_hardware_cost_usd 1000.00. devops_cli_ai_counterfactual_spend_usd changes with --reference-model. The bare devops ai cost --format prometheus behaves the same way.

Gate

  • No test touches the network, and none depends on the time of day. uv run devops ci passes, and the generated command docs list --reset. The PR adds changelog.d/793.md and its task file.
  • Person-run check: run devops ai cost update-pricing against the live genai-prices URL. devops ai cost list-pricing --search gpt-4o then shows priced rows, and devops ai cost update-pricing --reset removes <data>/ai/pricing_snapshot.json.

Key questions

  1. Merge a partial file, or reject it? Merge (proposed). Rejecting a file would require a definition of "models in use", and it would refuse a legitimate file that corrects only a few prices. A model-level merge keeps every bundled price and still lets a full file win everywhere. Proposed rules:
    • A provider in both the file and the bundled data merges field by field. A field the file sets wins. A field the file leaves out (None) keeps the bundled value. Replacing the whole provider would drop model_match, provider_match, extractors and fallback_model_providers, all of which default to None in genai-prices' Provider. That would break pricing with no provider and pydantic-ai's token counts.
    • Within a merged provider, the file's models come first and bundled models with other ids follow, so the file's prices are matched first.
    • A provider only the file has goes after all bundled providers, and bundled providers keep their order. genai-prices picks the first provider whose api_pattern or model_match fits. A file provider placed first with a broad pattern would capture lookups for bundled models: with a file provider matching starts_with: gpt placed first, calc_price(..., "gpt-4o") with no provider raises. The cost of this order is that a file-only model whose name a bundled provider also claims is priced only when its provider is given.
    • set-price remains the way to price a model that genai-prices does not know.
  2. What makes a snapshot older than the installed data? Proposed: it was fetched under a different genai-prices version from the installed one. The bundled data carries no date, but the package version identifies it and can be read offline through importlib.metadata. There is no age-based expiry: a fetch is a deliberate act, and a version change already invalidates it.
  3. What happens to a file the current code wrote (a bare list)? Proposed: it is treated as stale and ignored with the warning. The project is pre-1.0, so no migration is needed.
  4. Should an ignored file be deleted automatically? Proposed: no. Leave the file, log the warning, and let --reset delete it.
  5. How is "base tier" shown in JSON? Proposed: the JSON and YAML shape stays {model: pricing}, and the help text and generated docs say the rates are base tier. The table shows the label itself.
  6. Keep SpendGuard, which has no caller in src/? Proposed: keep it and fix it. It is part of the exported devops_cli.ai.agents API, and removing it is a separate decision. Rates the caller puts in its pricing mapping stay flat, because the caller chose them.
  7. Should the reference-model cost equivalents also move to tiered pricing? These are the report's counterfactual (ledger.py:376-395) and the per-call counter that feat(ai): track local llm usage against hardware spend and recognize cluster gateways (#930) #934 added (ledger.py:591-607). Proposed: no, not in this item. They estimate a hypothetical cost, and the report only has token totals. Keeping both at base-tier rates means the report and the Grafana counter agree.
  8. Fix list-pricing --format yaml here? Proposed: yes. The labelling change edits the same output branches, and the fix is a few lines with one test.

Depends on: none.
Related: #661 and #676 (origin). #887 (backlog) changes _is_local_host in the same file, with no ordering needed. #586 (v0.2.25) and #420 (v0.2.26) change lint rules that the new code must pass once they land.
Order: no other item in v0.2.25 to v0.2.29 touches these files, so this item can land at any point in v0.2.29.

Activity

  1. added
    type/bug
    scope/ai
    priority/p1-high
    on Oct 1, 2026
  2. added this to the v0.2.29 milestone on Oct 2, 2026
  3. dan-petty commented on Oct 2, 2026

    @dan-petty
    OwnerAuthor

    Placed in v0.2.29 on 2026-10-02. v0.2.29 holds P1 work that has to land before v0.3.0, which v0.2.25 to v0.2.28 had no room for. Backlog P1 items were ranked by Value, then Effort, with defects and security fixes first at a tie. This item ranked in the top ten, and two of the release's twelve slots stay open for P1 items that surface before then.

  4. dan-petty commented on Oct 2, 2026

    @dan-petty
    OwnerAuthor

    Refined to Ready on 2026-10-02 for v0.2.29. The body was checked claim by claim against release/v0.2.25 at 9c879ae, and a second agent then tried to refute it; every major objection was resolved in a revision. Cited lines were updated for code that moved, and the scope was corrected where merged work changed it. Acceptance criteria were tightened so each fails on the current code, and every key question now has a proposed answer.

  5. removed this from the v0.2.29 milestone on Oct 2, 2026
  6. dan-petty commented on Oct 2, 2026

    @dan-petty
    OwnerAuthor

    Moved to the backlog: #1034 (a P1 bug, High value and Low effort: paginated gh reads fail open, which PR readiness relies on) took this slot in v0.2.29. This item was the lowest-ranked one the job placed there (P1 bug, Medium/Medium, ranked below #892 when v0.2.29 was filled). It goes first among backlog P1 bugs when a pre-v0.3.0 slot opens.

  7. added this to the v0.2.34 milestone on Oct 9, 2026
  8. dan-petty commented on Oct 11, 2026

    @dan-petty
    OwnerAuthor

    Merged

  9. added a commit that references this issue on Oct 11, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    priority/p1-highscope/aitype/bug

    Type

    No type

    Projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions