llm-large-files 0.8.2 → 0.10.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 (288) hide show
  1. package/CHANGELOG.md +981 -0
  2. package/README.md +22 -17
  3. package/dist/access.d.ts +128 -0
  4. package/dist/access.d.ts.map +1 -0
  5. package/dist/access.js +234 -0
  6. package/dist/access.js.map +1 -0
  7. package/dist/aggregate.d.ts +6 -0
  8. package/dist/aggregate.d.ts.map +1 -1
  9. package/dist/aggregate.js +86 -13
  10. package/dist/aggregate.js.map +1 -1
  11. package/dist/analyze.d.ts +4 -0
  12. package/dist/analyze.d.ts.map +1 -1
  13. package/dist/analyze.js +2 -2
  14. package/dist/analyze.js.map +1 -1
  15. package/dist/answer-info.d.ts +26 -0
  16. package/dist/answer-info.d.ts.map +1 -0
  17. package/dist/answer-info.js +32 -0
  18. package/dist/answer-info.js.map +1 -0
  19. package/dist/anthropic/adapter.d.ts +5 -1
  20. package/dist/anthropic/adapter.d.ts.map +1 -1
  21. package/dist/anthropic/adapter.js +35 -10
  22. package/dist/anthropic/adapter.js.map +1 -1
  23. package/dist/ask.d.ts +159 -14
  24. package/dist/ask.d.ts.map +1 -1
  25. package/dist/ask.js +743 -113
  26. package/dist/ask.js.map +1 -1
  27. package/dist/cache.d.ts +12 -3
  28. package/dist/cache.d.ts.map +1 -1
  29. package/dist/cache.js +18 -5
  30. package/dist/cache.js.map +1 -1
  31. package/dist/citations.d.ts +36 -0
  32. package/dist/citations.d.ts.map +1 -0
  33. package/dist/citations.js +291 -0
  34. package/dist/citations.js.map +1 -0
  35. package/dist/encoding.js +5 -3
  36. package/dist/encoding.js.map +1 -1
  37. package/dist/error-info.d.ts +70 -0
  38. package/dist/error-info.d.ts.map +1 -0
  39. package/dist/error-info.js +253 -0
  40. package/dist/error-info.js.map +1 -0
  41. package/dist/errors.d.ts +74 -8
  42. package/dist/errors.d.ts.map +1 -1
  43. package/dist/errors.js +104 -15
  44. package/dist/errors.js.map +1 -1
  45. package/dist/events.d.ts +57 -13
  46. package/dist/events.d.ts.map +1 -1
  47. package/dist/events.js +42 -11
  48. package/dist/events.js.map +1 -1
  49. package/dist/evidence.d.ts +4 -2
  50. package/dist/evidence.d.ts.map +1 -1
  51. package/dist/evidence.js +35 -5
  52. package/dist/evidence.js.map +1 -1
  53. package/dist/extract.d.ts +32 -8
  54. package/dist/extract.d.ts.map +1 -1
  55. package/dist/extract.js +52 -36
  56. package/dist/extract.js.map +1 -1
  57. package/dist/gemini/adapter.d.ts +54 -7
  58. package/dist/gemini/adapter.d.ts.map +1 -1
  59. package/dist/gemini/adapter.js +152 -41
  60. package/dist/gemini/adapter.js.map +1 -1
  61. package/dist/gemini/chat.d.ts +38 -53
  62. package/dist/gemini/chat.d.ts.map +1 -1
  63. package/dist/gemini/chat.js +20 -25
  64. package/dist/gemini/chat.js.map +1 -1
  65. package/dist/gemini/endpoints.d.ts +59 -11
  66. package/dist/gemini/endpoints.d.ts.map +1 -1
  67. package/dist/gemini/endpoints.js +33 -7
  68. package/dist/gemini/endpoints.js.map +1 -1
  69. package/dist/gemini/errors.d.ts +39 -5
  70. package/dist/gemini/errors.d.ts.map +1 -1
  71. package/dist/gemini/errors.js +70 -9
  72. package/dist/gemini/errors.js.map +1 -1
  73. package/dist/gemini/generate.d.ts +53 -2
  74. package/dist/gemini/generate.d.ts.map +1 -1
  75. package/dist/gemini/generate.js +100 -50
  76. package/dist/gemini/generate.js.map +1 -1
  77. package/dist/gemini/index.d.ts +4 -4
  78. package/dist/gemini/index.d.ts.map +1 -1
  79. package/dist/http.d.ts +41 -3
  80. package/dist/http.d.ts.map +1 -1
  81. package/dist/http.js +40 -2
  82. package/dist/http.js.map +1 -1
  83. package/dist/index.d.ts +13 -8
  84. package/dist/index.d.ts.map +1 -1
  85. package/dist/index.js +8 -5
  86. package/dist/index.js.map +1 -1
  87. package/dist/ingest.d.ts +78 -0
  88. package/dist/ingest.d.ts.map +1 -0
  89. package/dist/ingest.js +893 -0
  90. package/dist/ingest.js.map +1 -0
  91. package/dist/library.d.ts +295 -33
  92. package/dist/library.d.ts.map +1 -1
  93. package/dist/library.js +458 -650
  94. package/dist/library.js.map +1 -1
  95. package/dist/map-reduce.d.ts +176 -10
  96. package/dist/map-reduce.d.ts.map +1 -1
  97. package/dist/map-reduce.js +807 -61
  98. package/dist/map-reduce.js.map +1 -1
  99. package/dist/model.d.ts +79 -6
  100. package/dist/model.d.ts.map +1 -1
  101. package/dist/model.js +80 -4
  102. package/dist/model.js.map +1 -1
  103. package/dist/node/handlers.d.ts +247 -14
  104. package/dist/node/handlers.d.ts.map +1 -1
  105. package/dist/node/handlers.js +491 -227
  106. package/dist/node/handlers.js.map +1 -1
  107. package/dist/node/index.d.ts +3 -2
  108. package/dist/node/index.d.ts.map +1 -1
  109. package/dist/node/index.js +2 -1
  110. package/dist/node/index.js.map +1 -1
  111. package/dist/node/ingest-child.d.ts +7 -1
  112. package/dist/node/ingest-child.d.ts.map +1 -1
  113. package/dist/node/ingest-child.js +19 -4
  114. package/dist/node/ingest-child.js.map +1 -1
  115. package/dist/node/isolated.d.ts +3 -1
  116. package/dist/node/isolated.d.ts.map +1 -1
  117. package/dist/node/isolated.js +11 -4
  118. package/dist/node/isolated.js.map +1 -1
  119. package/dist/node/originals.d.ts +19 -0
  120. package/dist/node/originals.d.ts.map +1 -0
  121. package/dist/node/originals.js +82 -0
  122. package/dist/node/originals.js.map +1 -0
  123. package/dist/node/spool.d.ts +106 -0
  124. package/dist/node/spool.d.ts.map +1 -0
  125. package/dist/node/spool.js +378 -0
  126. package/dist/node/spool.js.map +1 -0
  127. package/dist/node/sse.d.ts +6 -4
  128. package/dist/node/sse.d.ts.map +1 -1
  129. package/dist/node/sse.js +9 -7
  130. package/dist/node/sse.js.map +1 -1
  131. package/dist/openai/adapter.d.ts +5 -1
  132. package/dist/openai/adapter.d.ts.map +1 -1
  133. package/dist/openai/adapter.js +53 -12
  134. package/dist/openai/adapter.js.map +1 -1
  135. package/dist/output-limit.d.ts +2 -1
  136. package/dist/output-limit.d.ts.map +1 -1
  137. package/dist/output-limit.js +5 -2
  138. package/dist/output-limit.js.map +1 -1
  139. package/dist/pdf-layout.d.ts.map +1 -1
  140. package/dist/pdf-layout.js +71 -12
  141. package/dist/pdf-layout.js.map +1 -1
  142. package/dist/pdf-outline.d.ts +71 -0
  143. package/dist/pdf-outline.d.ts.map +1 -0
  144. package/dist/pdf-outline.js +414 -0
  145. package/dist/pdf-outline.js.map +1 -0
  146. package/dist/plan.d.ts +137 -7
  147. package/dist/plan.d.ts.map +1 -1
  148. package/dist/plan.js +248 -26
  149. package/dist/plan.js.map +1 -1
  150. package/dist/prepare.d.ts +50 -0
  151. package/dist/prepare.d.ts.map +1 -0
  152. package/dist/prepare.js +207 -0
  153. package/dist/prepare.js.map +1 -0
  154. package/dist/ranged.d.ts +16 -11
  155. package/dist/ranged.d.ts.map +1 -1
  156. package/dist/ranged.js +56 -12
  157. package/dist/ranged.js.map +1 -1
  158. package/dist/retry.d.ts +3 -1
  159. package/dist/retry.d.ts.map +1 -1
  160. package/dist/retry.js +6 -2
  161. package/dist/retry.js.map +1 -1
  162. package/dist/scope.d.ts +25 -0
  163. package/dist/scope.d.ts.map +1 -0
  164. package/dist/scope.js +60 -0
  165. package/dist/scope.js.map +1 -0
  166. package/dist/search.d.ts +7 -0
  167. package/dist/search.d.ts.map +1 -1
  168. package/dist/search.js +72 -10
  169. package/dist/search.js.map +1 -1
  170. package/dist/source.d.ts +60 -0
  171. package/dist/source.d.ts.map +1 -0
  172. package/dist/source.js +170 -0
  173. package/dist/source.js.map +1 -0
  174. package/dist/stores.d.ts +126 -31
  175. package/dist/stores.d.ts.map +1 -1
  176. package/dist/stores.js +655 -141
  177. package/dist/stores.js.map +1 -1
  178. package/dist/testing/fake-fetch.d.ts +31 -0
  179. package/dist/testing/fake-fetch.d.ts.map +1 -0
  180. package/dist/testing/fake-fetch.js +66 -0
  181. package/dist/testing/fake-fetch.js.map +1 -0
  182. package/dist/testing/fake-model.d.ts +38 -0
  183. package/dist/testing/fake-model.d.ts.map +1 -0
  184. package/dist/testing/fake-model.js +62 -0
  185. package/dist/testing/fake-model.js.map +1 -0
  186. package/dist/testing/index.d.ts +7 -0
  187. package/dist/testing/index.d.ts.map +1 -0
  188. package/dist/testing/index.js +9 -0
  189. package/dist/testing/index.js.map +1 -0
  190. package/dist/testing/store-checks.d.ts +72 -0
  191. package/dist/testing/store-checks.d.ts.map +1 -0
  192. package/dist/testing/store-checks.js +619 -0
  193. package/dist/testing/store-checks.js.map +1 -0
  194. package/dist/tools.d.ts +47 -2
  195. package/dist/tools.d.ts.map +1 -1
  196. package/dist/tools.js +440 -71
  197. package/dist/tools.js.map +1 -1
  198. package/dist/types.d.ts +165 -14
  199. package/dist/types.d.ts.map +1 -1
  200. package/dist/whole-cost.d.ts +37 -0
  201. package/dist/whole-cost.d.ts.map +1 -0
  202. package/dist/whole-cost.js +46 -0
  203. package/dist/whole-cost.js.map +1 -0
  204. package/docs/README.md +21 -8
  205. package/docs/getting-started.md +18 -13
  206. package/docs/guides/anthropic.md +17 -10
  207. package/docs/guides/conversations.md +112 -47
  208. package/docs/guides/costs-and-limits.md +147 -42
  209. package/docs/guides/deployment.md +380 -86
  210. package/docs/guides/errors-and-reliability.md +317 -67
  211. package/docs/guides/explorer-model.md +4 -1
  212. package/docs/guides/openai-compatible.md +47 -7
  213. package/docs/guides/own-adapter-and-loop.md +60 -16
  214. package/docs/guides/pdfs.md +219 -36
  215. package/docs/guides/storage.md +676 -145
  216. package/docs/guides/testing.md +149 -129
  217. package/docs/guides/vertex-and-gemini.md +169 -57
  218. package/docs/guides/web-app.md +318 -80
  219. package/docs/how-it-works.md +155 -30
  220. package/docs/measurements.md +215 -13
  221. package/docs/publishing.md +185 -37
  222. package/docs/reference/anthropic.md +12 -7
  223. package/docs/reference/ask.md +415 -47
  224. package/docs/reference/errors-and-retries.md +194 -14
  225. package/docs/reference/events.md +77 -27
  226. package/docs/reference/gemini.md +252 -87
  227. package/docs/reference/library.md +886 -178
  228. package/docs/reference/node.md +659 -111
  229. package/docs/reference/openai.md +21 -10
  230. package/docs/reference/testing.md +311 -0
  231. package/docs/reference/tools.md +285 -30
  232. package/docs/security.md +404 -78
  233. package/docs/troubleshooting.md +151 -70
  234. package/docs/upgrading-0.10.md +472 -0
  235. package/docs/upgrading-0.9.md +890 -0
  236. package/package.json +16 -3
  237. package/src/access.ts +267 -0
  238. package/src/aggregate.ts +92 -14
  239. package/src/analyze.ts +2 -2
  240. package/src/answer-info.ts +45 -0
  241. package/src/anthropic/adapter.ts +40 -11
  242. package/src/ask.ts +866 -115
  243. package/src/cache.ts +20 -5
  244. package/src/citations.ts +294 -0
  245. package/src/encoding.ts +6 -4
  246. package/src/error-info.ts +290 -0
  247. package/src/errors.ts +131 -15
  248. package/src/events.ts +112 -24
  249. package/src/evidence.ts +35 -5
  250. package/src/extract.ts +56 -34
  251. package/src/gemini/adapter.ts +196 -43
  252. package/src/gemini/chat.ts +63 -78
  253. package/src/gemini/endpoints.ts +89 -16
  254. package/src/gemini/errors.ts +74 -11
  255. package/src/gemini/generate.ts +147 -57
  256. package/src/gemini/index.ts +4 -4
  257. package/src/http.ts +65 -4
  258. package/src/index.ts +13 -8
  259. package/src/ingest.ts +958 -0
  260. package/src/library.ts +711 -651
  261. package/src/map-reduce.ts +858 -70
  262. package/src/model.ts +113 -9
  263. package/src/node/handlers.ts +709 -221
  264. package/src/node/index.ts +14 -2
  265. package/src/node/ingest-child.ts +24 -6
  266. package/src/node/isolated.ts +11 -4
  267. package/src/node/originals.ts +78 -0
  268. package/src/node/spool.ts +379 -0
  269. package/src/node/sse.ts +9 -7
  270. package/src/openai/adapter.ts +56 -13
  271. package/src/output-limit.ts +5 -2
  272. package/src/pdf-layout.ts +69 -11
  273. package/src/pdf-outline.ts +400 -0
  274. package/src/plan.ts +287 -36
  275. package/src/prepare.ts +253 -0
  276. package/src/ranged.ts +48 -14
  277. package/src/retry.ts +6 -2
  278. package/src/scope.ts +63 -0
  279. package/src/search.ts +69 -13
  280. package/src/source.ts +178 -0
  281. package/src/stores.ts +702 -142
  282. package/src/testing/fake-fetch.ts +80 -0
  283. package/src/testing/fake-model.ts +78 -0
  284. package/src/testing/index.ts +11 -0
  285. package/src/testing/store-checks.ts +660 -0
  286. package/src/tools.ts +461 -73
  287. package/src/types.ts +151 -14
  288. package/src/whole-cost.ts +64 -0
