Skip to content

fix(ai): embedding requests reach the spend ledger and the AI usage counters, priced against an embedding reference model #1623

Closed

Description

@dan-petty

Friction

  • The ai-spend-telemetry dashboard and devops ai cost leave out every embedding request devops-cli sends, so most gateway traffic is invisible.
  • In the 24 h ending 2026-10-17 13:20 UTC the gateway served 136 bge-m3:latest /v1/embeddings requests with about 4.29M input tokens. That is 72% of its 190 requests and about 89% of its input tokens.
  • None of them appears in devops_cli_ai_requests_total, devops_cli_ai_tokens_total, devops_cli_ai_local_cost_equivalent_usd_total or either spend ledger.
  • Every embedding caller is affected: RAG index and query, the per-file RAG step in reviews, library ingest and query, roadmap intake's duplicate check, the builtin search tool, the MCP RAG and library tools, the embedding benchmark and the dimension probe.
  • Recording them as the code stands would overstate savings. _emit_local_cost_equivalent prices every local token at the chat reference model, so 4.29M tokens a day at gpt-4o input ($2.50/M) would add about $10.73 a day, against about $0.09 at text-embedding-3-small ($0.02/M).

Evidence

Checked at main 3dd7fa6 (v0.2.36) on 2026-10-17, read-only, no model request sent.

  • track_request_spend (src/devops_cli/ai/spend/ledger.py:620-719) is the only writer of the ledger and the only emitter of the three counters (:706-718, :601-617).
  • Its callers are src/devops_cli/ai/client/unified.py:450, :586, :912 and src/devops_cli/ai/direct.py:118, :164. All are chat paths.
  • EmbeddingsEngine (src/devops_cli/ai/rag/embeddings.py) is the only client for gateway /v1/embeddings and Ollama /api/embed, and it never calls track_request_spend.
  • Gateway path: embed_texts :717 → _dispatch_embed :689 → _embed_openai :983 → _embed_single_openai_batch :950 and _embed_parallel_openai_batches :956 → _post_openai_batch_with_retry :902.
  • Ollama path: _query_ollama_node_batch :780. The dimension probe _probe_openai_dimension :640 sends one more request.
  • _openai_reply_vectors (:185-188) keeps data[].embedding and drops the reply's usage.prompt_tokens.
  • The pydantic-ai Embedder wrappers estimate tokens as words x 1.3 (src/devops_cli/ai/agents/embeddings.py:91, src/devops_cli/ai/rag/embeddings.py:1085) and record nothing.
  • The file records only text counts (devops_cli_embedding_cache_*, :737-739, :560) and batch-size metrics (:447-474).
  • Live, 24 h: gateway litellm_proxy_total_requests_metric_total{route="/v1/embeddings",requested_model="bge-m3:latest"} rose 136.0, all status 200, all with user agent python-httpx2/2.13.1 (the httpx2 pin in uv.lock).
  • Live, 7 d: no devops_cli_ai_* series carries an embedding model.
  • Both ledgers (repo .data/ai/spend.db and the user-level one), opened read-only, hold only chat, chat_dispatch and chat_cache_hit rows. There has never been an embedding row.
  • The requests are devops-cli's: devops_cli_embedding_cache_misses_total{job="devops-cli"} is non-zero in the same hours, and Open WebUI embeds against Ollama directly (k8s/llm/values-open-webui.yaml:38-41).
  • genai-prices 0.1.9 (offline) prices text-embedding-3-small at $0.02/M under provider openai. The chat reference default is gpt-4o-mini (src/devops_cli/config/defaults.py:65).
  • The worker threads already copy the caller's context (ContextPropagatingThreadPoolExecutor, src/devops_cli/ai/rag/embeddings.py:64, src/devops_cli/telemetry/tracer.py:58-63), so the spend stage and call observers reach them.
  • Call observers feed the review profile: ReviewProfiler.observe (src/devops_cli/ai/review/profile.py:240-259) adds every non-cached call to llm_calls and the token totals.

Remedy

