Agents ask the warehouse the same questions all day, in different words

Agent queries hide under one service account and miss the result cache. Tag them, fingerprint the history, promote the shapes that repeat, and budget the rest.

Agents Query tags Query history Fingerprinter Report Shared tables Registry Per-agent budget one role each agent, task, user strip literals repeat shapes promoted shapes points agents here ad hoc remainder
Tagged agent queries are fingerprinted into a shape report. Repeated shapes become shared tables behind the registry, and the ad hoc rest runs on a per-agent budget.
On this page
  1. Telling five agents apart in the query history
  2. Strip the literals and count what’s left
  3. Promoting a shape is a modeling call
  4. A daily budget for each agent role
  5. Small tables can skip the warehouse
  6. Cost per answered question

A warehouse’s result cache earns its keep on dashboards, which send the same SQL on every refresh. Agents rarely send the same SQL twice. Asked for open pipeline by owner at 9:00 and again at 9:15, an agent writes two statements that return the same rows and don’t match as text. The aliases are new, and the timestamp it pasted into the WHERE clause has moved on. The cache misses, so the warehouse scans the same tables again. Had the source table synced in between, identical text would have missed anyway.

Agents usually share one service account, too. The query history shows a single tireless user and can’t say which agent ran a query, or for whom. Until it can, there’s no telling which fix to try first.

I’ll carry one fictional company through the post: a SaaS business with five agents on its warehouse, whose agent spend rose 41% in two months, all of it under one login.

Telling five agents apart in the query history

Give each agent its own role, or its own service account where the warehouse attributes cost by user. That alone splits the bill, even for untagged queries, and gives permissions and limits somewhere to hang. A shared account saves an afternoon of setup and then hides everything after.

Then tag every query. Most warehouses let a session or job carry a tag or labels into the query history. I’d use a small JSON object, flattened into key-value labels where that’s all the warehouse takes:

{
  "v": 1,
  "agent": "pipeline_review",
  "agent_version": "2026.10.2",
  "task": "manager_pipeline_digest",
  "run_id": "r-7f3a91c2",
  "acting_for": "u-40417",
  "definition": "pipeline.open_by_owner@v3"
}

acting_for is an internal user id, not an email, because more people can read the query history than you’d guess. definition is null for ad hoc SQL and holds an id when the query came from the definitions registry. run_id adds up what one task cost.

Use the tag field, not a SQL comment. A run id in a comment makes every query’s text unique, so even true repeats miss the cache. Agents add comments of their own, which is why the fingerprint below strips -- comments.

With tags in place, the example company found its pipeline-review agent behind 62% of agent spend.

Strip the literals and count what’s left

Raw agent traffic looks endlessly varied. Normalized, much of it collapses into a few shapes, especially from scheduled agents. This fingerprint drops line comments, lowercases the text, swaps literals for ?, deletes whitespace and collapses IN lists. sample_query keeps a readable example of each shape:

-- agent_query_shapes.sql
-- Generic query-history columns: query_text, query_tag, role_name,
-- start_time, credits (or bytes_scanned times your price). Map them to
-- your warehouse's history view, and adjust the date math and the JSON
-- accessor to its dialect. regexp_replace replaces every match in most
-- warehouses; Postgres and DuckDB need 'g' as a fourth argument.
-- Block comments need one more regexp_replace.
WITH agent_queries AS (
  SELECT
    query_text,
    JSON_VALUE(query_tag, '$.agent')      AS agent,
    JSON_VALUE(query_tag, '$.acting_for') AS acting_for,
    credits
  FROM query_history
  WHERE lower(role_name) LIKE 'agent%'    -- one role per agent
    AND start_time >= CURRENT_DATE - INTERVAL '14' DAY
),
fingerprinted AS (
  SELECT
    agent,
    acting_for,
    credits,
    query_text,
    regexp_replace(                                      -- 5. collapse IN lists
      regexp_replace(                                    -- 4. delete whitespace
        regexp_replace(                                  -- 3. number literals
          regexp_replace(                                -- 2. string literals
            regexp_replace(lower(query_text),            -- 1. line comments
              '--[^\r\n]*', ''),
            '''[^'']*''', '?'),
          '[0-9]+([.][0-9]+)?', '?'),
        '[ \t\r\n]+', ''),
      'in[(][?,]+[)]', 'in(?)') AS fingerprint
  FROM agent_queries
),
shapes AS (
  SELECT
    fingerprint,
    min(query_text)                            AS sample_query,
    count(*)                                   AS runs,
    count(*) / 14.0                            AS runs_per_day,  -- 14-day window
    count(DISTINCT agent)                      AS agents,
    count(DISTINCT acting_for)                 AS acting_for_users,
    sum(credits)                               AS credits,
    sum(credits) * 1.0
      / NULLIF(sum(sum(credits)) OVER (), 0)   AS share_of_agent_spend
  FROM fingerprinted
  GROUP BY fingerprint
)
SELECT *
FROM shapes
WHERE runs_per_day >= 24                       -- at least hourly
  AND (agents > 1 OR acting_for_users > 1)     -- shared across agents or users
  AND share_of_agent_spend >= 0.01
