Blog

Why we measure cost per task in agent observability

30 November 2026Ankur Goyal10 min

How much does it cost an agent to answer a question about your traces?

We started asking this when we built Patterns. Historically, we’ve measured observability databases by how fast they return query results. With Patterns running investigations in the background, we wanted to know what it costs to get a correct answer and how much of the cost comes from the way the agent queries the data. If you’re running an agent every hour, a difference of $1 adds up to $8,760/year.

Take a question like, “how many conversations had a failed tool call?” If the database can count those conversations, a coding agent can get the answer in one query. If the MCP gives it access to individual spans, the agent may need to fetch several pages of tool calls, find the failures, and write code to count each conversation once. The answer is the same but the model spend depends on how much work the agent does to get there.

That’s why we believe cost per task should be the primary benchmark in agent observability. As teams use coding agents to investigate through MCP, they pay for that work every time an investigation runs. This is also why we’ve been focused on building our own database, Brainstore, to handle both the scale of agent data and agent queries.

SQL gives agents a faster, cheaper way to ask for the answer they need. Brainstore lets the database do the work of finding that answer, with support for filtering and aggregating whole traces. As agents investigate more data more often, we’ll continue optimizing Brainstore to handle that scale at a lower cost per task.

To see how much this matters, we gave Codex and Claude Code the same 20 questions and 4,000 traces. Then we measured what each agent spent and how many answers it got right through Braintrust, Datadog, Langfuse, and LangSmith MCPs.

The benchmark

Each of the 20 questions ran a new agent session against the 4,000 traces from τ²-bench. We calculated cost per correct answer by dividing the total estimated model spend across all 20 attempts by the number of correct answers.[1]

Cost/task benchmarking

20 analytical questions · 4,000 τ²-bench traces

Codex

GPT-6.2 Sol · xhigh · Code Mode

Braintrust20/20 correct
$0.12
LangSmith20/20 correct
+14%$0.13
Langfuse20/20 correct
+30%$0.15
Datadog20/20 correct
+80%$0.21

Claude Code

Opus 5.5 · xhigh · direct MCP

Braintrust20/20 correct
$0.78
LangSmith19/20 correct
+226%$2.53
Langfuse18/20 correct
+455%$4.32
Datadog18/20 correct
+796%$6.97

For Codex, accuracy was the same across all four MCPs but the difference in cost varied: $0.12 per correct answer through Braintrust compared with $0.13 to $0.21 through the other three. For Claude Code, both cost and accuracy varied by provider. The cost per correct answer through Braintrust was $0.78, $2.53 through LangSmith, $4.32 through Langfuse, and $6.97 through Datadog.

SQL lowers the cost of a trace investigation

One question in the benchmark asked the agent to find telecom conversations where a speed test returned “Speed test failed: No Connection.” It had to count those conversations and calculate how much the support agent spent across them.

The failure and the cost are recorded on different spans. The failed tool call contains the speed-test result, while the conversation’s root span contains its total cost. Filtering for failures alone drops the cost information. Joining each failure to its root can count the same cost several times when a conversation contains repeated failures.

Through Braintrust, the agent answered both parts in one SQL query.

sql
SELECT
  COUNT(DISTINCT root_span_id) AS traces,
  SUM(CASE WHEN is_root THEN metadata.agent_cost_usd ELSE 0 END) AS agent_cost,
  SUM(metrics.estimated_cost) AS est_cost,
  SUM(CASE WHEN is_root THEN 1 ELSE 0 END) AS roots,
  SUM(CASE WHEN is_root AND metadata.agent_cost_usd IS NOT NULL THEN 1 ELSE 0 END) AS roots_with_cost,
  MIN(created) AS mn,
  MAX(created) AS mx
FROM project_logs('007f92cb-1284-4c58-b139-ec1264b9fe39', shape => 'traces')
WHERE created >= '2026-11-27T07:01:51.513Z'
  AND created < '2026-11-27T15:25:10.972Z'
  AND metadata.domain = 'telecom'
  AND ANY_SPAN(
    span_attributes.name = 'run_speed_test'
    AND metadata.requestor = 'assistant'
    AND output.content = 'Speed test failed: No Connection.'
  )
LIMIT 10

ANY_SPAN(...) identifies conversations containing the failed speed test. With shape => 'traces', the query can still access every span in those conversations, including the root span that records the cost. It counts distinct conversations and sums costs only from root spans, so a conversation contributes its cost once even if several speed tests failed.

The full investigation took seven MCP calls and $0.079 in model spend. Through the other MCPs, the agent fetched matching spans, then wrote and ran code to combine the records and calculate the answer.

MCPModel spendMCP calls
Braintrust$0.0797
Langfuse$0.11365
LangSmith$0.11822
Datadog$0.13619

The difference in performance comes from what the agent can ask the database to do. Langfuse and other observability products are built on top of ClickHouse, a SQL database, so why don’t they support SQL?

Langfuse stores data in lower-level, multi-tenant tables and uses application logic to handle the nuances of ReplacingMergeTree, precompute expensive operations with materialized views, and implement security policies outside of the database. The main event schema stores metadata keys and values in separate arrays.

sql
-- Langfuse's 0039_create_events_full.up.sql
CREATE TABLE events_full (
  project_id String,
  trace_id String,
  span_id String,
  start_time DateTime64(6),
  ...
  cost_details Map(LowCardinality(String), Decimal(18,12)),
  metadata_names Array(String),
  metadata_values Array(String),
  event_ts DateTime64(6),
  is_deleted UInt8,
  ...
)
ENGINE = ReplacingMergeTree(event_ts, is_deleted)
PARTITION BY toYYYYMM(start_time)
PRIMARY KEY (project_id, toStartOfMinute(start_time), xxHash32(trace_id))
ORDER BY (project_id, toStartOfMinute(start_time), xxHash32(trace_id), span_id, start_time)

