llm-large-files 0.8.2 → 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 (201) hide show
  1. package/CHANGELOG.md +535 -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 +169 -34
  56. package/dist/library.d.ts.map +1 -1
  57. package/dist/library.js +324 -591
  58. package/dist/library.js.map +1 -1
  59. package/dist/map-reduce.js +3 -3
  60. package/dist/map-reduce.js.map +1 -1
  61. package/dist/model.d.ts +43 -2
  62. package/dist/model.d.ts.map +1 -1
  63. package/dist/model.js +63 -3
  64. package/dist/model.js.map +1 -1
  65. package/dist/node/handlers.d.ts +226 -14
  66. package/dist/node/handlers.d.ts.map +1 -1
  67. package/dist/node/handlers.js +423 -181
  68. package/dist/node/handlers.js.map +1 -1
  69. package/dist/node/index.d.ts +3 -2
  70. package/dist/node/index.d.ts.map +1 -1
  71. package/dist/node/index.js +2 -1
  72. package/dist/node/index.js.map +1 -1
  73. package/dist/node/ingest-child.d.ts +7 -1
  74. package/dist/node/ingest-child.d.ts.map +1 -1
  75. package/dist/node/ingest-child.js +18 -3
  76. package/dist/node/ingest-child.js.map +1 -1
  77. package/dist/node/isolated.d.ts +3 -1
  78. package/dist/node/isolated.d.ts.map +1 -1
  79. package/dist/node/isolated.js +11 -4
  80. package/dist/node/isolated.js.map +1 -1
  81. package/dist/node/originals.d.ts +19 -0
  82. package/dist/node/originals.d.ts.map +1 -0
  83. package/dist/node/originals.js +82 -0
  84. package/dist/node/originals.js.map +1 -0
  85. package/dist/node/spool.d.ts +102 -0
  86. package/dist/node/spool.d.ts.map +1 -0
  87. package/dist/node/spool.js +365 -0
  88. package/dist/node/spool.js.map +1 -0
  89. package/dist/node/sse.d.ts +4 -3
  90. package/dist/node/sse.d.ts.map +1 -1
  91. package/dist/node/sse.js +7 -6
  92. package/dist/node/sse.js.map +1 -1
  93. package/dist/pdf-layout.d.ts.map +1 -1
  94. package/dist/pdf-layout.js +71 -12
  95. package/dist/pdf-layout.js.map +1 -1
  96. package/dist/ranged.d.ts +15 -11
  97. package/dist/ranged.d.ts.map +1 -1
  98. package/dist/ranged.js +42 -11
  99. package/dist/ranged.js.map +1 -1
  100. package/dist/retry.d.ts +3 -1
  101. package/dist/retry.d.ts.map +1 -1
  102. package/dist/retry.js +6 -2
  103. package/dist/retry.js.map +1 -1
  104. package/dist/scope.d.ts +25 -0
  105. package/dist/scope.d.ts.map +1 -0
  106. package/dist/scope.js +60 -0
  107. package/dist/scope.js.map +1 -0
  108. package/dist/source.d.ts +60 -0
  109. package/dist/source.d.ts.map +1 -0
  110. package/dist/source.js +170 -0
  111. package/dist/source.js.map +1 -0
  112. package/dist/stores.d.ts +120 -31
  113. package/dist/stores.d.ts.map +1 -1
  114. package/dist/stores.js +582 -139
  115. package/dist/stores.js.map +1 -1
  116. package/dist/testing/fake-fetch.d.ts +31 -0
  117. package/dist/testing/fake-fetch.d.ts.map +1 -0
  118. package/dist/testing/fake-fetch.js +66 -0
  119. package/dist/testing/fake-fetch.js.map +1 -0
  120. package/dist/testing/fake-model.d.ts +38 -0
  121. package/dist/testing/fake-model.d.ts.map +1 -0
  122. package/dist/testing/fake-model.js +62 -0
  123. package/dist/testing/fake-model.js.map +1 -0
  124. package/dist/testing/index.d.ts +7 -0
  125. package/dist/testing/index.d.ts.map +1 -0
  126. package/dist/testing/index.js +9 -0
  127. package/dist/testing/index.js.map +1 -0
  128. package/dist/testing/store-checks.d.ts +72 -0
  129. package/dist/testing/store-checks.d.ts.map +1 -0
  130. package/dist/testing/store-checks.js +619 -0
  131. package/dist/testing/store-checks.js.map +1 -0
  132. package/dist/tools.d.ts +25 -0
  133. package/dist/tools.d.ts.map +1 -1
  134. package/dist/tools.js +135 -13
  135. package/dist/tools.js.map +1 -1
  136. package/dist/types.d.ts +116 -13
  137. package/dist/types.d.ts.map +1 -1
  138. package/docs/README.md +17 -8
  139. package/docs/getting-started.md +18 -13
  140. package/docs/guides/anthropic.md +12 -8
  141. package/docs/guides/conversations.md +112 -47
  142. package/docs/guides/costs-and-limits.md +16 -7
  143. package/docs/guides/deployment.md +284 -83
  144. package/docs/guides/errors-and-reliability.md +161 -23
  145. package/docs/guides/own-adapter-and-loop.md +27 -10
  146. package/docs/guides/pdfs.md +123 -29
  147. package/docs/guides/storage.md +633 -145
  148. package/docs/guides/testing.md +78 -129
  149. package/docs/guides/vertex-and-gemini.md +10 -7
  150. package/docs/guides/web-app.md +312 -78
  151. package/docs/how-it-works.md +35 -8
  152. package/docs/measurements.md +43 -8
  153. package/docs/publishing.md +112 -36
  154. package/docs/reference/ask.md +154 -13
  155. package/docs/reference/errors-and-retries.md +166 -14
  156. package/docs/reference/events.md +53 -20
  157. package/docs/reference/gemini.md +70 -21
  158. package/docs/reference/library.md +706 -165
  159. package/docs/reference/node.md +624 -110
  160. package/docs/reference/testing.md +311 -0
  161. package/docs/reference/tools.md +15 -5
  162. package/docs/security.md +304 -67
  163. package/docs/troubleshooting.md +144 -65
  164. package/docs/upgrading-0.9.md +890 -0
  165. package/package.json +12 -3
  166. package/src/access.ts +144 -0
  167. package/src/ask.ts +230 -19
  168. package/src/cache.ts +20 -5
  169. package/src/encoding.ts +6 -4
  170. package/src/error-info.ts +255 -0
  171. package/src/errors.ts +129 -15
  172. package/src/events.ts +86 -21
  173. package/src/evidence.ts +14 -3
  174. package/src/extract.ts +50 -33
  175. package/src/gemini/adapter.ts +97 -11
  176. package/src/gemini/chat.ts +20 -6
  177. package/src/gemini/index.ts +1 -1
  178. package/src/index.ts +9 -6
  179. package/src/ingest.ts +927 -0
  180. package/src/library.ts +467 -601
  181. package/src/map-reduce.ts +3 -3
  182. package/src/model.ts +69 -5
  183. package/src/node/handlers.ts +630 -183
  184. package/src/node/index.ts +13 -2
  185. package/src/node/ingest-child.ts +23 -5
  186. package/src/node/isolated.ts +11 -4
  187. package/src/node/originals.ts +78 -0
  188. package/src/node/spool.ts +365 -0
  189. package/src/node/sse.ts +7 -6
  190. package/src/pdf-layout.ts +69 -11
  191. package/src/ranged.ts +34 -13
  192. package/src/retry.ts +6 -2
  193. package/src/scope.ts +63 -0
  194. package/src/source.ts +178 -0
  195. package/src/stores.ts +635 -140
  196. package/src/testing/fake-fetch.ts +80 -0
  197. package/src/testing/fake-model.ts +78 -0
  198. package/src/testing/index.ts +11 -0
  199. package/src/testing/store-checks.ts +660 -0
  200. package/src/tools.ts +150 -14
  201. package/src/types.ts +106 -13