Tests first, in tests/test_rag_embeddings.py and tests/test_ai_spend_ledger.py, with an httpx2 MockTransport behind the engine's client and a tmp_path ledger. No network, cluster or model. Each case fails on today's code:

  • One gateway batch writes one ledger row: request_type="embedding", prompt_tokens from the reply's usage.prompt_tokens, completion_tokens=0, served_by from the x-litellm-model-api-base header.
  • That batch emits one request point and one prompt-token point with model="bge-m3:latest" and operation="embeddings".
  • A batch retried on 429 and then answered writes one row. Parallel batches write one row each.
  • An Ollama /api/embed batch takes its tokens from prompt_eval_count.
  • An embed_texts call answered wholly from the L1 or Valkey cache writes at most one cached=True row with 0 tokens, not one per text.
  • The dimension probe writes one row.
  • Local savings for an embedding row use the embedding reference price, not the chat reference.
  • A review profile does not count embedding rows in llm_calls or its chat token totals; it reports them apart.

Code:

Proposed: type/bug, P1-High. It is the largest share of the reported gap, and the savings-reference item depends on its operation label and embedding reference.

Proposed design

Problem statement

Embedding requests made by devops-cli are not being recorded in the AI spend ledger or usage counters, leading to invisible costs and inaccurate reporting. This affects all embedding callers including RAG index/query, library ingest/query, roadmap intake's duplicate check, builtin search tool, MCP tools, and embedding benchmark/probe.

Acceptance criteria

  • Criterion 1: Embedding requests are recorded in the spend ledger with correct token counts
    Verification: After implementation, gateway /v1/embeddings requests should create rows in the ledger with request_type="embedding", prompt_tokens from reply's usage, and completion_tokens=0
  • Criterion 2: Embedding requests emit OpenTelemetry metrics with operation label
    Verification: The counters devops_cli_ai_requests_total, devops_cli_ai_tokens_total should include points with operation="embeddings" for embedding calls
  • Criterion 3: Local cost calculations use embedding reference model instead of chat reference
    Verification: When calculating local cost equivalent, the system should use ai.reference_embedding_model (default text-embedding-3-small) pricing instead of gpt-4o-mini pricing
  • Criterion 4: Review profiles do not count embedding rows in chat token totals
    Verification: ReviewProfiler.observe should keep embedding calls separate from llm_calls and not add them to chat token counts

Key questions

  • Which functions need to be modified to record embedding requests?: Functions that handle embedding requests including _embed_single_openai_batch after _post_openai_batch_with_retry returns, _query_ollama_node_batch, and _probe_openai_dimension in src/devops_cli/ai/rag/embeddings.py [sources: src/devops_cli/ai/rag/embeddings.py]
  • How should the embedding requests be tracked in the ledger?: Each embedding request should call track_request_spend with request_type="embedding", using tokens from the API response instead of estimates [sources: src/devops_cli/ai/spend/ledger.py]
  • What is the embedding reference model to be used for local cost calculations?: The default embedding reference model is text-embedding-3-small which should be configurable via ai.reference_embedding_model [sources: src/devops_cli/config/defaults.py]
  • How should the operation label be added to the OpenTelemetry metrics?: Add an operation label with value embeddings to the request and token counters in the telemetry emissions [sources: src/devops_cli/ai/spend/ledger.py]
  • Should embedding calls be counted in review profiles?: No, embedding calls should be kept separate from llm_calls and chat token totals in ReviewProfiler.observe to avoid skewing benchmarks [sources: src/devops_cli/ai/review/profile.py]

Fit

Fits in one pull request.

Suspected block

None.

Dependencies

None.