To process a SQL query like SELECT COUNT(*) FROM spans WHERE metadata.requestor = 'assistant', the application would need to translate it into one or more lower-level queries against the underlying ClickHouse tables.

The storage layout also affects how efficiently a database can answer questions about complete traces. Langfuse recently disabled creating new dashboards at the trace-level because reconstructing trace-level fields across spans is too slow at scale, and their scaling writeup describes why ClickHouse’s ORDER BY tradeoffs led them to drop traces as a first-class entity in favor of spans.

In Brainstore, each customer’s data is stored in physically separate, time-ordered partitions on object storage. A global trace ID index lets us ensure that new spans belonging to old traces, even days later, end up in the same partition. This lets agents use shape => 'traces' and ANY_SPAN(...) in a single SQL query.

What about Code Mode?

An obvious takeaway from the results is that Code Mode closes a lot of the gap between MCPs. By writing code, the model can string together multiple MCP calls, avoid viewing raw results in its context, and essentially build an “on the fly” SQL planner for executing complex requests.

In our benchmark, Codex used this approach to answer questions that required fetching and combining records across multiple MCP calls. As an example, here's what Codex wrote for Langfuse on the speed-test question. First, it split the time window into nine intervals and ran nine parallel cursor loops to pull all run_speed_test spans:

javascript
// Time-window setup and validation omitted.
const getPage = async (window) => {
  const results = [];
  let cursor;
  do {
    const r = await tools.mcp__observability__listObservations({
      ...window,
      name: "run_speed_test",
      limit: 50,
      fields: [
        "id",
        "traceId",
        "name",
        "type",
        "output",
        "metadata",
        "parentObservationId",
        "startTime",
      ],
      ...(cursor ? { cursor } : {}),
    });
    const { data, meta } = JSON.parse(r.content[0].text);
    results.push(...data);
    cursor = meta?.cursor;
  } while (cursor);
  return results;
};

const settled = await Promise.allSettled(intervals.map(getPage));
settled.forEach((res, i) => {
  if (res.status === "fulfilled") store("tests" + i, res.value);
});

Then, in the next cell, it filtered those spans in JavaScript and ran nine more parallel cursor loops to pull every telecom root span so it could join costs client-side:

javascript
const rows = Array.from({ length: 9 }, (_, i) => load("tests" + i)).flat();
const failed = rows.filter(
  (row) =>
    row.metadata.requestor === "assistant" &&
    JSON.parse(row.output).content === "Speed test failed: No Connection.",
);
const ids = [...new Set(failed.map((row) => row.traceId))];
store("matchedIds", ids);

// Inside getRoots, the cursor loop uses this request.
const r = await tools.mcp__observability__listObservations({
  ...window,
  name: "telecom-support-conversation",
  limit: 100,
  isRootObservation: true,
  fields: ["id", "traceId", "metadata", "startTime", "endTime"],
  ...(cursor ? { cursor } : {}),
});

// Run the nine root lookups in parallel.
const settled = await Promise.allSettled([
  ...intervals.map(getRoots),
  // One additional observation lookup omitted.
]);

Codex generated similar code for both LangSmith and Datadog.

However, as the dataset grows, this tactic becomes challenging to scale. We ran the same 20 questions on Braintrust and Langfuse with 100,000 traces:

TracesBraintrustLangfuseTotal spend savings
4,000$2.34 (20/20 · $0.117/pass)$3.04 (20/20 · $0.152/pass)23.0%
100,000$2.86 (20/20 · $0.143/pass)$4.04 (19/20 · $0.213/pass)29.2%

At 100,000 traces, Codex answered all 20 questions correctly through Braintrust and 19 of 20 through Langfuse.[2] With Langfuse, Codex had to write a much more complex program to fetch and combine traces. With Braintrust, it used SQL to have the database filter and aggregate the data. The gap in total spend widened from 23% to 29.2%. Langfuse averaged 616 MCP calls per question vs. 28 on Braintrust.

How we’re building for cost per task

Once we started benchmarking this way, we also changed how we build our own MCP. Some of the improvements came from watching what agents did before they even ran a query.

Put common guidance in the tool description

Codex often loaded the full SQL skill before running a basic query. We moved the tips it needed most into the tool descriptions (for example, for sql_query) and added a “before the skill is loaded” guideline for each skill. On basic SQL tasks, skill loads fell from 100% to 0%, median MCP calls fell from 4 to 2, and spend per correct answer dropped 52% from $0.1002 to $0.0481.

Support SQL agents already write

We had an MCP resource (docs://sql) that was 5,100 tokens of instructions on how to write SQL in Braintrust. We removed it, looked at the queries agents tried to write, and fixed the syntax that tripped them up. Today we trace our MCP and use Patterns to find recurring errors and fix them automatically.

Make whole traces easy to query

We natively support the shape keyword and ANY_SPAN(...) for trace-level queries. We have a couple of sentences in our MCP that describe these operators, and agents love to use them. We tested a version without ANY_SPAN and saw that median MCP calls on a cross-span keyword benchmark grew from 3 to 16 and mean spend grew from $0.026 to $0.11.

These improvements to the Braintrust MCP reduce the work agents do to reach a correct answer. Our recent work on Brainstore, including Nitro, makes the searches behind those investigations faster. We’ll continue improving both the MCP and Brainstore to handle more agent data while lowering the cost of each investigation.

  1. 1.
    Reproduce the benchmark with this repo.
  2. 2.
    The incorrect Langfuse answer was caused by a phrase-search bug involving curly quotes. We reported it in issue #21192.
Share

Trace everything