@@ -57,7 +57,8 @@ this:
57
57
  metadata must be able to read the text.
58
58
  - **The text is kept byte for byte.** `readTextRange` reads UTF-8 byte offsets that the line index
59
59
  computed at ingest. A text that changed is noticed ("The stored text of … did not match its
60
- 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.
61
62
  - **`undefined` means "not there", and nothing else.** A read that failed (a timeout, a volume that
62
63
  does not answer) must throw: the library passes it on as `DocumentStoreError` instead of telling
63
64
  the user that the file is gone.
@@ -79,7 +80,18 @@ The built-in stores:
79
80
  [Sweeping expired documents](#sweeping-expired-documents)).
80
81
 
81
82
  It needs a file system whose rename is atomic and that shows each server the files of the
82
- 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:
83
95
 
84
96
  - An NFS client may remember for a while that a file did not exist (its negative lookup cache).
85
97
  A question sent to another server right after an upload can then find the document missing.
@@ -100,13 +112,15 @@ The built-in stores:
100
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 |
101
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 |
102
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) |
103
- | An ingest | Five to seven times the file above the uploaded bytes at its peak (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) |
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) |
104
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 |
105
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)) |
106
118
 
107
119
  Measured peaks are in [Measurements](../measurements.md#the-server): an ingest of a plain-text log
108
- takes about five to seven times the log above the uploaded bytes, and eight searches at once take
109
- 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.)
110
124
 
