feat(server-utils): Add first-party Flue instrumentation - #24265
feat(server-utils): Add first-party Flue instrumentation#24265RulaKhaled wants to merge 2 commits into
Conversation
size-limit report 📦
|
Instruments the Flue agent framework (`@flue/runtime`) through the runtime's own
`instrument()` hook, producing the `invoke_agent` -> `chat` / `execute_tool`
hierarchy with token usage and Flue-computed cost.
Flue exposes no diagnostics channels; it takes an `{ observe, interceptor }`
registration. The interceptor owns the agent span and the active context, so
spans opened underneath parent correctly. `observe` owns the turn and tool spans,
because `turn_start`/`turn` are the only signal one-to-one with a model call and
`turn` carries usage.
Reaching the app's own `instrument()` is the awkward part: it closes over a
module-scope registry, so registering into a second evaluated copy fails
silently, and `createRequire` — how `mastraIntegration` finds the app's copy —
cannot resolve an ESM-only package with no `require` export condition. Each
injection path therefore supplies it differently, and neither records what the
other uses: under a bundler plugin the injected snippet passes the binding out
(new optional `bindings` on the channel-integration definitions), and under the
runtime hook the module is imported by the resolved URL the hook records, which
ESM guarantees resolves to the same instance.
Also skips the raw provider integrations while Flue is instrumented: Flue calls
the providers through `@earendil-works/pi-ai`, which bundles the `openai`,
`@anthropic-ai/sdk` and `@google/genai` clients, so those would emit a second
`gen_ai.chat` beside ours.
Cloudflare needs manual registration — agents run in per-Durable-Object isolates
that an integration registered off `Sentry.init()` never sees — so
`createFlueInstrumentation` is exported from `@sentry/cloudflare` and performs
the provider skip itself.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Flue exposes the content on its event stream — `turn_request` carries the full `ModelRequest` (system prompt, messages, tool definitions), the settled `turn` carries `response.output`, and the tool events carry arguments and results — so there is no reason to omit it. Recorded as `gen_ai.input.messages`, `gen_ai.output.messages`, `gen_ai.system_instructions`, `gen_ai.tool.definitions`, `gen_ai.tool.call.arguments` and `gen_ai.tool.call.result`, gated on `recordInputs`/`recordOutputs` via `resolveAIRecordingOptions`, which falls back to the client's `dataCollection.genAI` settings. `FlueOptions` is threaded back through `flueIntegration` and now does something. Note the request content is only on `turn_request`; the settled `turn` reports request metadata alone. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
9fb3fcd to
d62f4f2
Compare
isaacs
left a comment
There was a problem hiding this comment.
I think this is on a good path, but there are still some gaps. It surfaced an interesting shortcoming of @apm-js-collab/tracing-hooks that could save around some lines on this side. apm-js-collab/tracing-hooks#52
| // A submission's agent operation re-enters once, and the two carry different halves of the | ||
| // agent's identity: the outer context names the agent, the inner one names the conversation. | ||
| // Only the outer becomes a span, so the conversation id is lifted onto it from the re-entry. | ||
| if (agentDepth++ > 0) { |
There was a problem hiding this comment.
This approach is not parallel-safe.
agentDepth and agentSpan are single closure variables, and this treats any re-entry as a re-entry of the same submission. However, if an HTTP server or some other concurrency-heavy application had two parallel operations, those could clobber each other.
This can probably be fixed by using the operationId and submissionId to link the operations together. Keep agent spans in a Map keyed by operation.operationId, and resolve the parent in observe from observation.operationId. That also removes the depth counter and the re-entry special case entirely.
There was a problem hiding this comment.
Also, I'm not sure this is actually guaranteed to enter exactly twice? Looking at the flue code, the two dispatch sites I found are the coordinator and the session's runOperation (for operationKind of 'prompt' and 'skill').
runOperation is behind runExclusive, so it can't nest within one session. But subagent delegation runs in a separate session (DelegationDepthExceededError and defineSubagent are both exported), and a nested session's own runOperation('prompt') would be a third-level agent operation. Under the current code every subagent invocation is swallowed into the parent's single invoke_agent span.
I had the clanker clank up a test, written to packages/server-utils/test/ai/flue/nested-agent-operations.test.ts that seems to demonstrate this, if I'm understanding the behavior here properly: https://gist.github.com/isaacs/8f703ebae6adc26696b54c5d4f76b50e
| } | ||
| }, | ||
| ); | ||
| }, |
There was a problem hiding this comment.
FlueExecutionContext.traceCarrier is { traceparent, tracestate }, populated by extractTraceCarrier from the incoming request headers and passed on the outer agent operation.
But, the code here never reads it, so it seems like dispatched submissions will start orphan traces? For a durable or dispatched submission the coordinator runs the work later, possibly in another isolate, Durable Object, or process. Without traceCarrier, the invoke_agent span starts a brand new trace with no link to the request that enqueued it.
We could do this with a small helper, like:
function sentryTraceFromTraceparent(traceparent: string): string | undefined {
const [version, traceId, spanId, flags] = traceparent.split('-');
if (version !== '00' || !traceId || !spanId || !flags) {
return undefined;
}
return `${traceId}-${spanId}-${parseInt(flags, 16) & 0x01 ? '1' : '0'}`;
}(This could perhaps be reasonable to put in @sentry/core somewhere, near generateTraceparentHeader? I didn't see any w3c traceparent parser there already, and it's tiny, so we could also wait until there's a second use for it before abstracting.)
And then apply it only when nothing already continued the trace:
const sentryTrace = ctx.traceCarrier?.traceparent
? sentryTraceFromTraceparent(ctx.traceCarrier.traceparent)
: undefined;
return sentryTrace && !getActiveSpan()
? continueTrace({ sentryTrace, baggage: undefined }, openAgentSpan)
: openAgentSpan();| // reports as a turn, emitting a second `gen_ai.chat` beside ours. Done here rather than in | ||
| // `flueIntegration` so registering by hand — the only option on Cloudflare, where agents run in | ||
| // per-Durable-Object isolates — gets it too. | ||
| _INTERNAL_skipAiProviderWrapping(SKIPPED_PROVIDERS); |
There was a problem hiding this comment.
This calls _INTERNAL_skipAiProviderWrapping once, when createFlueInstrumentation is constructed. On Cloudflare the documented usage is a manual call in module or Durable Object scope, so it runs once per isolate.
But, packages/cloudflare/src/client.ts line 188 calls _INTERNAL_clearAiProviderSkips() in _setupIntegrations(), and its comment states that Cloudflare calls init() per request. So the skip registered at isolate load is wiped by the first init() and never re-registered. Every request after the first in that isolate would double report gen_ai.chat for any provider client that is channel-instrumented, which is what the skip is there to prevent.
I think the skip needs to be re-applied per client, not once per instrumentation object. Registering it from an integration setup(client) would do that.
Also, the skip is a side effect of building the object, but the object is only useful once instrument() accepts it.
packages/server-utils/src/integrations/flue.ts lines 59-67 catch any throw from instrument() and log it.
So on the failure path the SDK has suppressed the other AI instrumentations and installed nothing in its place: the user gets no gen_ai.chat spans at all, only a debug log. Reading Flue's instrument function shows it throws InstrumentationAlreadyInstalledError when the key is taken and isDevMode() is false, and can also rethrow from registerExecutionInterceptor.
Recommendation: Move the skip to after a successful instrument() call, or restore the previous state on failure.
| // the app's copy — the only copy whose module-scope state the running app reads. | ||
| const args = [ | ||
| JSON.stringify(moduleName), | ||
| ...(exportName ? [exportName] : []), |
There was a problem hiding this comment.
| ...(exportName ? [exportName] : []), | |
| (exportName ? exportName : undefined), |
If a binding has moduleBindings but no exportName, then we'd get something like orchestrionModuleInjected("x", { instrument }), and the bindings object lands in the integrationFn slot. packages/server-utils/src/utils/moduleInjected.ts line 44-46 would then store that object as a factory, and packages/cloudflare/src/baseSdk.ts line 41 would call it as a function and throw.
If we put an explicit undefined here, it'll guarantee it's always a consistent argument position.
(Another option would be to make this an options object or something. Passing undefined is a little bit gross, to be fair.)
| // (Flue's `instrument()`) rather than through channels at its call sites: that API closes over | ||
| // module-scope state, so it only works on the copy the app itself loaded. This covers the bundler | ||
| // path, where the module is inlined and no resolved file is recorded to import instead. | ||
| { exportName: 'flueIntegration', modules: ['@flue/runtime'], bindings: ['instrument'] }, |
There was a problem hiding this comment.
This sets both exportName and bindings for @flue/runtime. exportName is there so a bundler-only SDK can auto-install the subscriber: packages/cloudflare/src/baseSdk.ts line 38 and lines 150-155 read marker.integrations and call each factory, at init() and on orchestrion.module-injected.
Cloudflare would then instantiate and install flueIntegration on the live client, which contradicts the intention that Cloudflare needs manual registration because an integration registered off init() never sees the per-Durable-Object isolates.
For Flue, exportName looks unnecessary: Node registers the integration statically, and Cloudflare is meant to register by hand. Only bindings is needed.
We should check whether the Cloudflare Vite plugin transforms @flue/runtime at all, and if it does, drop the exportName for this entry.
(Note: if we do drop exportName here, then this walks right into the issue commented in packages/server-utils/src/orchestrion/bundler/moduleInjectedTransform.ts, which is otherwise only theoretical.)
| // per-Durable-Object isolates — gets it too. | ||
| _INTERNAL_skipAiProviderWrapping(SKIPPED_PROVIDERS); | ||
|
|
||
| const { recordInputs, recordOutputs } = resolveAIRecordingOptions(options); |
There was a problem hiding this comment.
Every other AI integration resolves these values at span time (see packages/server-utils/src/integrations/openai.ts line 82 and 124), because resolveAIRecordingOptions reads getClient()?.getDataCollectionOptions() (packages/server-utils/src/ai/core/utils.ts line 72).
On Cloudflare the client is replaced per request, so the values captured at isolate load are the wrong ones for every later request. On Node it happens to work because the client is stable. Resolving lazily would remove the divergence.
| } | ||
|
|
||
| const open = (): Span => | ||
| startInactiveSpan({ |
There was a problem hiding this comment.
startToolSpan uses startInactiveSpan and parents off the agent span. Anything the tool does (database query, HTTP call, a nested call etc), then lands under invoke_agent as a sibling of execute_tool rather than inside it.
The interceptor already receives type: 'tool' with toolCallId and toolName, and type: 'model' with turnId. Wrapping next() in withActiveSpan(existingSpan, next) for those operation types would fix the nesting without creating extra spans, and would reuse the span the observe path already opened.
The comment at packages/server-utils/src/ai/flue/index.ts lines 173-174 says the
active span during observe "is whatever the provider SDK last opened". With the providers skipped, that is worth re-checking; if it no longer holds, the whole agentSpan plumbing could be replaced by the current active span.
| return; | ||
| } | ||
|
|
||
| import(url).then( |
There was a problem hiding this comment.
We usually try to avoid computed dynamic imports, but like you said, the ESM registry is the only way in, so it's probably fine.
Two practical consequences though:
- It works in the CJS build only because rollup 4 defaults
output.dynamicImportInCjstotrue, so theimport()survives instead of being rewritten torequire(). That default is load-bearing and undocumented here.packages/server-utils/rollup.npm.config.mjsdoes not pin it. - Bundlers that statically analyze this file will emit a critical-dependency warning for the expression import, even though the bundler path never executes it (the binding is preferred above, on lines 34-38).
The moduleBindings mechanism already exists; consider recording the module URL for the runtime path through the same channel so this branch can go away.
The root cause is upstream: registerDiagnosticsChannelInjection passes no customTransforms (packages/server-runtime-injection/src/register.ts line 167), so registrationOnly cannot be used on the --import path. That is the layer where a fix would remove both the dynamic import and the init anchor.
| */ | ||
| export const flueConfig: InstrumentationConfig[] = [ | ||
| { | ||
| channelName: 'flueInit', |
There was a problem hiding this comment.
This doesn't need to be prefixed, since it's already going to be prefixed by orchestrion, as orchestrion:@flue/runtime:<value>.
| channelName: 'flueInit', | |
| channelName: 'init', |
| span.setAttribute(GEN_AI_RESPONSE_MODEL, responseModel); | ||
| } | ||
|
|
||
| const provider = observation.request?.providerId ?? observation.request?.providerName; |
There was a problem hiding this comment.
Both fields are required strings on ModelRequestInfo, so the fallback seems like it's not doing any work? I think just providerId is the correct value here.
Instruments the Flue agent framework (
@flue/runtime) through its owninstrument()hook. Enabled by default on Node, no app code required. Verified against a scaffoldedflue initapp driven over HTTP against a real provider, on both injection paths:Message content is gated on
recordInputs/recordOutputs, falling back todataCollection.genAI. Flue reaches providers throughpi-ai, which bundles theopenai/@anthropic-ai/sdk/@google/genaiclients, so those are skipped while Flue is instrumented — otherwise every call gets a secondgen_ai.chat.Root cause: Flue publishes no diagnostics channels, only an
{ observe, interceptor }registration. The interceptor owns the agent span and the active context;observeowns the turn and tool spans, sinceturn_start/turnare the only signal one-to-one with a model call. Getting at the app's owninstrument()needs both injection paths, because neither records what the other uses: the bundler snippet passes the binding out, while the runtime hook imports the module by its recorded URL.Cloudflare needs manual registration — agents run in per-Durable-Object isolates an integration registered off
Sentry.init()never sees — socreateFlueInstrumentationis exported from@sentry/cloudflareand skips providers itself.Tests stacked in #24266.
Known gaps: Cloudflare untested end to end; Flue's own Sentry blueprint targets
@sentry/node@^10.64.0and our docs point at it, so on v11 both would register and double-report (needs a docs update, same shape as the@mastra/sentrymigration).Fixes #24017
🤖 Generated with Claude Code