ORDER BY credits DESC;

Fingerprints err in both directions. Different aliases, column order or join order split one question across several fingerprints, while date_trunc('day', ...) and date_trunc('month', ...) share one despite being different grains. Read the top 20 by hand before trusting the grouping.

The example pipeline agent produced a few dozen fingerprints. Side by side, they were six questions, asked every 15 minutes for each of 40 sales managers. That’s 240 freshly written queries every quarter hour.

Promoting a shape is a modeling call

Those 240 queries didn’t need 240 scans. One table grouped by owner holds every answer.

Building that table is a modeling decision, and a person has to make it. A cache can’t know that a pipeline review is fine at an hour old, or that Thursday’s forecast call needs fresher numbers. Whoever owns the meaning of pipeline sets the grain and how stale an answer may get.

So the example company built pipeline_by_owner_hourly and pointed the agent at it through the registry: the open-pipeline-by-owner definition now reads that table instead of raw opportunity facts. Nobody touched the prompt. Counting the hourly rebuilds, agent spend fell by a little over half.

A shared table also concentrates failure: one stalled rebuild makes every agent reading it wrong at once. So the definition lookup checks the table’s last refresh, and past max_staleness it falls back to the source query and pages the table’s owner. An hour of raw scans costs less than 40 managers acting on stale numbers. Answers carry the table’s as-of time either way.

A daily budget for each agent role

The ad hoc remainder gets a budget, with the soft and hard limits the post on LLM costs puts on model calls. The soft limit alerts the owner, and the hard limit stops that role’s queries for the day.

# agent-warehouse-budgets.yaml
# Invented company. Limits are warehouse credits per day.
version: 4

defaults:
  require_query_tag: true        # untagged agent queries are refused
  meter: running_total           # from finished queries; history views lag
  on_soft_limit: alert_owner
  on_hard_limit: refuse_queries
  resets_at: "00:00 UTC"
  raise_limit: owner_only

roles:
  agent_pipeline_review:
    owner: revops-data
    daily_credits: { soft: 30, hard: 45 }
  agent_finance_helper:
    owner: finance-systems
    daily_credits: { soft: 12, hard: 20 }
  agent_renewal_risk:
    owner: cs-ops
    daily_credits: { soft: 10, hard: 16 }
  agent_support_digest:
    owner: support-ops
    daily_credits: { soft: 6, hard: 10 }
  agent_account_research:
    owner: sales-ops
    daily_credits: { soft: 8, hard: 12 }

promoted_tables:
  pipeline_by_owner_hourly:
    source: crm.opportunities
    refresh_every: 1h
    max_staleness: 90m
    when_stale: use_source_query_and_page_owner
    serves: [pipeline.open_by_owner, pipeline.slipped_by_owner]
    stamp_answers_with: as_of

embedded_engine:
  max_table_size_gb: 2
  only_tables_without_row_policies: true
  stamp_answers_with: snapshot_commit_time

I’d enforce this in the SQL tool the agents call, from a running total of each finished query’s cost, estimated from runtime and cluster size where the warehouse doesn’t report it. History views can lag by an hour or more, and a meter that far behind stops nothing. Where the warehouse can cap spend itself, such as a monitor on one agent’s cluster, keep that as a backstop.

On day three, the example finance helper got back a total it couldn’t reconcile and kept rewriting the query. Every rewrite was a new fingerprint and a fresh scan, so a check for repeated queries saw nothing. The soft limit alerted its owner that afternoon. The hard limit stopped it that evening, instead of all night.

Someone waiting on that helper got “budget reached, ask the owner” instead of an answer, which is an easier conversation than the one about a runaway invoice. The owner can raise the limit for a day. The agent can’t.

Small tables can skip the warehouse

In the example, a third of the remaining queries touched only tables under 2 GB. Each was cheap, but on a warehouse billed while compute is awake, a steady trickle of them keeps it from ever suspending. Those moved to an embedded engine beside the agents, reading the open table files directly.

That route skips the warehouse’s row-level policies and masking, so I’d send only tables that have neither. It also hands the agents a storage credential, one more grant to audit.

Cost per answered question

With run_id in every tag, sum credits per run, join the agent’s run log, and divide by the runs that ended in an answer. Failed runs count in the cost but not in the answers, so a flailing agent pushes the number up. For the pipeline agent, that’s a cost per manager per day, which a sales leader can weigh against the time the digest saves.

Rerun the shape report monthly, too. A promoted table is one more pipeline to own, and its rebuilds run under a pipeline role, so they never show up in the agent numbers. Once its shape falls out of the top of the report, retire the table.