ai-persistence: usage is never persisted for router-owned subagent runs #2261
TanStack AI version#
1.8.0
Framework/Library version#
@tanstack/ai-persistence 1.1.0
Describe the bug and the steps to reproduce it#
Framework/Library version: framework-agnostic server usage (TanStack Start route, Bun 1.4.3)
Describe the bug and the steps to reproduce it
RunRecord.usage is never written for any run when a router owns the turn, i.e.
chat({ subagents: { agents, router }, middleware: [withPersistence(persistence)] }).
Both the parent run and the child (subagent) run records get status/finishedAt/error
updates, but usage always stays undefined — so an adapter's usageJson column stays NULL —
even though the model adapters report token usage.
Why:
In
packages/ai/src/activities/chat/index.ts, whensubagents.routeris set,runRoutedSubagents()replaces the parentrunChatEngine()entirely. Middleware hooks (onUsage,onFinish) are only invoked byTextEngine, sowithPersistence's usage path never runs for the parent turn.Child
chat()calls run with their own middleware viactx.forward; they carry no persistence middleware, so they don't record usage either.The only place the usage exists is the parent's terminal chunk:
withChildUsage()(packages/ai/src/activities/chat/agents/spawn.ts) attaches the children's usage to the parentRUN_FINISHED/RUN_ERRORas specusage[]plusmetadata.tanstack.usage.The records are settled by
RoutedSubagentPersistence(packages/ai-persistence/src/subagent-runs.ts) —start,suspend,finish,abort,startChild,writeSettled— and none of them ever passusagetoruns.createOrResume/runs.update.Repro (copy-paste runnable; on 1.8.0 + 1.1.0 the terminal chunk carries usage, the run record does not):
import { chat, defineAgent } from '@tanstack/ai'
import { fakeText } from '@tanstack/ai/testing'
import { memoryPersistence, withPersistence } from '@tanstack/ai-persistence'
const persistence = memoryPersistence()
const childAdapter = fakeText()
childAdapter.setResponses([{ text: 'child answer' }])
const child = defineAgent({
name: 'child',
description: 'Stub child that answers once.',
run: async (ctx) =>
chat({
adapter: childAdapter,
messages: [{ role: 'user', content: 'hello' }],
...ctx.forward,
}),
})
const parentAdapter = fakeText()
parentAdapter.setResponses([{ text: 'parent answer' }])
for await (const chunk of chat({
adapter: parentAdapter,
messages: [{ role: 'user', content: 'run something' }],
threadId: 't1',
runId: 'r1',
middleware: [withPersistence(persistence)],
subagents: { agents: [child], strategy: 'exclusive', router: () => 'child' },
})) {
if (chunk.type === 'RUN_FINISHED' || chunk.type === 'RUN_ERROR') {
console.log('terminal usage:', chunk.usage)
// [{ inputTokens: 3, outputTokens: 3, totalTokens: 6 }]
}
}
console.log(await persistence.stores.runs.get('r1'))
// { runId: 'r1', threadId: 't1', status: 'completed', startedAt: ..., finishedAt: ... }
// no `usage`
Expected: the parent RunRecord.usage equals the rebuilt terminal total (the value
withChildUsage already computed), and ideally each child record carries its own usage.
Suggested fix: pass usage through RoutedSubagentPersistence — e.g.
finish({ threadId, runId, usage }), suspend(...), abort(...). runRoutedSubagents
already has sink.total / sink.usage at every terminal, so it can pass the rebuilt
TokenUsage; subagent-runs.ts would include it in the runs.update it already performs.
Workaround we use: consume the terminal chunk and rebuild with the public
fromSpecTokenUsage(chunk.usage, chunk.metadata?.tanstack?.usage), then
stores.runs.update(runId, { usage }) before yielding the terminal.
Your Minimal, Reproducible Example - (Sandbox Highly Recommended)#
inline snippet above
Screenshots or Videos (Optional)#
No response
Do you intend to try to help solve this bug with your own PR?#
None
Terms & Code of Conduct#
- I agree to follow this project's Code of Conduct
- I understand that if my bug cannot be reliable reproduced in a debuggable environment, it will probably not be fixed and this issue may even be closed.
tanstack-source added labelsbug
pcbeingused33(GitHub profile, opens in a new tab) linked this to #2263
github-actions[bot](GitHub profile, opens in a new tab) assignedjherr
github-actions[bot](GitHub profile, opens in a new tab) added labelshas-pr
github-actions[bot](GitHub profile, opens in a new tab) added labelswaiting-on: maintainer
AlemTuzlak closed this
Sign in to join this conversation.