Why an Airflow Enrichment DAG’s LLM Bill Can Run 3.9x the Dashboard: Reasoning Tokens and an Invisible Compaction Pass

Airflow LLM cost accounting diagram comparing $12.35 logged on the dashboard versus $47.89 billed due to hidden reasoning tokens and compaction passes

Written by

in

Data teams are wiring LLM calls into pipelines the same way they wired in geocoding APIs ten years ago: a mapped task, a client library, a callback that writes a row into a cost table. Then a month later finance forwards the vendor invoice and asks why it is several times what the dashboard says. The SQL is fine and the DAG is fine. The cost table is wrong, because it trusted the top-level token counts in the API response.

This article walks through one nightly enrichment DAG where the invoice comes out at 3.9x the dashboard, and shows exactly where the missing money goes. The numbers are a worked scenario built on current list prices rather than a client’s invoice, but every mechanism in it is documented by the vendors. Two things cause the gap: reasoning tokens that one vendor reports outside its output field, and a server-side compaction pass whose tokens never appear in the top-level usage object. I covered the compaction mechanics in more depth in this breakdown of when agent context compaction pays off and when it backfires; here the focus is what it does to pipeline cost accounting.

The scenario: dashboard vs invoice

The DAG is a typical enrichment job. It runs nightly and has four tasks:

  • extract_rows pulls new and changed account records from the warehouse.
  • classify_rows sends each row to Gemini 3.8 Flash for a short label (industry, segment, a confidence flag). It is a mapped task, one call per row: 5,000 calls a night, each with a 1,000-token prompt and about 35 tokens of visible answer.
  • resolve_entities runs Claude Sonnet 5 as a multi-turn session per partition. Each turn feeds in a batch of candidate matches (about 35,000 tokens of rows and tool results) and asks the model to merge duplicates. There are 4 partitions, 18 turns each, with prompt caching and Anthropic’s compaction feature turned on at the default 150,000-token trigger.
  • load_enriched merges the results into dimension tables.

The cost logger is an on_success_callback that reads input_tokens / output_tokens style fields from each response and multiplies by the list price. Rates, per million tokens: Gemini 3.8 Flash at $0.75 input and $3.75 output; Claude Sonnet 5 at $2.00 input, $0.20 for a cache read, $2.50 for a five-minute cache write and $10.00 output.

Figure 1. One nightly run, illustrative scenario. The dashboard logs $12.35; the two vendors bill $47.89.

Here is the split:

  • Dashboard total: $12.35. Classify $4.41, resolve $7.94.
  • Gemini thought tokens: +$30.00. At the model’s default thinking level the classifier spends around 1,600 tokens thinking before each 35-token label.
  • Compaction passes: +$5.55. 16 compaction passes across the four sessions, each reading the whole window.
  • Invoice total: $47.89, or 3.9x the dashboard.

Neither adder is a bug in the vendor’s response. Both are reported correctly, just not where the logger looked.

Figure 2. The logger reads top-level fields on both LLM tasks. Thought tokens and compaction iterations sit elsewhere in the response.

Leak 1: reasoning tokens that live outside the output field

All three major vendors bill reasoning at the output rate, but they count it in different places:

  • Anthropic: output_tokens already includes thinking. It is the inclusive total used for billing.
  • OpenAI: reasoning appears in output_tokens_details.reasoning_tokens, and it is already inside output_tokens.
  • Google: total_output_tokens in the Interactions API (candidatesTokenCount in generateContent) is only the visible answer. Thoughts are reported separately in total_thought_tokens (thoughtsTokenCount), and Google’s pricing page says response pricing is the sum of output and thinking tokens.

So a cost function written against an OpenAI or Anthropic response, then reused for Gemini, silently drops the thinking. On a classification task that is most of the output bill: 35 visible tokens against 1,600 thought tokens per call in this scenario. The reverse mistake also exists. If you add reasoning_tokens on top of output_tokens for OpenAI or Anthropic, you double-count.

Why it hides so well in pipelines

Reasoning is on by default on most current models, and the defaults are not the cheap end of the dial. Classification and extraction tasks, the bread and butter of enrichment DAGs, rarely need long reasoning, but nobody turns it down because nobody sees it. Output is also the expensive side of the rate card: on both models here it costs five times the input rate.

Leak 2: the compaction pass you never see

Compaction is Anthropic’s answer to sessions that outgrow the context window. When input crosses a trigger (150,000 tokens by default, minimum 50,000), the API runs an extra sampling pass that summarizes the conversation into a compaction block, then drops everything before that block on the next request.

