@exulu/backend 5.12.0 → 5.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,257 @@
1
+ import * as fs from "fs";
2
+ import * as os from "os";
3
+ import * as path from "path";
4
+
5
+ jest.mock("@EE/entitlements", () => ({ checkLicense: () => ({ "advanced-document-processing": true }) }));
6
+ jest.mock("@SRC/utils/with-retry", () => ({
7
+ // Same attempts as the real helper, without the backoff sleeps.
8
+ withRetry: async (fn: () => Promise<unknown>, max = 3) => {
9
+ let last: unknown;
10
+ for (let i = 0; i < max; i++) {
11
+ try { return await fn(); } catch (e) { last = e; }
12
+ }
13
+ throw last;
14
+ },
15
+ }));
16
+ jest.mock("@SRC/utils/python-executor", () => ({ executePythonScript: jest.fn() }));
17
+ jest.mock("@SRC/exulu/resolve-ocr", () => ({ resolveOcr: jest.fn() }));
18
+ jest.mock("@SRC/exulu/resolve-model", () => ({ resolveModel: jest.fn(async () => ({ languageModel: {} })) }));
19
+ jest.mock("@llamaindex/liteparse", () => ({ LiteParse: jest.fn() }), { virtual: true });
20
+ jest.mock("ai", () => ({ generateText: jest.fn(), Output: { object: (x: unknown) => x } }));
21
+
22
+ import { documentProcessor } from "./doc_processor";
23
+ import { processWideLimiters, VISION_CALL_TIMEOUT_MS, OCR_CALL_TIMEOUT_MS } from "./limits";
24
+
25
+ const { executePythonScript } = require("@SRC/utils/python-executor") as { executePythonScript: jest.Mock };
26
+ const { resolveOcr } = require("@SRC/exulu/resolve-ocr") as { resolveOcr: jest.Mock };
27
+ const { LiteParse } = require("@llamaindex/liteparse") as { LiteParse: jest.Mock };
28
+ const { generateText } = require("ai") as { generateText: jest.Mock };
29
+
30
+ const chunkDir = fs.mkdtempSync(path.join(os.tmpdir(), "chunks-"));
31
+ const chunkFile = path.join(chunkDir, "chunk.pdf");
32
+ fs.writeFileSync(chunkFile, "x");
33
+
34
+ let running = 0;
35
+ let maxRunning = 0;
36
+
37
+ function setupDocument(pageCount: number) {
38
+ executePythonScript.mockResolvedValueOnce({
39
+ stdout: JSON.stringify(Array.from({ length: pageCount }, (_, i) => ({ path: chunkFile, start_page: i, end_page: i + 1 }))),
40
+ stderr: "",
41
+ });
42
+ LiteParse.mockImplementationOnce(() => ({
43
+ screenshot: async () => Array.from({ length: pageCount }, (_, i) => ({ pageNum: i + 1, imageBuffer: Buffer.from(`page-${i + 1}`) })),
44
+ }));
45
+ }
46
+
47
+ beforeEach(() => {
48
+ jest.clearAllMocks();
49
+ running = 0;
50
+ maxRunning = 0;
51
+ jest.spyOn(Math, "random").mockReturnValue(0);
52
+ jest.spyOn(console, "log").mockImplementation(() => undefined);
53
+ jest.spyOn(console, "error").mockImplementation(() => undefined);
54
+ let call = 0;
55
+ resolveOcr.mockResolvedValue({
56
+ ocr: async () => {
57
+ running++;
58
+ maxRunning = Math.max(maxRunning, running);
59
+ await new Promise((r) => setTimeout(r, 15));
60
+ running--;
61
+ call++;
62
+ // Every page carries a table so the vision pass looks at it.
63
+ return { pages: [{ index: 0, markdown: `| a | b |\n| 1 | 2 |\nocr text ${call}` }] };
64
+ },
65
+ });
66
+ generateText.mockResolvedValue({
67
+ output: { needs_correction: false, corrected_text: null, current_page_table: null, confidence: "high", reasoning: "ok" },
68
+ });
69
+ });
70
+ afterEach(() => jest.restoreAllMocks());
71
+
72
+ const mistral = (extra: Record<string, unknown> = {}) => ({
73
+ processor: { name: "mistral" as const, model: "vertex-ocr" },
74
+ vlm: { model: "vlm", concurrency: 4 },
75
+ ...extra,
76
+ });
77
+
78
+ describe("document processor limits", () => {
79
+ it("chat path: with the process-wide limiters never more than 8 OCR calls at once across two documents, and both finish", async () => {
80
+ setupDocument(12);
81
+ setupDocument(12);
82
+ const config = mistral({ ocr: { concurrency: 8 } });
83
+ const [a, b] = await Promise.all([
84
+ documentProcessor({ file: Buffer.from("%PDF"), name: "a.pdf", config, limiters: processWideLimiters }),
85
+ documentProcessor({ file: Buffer.from("%PDF"), name: "b.pdf", config, limiters: processWideLimiters }),
86
+ ]);
87
+ expect(a).toHaveLength(12);
88
+ expect(b).toHaveLength(12);
89
+ expect(maxRunning).toBeGreaterThan(3);
90
+ expect(maxRunning).toBeLessThanOrEqual(8);
91
+ });
92
+
93
+ it("knowledge-base path: a direct call is not capped globally, two documents run 16 OCR calls at once", async () => {
94
+ setupDocument(12);
95
+ setupDocument(12);
96
+ const config = mistral({ ocr: { concurrency: 8 } });
97
+ await Promise.all([
98
+ documentProcessor({ file: Buffer.from("%PDF"), name: "a.pdf", config }),
99
+ documentProcessor({ file: Buffer.from("%PDF"), name: "b.pdf", config }),
100
+ ]);
101
+ expect(maxRunning).toBeGreaterThan(8);
102
+ });
103
+
104
+ it("knowledge-base path: vision calls follow vlm.concurrency per document with no global cap", async () => {
105
+ setupDocument(10);
106
+ setupDocument(10);
107
+ let visionRunning = 0;
108
+ let visionMax = 0;
109
+ generateText.mockImplementation(async () => {
110
+ visionRunning++;
111
+ visionMax = Math.max(visionMax, visionRunning);
112
+ await new Promise((r) => setTimeout(r, 15));
113
+ visionRunning--;
114
+ return { output: { needs_correction: false, corrected_text: null, current_page_table: null, confidence: "high", reasoning: "ok" } };
115
+ });
116
+ const config = mistral({ ocr: { concurrency: 8 }, vlm: { model: "vlm", concurrency: 10 } });
117
+ await Promise.all([
118
+ documentProcessor({ file: Buffer.from("%PDF"), name: "a.pdf", config }),
119
+ documentProcessor({ file: Buffer.from("%PDF"), name: "b.pdf", config }),
120
+ ]);
121
+ expect(visionMax).toBeGreaterThan(8);
122
+ });
123
+
124
+ it("chat path: vision calls across two documents are capped at 8", async () => {
125
+ setupDocument(10);
126
+ setupDocument(10);
127
+ let visionRunning = 0;
128
+ let visionMax = 0;
129
+ generateText.mockImplementation(async () => {
130
+ visionRunning++;
131
+ visionMax = Math.max(visionMax, visionRunning);
132
+ await new Promise((r) => setTimeout(r, 15));
133
+ visionRunning--;
134
+ return { output: { needs_correction: false, corrected_text: null, current_page_table: null, confidence: "high", reasoning: "ok" } };
135
+ });
136
+ const config = mistral({ ocr: { concurrency: 8 }, vlm: { model: "vlm", concurrency: 10 } });
137
+ await Promise.all([
138
+ documentProcessor({ file: Buffer.from("%PDF"), name: "a.pdf", config, limiters: processWideLimiters }),
139
+ documentProcessor({ file: Buffer.from("%PDF"), name: "b.pdf", config, limiters: processWideLimiters }),
140
+ ]);
141
+ expect(visionMax).toBeGreaterThan(3);
142
+ expect(visionMax).toBeLessThanOrEqual(8);
143
+ });
144
+
145
+ it("honours documentProcessor.ocr.concurrency for one document", async () => {
146
+ setupDocument(20);
147
+ await documentProcessor({ file: Buffer.from("%PDF"), name: "a.pdf", config: mistral({ ocr: { concurrency: 8 } }) });
148
+ expect(maxRunning).toBe(8);
149
+ });
150
+
151
+ it("limits one document to documentProcessor.ocr.concurrency (default 3)", async () => {
152
+ setupDocument(9);
153
+ await documentProcessor({ file: Buffer.from("%PDF"), name: "a.pdf", config: mistral() });
154
+ expect(maxRunning).toBe(3);
155
+ });
156
+ });
157
+
158
+ describe("vision call time limit", () => {
159
+ it("is 120 seconds", () => {
160
+ expect(VISION_CALL_TIMEOUT_MS).toBe(120_000);
161
+ });
162
+
163
+ it("knowledge-base path: a direct call creates no abort signal for OCR or vision", async () => {
164
+ setupDocument(2);
165
+ const timeout = jest.spyOn(AbortSignal, "timeout");
166
+ await documentProcessor({ file: Buffer.from("%PDF"), name: "a.pdf", config: mistral() });
167
+ expect(timeout).not.toHaveBeenCalled();
168
+ expect(generateText).toHaveBeenCalled();
169
+ for (const [args] of generateText.mock.calls) expect(args.abortSignal).toBeUndefined();
170
+ expect(resolveOcr.mock.calls[0][0].timeoutMs).toBeUndefined();
171
+ });
172
+
173
+ it("chat path: OCR gets the 180 s timeout and vision calls carry a 120 s signal", async () => {
174
+ setupDocument(1);
175
+ const timeout = jest.spyOn(AbortSignal, "timeout");
176
+ await documentProcessor({ file: Buffer.from("%PDF"), name: "a.pdf", config: mistral(), limiters: processWideLimiters });
177
+ expect(resolveOcr.mock.calls[0][0].timeoutMs).toBe(OCR_CALL_TIMEOUT_MS);
178
+ expect(OCR_CALL_TIMEOUT_MS).toBe(180_000);
179
+ expect(timeout).toHaveBeenCalledWith(120_000);
180
+ expect(generateText.mock.calls[0][0].abortSignal).toBeInstanceOf(AbortSignal);
181
+ });
182
+
183
+ it("every vision call carries a timeout signal; a stalled call that is aborted counts as a failed attempt", async () => {
184
+ setupDocument(1);
185
+ const controller = new AbortController();
186
+ const timeout = jest.spyOn(AbortSignal, "timeout").mockReturnValue(controller.signal);
187
+ generateText.mockImplementation(
188
+ (args: { abortSignal?: AbortSignal }) =>
189
+ new Promise((_resolve, reject) => {
190
+ args.abortSignal?.addEventListener("abort", () => reject(new Error("timed out")));
191
+ if (args.abortSignal?.aborted) reject(new Error("timed out"));
192
+ }),
193
+ );
194
+ const pending = documentProcessor({ file: Buffer.from("%PDF"), name: "a.pdf", config: mistral(), tolerateVisionFailures: true, limiters: processWideLimiters });
195
+ for (let i = 0; i < 200 && generateText.mock.calls.length === 0; i++) await new Promise((r) => setTimeout(r, 10));
196
+ expect(timeout).toHaveBeenCalledWith(120_000);
197
+ controller.abort();
198
+ const result = await pending;
199
+ // Three attempts (the existing retry count), then the page is flagged instead of hanging.
200
+ expect(generateText).toHaveBeenCalledTimes(3);
201
+ expect(result![0].vlm_failed).toBe(true);
202
+ });
203
+ });
204
+
205
+ describe("vision failures", () => {
206
+ const failPage2 = () =>
207
+ generateText.mockImplementation(async (args: { messages: Array<{ content: Array<{ image?: string }> }> }) => {
208
+ const image = args.messages[0].content[1].image as string;
209
+ const text = Buffer.from(image.split(",")[1], "base64").toString();
210
+ if (text === "page-2") throw new Error("vision outage");
211
+ return { output: { needs_correction: false, corrected_text: null, current_page_table: null, confidence: "high", reasoning: "ok" } };
212
+ });
213
+
214
+ it("with tolerateVisionFailures a page whose vision call failed three times keeps its OCR text and is flagged", async () => {
215
+ setupDocument(3);
216
+ failPage2();
217
+ const result = await documentProcessor({ file: Buffer.from("%PDF"), name: "a.pdf", config: mistral(), tolerateVisionFailures: true });
218
+ expect(result).toHaveLength(3);
219
+ const page2 = result!.find((p) => p.page === 2)!;
220
+ expect(page2.content).toContain("| a | b |");
221
+ expect(page2.vlm_failed).toBe(true);
222
+ expect(result!.filter((p) => p.vlm_failed).map((p) => p.page)).toEqual([2]);
223
+ const failedCalls = generateText.mock.calls.filter((c) => Buffer.from(c[0].messages[0].content[1].image.split(",")[1], "base64").toString() === "page-2");
224
+ expect(failedCalls).toHaveLength(3);
225
+ });
226
+
227
+ it("without the flag the document fails as before", async () => {
228
+ setupDocument(3);
229
+ failPage2();
230
+ await expect(documentProcessor({ file: Buffer.from("%PDF"), name: "a.pdf", config: mistral() })).rejects.toThrow("vision outage");
231
+ });
232
+ });
233
+
234
+ describe("reconstructTableHeaders", () => {
235
+ const { reconstructTableHeaders } = require("./doc_processor") as typeof import("./doc_processor");
236
+ const tableOn = (headers: string[], is_continuation: boolean) =>
237
+ ({ needs_correction: false, confidence: "high", reasoning: "", current_page_table: { headers, is_continuation } }) as never;
238
+ const build = () => [
239
+ { page: 1, content: "| a | b |\n| - | - |\n| 1 | 2 |" },
240
+ { page: 2, content: "| 3 | 4 |", vlm_failed: true as boolean | undefined },
241
+ { page: 3, content: "| 5 | 6 |" },
242
+ ];
243
+ const results = () => new Map([[1, tableOn(["a", "b"], false)], [3, tableOn(["x", "y"], true)]]);
244
+
245
+ it("does not hand headers from before a failed page to a later continuation", () => {
246
+ const doc = build();
247
+ reconstructTableHeaders(doc, results());
248
+ expect(doc[2].content).toBe("| 5 | 6 |");
249
+ });
250
+
251
+ it("without a failed page the headers carry across as before", () => {
252
+ const doc = build();
253
+ doc[1].vlm_failed = undefined;
254
+ reconstructTableHeaders(doc, results());
255
+ expect(doc[2].content).toBe("| a | b |\n| --- | --- |\n| 5 | 6 |");
256
+ });
257
+ });
@@ -0,0 +1,151 @@
1
+ import * as fs from "fs";
2
+ import * as os from "os";
3
+ import * as path from "path";
4
+
5
+ jest.mock("@EE/entitlements", () => ({ checkLicense: () => ({ "advanced-document-processing": true }) }));
6
+ jest.mock("@SRC/utils/with-retry", () => ({
7
+ // Same attempts as the real helper, without the backoff sleeps.
8
+ withRetry: async (fn: () => Promise<unknown>, max = 3) => {
9
+ let last: unknown;
10
+ for (let i = 0; i < max; i++) {
11
+ try { return await fn(); } catch (e) { last = e; }
12
+ }
13
+ throw last;
14
+ },
15
+ }));
16
+ jest.mock("@SRC/utils/python-executor", () => ({ executePythonScript: jest.fn() }));
17
+ jest.mock("@SRC/exulu/resolve-ocr", () => ({ resolveOcr: jest.fn() }));
18
+ jest.mock("@SRC/exulu/resolve-model", () => ({ resolveModel: jest.fn(async () => ({ languageModel: {} })) }));
19
+ jest.mock("@llamaindex/liteparse", () => ({ LiteParse: jest.fn() }), { virtual: true });
20
+ jest.mock("ai", () => ({ generateText: jest.fn(), Output: { object: (x: unknown) => x } }));
21
+
22
+ import { documentProcessor } from "./doc_processor";
23
+
24
+ const { executePythonScript } = require("@SRC/utils/python-executor") as { executePythonScript: jest.Mock };
25
+ const { resolveOcr } = require("@SRC/exulu/resolve-ocr") as { resolveOcr: jest.Mock };
26
+ const { LiteParse } = require("@llamaindex/liteparse") as { LiteParse: jest.Mock };
27
+ const { generateText } = require("ai") as { generateText: jest.Mock };
28
+
29
+ const chunkDir = fs.mkdtempSync(path.join(os.tmpdir(), "chunks-"));
30
+ const chunkFile = path.join(chunkDir, "chunk.pdf");
31
+ fs.writeFileSync(chunkFile, "x");
32
+
33
+ let running = 0;
34
+ let maxRunning = 0;
35
+
36
+ function setupDocument(pageCount: number) {
37
+ executePythonScript.mockResolvedValueOnce({
38
+ stdout: JSON.stringify(Array.from({ length: pageCount }, (_, i) => ({ path: chunkFile, start_page: i, end_page: i + 1 }))),
39
+ stderr: "",
40
+ });
41
+ LiteParse.mockImplementationOnce(() => ({
42
+ screenshot: async () => Array.from({ length: pageCount }, (_, i) => ({ pageNum: i + 1, imageBuffer: Buffer.from(`page-${i + 1}`) })),
43
+ }));
44
+ }
45
+
46
+ beforeEach(() => {
47
+ jest.clearAllMocks();
48
+ running = 0;
49
+ maxRunning = 0;
50
+ jest.spyOn(Math, "random").mockReturnValue(0);
51
+ jest.spyOn(console, "log").mockImplementation(() => undefined);
52
+ jest.spyOn(console, "error").mockImplementation(() => undefined);
53
+ let call = 0;
54
+ resolveOcr.mockResolvedValue({
55
+ ocr: async () => {
56
+ running++;
57
+ maxRunning = Math.max(maxRunning, running);
58
+ await new Promise((r) => setTimeout(r, 15));
59
+ running--;
60
+ call++;
61
+ // Every page carries a table so the vision pass looks at it.
62
+ return { pages: [{ index: 0, markdown: `| a | b |\n| 1 | 2 |\nocr text ${call}` }] };
63
+ },
64
+ });
65
+ generateText.mockResolvedValue({
66
+ output: { needs_correction: false, corrected_text: null, current_page_table: null, confidence: "high", reasoning: "ok" },
67
+ });
68
+ });
69
+ afterEach(() => jest.restoreAllMocks());
70
+
71
+ const mistral = (extra: Record<string, unknown> = {}) => ({
72
+ processor: { name: "mistral" as const, model: "vertex-ocr" },
73
+ vlm: { model: "vlm", concurrency: 4 },
74
+ ...extra,
75
+ });
76
+
77
+
78
+ describe("document processor progress", () => {
79
+ const collect = () => {
80
+ const events: Array<{ phase: string; pagesDone: number; pagesTotal: number }> = [];
81
+ return { events, onProgress: (p: { phase: string; pagesDone: number; pagesTotal: number }) => { events.push({ ...p }); } };
82
+ };
83
+
84
+ it("reports OCR after each finished chunk with a monotonically increasing cumulative page count", async () => {
85
+ setupDocument(5);
86
+ // Chunks finish out of order: later chunks answer faster.
87
+ let n = 0;
88
+ resolveOcr.mockResolvedValue({
89
+ ocr: async () => {
90
+ const mine = n++;
91
+ await new Promise((r) => setTimeout(r, 40 - mine * 8));
92
+ return { pages: [{ index: 0, markdown: `plain ${mine}` }] };
93
+ },
94
+ });
95
+ const { events, onProgress } = collect();
96
+ await documentProcessor({ file: Buffer.from("%PDF"), name: "a.pdf", config: mistral({ ocr: { concurrency: 5 } }), onProgress });
97
+ const ocr = events.filter((e) => e.phase === "ocr");
98
+ expect(ocr.map((e) => e.pagesDone)).toEqual([1, 2, 3, 4, 5]);
99
+ expect(ocr.every((e) => e.pagesTotal === 5)).toBe(true);
100
+ });
101
+
102
+ it("reports vision per finished page, with the total being the pages that get a vision pass", async () => {
103
+ setupDocument(3);
104
+ let n = 0;
105
+ resolveOcr.mockResolvedValue({
106
+ ocr: async () => {
107
+ n++;
108
+ // Page with a table gets a vision pass; the other two are plain text and are skipped.
109
+ return { pages: [{ index: 0, markdown: n === 2 ? "| a | b |\n| 1 | 2 |" : "plain text" }] };
110
+ },
111
+ });
112
+ const { events, onProgress } = collect();
113
+ await documentProcessor({ file: Buffer.from("%PDF"), name: "a.pdf", config: mistral({ ocr: { concurrency: 1 } }), onProgress });
114
+ expect(events.filter((e) => e.phase === "vision")).toEqual([{ phase: "vision", pagesDone: 1, pagesTotal: 1 }]);
115
+ });
116
+
117
+ it("counts a tolerated vision failure as a finished page", async () => {
118
+ setupDocument(2);
119
+ generateText.mockRejectedValue(new Error("vision outage"));
120
+ const { events, onProgress } = collect();
121
+ await documentProcessor({ file: Buffer.from("%PDF"), name: "a.pdf", config: mistral(), tolerateVisionFailures: true, onProgress });
122
+ const vision = events.filter((e) => e.phase === "vision");
123
+ expect(vision.map((e) => e.pagesDone)).toEqual([1, 2]);
124
+ expect(vision.every((e) => e.pagesTotal === 2)).toBe(true);
125
+ });
126
+
127
+ it("emits nothing and still works without a callback", async () => {
128
+ setupDocument(2);
129
+ await expect(documentProcessor({ file: Buffer.from("%PDF"), name: "a.pdf", config: mistral() })).resolves.toHaveLength(2);
130
+ });
131
+
132
+ it("a throwing callback changes nothing: same result, no page flagged", async () => {
133
+ const run = async (onProgress?: () => void) => {
134
+ setupDocument(3);
135
+ return documentProcessor({ file: Buffer.from("%PDF"), name: "a.pdf", config: mistral(), tolerateVisionFailures: true, ...(onProgress ? { onProgress } : {}) });
136
+ };
137
+ const plain = await run();
138
+ const throwing = await run(() => { throw new Error("callback broke"); });
139
+ // The shared OCR mock numbers its answers per call, so compare with that number removed.
140
+ const norm = (r: typeof plain) => r!.map((p) => ({ ...p, content: p.content.replace(/ocr text \d+/, "ocr text") }));
141
+ expect(norm(throwing)).toEqual(norm(plain));
142
+ expect(throwing!.some((p) => p.vlm_failed)).toBe(false);
143
+ });
144
+
145
+ it("a throwing callback does not fail the document without the tolerate flag", async () => {
146
+ setupDocument(2);
147
+ await expect(
148
+ documentProcessor({ file: Buffer.from("%PDF"), name: "a.pdf", config: mistral(), onProgress: () => { throw new Error("callback broke"); } }),
149
+ ).resolves.toHaveLength(2);
150
+ });
151
+ });