@@ -2,9 +2,9 @@
2
2
 
3
3
  This page is for running an application built on llm-large-files in production: on several
4
4
  servers, behind a proxy or a load balancer, through restarts and upgrades. It says what state lives
5
- where, what the shared store must guarantee, how much memory a server needs, how to sweep expired
6
- documents, how to keep a streamed answer alive, and what Node.js and packages a production image
7
- needs.
5
+ where, what the shared store must guarantee, what happens when it stops answering, how much memory
6
+ a server needs, how to sweep expired documents, how to keep a streamed answer alive, and what
7
+ Node.js and packages a production image needs.
8
8
 
9
9
  ## What lives where
10
10
 
@@ -22,6 +22,7 @@ rebuild from the store.
22
22
  | Searches of large files waiting their turn | A queue in each `LargeFiles` (`maxConcurrentScans`) | No | Empty |
23
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
24
  | Uploads being received | A count in each set of `createDocumentHandlers` (`maxPendingUploadBytes`, new in 0.8.2) | No | Empty |
25
+ | Store calls past their time limit that have not ended | A count in each process (`files.stats().stuckStoreCalls`, new in 0.10.0) | No | Zero |
25
26
  | 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 |
26
27
  | The name of the output limit an OpenAI-compatible server takes | Each `openAiCompatible()` adapter | No | Learned again, at the cost of one refused request |
