OpenRAG is a comprehensive, single package Retrieval-Augmented Generation platform built on Langflow, Docling, and Opensearch.
Python
fix: cpd Ingestion fails with '413 Request Entity Too Large' for files of size 1MB and greater (#2470)
Wallgau0f86d17b7d5f
diff --git a/.env.example b/.env.exampleindex a0e4e8b98..8b22fee8d 100644--- a/.env.example+++ b/.env.example@@ -49,6 +49,12 @@ FETCH_OPENRAG_DOCS_AT_STARTUP=false# Default: 25# UPLOAD_BATCH_SIZE=25+# OPTIONAL: Largest accepted upload, in mebibytes. Oversized files are refused+# at upload time. This does not raise the body limit on the proxy in front of+# docling-serve. If that proxy cannot be changed, set this to its real limit.+# Default: 100+# OPENRAG_MAX_UPLOAD_MB=100+# make one like so https://docs.langflow.org/api-keys-and-authentication#langflow-secret-keyLANGFLOW_SECRET_KEY=diff --git a/docker-compose.yml b/docker-compose.ymlindex 76b92006f..5eed863ba 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -134,6 +134,7 @@ services:- LANGFLOW_CONNECT_TIMEOUT=${LANGFLOW_CONNECT_TIMEOUT:-30}- INGESTION_TIMEOUT=${INGESTION_TIMEOUT:-3600}- UPLOAD_BATCH_SIZE=${UPLOAD_BATCH_SIZE:-25}+ - OPENRAG_MAX_UPLOAD_MB=${OPENRAG_MAX_UPLOAD_MB:-100}- MAX_WORKERS=${MAX_WORKERS:-4}- IBM_AUTH_ENABLED=${IBM_AUTH_ENABLED:-false}- OPENRAG_AZURE_BLOB_ENABLED=${OPENRAG_AZURE_BLOB_ENABLED:-true}diff --git a/docs/docs/reference/configuration.mdx b/docs/docs/reference/configuration.mdxindex 26daa07b9..cb9dabe65 100644--- a/docs/docs/reference/configuration.mdx+++ b/docs/docs/reference/configuration.mdx@@ -257,6 +257,7 @@ For Langflow flow IDs and Langflow timeout settings, see [Langflow settings](#la| `HOST_DOCKER_INTERNAL` | `host.docker.internal` | Host address for accessing services running on the host machine from within Docker containers. This is used to connect to the local Docling Serve instance started by OpenRAG. If your system uses a different hostname for this purpose, set this variable accordingly. || `INGESTION_TIMEOUT` | `3600` | Document ingestion timeout limit in seconds for each file. Increase this value if you experience timeouts when ingesting very large documents. Must be greater than or equal to [`LANGFLOW_TIMEOUT`](#langflow-settings). || `UPLOAD_BATCH_SIZE` | `25` | When ingesting folders, set the maximum number of files to ingest per batch. Each batch is an [ingestion task](/ingestion#monitor-ingestion). Increase this value to ingest more files per batch. If this value is too high, performance issues can occur. |+| `OPENRAG_MAX_UPLOAD_MB` | `100` | Largest accepted upload, in mebibytes. A larger file is refused before ingestion starts, after the request body has been received. Cap the request at the reverse proxy in front of OpenRAG if temp disk must be bounded. This does not raise the body limit on the proxy in front of Docling Serve. A `proxy-body-size` annotation on the OpenRAG ingress does not change that proxy. Raise the Docling proxy's `client_max_body_size`, or set this variable to that proxy's real limit. || `OPENRAG_EMBEDDING_OVERFLOW_POLICY` | `average` | What OpenRAG does when the embedding model rejects a chunk or query as longer than its input limit. With `average`, OpenRAG embeds the text in smaller pieces and stores the length-weighted average of their vectors, so ingestion continues; the full text is still stored and searchable by keyword. With `error`, the request fails and the file reports that a section is longer than the model accepts. |## Langflow settings {#langflow-settings}diff --git a/frontend/app/chat/page.test.tsx b/frontend/app/chat/page.test.tsxindex 8824ba817..d767774e4 100644--- a/frontend/app/chat/page.test.tsx+++ b/frontend/app/chat/page.test.tsx@@ -13,6 +13,7 @@*/import { act, fireEvent, screen, waitFor } from "@testing-library/react";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { apiClient } from "@/lib/api-client";import { authPresets, makeUser, withAuth } from "@/test-utils/fixtures/auth";import { renderWithProviders } from "@/test-utils/render";import { PLACEHOLDER_GREETING } from "./_types/types";@@ -127,14 +128,30 @@ vi.mock("@/app/chat/_components/assistant-message", () => ({),}));-const { imeStateHolder, submitSpy } = vi.hoisted(() => ({- imeStateHolder: {- current: { composing: false, compositionEndedAt: 0, now: 0 },- },- submitSpy: vi.fn((event: { preventDefault: () => void }) => {- event.preventDefault();- }),-}));+const { imeStateHolder, submitSpy, chatCallbacks, uploadFileForContextMock } =+ vi.hoisted(() => ({+ imeStateHolder: {+ current: { composing: false, compositionEndedAt: 0, now: 0 },+ },+ submitSpy: vi.fn((event: { preventDefault: () => void }) => {+ event.preventDefault();+ }),+ chatCallbacks: {+ onSubmit: undefined as+ | ((event: { preventDefault: () => void }) => void | Promise<void>)+ | undefined,+ onFileSelected: undefined as ((file: File) => void) | undefined,+ },+ uploadFileForContextMock: vi.fn(),+ }));++vi.mock("@/lib/upload-utils", async (importOriginal) => {+ const actual = await importOriginal<typeof import("@/lib/upload-utils")>();+ return {+ ...actual,+ uploadFileForContext: uploadFileForContextMock,+ };+});vi.mock("@/app/chat/_components/chat-input", () => {const { forwardRef, useImperativeHandle } = require("react");@@ -144,9 +161,15 @@ vi.mock("@/app/chat/_components/chat-input", () => {props: {onChange?: (value: string) => void;onKeyDown?: (e: React.KeyboardEvent<HTMLTextAreaElement>) => void;+ onSubmit?: (event: {+ preventDefault: () => void;+ }) => void | Promise<void>;+ onFileSelected?: (file: File) => void;},ref: React.Ref<{ getImeState: () => unknown }>,) => {+ chatCallbacks.onSubmit = props.onSubmit;+ chatCallbacks.onFileSelected = props.onFileSelected;useImperativeHandle(ref, () => ({focusInput() {},clickFileInput() {},@@ -193,6 +216,7 @@ describe("ChatPage — coverage for diff-flagged lines", () => {now: 0,};submitSpy.mockClear();+ uploadFileForContextMock.mockReset();});afterEach(() => {vi.useRealTimers();@@ -299,6 +323,28 @@ describe("ChatPage — coverage for diff-flagged lines", () => {expect(submitSpy).toHaveBeenCalledOnce();});+ it("does not send a message when the attached upload fails", async () => {+ vi.useRealTimers();+ uploadFileForContextMock.mockRejectedValueOnce(new Error("too big"));+ const post = vi.spyOn(apiClient, "post");+ renderWithProviders(<ProtectedChatPage />, {+ providers: ["auth"],+ auth: authPresets.noAuthMode,+ });++ act(() => {+ chatCallbacks.onFileSelected?.(+ new File(["x"], "notes.pdf", { type: "application/pdf" }),+ );+ });+ await act(async () => {+ await chatCallbacks.onSubmit?.({ preventDefault() {} });+ });++ expect(uploadFileForContextMock).toHaveBeenCalledOnce();+ expect(post).not.toHaveBeenCalled();+ });+it("replaces the placeholder greeting after mount in no-auth mode", async () => {vi.useRealTimers();renderWithProviders(<ProtectedChatPage />, {diff --git a/frontend/app/chat/page.tsx b/frontend/app/chat/page.tsxindex d4f40dba2..adb333671 100644--- a/frontend/app/chat/page.tsx+++ b/frontend/app/chat/page.tsx@@ -28,7 +28,7 @@ import {handleInputKeyDown,type ImeCompositionState,} from "@/lib/ime-composition";-import { uploadFileForContext } from "@/lib/upload-utils";+import { uploadFailureText, uploadFileForContext } from "@/lib/upload-utils";import { resolveDisplayName } from "@/lib/user";import { cn } from "@/lib/utils";import { useGetConversationsQuery } from "../api/queries/useGetConversationsQuery";@@ -343,11 +343,12 @@ function ChatPage() {setChatError(true);const errorMessage: Message = {role: "assistant",- content: `❌ Failed to process document. Please try again.`,+ content: `❌ ${uploadFailureText(error)}`,timestamp: new Date(),error: true,};setMessages((prev) => [...prev.slice(0, -1), errorMessage]);+ return { type: "failed" as const };} finally {setIsUploading(false);setLoading(false);@@ -863,6 +864,14 @@ function ChatPage() {const uploadResult = await handleFileUpload(uploadedFile);setUploadedFile(null);+ if (+ uploadResult &&+ typeof uploadResult === "object" &&+ uploadResult.type === "failed"+ ) {+ return;+ }+if (uploadResult && typeof uploadResult === "object") {// File is being processed asynchronously — don't send the message yet.// The user can submit again once the task completes.diff --git a/frontend/components/knowledge-dropdown.test.tsx b/frontend/components/knowledge-dropdown.test.tsxnew file mode 100644index 000000000..6e24d85af--- /dev/null+++ b/frontend/components/knowledge-dropdown.test.tsx@@ -0,0 +1,218 @@+import { waitFor } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { HttpResponse, http } from "msw";+import { toast } from "sonner";+import { beforeEach, describe, expect, it, vi } from "vitest";+import { apiClient } from "@/lib/api-client";+import { resetUploadLimitCache } from "@/lib/upload-utils";+import { authPresets } from "@/test-utils/fixtures/auth";+import { renderWithProviders, screen } from "@/test-utils/render";+import { KnowledgeDropdown } from "./knowledge-dropdown";++function sizedPdf(name: string, size: number) {+ return new File([new Uint8Array(size)], name, { type: "application/pdf" });+}++function handlers(+ maxUploadMb: number,+ onOptions: () => void,+ defaults: () => Response = () => HttpResponse.json({}),+) {+ return [+ http.get("/api/upload_options", () => {+ onOptions();+ return HttpResponse.json({+ upload_batch_size: 25,+ max_upload_mb: maxUploadMb,+ });+ }),+ http.get("/api/connectors", () => HttpResponse.json({ connectors: {} })),+ http.get("/api/connectors/:type/defaults", () => defaults()),+ http.get("/api/documents/check-filename", () =>+ HttpResponse.json({ exists: false }),+ ),+ http.post("/api/router/upload_ingest", () =>+ HttpResponse.json({+ task_id: "task-1",+ file_count: 1,+ preview_mode: false,+ }),+ ),+ ];+}++async function chooseFolder(files: File[]) {+ let optionsLoaded = false;+ renderWithProviders(<KnowledgeDropdown />, {+ providers: ["brand", "task"],+ auth: authPresets.rbacDisabled,+ handlers: handlers(1, () => {+ optionsLoaded = true;+ }),+ });++ await screen.findByRole("button", { name: /add knowledge/i });+ await waitFor(() => expect(optionsLoaded).toBe(true));+ const folderInput = document.querySelector(+ "input[webkitdirectory]",+ ) as HTMLInputElement | null;+ if (!folderInput) throw new Error("folder input missing");+ await userEvent.upload(folderInput, files);+}++describe("KnowledgeDropdown folder upload limit", () => {+ beforeEach(() => {+ vi.restoreAllMocks();+ resetUploadLimitCache();+ vi.spyOn(toast, "error").mockReturnValue("toast");+ vi.spyOn(toast, "success").mockReturnValue("toast");+ vi.spyOn(toast, "info").mockReturnValue("toast");+ });++ it("skips a file over the configured limit and uploads the rest", async () => {+ await chooseFolder([+ sizedPdf("notes.pdf", 100),+ sizedPdf("huge.pdf", 2 * 1024 * 1024),+ ]);++ await waitFor(() => {+ expect(toast.error).toHaveBeenCalledWith(+ "1 file is over the upload limit",+ expect.objectContaining({+ description: expect.stringContaining("huge.pdf"),+ duration: Number.POSITIVE_INFINITY,+ }),+ );+ });+ await waitFor(() => {+ expect(toast.success).toHaveBeenCalledWith(+ expect.stringContaining("Successfully processed 1 file(s)"),+ );+ });+ });++ it("lists every skipped file in one toast", async () => {+ await chooseFolder([+ sizedPdf("huge.pdf", 2 * 1024 * 1024),+ sizedPdf("bigger.pdf", 3 * 1024 * 1024),+ ]);++ await waitFor(() => {+ expect(toast.error).toHaveBeenCalledWith(+ "2 files are over the upload limit",+ expect.objectContaining({+ description: expect.stringMatching(/huge\.pdf[\s\S]*bigger\.pdf/),+ duration: Number.POSITIVE_INFINITY,+ closeButton: true,+ }),+ );+ });+ expect(toast.error).toHaveBeenCalledTimes(1);+ });++ it("keeps a split folder on one task and records the skipped files once", async () => {+ const posts: Array<{+ existing: FormDataEntryValue | null;+ rejected: string;+ files: number;+ }> = [];+ vi.spyOn(apiClient, "post").mockImplementation(async (_url, body) => {+ const form = body as FormData;+ const existing = form.get("existing_task_id");+ posts.push({+ existing,+ rejected: String(form.get("rejected_files") ?? ""),+ files: form.getAll("file").length,+ });+ return {+ status: 202,+ data: {+ task_id:+ typeof existing === "string" && existing ? existing : "task-1",+ file_count: form.getAll("file").length,+ preview_mode: false,+ },+ };+ });+ let optionsLoaded = false;+ renderWithProviders(<KnowledgeDropdown />, {+ providers: ["brand", "task"],+ auth: authPresets.rbacDisabled,+ handlers: handlers(1, () => {+ optionsLoaded = true;+ }),+ });++ await screen.findByRole("button", { name: /add knowledge/i });+ await waitFor(() => expect(optionsLoaded).toBe(true));+ const folderInput = document.querySelector(+ "input[webkitdirectory]",+ ) as HTMLInputElement | null;+ if (!folderInput) throw new Error("folder input missing");+ await userEvent.upload(folderInput, [+ sizedPdf("first.pdf", 600 * 1024),+ sizedPdf("huge.pdf", 2 * 1024 * 1024),+ sizedPdf("second.pdf", 600 * 1024),+ ]);++ await waitFor(() => expect(posts).toHaveLength(2));+ expect(posts[0]).toMatchObject({ existing: null, files: 1 });+ expect(posts[0]?.rejected).toContain("huge.pdf");+ expect(posts[1]).toMatchObject({+ existing: "task-1",+ files: 1,+ rejected: "",+ });+ });++ it("does not report success when every file is over the limit", async () => {+ await chooseFolder([sizedPdf("huge.pdf", 2 * 1024 * 1024)]);++ await waitFor(() => {+ expect(toast.error).toHaveBeenCalledWith(+ "1 file is over the upload limit",+ expect.objectContaining({+ description: expect.stringContaining("huge.pdf"),+ duration: Number.POSITIVE_INFINITY,+ }),+ );+ });+ expect(toast.success).not.toHaveBeenCalled();+ });++ it("keeps the configured limit when a connector lookup fails", async () => {+ let optionsLoaded = false;+ renderWithProviders(<KnowledgeDropdown />, {+ providers: ["brand", "task"],+ auth: authPresets.rbacDisabled,+ handlers: handlers(+ 1,+ () => {+ optionsLoaded = true;+ },+ () => HttpResponse.error(),+ ),+ });++ await screen.findByRole("button", { name: /add knowledge/i });+ await waitFor(() => expect(optionsLoaded).toBe(true));+ const folderInput = document.querySelector(+ "input[webkitdirectory]",+ ) as HTMLInputElement | null;+ if (!folderInput) throw new Error("folder input missing");+ await userEvent.upload(folderInput, [+ sizedPdf("huge.pdf", 2 * 1024 * 1024),+ ]);++ await waitFor(() => {+ expect(toast.error).toHaveBeenCalledWith(+ "1 file is over the upload limit",+ expect.objectContaining({+ description: expect.stringContaining("huge.pdf"),+ duration: Number.POSITIVE_INFINITY,+ }),+ );+ });+ expect(toast.success).not.toHaveBeenCalled();+ });+});diff --git a/frontend/components/knowledge-dropdown.tsx b/frontend/components/knowledge-dropdown.tsxindex 2add6c0b5..c135cbb2c 100644--- a/frontend/components/knowledge-dropdown.tsx+++ b/frontend/components/knowledge-dropdown.tsx@@ -54,9 +54,14 @@ import {type PreviewDialogState,} from "@/lib/ingest-preview";import {+ countSentDuplicates,duplicateCheck,+ folderUploadSuccessText,+ getMaxUploadBytes,+ packUploadBatches,uploadFiles,uploadFile as uploadFileUtil,+ uploadTooLargeMessage,} from "@/lib/upload-utils";import { cn } from "@/lib/utils";@@ -163,24 +168,27 @@ export function KnowledgeDropdown() {(d) => d.kind === "bucket",);- // Check upload batch size and bucket connector availability in parallel- const [uploadOptionsRes, ...bucketResponses] = await Promise.all([- apiClient.get("/upload_options"),- ...bucketDescriptors.map((d) =>- apiClient.get(`/connectors/${d.connectorType}/defaults`),- ),- ]);-- if (uploadOptionsRes.status >= 200 && uploadOptionsRes.status < 300) {- const uploadOptionsData = uploadOptionsRes.data;- if (- typeof uploadOptionsData.upload_batch_size === "number" &&- uploadOptionsData.upload_batch_size > 0- ) {- setUploadBatchSize(uploadOptionsData.upload_batch_size);+ try {+ const uploadOptionsRes = await apiClient.get("/upload_options");+ if (uploadOptionsRes.status >= 200 && uploadOptionsRes.status < 300) {+ const uploadOptionsData = uploadOptionsRes.data;+ if (+ typeof uploadOptionsData.upload_batch_size === "number" &&+ uploadOptionsData.upload_batch_size > 0+ ) {+ setUploadBatchSize(uploadOptionsData.upload_batch_size);+ }}+ } catch (err) {+ console.error("Failed to load upload options", err);}+ const bucketResponses = await Promise.all(+ bucketDescriptors.map((d) =>+ apiClient.get(`/connectors/${d.connectorType}/defaults`),+ ),+ );+const configured: Record<string, boolean> = {};await Promise.all(bucketResponses.map(async (res, i) => {@@ -442,79 +450,128 @@ export function KnowledgeDropdown() {const uploadFolderBatches = async (filesToUpload: File[],replace: boolean,- ) => {+ ): Promise<{+ sentCount: number;+ sentNames: string[];+ oversizedCount: number;+ }> => {+ const maxUploadBytes = await getMaxUploadBytes();+ const { batches, oversized } = packUploadBatches(+ filesToUpload,+ uploadBatchSize,+ maxUploadBytes,+ );+ if (oversized.length > 0) {+ toast.error(+ oversized.length === 1+ ? "1 file is over the upload limit"+ : `${oversized.length} files are over the upload limit`,+ {+ description: oversized+ .map((file) =>+ uploadTooLargeMessage(file.name, file.size, maxUploadBytes),+ )+ .join("\n"),+ duration: Number.POSITIVE_INFINITY,+ closeButton: true,+ classNames: { description: "whitespace-pre-line" },+ },+ );+ }+ const filesToSend = batches.flat();+ if (filesToSend.length === 0) {+ if (oversized.length > 0) {+ try {+ const recorded = await uploadFiles([], false, false, {+ rejectedFiles: oversized,+ });+ addTask(recorded.taskId, { source: "folder" });+ refetchTasks();+ } catch (error) {+ console.error(+ "[Folder Upload] Could not record skipped files:",+ error,+ );+ }+ }+ return { sentCount: 0, sentNames: [], oversizedCount: oversized.length };+ }+trackStartProcess({processType: "Ingestion",process: "Document Upload",category: "Knowledge",source: "folder",- total_files: filesToUpload.length,+ total_files: filesToSend.length,});- openPreviewForFiles(filesToUpload, `${filesToUpload.length} files`);-- const batches: File[][] = [];- for (let i = 0; i < filesToUpload.length; i += uploadBatchSize) {- batches.push(filesToUpload.slice(i, i + uploadBatchSize));- }+ openPreviewForFiles(filesToSend, `${filesToSend.length} files`);const taskIdsByBatch: (string | undefined)[] = [];const failedBatchIndexes: number[] = [];- // Cap parallel batch uploads so large folders don't open every request at once.- const batchConcurrency = Math.min(2, batches.length);- let nextBatchIndex = 0;+ // Later batches join this task, so a folder that has to be split to stay+ // under the request size still shows as one operation.+ let sharedTaskId: string | undefined;// Set by any worker that gets previewMode=true; checked once after all// batches finish so a concurrent false cannot close a successful open.let previewModeConfirmed = false;- const runNextBatch = async () => {- while (nextBatchIndex < batches.length) {- const batchIndex = nextBatchIndex;- nextBatchIndex += 1;- const batch = batches[batchIndex];- if (!batch) continue;+ const sendBatch = async (batchIndex: number, attachRejected: boolean) => {+ const batch = batches[batchIndex];+ if (!batch) return;- try {- const result = await uploadFiles(- batch,- replace,- ingestPreviewEnabled,+ try {+ const result = await uploadFiles(batch, replace, ingestPreviewEnabled, {+ existingTaskId: batchIndex === 0 ? undefined : sharedTaskId,+ rejectedFiles: attachRejected ? oversized : undefined,+ });+ if (batchIndex === 0) sharedTaskId = result.taskId;+ addTask(result.taskId, { source: "folder" });+ if (result.previewMode) {+ previewModeConfirmed = true;+ taskIdsByBatch[batchIndex] = result.taskId;+ attachPreviewTaskIds(+ taskIdsByBatch.filter((id): id is string => id !== undefined),+ {+ files: filesToSend,+ filename: `${filesToSend.length} files`,+ },);- addTask(result.taskId, { source: "folder" });- if (result.previewMode) {- previewModeConfirmed = true;- taskIdsByBatch[batchIndex] = result.taskId;- attachPreviewTaskIds(- taskIdsByBatch.filter((id): id is string => id !== undefined),- {- files: filesToUpload,- filename: `${filesToUpload.length} files`,- },- );- refetchTasks();- }- } catch (error) {- failedBatchIndexes.push(batchIndex);- trackProcessFailure({- processType: "Ingestion",- process: "Document Upload",- category: "Knowledge",- source: "folder",- resultValue:- error instanceof Error ? error.message : "Unknown error",- });- console.error("[Folder Upload] Batch upload failed:", error);- toast.error("Batch upload failed", {- description:- error instanceof Error ? error.message : "Unknown error",- });+ refetchTasks();}+ } catch (error) {+ failedBatchIndexes.push(batchIndex);+ trackProcessFailure({+ processType: "Ingestion",+ process: "Document Upload",+ category: "Knowledge",+ source: "folder",+ resultValue: error instanceof Error ? error.message : "Unknown error",+ });+ console.error("[Folder Upload] Batch upload failed:", error);+ toast.error("Batch upload failed", {+ description: error instanceof Error ? error.message : "Unknown error",+ });}};- await Promise.all(- Array.from({ length: batchConcurrency }, () => runNextBatch()),- );+ await sendBatch(0, true);+ const remaining = batches.length - 1;+ if (remaining > 0) {+ // Cap parallel batch uploads so large folders don't open every request at once.+ const batchConcurrency = Math.min(2, remaining);+ let nextBatchIndex = 1;+ const runNextBatch = async () => {+ while (nextBatchIndex < batches.length) {+ const batchIndex = nextBatchIndex;+ nextBatchIndex += 1;+ await sendBatch(batchIndex, false);+ }+ };+ await Promise.all(+ Array.from({ length: batchConcurrency }, () => runNextBatch()),+ );+ }// Close the optimistic open only after all workers finish. Doing this// inside a worker races: a late previewMode=false can wipe a sibling's@@ -530,6 +587,12 @@ export function KnowledgeDropdown() {`${failedBatchIndexes.length} of ${batches.length} batch upload(s) failed`,);}++ return {+ sentCount: filesToSend.length,+ sentNames: filesToSend.map((file) => file.name),+ oversizedCount: oversized.length,+ };};const handleOverwriteFile = async () => {@@ -538,14 +601,20 @@ export function KnowledgeDropdown() {const { allFiles, duplicateNames, unsupportedCount } =pendingFolderUpload;try {- await uploadFolderBatches(allFiles, true);- const unsupportedMessage =+ const result = await uploadFolderBatches(allFiles, true);+ const overwriteCount = countSentDuplicates(+ result.sentNames,+ duplicateNames,+ );+ const success = folderUploadSuccessText(+ result.sentCount,+ result.oversizedCount,+ `Processed ${result.sentCount} file(s), including ${overwriteCount} overwrite(s)`,unsupportedCount > 0- ? `, skipped ${unsupportedCount} unsupported`- : "";- toast.success(- `Processed ${allFiles.length} file(s), including ${duplicateNames.length} overwrite(s)${unsupportedMessage}`,+ ? [`skipped ${unsupportedCount} unsupported`]+ : [],);+ if (success) toast.success(success);} catch (error) {toast.error("Folder upload incomplete", {description: error instanceof Error ? error.message : "Unknown error",@@ -592,7 +661,7 @@ export function KnowledgeDropdown() {pendingFolderUpload;if (nonDuplicateFiles.length > 0) {try {- await uploadFolderBatches(nonDuplicateFiles, false);+ const result = await uploadFolderBatches(nonDuplicateFiles, false);const extraParts: string[] = [];if (duplicateNames.length > 0) {extraParts.push(`skipped ${duplicateNames.length} duplicate(s)`);@@ -600,11 +669,13 @@ export function KnowledgeDropdown() {if (unsupportedCount > 0) {extraParts.push(`skipped ${unsupportedCount} unsupported`);}- const suffix =- extraParts.length > 0 ? `, ${extraParts.join(", ")}` : "";- toast.success(- `Processed ${nonDuplicateFiles.length} file(s)${suffix}`,+ const success = folderUploadSuccessText(+ result.sentCount,+ result.oversizedCount,+ `Processed ${result.sentCount} file(s)`,+ extraParts,);+ if (success) toast.success(success);} catch (error) {toast.error("Folder upload incomplete", {description:@@ -714,12 +785,14 @@ export function KnowledgeDropdown() {return;}- await uploadFolderBatches(nonDuplicateFiles, false);- const unsupportedMessage =- unsupportedCount > 0 ? `, skipped ${unsupportedCount} unsupported` : "";- toast.success(- `Successfully processed ${nonDuplicateFiles.length} file(s)${unsupportedMessage}`,+ const result = await uploadFolderBatches(nonDuplicateFiles, false);+ const success = folderUploadSuccessText(+ result.sentCount,+ result.oversizedCount,+ `Successfully processed ${result.sentCount} file(s)`,+ unsupportedCount > 0 ? [`skipped ${unsupportedCount} unsupported`] : [],);+ if (success) toast.success(success);} catch (error) {console.error("Folder upload error:", error);toast.error("Folder upload failed", {diff --git a/frontend/lib/upload-utils.test.ts b/frontend/lib/upload-utils.test.tsindex db4e5a05e..fa8c65cd4 100644--- a/frontend/lib/upload-utils.test.ts+++ b/frontend/lib/upload-utils.test.ts@@ -7,7 +7,13 @@ import {} from "@/test-utils/msw/multipart";import { server } from "@/test-utils/msw/server";import {+ countSentDuplicates,duplicateCheck,+ folderUploadSuccessText,+ getMaxUploadBytes,+ packUploadBatches,+ resetUploadLimitCache,+ uploadFailureText,uploadFile,uploadFileForContext,uploadFiles,@@ -49,6 +55,12 @@ function captureForm(path: string, respond: () => Response) {beforeEach(() => {vi.restoreAllMocks();+ resetUploadLimitCache();+ server.use(+ http.get("/api/upload_options", () =>+ HttpResponse.json({ upload_batch_size: 25, max_upload_mb: 100 }),+ ),+ );});describe("uploadFileForContext", () => {@@ -127,6 +139,36 @@ describe("uploadFileForContext", () => {);});+ it("shows a non-JSON 413 body instead of the raw page", async () => {+ server.use(+ http.post(UPLOAD_CONTEXT, () =>+ HttpResponse.text(+ "<html><body><h1>413 Request Entity Too Large</h1></body></html>",+ { status: 413 },+ ),+ ),+ );++ await expect(uploadFileForContext(txt(), "/chat", null)).rejects.toThrow(+ "413 Request Entity Too Large",+ );+ await expect(+ uploadFileForContext(txt(), "/chat", null),+ ).rejects.not.toThrow(/<html>/);+ });++ it("reads an error field from a JSON failure body", async () => {+ server.use(+ http.post(UPLOAD_CONTEXT, () =>+ HttpResponse.json({ error: "disk full" }, { status: 500 }),+ ),+ );++ await expect(uploadFileForContext(txt(), "/chat", null)).rejects.toThrow(+ "disk full",+ );+ });+it("surfaces the server's error body, falling back to a default", async () => {server.use(http.post(UPLOAD_CONTEXT, () =>@@ -243,6 +285,111 @@ describe("uploadFiles", () => {);});+ it("shows a non-JSON 413 body instead of a parse error", async () => {+ server.use(+ http.post(UPLOAD_INGEST, () =>+ HttpResponse.text(+ "<html><body><h1>413 Request Entity Too Large</h1></body></html>",+ { status: 413 },+ ),+ ),+ );++ await expect(uploadFiles([txt()])).rejects.toThrow(+ "413 Request Entity Too Large",+ );+ resetUploadLimitCache();+ await expect(uploadFile(txt())).rejects.toThrow(+ "413 Request Entity Too Large",+ );+ });++ it("rejects an oversized file before upload", async () => {+ resetUploadLimitCache();+ let posted = false;+ server.use(+ http.get("/api/upload_options", () =>+ HttpResponse.json({ max_upload_mb: 1 }),+ ),+ http.post(UPLOAD_INGEST, () => {+ posted = true;+ return HttpResponse.json({ task_id: "should-not-run" });+ }),+ );++ const big = new File([new Uint8Array(1024 * 1024 + 1)], "big.pdf");++ await expect(uploadFile(big)).rejects.toThrow(/big\.pdf/);+ await expect(uploadFile(big)).rejects.toThrow("OPENRAG_MAX_UPLOAD_MB");+ expect(posted).toBe(false);+ });++ it("falls back to 100 MB when the options payload has no limit", async () => {+ resetUploadLimitCache();+ server.use(+ http.get("/api/upload_options", () =>+ HttpResponse.json({ upload_batch_size: 25 }),+ ),+ );+ const overDefault = new File([new Uint8Array(1)], "huge.pdf");+ Object.defineProperty(overDefault, "size", {+ value: 100 * 1024 * 1024 + 1,+ });++ await expect(uploadFile(overDefault)).rejects.toThrow(/huge\.pdf/);+ });++ it("uses the default limit when the limit lookup fails", async () => {+ resetUploadLimitCache();+ let posted = false;+ server.use(+ http.get("/api/upload_options", () => HttpResponse.error()),+ http.post(UPLOAD_INGEST, () => {+ posted = true;+ return HttpResponse.json({ id: "f-ok" });+ }),+ );++ await expect(uploadFile(txt())).resolves.toMatchObject({ fileId: "f-ok" });+ expect(posted).toBe(true);++ resetUploadLimitCache();+ posted = false;+ const overDefault = new File([new Uint8Array(1)], "huge.pdf");+ Object.defineProperty(overDefault, "size", {+ value: 100 * 1024 * 1024 + 1,+ });+ await expect(uploadFile(overDefault)).rejects.toThrow(/huge\.pdf/);+ expect(posted).toBe(false);+ });++ it("retries the limit lookup after a fallback", async () => {+ resetUploadLimitCache();+ server.use(http.get("/api/upload_options", () => HttpResponse.error()));+ await expect(getMaxUploadBytes()).resolves.toBe(100 * 1024 * 1024);++ server.use(+ http.get("/api/upload_options", () =>+ HttpResponse.json({ upload_batch_size: 25 }, { status: 500 }),+ ),+ );+ await expect(getMaxUploadBytes()).resolves.toBe(100 * 1024 * 1024);++ server.use(+ http.get("/api/upload_options", () =>+ HttpResponse.json({ max_upload_mb: 1 }),+ ),+ );+ await expect(getMaxUploadBytes()).resolves.toBe(1024 * 1024);++ server.use(+ http.get("/api/upload_options", () =>+ HttpResponse.json({ max_upload_mb: 5 }),+ ),+ );+ await expect(getMaxUploadBytes()).resolves.toBe(1024 * 1024);+ });+it("throws when a successful response carries no task id", async () => {server.use(http.post(UPLOAD_INGEST, () => HttpResponse.json({})));@@ -250,6 +397,99 @@ describe("uploadFiles", () => {});});+describe("uploadFailureText", () => {+ it("shows the size error instead of asking for a retry", () => {+ const message =+ '"notes.pdf" is 2.0 MB. The upload limit is 1 MB (OPENRAG_MAX_UPLOAD_MB).';++ expect(uploadFailureText(new Error(message))).toBe(message);+ });++ it("keeps a retry hint when the failure has no message", () => {+ expect(uploadFailureText(new Error(" "))).toBe(+ "Failed to process document. Please try again.",+ );+ expect(uploadFailureText("nope")).toBe(+ "Failed to process document. Please try again.",+ );+ });+});++describe("countSentDuplicates", () => {+ it("does not count a duplicate that was skipped for size", () => {+ expect(countSentDuplicates(["a.pdf", "b.pdf"], ["a.pdf", "huge.pdf"])).toBe(+ 1,+ );+ });+});++describe("folderUploadSuccessText", () => {+ it("counts only the files that were sent and names the skipped ones", () => {+ expect(+ folderUploadSuccessText(3, 2, "Successfully processed 3 file(s)"),+ ).toBe("Successfully processed 3 file(s), skipped 2 over the upload limit");+ });++ it("stays quiet when every file was over the limit", () => {+ expect(+ folderUploadSuccessText(0, 2, "Successfully processed 0 file(s)"),+ ).toBeNull();+ });++ it("keeps the other skip reasons", () => {+ expect(+ folderUploadSuccessText(1, 0, "Processed 1 file(s)", [+ "skipped 4 duplicate(s)",+ ]),+ ).toBe("Processed 1 file(s), skipped 4 duplicate(s)");+ });+});++describe("packUploadBatches", () => {+ function sized(name: string, size: number) {+ const file = new File([new Uint8Array(1)], name);+ Object.defineProperty(file, "size", { value: size });+ return file;+ }++ it("keeps each batch under the byte budget and drops oversized files", () => {+ const { batches, oversized } = packUploadBatches(+ [+ sized("a.pdf", 600),+ sized("b.pdf", 600),+ sized("c.pdf", 100),+ sized("huge.pdf", 2000),+ ],+ 25,+ 1000,+ );++ expect(oversized.map((file) => file.name)).toEqual(["huge.pdf"]);+ expect(batches.map((batch) => batch.map((file) => file.name))).toEqual([+ ["a.pdf"],+ ["b.pdf", "c.pdf"],+ ]);+ for (const batch of batches) {+ const total = batch.reduce((sum, file) => sum + file.size, 0);+ expect(total).toBeLessThanOrEqual(1000);+ }+ });++ it("also splits when the file count is reached first", () => {+ const { batches, oversized } = packUploadBatches(+ [sized("a.pdf", 10), sized("b.pdf", 10), sized("c.pdf", 10)],+ 2,+ 1000,+ );++ expect(oversized).toEqual([]);+ expect(batches.map((batch) => batch.map((file) => file.name))).toEqual([+ ["a.pdf", "b.pdf"],+ ["c.pdf"],+ ]);+ });+});+describe("uploadFile", () => {it("reads id and path from the nested upload object", async () => {server.use(diff --git a/frontend/lib/upload-utils.ts b/frontend/lib/upload-utils.tsindex c01df2d28..2d8242420 100644--- a/frontend/lib/upload-utils.ts+++ b/frontend/lib/upload-utils.ts@@ -1,4 +1,10 @@import { apiClient } from "@/lib/api-client";+import { formatFileSize } from "@/lib/file-format";++const DEFAULT_MAX_UPLOAD_MB = 100;+const DEFAULT_MAX_UPLOAD_BYTES = DEFAULT_MAX_UPLOAD_MB * 1024 * 1024;++let maxUploadBytesRequest: Promise<number> | null = null;function getUploadErrorMessage(data: unknown): string {if (typeof data === "string") return data;@@ -12,6 +18,151 @@ function getUploadErrorMessage(data: unknown): string {}return "";}++/** Turn an nginx HTML 413 into a short line a toast can show. */+function plainTextBody(body: string): string {+ const text = body.includes("<")+ ? body+ .replace(/<[^>]*>/g, " ")+ .replace(/\s+/g, " ")+ .trim()+ : body.trim();+ if (!text) return "Upload failed";+ return text.length > 300 ? `${text.slice(0, 300)}…` : text;+}++function uploadErrorText(data: unknown, fallback: string): string {+ if (typeof data === "string") {+ if (!data.trim()) return fallback;+ return plainTextBody(data);+ }+ return getUploadErrorMessage(data) || fallback;+}++export function resetUploadLimitCache(): void {+ maxUploadBytesRequest = null;+}++export async function getMaxUploadBytes(): Promise<number> {+ if (!maxUploadBytesRequest) {+ maxUploadBytesRequest = apiClient+ .get("/upload_options")+ .then((response) => {+ const mb = response.data?.max_upload_mb;+ if (+ response.status >= 200 &&+ response.status < 300 &&+ typeof mb === "number" &&+ mb > 0+ ) {+ return mb * 1024 * 1024;+ }+ maxUploadBytesRequest = null;+ return DEFAULT_MAX_UPLOAD_BYTES;+ })+ .catch(() => {+ maxUploadBytesRequest = null;+ return DEFAULT_MAX_UPLOAD_BYTES;+ });+ }+ return maxUploadBytesRequest;+}++export function uploadTooLargeMessage(+ filename: string,+ sizeBytes: number,+ limitBytes: number,+): string {+ const limitMb = limitBytes / (1024 * 1024);+ const limitLabel = Number.isInteger(limitMb)+ ? String(limitMb)+ : limitMb.toFixed(1);+ return `"${filename}" is ${formatFileSize(sizeBytes)}. The upload limit is ${limitLabel} MB (OPENRAG_MAX_UPLOAD_MB).`;+}++/** Text shown in chat when a context upload fails. */+export function uploadFailureText(error: unknown): string {+ if (error instanceof Error && error.message.trim()) {+ return error.message;+ }+ return "Failed to process document. Please try again.";+}++/** Duplicates that were actually sent; an oversized duplicate was skipped. */+export function countSentDuplicates(+ sentNames: string[],+ duplicateNames: string[],+): number {+ const sent = new Set(sentNames);+ return duplicateNames.filter((name) => sent.has(name)).length;+}++/**+ * Success line for a folder upload. Null when nothing was sent, so callers+ * do not report a failure or a success for files that were only skipped.+ */+export function folderUploadSuccessText(+ sentCount: number,+ oversizedCount: number,+ lead: string,+ extraParts: string[] = [],+): string | null {+ if (sentCount <= 0) return null;+ const parts = extraParts.filter((part) => part.length > 0);+ if (oversizedCount > 0) {+ parts.push(`skipped ${oversizedCount} over the upload limit`);+ }+ const suffix = parts.length > 0 ? `, ${parts.join(", ")}` : "";+ return `${lead}${suffix}`;+}++export async function assertFilesWithinUploadLimit(+ files: File[],+): Promise<void> {+ const limitBytes = await getMaxUploadBytes();+ for (const file of files) {+ if (file.size > limitBytes) {+ throw new Error(uploadTooLargeMessage(file.name, file.size, limitBytes));+ }+ }+}++/**+ * Split a folder into requests that stay within the file-count limit and the+ * upload byte budget. A file larger than the budget is returned separately so+ * it is never posted.+ */+export function packUploadBatches(+ files: File[],+ maxCount: number,+ maxBytes: number,+): { batches: File[][]; oversized: File[] } {+ const countLimit = Math.max(1, maxCount);+ const oversized: File[] = [];+ const batches: File[][] = [];+ let current: File[] = [];+ let currentBytes = 0;++ for (const file of files) {+ if (file.size > maxBytes) {+ oversized.push(file);+ continue;+ }+ const nextWouldExceedCount = current.length >= countLimit;+ const nextWouldExceedBytes = currentBytes + file.size > maxBytes;+ if (current.length > 0 && (nextWouldExceedCount || nextWouldExceedBytes)) {+ batches.push(current);+ current = [];+ currentBytes = 0;+ }+ current.push(file);+ currentBytes += file.size;+ }+ if (current.length > 0) {+ batches.push(current);+ }+ return { batches, oversized };+}export type UploadContextResult =| { type: "task"; taskId: string }| { type: "direct"; filename: string; responseId: string };@@ -21,6 +172,8 @@ export async function uploadFileForContext(endpoint: string,previousResponseId: string | null,): Promise<UploadContextResult> {+ await assertFilesWithinUploadLimit([file]);+const formData = new FormData();formData.append("file", file);formData.append("endpoint", endpoint);@@ -31,8 +184,9 @@ export async function uploadFileForContext(const response = await apiClient.post("/upload_context", formData);if (response.status < 200 || response.status >= 300) {- const errorText = getUploadErrorMessage(response.data);- throw new Error(errorText || "Failed to process document");+ throw new Error(+ uploadErrorText(response.data, "Failed to process document"),+ );}const result = response.data;@@ -96,7 +250,15 @@ export async function uploadFiles(files: File[],replace = false,preview = false,+ options?: {+ existingTaskId?: string;+ rejectedFiles?: File[];+ },): Promise<{ taskId: string; fileCount: number; previewMode: boolean }> {+ if (files.length > 0) {+ await assertFilesWithinUploadLimit(files);+ }+const formData = new FormData();for (const file of files) {formData.append("file", file);@@ -105,6 +267,20 @@ export async function uploadFiles(if (preview) {formData.append("preview", "true");}+ if (options?.existingTaskId) {+ formData.append("existing_task_id", options.existingTaskId);+ }+ if (options?.rejectedFiles && options.rejectedFiles.length > 0) {+ formData.append(+ "rejected_files",+ JSON.stringify(+ options.rejectedFiles.map((file) => ({+ filename: file.name,+ size: file.size,+ })),+ ),+ );+ }const uploadResponse = await apiClient.post("/router/upload_ingest",@@ -119,6 +295,9 @@ export async function uploadFiles(}if (typeof payload === "string") {+ if (uploadResponse.status < 200 || uploadResponse.status >= 300) {+ throw new Error(plainTextBody(payload));+ }throw new Error("Upload failed: unable to parse server response");}@@ -156,6 +335,8 @@ export async function uploadFile(preview = false,): Promise<UploadFileResult> {try {+ await assertFilesWithinUploadLimit([file]);+const formData = new FormData();formData.append("file", file);formData.append("replace_duplicates", replace.toString());@@ -179,6 +360,9 @@ export async function uploadFile(}if (typeof payload === "string") {+ if (uploadResponse.status < 200 || uploadResponse.status >= 300) {+ throw new Error(plainTextBody(payload));+ }throw new Error("Upload failed: unable to parse server response");}diff --git a/kubernetes/helm/openrag/templates/backend/backend-dotenv.yaml b/kubernetes/helm/openrag/templates/backend/backend-dotenv.yamlindex 77b7235ec..3f77c641b 100644--- a/kubernetes/helm/openrag/templates/backend/backend-dotenv.yaml+++ b/kubernetes/helm/openrag/templates/backend/backend-dotenv.yaml@@ -48,6 +48,9 @@ stringData:{{- if .Values.backend.uploadBatchSize }}UPLOAD_BATCH_SIZE={{ .Values.backend.uploadBatchSize }}{{- end }}+ {{- if .Values.backend.maxUploadMb }}+ OPENRAG_MAX_UPLOAD_MB={{ .Values.backend.maxUploadMb }}+ {{- end }}# Langflow urlLANGFLOW_URL={{ include "openrag.langflow.url" . | quote }}diff --git a/kubernetes/helm/openrag/values.yaml b/kubernetes/helm/openrag/values.yamlindex 15a8ffd7a..f5dc12a3f 100644--- a/kubernetes/helm/openrag/values.yaml+++ b/kubernetes/helm/openrag/values.yaml@@ -339,6 +339,7 @@ backend:# ConcurrencyuploadBatchSize: 25 # Max files per batch when ingesting from a folder+ maxUploadMb: 100 # Largest accepted upload, in mebibytes (OPENRAG_MAX_UPLOAD_MB)maxWorkers: "" # Backend worker processes; empty = auto (min(4, CPU_COUNT // 2))# Feature flags@@ -573,7 +574,9 @@ ingress:# Annotations for ingress controllerannotations: {}- # For nginx:+ # For nginx. This limits the OpenRAG ingress only. It does not change the+ # proxy in front of docling-serve; raise that proxy's client_max_body_size+ # separately, or lower backend.maxUploadMb to match it.# nginx.ingress.kubernetes.io/proxy-body-size: "100m"# nginx.ingress.kubernetes.io/proxy-read-timeout: "300"# For AWS ALB:diff --git a/kubernetes/operator/internal/controller/env.go b/kubernetes/operator/internal/controller/env.goindex 1f2575f32..2893a04c1 100644--- a/kubernetes/operator/internal/controller/env.go+++ b/kubernetes/operator/internal/controller/env.go@@ -136,6 +136,7 @@ func NewEnvVarManager() *EnvVarManager {"DISABLE_INGEST_WITH_LANGFLOW": "false","INGESTION_TIMEOUT": "3600","UPLOAD_BATCH_SIZE": "25",+ "OPENRAG_MAX_UPLOAD_MB": "100","MAX_WORKERS": "4",// Segment analytics (default empty, set via CR or operator env)diff --git a/src/api/langflow_files.py b/src/api/langflow_files.pyindex c91a2a9ac..dea5eb34c 100644--- a/src/api/langflow_files.py+++ b/src/api/langflow_files.py@@ -16,6 +16,7 @@ from dependencies import (from session_manager import Userfrom utils.file_utils import langflow_safe_filename_and_mimetypefrom utils.logging_config import get_logger+from utils.upload_limits import UploadTooLarge, read_upload_within_limit, upload_too_large_messagelogger = get_logger(__name__)@@ -43,7 +44,7 @@ async def upload_user_file(logger.debug("upload_user_file endpoint called")logger.debug("Processing file", filename=file.filename, size=file.size)- content = await file.read()+ content = await read_upload_within_limit(file)# Langflow's docling chokes on text/plain — rename .txt -> .md.upload_filename, upload_mimetype = langflow_safe_filename_and_mimetype(file.filename, file.content_type@@ -54,12 +55,16 @@ async def upload_user_file(result = await langflow_file_service.upload_user_file(file_tuple, user.jwt_token)logger.debug("Upload successful", result=result)return JSONResponse(result, status_code=201)+ except UploadTooLarge as e:+ message = upload_too_large_message(e.filename, e.size_bytes, e.limit_mb)+ logger.warning("Upload rejected: file too large", error_type=type(e).__name__)+ return JSONResponse({"error": message}, status_code=413)except Exception as e:logger.error("upload_user_file endpoint failed", error_type=type(e).__name__, error=str(e))import tracebacklogger.error("Full traceback", traceback=traceback.format_exc())- return JSONResponse({"error": str(e)}, status_code=500)+ return JSONResponse({"error": "An internal error occurred."}, status_code=500)async def run_ingestion(@@ -110,7 +115,8 @@ async def run_ingestion()return JSONResponse(result)except Exception as e:- return JSONResponse({"error": str(e)}, status_code=500)+ logger.error("run_ingestion endpoint failed", error_type=type(e).__name__, error=str(e))+ return JSONResponse({"error": "An internal error occurred."}, status_code=500)async def upload_and_ingest_user_file(@@ -141,7 +147,7 @@ async def upload_and_ingest_user_file(return JSONResponse({"error": f"Invalid tweaks JSON: {e}"}, status_code=400)jwt_token = user.jwt_token- content = await file.read()+ content = await read_upload_within_limit(file)temp_dir = tempfile.gettempdir()safe_filename = file.filename.replace(" ", "_").replace("/", "_")@@ -181,6 +187,10 @@ async def upload_and_ingest_user_file(safe_unlink(temp_path)raise+ except UploadTooLarge as e:+ message = upload_too_large_message(e.filename, e.size_bytes, e.limit_mb)+ logger.warning("Upload rejected: file too large", error=message)+ return JSONResponse({"error": message}, status_code=413)except Exception as e:logger.error("upload_and_ingest_user_file endpoint failed", error=str(e))return JSONResponse({"error": str(e)}, status_code=500)diff --git a/src/api/router.py b/src/api/router.pyindex 426ff60a7..1c3482015 100644--- a/src/api/router.py+++ b/src/api/router.py@@ -21,14 +21,58 @@ from dependencies import (from session_manager import Userfrom utils.ingest_preview_flag import is_ingest_preview_enabledfrom utils.logging_config import get_logger+from utils.upload_limits import UploadTooLarge, read_upload_within_limitlogger = get_logger(__name__)+def _form_str(value) -> str | None:+ """A real form string. A direct call leaves FastAPI's Form default in place."""+ return value if isinstance(value, str) else None+++def _rejected_uploads(raw: str | None) -> list[tuple[str, int]]:+ """Files the client kept out of the body because they exceed the limit."""+ if not isinstance(raw, str) or not raw:+ return []+ try:+ data = json.loads(raw)+ except (json.JSONDecodeError, TypeError):+ return []+ if not isinstance(data, list):+ return []+ rejections: list[tuple[str, int]] = []+ for item in data:+ if not isinstance(item, dict):+ continue+ name = item.get("filename")+ size = item.get("size")+ if isinstance(name, str) and name and isinstance(size, int) and size >= 0:+ rejections.append((name, size))+ return rejections+++def _rejection_only_response(task_service, user_id: str, rejections: list[tuple[str, int]]):+ if not rejections:+ return None+ task_id = task_service.record_rejected_uploads(user_id, rejections)+ return JSONResponse(+ {+ "task_id": task_id,+ "message": f"{len(rejections)} file(s) were over the upload limit",+ "file_count": 0,+ "preview_mode": False,+ },+ status_code=202,+ )++async def upload_ingest_router(request: Request,- file: list[UploadFile] = File(...),+ file: list[UploadFile] | None = File(None),session_id: str | None = Form(None),+ existing_task_id: str | None = Form(None),+ rejected_files: str | None = Form(None),settings_json: str | None = Form(None, alias="settings"),tweaks_json: str | None = Form(None, alias="tweaks"),replace_duplicates: str = Form("true"),@@ -65,11 +109,14 @@ async def upload_ingest_router(allow_anonymous_delete = await has_effective_permission(request, user, rbac, "knowledge:delete:anonymous")+ upload_files = file or []+ existing_task_id = _form_str(existing_task_id)+ rejections = _rejected_uploads(rejected_files)if disable_ingest_with_langflow:logger.debug("Routing to traditional OpenRAG upload via task service")return await _traditional_upload_ingest_task(- upload_files=file,+ upload_files=upload_files,replace_duplicates=replace_duplicates.lower() == "true",create_filter=create_filter.lower() == "true",preview_mode=preview_mode,@@ -78,11 +125,13 @@ async def upload_ingest_router(user=user,allow_anonymous_delete=allow_anonymous_delete,settings_json=settings_json,+ existing_task_id=existing_task_id,+ rejected_uploads=rejections,)logger.debug("Routing to Langflow upload-ingest pipeline via task service")return await _langflow_upload_ingest_task(- upload_files=file,+ upload_files=upload_files,session_id=session_id,settings_json=settings_json,tweaks_json=tweaks_json,@@ -94,6 +143,8 @@ async def upload_ingest_router(task_service=task_service,user=user,allow_anonymous_delete=allow_anonymous_delete,+ existing_task_id=existing_task_id,+ rejected_uploads=rejections,)@@ -107,10 +158,16 @@ async def _traditional_upload_ingest_task(user: User,allow_anonymous_delete: bool,settings_json: str | None = None,+ existing_task_id: str | None = None,+ rejected_uploads: list[tuple[str, int]] | None = None,):"""Task-based traditional upload and ingest for single/multiple files"""+ rejections = rejected_uploads or []try:if not upload_files:+ only_rejections = _rejection_only_response(task_service, user.user_id, rejections)+ if only_rejections is not None:+ return only_rejectionsreturn JSONResponse({"error": "Missing files"}, status_code=400)settings = None@@ -130,7 +187,7 @@ async def _traditional_upload_ingest_task(try:for upload_file in upload_files:- content = await upload_file.read()+ content = await read_upload_within_limit(upload_file)original_filenames.append(upload_file.filename)# Generate unique temp file with the original extension to assist docling/format detectionsuffix = os.path.splitext(upload_file.filename)[1] if upload_file.filename else ""@@ -169,7 +226,10 @@ async def _traditional_upload_ingest_task(settings=settings,preview_mode=preview_mode,allow_anonymous_delete=allow_anonymous_delete,+ existing_task_id=existing_task_id,)+ if rejections and not existing_task_id:+ task_service.record_rejected_uploads(user_id, rejections, task_id=task_id)return JSONResponse({@@ -190,6 +250,8 @@ async def _traditional_upload_ingest_task(safe_unlink(temp_path)raise+ except UploadTooLarge as e:+ return JSONResponse({"error": str(e)}, status_code=413)except Exception as e:logger.error("Task-based traditional upload_ingest failed", error=str(e))import traceback@@ -214,10 +276,16 @@ async def _langflow_upload_ingest_task(task_service,user: User,allow_anonymous_delete: bool,+ existing_task_id: str | None = None,+ rejected_uploads: list[tuple[str, int]] | None = None,):"""Task-based langflow upload and ingest for single/multiple files"""+ rejections = rejected_uploads or []try:if not upload_files:+ only_rejections = _rejection_only_response(task_service, user.user_id, rejections)+ if only_rejections is not None:+ return only_rejectionsreturn JSONResponse({"error": "Missing files"}, status_code=400)settings = None@@ -245,7 +313,7 @@ async def _langflow_upload_ingest_task(try:for upload_file in upload_files:- content = await upload_file.read()+ content = await read_upload_within_limit(upload_file)original_filenames.append(upload_file.filename)# Generate unique temp file with the original extension to assist docling/format detectionsuffix = os.path.splitext(upload_file.filename)[1] if upload_file.filename else ""@@ -283,7 +351,10 @@ async def _langflow_upload_ingest_task(replace_duplicates=replace_duplicates,preview_mode=preview_mode,allow_anonymous_delete=allow_anonymous_delete,+ existing_task_id=existing_task_id,)+ if rejections and not existing_task_id:+ task_service.record_rejected_uploads(user_id, rejections, task_id=task_id)return JSONResponse({@@ -304,6 +375,8 @@ async def _langflow_upload_ingest_task(safe_unlink(temp_path)raise+ except UploadTooLarge as e:+ return JSONResponse({"error": str(e)}, status_code=413)except Exception as e:logger.error("Task-based langflow upload_ingest failed", error=str(e))import tracebackdiff --git a/src/api/upload.py b/src/api/upload.pyindex e51a37bdc..52d39da3d 100644--- a/src/api/upload.py+++ b/src/api/upload.py@@ -140,9 +140,15 @@ async def upload_context(jwt_token = user.jwt_token- doc_result = await document_service.process_upload_context(- file, filename, user_id=user_id, jwt_token=jwt_token- )+ from services.docling_service import DoclingPayloadTooLarge+ from utils.upload_limits import UploadTooLarge++ try:+ doc_result = await document_service.process_upload_context(+ file, filename, user_id=user_id, jwt_token=jwt_token+ )+ except (UploadTooLarge, DoclingPayloadTooLarge) as exc:+ return JSONResponse({"error": str(exc)}, status_code=413)from config.settings import is_no_auth_mode@@ -182,8 +188,15 @@ async def upload_options("""Return availability of upload features"""aws_enabled = bool(os.getenv("AWS_ACCESS_KEY_ID") and os.getenv("AWS_SECRET_ACCESS_KEY"))from config.settings import UPLOAD_BATCH_SIZE+ from utils.upload_limits import max_upload_mb- return JSONResponse({"aws": aws_enabled, "upload_batch_size": UPLOAD_BATCH_SIZE})+ return JSONResponse(+ {+ "aws": aws_enabled,+ "upload_batch_size": UPLOAD_BATCH_SIZE,+ "max_upload_mb": max_upload_mb(),+ }+ )async def upload_bucket(diff --git a/src/config/settings.py b/src/config/settings.pyindex 89a2bca92..831b4911b 100644--- a/src/config/settings.py+++ b/src/config/settings.py@@ -18,6 +18,7 @@ from utils.container_utils import determine_docling_host, get_container_hostfrom utils.embedding_fields import build_knn_vector_fieldfrom utils.env_utils import get_env_float, get_env_int, get_env_setfrom utils.logging_config import get_logger+from utils.upload_limits import max_upload_mb_from_env# Import configuration managerfrom .config_manager import config_manager@@ -721,6 +722,13 @@ FETCH_OPENRAG_DOCS_AT_STARTUP = os.getenv("FETCH_OPENRAG_DOCS_AT_STARTUP", "fals# Maximum number of files to upload / ingest (in batch) per task when adding knowledge via folderUPLOAD_BATCH_SIZE = get_env_int("UPLOAD_BATCH_SIZE", 25)+# Largest accepted upload, in mebibytes. Enforced before a task is created and+# again before the file is posted to Docling Serve. This does not raise the+# body limit on the proxy in front of docling-serve; set it to that proxy's+# real limit when the proxy cannot be changed. Unset stays at 100. A value that+# is set but not a positive integer is logged and replaced with 100.+OPENRAG_MAX_UPLOAD_MB = max_upload_mb_from_env(os.getenv("OPENRAG_MAX_UPLOAD_MB"))+# Langflow HTTP timeout configuration (in seconds)# For large documents (300+ pages), ingestion can take 30+ minutes# Default: 40 minutes total, 40 minutes read timeoutdiff --git a/src/services/docling_service.py b/src/services/docling_service.pyindex a585d5524..a96fca248 100644--- a/src/services/docling_service.py+++ b/src/services/docling_service.py@@ -53,6 +53,18 @@ class DoclingTransientError(DoclingServeError):"""Raised for errors that may resolve on retry (network failures, 5xx)."""+class DoclingPayloadTooLarge(DoclingServeError):+ """The proxy in front of docling-serve rejected the file body (HTTP 413).++ ``str(self)`` is the line shown to users. ``operator_detail`` keeps the+ internal endpoint for logs.+ """++ def __init__(self, message: str, *, operator_detail: str | None = None):+ super().__init__(message)+ self.operator_detail = operator_detail++class DoclingTaskState(StrEnum):"""Result of a single status check against Docling Serve."""@@ -563,6 +575,17 @@ class DoclingService:"""Upload a file to Docling Serve asynchronously using direct multipart/form-data upload."""+ from utils.upload_limits import (+ docling_payload_too_large_message,+ docling_rejected_size_message,+ ensure_within_upload_limit,+ format_byte_size,+ max_upload_mb,+ )++ ensure_within_upload_limit(filename, len(file_content))+ endpoint = f"{self.docling_url}/v1/convert/file/async"+options = await self._build_docling_options_async(ocr_override=ocr,picture_descriptions_override=picture_descriptions,@@ -592,24 +615,38 @@ class DoclingService:if should_close:async with client:response = await client.post(- f"{self.docling_url}/v1/convert/file/async",+ endpoint,files=files,data=data,headers=headers,)else:response = await client.post(- f"{self.docling_url}/v1/convert/file/async",+ endpoint,files=files,data=data,headers=headers,)+ if response.status_code == 413:+ size_bytes = len(file_content)+ raise DoclingPayloadTooLarge(+ docling_rejected_size_message(+ filename, format_byte_size(size_bytes), max_upload_mb()+ ),+ operator_detail=docling_payload_too_large_message(+ filename, size_bytes, endpoint+ ),+ )response.raise_for_status()task = response.json()return task["task_id"]except Exception as e:- logger.error("Docling upload failed", filename=filename, error=str(e))+ logger.error(+ "Docling upload failed",+ filename=filename,+ error=getattr(e, "operator_detail", None) or str(e),+ )raiseasync def get_docling_result_async(diff --git a/src/services/document_service.py b/src/services/document_service.pyindex 378b5c6c1..2766f43b4 100644--- a/src/services/document_service.py+++ b/src/services/document_service.py@@ -178,14 +178,10 @@ class DocumentService:if not filename:filename = upload_file.filename or "uploaded_document"- # Stream file content into BytesIO- content = io.BytesIO()- while True:- chunk = await upload_file.read(1 << 20) # 1MB chunks- if not chunk:- break- content.write(chunk)- content.seek(0) # Reset to beginning for reading+ from utils.upload_limits import read_upload_within_limit++ # Stop once the file crosses the upload limit, before the rest is buffered.+ content = io.BytesIO(await read_upload_within_limit(upload_file, filename))# Check if this is a .txt or .md file - use simple processingfile_ext = os.path.splitext(filename)[1].lower()diff --git a/src/services/langflow_file_service.py b/src/services/langflow_file_service.pyindex a8fea9709..47af817d0 100644--- a/src/services/langflow_file_service.py+++ b/src/services/langflow_file_service.py@@ -1032,6 +1032,9 @@ class LangflowFileService:"DoclingService is not configured. Ensure DOCLING_SERVE_URL is set ""and the service was injected correctly.")+ from services.docling_service import DoclingPayloadTooLarge+ from utils.upload_limits import UploadTooLarge+try:task_id = await self.docling_service.upload_to_docling_direct_async(filename,@@ -1052,6 +1055,8 @@ class LangflowFileService:"[LF] Docling submission failed",extra={"error": str(e), "filename": filename},)+ if isinstance(e, (UploadTooLarge, DoclingPayloadTooLarge)):+ raiseraise Exception(f"Docling upload failed: {str(e)}") from easync def upload_and_ingest_file(diff --git a/src/services/task_service.py b/src/services/task_service.pyindex 9cea924ad..11b361039 100644--- a/src/services/task_service.py+++ b/src/services/task_service.py@@ -374,6 +374,7 @@ class TaskService:preview_mode: bool = False,*,allow_anonymous_delete: bool,+ existing_task_id: str | None = None,) -> str:"""Create a new upload task for bulk file processing.@@ -404,6 +405,7 @@ class TaskService:original_filenames=original_filenames,temp_file_paths=file_paths,preview_mode=preview_mode,+ existing_task_id=existing_task_id,)async def create_langflow_upload_task(@@ -462,6 +464,54 @@ class TaskService:preview_mode=preview_mode,)+ def record_rejected_uploads(+ self,+ user_id: str,+ rejections: list[tuple[str, int]],+ *,+ task_id: str | None = None,+ ) -> str:+ """Keep files the client did not send because they exceed the upload limit.++ Attached to ``task_id`` when that task exists, already counted as+ failed, so the panel shows them after the toasts are gone. Otherwise a+ completed task that contains only these failures.+ """+ from utils.upload_limits import max_upload_mb, upload_too_large_message++ if not rejections:+ raise ValueError("rejections must not be empty")++ limit_mb = max_upload_mb()+ store_user_id = user_id or AnonymousUser().user_id+ upload_task = self._find_upload_task(task_id) if task_id else None+ created = upload_task is None+ if upload_task is None:+ upload_task = UploadTask(+ task_id=task_id or str(uuid.uuid4()),+ total_files=0,+ status=TaskStatus.COMPLETED,+ )+ if store_user_id not in self.task_store:+ self.task_store[store_user_id] = {}+ self.task_store[store_user_id][upload_task.task_id] = upload_task++ for index, (filename, size_bytes) in enumerate(rejections):+ key = f"over-limit:{upload_task.task_id}:{index}:{filename}"+ upload_task.file_tasks[key] = FileTask(+ file_path=key,+ filename=filename,+ status=TaskStatus.FAILED,+ error=upload_too_large_message(filename, size_bytes, limit_mb),+ )+ upload_task.total_files += 1+ upload_task.failed_files += 1+ upload_task.processed_files += 1+ upload_task.updated_at = time.time()+ if created:+ upload_task.status = TaskStatus.COMPLETED+ return upload_task.task_id+async def create_url_upload_task(self,owner_user_id: str,@@ -1276,6 +1326,19 @@ class TaskService:"actionable_by": "USER_ACTIONABLE",}+ from utils.upload_limits import is_upload_size_error, upload_size_user_message++ # A size refusal is stored while docling_status is still PENDING, because+ # the proxy rejects the body before a Docling task exists. Later branches+ # would drop that text.+ if is_upload_size_error(error):+ return {+ "component": "docling",+ "failure_phase": "parsing",+ "user_facing_message": upload_size_user_message(error),+ "actionable_by": "USER_ACTIONABLE",+ }+# Before the substring heuristics below, which would otherwise read this# as a plain duplicate: the file was never ingested, and retrying is# exactly the right move.diff --git a/src/utils/upload_limits.py b/src/utils/upload_limits.pynew file mode 100644index 000000000..bef6aec92--- /dev/null+++ b/src/utils/upload_limits.py@@ -0,0 +1,167 @@+"""Upload size limit shared by the API, Docling submission, and task errors.++The proxy in front of Docling Serve rejects the request body (often at 1 MB).+OpenRAG refuses a larger file before a task is created and again before the+file is posted to Docling. The HTTP body is already received by then; a reverse+proxy in front of OpenRAG is what caps it while it arrives. A 413 from the+Docling proxy uses a separate message that still carries the limit marker.+URL ingest does not post a file body and does not use this limit.+"""++from __future__ import annotations++import re++from utils.logging_config import get_logger++logger = get_logger(__name__)++_MIB = 1024 * 1024+_READ_CHUNK = 1 << 20+_MARKER = "OPENRAG_MAX_UPLOAD_MB"+_UNITS = ("B", "KB", "MB", "GB", "TB")+# Backstop. Callers store the user line, not this operator shape. If a task+# error still has "was rejected by <endpoint>", hide that endpoint.+_PROXY_REJECTION = re.compile(r'^"(?P<filename>.*)" \((?P<size>[^)]+)\) was rejected by \S+')+++class UploadTooLarge(Exception):+ """The file is larger than OPENRAG_MAX_UPLOAD_MB."""++ def __init__(self, filename: str, size_bytes: int, limit_mb: int):+ self.filename = filename+ self.size_bytes = size_bytes+ self.limit_mb = limit_mb+ super().__init__(upload_too_large_message(filename, size_bytes, limit_mb))+++def max_upload_mb_from_env(raw: str | None, *, default: int = 100) -> int:+ """Read OPENRAG_MAX_UPLOAD_MB. Unset stays at the default with no log.++ A value that is set but not a positive integer is logged and replaced with+ the default. Using 0 or a negative number as the limit would reject every+ non-empty file.+ """+ if raw is None or raw.strip() == "":+ return default+ try:+ value = int(raw.strip())+ except ValueError:+ value = None+ if value is None or value < 1:+ logger.warning(+ "OPENRAG_MAX_UPLOAD_MB is not a positive integer; using the default",+ value=raw,+ default=default,+ )+ return default+ return value+++def max_upload_mb() -> int:+ """Configured limit in mebibytes. Values below 1 fall back to 100."""+ from config import settings++ value = settings.OPENRAG_MAX_UPLOAD_MB+ if not isinstance(value, int) or value < 1:+ return 100+ return value+++def max_upload_bytes() -> int:+ return max_upload_mb() * _MIB+++def format_byte_size(num_bytes: int) -> str:+ """Match the frontend file-size label (1024-based, one decimal above bytes)."""+ size = float(max(num_bytes, 0))+ if size < 1024:+ return f"{int(size)} B"+ unit_index = 0+ while size >= 1024 and unit_index < len(_UNITS) - 1:+ size /= 1024+ unit_index += 1+ return f"{size:.1f} {_UNITS[unit_index]}"+++def upload_too_large_message(filename: str, size_bytes: int, limit_mb: int) -> str:+ return (+ f'"{filename}" is {format_byte_size(size_bytes)}. '+ f"The upload limit is {limit_mb} MB ({_MARKER})."+ )+++def docling_rejected_size_message(filename: str, size_label: str, limit_mb: int) -> str:+ """User-facing line when the document-processing service rejects the file.++ The file is already within ``OPENRAG_MAX_UPLOAD_MB``; a proxy in front of+ that service rejected it. Distinct from ``upload_too_large_message``. The+ marker keeps task classification on the size-error path. The nginx remedy+ stays in the operator log, not here.+ """+ return (+ f'"{filename}" is {size_label}. '+ "The document-processing service rejected the file because of its size. "+ f"This file is within the configured upload limit ({limit_mb} MB, {_MARKER}). "+ "A proxy in front of that service is enforcing a smaller limit. "+ f"Ask an administrator to raise it, or set {_MARKER} to that proxy's limit."+ )+++def docling_payload_too_large_message(filename: str, size_bytes: int, endpoint: str) -> str:+ return (+ f'"{filename}" ({format_byte_size(size_bytes)}) was rejected by {endpoint} '+ "with HTTP 413. The proxy in front of Docling Serve is limiting the request body. "+ "Raise that limit (nginx: client_max_body_size), or set "+ f"{_MARKER} to the proxy's real limit."+ )+++def ensure_within_upload_limit(filename: str | None, size_bytes: int) -> None:+ """Raise UploadTooLarge when the file is over the configured limit."""+ limit_bytes = max_upload_bytes()+ if size_bytes > limit_bytes:+ raise UploadTooLarge(filename or "upload", size_bytes, max_upload_mb())+++async def read_upload_within_limit(upload_file, filename: str | None = None) -> bytes:+ """Copy an upload into memory only when it is within OPENRAG_MAX_UPLOAD_MB.++ Starlette has already received the multipart part. A known size is rejected+ before those bytes are copied into memory. When the size is missing, the+ part is read in 1 MiB chunks and copying stops once the limit is crossed.+ """+ name = filename if filename is not None else getattr(upload_file, "filename", None)+ known_size = getattr(upload_file, "size", None)+ if isinstance(known_size, int) and known_size > max_upload_bytes():+ raise UploadTooLarge(name or "upload", known_size, max_upload_mb())++ chunks: list[bytes] = []+ size = 0+ while True:+ chunk = await upload_file.read(_READ_CHUNK)+ if not chunk:+ break+ size += len(chunk)+ ensure_within_upload_limit(name, size)+ chunks.append(chunk)+ # A short read is the end of the body. Stopping here also keeps a+ # caller that returns the same bytes on every read from looping.+ if len(chunk) < _READ_CHUNK:+ break+ return b"".join(chunks)+++def is_upload_size_error(error: str | None) -> bool:+ return _MARKER in (error or "")+++def upload_size_user_message(error: str) -> str:+ """Limit line for the task UI, without the internal Docling URL."""+ text = error.removeprefix("Docling upload failed: ").strip()+ match = _PROXY_REJECTION.match(text)+ if match is None:+ return text+ return docling_rejected_size_message(+ match.group("filename"), match.group("size"), max_upload_mb()+ )diff --git a/tests/unit/services/test_upload_context_size.py b/tests/unit/services/test_upload_context_size.pynew file mode 100644index 000000000..aee718662--- /dev/null+++ b/tests/unit/services/test_upload_context_size.py@@ -0,0 +1,73 @@+"""Chat context uploads refuse an oversized file on the request the user is waiting for."""++from unittest.mock import AsyncMock, MagicMock++import pytest++from services.docling_service import DoclingPayloadTooLarge+from services.document_service import DocumentService+from utils.upload_limits import (+ UploadTooLarge,+ docling_payload_too_large_message,+ docling_rejected_size_message,+ format_byte_size,+)+++async def test_process_upload_context_rejects_before_docling(monkeypatch):+ monkeypatch.setattr("config.settings.OPENRAG_MAX_UPLOAD_MB", 1)+ upload = MagicMock()+ upload.read = AsyncMock(side_effect=[b"x" * (1024 * 1024 + 1), b""])+ docling = MagicMock()+ docling.convert_bytes = AsyncMock()++ service = DocumentService(docling_service=docling)++ with pytest.raises(UploadTooLarge, match="notes.pdf"):+ await service.process_upload_context(upload, filename="notes.pdf")++ docling.convert_bytes.assert_not_called()+++async def test_upload_context_returns_413_for_a_size_refusal():+ from api import upload as upload_module++ class FakeUser:+ user_id = "alice"+ db_user_id = "db-alice"+ jwt_token = "token"+ name = "A"+ email = "a@x"++ document_service = MagicMock()+ document_service.process_upload_context = AsyncMock(+ side_effect=DoclingPayloadTooLarge(+ docling_rejected_size_message("notes.pdf", format_byte_size(2 * 1024 * 1024), 100),+ operator_detail=docling_payload_too_large_message(+ "notes.pdf",+ 2 * 1024 * 1024,+ "https://docling-serve:5001/v1/convert/file/async",+ ),+ )+ )+ chat_service = MagicMock()+ chat_service.upload_context_chat = AsyncMock()++ response = await upload_module.upload_context(+ file=MagicMock(),+ previous_response_id=None,+ endpoint="chat",+ document_service=document_service,+ chat_service=chat_service,+ session_manager=None,+ user=FakeUser(),+ )++ assert response.status_code == 413+ assert b"notes.pdf" in response.body+ assert b"document-processing service" in response.body+ assert b"client_max_body_size" not in response.body+ assert b"docling-serve" not in response.body+ chat_service.upload_context_chat.assert_not_called()diff --git a/tests/unit/test_docling_service.py b/tests/unit/test_docling_service.pyindex 091393dd6..945954572 100644--- a/tests/unit/test_docling_service.py+++ b/tests/unit/test_docling_service.py@@ -8,7 +8,8 @@ from unittest.mock import AsyncMock, MagicMock, patchimport httpximport pytest-from services.docling_service import DoclingServeError, DoclingService+from services.docling_service import DoclingPayloadTooLarge, DoclingServeError, DoclingService+from utils.upload_limits import UploadTooLarge# Shape of a /v1/result body for a password-protected PDF: the task ran to# completion, but the conversion failed and no document was exported.@@ -219,6 +220,48 @@ async def test_upload_http_error(docling_service, mock_httpx_client):await docling_service.upload_to_docling_direct_async("test.pdf", b"data")+async def test_upload_refuses_before_posting_when_over_the_limit(+ docling_service, mock_httpx_client, monkeypatch+):+ monkeypatch.setattr("config.settings.OPENRAG_MAX_UPLOAD_MB", 1)++ with pytest.raises(UploadTooLarge, match="big.pdf"):+ await docling_service.upload_to_docling_direct_async("big.pdf", b"x" * (1024 * 1024 + 1))++ mock_httpx_client.post.assert_not_called()+++async def test_upload_maps_docling_proxy_413(docling_service, mock_httpx_client):+ """A 413 from the proxy becomes a message that names the file and the fix."""+ mock_httpx_client.post.return_value = _make_response(413)++ with patch("services.docling_service.get_openrag_config") as mock_get_config:+ mock_config = MagicMock()+ mock_config.knowledge.table_structure = False+ mock_config.knowledge.ocr = False+ mock_config.knowledge.picture_descriptions = False+ mock_config.knowledge.vlm_enabled = False+ mock_get_config.return_value = mock_config++ with (+ patch("services.docling_service.logger") as mock_logger,+ pytest.raises(DoclingPayloadTooLarge, match="report.pdf") as exc_info,+ ):+ await docling_service.upload_to_docling_direct_async("report.pdf", b"data")++ message = str(exc_info.value)+ assert "document-processing service" in message+ assert "within the configured upload limit" in message+ assert "OPENRAG_MAX_UPLOAD_MB" in message+ assert "http://docling:8000" not in message+ assert "client_max_body_size" not in message+ logged = mock_logger.error.call_args.kwargs["error"]+ assert "http://docling:8000/v1/convert/file/async" in logged+ assert "client_max_body_size" in logged++# ── Configuration Logic ─────────────────────────────────────────────diff --git a/tests/unit/test_langflow_files_upload_limit.py b/tests/unit/test_langflow_files_upload_limit.pynew file mode 100644index 000000000..ba50c04fe--- /dev/null+++ b/tests/unit/test_langflow_files_upload_limit.py@@ -0,0 +1,108 @@+"""The Langflow file routes refuse an oversized upload before doing any work."""++import json+from unittest.mock import AsyncMock, MagicMock++import pytest+from fastapi import UploadFile++from api.langflow_files import upload_and_ingest_user_file, upload_user_file+from session_manager import User+++def _user() -> User:+ return User(user_id="user-1", email="[email protected]", name="User", jwt_token="Bearer tok")+++def _file(filename: str, content: bytes) -> MagicMock:+ upload = MagicMock(spec=UploadFile)+ upload.filename = filename+ upload.content_type = "application/pdf"+ upload.size = None+ upload.read = AsyncMock(side_effect=[content, b""])+ return upload+++def _error(response) -> str:+ return json.loads(response.body.decode())["error"]+++async def test_langflow_file_upload_rejects_an_oversized_file_before_posting(monkeypatch):+ monkeypatch.setattr("config.settings.OPENRAG_MAX_UPLOAD_MB", 1)+ service = MagicMock()+ service.upload_user_file = AsyncMock()++ response = await upload_user_file(+ file=_file("big.pdf", b"x" * (1024 * 1024 + 1)),+ langflow_file_service=service,+ user=_user(),+ )++ assert response.status_code == 413+ assert "big.pdf" in _error(response)+ assert "OPENRAG_MAX_UPLOAD_MB" in _error(response)+ service.upload_user_file.assert_not_called()+++async def test_langflow_file_upload_rejects_a_declared_size_without_reading(monkeypatch):+ monkeypatch.setattr("config.settings.OPENRAG_MAX_UPLOAD_MB", 1)+ upload = _file("big.pdf", b"")+ upload.size = 2 * 1024 * 1024+ upload.read = AsyncMock()+ service = MagicMock()+ service.upload_user_file = AsyncMock()++ response = await upload_user_file(file=upload, langflow_file_service=service, user=_user())++ assert response.status_code == 413+ upload.read.assert_not_called()+ service.upload_user_file.assert_not_called()+++async def test_langflow_upload_ingest_rejects_an_oversized_file_before_a_task(monkeypatch):+ monkeypatch.setattr("config.settings.OPENRAG_MAX_UPLOAD_MB", 1)+ task_service = MagicMock()+ task_service.create_langflow_upload_task = AsyncMock(return_value="task-1")++ response = await upload_and_ingest_user_file(+ file=_file("big.pdf", b"x" * (1024 * 1024 + 1)),+ session_id=None,+ settings_json=None,+ tweaks_json=None,+ langflow_file_service=MagicMock(),+ session_manager=MagicMock(),+ task_service=task_service,+ user=_user(),+ )++ assert response.status_code == 413+ assert "big.pdf" in _error(response)+ task_service.create_langflow_upload_task.assert_not_called()+++async def test_langflow_upload_ingest_rejects_a_declared_size_without_reading(monkeypatch):+ monkeypatch.setattr("config.settings.OPENRAG_MAX_UPLOAD_MB", 1)+ upload = _file("big.pdf", b"")+ upload.size = 2 * 1024 * 1024+ upload.read = AsyncMock()+ task_service = MagicMock()+ task_service.create_langflow_upload_task = AsyncMock(return_value="task-1")++ response = await upload_and_ingest_user_file(+ file=upload,+ session_id=None,+ settings_json=None,+ tweaks_json=None,+ langflow_file_service=MagicMock(),+ session_manager=MagicMock(),+ task_service=task_service,+ user=_user(),+ )++ assert response.status_code == 413+ upload.read.assert_not_called()+ task_service.create_langflow_upload_task.assert_not_called()diff --git a/tests/unit/test_router_upload_limit.py b/tests/unit/test_router_upload_limit.pynew file mode 100644index 000000000..dd8160b03--- /dev/null+++ b/tests/unit/test_router_upload_limit.py@@ -0,0 +1,134 @@+"""Oversized uploads are refused before a task is created."""++import json+from unittest.mock import AsyncMock, MagicMock, patch++import pytest+from fastapi import UploadFile++from api.router import _langflow_upload_ingest_task, _traditional_upload_ingest_task+from session_manager import User+++def _user() -> User:+ return User(user_id="user-1", email="[email protected]", name="User", jwt_token="Bearer tok")+++def _file(filename: str, content: bytes) -> MagicMock:+ upload = MagicMock(spec=UploadFile)+ upload.filename = filename+ upload.content_type = "application/pdf"+ upload.size = None+ upload.read = AsyncMock(side_effect=[content, b""])+ return upload+++async def test_langflow_upload_rejects_oversized_file_before_creating_a_task(monkeypatch):+ monkeypatch.setattr("config.settings.OPENRAG_MAX_UPLOAD_MB", 1)+ task_service = MagicMock()+ task_service.create_langflow_upload_task = AsyncMock(return_value="task-1")++ response = await _langflow_upload_ingest_task(+ upload_files=[_file("big.pdf", b"x" * (1024 * 1024 + 1))],+ session_id=None,+ settings_json=None,+ tweaks_json=None,+ replace_duplicates=True,+ create_filter=False,+ preview_mode=False,+ langflow_file_service=MagicMock(),+ session_manager=MagicMock(),+ task_service=task_service,+ user=_user(),+ allow_anonymous_delete=False,+ )++ assert response.status_code == 413+ body = json.loads(response.body.decode())+ assert "big.pdf" in body["error"]+ assert "OPENRAG_MAX_UPLOAD_MB" in body["error"]+ task_service.create_langflow_upload_task.assert_not_called()+++async def test_langflow_upload_rejects_declared_size_without_reading(monkeypatch):+ monkeypatch.setattr("config.settings.OPENRAG_MAX_UPLOAD_MB", 1)+ upload = _file("big.pdf", b"")+ upload.size = 2 * 1024 * 1024+ upload.read = AsyncMock()+ task_service = MagicMock()+ task_service.create_langflow_upload_task = AsyncMock(return_value="task-1")++ response = await _langflow_upload_ingest_task(+ upload_files=[upload],+ session_id=None,+ settings_json=None,+ tweaks_json=None,+ replace_duplicates=True,+ create_filter=False,+ preview_mode=False,+ langflow_file_service=MagicMock(),+ session_manager=MagicMock(),+ task_service=task_service,+ user=_user(),+ allow_anonymous_delete=False,+ )++ assert response.status_code == 413+ upload.read.assert_not_called()+ task_service.create_langflow_upload_task.assert_not_called()+++async def test_langflow_upload_accepts_a_file_under_the_limit():+ task_service = MagicMock()+ task_service.create_langflow_upload_task = AsyncMock(return_value="task-1")+ mock_temp_file = MagicMock()+ mock_temp_file.name = "/tmp/small.pdf"++ with (+ patch("api.router.tempfile.NamedTemporaryFile", return_value=mock_temp_file),+ patch("api.router.open", create=True),+ patch("utils.file_utils.safe_unlink"),+ ):+ response = await _langflow_upload_ingest_task(+ upload_files=[_file("small.pdf", b"%PDF")],+ session_id=None,+ settings_json=None,+ tweaks_json=None,+ replace_duplicates=True,+ create_filter=False,+ preview_mode=False,+ langflow_file_service=MagicMock(),+ session_manager=MagicMock(),+ task_service=task_service,+ user=_user(),+ allow_anonymous_delete=False,+ )++ assert response.status_code == 202+ task_service.create_langflow_upload_task.assert_awaited()+++async def test_traditional_upload_rejects_oversized_file_before_creating_a_task(monkeypatch):+ monkeypatch.setattr("config.settings.OPENRAG_MAX_UPLOAD_MB", 1)+ task_service = MagicMock()+ task_service.create_upload_task = AsyncMock(return_value="task-1")++ response = await _traditional_upload_ingest_task(+ upload_files=[_file("big.pdf", b"x" * (1024 * 1024 + 1))],+ replace_duplicates=True,+ create_filter=False,+ preview_mode=False,+ session_manager=MagicMock(),+ task_service=task_service,+ user=_user(),+ allow_anonymous_delete=False,+ )++ assert response.status_code == 413+ body = json.loads(response.body.decode())+ assert "big.pdf" in body["error"]+ task_service.create_upload_task.assert_not_called()diff --git a/tests/unit/test_task_service_get_task_status2.py b/tests/unit/test_task_service_get_task_status2.pyindex 8af68728a..32c5a5444 100644--- a/tests/unit/test_task_service_get_task_status2.py+++ b/tests/unit/test_task_service_get_task_status2.py@@ -57,6 +57,30 @@ def _store_task(task_service: TaskService, user_id: str, upload_task: UploadTaskclass TestInferFailureMetadata:+ def test_upload_size_error_while_docling_is_still_pending(self, task_service):+ message = (+ '"report.pdf" (1.9 MB) was rejected by '+ "https://docling-serve:5001/v1/convert/file/async with HTTP 413. "+ "Raise that limit (nginx: client_max_body_size), or set "+ "OPENRAG_MAX_UPLOAD_MB to the proxy's real limit."+ )+ ft = _make_file_task(+ phase=IngestionPhase.DOCLING,+ docling_status=DoclingPhaseStatus.PENDING,+ error=f"Docling upload failed: {message}",+ )+ meta = task_service._infer_failure_metadata(ft)+ assert meta is not None+ assert meta["component"] == "docling"+ assert meta["failure_phase"] == "parsing"+ assert meta["actionable_by"] == "USER_ACTIONABLE"+ assert meta["user_facing_message"].startswith('"report.pdf" is 1.9 MB.')+ assert "document-processing service" in meta["user_facing_message"]+ assert "within the configured upload limit" in meta["user_facing_message"]+ assert "OPENRAG_MAX_UPLOAD_MB" in meta["user_facing_message"]+ assert "docling-serve" not in meta["user_facing_message"]+ assert "client_max_body_size" not in meta["user_facing_message"]+def test_docling_failed_status(self, task_service):ft = _make_file_task(docling_status=DoclingPhaseStatus.FAILED)meta = task_service._infer_failure_metadata(ft)@@ -892,3 +916,37 @@ class TestGetTaskStatus2OpenSearchFailure:# ...but the raw error stays on the entry, which is the only way to# diagnose which OpenSearch operation actually failed.assert file_entry["error"].startswith("ConflictError(409, '{")+++class TestRejectedUploads:+ def test_files_over_the_limit_stay_on_a_task(self, task_service):+ task_id = task_service.record_rejected_uploads(+ "user1",+ [("huge.pdf", 5 * 1024 * 1024), ("big.pdf", 9 * 1024 * 1024)],+ )++ status = task_service.get_task_status2("user1", task_id)++ assert status["status"] == "completed"+ assert status["total_files"] == 2+ assert status["failed_files"] == 2+ assert status["successful_files"] == 0+ names = {entry["filename"] for entry in status["files"].values()}+ assert names == {"huge.pdf", "big.pdf"}+ for entry in status["files"].values():+ assert entry["status"] == "failed"+ assert entry["actionable_by"] == "USER_ACTIONABLE"+ assert "OPENRAG_MAX_UPLOAD_MB" in entry["user_facing_message"]++ def test_later_rejections_join_the_same_task(self, task_service):+ task_id = task_service.record_rejected_uploads("user1", [("huge.pdf", 5 * 1024 * 1024)])+ task_service.record_rejected_uploads(+ "user1",+ [("big.pdf", 9 * 1024 * 1024)],+ task_id=task_id,+ )++ status = task_service.get_task_status2("user1", task_id)++ assert status["failed_files"] == 2+ assert len(status["files"]) == 2diff --git a/tests/unit/test_upload_limits.py b/tests/unit/test_upload_limits.pynew file mode 100644index 000000000..94c54cef1--- /dev/null+++ b/tests/unit/test_upload_limits.py@@ -0,0 +1,144 @@+"""Messages for an upload that exceeds OPENRAG_MAX_UPLOAD_MB or the Docling proxy."""++import pytest++from utils import upload_limits+from utils.upload_limits import (+ docling_payload_too_large_message,+ docling_rejected_size_message,+ is_upload_size_error,+ max_upload_mb_from_env,+ read_upload_within_limit,+ upload_size_user_message,+ upload_too_large_message,+)+++class _Warnings:+ def __init__(self):+ self.records: list[tuple[str, dict]] = []++ def warning(self, message, **fields):+ self.records.append((message, fields))++ def __getattr__(self, _name):+ return lambda *args, **kwargs: None+++def test_unset_upload_limit_stays_at_the_default_without_a_warning(monkeypatch):+ recorder = _Warnings()+ monkeypatch.setattr(upload_limits, "logger", recorder)++ assert max_upload_mb_from_env(None) == 100+ assert max_upload_mb_from_env("") == 100+ assert max_upload_mb_from_env(" ") == 100+ assert recorder.records == []+++def test_bad_upload_limit_is_logged_and_replaced_with_the_default(monkeypatch):+ recorder = _Warnings()+ monkeypatch.setattr(upload_limits, "logger", recorder)++ for raw in ("100MB", "1.5", "0", "-1"):+ assert max_upload_mb_from_env(raw) == 100++ assert [fields["value"] for _, fields in recorder.records] == ["100MB", "1.5", "0", "-1"]+++def test_a_positive_upload_limit_is_kept(monkeypatch):+ recorder = _Warnings()+ monkeypatch.setattr(upload_limits, "logger", recorder)++ assert max_upload_mb_from_env("1") == 1+ assert max_upload_mb_from_env(" 100 ") == 100+ assert recorder.records == []+++def test_upload_too_large_message_names_the_file_and_its_size():+ message = upload_too_large_message("report.pdf", 2 * 1024 * 1024, 1)++ assert "report.pdf" in message+ assert "2.0 MB" in message+ assert "1 MB" in message+ assert "OPENRAG_MAX_UPLOAD_MB" in message+ assert is_upload_size_error(message)+++def test_docling_413_message_names_the_endpoint_and_both_fixes():+ endpoint = "https://docling-serve:5001/v1/convert/file/async"+ message = docling_payload_too_large_message("report.pdf", 2 * 1024 * 1024, endpoint)++ assert "report.pdf" in message+ assert "2.0 MB" in message+ assert endpoint in message+ assert "HTTP 413" in message+ assert "client_max_body_size" in message+ assert "OPENRAG_MAX_UPLOAD_MB" in message+ assert is_upload_size_error(message)+++def test_upload_size_user_message_drops_the_langflow_wrapper():+ inner = upload_too_large_message("report.pdf", 10, 1)+ assert upload_size_user_message(f"Docling upload failed: {inner}") == inner+++def test_upload_size_user_message_hides_the_docling_endpoint(monkeypatch):+ monkeypatch.setattr("config.settings.OPENRAG_MAX_UPLOAD_MB", 1)+ operator = docling_payload_too_large_message(+ "report.pdf",+ 2 * 1024 * 1024,+ "https://docling-serve:5001/v1/convert/file/async",+ )++ message = upload_size_user_message(f"Docling upload failed: {operator}")++ assert message == docling_rejected_size_message("report.pdf", "2.0 MB", 1)+ assert "document-processing service" in message+ assert "within the configured upload limit" in message+ assert "docling-serve" not in message+ assert "client_max_body_size" not in message+++class _ChunkedUpload:+ def __init__(self, chunks: list[bytes], size: int | None = None, filename: str = "notes.pdf"):+ self._chunks = list(chunks)+ self.size = size+ self.filename = filename+ self.reads = 0++ async def read(self, _n: int = -1) -> bytes:+ self.reads += 1+ if not self._chunks:+ return b""+ return self._chunks.pop(0)+++async def test_read_upload_stops_when_the_declared_size_is_over_the_limit(monkeypatch):+ monkeypatch.setattr("config.settings.OPENRAG_MAX_UPLOAD_MB", 1)+ upload = _ChunkedUpload([b"x" * 10], size=2 * 1024 * 1024)++ with pytest.raises(Exception, match="notes.pdf"):+ await read_upload_within_limit(upload)++ assert upload.reads == 0+++async def test_read_upload_stops_after_the_chunk_that_crosses_the_limit(monkeypatch):+ monkeypatch.setattr("config.settings.OPENRAG_MAX_UPLOAD_MB", 1)+ chunk = b"x" * (1024 * 1024)+ upload = _ChunkedUpload([chunk, chunk, chunk])++ with pytest.raises(Exception, match="notes.pdf"):+ await read_upload_within_limit(upload)++ assert upload.reads == 2+++async def test_read_upload_treats_a_short_chunk_as_the_end_of_the_body():+ upload = _ChunkedUpload([b"small", b"not-read"])++ assert await read_upload_within_limit(upload) == b"small"+ assert upload.reads == 1