llm-large-files 0.8.1 → 0.9.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.
Files changed (204) hide show
  1. package/CHANGELOG.md +631 -0
  2. package/README.md +9 -10
  3. package/dist/access.d.ts +86 -0
  4. package/dist/access.d.ts.map +1 -0
  5. package/dist/access.js +131 -0
  6. package/dist/access.js.map +1 -0
  7. package/dist/ask.d.ts +45 -1
  8. package/dist/ask.d.ts.map +1 -1
  9. package/dist/ask.js +181 -20
  10. package/dist/ask.js.map +1 -1
  11. package/dist/cache.d.ts +12 -3
  12. package/dist/cache.d.ts.map +1 -1
  13. package/dist/cache.js +18 -5
  14. package/dist/cache.js.map +1 -1
  15. package/dist/encoding.js +5 -3
  16. package/dist/encoding.js.map +1 -1
  17. package/dist/error-info.d.ts +57 -0
  18. package/dist/error-info.d.ts.map +1 -0
  19. package/dist/error-info.js +217 -0
  20. package/dist/error-info.js.map +1 -0
  21. package/dist/errors.d.ts +72 -8
  22. package/dist/errors.d.ts.map +1 -1
  23. package/dist/errors.js +102 -15
  24. package/dist/errors.js.map +1 -1
  25. package/dist/events.d.ts +35 -9
  26. package/dist/events.d.ts.map +1 -1
  27. package/dist/events.js +42 -11
  28. package/dist/events.js.map +1 -1
  29. package/dist/evidence.d.ts +4 -2
  30. package/dist/evidence.d.ts.map +1 -1
  31. package/dist/evidence.js +14 -3
  32. package/dist/evidence.js.map +1 -1
  33. package/dist/extract.d.ts +32 -8
  34. package/dist/extract.d.ts.map +1 -1
  35. package/dist/extract.js +46 -35
  36. package/dist/extract.js.map +1 -1
  37. package/dist/gemini/adapter.d.ts +19 -3
  38. package/dist/gemini/adapter.d.ts.map +1 -1
  39. package/dist/gemini/adapter.js +84 -12
  40. package/dist/gemini/adapter.js.map +1 -1
  41. package/dist/gemini/chat.d.ts +18 -6
  42. package/dist/gemini/chat.d.ts.map +1 -1
  43. package/dist/gemini/chat.js +2 -0
  44. package/dist/gemini/chat.js.map +1 -1
  45. package/dist/gemini/index.d.ts +1 -1
  46. package/dist/gemini/index.d.ts.map +1 -1
  47. package/dist/index.d.ts +9 -6
  48. package/dist/index.d.ts.map +1 -1
  49. package/dist/index.js +4 -3
  50. package/dist/index.js.map +1 -1
  51. package/dist/ingest.d.ts +70 -0
  52. package/dist/ingest.d.ts.map +1 -0
  53. package/dist/ingest.js +868 -0
  54. package/dist/ingest.js.map +1 -0
  55. package/dist/library.d.ts +176 -34
  56. package/dist/library.d.ts.map +1 -1
  57. package/dist/library.js +332 -512
  58. package/dist/library.js.map +1 -1
  59. package/dist/limiter.d.ts +2 -2
  60. package/dist/limiter.js +2 -2
  61. package/dist/map-reduce.js +3 -3
  62. package/dist/map-reduce.js.map +1 -1
  63. package/dist/model.d.ts +43 -2
  64. package/dist/model.d.ts.map +1 -1
  65. package/dist/model.js +63 -3
  66. package/dist/model.js.map +1 -1
  67. package/dist/node/handlers.d.ts +234 -7
  68. package/dist/node/handlers.d.ts.map +1 -1
  69. package/dist/node/handlers.js +482 -121
  70. package/dist/node/handlers.js.map +1 -1
  71. package/dist/node/index.d.ts +3 -2
  72. package/dist/node/index.d.ts.map +1 -1
  73. package/dist/node/index.js +2 -1
  74. package/dist/node/index.js.map +1 -1
  75. package/dist/node/ingest-child.d.ts +7 -1
  76. package/dist/node/ingest-child.d.ts.map +1 -1
  77. package/dist/node/ingest-child.js +18 -3
  78. package/dist/node/ingest-child.js.map +1 -1
  79. package/dist/node/isolated.d.ts +3 -1
  80. package/dist/node/isolated.d.ts.map +1 -1
  81. package/dist/node/isolated.js +11 -4
  82. package/dist/node/isolated.js.map +1 -1
  83. package/dist/node/originals.d.ts +19 -0
  84. package/dist/node/originals.d.ts.map +1 -0
  85. package/dist/node/originals.js +82 -0
  86. package/dist/node/originals.js.map +1 -0
  87. package/dist/node/spool.d.ts +102 -0
  88. package/dist/node/spool.d.ts.map +1 -0
  89. package/dist/node/spool.js +365 -0
  90. package/dist/node/spool.js.map +1 -0
  91. package/dist/node/sse.d.ts +4 -3
  92. package/dist/node/sse.d.ts.map +1 -1
  93. package/dist/node/sse.js +7 -6
  94. package/dist/node/sse.js.map +1 -1
  95. package/dist/pdf-layout.d.ts.map +1 -1
  96. package/dist/pdf-layout.js +71 -12
  97. package/dist/pdf-layout.js.map +1 -1
  98. package/dist/ranged.d.ts +22 -11
  99. package/dist/ranged.d.ts.map +1 -1
  100. package/dist/ranged.js +50 -12
  101. package/dist/ranged.js.map +1 -1
  102. package/dist/retry.d.ts +3 -1
  103. package/dist/retry.d.ts.map +1 -1
  104. package/dist/retry.js +6 -2
  105. package/dist/retry.js.map +1 -1
  106. package/dist/scope.d.ts +25 -0
  107. package/dist/scope.d.ts.map +1 -0
  108. package/dist/scope.js +60 -0
  109. package/dist/scope.js.map +1 -0
  110. package/dist/source.d.ts +60 -0
  111. package/dist/source.d.ts.map +1 -0
  112. package/dist/source.js +170 -0
  113. package/dist/source.js.map +1 -0
  114. package/dist/stores.d.ts +120 -31
  115. package/dist/stores.d.ts.map +1 -1
  116. package/dist/stores.js +582 -139
  117. package/dist/stores.js.map +1 -1
  118. package/dist/testing/fake-fetch.d.ts +31 -0
  119. package/dist/testing/fake-fetch.d.ts.map +1 -0
  120. package/dist/testing/fake-fetch.js +66 -0
  121. package/dist/testing/fake-fetch.js.map +1 -0
  122. package/dist/testing/fake-model.d.ts +38 -0
  123. package/dist/testing/fake-model.d.ts.map +1 -0
  124. package/dist/testing/fake-model.js +62 -0
  125. package/dist/testing/fake-model.js.map +1 -0
  126. package/dist/testing/index.d.ts +7 -0
  127. package/dist/testing/index.d.ts.map +1 -0
  128. package/dist/testing/index.js +9 -0
  129. package/dist/testing/index.js.map +1 -0
  130. package/dist/testing/store-checks.d.ts +72 -0
  131. package/dist/testing/store-checks.d.ts.map +1 -0
  132. package/dist/testing/store-checks.js +619 -0
  133. package/dist/testing/store-checks.js.map +1 -0
  134. package/dist/tools.d.ts +25 -0
  135. package/dist/tools.d.ts.map +1 -1
  136. package/dist/tools.js +135 -13
  137. package/dist/tools.js.map +1 -1
  138. package/dist/types.d.ts +116 -13
  139. package/dist/types.d.ts.map +1 -1
  140. package/docs/README.md +17 -8
  141. package/docs/getting-started.md +18 -13
  142. package/docs/guides/anthropic.md +12 -8
  143. package/docs/guides/conversations.md +112 -47
  144. package/docs/guides/costs-and-limits.md +16 -7
  145. package/docs/guides/deployment.md +309 -87
  146. package/docs/guides/errors-and-reliability.md +161 -23
  147. package/docs/guides/own-adapter-and-loop.md +27 -10
  148. package/docs/guides/pdfs.md +123 -29
  149. package/docs/guides/storage.md +634 -143
  150. package/docs/guides/testing.md +78 -129
  151. package/docs/guides/vertex-and-gemini.md +10 -7
  152. package/docs/guides/web-app.md +322 -77
  153. package/docs/how-it-works.md +35 -8
  154. package/docs/measurements.md +63 -8
  155. package/docs/publishing.md +112 -36
  156. package/docs/reference/ask.md +154 -13
  157. package/docs/reference/errors-and-retries.md +166 -14
  158. package/docs/reference/events.md +53 -20
  159. package/docs/reference/gemini.md +70 -21
  160. package/docs/reference/library.md +709 -165
  161. package/docs/reference/node.md +633 -104
  162. package/docs/reference/testing.md +311 -0
  163. package/docs/reference/tools.md +15 -5
  164. package/docs/security.md +316 -70
  165. package/docs/troubleshooting.md +165 -58
  166. package/docs/upgrading-0.9.md +890 -0
  167. package/package.json +12 -3
  168. package/src/access.ts +144 -0
  169. package/src/ask.ts +230 -19
  170. package/src/cache.ts +20 -5
  171. package/src/encoding.ts +6 -4
  172. package/src/error-info.ts +255 -0
  173. package/src/errors.ts +129 -15
  174. package/src/events.ts +86 -21
  175. package/src/evidence.ts +14 -3
  176. package/src/extract.ts +50 -33
  177. package/src/gemini/adapter.ts +97 -11
  178. package/src/gemini/chat.ts +20 -6
  179. package/src/gemini/index.ts +1 -1
  180. package/src/index.ts +9 -6
  181. package/src/ingest.ts +927 -0
  182. package/src/library.ts +482 -523
  183. package/src/limiter.ts +2 -2
  184. package/src/map-reduce.ts +3 -3
  185. package/src/model.ts +69 -5
  186. package/src/node/handlers.ts +691 -117
  187. package/src/node/index.ts +13 -2
  188. package/src/node/ingest-child.ts +23 -5
  189. package/src/node/isolated.ts +11 -4
  190. package/src/node/originals.ts +78 -0
  191. package/src/node/spool.ts +365 -0
  192. package/src/node/sse.ts +7 -6
  193. package/src/pdf-layout.ts +69 -11
  194. package/src/ranged.ts +42 -14
  195. package/src/retry.ts +6 -2
  196. package/src/scope.ts +63 -0
  197. package/src/source.ts +178 -0
  198. package/src/stores.ts +635 -140
  199. package/src/testing/fake-fetch.ts +80 -0
  200. package/src/testing/fake-model.ts +78 -0
  201. package/src/testing/index.ts +11 -0
  202. package/src/testing/store-checks.ts +660 -0
  203. package/src/tools.ts +150 -14
  204. package/src/types.ts +106 -13
