· 11 min read · 2060 words

Upgrading Deep Agents and LangGraph: The Silent Traps That Send Invoices

Framework upgrades rarely fail with an import error. Missing transitive model profiles triggered uncached 170k summarizations, FastMCP auto-negotiation added an HTTP 400 probe to every tool call, middleware hooks quietly turned 100 steps into 16 turns, and subagent tracing inflated tokens by 25%.

Part 3 of Deep Agents in Production.

Upgrading Deep Agents and LangGraph: The Silent Traps That Send Invoices

Framework upgrades rarely fail with an import error. In a production agent service, they fail politely: a default shifts, an exception loses its status code, a client begins probing a newer protocol, or a middleware hook silently eats your step budget. Unit tests pass. CI stays green. The code keeps answering users, and the bill or the p95 latency quietly climbs until somebody reads a cost report two weeks later.

Over the past year, our agent platform moved across LangChain 1.0 to 1.4, LangGraph 1.0 to 1.2, Deep Agents 0.4 to 0.7, and a major version jump in our outbound MCP client. Every single serious regression we hit during those upgrades was silent.

Here are the traps that actually bit us in production, why our existing unit tests missed every one of them, and the exact guards that finally caught them.


Trap 1: a missing transitive model profile tripled summarization cost share

In mid-October, we switched our main production model to a newer release in the same model family, one with a context window of roughly a million tokens. Two weeks later, a cost analyst noticed that cost per token had jumped by about a fifth.

When we pulled traces, the extra spend came from summarization calls that had barely existed before. They accounted for a tiny slice of total tokens, yet roughly three times that share of total dollars, because summarization calls do not hit the prompt cache and invalidate prefix reuse on the turn that follows.

The culprit sat inside Deep Agents' built-in summarization middleware. It computes its trigger from a static model-profile table shipped inside the model provider's LangChain package:

# Simplified from Deep Agents summarization defaults
def compute_summarization_defaults(model):
    if has_max_input_tokens(model.profile):
        return {"trigger": ("fraction", 0.85), "keep": ("fraction", 0.10)}
    # No profile row found: conservative fixed fallback
    return {"trigger": ("tokens", 170_000), "keep": ("messages", 6)}

Our lock file held an older version of the transitive provider package that had no rows for the new model IDs. So a million-token model silently fell back to summarizing at 170,000 tokens. Once a long thread crossed 170k, it summarized on almost every turn.

Two details camouflaged the bug for three weeks: on our older 200,000-token models, 85% of the window was also 170,000 tokens, so the fallback looked completely normal; and because the provider package was only a transitive dependency of Deep Agents, its profile table only moved whenever someone happened to refresh the lock file.

We compared pinning the transitive package directly, registering context windows ourselves, and upgrading Deep Agents to pull in the newer provider package. We chose the parent upgrade (the thin-harness answer from Part 1). In a live nine-turn test, summarization calls dropped from six to zero and total conversation cost fell to about a third.

Frameworks derive expensive defaults from lookup tables and fall back silently when a new model ID is missing; test the derived trigger, not just the config string.

Our CI guard now runs every configured model through the real model factory and asserts both that max_input_tokens is an integer and that compute_summarization_defaults(model)["trigger"] == ("fraction", 0.85). Adding a model without a profile now breaks the build before it ever touches a bill.


Trap 2: the MCP swap that passed 100 contract tests and still slowed production

In November, we migrated our outbound MCP client from a standalone adapter to LangChain's built-in MCP support running on FastMCP 4, looking ahead to the stateless MCP spec. We treated this carefully: over a hundred contract tests against a real in-process MCP server covering discovery, naming, per-call identity, tenancy, and failure isolation. Every test passed.

Two silent regressions still got through in the first week.

First, HTTP errors lost their status codes. The new transport turned any HTTP 4xx or 5xx into a bare protocol exception, stripping the status code and rate-limit headers. A rate-limited tool call stopped telling the model to back off; our error middleware told it to check its input and retry immediately into an exhausted window. Our unit tests had missed it because they raised hand-crafted exceptions shaped like the old library.

