Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

🐛 fix(file-parse): parse with the parent heap instead of refusing on a heap flag (#23361)

Mocha56429c71bf72
diff --git a/apps/server/src/services/fileParse/runner.heapCap.test.ts b/apps/server/src/services/fileParse/runner.heapCap.test.ts
index ae35f0ba646..5f1af37c5c4 100644
--- a/apps/server/src/services/fileParse/runner.heapCap.test.ts
+++ b/apps/server/src/services/fileParse/runner.heapCap.test.ts
@@ -83,17 +83,44 @@ const spawnDriver = async (flags: { args?: string[]; nodeOptions?: string }, oom
const env = { ...process.env };
delete env.NODE_OPTIONS;
if (flags.nodeOptions !== undefined) env.NODE_OPTIONS = flags.nodeOptions;
- const { stdout } = await run(
+ const { stderr, stdout } = await run(
process.execPath,
[...(flags.args ?? []), driverPath, workerPath, marker, oomLimitMb],
{ env, timeout: 60_000 },
);
- return { marker, results: JSON.parse(stdout.trim().split('\n').pop()!) as any[] };
+ const overrideWarnings = stderr
+ .split('\n')
+ .filter((line) => line.includes('"file_parse.heap_budget_overridden"'))
+ .map((line) => JSON.parse(line));
+ return {
+ marker,
+ overrideWarnings,
+ results: JSON.parse(stdout.trim().split('\n').pop()!) as any[],
+ };
+};
+
+/**
+ * A parent heap flag above the budget cannot be undone for a worker thread, and hosts such as
+ * Vercel set one on the function process themselves. The parse runs with the parent's limit,
+ * still on its own thread, and the override is logged once per runner.
+ */
+const expectRunsWithParentHeap = (
+ outcome: Awaited<ReturnType<typeof spawnDriver>>,
+ parentHeapMb: number,
+) => {
+ for (const result of outcome.results.slice(0, 2)) {
+ expect(result.value).toBeGreaterThanOrEqual(parentHeapMb);
+ }
+ expect(existsSync(outcome.marker)).toBe(true);
+ expect(outcome.results[2]).toEqual({ active: 0, queued: 0 });
+ expect(outcome.overrideWarnings).toHaveLength(1);
+ expect(outcome.overrideWarnings[0]).toMatchObject({ budgetMb: BUDGET_MB });
+ expect(outcome.overrideWarnings[0].workerHeapMb).toBeGreaterThanOrEqual(parentHeapMb);
};
describe('parent V8 heap flags vs the worker memory budget', () => {
it('runs with the configured heap when the parent sets no heap flag, and recovers from OOM', async () => {
- const { marker, results } = await spawnDriver({}, '64');
+ const { marker, overrideWarnings, results } = await spawnDriver({}, '64');
// Young generation is on top of the old generation budget; both runs are the same bounded thread.
expect(results[0].value).toBeGreaterThan(BUDGET_MB);
@@ -105,6 +132,7 @@ describe('parent V8 heap flags vs the worker memory budget', () => {
expect(results[4]).toEqual({ active: 0, queued: 0 });
expect(results[5]).toEqual({ active: 0, queued: 0 });
expect(existsSync(marker)).toBe(true);
+ expect(overrideWarnings).toEqual([]);
}, 60_000);
// Every form that gives the parent a larger old-space limit: CLI or NODE_OPTIONS, `-` or `_`.
@@ -115,17 +143,9 @@ describe('parent V8 heap flags vs the worker memory budget', () => {
['NODE_OPTIONS --max_old_space_size', { nodeOptions: '--max_old_space_size=4096' }],
['CLI --max-heap-size', { args: ['--max-heap-size=4096'] }],
])(
- 'refuses before loading any parser when the parent has %s above the budget',
+ 'still parses, warning once, when the parent has %s above the budget',
async (_, flags) => {
- const { marker, results } = await spawnDriver(flags);
-
- for (const result of results.slice(0, 2)) {
- expect(result).toMatchObject({ code: 'START_FAILED' });
- expect(result.message).toMatch(/--max-old-space-size/);
- }
- // The scenario (the parser entry) never ran, the slot is free and the queue still moves.
- expect(existsSync(marker)).toBe(false);
- expect(results[2]).toEqual({ active: 0, queued: 0 });
+ expectRunsWithParentHeap(await spawnDriver(flags), 4096);
},
60_000,
);
@@ -137,19 +157,20 @@ describe('parent V8 heap flags vs the worker memory budget', () => {
])(
'keeps working when the parent flag is %s (the heap is not larger)',
async (_, flags, mb) => {
- const { marker, results } = await spawnDriver(flags);
+ const { marker, overrideWarnings, results } = await spawnDriver(flags);
expect(results[0].value).toBeGreaterThanOrEqual(mb);
expect(results[0].value).toBeLessThan(mb + 400);
expect(results[1].value).toBe(results[0].value);
expect(existsSync(marker)).toBe(true);
+ expect(overrideWarnings).toEqual([]);
},
60_000,
);
- // Node versions differ in which heap option forms they accept. An accepted form must fail
- // closed in the runner (START_FAILED, parser never started); otherwise Node must reject the
- // specific option at startup, rather than crash or time out.
+ // Node versions differ in which heap option forms they accept. An accepted form parses with the
+ // parent's heap and warns once; otherwise Node must reject the specific option at startup,
+ // rather than crash or time out.
it.each([
[
'CLI --max-old-space-size (space-separated)',
@@ -167,7 +188,7 @@ describe('parent V8 heap flags vs the worker memory budget', () => {
/--max-heap-size=? is not allowed in NODE_OPTIONS/,
],
])(
- 'never starts a parser with a larger heap for version-dependent option forms (%s)',
+ 'either parses with a warning or is rejected by Node for version-dependent option forms (%s)',
async (_, flags, rejection) => {
const outcome = await spawnDriver(flags).then(
(value) => ({ value }),
@@ -181,11 +202,7 @@ describe('parent V8 heap flags vs the worker memory budget', () => {
expect(outcome.error.stderr).toMatch(rejection);
return;
}
- for (const result of outcome.value.results.slice(0, 2)) {
- expect(result).toMatchObject({ code: 'START_FAILED' });
- expect(result.message).toMatch(/--max-old-space-size/);
- }
- expect(existsSync(outcome.value.marker)).toBe(false);
+ expectRunsWithParentHeap(outcome.value, 4096);
},
60_000,
);
diff --git a/apps/server/src/services/fileParse/runner.ts b/apps/server/src/services/fileParse/runner.ts
index 660e7b62886..eb7f62dcf64 100644
--- a/apps/server/src/services/fileParse/runner.ts
+++ b/apps/server/src/services/fileParse/runner.ts
@@ -62,7 +62,8 @@ const WORKER_ENV_KEYS = ['DEBUG', 'LANG', 'NODE_ENV', 'TEMP', 'TMP', 'TMPDIR', '
* A V8 heap flag on the parent process (`--max-old-space-size` and friends, from the command line
* or `NODE_OPTIONS`) overrides the `resourceLimits` of every worker thread (Node docs, `Worker`
* options), and neither the worker `env` nor `execArgv` can undo it. So the budget is verified,
- * not assumed: a probe thread, never a parser, reports the heap limit it really got.
+ * not assumed: a probe thread, never a parser, reports the heap limit it really got, and an
+ * override is reported instead of being taken for the budget.
*/
const HEAP_PROBE_YOUNG_MB = 48;
const HEAP_PROBE_SOURCE = `
@@ -175,13 +176,17 @@ export const createFileParseRunner = (
let active = 0;
/** The process flags never change, so one successful probe holds for the runner's life. */
let heapProbe: Promise<number> | undefined;
+ let heapOverrideReported = false;
/**
- * Fails closed when the parent's V8 flags give a worker more heap than `maxOldGenerationSizeMb`
- * allows. A smaller limit is kept: it is inside the budget (a parse may then run out of memory
- * earlier, as a typed `OUT_OF_MEMORY`).
+ * Checks the heap a worker really gets against `maxOldGenerationSizeMb`. A parent V8 heap flag
+ * above it cannot be undone for a thread, and hosts such as Vercel set one on the function
+ * process themselves, so the parse is not refused: it runs with the parent's limit, still on its
+ * own thread and inside the input budgets, and the override is reported once. A smaller limit
+ * is kept: it is inside the budget (a parse may then run out of memory earlier, as a typed
+ * `OUT_OF_MEMORY`).
*/
- const assertHeapBudgetHolds = async () => {
+ const checkHeapBudget = async () => {
heapProbe ??= probeHeapLimitBytes(
options.maxOldGenerationSizeMb,
// The default parse budget, not the caller's: a thread cold start must not depend on a tight one.
@@ -195,14 +200,15 @@ export const createFileParseRunner = (
throw error;
}
const allowedBytes = (options.maxOldGenerationSizeMb + HEAP_PROBE_YOUNG_MB) * 1024 * 1024;
- if (actualBytes > allowedBytes) {
- throw new FileParseError(
- 'START_FAILED',
- `File parse workers get ${Math.round(actualBytes / 1024 / 1024)}MB of heap instead of the ` +
- `${options.maxOldGenerationSizeMb}MB old generation budget: the Node process was started ` +
- 'with a larger V8 heap flag (--max-old-space-size / --max-heap-size, on the command line ' +
- 'or in NODE_OPTIONS), which overrides the worker limit. Remove it or lower it to at most ' +
- 'the budget.',
+ if (actualBytes > allowedBytes && !heapOverrideReported) {
+ heapOverrideReported = true;
+ console.warn(
+ JSON.stringify({
+ budgetMb: options.maxOldGenerationSizeMb,
+ event: 'file_parse.heap_budget_overridden',
+ hint: 'a parent V8 heap flag (--max-old-space-size / --max-heap-size) overrides the worker limit',
+ workerHeapMb: Math.round(actualBytes / 1024 / 1024),
+ }),
);
}
};
@@ -254,9 +260,9 @@ export const createFileParseRunner = (
return release();
}
- // Before any parser is loaded: a worker that would outgrow its budget never starts.
+ // Before any parser is loaded, so a heap override is reported before the first parse.
try {
- await assertHeapBudgetHolds();
+ await checkHeapBudget();
} catch (error) {
task.reject(
isFileParseError(error)
diff --git a/docs/self-hosting/platform/vercel.mdx b/docs/self-hosting/platform/vercel.mdx
index 1536694903d..5d729de2a49 100644
--- a/docs/self-hosting/platform/vercel.mdx
+++ b/docs/self-hosting/platform/vercel.mdx
@@ -386,7 +386,7 @@ To sync manually: Actions → Upstream Sync → Run workflow.
## Troubleshooting
-**Deployment fails** — Check build logs in Vercel Dashboard → Deployments → click the failed deployment → Build Logs. Common causes: missing environment variables, TypeScript errors, or out of memory (fix with `NODE_OPTIONS=--max-old-space-size=4096`, set for the build step only: if it also applies at runtime, file parsing is refused with `START_FAILED`, because the larger heap flag overrides the parse worker's memory limit).
+**Deployment fails** — Check build logs in Vercel Dashboard → Deployments → click the failed deployment → Build Logs. Common causes: missing environment variables, TypeScript errors, or out of memory (fix with `NODE_OPTIONS=--max-old-space-size=4096`, preferably for the build step only: a heap flag that also applies at runtime overrides the parse worker's 768 MB memory limit, so file parsing then runs with the larger limit and logs `file_parse.heap_budget_overridden` once).
**Function timeout** — If requests timeout on Hobby plan: upgrade to Pro (60s timeout), use faster AI models (e.g., GPT-4o-mini instead of GPT-4o), reduce max tokens, or ensure streaming is enabled.
diff --git a/docs/self-hosting/platform/vercel.zh-CN.mdx b/docs/self-hosting/platform/vercel.zh-CN.mdx
index ffd7fc6b165..0e4d89581fa 100644
--- a/docs/self-hosting/platform/vercel.zh-CN.mdx
+++ b/docs/self-hosting/platform/vercel.zh-CN.mdx
@@ -381,7 +381,7 @@ tags:
## 故障排查
-**部署失败** — 在 Vercel 控制台 → 部署记录 → 点击失败的部署 → 构建日志中查看详情。常见原因:环境变量缺失、TypeScript 报错、内存不足(通过 `NODE_OPTIONS=--max-old-space-size=4096` 修复,仅在构建步骤设置:若运行时也生效,文件解析会因更大的堆参数覆盖解析 worker 的内存上限而被拒绝,返回 `START_FAILED`)。
+**部署失败** — 在 Vercel 控制台 → 部署记录 → 点击失败的部署 → 构建日志中查看详情。常见原因:环境变量缺失、TypeScript 报错、内存不足(通过 `NODE_OPTIONS=--max-old-space-size=4096` 修复,最好只在构建步骤设置:若运行时也生效,更大的堆参数会覆盖解析 worker 的 768 MB 内存上限,文件解析会按这个更大的上限运行,并记录一次 `file_parse.heap_budget_overridden`)。
**函数超时** — 在 Hobby 套餐遇到超时时:升级到 Pro(60 秒超时)、使用更快的模型(如 GPT-4o-mini 代替 GPT-4o)、减少最大 token 数,或确认已启用流式响应。