@@ -20,6 +20,8 @@ rebuild from the store.
20
20
  | Which documents belong to which user or chat | Your application, and `owner` on each document | Yours to share | Yours |
21
21
  | Documents ready to search, decoded pieces of large ones, line indexes | A cache in each `LargeFiles`, within `cacheBytes` | No | Empty; filled again from the store |
22
22
  | Searches of large files waiting their turn | A queue in each `LargeFiles` (`maxConcurrentScans`) | No | Empty |
23
+ | Ingests waiting their turn | A queue in each `LargeFiles` (`maxConcurrentIngests`, new in 0.8.2) | No | Empty: the uploads in it get no answer, and must be sent again |
24
+ | Uploads being received | A count in each set of `createDocumentHandlers` (`maxPendingUploadBytes`, new in 0.8.2) | No | Empty |
23
25
  | The output limit a thinking model needs for whole-file part reads | Each process, by URL and model | No | Learned again, at the cost of one request |
24
26
  | The name of the output limit an OpenAI-compatible server takes | Each `openAiCompatible()` adapter | No | Learned again, at the cost of one refused request |
25
27
 
@@ -55,7 +57,8 @@ this:
55
57
  metadata must be able to read the text.
56
58
  - **The text is kept byte for byte.** `readTextRange` reads UTF-8 byte offsets that the line index