We fixed it by recording failed HTTP responses per call in a ContextVar and re-raising an HTTPStatusError, and added a hard testing rule to the repo: a fake may only model shapes the real dependency is proven to emit, and every fake becomes suspect the moment its dependency upgrades.

Second, a default discovery probe added a failed HTTP 400 to every tool call. FastMCP 4 opens sessions in "auto" mode, sending a discovery probe for the newest MCP spec before falling back to the classic handshake. Our older MCP servers answered the probe with HTTP 400, the client fell back cleanly, and every single tool call succeeded.

The catch was that our agent opened a fresh MCP session for each sequential tool call, so every call paid the extra round trip, and through an API gateway that probe cost over five times what it cost on a direct hop. Worse, our new error recorder captured the probe's 400 and later misreported real timeouts as HTTP 400, switching off retries.

Pre-merge smoke evals passed because they only gated on answer quality. What caught it before production was reviewing the nightly release-candidate evals against the previous release: three agents were 13% to 20% slower per test case while model time stayed flat, and trace spans per MCP tool call had roughly doubled. One line fixed it less than ninety minutes into triage:

# Simplified from the harness MCP client
# Older servers answer the "auto" discovery probe with HTTP 400 on every session.
return Client(transport, timeout=spec.timeout, mode="legacy")

Two silent Deep Agents upgrade regressions: missing transitive model profile triggering uncached 170k summarization, and FastMCP auto-mode probing older MCP servers with HTTP 400 per tool call.

Left: a missing row in a transitive dependency quietly moved a 1M-token model back to a 170k uncached summarization loop. Right: a helpful protocol auto-negotiation default silently added an HTTP 400 round trip to every sequential tool call.


Trap 3: major-release churn, monkey patches, and resolver overrides

Three smaller upgrade hazards belong on the same checklist because they all come from leaning hard on fast-moving agent frameworks:

  • Opt-in planning and colliding tool names. Moving Deep Agents from 0.6 to 0.7 made the to-do planning middleware opt-in (without adding it explicitly, the planning tool and todos state key vanished) and introduced a new built-in tool named delete. Because our MCP client strips server prefixes from tool names and LangGraph's tool node keeps only one entry per name, any MCP tool named delete would silently overwrite the built-in. We now enforce an explicit _RESERVED_TOOL_NAMES set (delete, edit_file, execute, glob, grep, ls, read_file, write_file).
  • Patching framework internals requires patching three layers. Deep Agents ships a 100-line default on read_file to protect context windows, which made our agents loop repeatedly when reading longer SKILL.md files. Bumping the module constant alone did nothing: Pydantic had already built the tool schema, and the model copied "100 lines" from the tool description. The workaround patches the constant, rebuilds the Pydantic schema with model_rebuild(force=True), and appends an override note to the tool description. It works, and it is pure technical debt that any patch release can quietly break.
  • Global dependency overrides linger like landmines. A uv override added months earlier to force a newer OpenTelemetry version for a dev tool later pinned OpenTelemetry below what a major tracing-SDK upgrade required, crashing every LangChain callback handler at construction. Every override is a global policy decision; if it does not carry a comment naming the exact package it serves, nobody knows when it is safe to delete.

Even model swaps without a single package bump can break silently: one newer small model rejected any temperature argument (breaking conversation title generation on dev for two weeks), while a newer reasoning model emitted empty thinking text unless summarized display was explicitly requested, leaving the web UI blank on reasoning streams.


Trap 4: middleware hooks, super-steps, and double-traced subagents

Even when versions stay frozen, LangChain middleware, LangGraph interrupts, and Deep Agents subagents compose in ways you only discover by reading traces.

1. recursion_limit counts super-steps, not model turns. First, we hit a classic wiring bug where the streaming path failed to pass our configured limit of 150, falling back to LangGraph's default of 25. Then we learned the deeper rule: LangChain's agent factory compiles every before_model and after_model middleware hook into its own graph node, and every node costs a super-step. On a worker stack with two hooks on each side, one model turn cost six super-steps, so recursion_limit=100 bought 16 turns, not 100. Adding one middleware hook silently shrank every agent's turn budget. Stop blindly raising limits; size budgets in turns and derive super-steps in a test.

