Skip to content

fix(backends): unify raw-path token usage on mot.generation.usage; guard eval_count=None #1218

Closed

Description

@ajbozarth

Discovered during #1197 audit (Appendix A items 1 + planetf1's None-guard catch). Independent of #909 — files separately, no dependency.

Summary

Two related bugs in the same arithmetic block of mellea/stdlib/sampling/sampling_algos/budget_forcing_alg.py:

  1. Uniformity gap. mot.generation.usage is only populated by the chat path; generate_from_raw across all five backends still writes only to _meta["usage"] (never migrated in refactor!: partition ModelOutputThunk execution metadata into Generat… #908). Callers cannot read mot.generation.usage reliably regardless of which path produced the thunk.
  2. Latent TypeError. Ollama's response.eval_count and response.prompt_eval_count can be None (ollama docs). Budget forcing does arithmetic on those values without a None guard at lines 121, 152, 154–156, 192, 195, 197–199. A run that hits the None edge case raises a confusing TypeError mid-sample.

Folding both into a single fix because they touch the same arithmetic — splitting forces sequencing and risks rebases on overlapping lines.

Investigation

Audit on both main and feat/enhanced-tracing (#1181):

  • mot.generation.usage written: chat path only (post_processing of generate_from_chat_context) on all five backends.
  • _meta["usage"] written: raw path only (generate_from_raw) on all five backends.
  • refactor(telemetry)!: move backend tracing onto plugin/hook pattern #1181 leaves the raw-path _meta["usage"] write in place — this is not a "post-merge will fix it" situation.

So budget_forcing_alg.py reads from _meta["usage"] because that's the only place the data lives for raw paths. The reads aren't stale — the whole raw-path migration was just never done.

Fix

1. Migrate raw-path token usage

In each backend's generate_from_raw, after constructing the ModelOutputThunk, populate mot.generation.usage alongside (or instead of) _meta["usage"]. Touches:

  • mellea/backends/ollama.py (around line 575–590)
  • mellea/backends/openai.py (around line 1247–1256)
  • mellea/backends/litellm.py (generate_from_raw post-processing)
  • mellea/backends/watsonx.py (generate_from_raw post-processing)
  • mellea/backends/huggingface.py (generate_from_raw post-processing)

Same shape as the chat-path field: {"prompt_tokens": int | None, "completion_tokens": int | None, "total_tokens": int | None}.

2. Update budget forcing to read the unified field

mellea/stdlib/sampling/sampling_algos/budget_forcing_alg.py reads:

  • result[0]._meta["usage"]["completion_tokens"] → result[0].generation.usage["completion_tokens"]
  • Same pattern at lines 121, 152, 154–156, 192, 195, 197–199.

3. None guard

Wherever the code does arithmetic on usage["completion_tokens"] / usage["prompt_tokens"], treat None as 0 for accumulation, or short-circuit and skip the increment with a warning. Specifically lines 121 and 192:

gen_tok_count += result[0].generation.usage["completion_tokens"]  # may be None

Decision in PR review: silently treat None as 0, or raise a clear error? Leaning toward "treat as 0 with debug-log warning" to keep budget forcing robust; raising would surface the upstream Ollama edge case but at the cost of failing a sampling run that was probably otherwise fine.

Acceptance

  • All five backends populate mot.generation.usage in generate_from_raw
  • _meta["usage"] writes preserved (or moved behind a deprecation warning — to be decided in PR review; raw-path _meta["usage"] removal could fold into Epic: ModelOutputThunk structural cleanup #909 Area 1 (refactor(core): consolidate backend raw responses onto mot.raw namespace #1215)'s mot.raw migration)
  • budget_forcing_alg.py reads mot.generation.usage exclusively
  • None values in eval_count / prompt_eval_count no longer produce TypeError in budget forcing
  • Test added: budget forcing with eval_count=None does not raise
  • Test added: generate_from_raw populates mot.generation.usage (per backend)

Sequencing

Independent of #909. Can land before, during, or after — but landing before #909 Area 1 (#1215) is cleanest because Area 1 will retire the _meta keys, and migrating budget-forcing reads first means Area 1 doesn't have to coordinate with sampling.

Activity

  1. added
    bug
    area/backends
    area/sampling
    on Jun 5, 2026
  2. self-assigned this
    on Jun 11, 2026
  3. ajbozarth commented on Jun 11, 2026

    @ajbozarth
    MemberAuthor

    While planning #1183 I discovered that its design would be simplified if I included the populate mot.generation.usage piece of Part 1 in that work.

    So I will be including:

    • Part 1 (additive half): write mot.generation.usage per MOT in all five backends' raw paths, alongside the existing mot._meta["usage"] writes. Both fields populated; no removals.
    • Null-token policy decision: if any of prompt_tokens / completion_tokens / total_tokens cannot be determined for a MOT, set mot.generation.usage = None for that MOT (all-or-nothing dict). Matches the dict | None typing and the OpenAI-shape contract. Ollama's documented Optional[int] for prompt_eval_count/eval_count means "not yet available" (e.g. streaming intermediate chunks), not "zero" — None is the semantically correct write. Watsonx's current or 0 coerce switches to this policy for consistency.

    What stays open in this issue (#1218):

    • Part 1 (destructive half): remove or deprecation-warn the mot._meta["usage"] writes once consumers have migrated.
    • Part 2: migrate budget_forcing_alg.py reads from _meta["usage"] to mot.generation.usage.
    • Part 3 (consumer-side): handle mot.generation.usage is None in budget_forcing_alg.py arithmetic (skip vs. warn — design decision for that PR). This is now a "consumer guards None" task rather than "ollama backend coerces None" — the upstream null-write semantics are decided in refactor: move generate_from_raw hook firing into Backend base class #1183, so the consumer just needs to handle the documented dict | None contract.
  4. added a commit that references this issue on Jun 17, 2026
    9b3a3c2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

area/backendsarea/samplingbug

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions