Repository navigation
Description
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 laterPricingRegistryloads 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_costreturns None (pricing.py:328-358), andget_pricingthen falls back to $0 with sourceunknown(: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, whichEmbeddingResult.costtries 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 fallbackopenai, and parses the response with that provider'sextractors. A local Ollama endpoint matches nothing in the bundled data until theopenaifallback. If the snapshot has noopenaientry, or has one withoutextractors, every lookup fails andRequestUsage.extractreturns 0 input and 0 output tokens.direct_model_request_syncanddirect_model_requestrecordresp.usage.input_tokensin the ledger (src/devops_cli/ai/direct.py:122,:168), so those calls are recorded with 0 tokens. - The reference model,
gpt-4oby default (src/devops_cli/config/defaults.py:67), is priced with no provider (ledger.py:378,:604). genai-prices then finds the provider through itsmodel_match. With a one-model file that names another provider, the reference model costs $0 with sourceunknown, 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=...)andRequestUsage.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 (sourceunknown) and the same response yields 0/0 tokens.
The snapshot cannot be cleared and never expires.
update-pricinghas only--sourceand--timeout(src/devops_cli/commands/ai_cost.py:566-594).devops ai cost resetclears 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, becauseDataSnapshot.timestampdefaults 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-pricingprints per-million rates derived from a 1K/1K-token call at the current time (pricing.py:427,:435). The column headings arePrompt USD / 1MandCompletion 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 onlyjsonis handled (:634).SpendGuard.record_usage(src/devops_cli/ai/agents/spend.py:55-63) prices a call withget_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, whilecalculate_request_costgives $1.5225. The registry lookup also runs on every call, because it is thedict.getdefault argument (:57-59). SpendGuard has no caller insrc/; it is exported fromdevops_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 withget_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_remotehas a branch for a fetchedDataSnapshot, and that branch persists nothing (pricing.py:482-487). Real runs never reach it.UpdatePricesalways has aurl(genai_prices/update_prices.py:72), and the code fetches that URL itself (pricing.py:469-473). Only the mock intest_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_snapshotstubbed 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:
roidivides 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--dayswindow 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_dbwhen every column already exists, soALTERnever runs. - Item 8:
--format prometheusnow 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 thereport=parameter is new. No test checks that--days,--reference-modelor--hardware-costchange the Prometheus output.
- Item 4: overrides resolve through
What changed since this issue was written
- feat(ai): track local llm usage against hardware spend and recognize cluster gateways (#930) #934 (feat(ai): track local llm usage against hardware spend and recognize cluster gateways #930) shifted the
pricing.pylines by about 70. The line references above are current. - feat(ai): finish reasons and stream completeness for model replies (#599) #966 (feat(ai): finish reasons and stream completeness for model replies #599) moved the column migration into
_ADDED_COLUMNSand_add_column(ledger.py:64-68,:207-213). A test can now call_add_columndirectly. - feat(ai): track local llm usage against hardware spend and recognize cluster gateways (#930) #934 also added a per-call cost equivalent for local calls, priced at the reference model's base-tier rate (
ledger.py:591-607). See key question 7. - Nothing else that landed on 2026-10-02 touches these files. Every claim in the earlier body still holds, except that item 8 does have a test that fails on the old code; that test just does not check the behaviour.
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: callupdate_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 sourcegenai_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,extractorsandfallback_model_providers. Test with a file whose only provider isopenai, carrying onlyid,name,api_patternand 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 sourcegenai_prices:openai. - gpt-4o-mini keeps its bundled price both with provider openai and with no provider.
- gpt-4o has the file's price both with provider openai and through
- 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 --resetdeletes<data>/ai/pricing_snapshot.jsonand clears the process-wide snapshot and the registry caches. It exits 0 when there is no file. Passing--resetwith--sourceis a usage error. -
update-pricingreports how many models the source supplied and how many the merged catalog holds. - A full snapshot loaded with
--sourcekeeps working offline: a later registry prices from it with no network access. - The
DataSnapshotbranch inupdate_from_remote(pricing.py:482-487) is removed. The default update path is tested withhttpx2.getstubbed, and the test checks that the file is written and then reloaded.
Labels and per-call pricing
- The
list-pricingtable 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 yamlprints YAML with the same content as--json. -
SpendGuard.record_usageprices a call withcalculate_request_costat the request time, taken from an optionalrequest_timestampthat defaults to now. The exception is a model with an entry in the caller'spricingmapping, 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 ascalculate_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_snapshotis 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 relativedata.dir, reads overrides from the main worktree's data directory. It uses the same fixture astest_the_spend_ledger_is_shared_from_any_directory(tests/test_data_dir_worktrees.py:276-289). - Item 5:
_calculate_days_activewith two days of data anddays_filter=30returns 2.0. - Item 6: with the clock pinned,
--daysexcludes a record from earlier on the cutoff's calendar day than the cutoff. - Item 7:
_add_columndoes not raise for a column that already exists, and_init_dbsucceeds 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 1000prints nodevops_cli_ai_requests_totalline for the older model and printsdevops_cli_ai_hardware_cost_usd 1000.00.devops_cli_ai_counterfactual_spend_usdchanges with--reference-model. The baredevops ai cost --format prometheusbehaves the same way.
Gate
- No test touches the network, and none depends on the time of day.
uv run devops cipasses, and the generated command docs list--reset. The PR addschangelog.d/793.mdand its task file. - Person-run check: run
devops ai cost update-pricingagainst the live genai-prices URL.devops ai cost list-pricing --search gpt-4othen shows priced rows, anddevops ai cost update-pricing --resetremoves<data>/ai/pricing_snapshot.json.
Key questions
- 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,extractorsandfallback_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_patternormodel_matchfits. A file provider placed first with a broad pattern would capture lookups for bundled models: with a file provider matchingstarts_with: gptplaced 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-priceremains the way to price a model that genai-prices does not know.
- 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
- 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. - 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.
- Should an ignored file be deleted automatically? Proposed: no. Leave the file, log the warning, and let
--resetdelete it. - 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. - Keep SpendGuard, which has no caller in
src/? Proposed: keep it and fix it. It is part of the exporteddevops_cli.ai.agentsAPI, and removing it is a separate decision. Rates the caller puts in itspricingmapping stay flat, because the caller chose them. - 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. - Fix
list-pricing --format yamlhere? 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.
Metadata
Metadata
Assignees
Labels
Type
Projects
- StatusShow more project fieldsDone
Activity
dan-petty commentedon Oct 2, 2026
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.
dan-petty commentedon Oct 2, 2026
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.
dan-petty commentedon Oct 2, 2026
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.
fix(ai): a partial pricing snapshot replaces the whole catalog and ne…
dan-petty commentedon Oct 11, 2026
Merged
feat(release): v0.2.34 (#1566)