2. Config scalars are last-wins, while callbacks propagate and accumulate. When a parent agent runs a compiled Deep Agents subagent, the parent's tracing callback handler propagates down into the child. Because our graph builder also bound a fresh tracing handler onto every compiled graph, every subagent LLM call got logged twice, inflating reported agent tokens in CI evals by roughly 25%.

The fix sits in _build_runtime_config: skip binding a child tracing handler when self._is_subagent is true, while keeping the child's own recursion_limit (which wins the per-key scalar merge):

# Simplified from the agent base class
def _build_runtime_config(self) -> dict[str, Any]:
    config: dict[str, Any] = {"recursion_limit": settings.AGENT_RECURSION_LIMIT}
    if not self._is_subagent:
        # Subagents already inherit the parent's tracing handler via config propagation.
        config["callbacks"] = [build_callback_handler()]
    return config

Two composition bugs found only in traces: middleware hooks multiplying one turn into six super-steps, and parent-plus-child tracing handlers double-counting every subagent LLM call.

Left: four middleware hooks turn one model turn into six super-steps, cutting a 100-step budget down to 16 turns. Right: inherited plus bound tracing handlers record every subagent call twice.

3. Four more subtle composition traps to check in your own stack:

  • A rejected approval is a ToolMessage with status="error". A gate we were prototyping checked only whether a tool message existed for a pending call ID, which would have treated a user rejection as approval. Check status explicitly, or own approval state in graph edges.
  • Tool return shapes depend on how you invoke them. Calling tool.ainvoke(args_dict) directly from a workflow node returns raw content; calling it with a full tool_call dict (name, args, id, type) returns a ToolMessage. Our streaming adapter only emitted UI progress events for ToolMessage or Command, so direct dict calls silently dropped every update and forced the web app into polling 450 times across a 15-minute run. And remember: a tool error comes back as a ToolMessage value with status="error", not a Python exception.
  • Summarization thresholds are frozen at build time. Deep Agents computes its summarization threshold once against the agent's base model. When per-call model routing swapped in a smaller-window model mid-thread, summarization never fired and the conversation slammed into the smaller model's token limit. If you route models per call, you have to size context management per call too (and expect prompt-cache hits to suffer).
  • Built-in filesystem tools and the general-purpose subagent arrive automatically. Deep Agents appends ls, glob, grep, and read_file after harness filters, and wires in a default general-purpose subagent. An orchestrator with an empty virtual filesystem burned turns browsing it, and when we hid those tools, it delegated the browsing to the built-in general-purpose subagent instead. Decide explicitly per agent which built-in tools and named subagents it is allowed to reach.

What I am still going back and forth on

Every time I look at our upgrade checklist, I notice an awkward truth: the most expensive regression in this entire list (the 170k summarization fallback) was caught by a human reading a weekly cost report, not by CI, not by contract tests, and not by our correctness evals. We have since added the model-profile guard and nightly latency comparisons, yet we still bundle framework refreshes into feature weeks more often than we should.

I also still go back and forth on how aggressively to patch upstream internals like read_file's 100-line limit or private exclusion classes. Waiting for an upstream PR can stall a product team for months, so pragmatic patches win every sprint. Yet every private import quietly turns a thin harness back into a brittle one the next time a minor version drops. The honest middle ground is probably ugly and simple: isolate every private import into one compatibility module, pin an upper bound on the framework whenever that module is non-empty, and treat deleting a line from it as real engineering work.


Treat framework upgrades as product releases

If you take one operational habit from this whole series, make it this: never let a framework upgrade merge on correctness unit tests alone.

Test derived framework values (summarization triggers, super-step budgets), replace hand-made mocks with real in-process servers and real framework objects, count trace spans per call so silent duplication cannot hide, and run your nightly eval suite with cost and latency side by side against the previous release.

Import errors are a gift. It is the upgrades that stay green that send the invoice.

Read the full series: Part 1: Keep the Harness Thin, Put the Product in Skills · Part 2: Orchestrator-Worker Pattern in Production · Part 3 (you are here).

Related writings