From 706dbf03fb1f5071fa6866434b48f55ef18ef1df Mon Sep 17 00:00:00 2001 From: punyamsingh Date: Tue, 24 Nov 2026 17:23:30 +0530 Subject: [PATCH] feat(observability): redact Langfuse input and output per trace through setLangfuseContext - setLangfuseContext({ redactIO: true }) and a call's context.redactIO mark the OTel context - any truthy redactIO redacts; an inner redactIO: false cannot undo an outer scope or the exporter - ExporterSpanProcessor stamps neurolink.langfuse.redact_io before the propagated attributes - protectAttributes drops input and output of marked spans, as the exporter-wide redactIO does - the marker is not sent to Langfuse; OTLP and registry exporters get it, getSpans() records do not - K21 covers trace and observation I/O, nesting, other sinks, per-call generate() and stream() - docs: "Redacting a call or scope" after masking; NEUROLINK_RECORD_INPUTS scope stated precisely - docs/api and the docs-site search index regenerated --- docs-site/static/search-index.json | 7 +- docs/api/classes/ExporterSpanProcessor.md | 2 +- docs/api/functions/setLangfuseContext.md | 2 +- .../api/type-aliases/NeurolinkTraceContext.md | 8 + docs/features/observability.md | 24 +- src/lib/constants/langfuse.ts | 3 + src/lib/constants/telemetry.ts | 3 + src/lib/neurolink.ts | 1 + .../observability/exporterSpanProcessor.ts | 14 +- src/lib/observability/langfuseMasking.ts | 7 +- .../ai/observability/instrumentation.ts | 10 +- src/lib/types/observability.ts | 2 + ...-suite-observability-exporter-redaction.ts | 251 ++++++++++++++++-- 13 files changed, 302 insertions(+), 32 deletions(-) diff --git a/docs-site/static/search-index.json b/docs-site/static/search-index.json index 53d847177b..f534eeb892 100644 --- a/docs-site/static/search-index.json +++ b/docs-site/static/search-index.json @@ -3519,13 +3519,14 @@ {"objectID":"c3139194cb90b179cd9656356b659b38ab57c2b36ff72a0ae85ba1d83fb78aee","title":"Setup","url":"/docs/features/observability#setup","content":"Setup","hierarchy":{"lvl0":"Features","lvl1":"Observability Guide","lvl2":"Setup","lvl3":""}}, {"objectID":"f5b277d3ae78e90affc7f614bbe8f4ea0e076874c57d77d204bd0764d0952622","title":"Environment variables","url":"/docs/features/observability#environment-variables","content":"| Variable | Purpose |\n| ------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| LANGFUSE_PUBLIC_KEY | Langfuse public key (required to auto-enable) |\n| LANGFUSE_SECRET_KEY | Langfuse secret key (required to auto-enable) |\n| LANGFUSE_BASE_URL | Langfuse host; defaults to Langfuse Cloud","hierarchy":{"lvl0":"Features","lvl1":"Observability Guide","lvl2":"Environment variables","lvl3":""}}, {"objectID":"304f3b3f1d3d11c91945e49e4ae3f60d2b9a826b87a3948f18fd137a16b38c45","title":"Disable or override","url":"/docs/features/observability#disable-or-override","content":"Every field is optional. publicKey, secretKey, baseUrl, environment and release fall back to the variables above; the others have the defaults below. The type is NeurolinkLangfuseConfig.\n\n| Field | Meaning |\n| --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |\n| enabled | false turns Langfuse off although keys are set (from untyped config, the strings \"false\", \"0\", \"off\" and \"no\" do too); any other value, or leaving it out, leaves it on.","hierarchy":{"lvl0":"Features","lvl1":"Observability Guide","lvl2":"Disable or override","lvl3":""}}, -{"objectID":"d5c2e109ca689299bbc1e1068341dfd6ba1294b1ee3c11cebe6489977865892e","title":"Per-call context","url":"/docs/features/observability#per-call-context","content":"Pass context on generate, stream and decide. The values are attached to every span the call creates, including tool calls and fallback attempts, so one call is one trace.\n\n| Field | Recorded as |\n| ----------------- | ----------------------------------------------------------------------------------------------------------------------------------------- |\n| userId | Trace user |\n| sessionId | Trace session |\n| tags | Trace tags |\n| traceName | Trace name |\n| conversationId | Metadata key conversationId |\n| requestId | Metadata key requestId |\n| metadata | Metadata; values up to 200 characters are on every observation, longer values and arrays are recorded in full on the trace only |\n| observationName | Name of the root observation of this call; default generate or stream; not propagated to child observations or used as the trace name |","hierarchy":{"lvl0":"Features","lvl1":"Observability Guide","lvl2":"Per-call context","lvl3":""}}, -{"objectID":"d262ba0787c1b57c76e303845fc9c6f447a3a2f747a880270f15c61fcc1863bb","title":"setLangfuseContext","url":"/docs/features/observability#setlangfusecontext","content":"Wrap your own code to attach the same attributes to everything inside it, including spans you create yourself.\n\nsetLangfuseContext(params: NeurolinkTraceContext, fn) returns whatever fn returns. It is a thin wrapper over Langfuse's propagateAttributes.","hierarchy":{"lvl0":"Features","lvl1":"Observability Guide","lvl2":"setLangfuseContext","lvl3":""}}, +{"objectID":"d5c2e109ca689299bbc1e1068341dfd6ba1294b1ee3c11cebe6489977865892e","title":"Per-call context","url":"/docs/features/observability#per-call-context","content":"Pass context on generate, stream and decide. The values are attached to every span the call creates, including tool calls and fallback attempts, so one call is one trace.\n\n| Field | Recorded as |\n| ----------------- | ----------------------------------------------------------------------------------------------------------------------------------------- |\n| userId | Trace user |\n| sessionId | Trace session |\n| tags | Trace tags |\n| traceName | Trace name |\n| conversationId | Metadata key conversationId |\n| requestId | Metadata key requestId |\n| metadata | Metadata; values up to 200 characters are on every observation, longer values and arrays are recorded in full on the trace only |\n| observationName | Name of the root observation of this call; default generate or stream; not propagated to child observations or used as the trace name |\n| redactIO | true leaves this call's input and output out of what is sent to Langfuse; see Redacting a call or scope |","hierarchy":{"lvl0":"Features","lvl1":"Observability Guide","lvl2":"Per-call context","lvl3":""}}, +{"objectID":"d262ba0787c1b57c76e303845fc9c6f447a3a2f747a880270f15c61fcc1863bb","title":"setLangfuseContext","url":"/docs/features/observability#setlangfusecontext","content":"Wrap your own code to attach the same attributes to everything inside it, including spans you create yourself.\n\nsetLangfuseContext(params: NeurolinkTraceContext, fn) returns whatever fn returns. It is a thin wrapper over Langfuse's propagateAttributes. It takes the fields in the table above except observationName, plus prompt.","hierarchy":{"lvl0":"Features","lvl1":"Observability Guide","lvl2":"setLangfuseContext","lvl3":""}}, {"objectID":"ebe52665a13e8e28856b65cd1d82bb2709538cb3fdd9b2ab6e54cd7061a8fb0d","title":"Langfuse prompts","url":"/docs/features/observability#langfuse-prompts","content":"getLangfusePrompt(name, options) fetches a text prompt from Langfuse Prompt Management with the keys and host tracing uses (observability.langfuse, then LANGFUSE_PUBLIC_KEY, LANGFUSE_SECRET_KEY, LANGFUSE_BASE_URL). Pass the result as prompt to setLangfuseContext and Langfuse links the generations inside to that prompt version.\n\n| Option | Default | Effect |\n| ------------ | ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| label | production | Deployment label to fetch |\n| fallback | required | Text returned when the prompt cannot be fetched as a text prompt |\n| cacheTtlMs | 60000 | How long a prompt is served from the cache before it is refreshed in the background; the call that fetches an entry sets it for every caller of that name and label |\n| timeoutMs | 2000 | How long one fetch waits for Langfuse |\n\nIt never throws. Prompts are cached per project, host, name and label, up to 500 entries (the least recently fetched is dropped first), and each call gets its own copy; concurrent callers share one request, and an expired entry is returned at once while it refreshes.","hierarchy":{"lvl0":"Features","lvl1":"Observability Guide","lvl2":"Langfuse prompts","lvl3":""}}, {"objectID":"542eff7388511fe18f61b3de966dff32a0a0ccfa5c95df170298790e0233739d","title":"Naming","url":"/docs/features/observability#naming","content":"The observations below (generate, stream, decide, attempts, steps and tools) carry no product name in their span names, attribute keys or metadata keys. Names never carry per-execution values: the model and provider are fields, the step number is metadata. The product name remains in the plain spans listed under Other spans and in the proxy root's neurolink.user_id, neurolink.session_id and neurolink.conversation_id attributes.\n\n| Observation | Name | Langfuse type | Parent |\n| -------------------------- | ------------------------------------- | ------------- | ---------------------- |\n| generate / stream call | generate / stream | agent | none (trace root) |\n| Fallback attempt | generate.attempt / stream.attempt | span | root |\n| Agent loop step | step (step_index metadata) | span | the attempt span |\n| One model request | generate / stream | generation | its step |\n| Tool execution | the tool's name, e.g. get_weather | tool | the step that ran it |\n| decide | decide | generation | caller or root |\n\nA model request is named after the API the caller used (NeuroLink.generate or provider.generate gives generate, NeuroLink.stream or provider.stream gives stream). Its model is the observation's model field (the model the provider reported, falling back to the requested one) and the provider id is the provider metadata key.\n\nThe trace name is context.traceName when given, otherwise the operation name (generate, stream). An outer setLangfuseContext takes precedence over per-call context for user, session and trace name.\n\nEmbeddings, transcribe, TTS and media tracing are not yet recorded. The root also sets trace-level input and output; a generate or stream nested inside another turn does not.","hierarchy":{"lvl0":"Features","lvl1":"Observability Guide","lvl2":"Naming","lvl3":""}}, {"objectID":"bec7707961c02d5123e4dceed9e13f5f5311e2f47783dd81fc290b467f50ff7a","title":"Other spans","url":"/docs/features/observability#other-spans","content":"Spans from the RAG, workflow, file, memory, context and evaluation code are exported as plain span records with their name, timing, status and their own attributes. They keep their neurolink.* names: neurolink.rag.search, neurolink.rag.rerank, neurolink.rag.chunk, neurolink.workflow.* (run, run.streaming, response.condition, judge.score, ensemble.execute, layers.execute), neurolink.file.process, neurolink.file.video.process, neurolink.context.compact, neurolink.memory.summarize and neurolink.evaluation.ragas.","hierarchy":{"lvl0":"Features","lvl1":"Observability Guide","lvl2":"Other spans","lvl3":""}}, {"objectID":"ceb0e84f71b6a9deb6a57e236efa009236e933eb892ad569d59e36ba873292f3","title":"Steps and chat format","url":"/docs/features/observability#steps-and-chat-format","content":"Each iteration of the agent loop gets one step span with its one-based index in the step_index metadata. It parents that iteration's generation and the tool observations the model requested in it, so a multi-tool turn reads as step 1 (call, tools), step 2 (call, tools), and so on.\n\nGeneration input is a chat message array with the system message first. Generation output is an assistant message array: content, plus reasoning and tool_calls ({ id, type: \"function\", function: { name, arguments } }) when present. Langfuse renders both as a conversation.\n\nGeneration details:\nUsage includes input, output, total, cache read, cache creation and reasoning tokens, whatever naming the provider uses.\nCost is computed from NeuroLink's pricing table and recorded as costDetails.total.\nModel parameters are temperature, max tokens, top-p and thinking level.\nTime to first token is recorded as the generation's completion start time for streams.\nLevel is WARNING for a length or content-filter finish, an aborted call, an early break out of a stream, or an empty output, and ERROR when the call throws.\nStreams end their spans when the stream finishes, is abandoned or is aborted.","hierarchy":{"lvl0":"Features","lvl1":"Observability Guide","lvl2":"Steps and chat format","lvl3":""}}, -{"objectID":"7dbc08e9d130f6a8e970396c854cb6afb0be27558cdbaa21122d1df517e4006a","title":"Masking sensitive data","url":"/docs/features/observability#masking-sensitive-data","content":"mask runs on the input, output and metadata sent to Langfuse. It receives { data } and returns the value to send.\n\nmask and redactIO act on what NeuroLink sends to Langfuse, and on nothing else. They cover the trace and observation input and output (langfuse.observation.input, langfuse.observation.output, langfuse.trace.input, langfuse.trace.output); redactIO: true leaves those out of the request, and mask rewrites them instead. mask also runs on trace and observation metadata, whether or not the metadata is an object. If it throws, the value is replaced by .\n\nEverything else goes to Langfuse as it was recorded: the status message, exception.message, error.message, a tool's tool.error.message and a provider retry's retry.error, tool-call attributes, the proxy.body attribute of proxy body events, event attributes, and the prompt and completion attributes another library's GenAI instrumentation writes on spans that are exported with NeuroLink's. The policy does not reach any other sink either: an exporter you register with registerExporter, the spans NeuroLink sends to OTEL_EXPORTER_OTLP_ENDPOINT, and getSpans() receive the values as they were recorded. If one of them must not see content, take it out where it is recorded (NEUROLINK_RECORD_INPUTS=false) or in that sink's own processing.\n\nNeuroLink adds no credential masking of its own to error text. A failed call's status message, error.message, tool.error.message, retry.error and exception text are recorded as the provider returned them, in every sink, as the released build did, so an error that echoes a key reaches the sinks with the key. Input, output and tool arguments and results keep the credential masking they always had. To keep a credential out of error text, filter it in a custom exporter or keep it out of the provider's error.","hierarchy":{"lvl0":"Features","lvl1":"Observability Guide","lvl2":"Masking sensitive data","lvl3":""}}, +{"objectID":"7dbc08e9d130f6a8e970396c854cb6afb0be27558cdbaa21122d1df517e4006a","title":"Masking sensitive data","url":"/docs/features/observability#masking-sensitive-data","content":"mask runs on the input, output and metadata sent to Langfuse. It receives { data } and returns the value to send.\n\nmask and redactIO act on what NeuroLink sends to Langfuse, and on nothing else. They cover the trace and observation input and output (langfuse.observation.input, langfuse.observation.output, langfuse.trace.input, langfuse.trace.output); redactIO: true leaves those out of the request, and mask rewrites them instead. mask also runs on trace and observation metadata, whether or not the metadata is an object. If it throws, the value is replaced by .\n\nEverything else goes to Langfuse as it was recorded: the status message, exception.message, error.message, a tool's tool.error.message and a provider retry's retry.error, tool-call attributes, the proxy.body attribute of proxy body events, event attributes, and the prompt and completion attributes another library's GenAI instrumentation writes on spans that are exported with NeuroLink's. The policy does not reach any other sink either: an exporter you register with registerExporter, the spans NeuroLink sends to OTEL_EXPORTER_OTLP_ENDPOINT, and getSpans() receive the values as they were recorded. If one of them must not see content, take it out in that sink's own processing. NEUROLINK_RECORD_INPUTS=false keeps the inputs NeuroLink records (prompts, messages, tool arguments) out of the spans Langfuse, registerExporter exporters and OTEL_EXPORTER_OTLP_ENDPOINT receive. It does not filter the prompt attributes another library's instrumentation writes, or the stream records getSpans() returns, which still carry the prompt; output and error text are recorded either way.\n\nNeuroLink adds no credential masking of its own to error text. A failed call's status message, error.message, tool.error.message, retry.error and exception text are recorded as the provider returned them, in every sink, as the released build did, so an error that echoes a key reaches the sinks with the key.","hierarchy":{"lvl0":"Features","lvl1":"Observability Guide","lvl2":"Masking sensitive data","lvl3":""}}, +{"objectID":"f53dc64dd277933d89cc2fb8a6430c75fc283d5299a132602a62927d54b9a523","title":"Redacting a call or scope","url":"/docs/features/observability#redacting-a-call-or-scope","content":"The exporter's redactIO applies to every trace. To leave input and output out of some calls only, such as those that carry end-user content, pass redactIO: true in a call's context, or wrap the code in setLangfuseContext:\n\nEvery observation started inside the call or scope, nested scopes included, is sent to Langfuse without input and output. Observations started outside it keep theirs, including spans that were already open when it began, such as a trace root your code created, so a context.redactIO on a nested generate covers that call only. It covers the same attributes as the exporter's redactIO, and redactIO: false cannot undo an enclosing scope's or the exporter's redactIO. The scope is applied by NeuroLink's span processor, so it works with the exporter pipeline (createExporterSpanProcessor) and not with a LangfuseSpanProcessor you add yourself.\n\nSpans started inside carry the attribute neurolink.langfuse.redact_io: true. The Langfuse request drops it along with the input and output; an exporter registered with registerExporter and the spans sent to OTEL_EXPORTER_OTLP_ENDPOINT receive it with the content as recorded, so a sink of your own can redact the same spans. The records getSpans() returns are built separately and do not carry it.","hierarchy":{"lvl0":"Features","lvl1":"Observability Guide","lvl2":"Redacting a call or scope","lvl3":""}}, {"objectID":"bc90fcd87977756303a1a998fc869c12bbd8ef1f1b88e4f17746e4bd4463d15f","title":"Langfuse exporter behaviour","url":"/docs/features/observability#langfuse-exporter-behaviour","content":"Endpoint. POST {baseUrl}/api/public/otel/v1/traces as OTLP/HTTP JSON. Requests are cut at 500 spans or 3.5 MB.\nObservation types. Agent, generation, tool, step, attempt and the other observation types reach Langfuse with their native type, model, parameters, usage, cost and first-token time.\nIdentity. User, session, trace name, tags and trace metadata are set on every observation, not only the root.\nEnvironment and release. The config field, then LANGFUSE_TRACING_ENVIRONMENT / LANGFUSE_RELEASE; they fill spans that do not carry them already. The OTLP resource's deployment.environment and service.version also read LANGFUSE_ENVIRONMENT, PUBLIC_APP_ENVIRONMENT and PUBLIC_APP_VERSION; Langfuse traces do not.\nBatching. Spans are sent when flushAt spans are queued, every flushInterval seconds, on flushOpenTelemetry() and on shutdown. exportMode: \"immediate\" sends each span as it ends.\nFailures. A request that fails with 429, 5xx or a network error is retried with exponential backoff, or after the Retry-After a 429 or 503 names, up to 60 seconds and never past a flush's budget. Other 4xx responses are not retried. Spans Langfuse reports as rejected (partialSuccess) are logged once as a warning and not re-sent; a success whose body is not an object, or whose rejected count is not a whole number between zero and the spans sent, counts as all delivered. At most 4 export requests are in flight at once. Spans that end meanwhile wait, up to 10,000 of them; when Langfuse stops answering, the oldest waiting spans are dropped, counted in failedSpans and in the errors of healthCheck(), and warned about once a minute. Spans that end during shutdown are sent within the flush budget or counted as dropped. A 401 or 403 is not retried; it is logged as an error (\"Langfuse credentials rejected\") with the spans dropped at most once a minute, once more when the credentials are accepted again, and for any remainder at shutdown, and a refused batch gets no Dropped N of M spans warning.","hierarchy":{"lvl0":"Features","lvl1":"Observability Guide","lvl2":"Langfuse exporter behaviour","lvl3":""}}, {"objectID":"07d102a2518a59d4afc8618d87ee066c3c7e36fefe22ee00772e172d8055a720","title":"Metrics","url":"/docs/features/observability#metrics","content":"NeuroLink also records OpenTelemetry metrics, on one meter named neurolink-ai. They are recorded only when OTEL_EXPORTER_OTLP_ENDPOINT is set, when NEUROLINK_TELEMETRY_ENABLED=true, or when a global MeterProvider is registered (your application's, or NeuroLink's own); a global TracerProvider alone, NeuroLink's included, does not turn them on. They are written to the global MeterProvider. NeuroLink registers one, exporting to $OTEL_EXPORTER_OTLP_ENDPOINT/v1/metrics every 15 seconds, only when it owns the tracer provider and the endpoint is set; beside a host provider they go to the MeterProvider your application registered, and nowhere when it registered none.\n\n| Metric | Kind | Labels | Recorded for |\n| ----------------------------------------- | ----------------------- | ---------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| ai_requests_total | counter | provider, model | each generate() that finishes in BaseProvider.finalizeNativeGenerate (the native generate path of providers such as Anthropic, SageMaker and the OpenAI Chat Completions family), and each proxied request whose usage the proxy captured |\n| ai_request_duration_ms | histogram,","hierarchy":{"lvl0":"Features","lvl1":"Observability Guide","lvl2":"Metrics","lvl3":""}}, {"objectID":"ba32010e859f5101a6247151e93a3db0fdaa79d0afe2d47c1492c74a0e04f5f5","title":"External OpenTelemetry provider","url":"/docs/features/observability#external-opentelemetry-provider","content":"If your application registers its own global TracerProvider before tracing starts, NeuroLink creates no provider. OTEL_EXPORTER_OTLP_ENDPOINT is then ignored: NeuroLink logs one warning and exports no traces or metrics to it, so add an OTLP exporter, or any other vendor's span processor, to your own providers. neurolink.getTelemetryStatus().openTelemetry then reports usingExternalProvider: true (its enabled stays whether tracing is initialized, as before), and neurolink telemetry status and neurolink observability status print the endpoint as ignored. NeuroLink's metrics are recorded on the MeterProvider your application registers. For Langfuse choose one of two recipes.\n\nThe host provider must register a context manager, which NodeTracerProvider.register() and NodeSDK do. Without one OpenTelemetry cannot carry context between calls, so setLangfuseContext user, session and metadata never reach NeuroLink's spans and child spans lose their parents; NeuroLink logs a warning when it finds none. Shutting the host provider down shuts the shared exporters down, as createExporterSpanProcessor() always did. If the host rebuilds its provider, pass createExporterSpanProcessor(undefined, { shutdownExporters: false }): that processor only flushes the exporters on shutdown, so a rebuilt provider that adds one again keeps exporting.\n\n(a) Exporter pipeline (recommended). Add createExporterSpanProcessor() to your provider and give NeuroLink the Langfuse keys, either through new NeuroLink({ observability: { langfuse } }) or the LANGFUSE_PUBLIC_KEY / LANGFUSE_SECRET_KEY environment variables. NeuroLink registers its LangfuseExporter on the shared exporter registry, which the processor reads, so mask, batching, chunking and retry from the section above all apply. Register the processor before the first NeuroLink call; spans that end before the exporter is registered are not exported.\n\n(b) LangfuseSpanProcessor.","hierarchy":{"lvl0":"Features","lvl1":"Observability Guide","lvl2":"External OpenTelemetry provider","lvl3":""}}, diff --git a/docs/api/classes/ExporterSpanProcessor.md b/docs/api/classes/ExporterSpanProcessor.md index 029811a275..b5f6f3b913 100644 --- a/docs/api/classes/ExporterSpanProcessor.md +++ b/docs/api/classes/ExporterSpanProcessor.md @@ -70,7 +70,7 @@ Nothing. #### Description -Copies the propagated Langfuse trace attributes (user, session, trace name, tags, metadata) from the parent context onto the new span and remembers it until it ends. +Copies the propagated Langfuse trace attributes (user, session, trace name, tags, metadata) from the parent context onto the new span, marks it for input and output redaction when a `setLangfuseContext` scope asked for `redactIO`, and remembers it until it ends. #### Implementation of diff --git a/docs/api/functions/setLangfuseContext.md b/docs/api/functions/setLangfuseContext.md index 5b0511edef..89877d4508 100644 --- a/docs/api/functions/setLangfuseContext.md +++ b/docs/api/functions/setLangfuseContext.md @@ -36,7 +36,7 @@ Whatever `fn` returns. ## Description -Runs `fn` with trace attributes propagated to every span it creates. `conversationId` and `requestId` become metadata; empty values are dropped. `prompt` adds the trace tag `prompt:@` (`@fallback` for a fallback, no suffix without a version) and `promptName`, `promptVersion` and `promptLabel` metadata, and links generations to the prompt version unless it is a fallback; it replaces an enclosing prompt's tag, metadata and link. Metadata values of up to 200 characters once stringified are on every observation; longer values and arrays are recorded in full on the trace only, written by the trace root. +Runs `fn` with trace attributes propagated to every span it creates. `conversationId` and `requestId` become metadata; empty values are dropped. `prompt` adds the trace tag `prompt:@` (`@fallback` for a fallback, no suffix without a version) and `promptName`, `promptVersion` and `promptLabel` metadata, and links generations to the prompt version unless it is a fallback; it replaces an enclosing prompt's tag, metadata and link. `redactIO: true` leaves input and output out of the Langfuse export for every observation started inside, nested scopes included; `false` cannot undo it. Metadata values of up to 200 characters once stringified are on every observation; longer values and arrays are recorded in full on the trace only, written by the trace root. ## Example diff --git a/docs/api/type-aliases/NeurolinkTraceContext.md b/docs/api/type-aliases/NeurolinkTraceContext.md index 348320ccb3..b4307b5a12 100644 --- a/docs/api/type-aliases/NeurolinkTraceContext.md +++ b/docs/api/type-aliases/NeurolinkTraceContext.md @@ -83,3 +83,11 @@ Name of the root observation of this `generate` or `stream` call; not propagated > `optional` **prompt?**: [`LangfusePromptRef`](LangfusePromptRef.md) Langfuse prompt the call ran with, such as a `getLangfusePrompt` result; recorded as a `prompt:` trace tag and `promptName`, `promptVersion` and `promptLabel` metadata, replacing an enclosing prompt's tag and metadata. + +--- + +### redactIO? + +> `optional` **redactIO?**: `boolean` + +`true` leaves input and output out of what is sent to Langfuse for every observation started in this scope, nested scopes included, as the exporter's `redactIO` does for all traces. `false` cannot undo an enclosing scope's or the exporter's `redactIO`. diff --git a/docs/features/observability.md b/docs/features/observability.md index 0d95cba2ec..83574952a1 100644 --- a/docs/features/observability.md +++ b/docs/features/observability.md @@ -127,6 +127,7 @@ await neurolink.generate({ | `requestId` | Metadata key `requestId` | | `metadata` | Metadata; values up to 200 characters are on every observation, longer values and arrays are recorded in full on the trace only | | `observationName` | Name of the root observation of this call; default `generate` or `stream`; not propagated to child observations or used as the trace name | +| `redactIO` | `true` leaves this call's input and output out of what is sent to Langfuse; see [Redacting a call or scope](#redacting-a-call-or-scope) | ### setLangfuseContext @@ -143,7 +144,7 @@ const result = await setLangfuseContext( ); ``` -`setLangfuseContext(params: NeurolinkTraceContext, fn)` returns whatever `fn` returns. It is a thin wrapper over Langfuse's `propagateAttributes`. +`setLangfuseContext(params: NeurolinkTraceContext, fn)` returns whatever `fn` returns. It is a thin wrapper over Langfuse's `propagateAttributes`. It takes the fields in the table above except `observationName`, plus `prompt`. ### Langfuse prompts @@ -239,10 +240,29 @@ const neurolink = new NeuroLink({ `mask` and `redactIO` act on what NeuroLink sends to Langfuse, and on nothing else. They cover the trace and observation input and output (`langfuse.observation.input`, `langfuse.observation.output`, `langfuse.trace.input`, `langfuse.trace.output`); `redactIO: true` leaves those out of the request, and `mask` rewrites them instead. `mask` also runs on trace and observation metadata, whether or not the metadata is an object. If it throws, the value is replaced by ``. -Everything else goes to Langfuse as it was recorded: the status message, `exception.message`, `error.message`, a tool's `tool.error.message` and a provider retry's `retry.error`, tool-call attributes, the `proxy.body` attribute of proxy body events, event attributes, and the prompt and completion attributes another library's GenAI instrumentation writes on spans that are exported with NeuroLink's. The policy does not reach any other sink either: an exporter you register with `registerExporter`, the spans NeuroLink sends to `OTEL_EXPORTER_OTLP_ENDPOINT`, and `getSpans()` receive the values as they were recorded. If one of them must not see content, take it out where it is recorded (`NEUROLINK_RECORD_INPUTS=false`) or in that sink's own processing. +Everything else goes to Langfuse as it was recorded: the status message, `exception.message`, `error.message`, a tool's `tool.error.message` and a provider retry's `retry.error`, tool-call attributes, the `proxy.body` attribute of proxy body events, event attributes, and the prompt and completion attributes another library's GenAI instrumentation writes on spans that are exported with NeuroLink's. The policy does not reach any other sink either: an exporter you register with `registerExporter`, the spans NeuroLink sends to `OTEL_EXPORTER_OTLP_ENDPOINT`, and `getSpans()` receive the values as they were recorded. If one of them must not see content, take it out in that sink's own processing. `NEUROLINK_RECORD_INPUTS=false` keeps the inputs NeuroLink records (prompts, messages, tool arguments) out of the spans Langfuse, `registerExporter` exporters and `OTEL_EXPORTER_OTLP_ENDPOINT` receive. It does not filter the prompt attributes another library's instrumentation writes, or the stream records `getSpans()` returns, which still carry the prompt; output and error text are recorded either way. NeuroLink adds no credential masking of its own to error text. A failed call's status message, `error.message`, `tool.error.message`, `retry.error` and exception text are recorded as the provider returned them, in every sink, as the released build did, so an error that echoes a key reaches the sinks with the key. Input, output and tool arguments and results keep the credential masking they always had. To keep a credential out of error text, filter it in a custom exporter or keep it out of the provider's error. +### Redacting a call or scope + +The exporter's `redactIO` applies to every trace. To leave input and output out of some calls only, such as those that carry end-user content, pass `redactIO: true` in a call's `context`, or wrap the code in `setLangfuseContext`: + +```typescript +await neurolink.generate({ + input: { text: shopperMessage }, + context: { redactIO: true }, +}); + +await setLangfuseContext({ traceName: "storefront-chat", redactIO: true }, () => + neurolink.generate({ input: { text: shopperMessage } }), +); +``` + +Every observation started inside the call or scope, nested scopes included, is sent to Langfuse without input and output. Observations started outside it keep theirs, including spans that were already open when it began, such as a trace root your code created, so a `context.redactIO` on a nested `generate` covers that call only. It covers the same attributes as the exporter's `redactIO`, and `redactIO: false` cannot undo an enclosing scope's or the exporter's `redactIO`. The scope is applied by NeuroLink's span processor, so it works with the exporter pipeline (`createExporterSpanProcessor`) and not with a `LangfuseSpanProcessor` you add yourself. + +Spans started inside carry the attribute `neurolink.langfuse.redact_io: true`. The Langfuse request drops it along with the input and output; an exporter registered with `registerExporter` and the spans sent to `OTEL_EXPORTER_OTLP_ENDPOINT` receive it with the content as recorded, so a sink of your own can redact the same spans. The records `getSpans()` returns are built separately and do not carry it. + ## Langfuse exporter behaviour - **Endpoint.** `POST {baseUrl}/api/public/otel/v1/traces` as OTLP/HTTP JSON. Requests are cut at 500 spans or 3.5 MB. diff --git a/src/lib/constants/langfuse.ts b/src/lib/constants/langfuse.ts index 4797253e70..700f05b509 100644 --- a/src/lib/constants/langfuse.ts +++ b/src/lib/constants/langfuse.ts @@ -69,6 +69,9 @@ export const CONTENT_KEYS = new Set([ "langfuse.trace.output", ]); +/** @description Span attribute marking a span started inside a `setLangfuseContext({ redactIO: true })` scope; the Langfuse exporter leaves its input and output out and does not send the marker. */ +export const REDACT_IO_ATTRIBUTE = "neurolink.langfuse.redact_io"; + /** @description Attribute prefixes whose values are metadata entries. */ export const METADATA_PREFIXES = [ "langfuse.observation.metadata.", diff --git a/src/lib/constants/telemetry.ts b/src/lib/constants/telemetry.ts index 53b6f80395..973bb523af 100644 --- a/src/lib/constants/telemetry.ts +++ b/src/lib/constants/telemetry.ts @@ -39,6 +39,9 @@ export const TRACE_METADATA_CONTEXT_KEY = "neurolink.trace.metadata"; /** @description Name of the OpenTelemetry context key that carries the trace tag of the prompt `setLangfuseContext` was last given. */ export const PROMPT_TAG_CONTEXT_KEY = "neurolink.trace.promptTag"; +/** @description Name of the OpenTelemetry context key set when an enclosing `setLangfuseContext` asked for `redactIO`. */ +export const REDACT_IO_CONTEXT_KEY = "neurolink.trace.redactIO"; + /** @description Log prefix for NeuroLink's OpenTelemetry setup. */ export const OTEL_LOG_PREFIX = "[OpenTelemetry]"; diff --git a/src/lib/neurolink.ts b/src/lib/neurolink.ts index 11711a25ce..b4a41a8500 100644 --- a/src/lib/neurolink.ts +++ b/src/lib/neurolink.ts @@ -1490,6 +1490,7 @@ export class NeuroLink { ? (ctx.metadata as Record) : undefined, ...(isPromptRef(ctx.prompt) && { prompt: ctx.prompt }), + ...(Boolean(ctx.redactIO) && { redactIO: true }), }, callback, ); diff --git a/src/lib/observability/exporterSpanProcessor.ts b/src/lib/observability/exporterSpanProcessor.ts index 7dee0a03a2..b907ffc4b5 100644 --- a/src/lib/observability/exporterSpanProcessor.ts +++ b/src/lib/observability/exporterSpanProcessor.ts @@ -1,14 +1,20 @@ import { getPropagatedAttributesFromContext } from "@langfuse/core"; -import { type Context, SpanStatusCode } from "@opentelemetry/api"; +import { + type Context, + createContextKey, + SpanStatusCode, +} from "@opentelemetry/api"; import type { ReadableSpan, Span, SpanProcessor as OtelSpanProcessor, } from "@opentelemetry/sdk-trace-base"; +import { REDACT_IO_ATTRIBUTE } from "../constants/langfuse.js"; import { INTERNAL_SPAN_ATTRIBUTE, MAX_REMEMBERED_SPANS, PROXY_TRACER_SCOPE, + REDACT_IO_CONTEXT_KEY, } from "../constants/telemetry.js"; import type { ExporterSpanProcessorOptions, @@ -24,6 +30,7 @@ import { getExporterRegistry } from "./exporterRegistry.js"; const LANGFUSE_OBSERVATION_TYPE = "langfuse.observation.type"; const GEN_AI_OBSERVATION_TYPE = "gen_ai.observation.type"; const GEN_AI_OPERATION = "gen_ai.operation.name"; +const REDACT_IO_KEY = createContextKey(REDACT_IO_CONTEXT_KEY); const OBSERVATION_SPAN_TYPES: Record = { agent: SpanType.AGENT_RUN, @@ -170,13 +177,16 @@ export class ExporterSpanProcessor implements OtelSpanProcessor { ) {} /** - * @description Copies the propagated Langfuse trace attributes (user, session, trace name, tags, metadata) from the parent context onto the new span and remembers it until it ends. + * @description Copies the propagated Langfuse trace attributes (user, session, trace name, tags, metadata) from the parent context onto the new span, marks it for input and output redaction when a `setLangfuseContext` scope asked for `redactIO`, and remembers it until it ends. * @param span {Span} - Span that just started. * @param parentContext {Context} - Context the span was started in. * @returns {void} Nothing. */ onStart(span: Span, parentContext: Context): void { try { + if (parentContext.getValue(REDACT_IO_KEY) === true) { + span.setAttribute(REDACT_IO_ATTRIBUTE, true); + } span.setAttributes(getPropagatedAttributesFromContext(parentContext)); this.open.set(span.spanContext().spanId, span); this.hold(parentIdOf(span)); diff --git a/src/lib/observability/langfuseMasking.ts b/src/lib/observability/langfuseMasking.ts index fcc9760c2c..91358dc5f5 100644 --- a/src/lib/observability/langfuseMasking.ts +++ b/src/lib/observability/langfuseMasking.ts @@ -2,6 +2,7 @@ import { CONTENT_KEYS, FULLY_MASKED, METADATA_PREFIXES, + REDACT_IO_ATTRIBUTE, } from "../constants/langfuse.js"; import type { JsonValue, @@ -32,7 +33,7 @@ function maskValue( } /** - * @description Applies the Langfuse exporter's policy to a span's attributes as they are sent to Langfuse: fills environment and release when the span has none, removes input and output when `redactIO` is set, and masks input, output and metadata when a mask is configured. Nothing else is touched: other attributes, events and the status message go to Langfuse as they are, and no other exporter sees the policy. + * @description Applies the Langfuse exporter's policy to a span's attributes as they are sent to Langfuse: fills environment and release when the span has none, removes input and output when `redactIO` is set or the span was started in a `setLangfuseContext({ redactIO: true })` scope, masks input, output and metadata when a mask is configured, and drops the `neurolink.langfuse.redact_io` marker. Nothing else is touched: other attributes, events and the status message go to Langfuse as they are, and no other exporter sees the policy. * @param attributes {SpanAttributes} - Attributes of the span being exported. * @param policy {LangfuseAttributePolicy} - Environment, release, redaction and mask settings. * @returns {SpanAttributes} A new attribute record; the input is not modified. @@ -46,9 +47,11 @@ export function protectAttributes( ...(policy.release && { "langfuse.release": policy.release }), ...attributes, }; + const redactIO = policy.redactIO || attributes[REDACT_IO_ATTRIBUTE] === true; + delete result[REDACT_IO_ATTRIBUTE]; for (const key of Object.keys(result)) { if (CONTENT_KEYS.has(key)) { - if (policy.redactIO) { + if (redactIO) { delete result[key]; } else if (policy.mask) { result[key] = maskValue(result[key], policy.mask); diff --git a/src/lib/services/server/ai/observability/instrumentation.ts b/src/lib/services/server/ai/observability/instrumentation.ts index 744bde3818..cd4033af5d 100644 --- a/src/lib/services/server/ai/observability/instrumentation.ts +++ b/src/lib/services/server/ai/observability/instrumentation.ts @@ -39,6 +39,7 @@ import { import { OTEL_LOG_PREFIX, PROMPT_TAG_CONTEXT_KEY, + REDACT_IO_CONTEXT_KEY, TRACE_METADATA_CONTEXT_KEY, } from "../../../../constants/telemetry.js"; import { getExporterRegistry } from "../../../../observability/exporterRegistry.js"; @@ -76,6 +77,7 @@ const MAX_PROPAGATED_CHARS = 200; const LANGFUSE_EXPORTER_NAME = "langfuse"; const TRACE_METADATA_KEY = createContextKey(TRACE_METADATA_CONTEXT_KEY); const PROMPT_TAG_KEY = createContextKey(PROMPT_TAG_CONTEXT_KEY); +const REDACT_IO_KEY = createContextKey(REDACT_IO_CONTEXT_KEY); const CONTEXT_PROBE_KEY = createContextKey("neurolink.context-manager-probe"); // `false`, `0`, `off` or `no` skips the flush at process exit; the released build had none. const EXIT_FLUSH_SWITCH = "NEUROLINK_TELEMETRY_EXIT_FLUSH"; @@ -629,7 +631,7 @@ const promptTagOf = ({ }; /** - * @description Runs `fn` with trace attributes propagated to every span it creates. `conversationId` and `requestId` become metadata; empty values are dropped. `prompt` adds the trace tag `prompt:@` (`@fallback` for a fallback, no suffix without a version) and `promptName`, `promptVersion` and `promptLabel` metadata, and links generations to the prompt version unless it is a fallback; it replaces an enclosing prompt's tag, metadata and link. Metadata values of up to 200 characters once stringified are on every observation; longer values and arrays are recorded in full on the trace only, written by the trace root. + * @description Runs `fn` with trace attributes propagated to every span it creates. `conversationId` and `requestId` become metadata; empty values are dropped. `prompt` adds the trace tag `prompt:@` (`@fallback` for a fallback, no suffix without a version) and `promptName`, `promptVersion` and `promptLabel` metadata, and links generations to the prompt version unless it is a fallback; it replaces an enclosing prompt's tag, metadata and link. `redactIO: true` leaves input and output out of the Langfuse export for every observation started inside, nested scopes included; `false` cannot undo it. Metadata values of up to 200 characters once stringified are on every observation; longer values and arrays are recorded in full on the trace only, written by the trace root. * @param params {NeurolinkTraceContext} - User, session, trace name, tags, metadata and prompt for the trace. * @param fn {() => T} - Work to run inside the propagated context. * @returns {T} Whatever `fn` returns. @@ -671,7 +673,11 @@ export function setLangfuseContext( ...traceMetadataFromContext(scoped), ...full, }); - return context.with(withMetadata, () => + // Only `true` is stored, so an inner `redactIO: false` never clears an outer scope's redaction + const scope = params.redactIO + ? withMetadata.setValue(REDACT_IO_KEY, true) + : withMetadata; + return context.with(scope, () => propagateAttributes( { userId: params.userId || undefined, diff --git a/src/lib/types/observability.ts b/src/lib/types/observability.ts index 0b9ed96f0c..f1bedb1a9f 100644 --- a/src/lib/types/observability.ts +++ b/src/lib/types/observability.ts @@ -127,6 +127,8 @@ export type NeurolinkTraceContext = { observationName?: string | null; /** Langfuse prompt the call ran with, such as a `getLangfusePrompt` result; recorded as a `prompt:` trace tag and `promptName`, `promptVersion` and `promptLabel` metadata, replacing an enclosing prompt's tag and metadata. */ prompt?: LangfusePromptRef; + /** `true` leaves input and output out of what is sent to Langfuse for every observation started in this scope, nested scopes included, as the exporter's `redactIO` does for all traces. `false` cannot undo an enclosing scope's or the exporter's `redactIO`. */ + redactIO?: boolean; }; /** diff --git a/test/continuous-test-suite-observability-exporter-redaction.ts b/test/continuous-test-suite-observability-exporter-redaction.ts index 17f0ef5666..c4d9f33992 100644 --- a/test/continuous-test-suite-observability-exporter-redaction.ts +++ b/test/continuous-test-suite-observability-exporter-redaction.ts @@ -8,8 +8,9 @@ * * K11 only observations reach Langfuse, from every tracer scope * K14 parent ids from OpenTelemetry SDK 1.x and 2.x spans - * K21 mask and redactIO act on what is sent to Langfuse, as in the - * released build, and on no other sink + * K21 mask and redactIO (exporter-wide, or per call or scope through + * context and setLangfuseContext) act on what is sent to Langfuse, as + * in the released build, and on no other sink * K25 resource, links and nanosecond times survive the wire; scope and kind * are the sdk and INTERNAL Langfuse has always received * K26 flush and shutdown have a deadline @@ -70,7 +71,12 @@ import { LangfuseExporter } from "../src/lib/observability/exporters/langfuseExp import { ensureTelemetry, flushOpenTelemetry, + setLangfuseContext, } from "../src/lib/services/server/ai/observability/instrumentation.js"; +import { + CONTENT_KEYS, + REDACT_IO_ATTRIBUTE, +} from "../src/lib/constants/langfuse.js"; import { redactSpanContent, spanContentAttribute, @@ -99,6 +105,9 @@ import { logger } from "../src/lib/utils/logger.js"; const SELF = fileURLToPath(import.meta.url); const MARKER = "PII-MARKER-4821"; +// Input and output only, so their absence from the Langfuse request proves redaction +const SCOPE_MARKER = "TRACE-REDACT-MARKER-5c2e"; +const NESTED_MARKER = "NESTED-REDACT-MARKER-9b1d"; const MASKED = ""; const CHILD_RESULT = "CHILD_RESULT "; @@ -458,20 +467,43 @@ async function runChild(scenario: string): Promise { getExporterRegistry().register(second); await second.initialize(); ensureTelemetry({ langfuse }); - const span = tracers.sdk.startSpan("scenario.generate"); - observe(span, "generation", { - input: `prompt ${MARKER}`, - output: `answer ${MARKER}`, - ...(scenario !== "redact" && { metadata: { note: `note ${MARKER}` } }), - }); - span.addEvent("proxy.upstream.response_body", { - "proxy.body": `body ${MARKER}`, - }); - span.setAttribute( - "gen_ai.response.tool_calls", - `[{"name":"lookup","arguments":"${MARKER}"}]`, - ); - span.end(); + const emit = (name: string, content: string): void => { + const span = tracers.sdk.startSpan(name); + observe(span, "generation", { + input: `prompt ${content}`, + output: `answer ${content}`, + ...(scenario !== "redact" && { metadata: { note: `note ${MARKER}` } }), + }); + if (scenario === "trace-redact") { + observeTrace(span, { + input: `trace prompt ${content}`, + output: `trace answer ${content}`, + }); + } + span.addEvent("proxy.upstream.response_body", { + "proxy.body": `body ${MARKER}`, + }); + span.setAttribute( + "gen_ai.response.tool_calls", + `[{"name":"lookup","arguments":"${MARKER}"}]`, + ); + span.end(); + }; + if (scenario === "trace-redact") { + setLangfuseContext({ traceName: "redacted-trace", redactIO: true }, () => + emit("scenario.redacted", SCOPE_MARKER), + ); + setLangfuseContext({ redactIO: true }, () => + setLangfuseContext({ redactIO: false }, () => + emit("scenario.nested", NESTED_MARKER), + ), + ); + setLangfuseContext({ traceName: "kept-trace" }, () => + emit("scenario.generate", MARKER), + ); + } else { + emit("scenario.generate", MARKER); + } await flushOpenTelemetry(); await sleep(200); process.stdout.write( @@ -487,6 +519,8 @@ if (process.env.ER_CHILD) { type ScenarioResult = { /** Attributes of the scenario span, then of its events, as the Langfuse request carries them. */ langfuseAttrs: Record; + /** Attributes of every span the Langfuse request carries, by span name. */ + langfuseByName: Record>; langfuseEventAttrs: Record; langfuse: string; otlp: string; @@ -536,6 +570,12 @@ async function runScenario(scenario: string): Promise { ); return { langfuseAttrs: flatten(scenarioSpan?.attributes), + langfuseByName: Object.fromEntries( + wireSpans(langfuse).map((entry) => [ + entry.span.name, + flatten(entry.span.attributes), + ]), + ), langfuseEventAttrs: flatten( scenarioSpan?.events.flatMap((event) => event.attributes), ), @@ -606,6 +646,37 @@ async function startOpenAI(): Promise<{ req.on("data", (chunk: Buffer) => chunks.push(chunk)); req.on("end", () => { const text = Buffer.concat(chunks).toString("utf8"); + if ((JSON.parse(text) as { stream?: boolean }).stream === true) { + const common = { id: "chatcmpl-fake", created: 1, model: "tool-model" }; + res.writeHead(200, { "content-type": "text/event-stream" }); + for (const frame of [ + { + ...common, + object: "chat.completion.chunk", + choices: [ + { + index: 0, + delta: { role: "assistant", content: "hello there" }, + finish_reason: null, + }, + ], + }, + { + ...common, + object: "chat.completion.chunk", + choices: [{ index: 0, delta: {}, finish_reason: "stop" }], + usage: { + prompt_tokens: 12, + completion_tokens: 5, + total_tokens: 17, + }, + }, + ]) { + res.write(`data: ${JSON.stringify(frame)}\n\n`); + } + res.end("data: [DONE]\n\n"); + return; + } res.writeHead(200, { "content-type": "application/json" }); res.end(JSON.stringify(chatBody(text.includes("tool_call_id")))); }); @@ -636,7 +707,9 @@ const hostProvider = new NodeTracerProvider({ hostProvider.register(); process.env.NEUROLINK_SKIP_MCP = "true"; -async function turn(): Promise<{ +async function turn( + options: { context?: Record; stream?: boolean } = {}, +): Promise<{ spans: ReadableSpan[]; recorded: SpanData[]; }> { @@ -651,14 +724,24 @@ async function turn(): Promise<{ inputSchema: z.object({ q: z.string().optional() }), execute: async () => ({ found: true }), } as never); - await nl.generate({ + const request = { input: { text: PROMPT_MARKER }, provider: "openai", model: "tool-model", credentials: { openai: { apiKey: "test-key", baseURL: fake.baseURL } }, disableInternalFallback: true, maxSteps: 3, - } as never); + ...(options.context && { context: options.context }), + }; + if (options.stream) { + const result = await nl.stream(request as never); + const chunks: unknown[] = []; + for await (const chunk of result.stream) { + chunks.push(chunk); + } + } else { + await nl.generate(request as never); + } await hostProvider.forceFlush(); return { spans: hostSpans.getFinishedSpans(), @@ -669,6 +752,37 @@ async function turn(): Promise<{ } } +// Adds a Langfuse exporter to the host pipeline for one run and returns what it sent +async function sentToLangfuse(run: () => Promise): Promise { + const receiver = await startReceiver(); + const exporter = new LangfuseExporter({ + enabled: true, + publicKey: "pk-host", + secretKey: "sk-host", + baseUrl: receiver.url, + retries: 0, + maxBufferSize: 10_000, + flushIntervalMs: 60_000, + }); + await exporter.initialize(); + hostRegistry.register(exporter); + try { + await run(); + await hostProvider.forceFlush(); + return wireSpans(receiver); + } finally { + hostRegistry.unregister("langfuse"); + await exporter.shutdown(); + await receiver.close(); + } +} + +function carriesContent(wire: Wire[]): boolean { + return wire.some((entry) => + entry.span.attributes.some((kv) => CONTENT_KEYS.has(kv.key)), + ); +} + function observationsOf(spans: ReadableSpan[], type: string): ReadableSpan[] { return spans.filter( (span) => span.attributes["langfuse.observation.type"] === type, @@ -1094,6 +1208,105 @@ void runSuite(async () => { ); }, ); + await proof( + "K21", + "per-trace redactIO: a span started in setLangfuseContext({ redactIO: true }) reaches Langfuse with no observation or trace input or output, while a sibling trace on the same exporter keeps all four", + async () => { + const result = await scenario("trace-redact"); + const redacted = result.langfuseByName["scenario.redacted"]; + const kept = result.langfuseByName["scenario.generate"]; + return ( + redacted !== undefined && + kept !== undefined && + !result.langfuse.includes(SCOPE_MARKER) && + [...CONTENT_KEYS].every( + (key) => + redacted[key] === undefined && kept[key]?.includes(MARKER) === true, + ) + ); + }, + ); + await proof( + "K21", + "per-trace redactIO: an inner setLangfuseContext({ redactIO: false }) does not undo an enclosing scope's redactIO", + async () => { + const result = await scenario("trace-redact"); + const nested = result.langfuseByName["scenario.nested"]; + return ( + nested !== undefined && + nested["langfuse.observation.input"] === undefined && + nested["langfuse.observation.output"] === undefined && + !result.langfuse.includes(NESTED_MARKER) + ); + }, + ); + await proof( + "K21", + "per-trace redactIO: the redaction marker is not sent to Langfuse, while the OTLP processor and a second registry exporter receive it with the redacted input and output", + async () => { + const result = await scenario("trace-redact"); + return ( + !result.langfuse.includes(REDACT_IO_ATTRIBUTE) && + result.otlp.includes(REDACT_IO_ATTRIBUTE) && + result.recorded.includes(REDACT_IO_ATTRIBUTE) && + result.otlp.includes(SCOPE_MARKER) && + result.recorded.includes(SCOPE_MARKER) + ); + }, + ); + await proof( + "K21", + "per-trace redactIO end to end: every span generate() starts inside setLangfuseContext({ redactIO: true }) carries the redaction marker, and no span outside it does", + async () => { + const marked = (spans: ReadableSpan[]): number => + spans.filter((span) => span.attributes[REDACT_IO_ATTRIBUTE] === true) + .length; + const inside = await setLangfuseContext({ redactIO: true }, () => turn()); + const outside = await turn(); + return ( + inside.spans.length > 0 && + marked(inside.spans) === inside.spans.length && + outside.spans.length > 0 && + marked(outside.spans) === 0 + ); + }, + ); + const redactedOnLangfuse = (wire: Wire[]): boolean => + wire.length > 0 && + !carriesContent(wire) && + !JSON.stringify(wire).includes(PROMPT_MARKER); + const keptOnLangfuse = (wire: Wire[]): boolean => + carriesContent(wire) && JSON.stringify(wire).includes(PROMPT_MARKER); + await proof( + "K21", + "per-call redactIO: generate({ context: { redactIO: true } }) reaches Langfuse with no input or output on any observation, while the same call without it sends both", + async () => { + const redacted = await sentToLangfuse(() => + turn({ context: { redactIO: true } }), + ); + const kept = await sentToLangfuse(() => turn()); + return redactedOnLangfuse(redacted) && keptOnLangfuse(kept); + }, + ); + await proof( + "K21", + "per-call redactIO: a fully drained stream({ context: { redactIO: true } }) reaches Langfuse with no input or output on any observation, while the same stream without it sends both", + async () => { + const redacted = await sentToLangfuse(() => + turn({ context: { redactIO: true }, stream: true }), + ); + const kept = await sentToLangfuse(() => turn({ stream: true })); + return redactedOnLangfuse(redacted) && keptOnLangfuse(kept); + }, + ); + await proof( + "K21", + 'per-call redactIO: a truthy value that is not a boolean, such as "true", redacts as true does', + async () => + redactedOnLangfuse( + await sentToLangfuse(() => turn({ context: { redactIO: "true" } })), + ), + ); // ----------------------------------------------------------------- K25 section("K25 what the Langfuse request keeps of the span");