Skip to content

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

fix(trace): guard markdown rendering against stack overflow on deeply nested payloads (LFE-10604) (#14690)

Nikita Kabardin7495e6eb33f3
diff --git a/web/src/components/ui/MarkdownViewer.tsx b/web/src/components/ui/MarkdownViewer.tsx
index ff7118fe5b..e7aad7acf8 100644
--- a/web/src/components/ui/MarkdownViewer.tsx
+++ b/web/src/components/ui/MarkdownViewer.tsx
@@ -4,6 +4,7 @@ import {
type ReactNode,
type ReactElement,
memo,
+ useMemo,
isValidElement,
Children,
createElement,
@@ -52,6 +53,7 @@ import {
getRenderedInlineMediaIds,
getStandaloneMediaReferenceStrings,
} from "@/src/components/ui/markdown-media.utils";
+import { exceedsMarkdownRenderLimits } from "@/src/components/ui/markdown-render-limits";
type ReactMarkdownNode = ReactMarkdownExtraProps["node"];
type ReactMarkdownNodeChildren = Exclude<
@@ -211,6 +213,30 @@ function MarkdownRenderer({
}) {
const promptReferenceProjectId = usePromptReferenceProjectId();
+ // Guard against payloads that would overflow the JS call stack while
+ // react-markdown recursively walks the parsed tree (crashes Firefox, whose
+ // stack is much smaller than Chrome's). Rendered as plain text instead.
+ // See markdown-render-limits.ts for the mechanism.
+ const tooLargeOrDeep = useMemo(
+ () => exceedsMarkdownRenderLimits(markdown),
+ [markdown],
+ );
+
+ if (tooLargeOrDeep) {
+ return (
+ <div className={cn("space-y-2 overflow-x-auto text-sm", className)}>
+ <div className="text-muted-foreground flex items-center gap-1 text-xs">
+ <Info className="h-3 w-3" />
+ Content is too large or deeply nested to render as markdown.
+ Displaying as plain text.
+ </div>
+ <pre className="text-sm break-words whitespace-pre-wrap">
+ {markdown}
+ </pre>
+ </div>
+ );
+ }
+
// Try to parse markdown content
try {
diff --git a/web/src/components/ui/markdown-render-limits.clienttest.ts b/web/src/components/ui/markdown-render-limits.clienttest.ts
new file mode 100644
index 0000000000..63fba49964
--- /dev/null
+++ b/web/src/components/ui/markdown-render-limits.clienttest.ts
@@ -0,0 +1,96 @@
+import {
+ MARKDOWN_MAX_NESTING_DEPTH,
+ MARKDOWN_MAX_RENDER_BYTES,
+ estimateMarkdownNestingDepth,
+ exceedsMarkdownRenderLimits,
+} from "@/src/components/ui/markdown-render-limits";
+
+describe("estimateMarkdownNestingDepth", () => {
+ it("returns 0 for plain text", () => {
+ expect(estimateMarkdownNestingDepth("just a plain sentence")).toBe(0);
+ expect(estimateMarkdownNestingDepth("")).toBe(0);
+ });
+
+ it("stays low for typical markdown", () => {
+ const doc = [
+ "# Title",
+ "",
+ "Some **bold** and _italic_ and `code` text.",
+ "",
+ "- item one",
+ " - nested item",
+ " - deeper item",
+ "",
+ "> a short quote",
+ "",
+ "1. first",
+ "2. second",
+ ].join("\n");
+ expect(estimateMarkdownNestingDepth(doc)).toBeLessThan(
+ MARKDOWN_MAX_NESTING_DEPTH,
+ );
+ });
+
+ it("counts space-separated blockquote nesting exactly", () => {
+ expect(estimateMarkdownNestingDepth("> > > hi")).toBeGreaterThanOrEqual(3);
+ });
+
+ it("counts tightly-packed blockquote nesting exactly", () => {
+ const depth = 500;
+ expect(
+ estimateMarkdownNestingDepth(">".repeat(depth) + "text"),
+ ).toBeGreaterThanOrEqual(depth);
+ });
+
+ it("catches long emphasis/strikethrough delimiter runs", () => {
+ expect(
+ estimateMarkdownNestingDepth("*".repeat(400)),
+ ).toBeGreaterThanOrEqual(400);
+ expect(
+ estimateMarkdownNestingDepth("~".repeat(400)),
+ ).toBeGreaterThanOrEqual(400);
+ });
+
+ it("catches deeply indented (nested list) content", () => {
+ // Each level adds indentation; a 300-level list indents ~600 columns.
+ const lines = Array.from(
+ { length: 300 },
+ (_, i) => " ".repeat(i) + "- item",
+ );
+ expect(estimateMarkdownNestingDepth(lines.join("\n"))).toBeGreaterThan(
+ MARKDOWN_MAX_NESTING_DEPTH,
+ );
+ });
+
+ it("does not count mid-line dashes or emphasis as nesting", () => {
+ expect(estimateMarkdownNestingDepth("a - b - c - d")).toBe(0);
+ expect(estimateMarkdownNestingDepth("use foo_bar_baz names")).toBeLessThan(
+ 3,
+ );
+ });
+});
+
+describe("exceedsMarkdownRenderLimits", () => {
+ it("allows normal content", () => {
+ expect(exceedsMarkdownRenderLimits("Hello **world**")).toBe(false);
+ expect(exceedsMarkdownRenderLimits("- a\n - b\n - c")).toBe(false);
+ });
+
+ it("flags content over the size preempt", () => {
+ expect(
+ exceedsMarkdownRenderLimits("a".repeat(MARKDOWN_MAX_RENDER_BYTES + 1)),
+ ).toBe(true);
+ });
+
+ it("flags deeply nested content even when small", () => {
+ // A few KB of nested blockquotes overflows the parser/renderer in Firefox.
+ expect(exceedsMarkdownRenderLimits("> ".repeat(2000) + "boom")).toBe(true);
+ expect(exceedsMarkdownRenderLimits("*".repeat(2000))).toBe(true);
+ });
+
+ it("does not flag large-but-shallow markdown under the size cap", () => {
+ const shallow = "word ".repeat(10_000); // ~50KB, depth 0
+ expect(shallow.length).toBeLessThan(MARKDOWN_MAX_RENDER_BYTES);
+ expect(exceedsMarkdownRenderLimits(shallow)).toBe(false);
+ });
+});
diff --git a/web/src/components/ui/markdown-render-limits.ts b/web/src/components/ui/markdown-render-limits.ts
new file mode 100644
index 0000000000..7e779a9d0b
--- /dev/null
+++ b/web/src/components/ui/markdown-render-limits.ts
@@ -0,0 +1,133 @@
+// Safety limits for rendering user/model content as GFM markdown.
+//
+// react-markdown parses content to an mdast tree and then walks it recursively
+// (mdast -> hast conversion and remark plugins such as remark-gfm's
+// autolink-literal, via unist-util-visit). That walk recurses once per level of
+// *nesting depth*. Deeply nested markdown — e.g. long blockquote chains
+// (`> > > …`), nested lists, or long emphasis runs (`***…`) — therefore recurses
+// as deep as the tree and can overflow the JS call stack. Firefox's stack is much
+// smaller than Chrome's, so the same payload throws `InternalError: too much
+// recursion` in Firefox while rendering fine in Chrome.
+//
+// Byte size alone does not predict this: a flat multi-hundred-KB payload never
+// overflows, while a few KB of deeply nested markdown does. Even parsing such
+// input to *measure* its depth is unsafe — micromark's parser recurses too and
+// overflows on the same pathological input. So the depth check below is a single
+// pass, non-recursive scan that can never itself overflow.
+
+// Cheap preempt: individual strings larger than this are rendered as plain text
+// instead of markdown. Mirrors MARKDOWN_RENDER_CHARACTER_LIMIT (the caller-side
+// input+output+messages gate) as a per-string backstop for surfaces that do not
+// apply that gate (e.g. comments), and avoids scanning/rendering huge blobs.
+export const MARKDOWN_MAX_RENDER_BYTES = 150_000;
+
+// Content whose estimated markdown nesting depth exceeds this is rendered as
+// plain text. Legitimate markdown nests <20-30 levels deep; a stack-overflowing
+// payload needs hundreds+, so this threshold sits in a wide safe band.
+export const MARKDOWN_MAX_NESTING_DEPTH = 100;
+
+const isListBullet = (char: string): boolean =>
+ char === "-" || char === "+" || char === "*";
+
+const isEmphasisDelimiter = (char: string): boolean =>
+ char === "*" || char === "_" || char === "~";
+
+const isSpace = (char: string): boolean => char === " " || char === "\t";
+
+/**
+ * Returns a cheap, non-recursive over-estimate of the maximum markdown nesting
+ * depth in `content`. It is a safe upper bound for the byte-cheap vectors that
+ * can overflow a small stack without being large (blockquotes and emphasis
+ * runs); byte-expensive vectors (deep multi-line lists) are additionally bounded
+ * by the size preempt. Over-estimating is safe (worst case: content falls back
+ * to plain text); the scan never under-counts a pure blockquote chain.
+ */
+export function estimateMarkdownNestingDepth(content: string): number {
+ let maxDepth = 0;
+ let atLineStart = true;
+
+ // Leading container markers per line: each `>`, list bullet, or ordered-list
+ // marker opens a nesting level, plus a term for indentation-based list nesting.
+ let lineDepth = 0;
+ let leadingWhitespace = 0;
+ let inLeadingMarkers = false;
+
+ // Longest run of the same emphasis/strikethrough delimiter, an upper bound on
+ // inline emphasis nesting depth.
+ let runChar = "";
+ let runLength = 0;
+
+ for (let i = 0; i < content.length; i++) {
+ const char = content[i];
+
+ if (char === "\n") {
+ atLineStart = true;
+ lineDepth = 0;
+ leadingWhitespace = 0;
+ runChar = "";
+ runLength = 0;
+ continue;
+ }
+
+ if (atLineStart) {
+ if (isSpace(char)) {
+ leadingWhitespace++;
+ inLeadingMarkers = true;
+ continue;
+ }
+ if (char === ">") {
+ lineDepth++;
+ const depth = lineDepth + Math.floor(leadingWhitespace / 2);
+ if (depth > maxDepth) maxDepth = depth;
+ inLeadingMarkers = true;
+ continue;
+ }
+ // A list bullet or ordered marker only opens a level when followed by
+ // whitespace (or end of content); otherwise it is emphasis / plain text.
+ const next = content[i + 1];
+ const followedByWs = next === undefined || isSpace(next) || next === "\n";
+ if (isListBullet(char) && followedByWs) {
+ lineDepth++;
+ const depth = lineDepth + Math.floor(leadingWhitespace / 2);
+ if (depth > maxDepth) maxDepth = depth;
+ inLeadingMarkers = true;
+ continue;
+ }
+ // Leading markers ended for this line; account for indentation depth once
+ // more (covers indented content with no explicit bullet) then fall through
+ // to inline scanning of the rest of the line.
+ if (inLeadingMarkers) {
+ const depth = lineDepth + Math.floor(leadingWhitespace / 2);
+ if (depth > maxDepth) maxDepth = depth;
+ }
+ atLineStart = false;
+ inLeadingMarkers = false;
+ }
+
+ // Inline emphasis / strikethrough delimiter runs.
+ if (isEmphasisDelimiter(char)) {
+ if (char === runChar) {
+ runLength++;
+ } else {
+ runChar = char;
+ runLength = 1;
+ }
+ if (runLength > maxDepth) maxDepth = runLength;
+ } else {
+ runChar = "";
+ runLength = 0;
+ }
+ }
+
+ return maxDepth;
+}
+
+/**
+ * Whether `content` should be rendered as plain text rather than parsed as GFM
+ * markdown, to avoid stack-overflow crashes on pathologically large or deeply
+ * nested payloads. See the module header for the mechanism.
+ */
+export function exceedsMarkdownRenderLimits(content: string): boolean {
+ if (content.length > MARKDOWN_MAX_RENDER_BYTES) return true;
+ return estimateMarkdownNestingDepth(content) > MARKDOWN_MAX_NESTING_DEPTH;
+}