Activity

  1. added
    source/agent
    type/bug
    on Oct 18, 2026
  2. dan-petty commented on Oct 18, 2026

    @dan-petty
    OwnerAuthor

    Intake placed this item to the backlog: at intake only a critical fix goes into a release; a release start pulls Ready items in, P0 features first.

    • Type: type/bug. The candidate fixes a bug where embedding requests are not recorded in the spend ledger and AI usage counters.
    • Priority: P1-High. The bug causes significant inaccuracies in cost tracking and dashboard visibility for embedding requests.
    • Value: High. Embedding requests represent a large portion of gateway traffic and are critical for accurate cost monitoring.
    • Effort: Medium. Requires changes to the embedding engine and ledger recording logic, but tests can be isolated.
  3. dan-petty commented on Oct 18, 2026

    @dan-petty
    OwnerAuthor

    Status set to Ready at 25e2cda (see proposed design in issue body).

  4. dan-petty commented on Oct 18, 2026

    @dan-petty
    OwnerAuthor

    Amendment (2026-10-18): folded here by intake under the agent filing quota

    The cycle's agent filing allowance (#1153) was used, so devops roadmap intake filed nothing and named this item as the nearest. The candidate below is related work that can land with this item or be filed on its own in a later cycle. Candidate title: "fix(ai): every devops-cli install writes and reads one spend ledger, so devops ai cost counts every recorded call".

    Friction

    • Two spend ledgers exist on the workstation. Which one a call lands in depends on which devops binary ran, not only on the working directory.
    • The editable checkout writes <repo>/.data/ai/spend.db. Any installed copy writes ~/.local/share/devops-cli/.data/ai/spend.db, wherever it runs.
    • devops ai cost, cost report, roi, prometheus and reset read one ledger, picked by the same rule. Run in the repo, they missed 6 of the 54 gateway chat calls in the 24 h ending 2026-10-17 13:20 UTC (11%), with their tokens and savings.
    • The devcontainer image installs a non-editable copy (v0.2.34) as /usr/local/bin/devops. A shell where it comes before .venv/bin runs older code than the checkout and writes the user-level ledger.
    • The 6 rows came from plain devops roadmap intake runs that resolved to that copy.
    • Grafana is not affected: both binaries emit OTLP.

    Evidence

    Checked at main 3dd7fa6 (v0.2.36) on 2026-10-17, read-only. Ledgers opened read-only.

    • SpendLedger's default path is resolve_review_data_path(settings.data.dir)/ai/spend.db (src/devops_cli/ai/spend/ledger.py:226-237).
    • review_data_root() returns the main worktree only when is_own_source_repository() (src/devops_cli/core/repo.py:318-323, :274-291). An installed copy is never the source (_is_installed_copy, _source_repository, :209-238).
    • Reproduced from the repo as cwd: the system interpreter gives own_source_repo False and the user data root; .venv/bin/python gives True and the repo.
    • .devcontainer/Dockerfile:38-43 runs uv pip install --system --no-deps /tmp/devops-cli.
    • In the window the repo ledger holds 48 gateway chat rows and the user-level ledger 6. Together they match the gateway's count hour by hour.
    • The cost commands read the ledger at src/devops_cli/commands/ai_cost.py:327, :402, :469, :563 and :740.
    • The ledger has no repository column (ledger.py:33-51), so today the file location is the only per-repo split.
    • fix(security): reviews take config, data, contracts, scanner config and probe suppressions from the tree under review #972 placed spend under the review data root on purpose.

    Remedy

    Tests first, in tests/test_ai_spend_ledger.py and tests/test_core_repo.py, with tmp_path roots and a fake installed-copy location. No network:

    • An editable checkout and an installed copy, run from the same cwd, resolve the same ledger path.
    • devops ai cost report over that ledger counts rows written by both.

    Code (owner decision on #972's placement):

    • Proposed: the spend ledger always lives at user_data_root()/ai/spend.db, or under an absolute data.dir when one is set, independent of cwd and install type.
    • If per-repo reports matter, add a repository column filled from the active checkout, since the file location no longer splits them.
    • No migration code: the change note tells the person how to copy old rows across with sqlite3.
    • Alternative, not proposed: keep fix(security): reviews take config, data, contracts, scanner config and probe suppressions from the tree under review #972's placement and have the cost commands read both known locations. That leaves two writers.
    • Devcontainer: drop the system install from .devcontainer/Dockerfile:38-43, or keep it for bootstrap only and make .venv/bin come first on PATH in every shell (login, non-login and tool shells). Owner choice.
    • Add changelog.d/<n>.md under ### Fixed.

    Proposed: type/bug, P2-Medium.

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

    source/agenttype/bug

    Type

    No type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions