Repository navigation
Description
Update 2026-11-26 (infra move): the gateway and monitoring files are now in dan-petty/homelab.
- The ingress rule that lets
devopsreach Prometheus on TCP 9090 is a follow-up issue there. - This issue keeps the command, the CronJob, the egress rule, the secret row and the product alert.
- Read
k8s/llm/...below as a homelab path.
Follow-up: dan-petty/homelab#310.
Problem
Owner, 2026-11-17: "litellm prices should be passed through and accurate". They are not for streamed calls.
- OpenRouter Activity, last 1 day: $6.92 total, 522M tokens, cache hit rate 95.5%.
- The gateway counters for the same day (
litellm_spend_metric_total,api_provider="openrouter"): $5.85 ($3.60deepseek/deepseek-v4.1-flash-1017, $2.25deepseek/deepseek-v4.1-flash) for 517.7M tokens. The tokens agree within 1%, so the spend is about 15% low on price, not on traffic. - Cause: LiteLLM v1.103.11 (
litellm/llms/openrouter/chat/transformation.py) always asks OpenRouter for usage accounting (usage.include: true) and, intransform_response(no stream), copiesusage.costinto the hidden headerllm_provider-x-litellm-response-cost, so the billed cost passes through. The streaming handler (OpenRouterChatCompletionStreamingHandler.chunk_parser) keepsusagebut sets no cost. A streamed call is then priced from themodel_infoprices thatk8s/llm/gateway/config.yamlof dan-petty/homelab writes for each DeepSeek deployment (order 1: 0.0784 / 0.2352 / cache read 0.002352 USD per million; order 2: 0.30 / 1.20), which are fixed estimates. The roadmap jobs stream (fix(ai): one retry layer for a gateway call #5965). - LiteLLM 1.109.1 has the same streaming handler, so an upgrade alone does not fix it (chore(k8s): Update the LLM gateway to LiteLLM 1.109.1 #6001).
Expected behavior
- The gateway records the cost that OpenRouter bills for each call, streamed or not: the
usage.costof the final stream chunk, through the open tool first (an upstream LiteLLM fix or a supported LiteLLM hook), and no hand-kept price table for OpenRouter deployments. - A daily check compares the gateway spend of OpenRouter with the spend that OpenRouter reports for the same day (its activity or key usage API) and fails, or alerts, when they differ by more than 5%.
- Until the pass-through works, the
model_infoprices of the DeepSeek deployments match the prices of the providers that OpenRouter routes them to (thefp8filter), with the source and date in a comment.
Related
- fix(monitoring): read AI spend from the gateway counter #4724, fix(monitoring): price local savings at the reference model #5914, feat(ai): Route DeepSeek calls around a stalled provider #5995, chore(k8s): Update the LLM gateway to LiteLLM 1.109.1 #6001.
Alternatives check of 2026-11-24: in-use.
The repository already uses this tool.
Tool: BerriAI/litellm (https://github.com/BerriAI/litellm), NOASSERTION, last activity 2026-11-24, maintained.
Reason: Searches found no maintained tool that passes OpenRouter's billed streamed cost into gateway spend or reconciles it daily; the in-use LiteLLM gateway already passes usage.cost for non-streamed calls and offers the callback hook, so it covers only part.
Covers:
- Non-streamed OpenRouter usage.cost already passes through
- CustomLogger callbacks hook exists for pricing and spend
- Gateway spend metrics and per-deployment model_info prices
Lacks:
- No streamed usage.cost in v1.103.11 or v1.109.1
- No daily reconciliation against OpenRouter activity totals
- Fixed model_info estimates drift from provider fp8 rates
Proposed design
Problem statement
Streamed OpenRouter calls are priced from the fixed model_info prices, so the gateway spend was about 15% below the OpenRouter bill ($5.85 against $6.92 on 2026-11-17). The gateway and monitoring files are in dan-petty/homelab, so this repository adds only the daily reconciliation: it compares the gateway spend of a day with the OpenRouter activity total, exits 1 over 5 percent, and alerts when the Job fails. It also adds the CronJob, the key Secret, the egress rule to Prometheus and the pod label that homelab#310 admits. Gate: the Job reaches Prometheus only after a person merges dan-petty/homelab#310.
Acceptance criteria
Requirement: Gateway spend of the day
The reconciliation MUST read the gateway OpenRouter spend of a day as the Prometheus value of sum(increase(litellm_spend_metric_total{api_provider="openrouter"}[1d])) at 00:00 UTC of the next day.
Scenario: Prometheus gives the day spend
- WHEN A unit test gives the Prometheus client a fake response with the value
5.85and runs the reader for2026-11-17. - THEN The request holds the query
sum(increase(litellm_spend_metric_total{api_provider="openrouter"}[1d]))at2026-11-18T00:00:00Z, and the reader returns5.85.
Requirement: Prometheus retry
The Prometheus reader MUST retry a refused connection with a bounded backoff before it fails.
Scenario: The first connections are refused
- WHEN A unit test gives the reader a fake transport that refuses the first two connections and returns
5.85on the third. - THEN The reader makes three attempts, waits between the attempts, and returns
5.85.
Requirement: Activity request
The activity reader MUST request the OpenRouter activity endpoint for the day with the gateway key as a bearer token.
Scenario: The request names the day and the key
- WHEN A unit test runs the reader for
2026-11-17withDEVOPS_CLI_OPENROUTER_API_KEYset to a test key and a fake HTTP transport. - THEN The recorded request is
GET https://openrouter.ai/api/v1/activity?date=2026-11-17with the headerAuthorization: Bearer <test key>.
Requirement: Activity total of the day
The activity reader MUST sum the usage field of the rows of the requested day.
Scenario: Rows of another day are ignored
- WHEN A unit test gives the reader a recorded activity response with two rows of
2026-11-17whoseusageis4.10and2.82, and one row of2026-11-16. - THEN The reader returns
6.92.
Requirement: Daily reconciliation fails over 5 percent
The command MUST exit 1 when the gateway spend and the activity total of a day differ by more than 5 percent.
Scenario: Spend is 15 percent low
- WHEN A unit test calls the reconciliation with the gateway total
5.85USD and the activity total6.92USD for2026-11-17. - THEN The command exits 1 and prints a message with both totals and their percentage difference.
Requirement: Daily reconciliation passes within 5 percent
The command MUST exit 0 when the two daily totals differ by at most 5 percent.
Scenario: Spend is within tolerance
- WHEN A unit test calls the reconciliation with the gateway total
6.60USD and the activity total6.92USD for2026-11-17. - THEN The command exits 0 and prints a message with the difference.
Requirement: Daily reconciliation CronJob
A CronJob MUST run ai spend reconcile-openrouter once each day in namespace devops.
Scenario: The rendered CronJob has the schedule, the args and the label
- WHEN
uv run devops ci --check --only k8svalidates the rendered devops manifests. - THEN The check passes and the CronJob
openrouter-reconcilehas a daily schedule, the argsai spend reconcile-openrouter, the variableDEVOPS_CLI_PROMETHEUS_URLset tohttp://prometheus-server.monitoring.svc.cluster.local:9090, and the pod labelapp.kubernetes.io/name: openrouter-reconcile.
Requirement: Reconciliation key
Secret devops/openrouter-activity MUST hold DEVOPS_CLI_OPENROUTER_API_KEY adopted from key openrouter-api-key of Secret llm/llm-gateway-secrets.
Scenario: The cluster Secret plan adopts the key
- WHEN A unit test builds the cluster Secret plan.
- THEN The
devops/openrouter-activitySecret holdsDEVOPS_CLI_OPENROUTER_API_KEYwith anadopt_fromreference to keyopenrouter-api-keyof Secretllm/llm-gateway-secrets.
Requirement: Reconciliation alert
A Prometheus rule MUST alert when the daily reconciliation Job fails.
Scenario: The rule selects the failed Job
- WHEN
uv run devops ci --check --only k8svalidates the rendered monitoring rules. - THEN The check passes and the rule expression selects
kube_job_status_failedof the Jobopenrouter-reconcile.
Requirement: Egress to Prometheus
The devops egress rule MUST allow TCP 9090 to monitoring for the pods that carry the label app.kubernetes.io/name: openrouter-reconcile only.
Scenario: The egress rule selects the reconciliation pods
- WHEN
uv run devops ci --check --only k8svalidates the rendered network policies. - THEN The check passes and the
devopsegress rule that namesmonitoringon port 9090 selects the pod labelapp.kubernetes.io/name: openrouter-reconcileand no other pod.
Requirement: Pending a person after the merge
The reconciliation Job MUST reach Prometheus after a person merges dan-petty/homelab#310, which admits the label app.kubernetes.io/name: openrouter-reconcile on TCP 9090.
Scenario: One manual Job run reaches Prometheus
- WHEN A person creates one Job from CronJob
openrouter-reconcileafterdan-petty/homelab#310merges. - THEN The Job exits 0 and its log shows the two daily totals and their difference.
Existing Tool Considered
BerriAI/litellm (https://github.com/BerriAI/litellm), verdict in-use: the alternatives check in the issue body records what the tool covers and lacks. The gateway files are in dan-petty/homelab, so this change adds no gateway workaround. It builds the daily reconciliation in devops-cli on the existing devops prometheus client and the OpenRouter activity endpoint, which the tool lacks: about 220 lines of code and 320 lines of tests, about 45k tokens to build and review, about 6 hours of elapsed time, and about 8k tokens a month to keep and fix.
Key questions
- Where does the streamed-cost pass-through itself go?: To dan-petty/homelab, which holds the gateway. This repository holds no environment tree, so this change adds only the daily reconciliation and its cluster plumbing. The reconciliation shows whether the pass-through works. (best practice) [sources: CONTEXT.md]
- Chosen: Keep the gateway change in dan-petty/homelab. CONTEXT.md states that the environment of the homelab cluster lives only in dan-petty/homelab.
- Rejected: Add a LiteLLM callback in this repository. The gateway image and its config are in homelab, so a callback here would not load.
- Which OpenRouter endpoint gives a past day's billed total?: The activity endpoint,
GET https://openrouter.ai/api/v1/activity?date=YYYY-MM-DD, read with the gateway key as a bearer token. No source in the repository yet confirms the path, the parameter or the response shape, so keep the URL, the query and the parsing in one function with one recorded fixture. (best practice) [sources: docs/ENV_VARS.md:198]- Chosen: Activity endpoint with the day parameter. It is the endpoint that the issue names for a day's total, and the Job needs a past day.
- Rejected: Key usage endpoint. The earlier proposal recorded no source that it gives a past day, so the reader stays in one function until a fixture shows the shape.
- Which Prometheus query gives the gateway OpenRouter spend of a day?:
sum(increase(litellm_spend_metric_total{api_provider="openrouter"}[1d])), evaluated at 00:00 UTC of the next day, through the existingdevops prometheusclient. The 1-day window at the day's end is the calendar day, not a rolling 24 hours from the run time. (best practice) [sources: k8s/devops/dashboards/ai-spend.json, docs/ENV_VARS.md:199, docs/CONFIGURATION.md:78, tests/commands/test_prometheus.py:21]- Chosen: Reuse the
devops prometheusclient. The repository already reads Prometheus with it and reads the address fromDEVOPS_CLI_PROMETHEUS_URL. - Rejected: Build a new HTTP client. It repeats the address, the timeout and the error handling of an existing client.
- Chosen: Reuse the
- Where does the
reconcile-openroutercommand live?: Insrc/devops_cli/commands/ai_cost.py, the Typer app that serves the spend commands. Theai spendgroup and theai costgroup use the same app, so one module serves both names. [sources: src/devops_cli/commands/ai_cost.py, src/devops_cli/commands/ai.py, docs/CLI_REFERENCE.md] - How does the reconciliation pod get the OpenRouter key?: From a new Secret
devops/openrouter-activity, whoseDEVOPS_CLI_OPENROUTER_API_KEYis adopted from keyopenrouter-api-keyof Secretllm/llm-gateway-secrets, read by the pod withvalueFrom.secretKeyRef. Secretdevops-cliis loaded withenvFromby every Job pod, so a provider key must not go there. (best practice) [sources: src/devops_cli/k8s/cluster_secrets.py:230, tests/k8s/test_cluster_secret_plan.py, SECURITY.md, k8s/devops/cronjob-repos-drift.yaml]- Chosen: Dedicated Secret read with
secretKeyRef. Only the reconciliation pod holds the key, and the key keeps its one source. - Rejected: Add the key to Secret
devops-cli. Every pod that loads that Secret withenvFromwould hold the provider key.
- Chosen: Dedicated Secret read with
- Does the daily check fail, alert, or both?: Both. The command exits 1 over 5 percent, as the nightly drift Job exits 1 on a drift, and a Prometheus rule alerts on
kube_job_status_failedof the Job. (best practice) [sources: k8s/devops/cronjob-repos-drift.yaml, k8s/devops/monitoring/prometheus-rules-values.yaml]- Chosen: Fail and alert. The command gives a testable exit status, and the rule makes the daily failure visible.
- Rejected: Fail only. A failed CronJob with no alert is silent.
- Rejected: Alert only. A manual run would have no failing exit status.
- Which pods does the egress rule select, and how does the Job survive the kube-router sync?: The CronJob pod template carries the label
app.kubernetes.io/name: openrouter-reconcile. Thedevopsegress rule tomonitoringon TCP 9090 selects that label only, anddan-petty/homelab#310admits the same label. kube-router admits a new pod as an ingress source at its next policy sync, 0.3 s to 1.7 s, so the command retries the first Prometheus query with a bounded backoff. (best practice) [sources: k8s/devops/networkpolicy.yaml]- Chosen: A dedicated pod label and a retry. homelab#310 selects the label, and the retry covers the policy sync delay.
- Rejected: Admit the whole
devopsnamespace. homelab#310 admits only the reconciliation pods, and the reply says the egress must match.
- Do the gateway
model_infoprices or the client price table change?: No. The gateway prices are homelab config, and the client price table insrc/devops_cli/ai/spend/pricing.pyprices local and hosted calls, not the gateway's OpenRouter routes. A call whose final chunk carries nousage.coststill records the fallback price. (best practice) [sources: CONTEXT.md, src/devops_cli/ai/spend/pricing.py]- Chosen: Keep both price tables as the fallback. The billed cost wins when LiteLLM sets it, and a call with no cost still records a price.
- Rejected: Remove the OpenRouter prices. A call whose final chunk carries no cost would record zero cost.
Fit
Fits in one pull request.
Suspected block
None.
Dependencies
None.
Activity
dan-petty commentedon Nov 17, 2026
llm, and .github/labels.yml declares no scope/llm label. Add the label to the file to give the scope to this item.Both address gateway cost being recorded lower than actual, but #4734 fixes the CLI-side pricing computation while this candidate fixes the gateway streaming handler that drops usage.cost.devops-cli-service commentedon Nov 18, 2026
The result in the alternatives block of the issue body changed. Before this check: no check. A person decides what the new result means for the item.
Searches (10)
Tools considered:
Searches run:
Sources:
devops-cli-service commentedon Nov 18, 2026
Status set to Ready at 8d638d7 (see proposed design in issue body).
fix(roadmap): remove spend disagreement pair from catalog (#7125)
dan-petty commentedon Nov 25, 2026
Returning #6165 to New because its core premise (
litellm:v1.103.11lacks streamed OpenRouterusage.costpass-through and requires a customopenrouter_cost.pycallback + fallback price update) has been overtaken onmain, and thefp8fallback-price rule is underspecified against the live OpenRouter API:v1.103.11: PR fix(deps): update container images #6817 (fb349e537, merged 2026-11-23) updatedk8s/llm/gateway/deployment.yamlfromghcr.io/berriai/litellm:v1.103.11toghcr.io/berriai/litellm:1.110.2(anduv.lockis atlitellm==1.110.3). This issue was refined atsha=8d638d707assumingv1.103.11would stay pinned.usage.costpass-through is already fixed in LiteLLM1.110.2: In bothBerriAI/litellmv1.110.2(litellm/litellm_core_utils/streaming_handler.py_USAGE_COST_HEADER_PROVIDERSandCustomStreamWrapper._propagate_usage_cost_to_hidden_params) and local1.110.3, streamed OpenRouter chunks already propagateusage.costintoresponse.hidden_params["additional_headers"]["llm_provider-x-litellm-response-cost"], whichLogging.response_cost_calculatoruses ahead ofmodel_infoestimates. Verified locally on OpenRouter streamed chunks (usage.cost = 0.00042with conflicting0.0005token estimates): bothkwargs["response_cost"]andstandard_logging_object["response_cost"]inasync_log_success_eventare0.00042. Building an injectedopenrouter_cost.pyConfigMap callback contradicts the issue's own open-tool-first rule now that LiteLLM1.110.2includes the fix. (Also note that in1.110.2/1.110.3, dottedlitellm_settings.callbacksentries must resolve to an instancemodule.instance, andasync_logging_hook/async_log_success_eventrun afterstandard_logging_object["response_cost"]has already been computed.)fp8fallback price rule is ambiguous against live OpenRouter endpoints: On 2026-11-25,https://openrouter.ai/api/v1/models/deepseek/deepseek-v4.1-flash-1017/endpointsand.../deepseek-v4.1-flash/endpointsincludequantization == "fp8"endpoints inpriorityandultrafasttiers (e.g.morph/fastat $0.60/$2.40 per M andvenice/ultrafastat $1.50/$6.00 per M, 5x list price) alongside standardservice_tier: nullendpoints (venice/fp8,featherless/fp8), with no single endpoint holding the highest prompt, completion, and cache-read rate simultaneously and noservice_tierfilter rule in the spec; furthermore, those table updates were only specified "until the pass-through works."Suggested re-scope for refinement: drop the
v1.103.11openrouter_cost.pycallback / ConfigMap workaround (and temporarymodel_infotable bump), and scope the item cleanly if daily OpenRouter activity reconciliation (ai spend reconcile-openrouter, CronJob/alert, andDEVOPS_CLI_OPENROUTER_API_KEY) is still desired againstlitellm:1.110.2.2 remaining items
devops-cli-service commentedon Nov 25, 2026
Next step: the stage job writes the plan of the item. See the section Proposed design of the body.
dan-petty commentedon Nov 27, 2026
Input for the plan of this item from dan-petty/homelab#310 (checked live on 2026-11-27):
devopstoprometheus-server.monitoring:9090is closed on both sides today. A temporary pod with no NetworkPolicy gotConnection refusedfrom Prometheus (themonitoringingress refuses). A temporary pod indevopsgotConnection refusedfrom a test server on 9090 that admits all traffic (thedevopsegress refuses). Evidence: https://github.com/dan-petty/homelab/issues/310#issuecomment-7220019545monitoringadmits the wholedevopsnamespace on 9090. homelab#310 admits only the reconciliation pods. The plan must give those pods a label of their own and name it, so that homelab#310 can select them.monitoringon 9090 must also select only those pods, not the wholedevopsperimeter.k8s/README.md, NetworkPolicy). The first Prometheus query of the Job can getConnection refused, so the command must retry it.devops-cli-service commentedon Nov 27, 2026
Next step: the stage job writes the plan of the item. See the section Proposed design of the body.
devops-cli-service commentedon Nov 29, 2026
Released in v0.247.0: https://github.com/dan-petty/devops-cli/releases/tag/v0.247.0
devops-cli-service commentedon Nov 29, 2026
Live since 2026-11-29 16:17 UTC