111
125
  Other formats were not measured for memory. PDF text is extracted by pdf.js, which reads the whole
112
126
  file, and with `@cantoo/pdf-lib` installed the file is parsed a second time, before pdf.js reads a
@@ -121,17 +135,17 @@ Set the heap limit of Node yourself: about three quarters of the memory of the c
121
135
  everything runs in one process, less when files are read in child processes
122
136
  (`createIsolatedExtractors`) or ingest runs in a process of its own: each has a heap of its own. The
123
137
  limit is more than the flag. `--max-old-space-size` sets the old generation, and Node adds its young
124
- 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.
125
139
  `v8.getHeapStatistics().heap_size_limit` gives the sum. For three quarters of 2 GB, a limit of
126
140
  1,536 MB:
127
141
 
128
142
  | Node | Flag for a heap limit of 1,536 MB | What `--max-old-space-size=1536` gives |
129
143
  |---|---|---|
130
- | 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 |
131
145
  | 24 | `NODE_OPTIONS=--max-old-space-size=1344` | 1,728 MB, 84% of 2 GB |
132
146
  | 26 | `NODE_OPTIONS=--max-old-space-size=1440` | 1,632 MB |
133
147
 
134
- 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
135
149
  from the store are `Buffer`s, which live outside the heap and need the rest. The check that refuses
136
150
  a PDF too large to cut pages from compares it with the free heap, so a heap set to fit the
137
151
  container makes that check right.
@@ -139,9 +153,9 @@ container makes that check right.
139
153
  A worker thread does not get a heap limit of its own when the process has one: a
140
154
  `--max-old-space-size` on the command line or in `NODE_OPTIONS` replaces the
141
155
  `resourceLimits.maxOldGenerationSizeMb` of every worker. With `--max-old-space-size=1024`, a worker
142
- 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
143
157
  Node 26. Setting `execArgv: []` or `env` on the worker did not change it. A forked process does get
144
- 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,
145
159
  704 MB on Node 24 and 608 MB on Node 26, with `NODE_OPTIONS=--max-old-space-size=1024` in the
146
160
  environment it inherits or without it.
147
161
 
@@ -151,13 +165,13 @@ numbers of the last column:
151
165
 
152
166
  | Node | Main heap of 1 GB | Heap of 512 MB for the child that reads a file |
153
167
  |---|---|---|
