Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

fix(web): prevent crash on invalid JSONPath in dataset mapping editor (#13253)

Tobias Wochingercd3d02b75f23
diff --git a/packages/shared/src/features/batchAction/applyFieldMapping.ts b/packages/shared/src/features/batchAction/applyFieldMapping.ts
index 217f6b2d85..539a32305d 100644
--- a/packages/shared/src/features/batchAction/applyFieldMapping.ts
+++ b/packages/shared/src/features/batchAction/applyFieldMapping.ts
@@ -22,8 +22,22 @@ export type MappingError = {
message: string;
};
+export type JsonPathMissInfo = {
+ sourceField: SourceField;
+ jsonPath: string;
+ mappingKey: string | null;
+};
+
+export type JsonPathErrorInfo = JsonPathMissInfo & { message: string };
+
+export type FieldMappingResult = {
+ value: unknown;
+ misses: JsonPathMissInfo[];
+ errors: JsonPathErrorInfo[];
+};
+
/**
- * Test if a JSON path is valid against the given data
+ * Test if a JSONPath is valid against the given data
*/
export function testJsonPath(props: { jsonPath: string; data: unknown }): {
success: boolean;
@@ -43,7 +57,7 @@ export function testJsonPath(props: { jsonPath: string; data: unknown }): {
}
/**
- * Evaluate a JSON path against the given data and return the result
+ * Evaluate a JSONPath against the given data and return the result
*/
export function evaluateJsonPath(data: unknown, jsonPath: string): unknown {
const parsed = typeof data === "string" ? parseJsonPrioritised(data) : data;
@@ -58,7 +72,7 @@ export function evaluateJsonPath(data: unknown, jsonPath: string): unknown {
}
/**
- * Check if a value is a JSON path (starts with $)
+ * Check if a value is a JSONPath (starts with $)
*/
export function isJsonPath(value: string): boolean {
return value.startsWith("$");
@@ -88,93 +102,116 @@ export function applyFieldMappingConfig(props: {
observation: ObservationData;
config: FieldMappingConfig;
defaultSourceField: SourceField;
- onJsonPathMiss?: (info: {
- sourceField: SourceField;
- jsonPath: string;
- mappingKey: string | null;
- }) => void;
-}): unknown {
- const { observation, config, defaultSourceField, onJsonPathMiss } = props;
+}): FieldMappingResult {
+ const { observation, config, defaultSourceField } = props;
+ const misses: JsonPathMissInfo[] = [];
+ const errors: JsonPathErrorInfo[] = [];
+
+ const safeEvaluate = (
+ sourceField: SourceField,
+ jsonPath: string,
+ mappingKey: string | null,
+ ): { success: true; value: unknown } | { success: false } => {
+ try {
+ return {
+ success: true,
+ value: evaluateJsonPath(observation[sourceField], jsonPath),
+ };
+ } catch (error) {
+ errors.push({
+ sourceField,
+ jsonPath,
+ mappingKey,
+ message: error instanceof Error ? error.message : "Invalid JSONPath",
+ });
+ return { success: false };
+ }
+ };
+
+ const withValue = (value: unknown): FieldMappingResult => ({
+ value,
+ misses,
+ errors,
+ });
switch (config.mode) {
case "full":
- // Return the full source field
- return observation[defaultSourceField];
+ return withValue(observation[defaultSourceField]);
case "none":
- // Return null (will be written as Prisma.DbNull)
- return null;
+ // null is written as Prisma.DbNull
+ return withValue(null);
- case "custom":
- if (!config.custom) {
- return observation[defaultSourceField];
- }
+ case "custom": {
+ if (!config.custom) return withValue(observation[defaultSourceField]);
if (config.custom.type === "root") {
- // Root mode: extract single value using JSON path
const rootConfig = config.custom.rootConfig;
- if (!rootConfig) {
- return observation[defaultSourceField];
- }
+ if (!rootConfig) return withValue(observation[defaultSourceField]);
- const sourceData = observation[rootConfig.sourceField];
- const result = evaluateJsonPath(sourceData, rootConfig.jsonPath);
- if (result === undefined && onJsonPathMiss) {
- onJsonPathMiss({
+ const evaluated = safeEvaluate(
+ rootConfig.sourceField,
+ rootConfig.jsonPath,
+ null,
+ );
+ if (!evaluated.success) return withValue(undefined);
+ if (evaluated.value === undefined) {
+ misses.push({
sourceField: rootConfig.sourceField,
jsonPath: rootConfig.jsonPath,
mappingKey: null,
});
}
- return result;
+ return withValue(evaluated.value);
}
if (config.custom.type === "keyValueMap") {
- // Key-value map mode: build object from entries
- // Supports dot notation for nested objects (e.g., "context.user_id")
const keyValueMapConfig = config.custom.keyValueMapConfig;
if (!keyValueMapConfig || keyValueMapConfig.entries.length === 0) {
- return observation[defaultSourceField];
+ return withValue(observation[defaultSourceField]);
}
const result: Record<string, unknown> = {};
for (const entry of keyValueMapConfig.entries) {
- // Skip entries with empty values
- if (!entry.value && entry.value !== "") {
- continue;
- }
+ if (!entry.value && entry.value !== "") continue;
let resolvedValue: unknown;
if (isJsonPath(entry.value)) {
- // It's a JSON path - evaluate it
- const sourceData = observation[entry.sourceField];
- resolvedValue = evaluateJsonPath(sourceData, entry.value);
- if (resolvedValue === undefined && onJsonPathMiss) {
- onJsonPathMiss({
- sourceField: entry.sourceField,
- jsonPath: entry.value,
- mappingKey: entry.key,
- });
+ const evaluated = safeEvaluate(
+ entry.sourceField,
+ entry.value,
+ entry.key,
+ );
+ if (!evaluated.success) {
+ resolvedValue = undefined;
+ } else {
+ resolvedValue = evaluated.value;
+ if (resolvedValue === undefined) {
+ misses.push({
+ sourceField: entry.sourceField,
+ jsonPath: entry.value,
+ mappingKey: entry.key,
+ });
+ }
}
} else {
- // It's a literal string (including empty string)
resolvedValue = entry.value;
}
- // Use dot notation path setter for nested objects
if (entry.key.includes(".")) {
setNestedValue(result, entry.key, resolvedValue);
} else {
result[entry.key] = resolvedValue;
}
}
- return result;
+ return withValue(result);
}
- return observation[defaultSourceField];
+ return withValue(observation[defaultSourceField]);
+ }
default:
- return observation[defaultSourceField];
+ return withValue(observation[defaultSourceField]);
}
}
@@ -214,47 +251,45 @@ export function applyFullMapping(props: {
const results: Record<string, unknown> = {};
for (const field of fields) {
- const onJsonPathMiss = (info: {
- sourceField: SourceField;
- jsonPath: string;
- mappingKey: string | null;
- }) => {
- errors.push({
- type: "json_path_miss",
- targetField: field.key,
- sourceField: info.sourceField,
- jsonPath: info.jsonPath,
- mappingKey: info.mappingKey,
- message: `JSON path "${info.jsonPath}" did not match any data in "${info.sourceField}"${info.mappingKey ? ` (key: "${info.mappingKey}")` : ""}`,
- });
- };
-
try {
- results[field.key] = applyFieldMappingConfig({
+ const result = applyFieldMappingConfig({
observation,
config: field.config,
defaultSourceField: field.defaultSourceField,
- onJsonPathMiss,
});
- } catch (error) {
- // Capture rare JSONPath evaluation errors (e.g. malformed filter expressions)
- const sourceField =
- field.config.mode === "custom" && field.config.custom?.type === "root"
- ? (field.config.custom.rootConfig?.sourceField ??
- field.defaultSourceField)
- : field.defaultSourceField;
- const jsonPath =
- field.config.mode === "custom" && field.config.custom?.type === "root"
- ? (field.config.custom.rootConfig?.jsonPath ?? "")
- : "";
+ results[field.key] = result.value;
+
+ for (const miss of result.misses) {
+ errors.push({
+ type: "json_path_miss",
+ targetField: field.key,
+ sourceField: miss.sourceField,
+ jsonPath: miss.jsonPath,
+ mappingKey: miss.mappingKey,
+ message: `JSONPath "${miss.jsonPath}" did not match any data in "${miss.sourceField}"${miss.mappingKey ? ` (key: "${miss.mappingKey}")` : ""}`,
+ });
+ }
+ for (const err of result.errors) {
+ errors.push({
+ type: "json_path_error",
+ targetField: field.key,
+ sourceField: err.sourceField,
+ jsonPath: err.jsonPath,
+ mappingKey: err.mappingKey,
+ message: `JSONPath evaluation error for "${field.key}"${err.mappingKey ? ` (key: "${err.mappingKey}")` : ""}: ${err.message}`,
+ });
+ }
+ } catch (error) {
+ // Isolate per-field faults so a throw from one mapping doesn't abort
+ // the remaining fields on the same observation.
errors.push({
type: "json_path_error",
targetField: field.key,
- sourceField,
- jsonPath,
+ sourceField: field.defaultSourceField,
+ jsonPath: "",
mappingKey: null,
- message: `JSON path evaluation error for "${field.key}": ${error instanceof Error ? error.message : "Unknown error"}`,
+ message: `JSONPath evaluation error for "${field.key}": ${error instanceof Error ? error.message : "Unknown error"}`,
});
results[field.key] = undefined;
}
@@ -269,7 +304,7 @@ export function applyFullMapping(props: {
}
/**
- * Generate autocomplete suggestions for JSON paths based on the data structure
+ * Generate autocomplete suggestions for JSONPaths based on the data structure
*/
export function generateJsonPathSuggestions(
data: unknown,
diff --git a/web/src/features/batch-actions/components/AddObservationsToDatasetDialog/FinalPreviewStep.tsx b/web/src/features/batch-actions/components/AddObservationsToDatasetDialog/FinalPreviewStep.tsx
index 4cccea0e30..acfe0dcd51 100644
--- a/web/src/features/batch-actions/components/AddObservationsToDatasetDialog/FinalPreviewStep.tsx
+++ b/web/src/features/batch-actions/components/AddObservationsToDatasetDialog/FinalPreviewStep.tsx
@@ -1,11 +1,28 @@
import { useMemo } from "react";
import { Button } from "@/src/components/ui/button";
-import { AlertTriangle, Pencil } from "lucide-react";
+import { Pencil } from "lucide-react";
import { JSONView } from "@/src/components/ui/CodeJsonViewer";
import { cn } from "@/src/utils/tailwind";
import type { FinalPreviewStepProps, DialogStep } from "./types";
import { applyFullMapping } from "@langfuse/shared";
import type { MappingError } from "@langfuse/shared";
+import {
+ IssueBanner,
+ issueCardVariants,
+ issueChromeVariants,
+ issueIcons,
+ issueTextVariants,
+ type IssueVariant,
+} from "@/src/features/batch-actions/components/AddObservationsToDatasetDialog/components/IssueBanner";
+
+const STEP_FOR_FIELD: Record<string, DialogStep> = {
+ input: "input-mapping",
+ expectedOutput: "output-mapping",
+ metadata: "metadata-mapping",
+};
+
+const fieldLabel = (field: string) =>
+ field === "expectedOutput" ? "expected output" : field;
export function FinalPreviewStep({
dataset,
@@ -14,7 +31,6 @@ export function FinalPreviewStep({
totalCount,
onEditStep,
}: FinalPreviewStepProps) {
- // Compute the full preview
const previewResult = useMemo(() => {
if (!observationData) return null;
@@ -28,26 +44,22 @@ export function FinalPreviewStep({
});
}, [observationData, mapping]);
- // Group errors by target field
- const errorsByField = useMemo(() => {
- const errors = previewResult?.errors ?? [];
- const grouped: Record<string, MappingError[]> = {};
- for (const err of errors) {
- if (!grouped[err.targetField]) {
- grouped[err.targetField] = [];
+ const { errorsByField, missesByField, errorFields, missFields } =
+ useMemo(() => {
+ const errorsByField: Record<string, MappingError[]> = {};
+ const missesByField: Record<string, MappingError[]> = {};
+ for (const err of previewResult?.errors ?? []) {
+ const bucket =
+ err.type === "json_path_error" ? errorsByField : missesByField;
+ (bucket[err.targetField] ??= []).push(err);
}
- grouped[err.targetField].push(err);
- }
- return grouped;
- }, [previewResult?.errors]);
-
- const hasWarnings = (previewResult?.errors?.length ?? 0) > 0;
-
- const stepForField: Record<string, DialogStep> = {
- input: "input-mapping" as DialogStep,
- expectedOutput: "output-mapping" as DialogStep,
- metadata: "metadata-mapping" as DialogStep,
- };
+ return {
+ errorsByField,
+ missesByField,
+ errorFields: Object.keys(errorsByField),
+ missFields: Object.keys(missesByField),
+ };
+ }, [previewResult?.errors]);
return (
<div className="h-[62vh] space-y-6 p-6">
@@ -60,40 +72,32 @@ export function FinalPreviewStep({
</p>
</div>
- {/* Overall warning banner */}
- {hasWarnings && (
- <div className="rounded-md border border-amber-500/50 bg-amber-50 p-3 dark:bg-amber-950/30">
- <div className="flex items-start gap-2">
- <AlertTriangle className="mt-0.5 h-4 w-4 shrink-0 text-amber-600 dark:text-amber-500" />
- <div className="space-y-1">
- <p className="text-sm font-medium text-amber-600 dark:text-amber-500">
- Some JSON paths did not match the preview observation
- </p>
- <p className="text-xs text-amber-600/80 dark:text-amber-500/80">
- Observations with failed mappings will be skipped during
- processing.
- </p>
- <div className="flex flex-wrap gap-2 pt-1">
- {Object.entries(errorsByField).map(([field]) => (
- <Button
- key={field}
- variant="link"
- size="sm"
- className="h-auto p-0 text-xs text-amber-600 underline dark:text-amber-500"
- onClick={() => {
- const step = stepForField[field];
- if (step) onEditStep(step);
- }}
- >
- Edit{" "}
- {field === "expectedOutput" ? "expected output" : field}{" "}
- mapping
- </Button>
- ))}
- </div>
- </div>
- </div>
- </div>
+ {errorFields.length > 0 && (
+ <IssueBanner
+ variant="error"
+ title="Some JSONPaths are invalid"
+ description="Items using these mappings will be skipped during processing."
+ >
+ <EditMappingActions
+ variant="error"
+ fields={errorFields}
+ onEditStep={onEditStep}
+ />
+ </IssueBanner>
+ )}
+
+ {missFields.length > 0 && (
+ <IssueBanner
+ variant="warning"
+ title="Some JSONPaths did not match the preview observation"
+ description="Observations with failed mappings will be skipped during processing."
+ >
+ <EditMappingActions
+ variant="warning"
+ fields={missFields}
+ onEditStep={onEditStep}
+ />
+ </IssueBanner>
)}
<div className="text-muted-foreground text-sm">
@@ -108,28 +112,26 @@ export function FinalPreviewStep({
</div>
) : (
<div className="space-y-4">
- {/* Input Preview */}
<PreviewCard
label="Input"
data={previewResult?.input}
- onEdit={() => onEditStep("input-mapping" as DialogStep)}
- errors={errorsByField["input"]}
+ onEdit={() => onEditStep("input-mapping")}
+ pathErrors={errorsByField["input"]}
+ pathMisses={missesByField["input"]}
/>
-
- {/* Expected Output Preview */}
<PreviewCard
label="Expected Output"
data={previewResult?.expectedOutput}
- onEdit={() => onEditStep("output-mapping" as DialogStep)}
- errors={errorsByField["expectedOutput"]}
+ onEdit={() => onEditStep("output-mapping")}
+ pathErrors={errorsByField["expectedOutput"]}
+ pathMisses={missesByField["expectedOutput"]}
/>
-
- {/* Metadata Preview */}
<PreviewCard
label="Metadata"
data={previewResult?.metadata}
- onEdit={() => onEditStep("metadata-mapping" as DialogStep)}
- errors={errorsByField["metadata"]}
+ onEdit={() => onEditStep("metadata-mapping")}
+ pathErrors={errorsByField["metadata"]}
+ pathMisses={missesByField["metadata"]}
/>
</div>
)}
@@ -137,24 +139,65 @@ export function FinalPreviewStep({
);
}
+function EditMappingActions({
+ variant,
+ fields,
+ onEditStep,
+}: {
+ variant: IssueVariant;
+ fields: string[];
+ onEditStep: (step: DialogStep) => void;
+}) {
+ return (
+ <div className="flex flex-wrap gap-2 pt-1">
+ {fields.map((field) => (
+ <Button
+ key={field}
+ variant="link"
+ size="sm"
+ className={cn(
+ "h-auto p-0 text-xs underline",
+ issueTextVariants({ variant }),
+ )}
+ onClick={() => {
+ const step = STEP_FOR_FIELD[field];
+ if (step) onEditStep(step);
+ }}
+ >
+ Edit {fieldLabel(field)} mapping
+ </Button>
+ ))}
+ </div>
+ );
+}
+
type PreviewCardProps = {
label: string;
data: unknown;
onEdit: () => void;
- errors?: MappingError[];
+ pathErrors?: MappingError[];
+ pathMisses?: MappingError[];
};
-function PreviewCard({ label, data, onEdit, errors }: PreviewCardProps) {
- const hasErrors = errors && errors.length > 0;
+function PreviewCard({
+ label,
+ data,
+ onEdit,
+ pathErrors = [],
+ pathMisses = [],
+}: PreviewCardProps) {
+ const variant: IssueVariant | null =
+ pathErrors.length > 0 ? "error" : pathMisses.length > 0 ? "warning" : null;
+ const Icon = variant ? issueIcons[variant] : null;
return (
- <div
- className={cn("rounded-lg border", hasErrors && "border-amber-500/50")}
- >
+ <div className={issueCardVariants({ variant: variant ?? "none" })}>
<div className="bg-muted/30 flex items-center justify-between border-b px-4 py-2">
<span className="flex items-center gap-1.5 text-sm font-medium">
- {hasErrors && (
- <AlertTriangle className="h-3.5 w-3.5 text-amber-600 dark:text-amber-500" />
+ {Icon && variant && (
+ <Icon
+ className={cn("h-3.5 w-3.5", issueTextVariants({ variant }))}
+ />
)}
{label}
</span>
@@ -175,12 +218,20 @@ function PreviewCard({ label, data, onEdit, errors }: PreviewCardProps) {
<JSONView json={data} className="text-xs" />
)}
</div>
- {hasErrors && (
- <div className="border-t border-amber-500/50 bg-amber-50 px-4 py-2 dark:bg-amber-950/30">
- <p className="text-xs text-amber-600 dark:text-amber-500">
- {errors.length} path{errors.length !== 1 ? "s" : ""} did not match
- in preview observation. These items will be skipped during
- processing.
+ {variant && (
+ <div
+ className={cn("border-t px-4 py-2", issueChromeVariants({ variant }))}
+ >
+ <p className="text-xs">
+ {[
+ pathErrors.length > 0 &&
+ `${pathErrors.length} path${pathErrors.length !== 1 ? "s have" : " has"} invalid syntax`,
+ pathMisses.length > 0 &&
+ `${pathMisses.length} path${pathMisses.length !== 1 ? "s" : ""} did not match in preview observation`,
+ ]
+ .filter(Boolean)
+ .join("; ")}
+ . These items will be skipped during processing.
</p>
</div>
)}
diff --git a/web/src/features/batch-actions/components/AddObservationsToDatasetDialog/components/CustomMappingEditor.tsx b/web/src/features/batch-actions/components/AddObservationsToDatasetDialog/components/CustomMappingEditor.tsx
index 83166864e5..2413de7aed 100644
--- a/web/src/features/batch-actions/components/AddObservationsToDatasetDialog/components/CustomMappingEditor.tsx
+++ b/web/src/features/batch-actions/components/AddObservationsToDatasetDialog/components/CustomMappingEditor.tsx
@@ -168,7 +168,7 @@ export function CustomMappingEditor({
</div>
</div>
<div>
- <Label className="text-sm font-medium">JSON Path</Label>
+ <Label className="text-sm font-medium">JSONPath</Label>
<div className="mt-1">
<JsonPathInput
value={config.rootConfig?.jsonPath ?? "$."}
@@ -180,7 +180,7 @@ export function CustomMappingEditor({
/>
</div>
<p className="text-muted-foreground p-1 text-xs">
- Start with $. to use a JSON path (e.g., $.field)
+ Start with $. to use a JSONPath (e.g., $.field)
</p>
</div>
</div>
@@ -191,7 +191,7 @@ export function CustomMappingEditor({
<Label className="text-sm font-medium">Key-value mappings</Label>
<p className="text-muted-foreground text-xs">
Build an object with custom keys. Values starting with $ are treated
- as JSON paths.
+ as JSONPaths.
</p>
<div className="space-y-3">
@@ -343,7 +343,7 @@ function KeyValueEntryRow({
)}
<p className="text-muted-foreground pt-1 text-xs">
- Start with $. to use a JSON path (e.g., $.field)
+ Start with $. to use a JSONPath (e.g., $.field)
</p>
</div>
</div>
diff --git a/web/src/features/batch-actions/components/AddObservationsToDatasetDialog/components/IssueBanner.tsx b/web/src/features/batch-actions/components/AddObservationsToDatasetDialog/components/IssueBanner.tsx
new file mode 100644
index 0000000000..dc391960e3
--- /dev/null
+++ b/web/src/features/batch-actions/components/AddObservationsToDatasetDialog/components/IssueBanner.tsx
@@ -0,0 +1,106 @@
+import { type ReactNode } from "react";
+import { AlertCircle, AlertTriangle, type LucideIcon } from "lucide-react";
+import { cva } from "class-variance-authority";
+import { cn } from "@/src/utils/tailwind";
+
+export type IssueVariant = "error" | "warning";
+
+/**
+ * Colored chrome — border + bg + text — applied to elements that carry a full
+ * issue notice (banner, list root, card footer strip). Each consumer composes
+ * this with its own layout classes.
+ */
+export const issueChromeVariants = cva("", {
+ variants: {
+ variant: {
+ error: "border-destructive/50 bg-destructive/10 text-destructive",
+ warning:
+ "border-amber-500/50 bg-amber-50 text-amber-600 dark:bg-amber-950/30 dark:text-amber-500",
+ },
+ },
+});
+
+/** Outer card border that picks up a variant accent only when there is an issue. */
+export const issueCardVariants = cva("rounded-lg border", {
+ variants: {
+ variant: {
+ none: "",
+ error: "border-destructive/50",
+ warning: "border-amber-500/50",
+ },
+ },
+ defaultVariants: { variant: "none" },
+});
+
+/**
+ * Text color for inner elements that set their own color and therefore do not
+ * inherit from a variant-styled ancestor (e.g. Button's `variant="link"` that
+ * forces `text-primary`).
+ */
+export const issueTextVariants = cva("", {
+ variants: {
+ variant: {
+ error: "text-destructive",
+ warning: "text-amber-600 dark:text-amber-500",
+ },
+ },
+});
+
+export const issueIcons: Record<IssueVariant, LucideIcon> = {
+ error: AlertCircle,
+ warning: AlertTriangle,
+};
+
+export function IssueBanner({
+ variant,
+ title,
+ description,
+ children,
+}: {
+ variant: IssueVariant;
+ title: string;
+ description?: string;
+ children?: ReactNode;
+}) {
+ const Icon = issueIcons[variant];
+ return (
+ <div
+ className={cn("rounded-md border p-3", issueChromeVariants({ variant }))}
+ >
+ <div className="flex items-start gap-2">
+ <Icon className="mt-0.5 h-4 w-4 shrink-0" />
+ <div className="space-y-1">
+ <p className="text-sm font-medium">{title}</p>
+ {description && <p className="text-xs opacity-80">{description}</p>}
+ {children}
+ </div>
+ </div>
+ </div>
+ );
+}
+
+export function IssueList({
+ variant,
+ title,
+ children,
+}: {
+ variant: IssueVariant;
+ title: string;
+ children: ReactNode;
+}) {
+ return (
+ <div
+ className={cn(
+ "max-h-[5vh] overflow-y-auto rounded-md border p-2",
+ issueChromeVariants({ variant }),
+ )}
+ >
+ <p className="mb-1 text-xs font-medium">{title}</p>
+ <ul className="space-y-0.5">{children}</ul>
+ </div>
+ );
+}
+
+export function IssueItem({ children }: { children: ReactNode }) {
+ return <li className="text-xs">{children}</li>;
+}
diff --git a/web/src/features/batch-actions/components/AddObservationsToDatasetDialog/components/JsonPathInput.tsx b/web/src/features/batch-actions/components/AddObservationsToDatasetDialog/components/JsonPathInput.tsx
index 127488c90c..d50b9eba2e 100644
--- a/web/src/features/batch-actions/components/AddObservationsToDatasetDialog/components/JsonPathInput.tsx
+++ b/web/src/features/batch-actions/components/AddObservationsToDatasetDialog/components/JsonPathInput.tsx
@@ -8,7 +8,7 @@ import { darkTheme } from "@/src/components/editor/dark-theme";
import { cn } from "@/src/utils/tailwind";
import { evaluateJsonPath } from "@langfuse/shared";
-// JSON path language mode for syntax highlighting
+// JSONPath language mode for syntax highlighting
const jsonPathLanguage = StreamLanguage.define({
name: "jsonpath",
startState: () => ({ inBracket: false }),
@@ -101,14 +101,14 @@ export function JsonPathInput({
(newValue: string) => {
onChange(newValue);
- // Try to resolve the JSON path
+ // Try to resolve the JSONPath
if (newValue && newValue.startsWith("$") && parsedSourceData) {
try {
const result = evaluateJsonPath(parsedSourceData, newValue);
setResolveError(null);
setNoMatchWarning(result === undefined);
} catch (e) {
- setResolveError(e instanceof Error ? e.message : "Invalid JSON path");
+ setResolveError(e instanceof Error ? e.message : "Invalid JSONPath");
setNoMatchWarning(false);
}
} else {
diff --git a/web/src/features/batch-actions/components/AddObservationsToDatasetDialog/components/MappingPreviewPanel.tsx b/web/src/features/batch-actions/components/AddObservationsToDatasetDialog/components/MappingPreviewPanel.tsx
index 66930cce13..ce25d74c67 100644
--- a/web/src/features/batch-actions/components/AddObservationsToDatasetDialog/components/MappingPreviewPanel.tsx
+++ b/web/src/features/batch-actions/components/AddObservationsToDatasetDialog/components/MappingPreviewPanel.tsx
@@ -7,6 +7,10 @@ import {
} from "lucide-react";
import { JSONView } from "@/src/components/ui/CodeJsonViewer";
import { Skeleton } from "@/src/components/ui/skeleton";
+import {
+ IssueList,
+ IssueItem,
+} from "@/src/features/batch-actions/components/AddObservationsToDatasetDialog/components/IssueBanner";
import type {
FieldMappingConfig,
SourceField,
@@ -16,6 +20,8 @@ import type {
import {
applyFieldMappingConfig,
validateFieldAgainstSchema,
+ type JsonPathMissInfo,
+ type JsonPathErrorInfo,
} from "@langfuse/shared";
type MappingPreviewPanelProps = {
@@ -60,25 +66,16 @@ export function MappingPreviewPanel({
return observationData[defaultSourceField];
}, [observationData, config, defaultSourceField]);
- // Compute result data and collect JSON path misses
- const { resultData, jsonPathMisses } = useMemo(() => {
+ // Compute result data and collect JSONPath misses / syntax errors
+ const { resultData, jsonPathMisses, jsonPathErrors } = useMemo(() => {
if (!observationData)
return {
resultData: null,
- jsonPathMisses: [] as {
- sourceField: string;
- jsonPath: string;
- mappingKey: string | null;
- }[],
+ jsonPathMisses: [] as JsonPathMissInfo[],
+ jsonPathErrors: [] as JsonPathErrorInfo[],
};
- const misses: {
- sourceField: string;
- jsonPath: string;
- mappingKey: string | null;
- }[] = [];
-
- const data = applyFieldMappingConfig({
+ const result = applyFieldMappingConfig({
observation: {
input: observationData.input,
output: observationData.output,
@@ -86,17 +83,32 @@ export function MappingPreviewPanel({
},
config,
defaultSourceField,
- onJsonPathMiss: (info) => {
- misses.push(info);
- },
});
- return { resultData: data, jsonPathMisses: misses };
+ return {
+ resultData: result.value,
+ jsonPathMisses: result.misses,
+ jsonPathErrors: result.errors,
+ };
}, [observationData, config, defaultSourceField]);
- // Validate result against schema
+ // Validate result against schema, and treat JSONPath syntax errors as validation failures
const validationResult = useMemo(() => {
- // Skip validation if no schema or "none" mode
+ const jsonPathErrorItems: SchemaValidationError[] = jsonPathErrors.map(
+ (err) => ({
+ path: err.mappingKey
+ ? `${err.sourceField} (key: "${err.mappingKey}")`
+ : err.sourceField,
+ message: `Invalid JSONPath "${err.jsonPath}": ${err.message}`,
+ }),
+ );
+
+ // Any JSONPath syntax error blocks the mapping regardless of schema
+ if (jsonPathErrorItems.length > 0) {
+ return { isValid: false, errors: jsonPathErrorItems };
+ }
+
+ // Skip schema validation if no schema or "none" mode
if (!hasSchema || config.mode === "none") {
return { isValid: true, errors: [] as SchemaValidationError[] };
}
@@ -124,10 +136,10 @@ export function MappingPreviewPanel({
})),
};
} catch {
- // If validation fails to run, treat as valid (don't block on validation errors)
+ // If schema validation fails to run, treat as valid (don't block on validation errors)
return { isValid: true, errors: [] as SchemaValidationError[] };
}
- }, [hasSchema, config.mode, resultData, schema]);
+ }, [hasSchema, config.mode, resultData, schema, jsonPathErrors]);
// Track previous validation state to avoid redundant callbacks
const prevValidationRef = useRef<{
@@ -241,7 +253,8 @@ export function MappingPreviewPanel({
{/* Validation status indicator */}
{config.mode !== "none" && (
<div className="flex items-center gap-1">
- {hasSchema && !validationResult.isValid ? (
+ {jsonPathErrors.length > 0 ||
+ (hasSchema && !validationResult.isValid) ? (
<AlertCircle className="text-destructive h-3.5 w-3.5" />
) : jsonPathMisses.length > 0 ? (
<AlertTriangle className="h-3.5 w-3.5 text-amber-600 dark:text-amber-500" />
@@ -253,7 +266,9 @@ export function MappingPreviewPanel({
</div>
<div
className={`bg-background max-h-[21vh] overflow-auto rounded-md border ${
- hasSchema && !validationResult.isValid && config.mode !== "none"
+ (jsonPathErrors.length > 0 ||
+ (hasSchema && !validationResult.isValid)) &&
+ config.mode !== "none"
? "border-destructive"
: jsonPathMisses.length > 0 && config.mode !== "none"
? "border-amber-500/50"
@@ -267,44 +282,47 @@ export function MappingPreviewPanel({
)}
</div>
- {/* Validation errors */}
+ {/* JSONPath syntax errors (always blocking) */}
+ {jsonPathErrors.length > 0 && config.mode !== "none" && (
+ <IssueList variant="error" title="Invalid JSONPath:">
+ {jsonPathErrors.map((err, idx) => (
+ <IssueItem key={idx}>
+ <span className="font-mono">{err.jsonPath}</span>
+ {err.mappingKey ? ` (key: "${err.mappingKey}")` : ""}:{" "}
+ {err.message}
+ </IssueItem>
+ ))}
+ </IssueList>
+ )}
+
+ {/* Schema validation errors (only when no blocking JSONPath errors) */}
{hasSchema &&
- !validationResult.isValid &&
+ jsonPathErrors.length === 0 &&
validationResult.errors.length > 0 && (
- <div className="border-destructive/50 bg-destructive/10 max-h-[5vh] overflow-y-auto rounded-md border p-2">
- <p className="text-destructive mb-1 text-xs font-medium">
- Schema validation errors:
- </p>
- <ul className="space-y-0.5">
- {validationResult.errors.map((error, idx) => (
- <li key={idx} className="text-destructive text-xs">
- <span className="font-mono">{error.path || "root"}</span>:{" "}
- {error.message}
- </li>
- ))}
- </ul>
- </div>
+ <IssueList variant="error" title="Schema validation errors:">
+ {validationResult.errors.map((error, idx) => (
+ <IssueItem key={idx}>
+ <span className="font-mono">{error.path || "root"}</span>:{" "}
+ {error.message}
+ </IssueItem>
+ ))}
+ </IssueList>
)}
- {/* JSON path warnings */}
+ {/* JSONPath warnings */}
{jsonPathMisses.length > 0 && config.mode !== "none" && (
- <div className="max-h-[5vh] overflow-y-auto rounded-md border border-amber-500/50 bg-amber-50 p-2 dark:bg-amber-950/30">
- <p className="mb-1 text-xs font-medium text-amber-600 dark:text-amber-500">
- JSON path warnings (preview observation):
- </p>
- <ul className="space-y-0.5">
- {jsonPathMisses.map((miss, idx) => (
- <li
- key={idx}
- className="text-xs text-amber-600 dark:text-amber-500"
- >
- <span className="font-mono">{miss.jsonPath}</span> did not
- match any data in {miss.sourceField}
- {miss.mappingKey ? ` (key: "${miss.mappingKey}")` : ""}
- </li>
- ))}
- </ul>
- </div>
+ <IssueList
+ variant="warning"
+ title="JSONPath warnings (preview observation):"
+ >
+ {jsonPathMisses.map((miss, idx) => (
+ <IssueItem key={idx}>
+ <span className="font-mono">{miss.jsonPath}</span> did not match
+ any data in {miss.sourceField}
+ {miss.mappingKey ? ` (key: "${miss.mappingKey}")` : ""}
+ </IssueItem>
+ ))}
+ </IssueList>
)}
</div>
</div>
diff --git a/web/src/features/evals/hooks/useExtractVariables.ts b/web/src/features/evals/hooks/useExtractVariables.ts
index b73e7155fd..0404cfc6d2 100644
--- a/web/src/features/evals/hooks/useExtractVariables.ts
+++ b/web/src/features/evals/hooks/useExtractVariables.ts
@@ -1,7 +1,7 @@
import { type PreviewData } from "@/src/features/evals/hooks/usePreviewData";
import { type VariableMapping } from "@/src/features/evals/utils/evaluator-form-utils";
import { api } from "@/src/utils/api";
-import { trpcErrorToast } from "@/src/utils/trpcErrorToast";
+import { showErrorToast } from "@/src/features/notifications/showErrorToast";
import { EvalTargetObject, extractValueFromObject } from "@langfuse/shared";
import { useEffect, useState, useRef } from "react";
@@ -23,6 +23,10 @@ type ExtractedVariable = {
value: unknown;
};
+type ExtractionError =
+ | { kind: "jsonPath"; message: string }
+ | { kind: "unexpected"; message: string };
+
export function useExtractVariables({
variables,
variableMapping,
@@ -39,7 +43,8 @@ export function useExtractVariables({
ExtractedVariable[]
>([]);
const [isExtracting, setIsExtracting] = useState(false);
- const [extractionError, setExtractionError] = useState<Error | null>(null);
+ const [extractionError, setExtractionError] =
+ useState<ExtractionError | null>(null);
const previousMappingRef = useRef<string>("");
// Create a stable string representation of the current mapping for comparison
@@ -54,9 +59,12 @@ export function useExtractVariables({
// Handle error toasts separately to avoid repeated toasts on re-renders
useEffect(() => {
- if (extractionError) {
- trpcErrorToast(extractionError);
- }
+ if (!extractionError) return;
+ const title =
+ extractionError.kind === "jsonPath"
+ ? "Invalid JSONPath in variable mapping"
+ : "Failed to extract variable";
+ showErrorToast(title, extractionError.message, "WARNING");
}, [extractionError]);
useEffect(() => {
@@ -155,7 +163,12 @@ export function useExtractVariables({
mapping.selectedColumnId,
mapping.jsonSelector ?? undefined,
);
- return { variable, value, error };
+ return {
+ variable,
+ value,
+ error,
+ jsonSelector: mapping.jsonSelector ?? null,
+ };
});
// Resolve all promises and update state
@@ -165,7 +178,11 @@ export function useExtractVariables({
(result) => result.error instanceof Error,
);
if (firstError) {
- setExtractionError(firstError.error as Error);
+ const baseMessage = (firstError.error as Error).message;
+ const message = firstError.jsonSelector
+ ? `${firstError.jsonSelector}: ${baseMessage}`
+ : baseMessage;
+ setExtractionError({ kind: "jsonPath", message });
}
setExtractedVariables(results);
// Update the ref to the current mapping string to track changes
@@ -173,7 +190,10 @@ export function useExtractVariables({
})
.catch((error) => {
console.error("Error extracting variables:", error);
- setExtractionError(error);
+ setExtractionError({
+ kind: "unexpected",
+ message: error instanceof Error ? error.message : "Unknown error",
+ });
setExtractedVariables(
variables.map((variable) => ({
variable,
diff --git a/worker/src/__tests__/applyFieldMapping.test.ts b/worker/src/__tests__/applyFieldMapping.test.ts
index 5f4818b9cd..c2fe377bbf 100644
--- a/worker/src/__tests__/applyFieldMapping.test.ts
+++ b/worker/src/__tests__/applyFieldMapping.test.ts
@@ -144,7 +144,7 @@ describe("applyFieldMapping", () => {
defaultSourceField: "input",
});
- expect(result).toEqual(sampleObservation.input);
+ expect(result.value).toEqual(sampleObservation.input);
});
it("should return full output for 'full' mode with output as default", () => {
@@ -154,7 +154,7 @@ describe("applyFieldMapping", () => {
defaultSourceField: "output",
});
- expect(result).toEqual(sampleObservation.output);
+ expect(result.value).toEqual(sampleObservation.output);
});
it("should return full metadata for 'full' mode with metadata as default", () => {
@@ -164,7 +164,7 @@ describe("applyFieldMapping", () => {
defaultSourceField: "metadata",
});
- expect(result).toEqual(sampleObservation.metadata);
+ expect(result.value).toEqual(sampleObservation.metadata);
});
});
@@ -176,7 +176,7 @@ describe("applyFieldMapping", () => {
defaultSourceField: "input",
});
- expect(result).toBeNull();
+ expect(result.value).toBeNull();
});
});
@@ -197,7 +197,7 @@ describe("applyFieldMapping", () => {
defaultSourceField: "input",
});
- expect(result).toBe("What is 2+2?");
+ expect(result.value).toBe("What is 2+2?");
});
it("should allow extracting from different source field", () => {
@@ -216,7 +216,7 @@ describe("applyFieldMapping", () => {
defaultSourceField: "input",
});
- expect(result).toBe("4");
+ expect(result.value).toBe("4");
});
it("should return undefined for non-existent path", () => {
@@ -235,7 +235,7 @@ describe("applyFieldMapping", () => {
defaultSourceField: "input",
});
- expect(result).toBeUndefined();
+ expect(result.value).toBeUndefined();
});
it("should fallback to default source field if no custom config", () => {
@@ -250,7 +250,7 @@ describe("applyFieldMapping", () => {
defaultSourceField: "metadata",
});
- expect(result).toEqual(sampleObservation.metadata);
+ expect(result.value).toEqual(sampleObservation.metadata);
});
});
@@ -283,7 +283,7 @@ describe("applyFieldMapping", () => {
defaultSourceField: "input",
});
- expect(result).toEqual({
+ expect(result.value).toEqual({
prompt: "What is 2+2?",
response: "4",
});
@@ -317,7 +317,7 @@ describe("applyFieldMapping", () => {
defaultSourceField: "input",
});
- expect(result).toEqual({
+ expect(result.value).toEqual({
type: "conversation",
version: "1.0",
});
@@ -357,7 +357,7 @@ describe("applyFieldMapping", () => {
defaultSourceField: "input",
});
- expect(result).toEqual({
+ expect(result.value).toEqual({
prompt: "What is 2+2?",
category: "math",
user: "user-123",
@@ -394,7 +394,7 @@ describe("applyFieldMapping", () => {
defaultSourceField: "input",
});
- expect(result).toEqual({
+ expect(result.value).toEqual({
context: {
user_id: "user-123",
session_id: "session-456",
@@ -424,7 +424,7 @@ describe("applyFieldMapping", () => {
defaultSourceField: "input",
});
- expect(result).toEqual({
+ expect(result.value).toEqual({
a: {
b: {
c: {
@@ -481,7 +481,7 @@ describe("applyFieldMapping", () => {
defaultSourceField: "input",
});
- expect(result).toEqual({
+ expect(result.value).toEqual({
prompt: "What is 2+2?",
context: {
user_id: "user-123",
@@ -528,7 +528,7 @@ describe("applyFieldMapping", () => {
defaultSourceField: "input",
});
- expect(result).toEqual({
+ expect(result.value).toEqual({
prompt: "What is 2+2?",
context: {
user: "user-123",
@@ -565,7 +565,7 @@ describe("applyFieldMapping", () => {
defaultSourceField: "input",
});
- expect(result).toEqual({
+ expect(result.value).toEqual({
settings: {
theme: "dark",
language: "en",
@@ -601,7 +601,7 @@ describe("applyFieldMapping", () => {
defaultSourceField: "input",
});
- expect(result).toEqual({
+ expect(result.value).toEqual({
prompt: "What is 2+2?",
empty_string: "",
});
@@ -637,7 +637,7 @@ describe("applyFieldMapping", () => {
});
// The nested key should overwrite the flat value
- expect(result).toEqual({
+ expect(result.value).toEqual({
context: {
nested: "nested-value",
},
@@ -962,7 +962,7 @@ describe("applyFieldMapping", () => {
defaultSourceField: "input",
});
- expect(result).toBeNull();
+ expect(result.value).toBeNull();
});
it("should handle undefined paths gracefully", () => {
@@ -987,7 +987,7 @@ describe("applyFieldMapping", () => {
defaultSourceField: "input",
});
- expect(result).toEqual({
+ expect(result.value).toEqual({
nonexistent: undefined,
});
});
@@ -1007,7 +1007,7 @@ describe("applyFieldMapping", () => {
defaultSourceField: "input",
});
- expect(result).toEqual(sampleObservation.input);
+ expect(result.value).toEqual(sampleObservation.input);
});
it("should handle no custom config by returning default source", () => {
@@ -1019,7 +1019,158 @@ describe("applyFieldMapping", () => {
defaultSourceField: "metadata",
});
- expect(result).toEqual(sampleObservation.metadata);
+ expect(result.value).toEqual(sampleObservation.metadata);
+ });
+ });
+
+ describe("invalid JSON path syntax", () => {
+ const invalidPath = "$..[?(@.x=)]";
+
+ it("should not throw and report error for invalid root path", () => {
+ const result = applyFieldMappingConfig({
+ observation: sampleObservation,
+ config: {
+ mode: "custom",
+ custom: {
+ type: "root",
+ rootConfig: {
+ sourceField: "input",
+ jsonPath: invalidPath,
+ },
+ },
+ },
+ defaultSourceField: "input",
+ });
+
+ expect(result.value).toBeUndefined();
+ expect(result.errors).toHaveLength(1);
+ expect(result.errors[0]).toMatchObject({
+ sourceField: "input",
+ jsonPath: invalidPath,
+ mappingKey: null,
+ });
+ expect(result.errors[0].message).toBeTruthy();
+ });
+
+ it("should not throw and isolate invalid entries in keyValueMap", () => {
+ const result = applyFieldMappingConfig({
+ observation: sampleObservation,
+ config: {
+ mode: "custom",
+ custom: {
+ type: "keyValueMap",
+ keyValueMapConfig: {
+ entries: [
+ {
+ id: "1",
+ key: "good",
+ sourceField: "input",
+ value: "$.model",
+ },
+ {
+ id: "2",
+ key: "bad",
+ sourceField: "input",
+ value: invalidPath,
+ },
+ ],
+ },
+ },
+ },
+ defaultSourceField: "input",
+ });
+
+ expect(result.value).toEqual({ good: "gpt-4", bad: undefined });
+ expect(result.errors).toHaveLength(1);
+ expect(result.errors[0]).toMatchObject({
+ sourceField: "input",
+ jsonPath: invalidPath,
+ mappingKey: "bad",
+ });
+ });
+
+ it("should collect multiple errors from multiple invalid keyValueMap entries", () => {
+ const secondInvalidPath = "$..[?(@.y<)]";
+
+ const result = applyFieldMappingConfig({
+ observation: sampleObservation,
+ config: {
+ mode: "custom",
+ custom: {
+ type: "keyValueMap",
+ keyValueMapConfig: {
+ entries: [
+ {
+ id: "1",
+ key: "bad_one",
+ sourceField: "input",
+ value: invalidPath,
+ },
+ {
+ id: "2",
+ key: "good",
+ sourceField: "input",
+ value: "$.model",
+ },
+ {
+ id: "3",
+ key: "bad_two",
+ sourceField: "output",
+ value: secondInvalidPath,
+ },
+ ],
+ },
+ },
+ },
+ defaultSourceField: "input",
+ });
+
+ expect(result.value).toEqual({
+ bad_one: undefined,
+ good: "gpt-4",
+ bad_two: undefined,
+ });
+ expect(result.errors).toHaveLength(2);
+ expect(result.errors[0]).toMatchObject({
+ sourceField: "input",
+ jsonPath: invalidPath,
+ mappingKey: "bad_one",
+ });
+ expect(result.errors[1]).toMatchObject({
+ sourceField: "output",
+ jsonPath: secondInvalidPath,
+ mappingKey: "bad_two",
+ });
+ });
+
+ it("applyFullMapping should surface json_path_error for invalid paths", () => {
+ const result = applyFullMapping({
+ observation: sampleObservation,
+ mapping: {
+ input: {
+ mode: "custom",
+ custom: {
+ type: "root",
+ rootConfig: {
+ sourceField: "input",
+ jsonPath: invalidPath,
+ },
+ },
+ },
+ expectedOutput: { mode: "full" },
+ metadata: { mode: "none" },
+ },
+ });
+
+ expect(result.input).toBeUndefined();
+ expect(result.errors).toHaveLength(1);
+ expect(result.errors[0]).toMatchObject({
+ type: "json_path_error",
+ targetField: "input",
+ sourceField: "input",
+ jsonPath: invalidPath,
+ mappingKey: null,
+ });
});
});
});