🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
feat(ingestion): move oversized direct-event fields to media (#15350)
Hassieb Pakzadca751fbd5012
diff --git a/docker-compose.yml b/docker-compose.ymlindex 326238bd62..8ae1583408 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -44,9 +44,11 @@ services:LANGFUSE_S3_MEDIA_UPLOAD_REGION: ${LANGFUSE_S3_MEDIA_UPLOAD_REGION:-auto}LANGFUSE_S3_MEDIA_UPLOAD_ACCESS_KEY_ID: ${LANGFUSE_S3_MEDIA_UPLOAD_ACCESS_KEY_ID:-minio}LANGFUSE_S3_MEDIA_UPLOAD_SECRET_ACCESS_KEY: ${LANGFUSE_S3_MEDIA_UPLOAD_SECRET_ACCESS_KEY:-miniosecret} # CHANGEME- LANGFUSE_S3_MEDIA_UPLOAD_ENDPOINT: ${LANGFUSE_S3_MEDIA_UPLOAD_ENDPOINT:-http://localhost:9090}+ LANGFUSE_S3_MEDIA_UPLOAD_ENDPOINT: ${LANGFUSE_S3_MEDIA_UPLOAD_ENDPOINT:-http://minio:9000}LANGFUSE_S3_MEDIA_UPLOAD_FORCE_PATH_STYLE: ${LANGFUSE_S3_MEDIA_UPLOAD_FORCE_PATH_STYLE:-true}LANGFUSE_S3_MEDIA_UPLOAD_PREFIX: ${LANGFUSE_S3_MEDIA_UPLOAD_PREFIX:-media/}+ LANGFUSE_OBSERVATION_FIELD_OVERFLOW_ENABLED: ${LANGFUSE_OBSERVATION_FIELD_OVERFLOW_ENABLED:-false}+ LANGFUSE_OBSERVATION_FIELD_SIZE_LIMIT_BYTES: ${LANGFUSE_OBSERVATION_FIELD_SIZE_LIMIT_BYTES:-2097152}LANGFUSE_S3_BATCH_EXPORT_ENABLED: ${LANGFUSE_S3_BATCH_EXPORT_ENABLED:-false}LANGFUSE_S3_BATCH_EXPORT_BUCKET: ${LANGFUSE_S3_BATCH_EXPORT_BUCKET:-langfuse}LANGFUSE_S3_BATCH_EXPORT_PREFIX: ${LANGFUSE_S3_BATCH_EXPORT_PREFIX:-exports/}@@ -78,6 +80,7 @@ services:environment:<<: *langfuse-worker-envNEXTAUTH_SECRET: ${NEXTAUTH_SECRET:-mysecret} # CHANGEME+ LANGFUSE_S3_MEDIA_UPLOAD_ENDPOINT: ${LANGFUSE_S3_MEDIA_UPLOAD_ENDPOINT:-http://localhost:9090}LANGFUSE_INIT_ORG_ID: ${LANGFUSE_INIT_ORG_ID:-}LANGFUSE_INIT_ORG_NAME: ${LANGFUSE_INIT_ORG_NAME:-}LANGFUSE_INIT_PROJECT_ID: ${LANGFUSE_INIT_PROJECT_ID:-}diff --git a/packages/shared/src/domain/media.ts b/packages/shared/src/domain/media.tsindex 901387f0c7..029983a47d 100644--- a/packages/shared/src/domain/media.ts+++ b/packages/shared/src/domain/media.ts@@ -109,6 +109,8 @@ export enum MediaFileExtension {export type MediaField = "input" | "output" | "metadata";+export const OBSERVATION_FIELD_SIZE_LIMIT_MEDIA_SOURCE = "field_size_limit";+const mediaContentTypes = new Set<string>(Object.values(MediaContentType));export function isMediaContentType(value: unknown): value is MediaContentType {diff --git a/web/src/components/editor/mediaTagWidget.tsx b/web/src/components/editor/mediaTagWidget.tsxindex 6760ec32d9..126c9d1c4e 100644--- a/web/src/components/editor/mediaTagWidget.tsx+++ b/web/src/components/editor/mediaTagWidget.tsx@@ -15,7 +15,7 @@ import {classifyMediaValue,type MediaDescriptor,} from "@/src/components/ui/media/mediaUtils";-import { JsonMediaTag } from "@/src/components/ui/media/JsonMediaTag";+import { MediaReferenceTag } from "@/src/components/ui/media/MediaReferenceTag";type LangfuseRefDescriptor = Extract<MediaDescriptor, { kind: "langfuseRef" }>;@@ -33,7 +33,7 @@ const EMPTY: MediaAnchor[] = [];* The CodeMirror widget can only produce a detached DOM node — which has no* access to the app's React providers (tRPC, router, layers) — so instead of* mounting React there, the widget registers an empty anchor here and the- * in-tree portal host (`MediaTagWidgetPortals`) renders `JsonMediaTag` into it,+ * in-tree portal host (`MediaTagWidgetPortals`) renders `MediaReferenceTag` into it,* keeping the hover-peek's lazy fetch and popover working.*/class MediaTagWidgetStore {@@ -189,7 +189,7 @@ function MediaTagWidgetPortals({ store }: { store: MediaTagWidgetStore }) {<>{anchors.map((anchor) =>createPortal(- <JsonMediaTag descriptor={anchor.descriptor} />,+ <MediaReferenceTag descriptor={anchor.descriptor} />,anchor.dom,String(anchor.id),),diff --git a/web/src/components/table/ValueCell.tsx b/web/src/components/table/ValueCell.tsxindex 59f8f4974c..f21ee54812 100644--- a/web/src/components/table/ValueCell.tsx+++ b/web/src/components/table/ValueCell.tsx@@ -4,7 +4,7 @@ import { type Row } from "@tanstack/react-table";import { urlRegex } from "@langfuse/shared";import { type JsonTableRow } from "@/src/components/table/utils/jsonExpansionUtils";import { classifyMediaValue } from "@/src/components/ui/media/mediaUtils";-import { JsonMediaTag } from "@/src/components/ui/media/JsonMediaTag";+import { MediaReferenceTag } from "@/src/components/ui/media/MediaReferenceTag";import { copyTextToClipboard } from "@/src/utils/clipboard";import { Button } from "@/src/components/ui/button";import {@@ -382,7 +382,7 @@ export const ValueCell = memo(const mediaDescriptor = classifyMediaValue(stringValue);if (mediaDescriptor) {return {- content: <JsonMediaTag descriptor={mediaDescriptor} />,+ content: <MediaReferenceTag descriptor={mediaDescriptor} />,needsTruncation: false,};}diff --git a/web/src/components/trace/components/IOPreview/components/SectionMedia.tsx b/web/src/components/trace/components/IOPreview/components/SectionMedia.tsxindex 8bdedf9b7b..17331b1a3b 100644--- a/web/src/components/trace/components/IOPreview/components/SectionMedia.tsx+++ b/web/src/components/trace/components/IOPreview/components/SectionMedia.tsx@@ -17,7 +17,7 @@ export function SectionMedia({ media }: SectionMediaProps) {return (<><div className="text-muted-foreground my-1 px-2 py-1 text-xs">Media</div>- <div className="flex flex-wrap gap-2 pt-1 pb-4">+ <div className="flex flex-wrap gap-2 px-2 pt-1 pb-4">{media.map((m) => (<LangfuseMediaViewmediaAPIReturnValue={m}diff --git a/web/src/components/ui/AdvancedJsonViewer/components/JsonValue.tsx b/web/src/components/ui/AdvancedJsonViewer/components/JsonValue.tsxindex 218cabc5d4..6a48e47543 100644--- a/web/src/components/ui/AdvancedJsonViewer/components/JsonValue.tsx+++ b/web/src/components/ui/AdvancedJsonViewer/components/JsonValue.tsx@@ -18,7 +18,7 @@ import {TooltipTrigger,} from "@/src/components/ui/tooltip";import { classifyMediaValue } from "@/src/components/ui/media/mediaUtils";-import { JsonMediaTag } from "@/src/components/ui/media/JsonMediaTag";+import { MediaReferenceTag } from "@/src/components/ui/media/MediaReferenceTag";export function JsonValue({value,@@ -115,7 +115,7 @@ export function JsonValue({// text highlighter found no search/comment overlays to preserve.const mediaDescriptor = classifyMediaValue(str);if (mediaDescriptor && segments.every((segment) => segment.type === null)) {- return <JsonMediaTag descriptor={mediaDescriptor} />;+ return <MediaReferenceTag descriptor={mediaDescriptor} />;}return (diff --git a/web/src/components/ui/CodeJsonViewer.tsx b/web/src/components/ui/CodeJsonViewer.tsxindex 05d51565b4..05522fd4ca 100644--- a/web/src/components/ui/CodeJsonViewer.tsx+++ b/web/src/components/ui/CodeJsonViewer.tsx@@ -20,7 +20,7 @@ import { useMarkdownContext } from "@/src/features/theming/useMarkdownContext";import { type MediaReturnType } from "@/src/features/media/validation";import { LangfuseMediaView } from "@/src/components/ui/LangfuseMediaView";import { classifyMediaValue } from "@/src/components/ui/media/mediaUtils";-import { JsonMediaTag } from "@/src/components/ui/media/JsonMediaTag";+import { MediaReferenceTag } from "@/src/components/ui/media/MediaReferenceTag";import { MarkdownJsonViewHeader } from "@/src/components/ui/MarkdownJsonView";import {renderRichPromptContent,@@ -153,7 +153,7 @@ export function JSONView(props: {customizeNode={({ node }) => {const descriptor = classifyMediaValue(node);return descriptor ? (- <JsonMediaTag descriptor={descriptor} />+ <MediaReferenceTag descriptor={descriptor} />) : undefined;}}customizeCopy={(node) => stringifyJsonNode(node)}diff --git a/web/src/components/ui/IOTableCell.tsx b/web/src/components/ui/IOTableCell.tsxindex bd7e5ab232..f7c2325b2e 100644--- a/web/src/components/ui/IOTableCell.tsx+++ b/web/src/components/ui/IOTableCell.tsx@@ -5,7 +5,7 @@ import {JSONView,} from "@/src/components/ui/CodeJsonViewer";import { splitStringByMediaReferences } from "@/src/components/ui/media/mediaUtils";-import { JsonMediaTag } from "@/src/components/ui/media/JsonMediaTag";+import { MediaReferenceTag } from "@/src/components/ui/media/MediaReferenceTag";import { cn } from "@/src/utils/tailwind";import { memo, useRef, useState } from "react";import {@@ -57,7 +57,7 @@ function renderStringWithMediaReferences(value: string) {return segments.map((segment, index) =>segment.type === "media" ? (- <JsonMediaTag+ <MediaReferenceTagkey={`${segment.value}-${index}`}descriptor={segment.descriptor}/>diff --git a/web/src/components/ui/LangfuseMediaView.clienttest.tsx b/web/src/components/ui/LangfuseMediaView.clienttest.tsxnew file mode 100644index 0000000000..6c5ff146ae--- /dev/null+++ b/web/src/components/ui/LangfuseMediaView.clienttest.tsx@@ -0,0 +1,34 @@+import { render, screen } from "@testing-library/react";+import { describe, expect, it, vi } from "vitest";++import { LangfuseMediaView } from "./LangfuseMediaView";++vi.mock("@/src/hooks/useProjectIdFromURL", () => ({+ default: () => "project-id",+}));++vi.mock("@/src/utils/api", () => ({+ api: {+ media: {+ getById: {+ useQuery: () => ({ data: undefined }),+ },+ },+ },+}));++vi.mock("./media/useResolvedMedia", () => ({+ useResolvedMedia: () => ({ status: "idle", url: undefined }),+}));++describe("LangfuseMediaView", () => {+ it("renders a field-limit reference as the specialized warning", () => {+ render(+ <LangfuseMediaView mediaReferenceString="@@@langfuseMedia:type=text/plain|id=oversized-field|source=field_size_limit@@@" />,+ );++ expect(+ screen.getByRole("button", { name: "Field over size limit media" }),+ ).toBeInTheDocument();+ });+});diff --git a/web/src/components/ui/LangfuseMediaView.tsx b/web/src/components/ui/LangfuseMediaView.tsxindex 087d3499b8..562fe13cb9 100644--- a/web/src/components/ui/LangfuseMediaView.tsx+++ b/web/src/components/ui/LangfuseMediaView.tsx@@ -6,6 +6,7 @@ import { Button } from "@/src/components/ui/button";import { ImageOff } from "lucide-react";import {MediaReferenceStringSchema,+ OBSERVATION_FIELD_SIZE_LIMIT_MEDIA_SOURCE,type ParsedMediaReferenceType,} from "@langfuse/shared";import {@@ -24,6 +25,7 @@ import {Video,Volume2,} from "lucide-react";+import { MediaReferenceTag } from "@/src/components/ui/media/MediaReferenceTag";// Above this, "preview" media falls back to the click-to-open icon instead of// rendering inline, so a large file isn't fetched/decoded just by opening a view.@@ -45,7 +47,12 @@ export const LangfuseMediaView = ({// Non-previewable types (e.g. PDF) are always a click-to-open icon.variant?: "inline" | "icon" | "preview";}) => {- let mediaData: { id: string; type: MediaContentType } | null = null;+ let mediaData: {+ id: string;+ type: MediaContentType;+ referenceString?: string;+ source?: string;+ } | null = null;const projectId = useProjectIdFromURL();@@ -56,11 +63,15 @@ export const LangfuseMediaView = ({mediaData = {id: parsedTag.id,type: parsedTag.type as MediaContentType,+ referenceString: parsedTag.referenceString,+ source: parsedTag.source,};} else if (mediaReferenceString && typeof mediaReferenceString !== "string") {mediaData = {id: mediaReferenceString.id,type: mediaReferenceString.type as MediaContentType,+ referenceString: mediaReferenceString.referenceString,+ source: mediaReferenceString.source,};} else if (mediaAPIReturnValue) {mediaData = {@@ -84,13 +95,16 @@ export const LangfuseMediaView = ({);}+ const isOversizedField =+ mediaData.source === OBSERVATION_FIELD_SIZE_LIMIT_MEDIA_SOURCE;+const { data } = api.media.getById.useQuery({mediaId: mediaData.id,projectId: projectId as string,},{- enabled: Boolean(projectId),+ enabled: Boolean(projectId) && !isOversizedField,refetchOnWindowFocus: false,refetchOnMount: false,refetchOnReconnect: false,@@ -98,6 +112,20 @@ export const LangfuseMediaView = ({},);+ if (isOversizedField && mediaData.referenceString) {+ return (+ <MediaReferenceTag+ descriptor={{+ kind: "langfuseRef",+ contentType: mediaData.type,+ mediaId: mediaData.id,+ referenceString: mediaData.referenceString,+ source: OBSERVATION_FIELD_SIZE_LIMIT_MEDIA_SOURCE,+ }}+ />+ );+ }+const mediaUrl = data?.url;if (!mediaUrl) return null;diff --git a/web/src/components/ui/MarkdownViewer.tsx b/web/src/components/ui/MarkdownViewer.tsxindex 37466c01a5..c5df72f8fd 100644--- a/web/src/components/ui/MarkdownViewer.tsx+++ b/web/src/components/ui/MarkdownViewer.tsx@@ -674,7 +674,7 @@ export function MarkdownView({<div className="text-muted-foreground mx-3 border-t px-2 py-1 text-xs">Media</div>- <div className="mx-3 flex flex-wrap gap-2 pt-1 pb-4">+ <div className="mx-3 flex flex-wrap gap-2 px-2 pt-1 pb-4">{remainingMedia.map((m) => (<LangfuseMediaViewmediaAPIReturnValue={m}diff --git a/web/src/components/ui/PrettyJsonView.media.clienttest.tsx b/web/src/components/ui/PrettyJsonView.media.clienttest.tsxnew file mode 100644index 0000000000..f6155bbfe3--- /dev/null+++ b/web/src/components/ui/PrettyJsonView.media.clienttest.tsx@@ -0,0 +1,37 @@+import { render, screen } from "@testing-library/react";+import { MediaContentType } from "@langfuse/shared";++vi.mock("@/src/features/posthog-analytics/usePostHogClientCapture", () => ({+ usePostHogClientCapture: () => vi.fn(),+}));++vi.mock("@/src/components/ui/LangfuseMediaView", () => ({+ LangfuseMediaView: () => <div data-testid="media-item" />,+}));++import { PrettyJsonView } from "@/src/components/ui/PrettyJsonView";+import { LARGE_STRING_RENDER_CHAR_LIMIT } from "@/src/components/ui/largeStringGate";+import { MediaEnabledFields } from "@/src/features/media/validation";++describe("PrettyJsonView media layout", () => {+ it("aligns attachment tiles with the section content", () => {+ render(+ <PrettyJsonView+ json={"x".repeat(LARGE_STRING_RENDER_CHAR_LIMIT + 1)}+ title="Output"+ media={[+ {+ mediaId: "media-id",+ contentType: MediaContentType.TXT,+ contentLength: 1,+ url: "https://example.com/media.txt",+ urlExpiry: "2099-01-01T00:00:00.000Z",+ field: MediaEnabledFields.Output,+ },+ ]}+ />,+ );++ expect(screen.getByTestId("media-item").parentElement).toHaveClass("px-2");+ });+});diff --git a/web/src/components/ui/PrettyJsonView.tsx b/web/src/components/ui/PrettyJsonView.tsxindex 327af55bd5..a43264ac07 100644--- a/web/src/components/ui/PrettyJsonView.tsx+++ b/web/src/components/ui/PrettyJsonView.tsx@@ -1399,7 +1399,7 @@ export function PrettyJsonView(props: {<div className="text-muted-foreground my-1 px-2 py-1 text-xs">Media</div>- <div className="flex flex-wrap gap-2 pt-1 pb-4">+ <div className="flex flex-wrap gap-2 px-2 pt-1 pb-4">{remainingMarkdownMedia.map((m) => (<LangfuseMediaViewmediaAPIReturnValue={m}@@ -1418,7 +1418,7 @@ export function PrettyJsonView(props: {<div className="text-muted-foreground my-1 px-2 py-1 text-xs">Media</div>- <div className="flex flex-wrap gap-2 pt-1 pb-4">+ <div className="flex flex-wrap gap-2 px-2 pt-1 pb-4">{props.media.map((m) => (<LangfuseMediaViewmediaAPIReturnValue={m}diff --git a/web/src/components/ui/media/MediaReferenceTag.clienttest.tsx b/web/src/components/ui/media/MediaReferenceTag.clienttest.tsxnew file mode 100644index 0000000000..a1e960a281--- /dev/null+++ b/web/src/components/ui/media/MediaReferenceTag.clienttest.tsx@@ -0,0 +1,24 @@+import { render, screen } from "@testing-library/react";+import { describe, expect, it, vi } from "vitest";++import { MediaReferenceTag } from "./MediaReferenceTag";+import { classifyMediaValue } from "./mediaUtils";++vi.mock("./useResolvedMedia", () => ({+ useResolvedMedia: () => ({ status: "idle", url: undefined }),+}));++describe("MediaReferenceTag", () => {+ it("renders a bare field-limit media reference as the specialized warning", () => {+ const descriptor = classifyMediaValue(+ "@@@langfuseMedia:type=text/plain|id=oversized-field|source=field_size_limit@@@",+ );++ expect(descriptor).not.toBeNull();+ render(<MediaReferenceTag descriptor={descriptor!} />);++ expect(+ screen.getByRole("button", { name: "Field over size limit media" }),+ ).toBeInTheDocument();+ });+});diff --git a/web/src/components/ui/media/JsonMediaTag.tsx b/web/src/components/ui/media/MediaReferenceTag.tsxsimilarity index 67%rename from web/src/components/ui/media/JsonMediaTag.tsxrename to web/src/components/ui/media/MediaReferenceTag.tsxindex 597c1aa304..de4361a1af 100644--- a/web/src/components/ui/media/JsonMediaTag.tsx+++ b/web/src/components/ui/media/MediaReferenceTag.tsx@@ -2,6 +2,7 @@ import { useState } from "react";import { MediaTag } from "./MediaTag";import { useResolvedMedia } from "./useResolvedMedia";import { type MediaDescriptor } from "./mediaUtils";+import { OBSERVATION_FIELD_SIZE_LIMIT_MEDIA_SOURCE } from "@langfuse/shared";type LangfuseRefDescriptor = Extract<MediaDescriptor, { kind: "langfuseRef" }>;@@ -10,7 +11,11 @@ type LangfuseRefDescriptor = Extract<MediaDescriptor, { kind: "langfuseRef" }>;* arms the lazy fetch the first time the peek opens (hover/focus) and keeps it* armed so re-hovers read from the query cache instead of re-fetching.*/-export function JsonMediaTag({ descriptor }: { descriptor: MediaDescriptor }) {+export function MediaReferenceTag({+ descriptor,+}: {+ descriptor: MediaDescriptor;+}) {if (descriptor.kind !== "langfuseRef") {return (<MediaTag@@ -31,12 +36,21 @@ function LangfuseRefMediaTag({}) {const [armed, setArmed] = useState(false);const { status, url } = useResolvedMedia(descriptor, { enabled: armed });+ const isOversizedField =+ descriptor.source === OBSERVATION_FIELD_SIZE_LIMIT_MEDIA_SOURCE;return (<MediaTagcontentType={descriptor.contentType}status={status}url={url}+ label={isOversizedField ? "Field over size limit" : undefined}+ description={+ isOversizedField+ ? "This field exceeded the configured storage limit. Open the file to view the original content."+ : undefined+ }+ warning={isOversizedField}onOpenChange={(open) => {if (open) setArmed(true);}}diff --git a/web/src/components/ui/media/MediaTag.clienttest.tsx b/web/src/components/ui/media/MediaTag.clienttest.tsxindex d2cad15c3d..de5b64a269 100644--- a/web/src/components/ui/media/MediaTag.clienttest.tsx+++ b/web/src/components/ui/media/MediaTag.clienttest.tsx@@ -78,4 +78,31 @@ describe("MediaTag", () => {expect(await screen.findByText("Failed to load media")).toBeInTheDocument();});++ it("renders an oversized-field warning with download context", () => {+ render(+ <MediaTag+ contentType="text/plain"+ status="ready"+ url="https://example.com/oversized.txt"+ label="Field over size limit"+ description="This field exceeded the configured storage limit. Open the file to view the original content."+ warning+ open+ />,+ );++ expect(+ screen.getByRole("button", { name: "Field over size limit media" }),+ ).toBeInTheDocument();+ expect(+ screen.getByText(+ "This field exceeded the configured storage limit. Open the file to view the original content.",+ ),+ ).toBeInTheDocument();+ expect(screen.getByTitle("Open in new tab")).toHaveAttribute(+ "href",+ "https://example.com/oversized.txt",+ );+ });});diff --git a/web/src/components/ui/media/MediaTag.stories.tsx b/web/src/components/ui/media/MediaTag.stories.tsxindex bd0c1665a1..e1a763c2b6 100644--- a/web/src/components/ui/media/MediaTag.stories.tsx+++ b/web/src/components/ui/media/MediaTag.stories.tsx@@ -112,6 +112,21 @@ export const PreviewFile = meta.story({},});+// Oversized observation fields use the media surface as a deliberate warning,+// rather than looking like ordinary user-attached media.+export const OversizedField = meta.story({+ args: {+ contentType: "text/plain",+ label: "Field over size limit",+ description:+ "This field exceeded the configured storage limit. Open the file to view the original content.",+ warning: true,+ open: true,+ status: "ready",+ url: "data:text/plain,original%20oversized%20field",+ },+});+// Design showcase: one chip per media kind, collapsed.export const AllKinds = meta.story({render: () => (diff --git a/web/src/components/ui/media/MediaTag.tsx b/web/src/components/ui/media/MediaTag.tsxindex 951bcc5e06..5e030697a5 100644--- a/web/src/components/ui/media/MediaTag.tsx+++ b/web/src/components/ui/media/MediaTag.tsx@@ -4,6 +4,7 @@ import {File,Image as ImageIcon,ImageOff,+ TriangleAlert,Video,Volume2,type LucideIcon,@@ -40,6 +41,10 @@ export interface MediaTagProps {url?: string;/** Overrides the chip label (defaults to the MIME subtype, e.g. "JPEG"). */label?: string;+ /** Optional context shown above the preview in the peek popover. */+ description?: string;+ /** Renders the chip as a warning rather than a generic media attachment. */+ warning?: boolean;/** Controlled open state of the peek popover (used by stories/tests). */open?: boolean;/**@@ -163,10 +168,22 @@ function PeekBody({* popover with a preview and an "open in new tab" action.** It receives the resolved `url` + `status` as props and never fetches — the- * owning container (`JsonMediaTag`) gates a lazy fetch on `onOpenChange`.+ * owning container (`MediaReferenceTag`) gates a lazy fetch on `onOpenChange`.*/export const MediaTag = React.forwardRef<HTMLButtonElement, MediaTagProps>(- ({ contentType, status = "idle", url, label, open, onOpenChange }, ref) => {+ (+ {+ contentType,+ status = "idle",+ url,+ label,+ description,+ warning = false,+ open,+ onOpenChange,+ },+ ref,+ ) => {const kind = getMediaKind(contentType);const chipLabel = label ?? getDefaultLabel(contentType);const canOpen = status === "ready" && Boolean(url);@@ -201,7 +218,11 @@ export const MediaTag = React.forwardRef<HTMLButtonElement, MediaTagProps>(data-media-tag=""aria-label={`${chipLabel} media`}aria-expanded={isOpen}- className="hover:bg-accent focus-visible:ring-ring bg-background inline-flex h-3.5 max-w-full items-center gap-1 rounded-sm border px-1 py-0 align-middle text-xs leading-none transition-colors focus-visible:ring-2 focus-visible:outline-hidden"+ className={+ warning+ ? "focus-visible:ring-ring inline-flex h-3.5 max-w-full items-center gap-1 rounded-sm border border-amber-500/60 bg-amber-50 px-1 py-0 align-middle text-xs leading-none text-amber-900 transition-colors hover:bg-amber-100 focus-visible:ring-2 focus-visible:outline-hidden dark:bg-amber-950/40 dark:text-amber-200 dark:hover:bg-amber-950/60"+ : "hover:bg-accent focus-visible:ring-ring bg-background inline-flex h-3.5 max-w-full items-center gap-1 rounded-sm border px-1 py-0 align-middle text-xs leading-none transition-colors focus-visible:ring-2 focus-visible:outline-hidden"+ }onClick={openPeek}onPointerDown={(event) => {if (event.pointerType !== "mouse") {@@ -210,7 +231,11 @@ export const MediaTag = React.forwardRef<HTMLButtonElement, MediaTagProps>(}}}>- <KindIcon kind={kind} className="h-2.5 w-2.5 shrink-0" />+ {warning ? (+ <TriangleAlert className="h-2.5 w-2.5 shrink-0" />+ ) : (+ <KindIcon kind={kind} className="h-2.5 w-2.5 shrink-0" />+ )}<spanclassName="relative top-0.25 truncate align-baseline font-mono leading-none"// Empty while the peek is open: a native tooltip would render on@@ -258,6 +283,11 @@ export const MediaTag = React.forwardRef<HTMLButtonElement, MediaTagProps>(</Button>)}</div>+ {description ? (+ <p className="text-muted-foreground max-w-64 text-xs">+ {description}+ </p>+ ) : null}<PeekBodykind={kind}status={previewStatus}diff --git a/web/src/components/ui/media/mediaUtils.clienttest.ts b/web/src/components/ui/media/mediaUtils.clienttest.tsindex e7a3299bfd..98df0c8fd5 100644--- a/web/src/components/ui/media/mediaUtils.clienttest.ts+++ b/web/src/components/ui/media/mediaUtils.clienttest.ts@@ -14,6 +14,20 @@ describe("classifyMediaValue", () => {contentType: "image/png",mediaId: "cc48838a-3da8-4ca4-a007-2cf8df930e69",referenceString: ref,+ source: "bytes",+ });+ });++ it("preserves the field-size-limit source for warning rendering", () => {+ const oversizedFieldRef =+ "@@@langfuseMedia:type=text/plain|id=oversized-field|source=field_size_limit@@@";++ expect(classifyMediaValue(oversizedFieldRef)).toEqual({+ kind: "langfuseRef",+ contentType: "text/plain",+ mediaId: "oversized-field",+ referenceString: oversizedFieldRef,+ source: "field_size_limit",});});@@ -157,6 +171,7 @@ describe("classifyMediaValue", () => {contentType: "image/png",mediaId: "cc48838a-3da8-4ca4-a007-2cf8df930e69",referenceString: ref,+ source: "bytes",},},{ type: "text", value: '"}' },diff --git a/web/src/components/ui/media/mediaUtils.ts b/web/src/components/ui/media/mediaUtils.tsindex 119ad44f97..6ea8f3c15c 100644--- a/web/src/components/ui/media/mediaUtils.ts+++ b/web/src/components/ui/media/mediaUtils.ts@@ -75,6 +75,7 @@ export function classifyMediaValue(value: unknown) {contentType: parsed.data.type,mediaId: parsed.data.id,referenceString: parsed.data.referenceString,+ source: parsed.data.source,};}diff --git a/worker/src/env.ts b/worker/src/env.tsindex f4c91fcb30..a40313f138 100644--- a/worker/src/env.ts+++ b/worker/src/env.ts@@ -365,6 +365,14 @@ const EnvSchema = z.object({.default("false"),LANGFUSE_S3_MEDIA_UPLOAD_SSE: z.enum(["AES256", "aws:kms"]).optional(),LANGFUSE_S3_MEDIA_UPLOAD_SSE_KMS_KEY_ID: z.string().optional(),+ LANGFUSE_OBSERVATION_FIELD_OVERFLOW_ENABLED: z+ .enum(["true", "false"])+ .default("false"),+ LANGFUSE_OBSERVATION_FIELD_SIZE_LIMIT_BYTES: z.coerce+ .number()+ .int()+ .positive()+ .default(2 * 1024 * 1024),// Metering data Postgres export - Langfuse CloudLANGFUSE_POSTGRES_METERING_DATA_EXPORT_IS_ENABLED: zdiff --git a/worker/src/features/internal-tracing/createInternalEventsWriter.ts b/worker/src/features/internal-tracing/createInternalEventsWriter.tsindex 00bd7db6db..a54de4d720 100644--- a/worker/src/features/internal-tracing/createInternalEventsWriter.ts+++ b/worker/src/features/internal-tracing/createInternalEventsWriter.ts@@ -39,7 +39,7 @@ async function writeInternalEventInputs(params: {if (v4WritesToEventsTable(env)) {for (const eventRecord of eventRecords) {- service.writeEventRecord(eventRecord);+ await service.writeEventRecord(eventRecord);}}diff --git a/worker/src/features/observation-field-overflow/processObservationFieldOverflow.test.ts b/worker/src/features/observation-field-overflow/processObservationFieldOverflow.test.tsnew file mode 100644index 0000000000..115db46f8a--- /dev/null+++ b/worker/src/features/observation-field-overflow/processObservationFieldOverflow.test.ts@@ -0,0 +1,280 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import type { EventRecordInsertType } from "@langfuse/shared/src/server";++const mocks = vi.hoisted(() => ({+ env: {+ LANGFUSE_S3_MEDIA_UPLOAD_BUCKET: "media-bucket" as string | undefined,+ LANGFUSE_S3_MEDIA_UPLOAD_PREFIX: "media/",+ LANGFUSE_OBSERVATION_FIELD_OVERFLOW_ENABLED: "true",+ LANGFUSE_OBSERVATION_FIELD_SIZE_LIMIT_BYTES: 10,+ },+ logger: { warn: vi.fn() },+ recordDistribution: vi.fn(),+ recordIncrement: vi.fn(),+ uploadMediaForTrace: vi.fn(),+}));++vi.mock("@langfuse/shared/src/server", async (importOriginal) => ({+ ...(await importOriginal<typeof import("@langfuse/shared/src/server")>()),+ logger: mocks.logger,+ recordDistribution: mocks.recordDistribution,+ recordIncrement: mocks.recordIncrement,+ uploadMediaForTrace: mocks.uploadMediaForTrace,+}));++vi.mock("../../env", () => ({+ env: mocks.env,+}));++import { applyObservationFieldOverflow } from "./processObservationFieldOverflow";++const createEventRecord = (+ fields: Partial<EventRecordInsertType> = {},+): EventRecordInsertType =>+ ({+ project_id: "project-id",+ trace_id: "trace-id",+ span_id: "observation-id",+ metadata_values: [],+ ...fields,+ }) as EventRecordInsertType;++const mediaReference = (id: string) =>+ `@@@langfuseMedia:type=text/plain|id=${id}|source=field_size_limit@@@`;++const createDeferred = <T>() => {+ let resolve!: (value: T) => void;+ const promise = new Promise<T>((resolvePromise) => {+ resolve = resolvePromise;+ });++ return { promise, resolve };+};++describe("applyObservationFieldOverflow", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mocks.uploadMediaForTrace.mockReset();+ mocks.recordDistribution.mockReset();+ mocks.recordIncrement.mockReset();+ mocks.env.LANGFUSE_S3_MEDIA_UPLOAD_BUCKET = "media-bucket";+ mocks.env.LANGFUSE_OBSERVATION_FIELD_OVERFLOW_ENABLED = "true";+ mocks.env.LANGFUSE_OBSERVATION_FIELD_SIZE_LIMIT_BYTES = 10;+ });++ it("returns the original event record when overflow is disabled", async () => {+ mocks.env.LANGFUSE_OBSERVATION_FIELD_OVERFLOW_ENABLED = "false";+ const eventRecord = createEventRecord({ input: "x".repeat(11) });++ const result = await applyObservationFieldOverflow(eventRecord);++ expect(result).toBe(eventRecord);+ expect(mocks.uploadMediaForTrace).not.toHaveBeenCalled();+ });++ it("replaces oversized input, output, and metadata values by UTF-8 byte size", async () => {+ mocks.uploadMediaForTrace+ .mockResolvedValueOnce({ mediaId: "input-media", outcome: "uploaded" })+ .mockResolvedValueOnce({ mediaId: "output-media", outcome: "reused" })+ .mockResolvedValueOnce({+ mediaId: "metadata-media",+ outcome: "uploaded",+ });+ const eventRecord = createEventRecord({+ input: "x".repeat(11),+ output: "🔥🔥🔥",+ metadata_values: ["1234567890", "y".repeat(11)],+ });++ const result = await applyObservationFieldOverflow(eventRecord);++ expect(result).toMatchObject({+ input: mediaReference("input-media"),+ output: mediaReference("output-media"),+ metadata_values: ["1234567890", mediaReference("metadata-media")],+ });+ expect(eventRecord).toMatchObject({+ input: "x".repeat(11),+ output: "🔥🔥🔥",+ metadata_values: ["1234567890", "y".repeat(11)],+ });+ expect(mocks.uploadMediaForTrace).toHaveBeenNthCalledWith(+ 2,+ expect.objectContaining({+ field: "output",+ contentBytes: Buffer.from("🔥🔥🔥"),+ }),+ );+ expect(mocks.recordIncrement).toHaveBeenCalledTimes(3);+ });++ it("applies the limit to each metadata value rather than their aggregate size", async () => {+ const eventRecord = createEventRecord({+ metadata_values: ["123456", "123456"],+ });++ const result = await applyObservationFieldOverflow(eventRecord);++ expect(result.metadata_values).toEqual(["123456", "123456"]);+ expect(mocks.uploadMediaForTrace).not.toHaveBeenCalled();+ });++ it("uploads at most three oversized fields concurrently and preserves field order", async () => {+ const uploads = Array.from({ length: 5 }, () =>+ createDeferred<{ mediaId: string; outcome: "uploaded" }>(),+ );+ let activeUploads = 0;+ let maxActiveUploads = 0;+ let uploadIndex = 0;+ mocks.uploadMediaForTrace.mockImplementation(async () => {+ const currentIndex = uploadIndex++;+ activeUploads += 1;+ maxActiveUploads = Math.max(maxActiveUploads, activeUploads);+ const result = await uploads[currentIndex].promise;+ activeUploads -= 1;+ return result;+ });+ const eventRecord = createEventRecord({+ input: "input-value",+ output: "output-value",+ metadata_values: ["metadata-one", "metadata-two", "metadata-three"],+ });++ const resultPromise = applyObservationFieldOverflow(eventRecord);++ await vi.waitFor(() =>+ expect(mocks.uploadMediaForTrace).toHaveBeenCalledTimes(3),+ );+ expect(maxActiveUploads).toBe(3);++ uploads[0].resolve({ mediaId: "input-media", outcome: "uploaded" });+ uploads[1].resolve({ mediaId: "output-media", outcome: "uploaded" });+ uploads[2].resolve({ mediaId: "metadata-one", outcome: "uploaded" });+ await vi.waitFor(() =>+ expect(mocks.uploadMediaForTrace).toHaveBeenCalledTimes(5),+ );+ expect(maxActiveUploads).toBe(3);++ uploads[3].resolve({ mediaId: "metadata-two", outcome: "uploaded" });+ uploads[4].resolve({ mediaId: "metadata-three", outcome: "uploaded" });++ await expect(resultPromise).resolves.toMatchObject({+ input: mediaReference("input-media"),+ output: mediaReference("output-media"),+ metadata_values: [+ mediaReference("metadata-one"),+ mediaReference("metadata-two"),+ mediaReference("metadata-three"),+ ],+ });+ });++ it("keeps an individual field when its upload fails and continues processing", async () => {+ const uploadError = new Error("S3 unavailable");+ mocks.uploadMediaForTrace+ .mockRejectedValueOnce(uploadError)+ .mockResolvedValueOnce({ mediaId: "output-media", outcome: "uploaded" });+ const eventRecord = createEventRecord({+ input: "x".repeat(11),+ output: "y".repeat(11),+ });++ const result = await applyObservationFieldOverflow(eventRecord);++ expect(result.input).toBe(eventRecord.input);+ expect(result.output).toBe(mediaReference("output-media"));+ expect(mocks.logger.warn).toHaveBeenCalledWith(+ "Oversized observation field upload failed; persisting original field",+ {+ error: uploadError,+ projectId: "project-id",+ traceId: "trace-id",+ observationId: "observation-id",+ field: "input",+ originalBytes: 11,+ },+ );+ expect(mocks.recordIncrement).toHaveBeenCalledWith(+ "langfuse.ingestion.observation_field_overflow",+ 1,+ { field: "input", outcome: "failed" },+ );+ });++ it("logs once and returns the original oversized record when media storage is not configured", async () => {+ mocks.env.LANGFUSE_S3_MEDIA_UPLOAD_BUCKET = undefined;+ await applyObservationFieldOverflow(+ createEventRecord({ input: "within cap" }),+ );+ expect(mocks.logger.warn).not.toHaveBeenCalled();++ const eventRecord = createEventRecord({+ input: "x".repeat(11),+ output: "y".repeat(11),+ });++ const result = await applyObservationFieldOverflow(eventRecord);++ expect(result).toBe(eventRecord);+ expect(mocks.uploadMediaForTrace).not.toHaveBeenCalled();+ expect(mocks.logger.warn).toHaveBeenCalledOnce();+ expect(mocks.logger.warn).toHaveBeenCalledWith(+ "Observation field overflow processing failed; persisting original record",+ expect.objectContaining({+ error: expect.objectContaining({+ message: "Media upload bucket is not configured",+ }),+ projectId: "project-id",+ traceId: "trace-id",+ observationId: "observation-id",+ }),+ );+ });++ it("waits for the active batch before returning the original record on an unexpected failure", async () => {+ const processorError = new Error("metrics unavailable");+ const outputUpload = createDeferred<{+ mediaId: string;+ outcome: "uploaded";+ }>();+ mocks.uploadMediaForTrace+ .mockResolvedValueOnce({+ mediaId: "input-media",+ outcome: "uploaded",+ })+ .mockReturnValueOnce(outputUpload.promise);+ mocks.recordIncrement.mockImplementationOnce(() => {+ throw processorError;+ });+ const eventRecord = createEventRecord({+ input: "x".repeat(11),+ output: "y".repeat(11),+ });++ let didSettle = false;+ const resultPromise = applyObservationFieldOverflow(eventRecord).finally(+ () => {+ didSettle = true;+ },+ );++ await vi.waitFor(() =>+ expect(mocks.uploadMediaForTrace).toHaveBeenCalledTimes(2),+ );+ await Promise.resolve();+ expect(didSettle).toBe(false);++ outputUpload.resolve({ mediaId: "output-media", outcome: "uploaded" });++ await expect(resultPromise).resolves.toBe(eventRecord);+ expect(mocks.logger.warn).toHaveBeenCalledWith(+ "Observation field overflow processing failed; persisting original record",+ {+ error: processorError,+ projectId: "project-id",+ traceId: "trace-id",+ observationId: "observation-id",+ },+ );+ });+});diff --git a/worker/src/features/observation-field-overflow/processObservationFieldOverflow.ts b/worker/src/features/observation-field-overflow/processObservationFieldOverflow.tsnew file mode 100644index 0000000000..b15084c48b--- /dev/null+++ b/worker/src/features/observation-field-overflow/processObservationFieldOverflow.ts@@ -0,0 +1,221 @@+import {+ type EventRecordInsertType,+ logger,+ recordDistribution,+ recordIncrement,+ uploadMediaForTrace,+} from "@langfuse/shared/src/server";+import {+ MediaContentType,+ OBSERVATION_FIELD_SIZE_LIMIT_MEDIA_SOURCE,+} from "@langfuse/shared";++import { env } from "../../env";++const OBSERVATION_FIELD_OVERFLOW_UPLOAD_BATCH_SIZE = 3;++type OverflowTarget =+ | { field: "input" | "output" }+ | { field: "metadata"; metadataIndex: number };++type OverflowCandidate = OverflowTarget & {+ value: string;+ originalBytes: number;+};++type OverflowResult = {+ candidate: OverflowCandidate;+ overflowedValue: string;+};++export async function applyObservationFieldOverflow(+ eventRecord: EventRecordInsertType,+): Promise<EventRecordInsertType> {+ if (env.LANGFUSE_OBSERVATION_FIELD_OVERFLOW_ENABLED !== "true") {+ return eventRecord;+ }++ try {+ const mediaBucket = env.LANGFUSE_S3_MEDIA_UPLOAD_BUCKET;+ const candidates = collectOverflowCandidates(eventRecord);++ if (candidates.length === 0) {+ return eventRecord;+ }+ if (!mediaBucket) {+ throw new Error("Media upload bucket is not configured");+ }++ const results = await uploadOverflowCandidates(+ eventRecord,+ candidates,+ mediaBucket,+ );++ return applyOverflowResults(eventRecord, results);+ } catch (error) {+ logger.warn(+ "Observation field overflow processing failed; persisting original record",+ {+ error,+ projectId: eventRecord.project_id,+ traceId: eventRecord.trace_id,+ observationId: eventRecord.span_id,+ },+ );+ return eventRecord;+ }+}++function collectOverflowCandidates(+ eventRecord: EventRecordInsertType,+): OverflowCandidate[] {+ const candidates: OverflowCandidate[] = [];+ const addCandidate = (target: OverflowTarget, value: string) => {+ const originalBytes = Buffer.byteLength(value, "utf8");+ if (originalBytes > env.LANGFUSE_OBSERVATION_FIELD_SIZE_LIMIT_BYTES) {+ candidates.push({ ...target, value, originalBytes });+ }+ };++ if (eventRecord.input != null) {+ addCandidate({ field: "input" }, eventRecord.input);+ }+ if (eventRecord.output != null) {+ addCandidate({ field: "output" }, eventRecord.output);+ }+ eventRecord.metadata_values.forEach((value, metadataIndex) => {+ addCandidate({ field: "metadata", metadataIndex }, value);+ });++ return candidates;+}++async function uploadOverflowCandidates(+ eventRecord: EventRecordInsertType,+ candidates: OverflowCandidate[],+ mediaBucket: string,+): Promise<OverflowResult[]> {+ const overflowResults: OverflowResult[] = [];++ // Bound the additional buffers retained by concurrent uploads per event.+ for (+ let start = 0;+ start < candidates.length;+ start += OBSERVATION_FIELD_OVERFLOW_UPLOAD_BATCH_SIZE+ ) {+ const batch = candidates.slice(+ start,+ start + OBSERVATION_FIELD_OVERFLOW_UPLOAD_BATCH_SIZE,+ );+ const settledBatch = await Promise.allSettled(+ batch.map((candidate) =>+ uploadOverflowCandidate(eventRecord, candidate, mediaBucket),+ ),+ );++ for (const result of settledBatch) {+ if (result.status === "rejected") {+ throw result.reason;+ }+ overflowResults.push(result.value);+ }+ }++ return overflowResults;+}++function applyOverflowResults(+ eventRecord: EventRecordInsertType,+ results: OverflowResult[],+): EventRecordInsertType {+ let input = eventRecord.input;+ let output = eventRecord.output;+ const metadataValues = eventRecord.metadata_values.slice();++ for (const { candidate, overflowedValue } of results) {+ switch (candidate.field) {+ case "input":+ input = overflowedValue;+ break;+ case "output":+ output = overflowedValue;+ break;+ case "metadata":+ metadataValues[candidate.metadataIndex] = overflowedValue;+ break;+ }+ }++ return {+ ...eventRecord,+ input,+ output,+ metadata_values: metadataValues,+ };+}++async function uploadOverflowCandidate(+ eventRecord: EventRecordInsertType,+ candidate: OverflowCandidate,+ mediaBucket: string,+): Promise<OverflowResult> {+ const { field, value, originalBytes } = candidate;++ const uploadResult = await uploadMediaForTrace({+ projectId: eventRecord.project_id,+ traceId: eventRecord.trace_id,+ observationId: eventRecord.span_id,+ field,+ contentType: MediaContentType.TXT,+ contentBytes: Buffer.from(value, "utf8"),+ mediaBucket,+ mediaPrefix: env.LANGFUSE_S3_MEDIA_UPLOAD_PREFIX,+ }).catch((error) => {+ logger.warn(+ "Oversized observation field upload failed; persisting original field",+ {+ error,+ projectId: eventRecord.project_id,+ traceId: eventRecord.trace_id,+ observationId: eventRecord.span_id,+ field,+ originalBytes,+ },+ );+ const metricTags = { field, outcome: "failed" };+ recordIncrement(+ "langfuse.ingestion.observation_field_overflow",+ 1,+ metricTags,+ );+ recordDistribution(+ "langfuse.ingestion.observation_field_overflow.bytes_removed",+ 0,+ metricTags,+ );++ return null;+ });+ if (!uploadResult) {+ return { candidate, overflowedValue: value };+ }++ const mediaReference =+ `@@@langfuseMedia:type=text/plain|id=${uploadResult.mediaId}` ++ `|source=${OBSERVATION_FIELD_SIZE_LIMIT_MEDIA_SOURCE}@@@`;+ const metricTags = { field, outcome: uploadResult.outcome };++ recordIncrement(+ "langfuse.ingestion.observation_field_overflow",+ 1,+ metricTags,+ );+ recordDistribution(+ "langfuse.ingestion.observation_field_overflow.bytes_removed",+ Math.max(originalBytes - Buffer.byteLength(mediaReference, "utf8"), 0),+ metricTags,+ );++ return { candidate, overflowedValue: mediaReference };+}diff --git a/worker/src/queues/otelIngestionQueue.ts b/worker/src/queues/otelIngestionQueue.tsindex ec0296ed18..4d0da1994b 100644--- a/worker/src/queues/otelIngestionQueue.ts+++ b/worker/src/queues/otelIngestionQueue.ts@@ -615,7 +615,7 @@ export const otelIngestionQueueProcessorBuilder = (// Step 3: Write to events table (independent of eval scheduling)if (shouldWriteToEventsTable) {try {- ingestionService.writeEventRecord(eventRecord);+ await ingestionService.writeEventRecord(eventRecord);} catch (error) {traceException(error);logger.error(diff --git a/worker/src/services/IngestionService/index.ts b/worker/src/services/IngestionService/index.tsindex 4b517b80e7..016985945e 100644--- a/worker/src/services/IngestionService/index.ts+++ b/worker/src/services/IngestionService/index.ts@@ -67,6 +67,7 @@ import {import { randomUUID } from "crypto";import { SpanKind } from "@opentelemetry/api";import { ClickhouseReadSkipCache } from "../../utils/clickhouseReadSkipCache";+import { applyObservationFieldOverflow } from "../../features/observation-field-overflow/processObservationFieldOverflow";/*** Parse a value to a UInt16-compatible number (0–65535).@@ -430,6 +431,8 @@ export class IngestionService {/*** Writes an event record directly to the events_full table.* A materialized view auto-populates events_core from events_full.+ * Legacy observation writes and staging-based dual writes intentionally do+ * not use field overflow.* Use createEventRecord() first to get the record, then call this to write.** Enqueues a new record whose `event_bytes` describes the final normalized@@ -438,10 +441,14 @@ export class IngestionService {** @param eventRecord - The event record to write*/- public writeEventRecord(eventRecord: EventRecordInsertType): void {+ public async writeEventRecord(+ eventRecord: EventRecordInsertType,+ ): Promise<void> {+ const persistedRecord = await applyObservationFieldOverflow(eventRecord);+this.clickHouseWriter.addToQueue(TableName.EventsFull,- withSerializedEventByteLength(eventRecord),+ withSerializedEventByteLength(persistedRecord),);}diff --git a/worker/src/services/IngestionService/tests/IngestionService.integration.test.ts b/worker/src/services/IngestionService/tests/IngestionService.integration.test.tsindex 3bf28b3a92..b069bb7a79 100644--- a/worker/src/services/IngestionService/tests/IngestionService.integration.test.ts+++ b/worker/src/services/IngestionService/tests/IngestionService.integration.test.ts@@ -173,7 +173,9 @@ describe("Ingestion end-to-end tests", () => {true,);- eventRecords.forEach((record) => ingestionService.writeEventRecord(record));+ await Promise.all(+ eventRecords.map((record) => ingestionService.writeEventRecord(record)),+ );await clickhouseWriter.flushAll(true);await waitForExpect(async () => {diff --git a/worker/src/services/IngestionService/tests/IngestionService.unit.test.ts b/worker/src/services/IngestionService/tests/IngestionService.unit.test.tsindex 7a01d630a8..633b7b5897 100644--- a/worker/src/services/IngestionService/tests/IngestionService.unit.test.ts+++ b/worker/src/services/IngestionService/tests/IngestionService.unit.test.ts@@ -1,4 +1,16 @@-import { expect, describe, it, vi } from "vitest";+import { beforeEach, expect, describe, it, vi } from "vitest";++const mocks = vi.hoisted(() => ({+ applyObservationFieldOverflow: vi.fn(),+}));++vi.mock(+ "../../../features/observation-field-overflow/processObservationFieldOverflow",+ () => ({+ applyObservationFieldOverflow: mocks.applyObservationFieldOverflow,+ }),+);+import { IngestionService } from "../../IngestionService";import {convertDateToClickhouseDateTime,@@ -9,6 +21,13 @@ import {import { TableName } from "../../ClickhouseWriter";describe("IngestionService unit tests", () => {+ beforeEach(() => {+ mocks.applyObservationFieldOverflow.mockReset();+ mocks.applyObservationFieldOverflow.mockImplementation(+ async (eventRecord) => eventRecord,+ );+ });+it("writes the final serialized event size instead of the raw OTEL span size", async () => {const addToQueue = vi.fn();const ingestionService = new IngestionService(@@ -40,7 +59,7 @@ describe("IngestionService unit tests", () => {expect(eventRecord.event_bytes).toBe(rawOtelSpanBytes);- ingestionService.writeEventRecord(eventRecord);+ await ingestionService.writeEventRecord(eventRecord);expect(addToQueue).toHaveBeenCalledOnce();const queuedRecord = addToQueue.mock.calls[0]?.[1];@@ -54,6 +73,125 @@ describe("IngestionService unit tests", () => {expect(eventBytes).toBeLessThan(rawOtelSpanBytes);});+ it("overflows only the direct events_full copy and preserves the enriched record", async () => {+ const addToQueue = vi.fn();+ const ingestionService = new IngestionService(+ {} as any,+ {} as any,+ { addToQueue } as any,+ {} as any,+ );+ const eventRecord = await ingestionService.createEventRecord(+ {+ projectId: "project-id",+ traceId: "trace-id",+ spanId: "observation-id",+ parentSpanId: "",+ name: "overflow-copy",+ type: "SPAN",+ environment: "default",+ startTimeISO: "2026-07-22T00:00:00.000Z",+ endTimeISO: "2026-07-22T00:00:01.000Z",+ input: "original input",+ output: "original output",+ metadata: { keep: "small", large: { nested: "large" } },+ source: "otel",+ eventBytes: 1234,+ },+ "raw-event.json",+ );+ mocks.applyObservationFieldOverflow.mockResolvedValueOnce({+ ...eventRecord,+ input:+ "@@@langfuseMedia:type=text/plain|id=input-media|source=field_size_limit@@@",+ metadata_values: [+ "small",+ "@@@langfuseMedia:type=text/plain|id=metadata-media|source=field_size_limit@@@",+ ],+ });++ await ingestionService.writeEventRecord(eventRecord);++ expect(mocks.applyObservationFieldOverflow).toHaveBeenCalledWith(+ eventRecord,+ );+ expect(eventRecord.input).toBe("original input");+ expect(eventRecord.metadata_names).toEqual(["keep", "large.nested"]);+ expect(addToQueue).toHaveBeenCalledOnce();+ expect(addToQueue.mock.calls[0]?.[1]).toMatchObject({+ input: expect.stringContaining("input-media"),+ metadata_names: ["keep", "large.nested"],+ metadata_values: ["small", expect.stringContaining("metadata-media")],+ });+ });++ it("does not overflow legacy observation or dual-write staging records", async () => {+ const addToQueue = vi.fn();+ const ingestionService = new IngestionService(+ {} as any,+ {} as any,+ { addToQueue } as any,+ {} as any,+ );+ const timestamp = "2026-07-22T00:00:00.000Z";+ const input = "x".repeat(11);+ const output = "y".repeat(11);+ const metadataValue = "z".repeat(11);+ const observationEventList: ObservationEvent[] = [+ {+ id: "event-id",+ timestamp,+ type: "generation-create",+ body: {+ id: "observation-id",+ traceId: "trace-id",+ startTime: timestamp,+ input,+ output,+ metadata: { large: metadataValue },+ environment: "default",+ },+ },+ ];++ vi.spyOn(ingestionService as any, "getClickhouseRecord").mockResolvedValue(+ null,+ );+ vi.spyOn(ingestionService as any, "getPrompt").mockResolvedValue(null);+ vi.spyOn(ingestionService as any, "getGenerationUsage").mockResolvedValue(+ {},+ );++ await (ingestionService as any).processObservationEventList({+ projectId: "project-id",+ entityId: "observation-id",+ createdAtTimestamp: new Date(timestamp),+ observationEventList,+ writeToStagingTables: true,+ attribution: {+ ingestionApiKey: "api-key",+ ingestionSdkName: "sdk",+ ingestionSdkVersion: "1.0.0",+ },+ });++ expect(mocks.applyObservationFieldOverflow).not.toHaveBeenCalled();+ for (const table of [+ TableName.Observations,+ TableName.ObservationsBatchStaging,+ ]) {+ expect(+ addToQueue.mock.calls.find(+ ([queuedTable]) => queuedTable === table,+ )?.[1],+ ).toMatchObject({+ input,+ output,+ metadata: { large: metadataValue },+ });+ }+ });+it("correctly sorts events in ascending order by timestamp", async () => {const firstTrace = { timestamp: 1, type: "observation-create" };const secondTrace = { timestamp: 1, type: "observation-update" };diff --git a/worker/src/services/IngestionService/tests/calculateTokenCost.unit.test.ts b/worker/src/services/IngestionService/tests/calculateTokenCost.unit.test.tsindex 57bec634b0..052c4b8ab2 100644--- a/worker/src/services/IngestionService/tests/calculateTokenCost.unit.test.ts+++ b/worker/src/services/IngestionService/tests/calculateTokenCost.unit.test.ts@@ -1317,7 +1317,7 @@ describe("Token Cost Calculation", () => {events[0],"testfile.txt",);- (mockIngestionService as any).writeEventRecord(eventRecord);+ await (mockIngestionService as any).writeEventRecord(eventRecord);expect(mockAddToClickhouseWriter).toHaveBeenCalled();const args = mockAddToClickhouseWriter.mock.calls[0];@@ -1354,7 +1354,7 @@ describe("Token Cost Calculation", () => {events[0],"testfile.txt",);- (mockIngestionService as any).writeEventRecord(eventRecord);+ await (mockIngestionService as any).writeEventRecord(eventRecord);// Invalid values should be ignoredexpect(mockAddToClickhouseWriter).toHaveBeenCalled();