154
- | 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` |
155
169
  | 24 | `--max-old-space-size=832` | `--max-old-space-size=320`, `maxHeapMb: 320` |
156
170
  | 26 | `--max-old-space-size=928` | `--max-old-space-size=416`, `maxHeapMb: 416` |
157
171
 
158
172
  The flags 1024 and 512 give heap limits of 1,216 and 704 MB on Node 24: 1,920 MB, which leaves
159
173
  about 128 MB of the container for the upload, its copy, files read from the store and two Node
160
- 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.
161
175
 
162
176
  ```ts
163
177
  // large-files.ts: created once per process and imported by every route.
@@ -174,6 +188,7 @@ export const files = createLargeFiles({
174
188
  store: new FileDocumentStore(process.env.DOCUMENTS_DIR ?? "/mnt/documents"),
175
189
  extractors: isolated.extractors, // PDF, DOCX, PPTX and XLSX
176
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
177
192
  cacheBytes: 256 * 1024 * 1024, // the default
178
193
  maxConcurrentScans: 4, // the default
179
194
  maxConcurrentIngests: 2, // the default: the others wait their turn
@@ -183,9 +198,9 @@ export const files = createLargeFiles({
183
198
 
184
199
  | Where 2 GB go | |
185
200
  |---|---|
186
- | 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) |
187
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 |
188
- | 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 |
189
204
 
190
205
  Raise `cacheBytes` to spend memory on speed: at 1 GB, the decoded pieces of an ASCII log of up to
191
206
  about 125 MB are kept between searches. Lower `maxUploadBytes` if large uploads are not needed:
@@ -193,12 +208,14 @@ an ingest is one of the largest single uses of memory.
193
208
 
194
209
  ### Uploads and ingest
195
210
 
196
- `createDocumentHandlers` reads the whole upload into memory before it calls `ingest`. It refuses a
197
- body whose `Content-Length` is over `maxUploadBytes` before reading it, and stops reading one that
198
- 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
199
216
  that takes longer than five minutes to arrive: raise it for users on slow links.
200
217
 
201
- Since 0.8.2 the handlers hold uploads of at most `maxPendingUploadBytes` at once (twice
218
+ Since 0.8.2 the handlers hold uploads of at most `maxPendingUploadBytes` at once in memory (twice
202
219
  `maxUploadBytes` by default), and answer one that would pass it 503 with `Retry-After: 5` before
203
220
  reading its body. The room of an upload is taken before its body arrives, from its `Content-Length`
204
221
  (or `maxUploadBytes` when it declares none), so a client that sends headers and then nothing, or
@@ -209,9 +226,89 @@ body before it passes the request on (nginx does by default, `proxy_request_buff
209
226
  arrive at once and none of this happens; otherwise, limit the connections of each client at the
210
227
  proxy.
211
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
+
212
305
  An ingest runs in your server's process, a slice at a time. It pauses for other requests about
213
306
  every 12 ms of its work, so an answer streaming on the same server waits a fraction of a second,
214
- 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
215
312
  PDF, where 0.5.0 held the server for 2.0 s and 4.5 s ([measured](../measurements.md#the-server)).
216
313
  A text file in an older encoding is decoded a megabyte at a time, and a line of megabytes is
217
314
  cleaned in pieces of 256K characters: one line of 30 MB with a control character between its
@@ -238,8 +335,8 @@ await import("@cantoo/pdf-lib");
238
335
  await (await import("unpdf")).getResolvedPDFJS();
239
336
  ```
240
337
 
241
- `getResolvedPDFJS()` rejects when the `unpdf` installed cannot load pdf.js on this Node (unpdf 1.9
242
- 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
243
340
  ([PDFs and other formats](./pdfs.md#formats)).
244
341
 
245
342
  What it does not do is keep its memory apart. The text and its copies, and what pdf.js,
@@ -280,7 +377,9 @@ end after the time limit. Four ways to bound that:
280
377
 
281
378
  **Child processes for the parsers.** With the `extractors` of `createIsolatedExtractors`, each PDF,
282
379
  DOCX, PPTX or XLSX file is copied to a child process, read there by the built-in extractor, and its
283
- 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
284
383
  before. Text files, HTML included, are read in the server, in slices. What a file can do from there:
285
384
 
286
385
  - run its child out of memory: the child stops, and the file is refused with an `IngestError` of
@@ -322,35 +421,40 @@ itself is the isolation:
322
421
 
323
422
  ```ts
324
423
  // ingest-process.ts: one ingest, in a process of its own, forked by documents.ts below.
325
- 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";
326
428
 
327
429
  const files = createLargeFiles({
328
430
  store: new FileDocumentStore(process.env.DOCUMENTS_DIR ?? "/mnt/documents"),
329
431
  keepOriginals: ["pdf"],
330
432
  });
331
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
+
332
452
  process.once("message", async (message) => {
333
453
  try {
334
- 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) });
335
456
  } catch (error) {
336
- const { code, syscall, status, statusCode } = (error ?? {}) as { code?: unknown; syscall?: unknown; status?: unknown; statusCode?: unknown };
337
- const httpStatus = typeof status === "number" ? status : typeof statusCode === "number" ? statusCode : undefined;
338
- process.send!({
339
- failed: error instanceof Error ? {
340
- message: error.message,
341
- // What createDocumentHandlers answers by: a status (a 503 from your store or an OCR service),
342
- // or the code and syscall of a failure of the store (500). Without either, a 422 with this
343
- // message, even for an error of your store (below).
344
- ...(httpStatus !== undefined ? { status: httpStatus } : {}),
345
- ...(typeof code === "string" && typeof syscall === "string" ? { code, syscall } : {}),
346
- } : {
347
- // Not an Error: its code and syscall when it has both, or else a 500 with no message.
348
- // createDocumentHandlers answers it as it does without this process: with the code, or with
349
- // { "error": "Upload failed." }.
350
- message: "",
351
- ...(typeof code === "string" && typeof syscall === "string" ? { code, syscall } : { status: 500 }),
352
- },
353
- });
457
+ process.send!({ failed: failureOf(error) });
354
458
  }
355
459
  });
356
460
  ```
@@ -361,21 +465,33 @@ takes any `LargeFiles`, so the rest stays as it is:
361
465
  ```ts
362
466
  // documents.ts: the upload routes. Each ingest runs in a process of its own, one at a time on this server.
363
467
  import { fork } from "node:child_process";
364
- import type { DocumentMeta, IngestInput } from "llm-large-files";
468
+ import { DocumentScopeError, DocumentStoreError, IngestError, type DocumentMeta, type IngestFromSource, type IngestInput } from "llm-large-files";
365
469
  import { createDocumentHandlers } from "llm-large-files/node";
366
470
  import { files } from "./large-files.js";
367
471
  import { userIdOf } from "./auth.js"; // your sign-in
472
+ import type { IngestFailure } from "./ingest-process.js";
368
473
 
369
474
  const INGESTS_AT_ONCE = 1;
370
475
  let running = 0;
371
476
 
372
- 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
+ }
373
489
 
374
- function ingestInProcess(input: IngestInput): Promise<DocumentMeta> {
490
+ function ingestInProcess(input: IngestInput | IngestFromSource): Promise<DocumentMeta> {
375
491
  if (input.signal?.aborted) return Promise.reject(input.signal.reason);
376
492
  if (running >= INGESTS_AT_ONCE) {
377
- // An error with a status is answered with that status and its message.
378
- 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 }));
379
495
  }
380
496
  running++;
381
497
  return new Promise<DocumentMeta>((resolve, reject) => {
@@ -384,7 +500,7 @@ function ingestInProcess(input: IngestInput): Promise<DocumentMeta> {
384
500
  // flag (the table above has the flags of other versions). This flag wins over a
385
501
  // --max-old-space-size in NODE_OPTIONS, which the child inherits.
386
502
  execArgv: ["--max-old-space-size=320"],
387
- 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
388
504
  });
389
505
  let reply: IngestReply | undefined;
390
506
  let timedOut = false;
@@ -408,13 +524,10 @@ function ingestInProcess(input: IngestInput): Promise<DocumentMeta> {
408
524
  running--;
409
525
  if (reply?.meta) resolve(reply.meta);
410
526
  else if (input.signal?.aborted) reject(input.signal.reason);
411
- // With a status, that status and message (a 503 from your store or an OCR service); with a
412
- // code and a syscall, a failure of the store (500); otherwise a file that cannot be read
413
- // (422), even when the error came from your store (below).
414
- else if (reply?.failed) reject(Object.assign(new Error(reply.failed.message), reply.failed));
415
- 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.`));
416
529
  // Out of memory, or crashed: that process is gone, and this server goes on.
417
- 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.`));
418
531
  };
419
532
  child.once("message", (message) => {
420
533
  reply = message as IngestReply;
@@ -425,27 +538,40 @@ function ingestInProcess(input: IngestInput): Promise<DocumentMeta> {
425
538
  child.kill();
426
539
  settle();
427
540
  });
428
- // The bytes are copied to the process. A signal cannot be sent: the process has its own
429
- // 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.
430
544
  const { signal: _signal, ...message } = input;
431
545
  child.send(message);
432
546
  });
433
547
  }
434
548
 
435
- 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
+ });
436
554
  ```
437
555
 
438
556
  Checked on Node 24: with `NODE_OPTIONS=--max-old-space-size=1024` on the server and a heap of 48 MB
439
557
  for the child, a 2,000-page PDF ran the child out of memory; the upload was answered "book.pdf
440
558
  could not be read on this server.", and the next upload was ingested.
441
559
 
442
- The error that `ingestInProcess` rebuilds from the process's reply is a new `Error`, so
443
- `createDocumentHandlers` cannot tell a store that failed to write from a file that cannot be read.
444
- Given `files` itself, it answers a store's error that has no status, and no `code` and `syscall`,
445
- with 500 `{ "error": "Upload failed." }`. Through this process, it answers that error 422 with the
446
- store's own message, which may name a database host. Give your store's errors a status and a
447
- message of your own, as [Storage](./storage.md#errors) shows: the process passes the status on. A
448
- 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.
449
575
 
450
576
  A process stopped by its limit or its timeout may leave the files of a document that was never
451
577
  finished. `FileDocumentStore` removes them at the first sweep after they are an hour old. One
@@ -466,6 +592,14 @@ declares, not what they take: a crafted file that a process of its own ingested
466
592
  chat server out of memory at its first look, or take memory outside the heap. And what
467
593
  `@cantoo/pdf-lib` keeps after each look adds up from file to file: files of 9 KB ran a heap of 1 GB
468
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.
469
603
  For the documents of users you do not trust, do not offer `view_pages` (`viewPages: false`), or keep
470
604
  no PDF originals. To offer it anyway, run each of their questions, the whole tool loop, in a process
471
605
  you fork, with its own heap and memory limits. What the model is told when pages cannot be shown,
@@ -481,17 +615,24 @@ documents it removed, or 0 for a store without one.
481
615
 
482
616
  `FileDocumentStore.sweep` also removes the files of uploads that were never finished, once they are
483
617
  `orphanAgeMs` old (one hour by default): younger ones may be an upload in progress on another
484
- 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.
485
621
 
486
622
  **Where to run it.** On one server, or from a scheduled job. Running it on every server is safe
487
623
  with `FileDocumentStore`, since removing a file that another sweep just removed is no error, but
488
- 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:
489
628
 
490
629
  ```ts
491
630
  // sweep.ts: run every hour by a scheduled job (cron, a Kubernetes CronJob, Cloud Scheduler).
492
631
  import { createLargeFiles, FileDocumentStore } from "llm-large-files";
493
632
 
494
- 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 });
495
636
  const removed = await files.sweep();
496
637
  console.log(`Removed ${removed} expired documents.`);
497
638
  ```
@@ -599,12 +740,66 @@ export function stopOnSigterm(server: Server, graceMs = 25_000): void {
599
740
  ```
600
741
 
601
742
  Abort with an `Error`, as here, not a string: `partialResultOf` needs an object to look the
602
- question up by. An upload cut by the restart leaves files that the sweep removes an hour later.
603
- With [`createIsolatedExtractors`](../reference/node.md#createisolatedextractorsoptions), call
743
+ question up by. With
744
+ [`createIsolatedExtractors`](../reference/node.md#createisolatedextractorsoptions), call
604
745
  `isolated.close()` when the grace period ends, next to `stopping.abort`: it kills its child
605
746
  processes, and refuses the files still waiting or being read as `"busy"` (503 "The server is
606
747
  shutting down. Try again in a moment.").
607
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
+
608
803
  After a restart the cache is empty: the first tool calls read their documents from the store again,
609
804
  and a thinking model's first whole-file read in the new process may spend one request finding the
610
805
  output limit it needs.
@@ -622,6 +817,13 @@ same conversations.
622
817
  8% more in JSON. One ingested before 0.4.0 has no index: it is built the first time the document
623
818
  is used, and saved for the other servers. Upgrading from 0.3.x has notes of its own in
624
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.
625
827
  - **A document keeps what the version that ingested it extracted**: its text, outline and log
626
828
  profile. A better extractor applies to files uploaded after the upgrade. A text file in an older
627
829
  encoding that 0.5.0 stored holds U+FFFD where 0.6.0 reads its letters, and text that 0.5.0
@@ -629,8 +831,10 @@ same conversations.
629
831
  again to get the new reading. A document that 0.5.0 stored with the owner `""` stays readable
630
832
  with that owner until it expires.
631
833
  - **Conversations.** `toolTurns` are plain JSON, and their type (`ToolTurn`) has not changed since
632
- they appeared in 0.5.0. Both versions read the ones the other stored. 0.6.0 sends the rounds of
633
- 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`
634
838
  ([Conversations](./conversations.md#what-toolturns-holds)).
635
839
  - **Provider caches.** The tool guide in the system instruction, the descriptions of
636
840
  `analyze_whole_document` and `search_document`, and the frame lines of a file sent whole changed
@@ -647,19 +851,16 @@ same conversations.
647
851
 
648
852
  ## Node.js, ESM and `require()`
649
853
 
650
- - **Node.js 20.19 or newer** (`engines` in `package.json`). The tests run on Node 20, 22 and 24,
651
- 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
652
- 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)).
653
857
  - **The package is ESM only.** It has `"type": "module"` and an `exports` map with `types` and
654
858
  `default`; there is no CommonJS build. An ESM application imports it as it is.
655
- - **A CommonJS application can `require()` it** on Node 20.19 and newer in the 20 line, and on Node
656
- 22.12 and newer: those load an ES module with `require()`, and the library has no top-level
657
- `await`. On Node 22.0 to 22.11, load it with `import()` from an async function: a CommonJS file
658
- has no top-level `await`, so write `const { createLargeFiles } = await import("llm-large-files");`
659
- 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`.
660
861
 
661
862
  ```js
662
- // CommonJS, Node 20.19+ or 22.12+
863
+ // CommonJS
663
864
  const { createLargeFiles, FileDocumentStore } = require("llm-large-files");
664
865
  const { askGemini, vertexAi } = require("llm-large-files/gemini");
665
866
  const { createDocumentHandlers } = require("llm-large-files/node");
@@ -703,14 +904,14 @@ optional peer dependencies. Add the ones you need to the `dependencies` of your
703
904
 
704
905
  | Package | Version | Needed for | Without it |
705
906
  |---|---|---|---|
706
- | `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.` |
707
908
  | `jszip` | `^3.10.0` | DOCX, PPTX and XLSX | The upload is refused: `Reading DOCX, PPTX and XLSX files needs the optional dependency "jszip".` |
708
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 |
709
910
 
710
911
  The last one fails quietly at ingest, so an image without it ingests PDFs differently from your
711
912
  machine, and lets through the pages the check would refuse. On Node 24 and later,
712
- `npm install unpdf` installs unpdf 2, which does not run on Node 20: for an image on Node 20 or 22,
713
- 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
714
915
  uses:
715
916
 
716
917
  ```ts