57
59
  computed at ingest. A text that changed is noticed ("The stored text of … did not match its
58
- index. Try the call again.") and its index is built again.
60
+ index. Try the call again.") and its index is built again. A text of another length or number of
61
+ lines than its metadata says then reads as missing.
59
62
  - **`undefined` means "not there", and nothing else.** A read that failed (a timeout, a volume that
60
63
  does not answer) must throw: the library passes it on as `DocumentStoreError` instead of telling
61
64
  the user that the file is gone.
@@ -77,7 +80,18 @@ The built-in stores:
77
80
  [Sweeping expired documents](#sweeping-expired-documents)).
78
81
 
79
82
  It needs a file system whose rename is atomic and that shows each server the files of the
80
- others: an NFS share (Amazon EFS, Google Filestore, Azure Files over NFS) or similar. Two caveats:
83
+ others: an NFS share (Amazon EFS, Google Filestore, Azure Files over NFS) or similar. Every server
84
+ opens its own `FileDocumentStore` over the same directory, with the same options (`scopes` above
85
+ all), and one library per process: then `maxConcurrentIngests`, `cacheBytes` and
86
+ `maxConcurrentScans` hold for the whole server, whatever the number of chats
87
+ ([Storage](./storage.md#files-in-a-folder-per-user-or-per-chat)).
88
+
89
+ Since 0.9.0 it writes files `0600` and folders `0700`: only the user that wrote them can read
90
+ them. Run every server, and any job that reads the volume (a backup, a sweep job), as the same
91
+ user. If they run as different users of one group, as pods with a shared `fsGroup` in Kubernetes
92
+ do, set `fileMode: 0o640` and `directoryMode: 0o750` on every store: a server that cannot read a
93
+ file another one wrote answers "The document store could not be read (EACCES)". The umask of the
94
+ process still applies. Two caveats:
81
95
 
82
96
  - An NFS client may remember for a while that a file did not exist (its negative lookup cache).
83
97
  A question sent to another server right after an upload can then find the document missing.
@@ -95,16 +109,18 @@ The built-in stores:
95
109
  | Documents kept ready to search | Up to `cacheBytes`, 256 MB by default | `cacheBytes`; `cacheSize` also caps their number |
96
110
  | A document loaded whole: text up to `wholeDocumentBytes` (2 MB), or any size when the store has no `readTextRange` | Its text and a lowercased copy: 2 bytes a character for ASCII text, 4 for any other | Counted in `cacheBytes`. One larger than `cacheBytes` is loaded again for each call and not kept |
97
111
  | A document read by range | Its line index: about 8 bytes a line (8.2 MB for a log of a million lines) | Counted in `cacheBytes` |
98
- | Searches of documents read by range | A few MB each: `scanChunkBytes` (1 MB) of text read, decoded and lowercased, and the next piece read ahead | `maxConcurrentScans` (4) per `LargeFiles`. The others wait, and those waiting for the same file share one pass over it |
112
+ | Searches of documents read by range | Tens of MB each at their peak (60 to 80 MB for a search of a log of 95 MB on Windows; 49 MB above the process for one of 100 MB on Linux, [measurements](../measurements.md#the-server)): `scanChunkBytes` (1 MB) of text read, decoded and lowercased, the next piece read ahead, and what the pieces leave until the next collection | `maxConcurrentScans` (4) per `LargeFiles`. The others wait, and those waiting for the same file share one pass over it |
99
113
  | Decoded pieces of a document read by range | Up to its whole decoded text | Kept within `cacheBytes`, and only for a document whose decoded text takes at most a quarter of it |
100
- | An upload | The body, buffered whole | `maxUploadBytes`, 100 MB by default |
101
- | An ingest | Several copies of the text at once (below), and what the parsers of PDF, DOCX, PPTX and XLSX take while they read. A crafted PDF can make them take far more: one of 732 bytes ran a heap of 512 MB out of memory, and one of 1.6 KB took 1.6 GB of memory outside the heap, with 20 MB of heap, for a stream that unpacks to 512 MB ([Security](../security.md#uploads)) | `maxTextBytes` bounds the text (100 MB by default). Nothing in the server bounds what the parsers build or unpack: read PDF and Office files with `createIsolatedExtractors`, in child processes with a heap limit of their own, or ingest in a process of its own with a memory limit of its own (below) |
114
+ | An upload | The body, buffered whole, from the reading of the body to the end of its ingest. 100 uploads of 2 MB sent at once held 190 MB | `maxUploadBytes` (100 MB by default) for one; `maxPendingUploadBytes` of `createDocumentHandlers` (twice `maxUploadBytes`) for all those the handlers hold, the others answered 503 before their body is read. A route of your own must bound them itself (below) |
115
+ | An ingest | About three and a half to five and a half times the file above the uploaded bytes at its peak, for a plain-text log over a `FileDocumentStore` (below): several copies of the text at once (below), and what the parsers of PDF, DOCX, PPTX and XLSX take while they read. `maxConcurrentIngests` (2 by default) of them at once in a `LargeFiles`; the others wait, holding only their upload. A crafted PDF can make them take far more: one of 732 bytes ran a heap of 512 MB out of memory, and one of 1.6 KB took 1.6 GB of memory outside the heap, with 20 MB of heap, for a stream that unpacks to 512 MB ([Security](../security.md#uploads)) | `maxTextBytes` bounds the text (100 MB by default). Nothing in the server bounds what the parsers build or unpack: read PDF and Office files with `createIsolatedExtractors`, in child processes with a heap limit of their own, or ingest in a process of its own with a memory limit of its own (below) |
102
116
  | A look at the pages of a PDF (`view_pages`) | The whole original, read and parsed: about twice the size of the file, plus 1 to 1.6 KB for each object in it (about 300 MB for a 100 MB file of photos, 700 MB for 54 MB of 330,000 objects). A crafted file can take far more: a look at a PDF of 8 MB that is one array of numbers took 422 to 427 MB of heap, one of 16 MB ran a heap of 512 MB out of memory, and one at the PDF of 1.6 KB above took 1.1 GB outside the heap. What `@cantoo/pdf-lib` keeps after a look adds up from file to file, until the server restarts | Refused for a file that declares more than 1,000,000 objects, or more objects than about 60% of the free heap can hold. A crafted file of few objects passes that check. Ingested in a process of its own (below), with `@cantoo/pdf-lib` installed, a file that needs more than that process's heap fails there and is not stored; one that fits is parsed again by each look, which takes more than its ingest did (232 to 244 MB for that file of 8 MB). For the documents of users you do not trust, `viewPages: false`, or no PDF originals |
103
117
  | A question in flight | Its conversation, and each request it builds: up to `maxRequestBytes` (10 MB by default) of JSON, the pages it was shown included as base64 | The budget ([Costs and limits](./costs-and-limits.md)) |
104
118
 
105
119
  Measured peaks are in [Measurements](../measurements.md#the-server): an ingest of a plain-text log
106
- takes about five to seven times the log above the uploaded bytes, and eight searches at once take
107
- little more than one.
120
+ over a `FileDocumentStore` takes about three and a half to five and a half times the log above the
121
+ uploaded bytes (135 MB for a log of 25 MB, 345 MB for one of 95 MB, measured on 0.9.0 with Node 22),
122
+ and eight searches at once take little more than one. (Before 0.6.0 an ingest took five to seven
123
+ times the log.)
108
124
 
109
125
  Other formats were not measured for memory. PDF text is extracted by pdf.js, which reads the whole
110
126
  file, and with `@cantoo/pdf-lib` installed the file is parsed a second time, before pdf.js reads a
@@ -119,17 +135,17 @@ Set the heap limit of Node yourself: about three quarters of the memory of the c
119
135
  everything runs in one process, less when files are read in child processes
120
136
  (`createIsolatedExtractors`) or ingest runs in a process of its own: each has a heap of its own. The
121
137
  limit is more than the flag. `--max-old-space-size` sets the old generation, and Node adds its young
122
- generation above it: 48 MB on Node 20 and 22, 192 MB on Node 24, and 96 MB on Node 26.
138
+ generation above it: 48 MB on Node 22, 192 MB on Node 24, and 96 MB on Node 26.
123
139
  `v8.getHeapStatistics().heap_size_limit` gives the sum. For three quarters of 2 GB, a limit of
124
140
  1,536 MB:
125
141
 
126
142
  | Node | Flag for a heap limit of 1,536 MB | What `--max-old-space-size=1536` gives |
127
143
  |---|---|---|
128
- | 20 and 22 | `NODE_OPTIONS=--max-old-space-size=1488` | 1,584 MB |
144
+ | 22 | `NODE_OPTIONS=--max-old-space-size=1488` | 1,584 MB |
129
145
  | 24 | `NODE_OPTIONS=--max-old-space-size=1344` | 1,728 MB, 84% of 2 GB |
130
146
  | 26 | `NODE_OPTIONS=--max-old-space-size=1440` | 1,632 MB |
131
147
 
132
- Checked with `heap_size_limit` on Node 20.19, 22.12, 24.19 and 26.13. Upload bodies and files read
148
+ Checked with `heap_size_limit` on Node 22.12, 24.19 and 26.13. Upload bodies and files read
133
149
  from the store are `Buffer`s, which live outside the heap and need the rest. The check that refuses
134
150
  a PDF too large to cut pages from compares it with the free heap, so a heap set to fit the
135
151
  container makes that check right.
@@ -137,9 +153,9 @@ container makes that check right.
137
153
  A worker thread does not get a heap limit of its own when the process has one: a
138
154
  `--max-old-space-size` on the command line or in `NODE_OPTIONS` replaces the
139
155
  `resourceLimits.maxOldGenerationSizeMb` of every worker. With `--max-old-space-size=1024`, a worker
140
- given 512 MB had the process's limit: 1,072 MB on Node 20 and 22, 1,216 MB on Node 24, 1,120 MB on
156
+ given 512 MB had the process's limit: 1,072 MB on Node 22, 1,216 MB on Node 24, 1,120 MB on
141
157
  Node 26. Setting `execArgv: []` or `env` on the worker did not change it. A forked process does get
142
- its own: one forked with `execArgv: ["--max-old-space-size=512"]` had 560 MB on Node 20 and 22,
158
+ its own: one forked with `execArgv: ["--max-old-space-size=512"]` had 560 MB on Node 22,
143
159
  704 MB on Node 24 and 608 MB on Node 26, with `NODE_OPTIONS=--max-old-space-size=1024` in the
144
160
  environment it inherits or without it.
145
161
 
@@ -149,13 +165,13 @@ numbers of the last column:
149
165
 
150
166
  | Node | Main heap of 1 GB | Heap of 512 MB for the child that reads a file |
151
167
  |---|---|---|
152
- | 20 and 22 | `--max-old-space-size=976` | `--max-old-space-size=464`, `maxHeapMb: 464` |
168
+ | 22 | `--max-old-space-size=976` | `--max-old-space-size=464`, `maxHeapMb: 464` |
153
169
  | 24 | `--max-old-space-size=832` | `--max-old-space-size=320`, `maxHeapMb: 320` |
154
170
  | 26 | `--max-old-space-size=928` | `--max-old-space-size=416`, `maxHeapMb: 416` |
155
171
 
156
172
  The flags 1024 and 512 give heap limits of 1,216 and 704 MB on Node 24: 1,920 MB, which leaves
157
173
  about 128 MB of the container for the upload, its copy, files read from the store and two Node
158
- processes. On Node 20 and 22 they give 1,072 and 560 MB.
174
+ processes. On Node 22 they give 1,072 and 560 MB.
159
175
 
160
176
  ```ts
161
177
  // large-files.ts: created once per process and imported by every route.
@@ -172,17 +188,19 @@ export const files = createLargeFiles({
172
188
  store: new FileDocumentStore(process.env.DOCUMENTS_DIR ?? "/mnt/documents"),
173
189
  extractors: isolated.extractors, // PDF, DOCX, PPTX and XLSX
174
190
  keepOriginals: ["pdf"], // view_pages: a look reads the whole PDF into this heap
191
+ maxConcurrentPageLooks: 1, // the default: one look at a time, the others wait their turn
175
192
  cacheBytes: 256 * 1024 * 1024, // the default
176
193
  maxConcurrentScans: 4, // the default
194
+ maxConcurrentIngests: 2, // the default: the others wait their turn
177
195
  maxUploadBytes: 100 * 1024 * 1024, // the default
178
196
  });
179
197
  ```
180
198
 
181
199
  | Where 2 GB go | |
182
200
  |---|---|
183
- | The main heap, 1 GB | The cache (256 MB), the questions in flight, a look at the pages of a PDF, and the ingests: the text and its copies (an ingest of a 95 MB log fitted in a heap of 256 MB) |
201
+ | The main heap, 1 GB | The cache (256 MB), the questions in flight, a look at the pages of a PDF, and the ingests: the text and its copies (an ingest of a 95 MB log fitted in a heap of 256 MB, and in 0.9.0 with Node 22 in one of 192) |
184
202
  | One PDF or Office file at a time, read in a child process with a heap of 512 MB | What the parsers take. A process takes about 50 MB more for Node itself |
185
- | Outside the heaps | The upload being read (up to 100 MB) and its copy sent to the child process, files read from the store, Node itself. Also what the PDF parsers unpack, which no heap limit bounds: a crafted PDF of 1.6 KB took 1.6 GB at ingest and 1.1 GB at a look, far more than this row has left. For uploads you do not trust, ingest in a container of its own, and do not offer `view_pages` on their documents |
203
+ | Outside the heaps | The upload being read (up to 100 MB; while it waits for its turn, none with `uploadSpool`) and its copy sent to the child process, files read from the store, Node itself. Also what the PDF parsers unpack, which no heap limit bounds: a crafted PDF of 1.6 KB took 1.6 GB at ingest and 1.1 GB at a look, far more than this row has left. For uploads you do not trust, ingest in a container of its own, and do not offer `view_pages` on their documents |
186
204
 
187
205
  Raise `cacheBytes` to spend memory on speed: at 1 GB, the decoded pieces of an ASCII log of up to
188
206
  about 125 MB are kept between searches. Lower `maxUploadBytes` if large uploads are not needed:
@@ -190,14 +208,107 @@ an ingest is one of the largest single uses of memory.
190
208
 
191
209
  ### Uploads and ingest
192
210
 
193
- `createDocumentHandlers` reads the whole upload into memory before it calls `ingest`. It refuses a
194
- body whose `Content-Length` is over `maxUploadBytes` before reading it, and stops reading one that
195
- grows past it (HTTP 413). Node's own `server.requestTimeout` (300,000 ms by default) ends an upload
211
+ By default `createDocumentHandlers` reads the whole upload into memory before it calls `ingest`.
212
+ Since 0.9.0 it can write the body to a file as it arrives instead, and ingest it from there: the
213
+ path `prepareUpload` gives, or a temporary file of the spool (`uploadSpool`, below). Either way it
214
+ refuses a body whose `Content-Length` is over `maxUploadBytes` before reading it, and stops reading
215
+ one that grows past it (HTTP 413). Node's own `server.requestTimeout` (300,000 ms by default) ends an upload
196
216
  that takes longer than five minutes to arrive: raise it for users on slow links.
197
217
 
218
+ Since 0.8.2 the handlers hold uploads of at most `maxPendingUploadBytes` at once in memory (twice
219
+ `maxUploadBytes` by default), and answer one that would pass it 503 with `Retry-After: 5` before
220
+ reading its body. The room of an upload is taken before its body arrives, from its `Content-Length`
221
+ (or `maxUploadBytes` when it declares none), so a client that sends headers and then nothing, or
222
+ trickles, holds room it does not use: an upload whose body stops arriving for
223
+ `uploadIdleTimeoutMs` (30 s) is answered 408 and its room given back, but a client that sends a byte
224
+ now and then keeps it until `server.requestTimeout`. Behind a reverse proxy that reads the whole
225
+ body before it passes the request on (nginx does by default, `proxy_request_buffering on`), bodies
226
+ arrive at once and none of this happens; otherwise, limit the connections of each client at the
227
+ proxy.
228
+
229
+ **Spooling uploads to disk.** New in 0.9.0. With `uploadSpool`, the handlers write each body over
230
+ `minBytes` (1 MiB), and each body sent without a `Content-Length`, to a temporary file as it
231
+ arrives, and ingest it from its path. So a body is not held in memory while it waits for its turn:
232
+ the ingest reads it once, at its turn. The file is made new with mode `0o600`,
233
+ and removed once the ingest ends, whatever the end. `maxSpooledUploadBytes` (ten times
234
+ `maxUploadBytes`, 1 GB by default) bounds the files at once, and a full disk (`ENOSPC`) is answered
235
+ 503 with `Retry-After`. `maxPendingUploadBytes` then counts only the bodies kept in memory: in
236
+ memory, a body without a `Content-Length` takes `maxUploadBytes` of room until it is read, so two
237
+ of them filled the default room, and a third was refused 503 while they arrived.
238
+
239
+ ```ts
240
+ const documents = createDocumentHandlers(files, {
241
+ getOwner: userIdOf,
242
+ uploadSpool: { directory: "/var/spool/uploads" }, // this server's own folder, on a disk: not a tmpfs
243
+ });
244
+ ```
245
+
246
+ - **Put the spool on a disk.** A Kubernetes `emptyDir` with `medium: Memory` is a tmpfs: what is
247
+ written there counts against the pod's memory limit, and spooling there saves nothing. So does a
248
+ `/tmp` that is a tmpfs, as in some images, and `os.tmpdir()` is the default directory. Point
249
+ `directory` at a disk-backed `emptyDir` (no `medium`), or at a folder on the shared volume, with
250
+ room for `maxSpooledUploadBytes`.
251
+ - **Give each server process a spool folder of its own.** A server that stops in the middle of an
252
+ upload leaves its file (named `llf-upload-` and a UUID). The name does not say which server
253
+ wrote it. So each server empties its own folder when it starts, and no other. A disk-backed
254
+ `emptyDir` is one pod's already, and goes with the pod: the simplest choice. On the shared
255
+ volume, make a folder for each pod, such as `path.join("/data/spool", os.hostname())` (a pod's
256
+ hostname is its name). A pod that is replaced gets a new name, and leaves its folder behind:
257
+ remove the folders of pods that are no longer running (the names of the running pods tell which;
258
+ a folder without recent files may be an idle server's). Both give one folder a pod or a host,
259
+ which is enough with one server process in each. With several (`node:cluster`, PM2 in cluster
260
+ mode), add a number that each process keeps across its restarts, such as PM2's
261
+ `NODE_APP_INSTANCE`, or one the primary passes to each worker it forks:
262
+ `` path.join(dir, `${os.hostname()}-${process.env.NODE_APP_INSTANCE ?? 0}`) ``. Never empty a
263
+ folder that several servers share: the uploads still arriving or waiting for their turn lose
264
+ their files, and fail with `500` `{ "error": "Upload failed (ENOENT)." }`.
265
+ - **It costs a write and a read.** Each spooled upload is written once, and read once at its turn.
266
+ On a network volume, that is the price of taking it off the heap.
267
+ - **A volume that stops answering.** Each call to the disk (opening the file, each write, closing
268
+ it) is waited for no longer than `uploadIdleTimeoutMs` (30 s). Past it, the upload is answered
269
+ `500` `{ "error": "Upload failed (ETIMEDOUT)." }`, and its room is given back. The file is removed
270
+ at once, or once the volume answers. On a network volume, closing a file can wait for the writes
271
+ the system held back: on a slow one, raise `uploadIdleTimeoutMs`. The same holds for the `path`
272
+ of `prepareUpload`, and for the check of its folders with a ref. The removal of the file, once
273
+ the ingest ends, is waited for no longer either: the upload is answered, its room is given back,
274
+ and the removal goes on alone. The ingest's look at the file before its turn, and its read at its
275
+ turn, are waited for no longer than `ingestTimeoutMs` (2 minutes by default). Past it, the look
276
+ is answered `500` `{ "error": "Upload failed (ETIMEDOUT)." }`. The read fails as a file that took
277
+ too long to read: `422`, code `"timeout"`. Until then, the upload holds its room. With
278
+ `ingestTimeoutMs: 0`, the look still stops at 2 minutes, but the read waits until the client
279
+ leaves.
280
+ - **Saving the upload where you keep it.** When your app keeps each upload anyway, `prepareUpload`
281
+ gives its path, and the body is written there instead, once, and kept by reference
282
+ ([Web app](./web-app.md#save-each-upload-where-you-keep-it-prepareupload)). Such a body takes no
283
+ room of either limit: it is on your volume, and stays.
284
+
285
+ **Ingest from a path.** New in 0.9.0. Code that saves an upload to disk before it ingests it (to
286
+ keep it, or to take it off the heap while it waits) can give `files.ingest` the path in place of the
287
+ bytes ([`IngestFromSource`](../reference/library.md#ingestfromsource)). A relative path is made
288
+ absolute when `ingest` is called. The path is looked at with `lstat` then, which refuses an empty
289
+ file or one over `maxUploadBytes` at once. That look is given up on when the caller's `signal`
290
+ aborts, and fails after `ingestTimeoutMs` when the volume does not answer. The file is read when
291
+ the ingest's turn comes (`maxConcurrentIngests`): once, and at most `maxUploadBytes + 1` bytes.
292
+ The bytes are let go as soon as the extractor returns: they are not held while the text is
293
+ prepared and stored, unless the store keeps a copy (`keepOriginals` with a store that has
294
+ `putOriginal`, and no `original`). So ingests that wait for their turn hold none of their files. Measured
295
+ on Node 22 with 100 ingests of 2 MB logs waiting behind one that held the turn: the process held
296
+ 73 MB (RSS) with paths, against 282 to 286 MB with the bytes given, 200 MB of which were the
297
+ uploads. With all 100 run, two at a time (the default), the peak was 159 to 160 MB with paths,
298
+ against 265 to 277 MB, in the same time. With `createIsolatedExtractors`, a PDF or Office file at a
299
+ path is read by its child process, and the server reads none of it (below), unless the store keeps
300
+ a copy of it (as above): the server then reads it, and sends the bytes to the child.
301
+ The library never writes, moves or deletes the file: remove it once it is ingested, or keep it and
302
+ let `view_pages` read it from there ([Storage](./storage.md#keeping-the-uploaded-files)). Never
303
+ build the path from what a client sends.
304
+
198
305
  An ingest runs in your server's process, a slice at a time. It pauses for other requests about
199
306
  every 12 ms of its work, so an answer streaming on the same server waits a fraction of a second,
200
- not seconds: the longest stall measured was 34 ms for a 99 MB log and 0.16 s for a 2,000-page
307
+ not seconds. Two steps of a text file still run in one block, each as long as the file is large:
308
+ the decoding of a UTF-8 file when its reading starts, and, over a `FileDocumentStore`, the writing
309
+ of its text. On 0.9.0 with Node 22, on a busy laptop, the longest stall was 56 to 64 ms for a log
310
+ of 25 MB and 0.23 to 0.36 s for one of 95 MB, about 2 to 4 ms for each MB. 0.6.0 measured 34 ms
311
+ for a 99 MB log over a `MemoryDocumentStore` on Windows with Node 24, and 0.16 s for a 2,000-page
201
312
  PDF, where 0.5.0 held the server for 2.0 s and 4.5 s ([measured](../measurements.md#the-server)).
202
313
  A text file in an older encoding is decoded a megabyte at a time, and a line of megabytes is
203
314
  cleaned in pieces of 256K characters: one line of 30 MB with a control character between its
@@ -224,8 +335,8 @@ await import("@cantoo/pdf-lib");
224
335
  await (await import("unpdf")).getResolvedPDFJS();
225
336
  ```
226
337
 
227
- `getResolvedPDFJS()` rejects when the `unpdf` installed cannot load pdf.js on this Node (unpdf 1.9
228
- and later on Node 20), and the server then does not start: install the version for your Node
338
+ `getResolvedPDFJS()` rejects when the `unpdf` installed cannot load pdf.js on this Node, and the
339
+ server then does not start: install the version for your Node
229
340
  ([PDFs and other formats](./pdfs.md#formats)).
230
341
 
231
342
  What it does not do is keep its memory apart. The text and its copies, and what pdf.js,
@@ -240,8 +351,14 @@ end after the time limit. Four ways to bound that:
240
351
  to 704 MB, depending on the version of Node, as the tables above show) and a kill timer (120 s),
241
352
  and a file that runs the child out of memory is refused while the server goes on.
242
353
  - **Accept one or two ingests at a time** per server, and answer the others with 503: this bounds
243
- memory and keeps stalls from adding up. `createIsolatedExtractors` does it for the files it reads
244
- (`concurrency` and `maxQueue`); the recipe at the end of this section does it for whole ingests.
354
+ memory and keeps stalls from adding up. Since 0.8.2 the library does it by default: each
355
+ `LargeFiles` lets `maxConcurrentIngests` (2) ingests work at once and queues the others, and
356
+ `createDocumentHandlers` answers 503 with `Retry-After` once it holds `maxPendingUploadBytes`
357
+ (twice `maxUploadBytes`) of uploads, before reading the next body. A route of your own around
358
+ `files.ingest` gets the queue, but must bound the bodies it reads itself: count the bytes of the
359
+ uploads it holds, and answer 503 before reading one that would pass your limit.
360
+ `createIsolatedExtractors` bounds the files it reads too (`concurrency` and `maxQueue`); the
361
+ recipe at the end of this section runs whole ingests in a process of their own.
245
362
  - **Ingest in a process of its own**, the whole ingest, with a heap limit and a time limit: at the
246
363
  end of this section. It also keeps the copies of the text off your server's heap, and runs an
247
364
  extractor of your own, such as OCR, apart. A process that runs out of memory stops alone, and the
@@ -253,13 +370,16 @@ end after the time limit. Four ways to bound that:
253
370
  own `createLargeFiles` and `createDocumentHandlers`, on servers sized for uploads, can write the
254
371
  documents that the chat servers read. Give it the options that apply at ingest, the same as the
255
372
  chat servers would have: `ttlMs`, `maxUploadBytes`, `maxTextBytes`, `maxPdfPages`,
256
- `ingestTimeoutMs`, `extractors`, `keepOriginals` and `scannedPdfPages`. The chat servers need the
373
+ `ingestTimeoutMs`, `extractors`, `keepOriginals`, `scannedPdfPages` and `maxConcurrentIngests`,
374
+ and to its handlers `maxPendingUploadBytes` and `uploadIdleTimeoutMs`. The chat servers need the
257
375
  options that apply to reading: `cacheBytes`, `cacheSize`, `wholeDocumentBytes`, `scanChunkBytes`,
258
376
  `maxConcurrentScans` and `budget`.
259
377
 
260
378
  **Child processes for the parsers.** With the `extractors` of `createIsolatedExtractors`, each PDF,
261
379
  DOCX, PPTX or XLSX file is copied to a child process, read there by the built-in extractor, and its
262
- text sent back; the text is then normalized, profiled, indexed and stored in your server, as
380
+ text sent back; a file ingested from a path is not copied: since 0.9.0 the child reads it from its
381
+ path, within `maxUploadBytes`, and nothing of it waits in the server for a child (unless the store
382
+ keeps a copy of it: `keepOriginals`, a store with `putOriginal`, and no `original`); the text is then normalized, profiled, indexed and stored in your server, as
263
383
  before. Text files, HTML included, are read in the server, in slices. What a file can do from there:
264
384
 
265
385
  - run its child out of memory: the child stops, and the file is refused with an `IngestError` of
@@ -301,35 +421,40 @@ itself is the isolation:
301
421
 
302
422
  ```ts
303
423
  // ingest-process.ts: one ingest, in a process of its own, forked by documents.ts below.
304
- import { createLargeFiles, FileDocumentStore, type IngestInput } from "llm-large-files";
424
+ import {
425
+ createLargeFiles, DocumentScopeError, DocumentStoreError, FileDocumentStore, IngestError,
426
+ type DocumentScopeErrorCode, type DocumentStoreOperation, type IngestErrorCode, type IngestFromSource, type IngestInput,
427
+ } from "llm-large-files";
305
428
 
306
429
  const files = createLargeFiles({
307
430
  store: new FileDocumentStore(process.env.DOCUMENTS_DIR ?? "/mnt/documents"),
308
431
  keepOriginals: ["pdf"],
309
432
  });
310
433
 
434
+ /** What the server needs to answer an error as createDocumentHandlers does: never a path or a host. */
435
+ export type IngestFailure =
436
+ | { kind: "ingest"; code: IngestErrorCode; message: string; retryAfterMs?: number } // a file refused: its words are for the user
437
+ | { kind: "store"; operation: DocumentStoreOperation; code?: string } // the store failed: a 503 to try again
438
+ | { kind: "scope"; code: DocumentScopeErrorCode }
439
+ | { kind: "status"; status: number; message: string } // an error with a status, such as a 503 of an OCR service
440
+ | { kind: "other" }; // anything else: a 500 "Upload failed.", without its message
441
+
442
+ function failureOf(error: unknown): IngestFailure {
443
+ if (IngestError.is(error)) return { kind: "ingest", code: error.code, message: error.message, ...(error.retryAfterMs !== undefined ? { retryAfterMs: error.retryAfterMs } : {}) };
444
+ if (DocumentStoreError.is(error)) return { kind: "store", operation: error.operation, ...(error.code ? { code: error.code } : {}) };
445
+ if (DocumentScopeError.is(error)) return { kind: "scope", code: error.code };
446
+ const { status } = (error ?? {}) as { status?: unknown };
447
+ if (error instanceof Error && typeof status === "number" && status >= 400 && status <= 599) return { kind: "status", status, message: error.message };
448
+ console.error("The ingest failed", error); // its own words, for your log only
449
+ return { kind: "other" };
450
+ }
451
+
311
452
  process.once("message", async (message) => {
312
453
  try {
313
- process.send!({ meta: await files.ingest(message as IngestInput) });
454
+ // The path of the file (`source`): this process reads it itself. Bytes only for a body a framework read.
455
+ process.send!({ meta: await files.ingest(message as IngestInput | IngestFromSource) });
314
456
  } catch (error) {
315
- const { code, syscall, status, statusCode } = (error ?? {}) as { code?: unknown; syscall?: unknown; status?: unknown; statusCode?: unknown };
316
- const httpStatus = typeof status === "number" ? status : typeof statusCode === "number" ? statusCode : undefined;
317
- process.send!({
318
- failed: error instanceof Error ? {
319
- message: error.message,
320
- // What createDocumentHandlers answers by: a status (a 503 from your store or an OCR service),
321
- // or the code and syscall of a failure of the store (500). Without either, a 422 with this
322
- // message, even for an error of your store (below).
323
- ...(httpStatus !== undefined ? { status: httpStatus } : {}),
324
- ...(typeof code === "string" && typeof syscall === "string" ? { code, syscall } : {}),
325
- } : {
326
- // Not an Error: its code and syscall when it has both, or else a 500 with no message.
327
- // createDocumentHandlers answers it as it does without this process: with the code, or with
328
- // { "error": "Upload failed." }.
329
- message: "",
330
- ...(typeof code === "string" && typeof syscall === "string" ? { code, syscall } : { status: 500 }),
331
- },
332
- });
457
+ process.send!({ failed: failureOf(error) });
333
458
  }
334
459
  });
335
460
  ```
@@ -340,21 +465,33 @@ takes any `LargeFiles`, so the rest stays as it is:
340
465
  ```ts
341
466
  // documents.ts: the upload routes. Each ingest runs in a process of its own, one at a time on this server.
342
467
  import { fork } from "node:child_process";
343
- import type { DocumentMeta, IngestInput } from "llm-large-files";
468
+ import { DocumentScopeError, DocumentStoreError, IngestError, type DocumentMeta, type IngestFromSource, type IngestInput } from "llm-large-files";
344
469
  import { createDocumentHandlers } from "llm-large-files/node";
345
470
  import { files } from "./large-files.js";
346
471
  import { userIdOf } from "./auth.js"; // your sign-in
472
+ import type { IngestFailure } from "./ingest-process.js";
347
473
 
348
474
  const INGESTS_AT_ONCE = 1;
349
475
  let running = 0;
350
476
 
351
- type IngestReply = { meta?: DocumentMeta; failed?: { message: string; code?: string; syscall?: string; status?: number } };
477
+ type IngestReply = { meta?: DocumentMeta; failed?: IngestFailure };
478
+
479
+ /** The process's failure as the error createDocumentHandlers answers: an IngestError is the only 422. */
480
+ function errorOf(failed: IngestFailure): Error {
481
+ switch (failed.kind) {
482
+ case "ingest": return new IngestError(failed.code, failed.message, failed.retryAfterMs !== undefined ? { retryAfterMs: failed.retryAfterMs } : {});
483
+ case "store": return new DocumentStoreError(new Error("The store failed in the ingest process."), { operation: failed.operation, ...(failed.code ? { code: failed.code } : {}) });
484
+ case "scope": return new DocumentScopeError(failed.code);
485
+ case "status": return Object.assign(new Error(failed.message), { status: failed.status });
486
+ default: return new Error("The ingest process failed."); // answered 500 "Upload failed."
487
+ }
488
+ }
352
489
 
353
- function ingestInProcess(input: IngestInput): Promise<DocumentMeta> {
490
+ function ingestInProcess(input: IngestInput | IngestFromSource): Promise<DocumentMeta> {
354
491
  if (input.signal?.aborted) return Promise.reject(input.signal.reason);
355
492
  if (running >= INGESTS_AT_ONCE) {
356
- // An error with a status is answered with that status and its message.
357
- return Promise.reject(Object.assign(new Error("The server is reading other files. Try again in a minute."), { status: 503 }));
493
+ // Answered 503, with Retry-After.
494
+ return Promise.reject(new IngestError("busy", "The server is reading other files. Try again in a minute.", { retryAfterMs: 60_000 }));
358
495
  }
359
496
  running++;
360
497
  return new Promise<DocumentMeta>((resolve, reject) => {
@@ -363,7 +500,7 @@ function ingestInProcess(input: IngestInput): Promise<DocumentMeta> {
363
500
  // flag (the table above has the flags of other versions). This flag wins over a
364
501
  // --max-old-space-size in NODE_OPTIONS, which the child inherits.
365
502
  execArgv: ["--max-old-space-size=320"],
366
- serialization: "advanced", // the bytes go as they are, not as JSON
503
+ serialization: "advanced", // bytes, when there are any, go as they are, not as JSON
367
504
  });
368
505
  let reply: IngestReply | undefined;
369
506
  let timedOut = false;
@@ -387,13 +524,10 @@ function ingestInProcess(input: IngestInput): Promise<DocumentMeta> {
387
524
  running--;
388
525
  if (reply?.meta) resolve(reply.meta);
389
526
  else if (input.signal?.aborted) reject(input.signal.reason);
390
- // With a status, that status and message (a 503 from your store or an OCR service); with a
391
- // code and a syscall, a failure of the store (500); otherwise a file that cannot be read
392
- // (422), even when the error came from your store (below).
393
- else if (reply?.failed) reject(Object.assign(new Error(reply.failed.message), reply.failed));
394
- else if (timedOut) reject(new Error(`${input.name} took too long to read.`));
527
+ else if (reply?.failed) reject(errorOf(reply.failed));
528
+ else if (timedOut) reject(new IngestError("timeout", `${input.name} took too long to read.`));
395
529
  // Out of memory, or crashed: that process is gone, and this server goes on.
396
- else reject(new Error(`${input.name} could not be read on this server.`));
530
+ else reject(new IngestError("out_of_memory", `${input.name} could not be read on this server.`));
397
531
  };
398
532
  child.once("message", (message) => {
399
533
  reply = message as IngestReply;
@@ -404,27 +538,40 @@ function ingestInProcess(input: IngestInput): Promise<DocumentMeta> {
404
538
  child.kill();
405
539
  settle();
406
540
  });
407
- // The bytes are copied to the process. A signal cannot be sent: the process has its own
408
- // ingestTimeoutMs, and is killed when this one aborts.
541
+ // With the spool, the message holds the path of the file, not its bytes: the process reads it.
542
+ // The handler removes the file once this promise settles, after the process is gone. A signal
543
+ // cannot be sent: the process has its own ingestTimeoutMs, and is killed when this one aborts.
409
544
  const { signal: _signal, ...message } = input;
410
545
  child.send(message);
411
546
  });
412
547
  }
413
548
 
414
- export const documents = createDocumentHandlers({ ...files, ingest: ingestInProcess }, { getOwner: userIdOf });
549
+ export const documents = createDocumentHandlers({ ...files, ingest: ingestInProcess }, {
550
+ getOwner: userIdOf,
551
+ // Every body to a file of the spool, so that only its path goes to the process.
552
+ uploadSpool: { directory: "/var/spool/uploads", minBytes: 0 },
553
+ });
415
554
  ```
416
555
 
417
556
  Checked on Node 24: with `NODE_OPTIONS=--max-old-space-size=1024` on the server and a heap of 48 MB
418
557
  for the child, a 2,000-page PDF ran the child out of memory; the upload was answered "book.pdf
419
558
  could not be read on this server.", and the next upload was ingested.
420
559
 
421
- The error that `ingestInProcess` rebuilds from the process's reply is a new `Error`, so
422
- `createDocumentHandlers` cannot tell a store that failed to write from a file that cannot be read.
423
- Given `files` itself, it answers a store's error that has no status, and no `code` and `syscall`,
424
- with 500 `{ "error": "Upload failed." }`. Through this process, it answers that error 422 with the
425
- store's own message, which may name a database host. Give your store's errors a status and a
426
- message of your own, as [Storage](./storage.md#errors) shows: the process passes the status on. A
427
- thrown value that is not an `Error` gets the same answer with the process as without it.
560
+ Since 0.9.0 the server sends the process the path of the upload, not its bytes: with
561
+ `uploadSpool` and `minBytes: 0`, every body the handler reads is written to a file of the spool, and
562
+ `ingest` gets `source: { path }`. The process reads the file itself, so the upload is neither held
563
+ in the server while the process starts nor copied over the IPC channel. The process runs as the
564
+ server's user, so it can read the spool's `0o600` files. A body a framework already read
565
+ (`express.raw()`) still comes as bytes, and is copied. The handler removes the file once the
566
+ promise of `ingestInProcess` settles, which is after the process exited.
567
+
568
+ Since 0.9.0 `createDocumentHandlers` answers `422` only an `IngestError`, and any other error
569
+ without a status `500` "Upload failed.", without its message (S12). So the server rebuilds the
570
+ error the process caught by its kind: an `IngestError` with its code and message, a
571
+ `DocumentStoreError` (`503`, `Retry-After: 5`) with its operation and code, never the store's own
572
+ words. The process logs the errors it cannot pass on. Until 0.9.0 this recipe rebuilt a plain
573
+ `Error`, which the handler answered `422` with its message: a store's own message, which may name a
574
+ database host.
428
575
 
429
576
  A process stopped by its limit or its timeout may leave the files of a document that was never
430
577
  finished. `FileDocumentStore` removes them at the first sweep after they are an hour old. One
@@ -445,6 +592,14 @@ declares, not what they take: a crafted file that a process of its own ingested
445
592
  chat server out of memory at its first look, or take memory outside the heap. And what
446
593
  `@cantoo/pdf-lib` keeps after each look adds up from file to file: files of 9 KB ran a heap of 1 GB
447
594
  out of memory at the seventh look ([Security](../security.md#reading-pdfs-for-pages-and-pictures)).
595
+ Since 0.9.0 one look runs at a time in a library (`maxConcurrentPageLooks`, 1 by default), over
596
+ all its questions: the others wait, before their PDF is loaded, for up to `pageLookWaitMs` (30 s),
597
+ and then the model is told the server is busy. So the heap holds one parsed PDF at a time, not one
598
+ for each question that looks. Raise it only with the heap to match: six looks at once took 352 MB
599
+ more than one, and did not finish sooner. A look holds its turn while it reads the PDF from the
600
+ store, for at most `ingestTimeoutMs` (2 minutes by default). Past it, the turn goes back and the
601
+ model is told the file could not be read in time. The read itself goes on: give your store's
602
+ `getOriginal` a time limit of its own, shorter than that, when it reads over a network.
448
603
  For the documents of users you do not trust, do not offer `view_pages` (`viewPages: false`), or keep
449
604
  no PDF originals. To offer it anyway, run each of their questions, the whole tool loop, in a process
450
605
  you fork, with its own heap and memory limits. What the model is told when pages cannot be shown,
@@ -460,17 +615,24 @@ documents it removed, or 0 for a store without one.
460
615
 
461
616
  `FileDocumentStore.sweep` also removes the files of uploads that were never finished, once they are
462
617
  `orphanAgeMs` old (one hour by default): younger ones may be an upload in progress on another
463
- server ([Storage](./storage.md#filedocumentstore)).
618
+ server ([Storage](./storage.md#filedocumentstore)). It reads `sweepConcurrency` files at once, 16 by
619
+ default. With `scopes`, `files.sweep()` walks the folders of every scope (exactly `depth` levels,
620
+ following no link), and `files.sweep({ scope })` sweeps the folder of one chat.
464
621
 
465
622
  **Where to run it.** On one server, or from a scheduled job. Running it on every server is safe
466
623
  with `FileDocumentStore`, since removing a file that another sweep just removed is no error, but
467
- each server then lists the whole directory and reads every metadata file. A job of its own:
624
+ each server then lists the whole directory (with `scopes`, every chat's folder) and reads every
625
+ metadata file. Run it from one server, or take a lease first (a document in MongoDB with an expiry
626
+ that one server holds at a time). A job of its own runs as the user of the servers, or in their
627
+ group with the modes above. Give it the options of the servers' store:
468
628
 
469
629
  ```ts
470
630
  // sweep.ts: run every hour by a scheduled job (cron, a Kubernetes CronJob, Cloud Scheduler).
471
631
  import { createLargeFiles, FileDocumentStore } from "llm-large-files";
472
632
 
473
- const files = createLargeFiles({ store: new FileDocumentStore(process.env.DOCUMENTS_DIR ?? "/mnt/documents") });
633
+ // The options of the servers' store: here, a folder per user and chat.
634
+ const store = new FileDocumentStore(process.env.DOCUMENTS_DIR ?? "/mnt/documents", { scopes: { depth: 2 } });
635
+ const files = createLargeFiles({ store });
474
636
  const removed = await files.sweep();
475
637
  console.log(`Removed ${removed} expired documents.`);
476
638
  ```
@@ -578,12 +740,66 @@ export function stopOnSigterm(server: Server, graceMs = 25_000): void {
578
740
  ```
579
741
 
580
742
  Abort with an `Error`, as here, not a string: `partialResultOf` needs an object to look the
581
- question up by. An upload cut by the restart leaves files that the sweep removes an hour later.
582
- With [`createIsolatedExtractors`](../reference/node.md#createisolatedextractorsoptions), call
743
+ question up by. With
744
+ [`createIsolatedExtractors`](../reference/node.md#createisolatedextractorsoptions), call
583
745
  `isolated.close()` when the grace period ends, next to `stopping.abort`: it kills its child
584
746
  processes, and refuses the files still waiting or being read as `"busy"` (503 "The server is
585
747
  shutting down. Try again in a moment.").
586
748
 
749
+ An upload cut by the restart, or by a server killed past its grace period or out of memory, can
750
+ leave files of three kinds:
751
+
752
+ - **The store's.** The files of `FileDocumentStore` for a document that was never finished. The
753
+ sweep removes them once they are an hour old.
754
+ - **The spool's.** A server empties its own spool folder when it starts. A container restarted in
755
+ its pod (after an OOM kill, say) has the same hostname and folder, and empties it. A pod that is
756
+ replaced gets a new hostname, so its folder on the shared volume stays until you remove it. An
757
+ `emptyDir` goes with its pod ([Uploads and ingest](#uploads-and-ingest)).
758
+ - **The partial file at the `path` of `prepareUpload`.** Nothing removes it: the sweep removes only
759
+ the store's files, and no document refers to it. A record of your own that `prepareUpload` wrote
760
+ for it stays too. Remove such files with a job of your own, now and then: each file of `uploads/`
761
+ older than any upload takes, whose document is not stored (`files.getMeta(id, { owner, scope })`
762
+ gives `undefined`). An upload takes up to `server.requestTimeout` (5 minutes) for its body, then
763
+ its wait for a turn, `ingestTimeoutMs` (2 minutes) and your `onUploaded`: an hour leaves room.
764
+
765
+ ```ts
766
+ // remove-cut-uploads.ts: run now and then, for each chat (a CronJob, or a timer on one server).
767
+ import { readdir, rm, stat } from "node:fs/promises";
768
+ import path from "node:path";
769
+ import type { LargeFiles } from "llm-large-files";
770
+
771
+ /** Longer than any upload takes: its body, its wait for a turn, its ingest and onUploaded. */
772
+ const CUT_AFTER_MS = 60 * 60_000;
773
+
774
+ /**
775
+ * Removes the files of <user>/<chat>/uploads that no stored document has: those of uploads cut by a
776
+ * killed server, and those of documents deleted or expired.
777
+ */
778
+ export async function removeCutUploads(files: LargeFiles, volume: string, user: string, chat: string): Promise<void> {
779
+ const folder = path.join(volume, user, chat, "uploads");
780
+ // A chat without the folder (one made before 0.9.0) has nothing to remove.
781
+ for (const entry of await readdir(folder, { withFileTypes: true }).catch(() => [])) {
782
+ if (!entry.isFile()) continue;
783
+ const file = path.join(folder, entry.name);
784
+ // Still arriving, or waiting for its ingest; or removed meanwhile (by onRemoved).
785
+ const info = await stat(file).catch(() => undefined);
786
+ if (!info || Date.now() - info.mtimeMs < CUT_AFTER_MS) continue;
787
+ // Its document is stored: the file is the document's, and yours.
788
+ if (await files.getMeta(entry.name, { owner: user, scope: [user, chat] })) continue;
789
+ await rm(file, { force: true });
790
+ }
791
+ }
792
+ ```
793
+
794
+ Each file is named by its document's ID, as in the examples of
795
+ [`prepareUpload`](../reference/node.md#saving-the-body-prepareupload). The folder holds only those
796
+ files: anything else in it an hour old, with no document of its name, goes too. A file is kept only
797
+ while its document is stored, so the file of a document that was deleted or has expired goes as
798
+ well. That fits an app that keeps each file as long as its document, as the
799
+ [upgrade guide's example](../upgrading-0.9.md) does (`ttlMs: Infinity`, and `onRemoved` removes the
800
+ file). An app that keeps its files longer should look up its own record of the upload (the one
801
+ `prepareUpload` or `onUploaded` wrote) instead of `getMeta`.
802
+
587
803
  After a restart the cache is empty: the first tool calls read their documents from the store again,
588
804
  and a thinking model's first whole-file read in the new process may spend one request finding the
589
805
  output limit it needs.
@@ -601,6 +817,13 @@ same conversations.
601
817
  8% more in JSON. One ingested before 0.4.0 has no index: it is built the first time the document
602
818
  is used, and saved for the other servers. Upgrading from 0.3.x has notes of its own in
603
819
  [the 0.4.0 entry of the changelog](https://github.com/renanbazinin/llm-large-files/blob/v0.5.0/CHANGELOG.md#040---2026-11-12).
820
+ - **Documents of 0.9.0.** In the flat layout, 0.9.0 keeps the names and fields of 0.8, so servers of
821
+ 0.8 read the documents 0.9.0 writes under the IDs the library makes, and ignore the new fields.
822
+ They do not read a document under an application's ID, nor the folders of a store with `scopes`:
823
+ they answer such documents as missing, and the user is asked for the file again. Upgrade every
824
+ server at once, or keep each chat on servers of one version until the rollout ends. Files that
825
+ 0.9.0 writes are `0600`: servers of 0.8 that run as another user cannot read them either.
826
+ [Upgrading to 0.9](../upgrading-0.9.md#several-servers-and-rolling-deploys) has the steps.
604
827
  - **A document keeps what the version that ingested it extracted**: its text, outline and log
605
828
  profile. A better extractor applies to files uploaded after the upgrade. A text file in an older
606
829
  encoding that 0.5.0 stored holds U+FFFD where 0.6.0 reads its letters, and text that 0.5.0
@@ -608,8 +831,10 @@ same conversations.
608
831
  again to get the new reading. A document that 0.5.0 stored with the owner `""` stays readable
609
832
  with that owner until it expires.
610
833
  - **Conversations.** `toolTurns` are plain JSON, and their type (`ToolTurn`) has not changed since
611
- they appeared in 0.5.0. Both versions read the ones the other stored. 0.6.0 sends the rounds of
612
- an earlier question without their `tool_turns_left`
834
+ they appeared in 0.5.0, but for `version`, which 0.9.0 adds to the rounds it makes. Both versions
835
+ read the ones the other stored: a version before 0.9.0 ignores `version`, and 0.9.0 refuses a
836
+ round whose `version` is above 1, made by a later version, with a `TypeError`. 0.6.0 sends the
837
+ rounds of an earlier question without their `tool_turns_left`
613
838
  ([Conversations](./conversations.md#what-toolturns-holds)).
614
839
  - **Provider caches.** The tool guide in the system instruction, the descriptions of
615
840
  `analyze_whole_document` and `search_document`, and the frame lines of a file sent whole changed
@@ -626,19 +851,16 @@ same conversations.
626
851
 
627
852
  ## Node.js, ESM and `require()`
628
853
 
629
- - **Node.js 20.19 or newer** (`engines` in `package.json`). The tests run on Node 20, 22 and 24,
630
- and again with unpdf 1.7.0 on Node 20, the newest 1.x on Node 22 and 24, and the newest 2.x on
631
- Node 24. Pick the `unpdf` for your Node ([PDFs and other formats](./pdfs.md#formats)).
854
+ - **Node.js 22.12 or newer** (`engines` in `package.json`; 20.19 until 0.9.0). The tests run on
855
+ Node 22, 24 and 26, and again with the newest unpdf 1.x on Node 22 and 24, and the newest 2.x on
856
+ Node 24 and 26. Pick the `unpdf` for your Node ([PDFs and other formats](./pdfs.md#formats)).
632
857
  - **The package is ESM only.** It has `"type": "module"` and an `exports` map with `types` and
633
858
  `default`; there is no CommonJS build. An ESM application imports it as it is.
634
- - **A CommonJS application can `require()` it** on Node 20.19 and newer in the 20 line, and on Node
635
- 22.12 and newer: those load an ES module with `require()`, and the library has no top-level
636
- `await`. On Node 22.0 to 22.11, load it with `import()` from an async function: a CommonJS file
637
- has no top-level `await`, so write `const { createLargeFiles } = await import("llm-large-files");`
638
- inside `async function main() { ... }`.
859
+ - **A CommonJS application can `require()` it**: Node 22.12 and newer load an ES module with
860
+ `require()`, and the library has no top-level `await`.
639
861
 
640
862
  ```js
641
- // CommonJS, Node 20.19+ or 22.12+
863
+ // CommonJS
642
864
  const { createLargeFiles, FileDocumentStore } = require("llm-large-files");
643
865
  const { askGemini, vertexAi } = require("llm-large-files/gemini");
644
866
  const { createDocumentHandlers } = require("llm-large-files/node");
@@ -682,14 +904,14 @@ optional peer dependencies. Add the ones you need to the `dependencies` of your
682
904
 
683
905
  | Package | Version | Needed for | Without it |
684
906
  |---|---|---|---|
685
- | `unpdf` | `^1.4.0 \|\| ^2.0.0`, in a version that runs on your Node: 1.7.0 on Node 20, a 1.x from 1.6.1 on Node 22, any on Node 24 and later ([PDFs](./pdfs.md#formats)) | The text of PDFs | The upload is refused: `Reading PDF files needs the optional dependency "unpdf".` (422 from `createDocumentHandlers`). A version that does not run on your Node is refused too, with a message that says what to install: `The unpdf installed cannot read PDF files on Node 20 (…). Install unpdf 1.7.0 (npm install unpdf@1.7.0), or run Node 22 or later.` |
907
+ | `unpdf` | `^1.4.0 \|\| ^2.0.0`, in a version that runs on your Node: a 1.x from 1.6.1 on Node 22, any on Node 24 and later ([PDFs](./pdfs.md#formats)) | The text of PDFs | The upload is refused: `Reading PDF files needs the optional dependency "unpdf".` (422 from `createDocumentHandlers`). A version that would stop the server on your Node is refused too, with a message that says what to install: `The unpdf installed would stop the whole server at the first PDF file on Node 22, so PDF files are not read. Install unpdf 1.6.1 or later, or run Node 24 or later.` |
686
908
  | `jszip` | `^3.10.0` | DOCX, PPTX and XLSX | The upload is refused: `Reading DOCX, PPTX and XLSX files needs the optional dependency "jszip".` |
687
909
  | `@cantoo/pdf-lib` | `^2.11.1` | `view_pages`, the check of PDF pages that would hold the server, and the marks on PDF pages that show a picture | `view_pages` answers the model `report.pdf: Showing PDF pages needs the optional dependency "@cantoo/pdf-lib".` (with the file's name), and PDFs are ingested without the check and without the marks, with no error |
688
910
 
689
911
  The last one fails quietly at ingest, so an image without it ingests PDFs differently from your
690
912
  machine, and lets through the pages the check would refuse. On Node 24 and later,
691
- `npm install unpdf` installs unpdf 2, which does not run on Node 20: for an image on Node 20 or 22,
692
- name the version in your `dependencies`. Check at startup that the image has what your application
913
+ `npm install unpdf` installs unpdf 2, which asks for Node 24: for an image on Node 22, name the
914
+ version in your `dependencies`. Check at startup that the image has what your application
693
915
  uses:
694
916
 
695
917
  ```ts