That extra pass reads your entire window and writes the summary, and it is billed like any other call. The catch is in the accounting. Anthropic’s docs state it plainly: the top-level input_tokens and output_tokens do not include compaction iteration usage. To get the billed total you have to sum every entry in usage.iterations.

{
  "usage": {
    "input_tokens": 23000,
    "output_tokens": 1000,
    "iterations": [
      { "type": "compaction", "input_tokens": 180000, "output_tokens": 3500 },
      { "type": "message",    "input_tokens": 23000,  "output_tokens": 1000 }
    ]
  }
}

That is the example from Anthropic’s own documentation. Priced at Sonnet 5 rates, the top level says $0.056. The request actually cost $0.451.

Figure 3. Anthropic’s documented compaction example. A logger reading top-level fields sees 12.4% of the cost.

For a data engineer, the closest analogy is a query profile that looks clean while the warehouse metering history keeps burning credits for work the profile does not show. Worse, the turn where compaction fires looks cheaper than the turns around it, because the top-level counts reflect the newly shortened context. Your dashboard shows cost dropping at the exact moment it spikes.

What to log per Airflow task

The fix is to normalize usage at the point of capture and to keep raw token classes, not just a dollar figure. Then a rate change or a newly discovered field means a re-query, not a backfill.

The cost table

CREATE TABLE llm_usage (
    dag_id            text        NOT NULL,
    run_id            text        NOT NULL,
    task_id           text        NOT NULL,
    map_index         integer     NOT NULL DEFAULT -1,
    called_at         timestamptz NOT NULL DEFAULT now(),
    vendor            text        NOT NULL,
    model_served      text        NOT NULL,  -- from the response, not the request
    uncached_in       bigint      NOT NULL,
    cache_read        bigint      NOT NULL,
    cache_write       bigint      NOT NULL,
    output_tokens     bigint      NOT NULL,  -- always INCLUDES reasoning
reasoning_tokens  bigint      NOT NULL,  -- observability only
    compaction_passes smallint    NOT NULL DEFAULT 0,
    est_cost_usd      numeric(12,6) NOT NULL
);

The capture helper

This runs inside the task, right after each LLM call, so map_index ties every row back to the mapped task instance that produced it.

from airflow.decorators import task
from airflow.operators.python import get_current_context
from airflow.providers.postgres.hooks.postgres import PostgresHook

RATES = {  # $ per 1M tokens, list price; re-check against the vendor page
    "gemini-3.8-flash": {"in": 0.75, "read": 0.075, "write": 0.0, "out": 3.75},
    "claude-sonnet-5":  {"in": 2.00, "read": 0.20,  "write": 2.50, "out": 10.00},
}


def normalize(vendor: str, resp: dict) -> dict:
    u = resp["usage"]
    if vendor == "google":                       # Interactions API field names
        thoughts = u.get("total_thought_tokens", 0)
        inp, read = u.get("total_input_tokens", 0), u.get("total_cached_tokens", 0)
        return dict(uncached_in=inp - read, cache_read=read, cache_write=0,
                    output_tokens=u.get("total_output_tokens", 0) + thoughts,
                    reasoning_tokens=thoughts, compaction_passes=0)
    if vendor == "anthropic":
        rows = u.get("iterations") or [u]        # compaction lives here
        return dict(
            uncached_in=sum(r.get("input_tokens", 0) for r in rows),
            cache_read=sum(r.get("cache_read_input_tokens", 0) for r in rows),
            cache_write=sum(r.get("cache_creation_input_tokens", 0) for r in rows),
            output_tokens=sum(r.get("output_tokens", 0) for r in rows),  # incl. thinking
            reasoning_tokens=0,
            compaction_passes=sum(1 for r in rows if r.get("type") == "compaction"))
    raise ValueError(f"no normalizer for {vendor}")


def record_usage(vendor: str, resp: dict) -> None:
    ctx = get_current_context()
    ti = ctx["ti"]
    n = normalize(vendor, resp)
    r = RATES[resp["model"]]
    cost = (n["uncached_in"] * r["in"] + n["cache_read"] * r["read"]
            + n["cache_write"] * r["write"] + n["output_tokens"] * r["out"]) / 1e6
    PostgresHook(postgres_conn_id="llm_costs").run(
        """INSERT INTO llm_usage (dag_id, run_id, task_id, map_index, vendor,
               model_served, uncached_in, cache_read, cache_write, output_tokens,
               reasoning_tokens, compaction_passes, est_cost_usd)
           VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)""",
        parameters=(ti.dag_id, ctx["run_id"], ti.task_id, ti.map_index, vendor,
                    resp["model"], n["uncached_in"], n["cache_read"],
                    n["cache_write"], n["output_tokens"], n["reasoning_tokens"],
                    n["compaction_passes"], cost))