27
28
 
@@ -57,7 +58,8 @@ this:
57
58
  metadata must be able to read the text.
58
59
  - **The text is kept byte for byte.** `readTextRange` reads UTF-8 byte offsets that the line index
59
60
  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.
61
+ index. Try the call again.") and its index is built again. A text of another length or number of
62
+ lines than its metadata says then reads as missing.
61
63
  - **`undefined` means "not there", and nothing else.** A read that failed (a timeout, a volume that
62
64
  does not answer) must throw: the library passes it on as `DocumentStoreError` instead of telling
63
65
  the user that the file is gone.
@@ -79,7 +81,18 @@ The built-in stores:
79
81
  [Sweeping expired documents](#sweeping-expired-documents)).
80
82
 
81
83
  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:
84
+ others: an NFS share (Amazon EFS, Google Filestore, Azure Files over NFS) or similar. Every server
85
+ opens its own `FileDocumentStore` over the same directory, with the same options (`scopes` above
86
+ all), and one library per process: then `maxConcurrentIngests`, `cacheBytes` and
87
+ `maxConcurrentScans` hold for the whole server, whatever the number of chats
88
+ ([Storage](./storage.md#files-in-a-folder-per-user-or-per-chat)).
89
+
90
+ Since 0.9.0 it writes files `0600` and folders `0700`: only the user that wrote them can read
91
+ them. Run every server, and any job that reads the volume (a backup, a sweep job), as the same
92
+ user. If they run as different users of one group, as pods with a shared `fsGroup` in Kubernetes
93
+ do, set `fileMode: 0o640` and `directoryMode: 0o750` on every store: a server that cannot read a
94
+ file another one wrote answers "The document store could not be read (EACCES)". The umask of the
95
+ process still applies. Two caveats:
83
96
 
84
97
  - An NFS client may remember for a while that a file did not exist (its negative lookup cache).
85
98
  A question sent to another server right after an upload can then find the document missing.
@@ -90,6 +103,84 @@ The built-in stores:
90
103
  - **A store of your own**, over MongoDB, S3, Cloud Storage, Redis or a database: see
91
104
  [Storage](./storage.md) for the contract method by method and a complete example.
92
105
 
106
+ ## A store that stops answering
107
+
108
+ A network volume can stop answering without failing: an NFS server that is gone, a mount that
109
+ hangs. Before 0.10.0 a question whose store call did not answer waited forever, and so did
110
+ `files.delete`. Since 0.10.0 every store call of the library has a time limit, `storeTimeoutMs`,
111
+ 30 seconds by default: a look-up (`getMeta`), a read of a text whole or by range, of its index or
112
+ of its original, and a delete. Past it, the call fails with a `DocumentStoreError` of code
113
+ `"ETIMEDOUT"`, a 503 that `errorInfoOf` marks as one to retry. In a question it ends the question
114
+ with `run.error`; the upload handlers' `remove` answers 503 with `Retry-After`. `ingest` keeps its
115
+ own limits (`ingestTimeoutMs`), and `sweep` has `sweepTimeoutMs`
116
+ ([below](#sweeping-expired-documents)).
117
+
118
+ **Size it** above the slowest healthy call: a read of the largest text loaded whole
119
+ (`wholeDocumentBytes`, 2 MB by default) or of the largest original a look at pages reads, over your
120
+ volume at its busiest. Raise it for a slow store, or set 0 for no limit.
121
+
122
+ **The thread pool.** A call to the disk that does not answer cannot be stopped: Node.js gives up
123
+ waiting for it, and the call holds one thread of libuv's pool until the volume answers. The pool
124
+ has 4 threads by default, and every file call of the process uses it, and so does every DNS look-up
125
+ (`dns.lookup`, which `fetch` calls for each new connection, to Vertex AI too). Measured on Node 22
126
+ with calls that never end (opens of a FIFO with no writer, as a hung NFS mount behaves):
127
+
128
+ | Threads (`UV_THREADPOOL_SIZE`) | Calls stuck | A read of another file | `dns.lookup("localhost")` |
129
+ |---|---|---|---|
130
+ | 4 (the default) | 3 | 9 ms | 13 ms |
131
+ | 4 (the default) | 4 | still waiting after 2 s | still waiting after 2 s |
132
+ | 32 | 4 | 2 ms | 13 ms |
133
+
134
+ So on servers that use a network volume, set `UV_THREADPOOL_SIZE=32` in the environment of the
135
+ process (the pool is made at the first call that needs it: setting it in your code later may do
136
+ nothing). Check that the value reaches the process: libuv reads an empty value, 0, or one that
137
+ does not start with digits as a pool of 1 thread, where one stuck call freezes every file call. A
138
+ template whose value is unset can give an empty one.
139
+
140
+ **Calls left stuck.** A call counts as stuck once it has run past `storeTimeoutMs`, whether its
141
+ caller timed out or left, until it ends. One that ends within the limit never counts, so users who
142
+ press stop during slow but healthy reads do not raise it. The count is the process's, as the pool
143
+ is: the calls of every library, the writes and look-ups of `ingest` past `ingestTimeoutMs` (the
144
+ time it gives them, so that a large upload written slowly is not counted at 30 s), and the upload
145
+ handlers' calls to the disk past `uploadIdleTimeoutMs`. While it is at `maxStuckStoreCalls`, every
146
+ new store call of the library, those of `ingest` included, fails at once with code `"STORE_STUCK"`
147
+ (503), without touching the volume, so that the threads left keep serving file calls and DNS. The
148
+ default is half the pool, read from `UV_THREADPOOL_SIZE` when the library is made: 2 with 4
149
+ threads, 16 with 32. Deletes of one library run one at a time, so a volume that hangs holds one
150
+ thread for them, not one for each.
151
+
152
+ **Alerts and readiness.** `files.stats()` and `handlers.stats()` read counters only, with no store
153
+ call: call them as often as your metrics need.
154
+
155
+ ```ts
156
+ import http from "node:http";
157
+
158
+ // One library and one set of handlers per process, made at startup.
159
+ let stuckSince: number | undefined;
160
+ http.createServer((request, response) => {
161
+ const stats = files.stats();
162
+ const uploads = handlers.stats();
163
+ if (request.url === "/metrics") {
164
+ response.setHeader("Content-Type", "application/json");
165
+ return void response.end(JSON.stringify({ ...stats, uploads }));
166
+ }
167
+ // Ready unless this pod is saturated, or its calls have been stuck at the limit for a minute.
168
+ const atLimit = stats.stuckStoreCalls >= stats.maxStuckStoreCalls;
169
+ stuckSince = atLimit ? (stuckSince ?? Date.now()) : undefined;
170
+ const ready = stats.ingests.waiting <= 20 && !(stuckSince !== undefined && Date.now() - stuckSince >= 60_000);
171
+ response.statusCode = ready ? 200 : 503;
172
+ response.end(ready ? "ready" : "busy");
173
+ }).listen(9090);
174
+ ```
175
+
176
+ - **Alert on `stuckStoreCalls` above 0.** It means the store stopped answering on that pod.
177
+ - **Fail readiness on local saturation**: `ingests.waiting`, `pageLooks.waiting` or
178
+ `uploads.uploadsInFlight` past a bound you choose. Another pod can take the next request.
179
+ - **Fail readiness on stuck calls only when they stay at the limit for 60 s or more.** All pods
180
+ share one volume: when it hangs, a readiness probe that fails at once takes every pod out at
181
+ once, and users get the ingress's error instead of your app's "try again". A short hang then
182
+ costs a few 503s, which your app tells as a store to retry.
183
+
93
184
  ## Memory on each server
94
185
 
95
186
  | What takes memory | How much | What bounds it |
@@ -100,13 +191,15 @@ The built-in stores:
100
191
  | 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
192
  | 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
193
  | 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) |
194
+ | 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
195
  | 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
196
  | 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
197
 
107
198
  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.
199
+ over a `FileDocumentStore` takes about three and a half to five and a half times the log above the
200
+ 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),
201
+ and eight searches at once take little more than one. (Before 0.6.0 an ingest took five to seven
202
+ times the log.)
110
203
 
111
204
  Other formats were not measured for memory. PDF text is extracted by pdf.js, which reads the whole
112
205
  file, and with `@cantoo/pdf-lib` installed the file is parsed a second time, before pdf.js reads a
@@ -121,17 +214,17 @@ Set the heap limit of Node yourself: about three quarters of the memory of the c
121
214
  everything runs in one process, less when files are read in child processes
122
215
  (`createIsolatedExtractors`) or ingest runs in a process of its own: each has a heap of its own. The
123
216
  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.
217
+ generation above it: 48 MB on Node 22, 192 MB on Node 24, and 96 MB on Node 26.
125
218
  `v8.getHeapStatistics().heap_size_limit` gives the sum. For three quarters of 2 GB, a limit of
126
219
  1,536 MB:
127
220
 
128
221
  | Node | Flag for a heap limit of 1,536 MB | What `--max-old-space-size=1536` gives |
129
222
  |---|---|---|
130
- | 20 and 22 | `NODE_OPTIONS=--max-old-space-size=1488` | 1,584 MB |
223
+ | 22 | `NODE_OPTIONS=--max-old-space-size=1488` | 1,584 MB |
131
224
  | 24 | `NODE_OPTIONS=--max-old-space-size=1344` | 1,728 MB, 84% of 2 GB |
132
225
  | 26 | `NODE_OPTIONS=--max-old-space-size=1440` | 1,632 MB |
133
226
 
134
- Checked with `heap_size_limit` on Node 20.19, 22.12, 24.19 and 26.13. Upload bodies and files read
227
+ Checked with `heap_size_limit` on Node 22.12, 24.19 and 26.13. Upload bodies and files read
135
228
  from the store are `Buffer`s, which live outside the heap and need the rest. The check that refuses
136
229
  a PDF too large to cut pages from compares it with the free heap, so a heap set to fit the
137
230
  container makes that check right.
@@ -139,9 +232,9 @@ container makes that check right.
139
232
  A worker thread does not get a heap limit of its own when the process has one: a
140
233
  `--max-old-space-size` on the command line or in `NODE_OPTIONS` replaces the
141
234
  `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
235
+ 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
236
  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,
237
+ its own: one forked with `execArgv: ["--max-old-space-size=512"]` had 560 MB on Node 22,
145
238
  704 MB on Node 24 and 608 MB on Node 26, with `NODE_OPTIONS=--max-old-space-size=1024` in the
146
239
  environment it inherits or without it.
147
240
 
@@ -151,13 +244,13 @@ numbers of the last column:
151
244
 
152
245
  | Node | Main heap of 1 GB | Heap of 512 MB for the child that reads a file |
153
246
  |---|---|---|
154
- | 20 and 22 | `--max-old-space-size=976` | `--max-old-space-size=464`, `maxHeapMb: 464` |
247
+ | 22 | `--max-old-space-size=976` | `--max-old-space-size=464`, `maxHeapMb: 464` |
155
248
  | 24 | `--max-old-space-size=832` | `--max-old-space-size=320`, `maxHeapMb: 320` |
156
249
  | 26 | `--max-old-space-size=928` | `--max-old-space-size=416`, `maxHeapMb: 416` |
157
250
 
158
251
  The flags 1024 and 512 give heap limits of 1,216 and 704 MB on Node 24: 1,920 MB, which leaves
159
252
  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.
253
+ processes. On Node 22 they give 1,072 and 560 MB.
161
254
 
162
255
  ```ts
163
256
  // large-files.ts: created once per process and imported by every route.
@@ -174,6 +267,7 @@ export const files = createLargeFiles({
174
267
  store: new FileDocumentStore(process.env.DOCUMENTS_DIR ?? "/mnt/documents"),
175
268
  extractors: isolated.extractors, // PDF, DOCX, PPTX and XLSX
176
269
  keepOriginals: ["pdf"], // view_pages: a look reads the whole PDF into this heap
270
+ maxConcurrentPageLooks: 1, // the default: one look at a time, the others wait their turn
177
271
  cacheBytes: 256 * 1024 * 1024, // the default
178
272
  maxConcurrentScans: 4, // the default
179
273
  maxConcurrentIngests: 2, // the default: the others wait their turn
@@ -183,9 +277,9 @@ export const files = createLargeFiles({
183
277
 
184
278
  | Where 2 GB go | |
185
279
  |---|---|
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) |
280
+ | 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
281
  | 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 |
282
+ | 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
283
 
190
284
  Raise `cacheBytes` to spend memory on speed: at 1 GB, the decoded pieces of an ASCII log of up to
191
285
  about 125 MB are kept between searches. Lower `maxUploadBytes` if large uploads are not needed:
@@ -193,12 +287,14 @@ an ingest is one of the largest single uses of memory.
193
287
 
194
288
  ### Uploads and ingest
195
289
 
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
290
+ By default `createDocumentHandlers` reads the whole upload into memory before it calls `ingest`.
291
+ Since 0.9.0 it can write the body to a file as it arrives instead, and ingest it from there: the
292
+ path `prepareUpload` gives, or a temporary file of the spool (`uploadSpool`, below). Either way it
293
+ refuses a body whose `Content-Length` is over `maxUploadBytes` before reading it, and stops reading
294
+ one that grows past it (HTTP 413). Node's own `server.requestTimeout` (300,000 ms by default) ends an upload
199
295
  that takes longer than five minutes to arrive: raise it for users on slow links.
200
296
 
201
- Since 0.8.2 the handlers hold uploads of at most `maxPendingUploadBytes` at once (twice
297
+ Since 0.8.2 the handlers hold uploads of at most `maxPendingUploadBytes` at once in memory (twice
202
298
  `maxUploadBytes` by default), and answer one that would pass it 503 with `Retry-After: 5` before
203
299
  reading its body. The room of an upload is taken before its body arrives, from its `Content-Length`
204
300
  (or `maxUploadBytes` when it declares none), so a client that sends headers and then nothing, or
@@ -209,9 +305,92 @@ body before it passes the request on (nginx does by default, `proxy_request_buff
209
305
  arrive at once and none of this happens; otherwise, limit the connections of each client at the
210
306
  proxy.
211
307
 
308
+ **Spooling uploads to disk.** New in 0.9.0. With `uploadSpool`, the handlers write each body over
309
+ `minBytes` (1 MiB), and each body sent without a `Content-Length`, to a temporary file as it
310
+ arrives, and ingest it from its path. So a body is not held in memory while it waits for its turn:
311
+ the ingest reads it once, at its turn. The file is made new with mode `0o600`,
312
+ and removed once the ingest ends, whatever the end. `maxSpooledUploadBytes` (ten times
313
+ `maxUploadBytes`, 1 GB by default) bounds the files at once, and a full disk (`ENOSPC`) is answered
314
+ 503 with `Retry-After`. `maxPendingUploadBytes` then counts only the bodies kept in memory: in
315
+ memory, a body without a `Content-Length` takes `maxUploadBytes` of room until it is read, so two
316
+ of them filled the default room, and a third was refused 503 while they arrived.
317
+
318
+ ```ts
319
+ const documents = createDocumentHandlers(files, {
320
+ getOwner: userIdOf,
321
+ uploadSpool: { directory: "/var/spool/uploads" }, // this server's own folder, on a disk: not a tmpfs
322
+ });
323
+ ```
324
+
325
+ - **Put the spool on a disk.** A Kubernetes `emptyDir` with `medium: Memory` is a tmpfs: what is
326
+ written there counts against the pod's memory limit, and spooling there saves nothing. So does a
327
+ `/tmp` that is a tmpfs, as in some images, and `os.tmpdir()` is the default directory. Point
328
+ `directory` at a disk-backed `emptyDir` (no `medium`), or at a folder on the shared volume, with
329
+ room for `maxSpooledUploadBytes`.
330
+ - **Give each server process a spool folder of its own.** A server that stops in the middle of an
331
+ upload leaves its file (named `llf-upload-` and a UUID). The name does not say which server
332
+ wrote it. So each server empties its own folder when it starts, and no other. A disk-backed
333
+ `emptyDir` is one pod's already, and goes with the pod: the simplest choice. On the shared
334
+ volume, make a folder for each pod, such as `path.join("/data/spool", os.hostname())` (a pod's
335
+ hostname is its name). A pod that is replaced gets a new name, and leaves its folder behind:
336
+ remove the folders of pods that are no longer running (the names of the running pods tell which;
337
+ a folder without recent files may be an idle server's). Both give one folder a pod or a host,
338
+ which is enough with one server process in each. With several (`node:cluster`, PM2 in cluster
339
+ mode), add a number that each process keeps across its restarts, such as PM2's
340
+ `NODE_APP_INSTANCE`, or one the primary passes to each worker it forks:
341
+ `` path.join(dir, `${os.hostname()}-${process.env.NODE_APP_INSTANCE ?? 0}`) ``. Never empty a
342
+ folder that several servers share: the uploads still arriving or waiting for their turn lose
343
+ their files, and fail with `500` `{ "error": "Upload failed (ENOENT)." }`.
344
+ - **It costs a write and a read.** Each spooled upload is written once, and read once at its turn.
345
+ On a network volume, that is the price of taking it off the heap.
346
+ - **A volume that stops answering.** Each call to the disk (opening the file, each write, closing
347
+ it) is waited for no longer than `uploadIdleTimeoutMs` (30 s). Past it, the upload is answered
348
+ `503` `{ "error": "Upload failed (ETIMEDOUT)." }` with `Retry-After: 5` (a `500` before 0.10.0),
349
+ its room is given back, and the call counts as stuck until it ends
350
+ ([A store that stops answering](#a-store-that-stops-answering)). The file is removed
351
+ at once, or once the volume answers. On a network volume, closing a file can wait for the writes
352
+ the system held back: on a slow one, raise `uploadIdleTimeoutMs`. The same holds for the `path`
353
+ of `prepareUpload`, and for the check of its folders with a ref. The removal of the file, once
354
+ the ingest ends, is waited for no longer either: the upload is answered, its room is given back,
355
+ and the removal goes on alone. The ingest's look at the file before its turn, and its read at its
356
+ turn, are waited for no longer than `ingestTimeoutMs` (2 minutes by default). Past it, both are
357
+ answered `503` `{ "error": "Upload failed (ETIMEDOUT)." }` with `Retry-After: 5`. Before 0.10.0
358
+ the look was a `500`, and the read failed as a file that took too long to read (`422`, code
359
+ `"timeout"`, "split it"), though the trouble was the volume's. Until then, the upload holds its room. With
360
+ `ingestTimeoutMs: 0`, the look still stops at 2 minutes, but the read waits until the client
361
+ leaves.
362
+ - **Saving the upload where you keep it.** When your app keeps each upload anyway, `prepareUpload`
363
+ gives its path, and the body is written there instead, once, and kept by reference
364
+ ([Web app](./web-app.md#save-each-upload-where-you-keep-it-prepareupload)). Such a body takes no
365
+ room of either limit: it is on your volume, and stays.
366
+
367
+ **Ingest from a path.** New in 0.9.0. Code that saves an upload to disk before it ingests it (to
368
+ keep it, or to take it off the heap while it waits) can give `files.ingest` the path in place of the
369
+ bytes ([`IngestFromSource`](../reference/library.md#ingestfromsource)). A relative path is made
370
+ absolute when `ingest` is called. The path is looked at with `lstat` then, which refuses an empty
371
+ file or one over `maxUploadBytes` at once. That look is given up on when the caller's `signal`
372
+ aborts, and fails after `ingestTimeoutMs` when the volume does not answer. The file is read when
373
+ the ingest's turn comes (`maxConcurrentIngests`): once, and at most `maxUploadBytes + 1` bytes.
374
+ The bytes are let go as soon as the extractor returns: they are not held while the text is
375
+ prepared and stored, unless the store keeps a copy (`keepOriginals` with a store that has
376
+ `putOriginal`, and no `original`). So ingests that wait for their turn hold none of their files. Measured
377
+ on Node 22 with 100 ingests of 2 MB logs waiting behind one that held the turn: the process held
378
+ 73 MB (RSS) with paths, against 282 to 286 MB with the bytes given, 200 MB of which were the
379
+ uploads. With all 100 run, two at a time (the default), the peak was 159 to 160 MB with paths,
380
+ against 265 to 277 MB, in the same time. With `createIsolatedExtractors`, a PDF or Office file at a
381
+ path is read by its child process, and the server reads none of it (below), unless the store keeps
382
+ a copy of it (as above): the server then reads it, and sends the bytes to the child.
383
+ The library never writes, moves or deletes the file: remove it once it is ingested, or keep it and
384
+ let `view_pages` read it from there ([Storage](./storage.md#keeping-the-uploaded-files)). Never
385
+ build the path from what a client sends.
386
+
212
387
  An ingest runs in your server's process, a slice at a time. It pauses for other requests about
213
388
  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
389
+ not seconds. Two steps of a text file still run in one block, each as long as the file is large:
390
+ the decoding of a UTF-8 file when its reading starts, and, over a `FileDocumentStore`, the writing
391
+ 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
392
+ 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
393
+ for a 99 MB log over a `MemoryDocumentStore` on Windows with Node 24, and 0.16 s for a 2,000-page
215
394
  PDF, where 0.5.0 held the server for 2.0 s and 4.5 s ([measured](../measurements.md#the-server)).
216
395
  A text file in an older encoding is decoded a megabyte at a time, and a line of megabytes is
217
396
  cleaned in pieces of 256K characters: one line of 30 MB with a control character between its
@@ -238,8 +417,8 @@ await import("@cantoo/pdf-lib");
238
417
  await (await import("unpdf")).getResolvedPDFJS();
239
418
  ```
240
419
 
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
420
+ `getResolvedPDFJS()` rejects when the `unpdf` installed cannot load pdf.js on this Node, and the
421
+ server then does not start: install the version for your Node
243
422
  ([PDFs and other formats](./pdfs.md#formats)).
244
423
 
245
424
  What it does not do is keep its memory apart. The text and its copies, and what pdf.js,
@@ -280,7 +459,9 @@ end after the time limit. Four ways to bound that:
280
459
 
281
460
  **Child processes for the parsers.** With the `extractors` of `createIsolatedExtractors`, each PDF,
282
461
  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
462
+ text sent back; a file ingested from a path is not copied: since 0.9.0 the child reads it from its
463
+ path, within `maxUploadBytes`, and nothing of it waits in the server for a child (unless the store
464
+ 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
465
  before. Text files, HTML included, are read in the server, in slices. What a file can do from there:
285
466
 
286
467
  - run its child out of memory: the child stops, and the file is refused with an `IngestError` of
@@ -322,35 +503,40 @@ itself is the isolation:
322
503
 
323
504
  ```ts
324
505
  // 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";
506
+ import {
507
+ createLargeFiles, DocumentScopeError, DocumentStoreError, FileDocumentStore, IngestError,
508
+ type DocumentScopeErrorCode, type DocumentStoreOperation, type IngestErrorCode, type IngestFromSource, type IngestInput,
509
+ } from "llm-large-files";
326
510
 
327
511
  const files = createLargeFiles({
328
512
  store: new FileDocumentStore(process.env.DOCUMENTS_DIR ?? "/mnt/documents"),
329
513
  keepOriginals: ["pdf"],
330
514
  });
331
515
 
516
+ /** What the server needs to answer an error as createDocumentHandlers does: never a path or a host. */
517
+ export type IngestFailure =
518
+ | { kind: "ingest"; code: IngestErrorCode; message: string; retryAfterMs?: number } // a file refused: its words are for the user
519
+ | { kind: "store"; operation: DocumentStoreOperation; code?: string } // the store failed: a 503 to try again
520
+ | { kind: "scope"; code: DocumentScopeErrorCode }
521
+ | { kind: "status"; status: number; message: string } // an error with a status, such as a 503 of an OCR service
522
+ | { kind: "other" }; // anything else: a 500 "Upload failed.", without its message
523
+
524
+ function failureOf(error: unknown): IngestFailure {
525
+ if (IngestError.is(error)) return { kind: "ingest", code: error.code, message: error.message, ...(error.retryAfterMs !== undefined ? { retryAfterMs: error.retryAfterMs } : {}) };
526
+ if (DocumentStoreError.is(error)) return { kind: "store", operation: error.operation, ...(error.code ? { code: error.code } : {}) };
527
+ if (DocumentScopeError.is(error)) return { kind: "scope", code: error.code };
528
+ const { status } = (error ?? {}) as { status?: unknown };
529
+ if (error instanceof Error && typeof status === "number" && status >= 400 && status <= 599) return { kind: "status", status, message: error.message };
530
+ console.error("The ingest failed", error); // its own words, for your log only
531
+ return { kind: "other" };
532
+ }
533
+
332
534
  process.once("message", async (message) => {
333
535
  try {
334
- process.send!({ meta: await files.ingest(message as IngestInput) });
536
+ // The path of the file (`source`): this process reads it itself. Bytes only for a body a framework read.
537
+ process.send!({ meta: await files.ingest(message as IngestInput | IngestFromSource) });
335
538
  } 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
- });
539
+ process.send!({ failed: failureOf(error) });
354
540
  }
355
541
  });
356
542
  ```
@@ -361,21 +547,33 @@ takes any `LargeFiles`, so the rest stays as it is:
361
547
  ```ts
362
548
  // documents.ts: the upload routes. Each ingest runs in a process of its own, one at a time on this server.
363
549
  import { fork } from "node:child_process";
364
- import type { DocumentMeta, IngestInput } from "llm-large-files";
550
+ import { DocumentScopeError, DocumentStoreError, IngestError, type DocumentMeta, type IngestFromSource, type IngestInput } from "llm-large-files";
365
551
  import { createDocumentHandlers } from "llm-large-files/node";
366
552
  import { files } from "./large-files.js";
367
553
  import { userIdOf } from "./auth.js"; // your sign-in
554
+ import type { IngestFailure } from "./ingest-process.js";
368
555
 
369
556
  const INGESTS_AT_ONCE = 1;
370
557
  let running = 0;
371
558
 
372
- type IngestReply = { meta?: DocumentMeta; failed?: { message: string; code?: string; syscall?: string; status?: number } };
559
+ type IngestReply = { meta?: DocumentMeta; failed?: IngestFailure };
373
560
 
374
- function ingestInProcess(input: IngestInput): Promise<DocumentMeta> {
561
+ /** The process's failure as the error createDocumentHandlers answers: an IngestError is the only 422. */
562
+ function errorOf(failed: IngestFailure): Error {
563
+ switch (failed.kind) {
564
+ case "ingest": return new IngestError(failed.code, failed.message, failed.retryAfterMs !== undefined ? { retryAfterMs: failed.retryAfterMs } : {});
565
+ case "store": return new DocumentStoreError(new Error("The store failed in the ingest process."), { operation: failed.operation, ...(failed.code ? { code: failed.code } : {}) });
566
+ case "scope": return new DocumentScopeError(failed.code);
567
+ case "status": return Object.assign(new Error(failed.message), { status: failed.status });
568
+ default: return new Error("The ingest process failed."); // answered 500 "Upload failed."
569
+ }
570
+ }
571
+
572
+ function ingestInProcess(input: IngestInput | IngestFromSource): Promise<DocumentMeta> {
375
573
  if (input.signal?.aborted) return Promise.reject(input.signal.reason);
376
574
  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 }));
575
+ // Answered 503, with Retry-After.
576
+ return Promise.reject(new IngestError("busy", "The server is reading other files. Try again in a minute.", { retryAfterMs: 60_000 }));
379
577
  }
380
578
  running++;
381
579
  return new Promise<DocumentMeta>((resolve, reject) => {
@@ -384,7 +582,7 @@ function ingestInProcess(input: IngestInput): Promise<DocumentMeta> {
384
582
  // flag (the table above has the flags of other versions). This flag wins over a
385
583
  // --max-old-space-size in NODE_OPTIONS, which the child inherits.
386
584
  execArgv: ["--max-old-space-size=320"],
387
- serialization: "advanced", // the bytes go as they are, not as JSON
585
+ serialization: "advanced", // bytes, when there are any, go as they are, not as JSON
388
586
  });
389
587
  let reply: IngestReply | undefined;
390
588
  let timedOut = false;
@@ -408,13 +606,10 @@ function ingestInProcess(input: IngestInput): Promise<DocumentMeta> {
408
606
  running--;
409
607
  if (reply?.meta) resolve(reply.meta);
410
608
  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.`));
609
+ else if (reply?.failed) reject(errorOf(reply.failed));
610
+ else if (timedOut) reject(new IngestError("timeout", `${input.name} took too long to read.`));
416
611
  // 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.`));
612
+ else reject(new IngestError("out_of_memory", `${input.name} could not be read on this server.`));
418
613
  };
419
614
  child.once("message", (message) => {
420
615
  reply = message as IngestReply;
@@ -425,27 +620,40 @@ function ingestInProcess(input: IngestInput): Promise<DocumentMeta> {
425
620
  child.kill();
426
621
  settle();
427
622
  });
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.
623
+ // With the spool, the message holds the path of the file, not its bytes: the process reads it.
624
+ // The handler removes the file once this promise settles, after the process is gone. A signal
625
+ // cannot be sent: the process has its own ingestTimeoutMs, and is killed when this one aborts.
430
626
  const { signal: _signal, ...message } = input;
431
627
  child.send(message);
432
628
  });
433
629
  }
434
630
 
435
- export const documents = createDocumentHandlers({ ...files, ingest: ingestInProcess }, { getOwner: userIdOf });
631
+ export const documents = createDocumentHandlers({ ...files, ingest: ingestInProcess }, {
632
+ getOwner: userIdOf,
633
+ // Every body to a file of the spool, so that only its path goes to the process.
634
+ uploadSpool: { directory: "/var/spool/uploads", minBytes: 0 },
635
+ });
436
636
  ```
437
637
 
438
638
  Checked on Node 24: with `NODE_OPTIONS=--max-old-space-size=1024` on the server and a heap of 48 MB
439
639
  for the child, a 2,000-page PDF ran the child out of memory; the upload was answered "book.pdf
440
640
  could not be read on this server.", and the next upload was ingested.
441
641
 
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.
642
+ Since 0.9.0 the server sends the process the path of the upload, not its bytes: with
643
+ `uploadSpool` and `minBytes: 0`, every body the handler reads is written to a file of the spool, and
644
+ `ingest` gets `source: { path }`. The process reads the file itself, so the upload is neither held
645
+ in the server while the process starts nor copied over the IPC channel. The process runs as the
646
+ server's user, so it can read the spool's `0o600` files. A body a framework already read
647
+ (`express.raw()`) still comes as bytes, and is copied. The handler removes the file once the
648
+ promise of `ingestInProcess` settles, which is after the process exited.
649
+
650
+ Since 0.9.0 `createDocumentHandlers` answers `422` only an `IngestError`, and any other error
651
+ without a status `500` "Upload failed.", without its message (S12). So the server rebuilds the
652
+ error the process caught by its kind: an `IngestError` with its code and message, a
653
+ `DocumentStoreError` (`503`, `Retry-After: 5`) with its operation and code, never the store's own
654
+ words. The process logs the errors it cannot pass on. Until 0.9.0 this recipe rebuilt a plain
655
+ `Error`, which the handler answered `422` with its message: a store's own message, which may name a
656
+ database host.
449
657
 
450
658
  A process stopped by its limit or its timeout may leave the files of a document that was never
451
659
  finished. `FileDocumentStore` removes them at the first sweep after they are an hour old. One
@@ -466,6 +674,15 @@ declares, not what they take: a crafted file that a process of its own ingested
466
674
  chat server out of memory at its first look, or take memory outside the heap. And what
467
675
  `@cantoo/pdf-lib` keeps after each look adds up from file to file: files of 9 KB ran a heap of 1 GB
468
676
  out of memory at the seventh look ([Security](../security.md#reading-pdfs-for-pages-and-pictures)).
677
+ Since 0.9.0 one look runs at a time in a library (`maxConcurrentPageLooks`, 1 by default), over
678
+ all its questions: the others wait, before their PDF is loaded, for up to `pageLookWaitMs` (30 s),
679
+ and then the model is told the server is busy. So the heap holds one parsed PDF at a time, not one
680
+ for each question that looks. Raise it only with the heap to match: six looks at once took 352 MB
681
+ more than one, and did not finish sooner. A look holds its turn while it reads the PDF from the
682
+ store, for at most `ingestTimeoutMs` (2 minutes by default). Past it, the turn goes back and the
683
+ model is told the file could not be read in time. Since 0.10.0 the read of the original is a store
684
+ call within `storeTimeoutMs` (30 s by default), which fails it first: the read itself goes on, and
685
+ counts as stuck until it ends ([A store that stops answering](#a-store-that-stops-answering)).
469
686
  For the documents of users you do not trust, do not offer `view_pages` (`viewPages: false`), or keep
470
687
  no PDF originals. To offer it anyway, run each of their questions, the whole tool loop, in a process
471
688
  you fork, with its own heap and memory limits. What the model is told when pages cannot be shown,
@@ -481,17 +698,34 @@ documents it removed, or 0 for a store without one.
481
698
 
482
699
  `FileDocumentStore.sweep` also removes the files of uploads that were never finished, once they are
483
700
  `orphanAgeMs` old (one hour by default): younger ones may be an upload in progress on another
484
- server ([Storage](./storage.md#filedocumentstore)).
701
+ server ([Storage](./storage.md#filedocumentstore)). It reads `sweepConcurrency` files at once, 16 by
702
+ default. With `scopes`, `files.sweep()` walks the folders of every scope (exactly `depth` levels,
703
+ following no link), and `files.sweep({ scope })` sweeps the folder of one chat.
485
704
 
486
705
  **Where to run it.** On one server, or from a scheduled job. Running it on every server is safe
487
706
  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:
707
+ each server then lists the whole directory (with `scopes`, every chat's folder) and reads every
708
+ metadata file. Run it from one server, or take a lease first (a document in MongoDB with an expiry
709
+ that one server holds at a time). A job of its own runs as the user of the servers, or in their
710
+ group with the modes above.
711
+
712
+ **On a network volume**, run it from one pod only, a Kubernetes CronJob for example, not from the
713
+ pods that answer users. `sweepConcurrency` file calls run at once (16 by default), and on a volume
714
+ that hangs each holds a thread of the pool ([A store that stops answering](#a-store-that-stops-answering)):
715
+ set it to at most a quarter of the pool, 8 with `UV_THREADPOOL_SIZE=32`. A sweep has no time limit
716
+ by default, since a sweep of a large volume may take long, and it never counts as a stuck call:
717
+ `sweepTimeoutMs` (new in 0.10.0) gives up on one that takes longer, with a `DocumentStoreError` of
718
+ code `"ETIMEDOUT"`, while the sweep itself goes on. While the process has `maxStuckStoreCalls`
719
+ calls stuck, a sweep is refused at once, as other store calls are. Give it the options of the
720
+ servers' store:
489
721
 
490
722
  ```ts
491
723
  // sweep.ts: run every hour by a scheduled job (cron, a Kubernetes CronJob, Cloud Scheduler).
492
724
  import { createLargeFiles, FileDocumentStore } from "llm-large-files";
493
725
 
494
- const files = createLargeFiles({ store: new FileDocumentStore(process.env.DOCUMENTS_DIR ?? "/mnt/documents") });
726
+ // The options of the servers' store: here, a folder per user and chat. Run with UV_THREADPOOL_SIZE=32.
727
+ const store = new FileDocumentStore(process.env.DOCUMENTS_DIR ?? "/mnt/documents", { scopes: { depth: 2 }, sweepConcurrency: 8 });
728
+ const files = createLargeFiles({ store, sweepTimeoutMs: 30 * 60 * 1000 });
495
729
  const removed = await files.sweep();
496
730
  console.log(`Removed ${removed} expired documents.`);
497
731
  ```
@@ -599,12 +833,66 @@ export function stopOnSigterm(server: Server, graceMs = 25_000): void {
599
833
  ```
600
834
 
601
835
  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
836
+ question up by. With
837
+ [`createIsolatedExtractors`](../reference/node.md#createisolatedextractorsoptions), call
604
838
  `isolated.close()` when the grace period ends, next to `stopping.abort`: it kills its child
605
839
  processes, and refuses the files still waiting or being read as `"busy"` (503 "The server is
606
840
  shutting down. Try again in a moment.").
607
841
 
842
+ An upload cut by the restart, or by a server killed past its grace period or out of memory, can
843
+ leave files of three kinds:
844
+
845
+ - **The store's.** The files of `FileDocumentStore` for a document that was never finished. The
846
+ sweep removes them once they are an hour old.
847
+ - **The spool's.** A server empties its own spool folder when it starts. A container restarted in
848
+ its pod (after an OOM kill, say) has the same hostname and folder, and empties it. A pod that is
849
+ replaced gets a new hostname, so its folder on the shared volume stays until you remove it. An
850
+ `emptyDir` goes with its pod ([Uploads and ingest](#uploads-and-ingest)).
851
+ - **The partial file at the `path` of `prepareUpload`.** Nothing removes it: the sweep removes only
852
+ the store's files, and no document refers to it. A record of your own that `prepareUpload` wrote
853
+ for it stays too. Remove such files with a job of your own, now and then: each file of `uploads/`
854
+ older than any upload takes, whose document is not stored (`files.getMeta(id, { owner, scope })`
855
+ gives `undefined`). An upload takes up to `server.requestTimeout` (5 minutes) for its body, then
856
+ its wait for a turn, `ingestTimeoutMs` (2 minutes) and your `onUploaded`: an hour leaves room.
857
+
858
+ ```ts
859
+ // remove-cut-uploads.ts: run now and then, for each chat (a CronJob, or a timer on one server).
860
+ import { readdir, rm, stat } from "node:fs/promises";
861
+ import path from "node:path";
862
+ import type { LargeFiles } from "llm-large-files";
863
+
864
+ /** Longer than any upload takes: its body, its wait for a turn, its ingest and onUploaded. */
865
+ const CUT_AFTER_MS = 60 * 60_000;
866
+
867
+ /**
868
+ * Removes the files of <user>/<chat>/uploads that no stored document has: those of uploads cut by a
869
+ * killed server, and those of documents deleted or expired.
870
+ */
871
+ export async function removeCutUploads(files: LargeFiles, volume: string, user: string, chat: string): Promise<void> {
872
+ const folder = path.join(volume, user, chat, "uploads");
873
+ // A chat without the folder (one made before 0.9.0) has nothing to remove.
874
+ for (const entry of await readdir(folder, { withFileTypes: true }).catch(() => [])) {
875
+ if (!entry.isFile()) continue;
876
+ const file = path.join(folder, entry.name);
877
+ // Still arriving, or waiting for its ingest; or removed meanwhile (by onRemoved).
878
+ const info = await stat(file).catch(() => undefined);
879
+ if (!info || Date.now() - info.mtimeMs < CUT_AFTER_MS) continue;
880
+ // Its document is stored: the file is the document's, and yours.
881
+ if (await files.getMeta(entry.name, { owner: user, scope: [user, chat] })) continue;
882
+ await rm(file, { force: true });
883
+ }
884
+ }
885
+ ```
886
+
887
+ Each file is named by its document's ID, as in the examples of
888
+ [`prepareUpload`](../reference/node.md#saving-the-body-prepareupload). The folder holds only those
889
+ files: anything else in it an hour old, with no document of its name, goes too. A file is kept only
890
+ while its document is stored, so the file of a document that was deleted or has expired goes as
891
+ well. That fits an app that keeps each file as long as its document, as the
892
+ [upgrade guide's example](../upgrading-0.9.md) does (`ttlMs: Infinity`, and `onRemoved` removes the
893
+ file). An app that keeps its files longer should look up its own record of the upload (the one
894
+ `prepareUpload` or `onUploaded` wrote) instead of `getMeta`.
895
+
608
896
  After a restart the cache is empty: the first tool calls read their documents from the store again,
609
897
  and a thinking model's first whole-file read in the new process may spend one request finding the
610
898
  output limit it needs.
@@ -622,6 +910,13 @@ same conversations.
622
910
  8% more in JSON. One ingested before 0.4.0 has no index: it is built the first time the document
623
911
  is used, and saved for the other servers. Upgrading from 0.3.x has notes of its own in
624
912
  [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).
913
+ - **Documents of 0.9.0.** In the flat layout, 0.9.0 keeps the names and fields of 0.8, so servers of
914
+ 0.8 read the documents 0.9.0 writes under the IDs the library makes, and ignore the new fields.
915
+ They do not read a document under an application's ID, nor the folders of a store with `scopes`:
916
+ they answer such documents as missing, and the user is asked for the file again. Upgrade every
917
+ server at once, or keep each chat on servers of one version until the rollout ends. Files that
918
+ 0.9.0 writes are `0600`: servers of 0.8 that run as another user cannot read them either.
919
+ [Upgrading to 0.9](../upgrading-0.9.md#several-servers-and-rolling-deploys) has the steps.
625
920
  - **A document keeps what the version that ingested it extracted**: its text, outline and log
626
921
  profile. A better extractor applies to files uploaded after the upgrade. A text file in an older
627
922
  encoding that 0.5.0 stored holds U+FFFD where 0.6.0 reads its letters, and text that 0.5.0
@@ -629,8 +924,10 @@ same conversations.
629
924
  again to get the new reading. A document that 0.5.0 stored with the owner `""` stays readable
630
925
  with that owner until it expires.
631
926
  - **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`
927
+ they appeared in 0.5.0, but for `version`, which 0.9.0 adds to the rounds it makes. Both versions
928
+ read the ones the other stored: a version before 0.9.0 ignores `version`, and 0.9.0 refuses a
929
+ round whose `version` is above 1, made by a later version, with a `TypeError`. 0.6.0 sends the
930
+ rounds of an earlier question without their `tool_turns_left`
634
931
  ([Conversations](./conversations.md#what-toolturns-holds)).
635
932
  - **Provider caches.** The tool guide in the system instruction, the descriptions of
636
933
  `analyze_whole_document` and `search_document`, and the frame lines of a file sent whole changed
@@ -647,19 +944,16 @@ same conversations.
647
944
 
648
945
  ## Node.js, ESM and `require()`
649
946
 
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)).
947
+ - **Node.js 22.12 or newer** (`engines` in `package.json`; 20.19 until 0.9.0). The tests run on
948
+ Node 22, 24 and 26, and again with the newest unpdf 1.x on Node 22 and 24, and the newest 2.x on
949
+ Node 24 and 26. Pick the `unpdf` for your Node ([PDFs and other formats](./pdfs.md#formats)).
653
950
  - **The package is ESM only.** It has `"type": "module"` and an `exports` map with `types` and
654
951
  `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() { ... }`.
952
+ - **A CommonJS application can `require()` it**: Node 22.12 and newer load an ES module with
953
+ `require()`, and the library has no top-level `await`.
660
954
 
661
955
  ```js
662
- // CommonJS, Node 20.19+ or 22.12+
956
+ // CommonJS
663
957
  const { createLargeFiles, FileDocumentStore } = require("llm-large-files");
664
958
  const { askGemini, vertexAi } = require("llm-large-files/gemini");
665
959
  const { createDocumentHandlers } = require("llm-large-files/node");
@@ -703,14 +997,14 @@ optional peer dependencies. Add the ones you need to the `dependencies` of your
703
997
 
704
998
  | Package | Version | Needed for | Without it |
705
999
  |---|---|---|---|
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.` |
1000
+ | `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
1001
  | `jszip` | `^3.10.0` | DOCX, PPTX and XLSX | The upload is refused: `Reading DOCX, PPTX and XLSX files needs the optional dependency "jszip".` |
708
1002
  | `@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
1003
 
710
1004
  The last one fails quietly at ingest, so an image without it ingests PDFs differently from your
711
1005
  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
1006
+ `npm install unpdf` installs unpdf 2, which asks for Node 24: for an image on Node 22, name the
1007
+ version in your `dependencies`. Check at startup that the image has what your application
714
1008
  uses:
715
1009
 
716
1010
  ```ts