@task
def classify_row(row: dict) -> dict:
    resp = call_gemini(row)          # your client wrapper; returns the raw response dict
    record_usage("google", resp)
    return parse_label(resp)

On Airflow 3 the decorator and context helpers come from airflow.sdk instead; the logic is identical. Two details matter. The Anthropic branch sums iterations when it exists and falls back to the top level when it doesn’t, so it is correct with or without compaction. And RATES is keyed on the model the response reports, not the one you configured, because they are not always the same.

A per-run view for the morning check

SELECT dag_id, run_id, task_id,
       count(*)                                        AS calls,
       sum(est_cost_usd)                               AS est_cost,
       sum(reasoning_tokens)::float / nullif(sum(output_tokens), 0) AS reasoning_share,
       sum(compaction_passes)                          AS compactions
FROM llm_usage
WHERE called_at >= now() - interval '1 day'
GROUP BY 1, 2, 3
ORDER BY est_cost DESC;

reasoning_share near 1.0 on a classification task is your first red flag. A non-zero compactions count on a task that was never meant to run long sessions is the second.

Before and after: same models, smaller bill

Once both leaks were visible, two changes cut the bill without switching models.

Fix 1: turn the thinking dial down on tasks that don’t need it

Every major vendor exposes a reasoning control: reasoning_effort on OpenAI, effort on Anthropic, thinking_level on Gemini. On the Gemini 3.x line thinking cannot be switched fully off, but it can be lowered (on Gemini 3.5 Flash the floor is minimal). Setting it per task is a one-line change in the client call. Validate label quality on a sample before and after; more thinking does not reliably mean better labels on simple tasks, but your task is the one that matters.

Fix 2: keep state in a table, not in the context window

Instead of one 18-turn session per partition that keeps hitting the compaction trigger, split the work into short sessions of four batches each. The state the model needs from earlier batches (already-resolved entity IDs and canonical names) goes into a compact block built from a warehouse table at the start of each session. Each session stays below the trigger, so compaction never fires, and the state is exact rather than a lossy model-written summary. That last point matters as much as cost: compaction is a rewrite, and anything not in the summary is gone.

Figure 4. Same rows, same models. Illustrative scenario assuming thought tokens drop from 1,600 to 200 per classify call.

In this scenario the nightly run drops from $47.89 to $16.80, about 65% lower. The resolve task gets slightly more expensive per run ($7.94 to $8.65) because each new session writes its system block and state to the cache, but losing the compaction passes more than pays for it. The 200-token thinking figure is an assumption; measure your own counts with the view above before you promise anyone a number.

FAQ

When does compaction help in a pipeline?

When a task genuinely needs a long, continuous conversation and would otherwise hit the context limit, such as an agent working through a large, interdependent document set. It is a lump-sum cost that pays back over the turns that follow. A session that ends shortly after compaction fires paid to summarize history it then threw away.

When does it hurt?

Short sessions, where it is overhead. Tasks that need exact earlier tool output, because the summary replaces it. And custom summarization prompts: Anthropic’s instructions parameter replaces the default summarization prompt entirely rather than adding to it.

How do reasoning tokens show up per vendor?

Inside output_tokens at OpenAI and Anthropic (with a breakdown you must not add on top), outside the output field at Google (which you must add). All three bill them at the output rate.

What breaks naive dbt or Airflow cost models?

Pricing from request config instead of the response, reading only top-level usage, treating input_tokens as the same quantity across vendors (Anthropic’s excludes cached tokens; OpenAI’s and Google’s include them), and storing a dollar figure without the token classes behind it.

When not to do this

  • Short interactive jobs that never approach the compaction trigger do not need the iterations logic, though it costs nothing to keep.
  • Tasks with already-cached, stable prefixes may not benefit from splitting sessions; each new session pays a cache write for its prefix, so check the trade-off on your volumes.
  • Tasks that need exact prior tool output should not rely on compaction at all. Use a state table or the vendor’s context-editing tools, which remove specific stale results instead of rewriting the conversation.

The general rule fits on one line: log token classes per call from the response, sum iterations when they exist, add thoughts only where the vendor counts them separately, and reconcile against the invoice before trusting the dashboard.