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
@@ -12,13 +12,16 @@ parts under the document's ID:
12
12
 
13
13
  | Part | What it is | Written |
14
14
  |---|---|---|
15
- | Metadata | `DocumentMeta`: owner, file name, format, sizes, lines, outline, log profile, `createdAt`, `expiresAt`. | Always, last. |
15
+ | Metadata | `DocumentMeta`: owner, scope, file name, format, sizes, the SHA-256 of the upload (0.9.0), lines, outline, log profile, `createdAt`, `expiresAt`. | Always, last. |
16
16
  | Text | The extracted text, normalized, as one string. | Always. |
17
17
  | Line index | Where each line starts, in bytes and in characters: about 8 bytes a line. With it, a document read by range is opened without first reading all of its text. | When the store has `putIndex`. |
18
- | Original | The uploaded file, byte for byte. | When `keepOriginals` lists the format and the store has `putOriginal`. |
18
+ | Original | The uploaded file, byte for byte. | When `keepOriginals` lists the format and the store has `putOriginal`, unless the ingest gives `original`: then your application keeps the file, and the metadata says where ([Keeping the uploaded files](#keeping-the-uploaded-files)). |
19
19
 
20
20
  The library makes the ID: `doc_` and 32 hexadecimal digits of a random UUID. It is new at every
21
- ingest and never reused. `DOCUMENT_ID_PATTERN` (`/^doc_[a-f0-9]{32}$/`) matches it, and
21
+ ingest and never reused. `DOCUMENT_ID_PATTERN` (`/^doc_[a-f0-9]{32}$/`) matches it. Since 0.9.0 the
22
+ application may give the ID instead ([Application IDs](#application-ids)), of the shape
23
+ `APP_DOCUMENT_ID_PATTERN` (`/^(?!(?:con|prn|aux|nul|com[0-9]|lpt[0-9])$)[a-z0-9][a-z0-9_-]{0,63}$/`:
24
+ no name Windows keeps for a device), which the made IDs fit too.
22
25
  `isDocumentId(value)` tests a value against it: use it on IDs that arrive in a request before they
23
26
  reach your database. The library tests every ID itself before it asks the store. An ID that does
24
27
  not match counts as missing, so a store only ever receives IDs that match.
@@ -55,14 +58,14 @@ export const scratch = createLargeFiles({ store: new MemoryDocumentStore() });
55
58
  - It copies the metadata it is given and the metadata it hands out, as a store that writes it
56
59
  somewhere does: changing the `meta` that `ingest` or `getMeta` returned (deleting its `owner`
57
60
  before you send it to a browser, say) changes nothing stored. Each call returns a new object.
58
- `getOriginal` still returns the kept bytes themselves: treat them as read-only.
61
+ `getOriginal` returns a copy of the kept bytes too, since 0.9.0.
59
62
  - `now` is its clock, `() => new Date()` by default. In a test, give the store and
60
63
  `createLargeFiles({ now })` the same clock: see [Testing](./testing.md).
61
64
 
62
65
  ### `FileDocumentStore`
63
66
 
64
- `new FileDocumentStore(directory, { now, orphanAgeMs })` keeps each document as files in one
65
- directory, which it creates at the first write. There are no subdirectories:
67
+ `new FileDocumentStore(directory, options)` keeps each document as files on a volume. Without
68
+ `scopes`, they are all in `directory`, which it creates at the first write:
66
69
 
67
70
  | File | Holds |
68
71
  |---|---|
@@ -72,35 +75,73 @@ directory, which it creates at the first write. There are no subdirectories:
72
75
  | `<id>.bin` | The uploaded file, with `keepOriginals`. |
73
76
  | `<id>.<ext>.<8 hex digits>.tmp` | A file being written. It is renamed to its own name once complete. |
74
77
 
78
+ With `scopes` (new in 0.9.0), the files of each scope are in a folder of their own:
79
+ `<directory>/<userId>/<chatId>/.llm-large-files/<id>.json`. See
80
+ [Files in a folder per user or per chat](#files-in-a-folder-per-user-or-per-chat).
81
+
82
+ | Option | Default | What it does |
83
+ |---|---|---|
84
+ | `now` | `() => new Date()` | The store's clock: what has expired, and the default time of `sweep`. |
85
+ | `orphanAgeMs` | One hour | How old a file of no document must be before `sweep` removes it. |
86
+ | `scopes` | None | `{ depth, folder, createScopeFolders, unscoped }`: a folder per scope. New in 0.9.0. |
87
+ | `fileMode` | `0o600` | The mode of the files it writes, minus the umask. New in 0.9.0. |
88
+ | `directoryMode` | `0o700` | The mode of the folders it makes, minus the umask. New in 0.9.0. |
89
+ | `sweepConcurrency` | 16 | How many files `sweep` reads at once. New in 0.9.0. |
90
+
75
91
  - Every file is written under a temporary name and then renamed, so no reader, on this server or
76
- another one, sees half a file. A rename that meets `EPERM`, `EACCES` or `EBUSY` (on Windows,
77
- another process has the file open for a moment) is tried again for up to about three seconds.
92
+ another one, sees half a file. A rename or a removal that meets `EPERM`, `EACCES` or `EBUSY` (on
93
+ Windows, another process has the file open for a moment) is tried again for about 2.6 seconds.
78
94
  - `put` writes the text first and the metadata last. `delete` removes the metadata first, and
79
- nothing else when that fails. A document never appears without its text, and is never listed once
80
- its text is gone.
81
- - Only IDs that match `DOCUMENT_ID_PATTERN` reach the file system. A read or a `delete` with another
82
- ID finds nothing, and `put`, `putIndex` and `putOriginal` throw "Invalid document ID."
95
+ nothing else when that fails: it throws, and the document stays whole. Once the metadata is
96
+ gone, the document is gone: `delete` returns true, and a text, index or original it could not
97
+ remove is left for `sweep` (new in 0.9.0: it threw). A document never appears without its text,
98
+ and is never listed once its text is gone.
99
+ - File names are document IDs: the library's (`doc_` and 32 hex digits), or, since 0.9.0, an
100
+ application's ([Application IDs](#application-ids)). `APP_DOCUMENT_ID_PATTERN` leaves out the
101
+ names Windows keeps for devices (`con`, `nul`, `com1` and the like), since `con.json` is not a
102
+ file there: `ingest` refuses them with a `TypeError`. A read or a `delete` with an ID that is not
103
+ valid finds nothing, and `put`, `putIndex` and `putOriginal` throw "Invalid document ID." The
104
+ library's IDs keep the names they had, so servers of 0.8 still read them.
105
+ - The names `<id>.json`, `<id>.txt`, `<id>.idx` and `<id>.bin`, and their temporary files, belong
106
+ to the store for every ID it is given. Without `scopes`, `directory` is a folder where your files
107
+ may sit too: an ingest under the ID `report` writes over your `report.txt`, and a `delete` or
108
+ `ifExists: "replace"` removes it. Keep your own files in a subfolder, or under other names.
109
+ - A read does not follow a link at a file name (new in 0.9.0): a document file that is a link counts
110
+ as missing. Windows cannot refuse such a link, so there it is followed.
111
+ - Files are written `0600` and folders made `0700` (new in 0.9.0: before, `0666` and `0777`, minus
112
+ the umask, which gave `0664` and `0775` under the usual `0002`). Only the user the server runs as
113
+ reads them. Servers or a backup job that run as other users of one group (a Kubernetes `fsGroup`)
114
+ need `fileMode: 0o640` and `directoryMode: 0o750`. Files written before keep their modes.
83
115
  - A missing file means a missing document. Any other failure of a read (a volume that does not
84
116
  answer, too many open files) is thrown, and the library passes it on as a `DocumentStoreError`.
85
117
  There are two exceptions: an index file that cannot be read is built again from the text, and
86
- `sweep` returns 0 when it cannot list the directory. A failed write or delete is thrown as it
87
- came ([Errors](#errors)). Metadata that cannot be parsed counts as absent.
88
- - `getMeta` removes a document that has expired, by the store's own clock (`now`).
118
+ `sweep` counts a folder it cannot list as empty. A failed write or delete is thrown as it came,
119
+ and the library wraps it ([Errors](#errors)). Metadata that cannot be parsed counts as absent.
120
+ - `getMeta` removes a document that has expired, by the store's own clock (`now`), and returns
121
+ undefined. Since 0.9.0 it does so also when the removal fails: the next `sweep` tries again.
89
122
  - `readTextRange` reads only the bytes asked for, so a tool call never loads a large file whole.
90
123
  The whole text is read only when the plan sends it in the prompt.
91
- - `sweep` removes expired documents and returns how many. It also removes files that belong to no
92
- document (an upload that failed, a server that stopped while writing) and temporary files, once
124
+ - `sweep` removes expired documents and returns how many: those whose metadata it removed itself,
125
+ so two sweeps at once count each document once (on Windows, two removals of one file at the
126
+ same moment can both succeed, and a document can be counted twice). It also removes files that
127
+ belong to no document (an upload that failed, a server that stopped while writing) and temporary files, once
93
128
  they are `orphanAgeMs` old, one hour by default: a younger one may be an upload in progress on
94
- another server. A document whose metadata could not be read at all is left alone, whatever its
95
- age. One that cannot be removed is left for the next sweep, and does not stop this one.
96
- - The files are plain. The metadata names the owner, the file name, the headings and the log
97
- message templates. A delete removes the files without overwriting them. If that matters, encrypt
98
- the volume: see [Security](../security.md).
129
+ another server. In a folder that may hold files of yours too (`directory` without `scopes`), it
130
+ removes such a file only when its name is an ID the library makes, or a temporary file:
131
+ `notes.txt` may be yours, not the text of a document `notes`. A document whose metadata could not
132
+ be read at all is left alone, whatever its age. One that cannot be removed is left for the next
133
+ sweep, and does not stop this one.
134
+ - `sweep` reads up to `sweepConcurrency` files at once (new in 0.9.0: one after another). A sweep
135
+ of 5,000 documents in one folder on a local SSD took about 2.5 s one file at a time, and about
136
+ 1.1 s 16 at a time.
137
+ - The files are plain. The metadata names the owner, the scope, the file name, the headings and the
138
+ log message templates. A delete removes the files without overwriting them. If that matters,
139
+ encrypt the volume: see [Security](../security.md).
99
140
 
100
141
  Several servers can share the directory on a network volume. What that needs, from where to run the
101
142
  sweep to servers of two versions during an upgrade, is in [Deployment](./deployment.md).
102
143
 
103
- ## Owners
144
+ ## Owners and scopes
104
145
 
105
146
  ### How ownership works
106
147
 
@@ -119,15 +160,15 @@ await files.delete(meta.id, { owner: "user-7" }); // false: nothing is remove
119
160
  await files.delete(meta.id, { owner: "user-42" }); // true
120
161
  ```
121
162
 
122
- | Call | Takes the owner as | A document of another owner |
163
+ | Call | Takes the owner (and the scope) as | A document of another owner or scope |
123
164
  |---|---|---|
124
- | `files.ingest(input)` | `input.owner` | |
125
- | `files.getMeta(id, access)` | `access.owner` | `undefined` |
126
- | `files.getOriginal(id, access)` | `access.owner` | `undefined` |
127
- | `files.delete(id, access)` | `access.owner` | `false`, and nothing is removed |
128
- | `files.prepare(ids, base, options)` | `options.owner` | Listed in `missing`, and never read |
129
- | `files.tools(documents, options)` | the `owner` of each `DocumentMeta` in `documents` (and in `viewPages`) | Each call that reads it answers `doc_… is no longer available on the server. Ask the user to attach the file again.` |
130
- | `askWithFiles(options)`, `askGemini(options)` | `options.owner` | `DocumentsNotFoundError`, before any model request |
165
+ | `files.ingest(input)` | `input.owner`, `input.scope` | |
166
+ | `files.getMeta(id, access)` | `access.owner`, `access.scope` | `undefined` |
167
+ | `files.getOriginal(id, access)` | `access.owner`, `access.scope` | `undefined` |
168
+ | `files.delete(id, access)` | `access.owner`, `access.scope` | `false`, and nothing is removed |
169
+ | `files.prepare(ids, base, options)` | `options.owner`, `options.scope` | Listed in `missing`, and never read |
170
+ | `files.tools(documents, options)` | `options.access` (new in 0.9.0); without it, the `owner` and `scope` of each `DocumentMeta` in `documents` (and in `viewPages`) | Each call that reads it answers `doc_… is no longer available on the server. Ask the user to attach the file again.` |
171
+ | `askWithFiles(options)`, `askStream(options)`, `askGemini(options)` | `options.owner`, `options.scope` | `DocumentsNotFoundError`, before any model request |
131
172
  | `createDocumentHandlers(files, options)` | `options.getOwner(request)` | 404 "This file is no longer available." on GET; `{ "deleted": false }` on DELETE |
132
173
 
133
174
  - An owner is a string that is not empty or only spaces. `ingest` throws a `TypeError` for `""`,
@@ -138,41 +179,163 @@ await files.delete(meta.id, { owner: "user-42" }); // true
138
179
  It throws the same for an owner from JavaScript that is neither a string nor a finite number,
139
180
  such as the user object in place of its ID. A number is accepted, as before. Reads with
140
181
  `owner: ""` work as before, so documents that 0.5.0 stored with that owner stay readable until
141
- they expire.
182
+ they expire (not under `requireOwner`, which refuses `""` on every call).
142
183
  - In `createDocumentHandlers`, a `getOwner` that returns such an owner is the server's mistake: the
143
184
  upload is answered 500 `{ "error": "Upload failed (empty owner)." }` for `""`, spaces only or
144
185
  `null`, and `{ "error": "Upload failed (owner is not a string)." }` for an object, a boolean,
145
186
  `NaN` or an array, before its body is read. Nothing is logged. Where every upload needs a
146
187
  signed-in user, throw an error with `status: 401` from `getOwner`; return `undefined` only where
147
188
  anonymous uploads are meant (`user?.id || undefined`); and return the user's ID, not the user.
189
+ Under `requireOwner`, `undefined` and `null` are a request that is not signed in: `401`
190
+ `{ "error": "Sign in first." }` on every route, and `""` or spaces only a `500` "(empty owner)" on
191
+ every route (new in 0.9.0).
148
192
  - A document of another owner looks exactly like one that does not exist, so a caller cannot learn
149
- that an ID is in use.
193
+ that an ID is in use. There is one exception: `ingest` with an
194
+ [application's ID](#application-ids) answers 409 when the ID is taken, whoever has it.
150
195
  - The comparison is exact (`===`): `"alice"` does not reach a document of `"Alice"` or of
151
196
  `"alice/chat-1"`. There is no hierarchy and no wildcard.
152
197
  - A document ingested without an owner can be used by anyone who has its ID, whether they pass an
153
- owner or not. With signed-in users, always pass one. In `createDocumentHandlers`, a `getOwner` that
198
+ owner or not. With signed-in users, always pass one, and turn on
199
+ [`requireOwner`](#requiring-an-owner-and-a-scope). In `createDocumentHandlers`, a `getOwner` that
154
200
  returns undefined makes an anonymous upload. To refuse a request without a user, throw from it with
155
201
  a status ([Web app](./web-app.md)).
202
+ - An owner of `null` from your store (a MongoDB driver writes a field that was left out as `null`)
203
+ counts as no owner, new in 0.9.0. Before, `getMeta` read such a document as missing for every
204
+ owner, and the tools as open to all.
156
205
  - The owner cannot be changed after ingest. Use a stable, opaque ID, not an email address that may
157
206
  change.
158
- - `files.tools(documents)` takes no owner option: it compares the owner stored with each document
159
- with the `owner` of the metadata it is given, and answers a mismatch as a document that is gone
160
- (`doc_… is no longer available on the server. …`). In a loop of your own, pass it only metadata
161
- from `prepare(ids, base, { owner })` or `getMeta(id, { owner })`
162
- ([Your own adapter and loop](./own-adapter-and-loop.md)). `askWithFiles` does this for you.
207
+ - `files.tools(documents, { access })` asks the store for each document with the owner and scope of
208
+ `access`, and checks the ones the store holds against them, as `getMeta` does. `askWithFiles`
209
+ passes it. Without `access`, as before 0.9.0, `tools` compares the owner and scope stored with
210
+ each document with those of the metadata it is given, and answers a mismatch as a document that
211
+ is gone. In a loop of your own, pass `access`
212
+ ([Your own adapter and loop](./own-adapter-and-loop.md)).
213
+
214
+ ### Scopes
215
+
216
+ A scope says where a document belongs, from the widest part to the narrowest: `[userId, chatId]`.
217
+ It is new in 0.9.0. Pass it at ingest and on every later call, as the owner:
218
+
219
+ ```ts
220
+ // `files` and `bytes` as above.
221
+ const scope = ["user-42", "chat-7"];
222
+ const notes = await files.ingest({ name: "notes.txt", bytes, owner: "user-42", scope });
223
+
224
+ await files.getMeta(notes.id, { owner: "user-42", scope }); // the metadata
225
+ await files.getMeta(notes.id, { owner: "user-42", scope: ["user-42", "chat-8"] }); // undefined
226
+ await files.getMeta(notes.id, { owner: "user-42" }); // undefined
227
+ ```
228
+
229
+ - The library keeps the scope in `meta.scope`, a copy, and passes it to every store call in the
230
+ [context](#writing-a-store-of-your-own). It never reaches the model or a summary. An event holds
231
+ it only with `eventResults: true`, in the full plan of `run.finish` and `run.error`
232
+ ([events](../reference/events.md#documents-eventresults-and-eventresult)).
233
+ - A document with a scope serves only a caller of the same scope, segment by segment: another
234
+ scope, a longer or a shorter one, or none, finds it missing. A document without a scope serves a
235
+ caller of any scope, unless the library has `requireScope`.
236
+ - A store may keep the documents of each scope apart: `MemoryDocumentStore` does, and
237
+ `FileDocumentStore` with [`scopes`](#files-in-a-folder-per-user-or-per-chat), so one ID in two
238
+ scopes is two documents. A store that ignores the context, as every store written for 0.8 does,
239
+ still keeps scopes apart for the library, through `meta.scope`: a caller of scope B never reads a
240
+ document of scope A.
241
+ - What the library keeps in memory is kept by scope too: a cached copy of a document of one scope
242
+ is never served to a caller of another, even when both documents have the same ID. Nor to another
243
+ owner: the copy is checked against the owner of the document the store holds now.
244
+ - A scope has 1 to 8 segments of 1 to 256 characters, with no control character, no `/` or `\`, and
245
+ none of them `.` or `..`. Another is a `DocumentScopeError` of code `"scope_invalid"`, whose
246
+ message never repeats a segment. `null` counts as no scope.
247
+ - Segments are compared exactly: `"Chat-7"` is not `"chat-7"`.
248
+
249
+ The owner says who may use a document. The scope says where it belongs. With both, one user's two
250
+ chats cannot use each other's files, and a store can lay the files of each chat out apart.
251
+
252
+ ### Requiring an owner and a scope
253
+
254
+ New in 0.9.0. On a server where every document belongs to a signed-in user, turn both on:
163
255
 
164
- ### Choosing the owner string
256
+ ```ts
257
+ import { createLargeFiles, MemoryDocumentStore } from "llm-large-files";
258
+
259
+ export const strict = createLargeFiles({ store: new MemoryDocumentStore(), requireOwner: true, requireScope: true });
260
+ ```
165
261
 
166
- The owner is any string you choose. The library has no notion of a chat or session, and cannot list
167
- documents by owner. Two schemes work well:
262
+ - Every call must then name its owner and its scope: `ingest`, `getMeta`, `getOriginal`, `delete`,
263
+ `prepare`, `askWithFiles`, `askStream`, `askGemini`, and `tools`, which needs `access`. A call
264
+ without one throws `TypeError("owner is required: requireOwner is on")` or
265
+ `TypeError("scope is required: requireScope is on")`, before the store is asked anything. A
266
+ forgotten owner fails loudly, instead of reaching every document stored without one.
267
+ - A document stored without an owner, or without a scope, then reads as missing, for every caller.
268
+ - `files.sweep()` needs no scope: it is upkeep of the store, not a user's access.
269
+ - `files.access` says which are on, for code that serves the library (the upload handlers).
168
270
 
169
- | Owner | What the library enforces | What your application does |
271
+ ### Application IDs
272
+
273
+ New in 0.9.0. Give `ingest` the document's ID, such as the ID of the upload in your database:
274
+
275
+ ```ts
276
+ // `strict` and `bytes` as above; "upload-3f9a" is the ID of the upload in your own records.
277
+ const report = await strict.ingest({ name: "report.txt", bytes, owner: "user-42", scope: ["user-42", "chat-7"], id: "upload-3f9a" });
278
+ ```
279
+
280
+ - The ID must match `APP_DOCUMENT_ID_PATTERN`: lowercase letters, digits, `_` and `-`, up to 64
281
+ characters, starting with a letter or a digit. Another is a `TypeError`. Without an `id`, the
282
+ library makes one, as before.
283
+ - The model sees the ID, in the cards and the tool calls. It must hold no personal data: not an
284
+ email address, not a name.
285
+ - `ifExists: "fail"`, the default, refuses an ID that is taken with an `IngestError` of code
286
+ `"exists"` (status 409), before the file is read. `ifExists: "replace"` deletes the document there,
287
+ then stores the new one, but only one of the same owner and scope. A document of another owner or
288
+ scope is `"exists"` too, even when its text seems to be gone: a store that loses the context of a
289
+ read would say that of a document that is there. A document that has expired is written over in
290
+ both cases.
291
+ - The store is asked "is this ID taken?" in the scope of the ingest. Over a store that ignores the
292
+ context, the question spans every scope: one chat cannot write over another chat's document, and
293
+ the IDs must be unique in the whole store.
294
+ - In one library, one ID is stored by one ingest at a time. While an ingest of an ID is under way,
295
+ from its first look at the store to the end of its writes, another ingest of that ID is
296
+ `"exists"`, whatever its `ifExists`, owner or scope. A user who uploads the same file twice at once
297
+ gets a 409 for the second.
298
+ - When the writes (or the clean-up after a write that failed) do not end within `ingestTimeoutMs`,
299
+ the ingest throws, but its writes may still land. So the ID stays held in that library until they have ended, and the removal of what they
300
+ wrote too. This fails closed: a store that never answers keeps that one ID refused in that library
301
+ until the process restarts.
302
+ - Across servers, the store is asked twice: before the file is read, and just before the writes.
303
+ Two servers can still both find an ID free and write it at the same moment. The library assumes
304
+ that two ingests of one ID on two servers at once are the same upload, sent twice: the last write
305
+ wins. Over a store that hides a record until its text is written, as the
306
+ [example](#example-object-storage-and-a-database) does, both usually fail with a 503 instead, and
307
+ nothing is stored. So give each upload an ID of its own.
308
+ - When a write fails, the ingest removes what it wrote, but only while the document under the ID is
309
+ its own. A document whose metadata it finds there, and that is not its own, is left. If that one
310
+ has not expired and is of another owner or scope (another server stored it meanwhile), the ingest
311
+ throws `"exists"`. Otherwise, as when the delete of the document a replace was to remove fails, it
312
+ throws the store's error (503), as for any failed write.
313
+ - The clean-up sees only metadata. The parts of a document that another server is still writing at
314
+ that moment (its original, its index; with a store that hides a record until its text is written,
315
+ as the example does, that record and its text too) may be removed. One more reason to give each
316
+ upload an ID of its own.
317
+ - A 409 tells the caller that the ID is taken, whoever has it: over a store that ignores the
318
+ context, in any scope. So an ID that can be guessed can be probed. Use random IDs, as
319
+ [`attach()` below](#a-layout-per-user-and-per-chat) does
320
+ (`` `up-${randomUUID().replaceAll("-", "")}` ``), or IDs that start with the tenant's own prefix.
321
+ - Replacing a document is not atomic for readers on other servers: for a moment it is missing.
322
+ - An ID you choose keeps the stored rounds of a conversation valid: a file ingested again under the
323
+ same ID is found by the `toolTurns` that name it ([Conversations](./conversations.md)).
324
+
325
+ ### Choosing the owner and the scope
326
+
327
+ The owner and the scope are strings you choose. The library cannot list documents by owner or by
328
+ scope. A good fit for a chat application:
329
+
330
+ | Field | Value | What the library enforces |
170
331
  |---|---|---|
171
- | The user: `userId` | No user can use another user's documents. | Keeps each chat's document IDs in its session record and passes those, never a list from the browser as it came. A document can serve several chats of its user. |
172
- | The user and the chat: `` `${userId}/${sessionId}` `` | A document can be used only in the chat it was uploaded to. | Builds the same string for every call: upload, questions, GET, DELETE. `getOwner` must then know the chat, from the URL or a header. A file used in two chats is uploaded twice. |
332
+ | `owner` | `userId` | No user can use another user's documents. |
333
+ | `scope` | `[userId, chatId]` | A document can be used only in the chat it was uploaded to. A file used in two chats is uploaded twice. |
334
+ | `id` | the upload's ID | The ID your session record keeps is the document's ID. |
173
335
 
174
- The [Conversations](./conversations.md) guide uses the first scheme. To switch to the second,
175
- change the `owner` you pass, everywhere.
336
+ Build the same owner and scope for every call: upload, questions, GET, DELETE. Before 0.9.0, an
337
+ owner of `` `${userId}/${sessionId}` `` did the work of the scope. It still works, but a store
338
+ cannot lay files out by it, and the owner is no longer one user.
176
339
 
177
340
  ### A layout per user and per chat
178
341
 
@@ -183,17 +346,20 @@ list of a chat's documents:
183
346
  ```ts
184
347
  // chat-documents.ts. `files` is your library; `sessions` and `turns` are the collections of the
185
348
  // Conversations guide.
349
+ import { randomUUID } from "node:crypto";
186
350
  import { toDocumentSummary, type DocumentSummary } from "llm-large-files";
187
351
 
188
- /** Adds a file to a chat. The user owns it, and the session record lists it. */
352
+ /** Adds a file to a chat. The user owns it, the chat is its scope, and the session record lists it. */
189
353
  export async function attach(userId: string, sessionId: string, file: { name: string; mimeType?: string; bytes: Uint8Array }): Promise<DocumentSummary> {
190
354
  if (!await sessions.findOne({ _id: sessionId, userId })) throw new Error("No such chat.");
191
- const meta = await files.ingest({ ...file, owner: userId });
355
+ const scope = [userId, sessionId];
356
+ // The document's ID is yours: here a new one, as the ID of an upload record would be.
357
+ const meta = await files.ingest({ ...file, owner: userId, scope, id: `up-${randomUUID().replaceAll("-", "")}` });
192
358
  try {
193
359
  await sessions.updateOne({ _id: sessionId, userId }, { $addToSet: { documentIds: meta.id } });
194
360
  } catch (error) {
195
361
  // A document that no chat lists would stay until it expires.
196
- await files.delete(meta.id, { owner: userId }).catch(() => undefined);
362
+ await files.delete(meta.id, { owner: userId, scope }).catch(() => undefined);
197
363
  throw error;
198
364
  }
199
365
  return toDocumentSummary(meta);
@@ -210,50 +376,145 @@ export async function documentsFor(userId: string, sessionId: string, picked?: s
210
376
  export async function deleteChat(userId: string, sessionId: string): Promise<void> {
211
377
  const session = await sessions.findOne({ _id: sessionId, userId });
212
378
  if (!session) return;
213
- for (const id of session.documentIds) await files.delete(id, { owner: userId });
379
+ for (const id of session.documentIds) await files.delete(id, { owner: userId, scope: [userId, sessionId] });
214
380
  await turns.deleteMany({ sessionId });
215
381
  await sessions.deleteOne({ _id: sessionId, userId });
216
382
  }
217
383
  ```
218
384
 
219
- - Ask with `owner: userId` and `documentIds: await documentsFor(userId, sessionId)`. When documents
220
- have expired, the question throws `DocumentsNotFoundError` with their IDs:
221
- [Conversations](./conversations.md) shows how to take them off the chat and ask the user for them
222
- again.
385
+ - Ask with `owner: userId`, `scope: [userId, sessionId]` and
386
+ `documentIds: await documentsFor(userId, sessionId)`. When documents have expired, the question
387
+ throws `DocumentsNotFoundError` with their IDs, or, with `onMissingDocuments: "drop"` (new in
388
+ 0.9.0), is answered without them and lists them in `result.missing`:
389
+ [Conversations](./conversations.md#documents-that-are-gone) shows how to take them off the chat
390
+ and ask the user for them again.
223
391
  - `files.delete` gives false for a document that has already expired or been deleted. There is
224
392
  nothing left to do for it.
225
- - If your application lets a document serve several chats, delete it only when no other chat lists
226
- it.
227
- - The `upload` handler of `createDocumentHandlers` answers the request itself, so it cannot record
228
- the new ID in your session. Call `attach` from a route of your own, or record the ID the browser
229
- sends back in a second request, after checking it with `files.getMeta(id, { owner })`. Routes are
230
- in [Web app](./web-app.md).
393
+ - Over a `FileDocumentStore` with `scopes`, `deleteChat` can remove the chat's folder in place of
394
+ each document ([below](#files-in-a-folder-per-user-or-per-chat)).
395
+ - The `upload` handler of `createDocumentHandlers` answers the request itself. Since 0.9.0 its
396
+ hooks do what `attach` does: `prepareUpload` gives the upload its ID (and can save the body in the
397
+ chat's folder), and `onUploaded` records the ID in your session, or fails the upload
398
+ ([Web app](./web-app.md#save-each-upload-where-you-keep-it-prepareupload)). Otherwise call
399
+ `attach` from a route of your own.
231
400
  - To delete everything of a user (an account that is closed), collect the IDs from the user's chats.
232
401
  The library cannot find a user's documents. A store of your own can, if it keeps the owner where it
233
- can query it, as the [example store](#example-object-storage-and-a-database) does.
402
+ can query it, as the [example store](#example-object-storage-and-a-database) does: the context of
403
+ every call gives it the owner and the scope.
234
404
 
235
405
  ### Files in a folder per user or per chat
236
406
 
237
- Every call but `put` gives a store the document ID without its metadata. `putOriginal` and
238
- `putIndex` come before `put`, so a store cannot know the owner of a file it is writing.
239
- A store therefore keys its files by document ID, and the layout by user and chat lives in your
240
- database: the session record lists the IDs, and a store of your own can keep the owner next to each
241
- document.
242
-
243
- If your storage rules need each chat's files in a folder of their own, give each chat a library of
244
- its own, over its own `FileDocumentStore`:
407
+ New in 0.9.0. Give `FileDocumentStore` the `scopes` option, and one library serves every user and
408
+ every chat, with each chat's files in a folder of its own:
245
409
 
246
410
  ```ts
411
+ import { mkdir } from "node:fs/promises";
247
412
  import path from "node:path";
248
- import { createLargeFiles, FileDocumentStore, type LargeFiles } from "llm-large-files";
413
+ import { createLargeFiles, FileDocumentStore, isSafeScopeSegment, toDocumentSummary } from "llm-large-files";
414
+
415
+ const DOCUMENTS_DIR = process.env.DOCUMENTS_DIR!;
416
+
417
+ // One store and one library for the process: their limits hold for every chat at once.
418
+ export const store = new FileDocumentStore(DOCUMENTS_DIR, { scopes: { depth: 2 } });
419
+ export const files = createLargeFiles({ store, requireOwner: true, requireScope: true });
420
+
421
+ /**
422
+ * Makes the folder of a chat. Call it once, when you create the chat's record, not on each upload:
423
+ * an upload after you removed the folder must fail, not make it again.
424
+ */
425
+ export async function startChat(userId: string, chatId: string) {
426
+ // Check the IDs before they become a path. For IDs that do not pass, use hashedScopeSegment.
427
+ if (!isSafeScopeSegment(userId) || !isSafeScopeSegment(chatId)) throw new TypeError("The user or chat ID cannot name a folder.");
428
+ await mkdir(path.join(DOCUMENTS_DIR, userId, chatId), { recursive: true, mode: 0o700 });
429
+ }
249
430
 
250
- // One case only: on a volume that ignores case, "Alice" and "alice" would be one folder.
251
- const SAFE_ID = /^[a-z0-9_-]{1,64}$/;
431
+ /** Adds a file to a chat. `uploadId` is the ID of the upload in your records: lowercase, as UUIDs are. */
432
+ export async function upload(userId: string, chatId: string, uploadId: string, file: { name: string; bytes: Uint8Array }) {
433
+ // The store makes only its own folder in the chat's. A chat whose folder is gone: "scope_missing".
434
+ const meta = await files.ingest({ ...file, owner: userId, scope: [userId, chatId], id: uploadId });
435
+ return toDocumentSummary(meta);
436
+ }
437
+ ```
438
+
439
+ The volume then holds:
440
+
441
+ ```text
442
+ <DOCUMENTS_DIR>/
443
+ user-42/
444
+ chat-7/
445
+ .llm-large-files/ the store's: upload-3f9a.json, upload-3f9a.txt, upload-3f9a.idx
446
+ uploads/ yours, if you keep the uploads: the sweep never goes in, and fileOriginals reads them
447
+ ```
448
+
449
+ - Pass the same `scope` on every later call: questions (`askWithFiles({ owner, scope })`),
450
+ `getMeta`, `getOriginal`, `delete`. A document of one chat is not found from another, even under
451
+ the same ID: the folder is the boundary, and the library checks `meta.scope` too.
452
+ - `depth` is the number of segments of every scope: 2 for `[userId, chatId]`. A scope of another
453
+ length, or a call without one, throws a `DocumentScopeError` (`"scope_invalid"`,
454
+ `"scope_required"`).
455
+ - Each segment names a folder, so it must pass `isSafeScopeSegment`: lowercase letters, digits,
456
+ `_` and `-`, up to 64 characters, and no name Windows keeps for a device (`con`, `nul`). Lower
457
+ case only, because SMB and Azure Files ignore case: `Alice` and `alice` would share a folder. IDs
458
+ your database makes (UUIDs, MongoDB ObjectIds in lowercase hex) pass as they are. For IDs in mixed
459
+ case, or in Hebrew, pass `hashedScopeSegment(userId)` as the segment, everywhere: it gives `h` and
460
+ 40 hex digits of the ID's SHA-256. Name the folders you make and remove with it too.
461
+ - The store makes its own folder (`.llm-large-files`, the `folder` option) inside a chat's folder
462
+ that exists, and never the chat's folder itself. To delete a chat, stop its questions, then remove
463
+ its folder: `rm(path.join(DOCUMENTS_DIR, userId, chatId), { recursive: true, force: true, maxRetries: 5 })`.
464
+ An upload that finishes after that throws a `DocumentScopeError` of code `"scope_missing"`,
465
+ instead of making the folder again. Reads in that chat find nothing. An upload being stored at
466
+ that moment can write its files into the folder while `rm` empties it. Without `maxRetries`, `rm`
467
+ then fails with `ENOTEMPTY`; with it, `rm` looks again and removes them. Remove the chat's other
468
+ data (its record, its messages) before the folder: if `rm` still fails, only files are left, for
469
+ a cleanup job. To delete a user, remove the user's folder the same way.
470
+ - `createScopeFolders: true` makes the folders of a chat at its first upload, for an application
471
+ that keeps none of its own. The removal above then cannot stop a late upload. It makes them one
472
+ level at a time, and makes nothing where a link points.
473
+ - `folder: ""` puts the store's files in the chat's folder itself, beside yours. The names
474
+ `<id>.json`, `.txt`, `.idx` and `.bin`, and their temporary files, then belong to the store for
475
+ every ID it is given: an ingest under the ID `report` writes over your `report.txt`. Keep your own
476
+ files in a subfolder, such as `uploads/`, or under other names.
477
+ - `files.sweep()` sweeps every chat: it goes down exactly `depth` levels of folders, into folders
478
+ whose names a segment may have, and never follows a link. `files.sweep({ scope })` sweeps one
479
+ chat's folder. Run it from one server ([Deployment](./deployment.md#sweeping-expired-documents)).
480
+ - A folder of a scope that is a link, or lies under one, is refused with `"scope_invalid"`: a call
481
+ checks that the folder is where its path says, inside `DOCUMENTS_DIR`. Writes, deletes and sweeps
482
+ check every time. A read takes a folder checked less than a second ago as checked, so a link put
483
+ in place of a chat's folder is seen by reads within a second. A link at a file name is not
484
+ followed either, except on Windows.
485
+ - That check costs one `realpath` of the chat's folder, a look at each folder on its path. Reads
486
+ share it for a second, so a search that reads a large document by range checks once a second,
487
+ not once a read. On a local SSD, 10,000 ranged reads in a chat's folder took 0 to 17% longer than
488
+ in the flat layout; when each read checked, they took 40 to 60% longer. On a network volume each
489
+ of those looks can be a round trip.
490
+ - Documents ingested before 0.9.0 are in `DOCUMENTS_DIR` itself. `unscoped: "root"` serves a call
491
+ without a scope from there, as before, until they expire, and `files.sweep()` sweeps them too.
492
+ It cannot go with `requireScope`, which refuses such calls first.
493
+ - A wrapper or a subclass of the store must pass the context on (`super.getMeta(id, context)`).
494
+ Without it, every call but `sweep` throws `"scope_required"`, and a `sweep` sweeps every chat.
495
+ Under `unscoped: "root"` nothing throws: the text and the metadata go to the root folder, outside
496
+ the chat's folder, and removing that folder does not erase them. Another chat still cannot read
497
+ them: the library checks `meta.scope`.
498
+ - Servers of 0.8 do not see these folders, nor documents under an application's ID: during an
499
+ upgrade they find them missing ([Deployment](./deployment.md#servers-of-two-versions)).
500
+
501
+ One library for the process keeps its limits for the whole process: `maxConcurrentIngests` and its
502
+ queue, `cacheBytes` and `maxConcurrentScans` bound every chat together, and a document read in one
503
+ question stays in the cache for the next.
504
+
505
+ #### A library per chat
506
+
507
+ Before 0.9.0, the only way to a folder per chat was a library per chat, each over its own
508
+ `FileDocumentStore`. It still works:
509
+
510
+ ```ts
511
+ import path from "node:path";
512
+ import { createLargeFiles, FileDocumentStore, isSafeScopeSegment, type LargeFiles } from "llm-large-files";
252
513
 
253
514
  /** The library of one chat: its files are in <DOCUMENTS_DIR>/<user>/<chat>/. */
254
515
  export function filesOf(userId: string, sessionId: string): LargeFiles {
255
516
  // The IDs become a path: refuse anything that could lead out of the directory.
256
- if (!SAFE_ID.test(userId) || !SAFE_ID.test(sessionId)) throw new Error("Invalid user or chat ID.");
517
+ if (!isSafeScopeSegment(userId) || !isSafeScopeSegment(sessionId)) throw new Error("Invalid user or chat ID.");
257
518
  return createLargeFiles({
258
519
  store: new FileDocumentStore(path.join(process.env.DOCUMENTS_DIR!, userId, sessionId)),
259
520
  cacheBytes: 32 * 1024 * 1024, // each library has a cache of its own
@@ -261,22 +522,17 @@ export function filesOf(userId: string, sessionId: string): LargeFiles {
261
522
  }
262
523
  ```
263
524
 
264
- On a volume that ignores case (Windows, macOS, SMB shares), IDs that differ only in case would
265
- share a folder, so the check takes lower case only. If your IDs are mixed case and unique
266
- regardless of case, lower-case them before the check. IDs your database makes, such as UUIDs or
267
- MongoDB ObjectIds in lower-case hex, pass it as they are.
268
-
269
- What that costs:
525
+ What that costs, against one library over a store with `scopes`:
270
526
 
271
527
  - `cacheBytes`, `maxConcurrentScans` and `maxConcurrentIngests` bound each library, not the process,
272
- and `maxPendingUploadBytes` each set of upload handlers. With a library per chat, ingests of
273
- different chats all work at once, as before 0.8.2: bound them for the process yourself, with one
274
- queue or count shared by the chats' routes. A library made for one request starts with an empty
275
- cache, so each question reads its documents from the store again.
528
+ and `maxPendingUploadBytes` each set of upload handlers. Ingests of different chats all work at
529
+ once, as before 0.8.2: bound them for the process yourself, with one queue or count shared by the
530
+ chats' routes. A library made for one request starts with an empty cache, so each question reads
531
+ its documents from the store again.
276
532
  - Each chat's folder needs a sweep of its own: `new FileDocumentStore(folder).sweep()` for each one.
277
- The store never removes the folder itself.
278
- - Deleting a chat is removing its folder, once no question of that chat is running.
279
- - A document of another chat is not found: the folder is the boundary.
533
+ - The store makes the chat's folder again at a late upload, after you removed it.
534
+ - The store's files sit in the chat's folder itself, so its sweep leaves files of no document there
535
+ unless their names are the library's own IDs.
280
536
 
281
537
  ## Retention
282
538
 
@@ -324,7 +580,9 @@ setInterval(() => {
324
580
  provider keeps is in [Security](../security.md).
325
581
 
326
582
  A chat that lives longer than `ttlMs` loses its documents, and its next question throws
327
- `DocumentsNotFoundError`. To keep documents as long as their chat:
583
+ `DocumentsNotFoundError`, unless it is asked with `onMissingDocuments` (new in 0.9.0): `"drop"`
584
+ answers without them, and a function can ingest them again from the uploads you kept
585
+ ([missing documents](../reference/ask.md#missing-documents)). To keep documents as long as their chat:
328
586
 
329
587
  - Set a `ttlMs` longer than your chats live.
330
588
  - Or set `ttlMs: Infinity`, and delete the documents yourself: with their chat (`deleteChat` above),
@@ -339,11 +597,24 @@ A chat that lives longer than `ttlMs` loses its documents, and its next question
339
597
 
340
598
  ## Keeping the uploaded files
341
599
 
342
- By default a store keeps only the text of a document. `keepOriginals` also keeps the uploaded file:
600
+ By default only the text of a document is kept. `keepOriginals` keeps the uploaded file too, for
601
+ the formats it lists, so that `view_pages` can show the model the pages of a PDF, and a scanned PDF
602
+ can be accepted ([PDFs](./pdfs.md)). The file is kept in one of two places:
603
+
604
+ - **A copy in the store**, next to the text (`putOriginal`).
605
+ - **Where your application keeps it**, new in 0.9.0: the ingest gives `original: { ref }`, and the
606
+ library reads the file from there through `originals`. The store keeps no second copy.
343
607
 
344
608
  | Option | Default | What it does |
345
609
  |---|---|---|
346
- | `keepOriginals` | `[]` | Formats whose uploaded file is kept next to its text, for example `["pdf"]`. |
610
+ | `keepOriginals` | `[]` | Formats whose uploaded file is kept, for example `["pdf"]`. |
611
+ | `originals` | none | Reads the files your application keeps, by their ref: `fileOriginals(root)` of `llm-large-files/node`, or your own `{ read(ref, context) }`. New in 0.9.0. |
612
+
613
+ Either way, `meta.originalKept` is true, `files.getOriginal(id, { owner, scope })` returns the
614
+ file under the same owner and scope rules as everything else, and `view_pages` reads it. Treat the
615
+ bytes as read-only: they may be the store's own copy.
616
+
617
+ ### A copy in the store
347
618
 
348
619
  ```ts
349
620
  import type { ServerResponse } from "node:http";
@@ -377,29 +648,144 @@ export async function sendOriginal(response: ServerResponse, id: string, owner:
377
648
 
378
649
  - It is off by default because it costs space: a kept file is as large as the upload, up to
379
650
  `maxUploadBytes` (100 MB by default), and stays until the document expires or is deleted.
380
- - A kept original is what `view_pages` shows the model, and what lets a scanned PDF be accepted.
381
- Both are in [PDFs](./pdfs.md).
382
651
  - The store needs `putOriginal` to keep a file and `getOriginal` to give it back. The built-in stores
383
- have both. A store without `putOriginal` keeps nothing, whatever `keepOriginals` says.
384
- - `meta.originalKept` is true when the file of a document is kept. `files.getOriginal(id, { owner })`
385
- returns it, under the same owner rule as everything else. Treat the bytes as read-only: they may be
386
- the store's own copy.
652
+ have both. A store without `putOriginal` keeps no copy, whatever `keepOriginals` says.
653
+ - The bytes are checked when they are read back. Since 0.9.0, `getOriginal` and `view_pages` ask
654
+ the store for the metadata again once the file is read, and the file is missing unless the
655
+ document is still the same one, of the same owner and scope, and the file is that of the upload:
656
+ of its size (`meta.bytes`) and, for documents of 0.9.0 and later, of its SHA-256 (`meta.sha256`).
657
+ Another server may have deleted the document and stored another under its ID meanwhile, and a
658
+ store may give back another file of the same size.
387
659
  - Documents ingested before you turned it on have no original. Upload them again to get one.
388
660
 
661
+ ### The file your application keeps
662
+
663
+ New in 0.9.0. When your application saves each upload anyway (to send it back, or to ingest it
664
+ again later), keep only that one. The ingest says where it is, and the library reads it from there.
665
+ With `createDocumentHandlers`, `prepareUpload` saves the body there and gives the ref
666
+ ([Web app](./web-app.md#save-each-upload-where-you-keep-it-prepareupload)); a route of your own
667
+ saves it, then calls `ingest`:
668
+
669
+ ```ts
670
+ import path from "node:path";
671
+ import { createLargeFiles, FileDocumentStore } from "llm-large-files";
672
+ import { fileOriginals } from "llm-large-files/node";
673
+
674
+ const VOLUME = process.env.DOCUMENTS_DIR!;
675
+
676
+ export const files = createLargeFiles({
677
+ store: new FileDocumentStore(VOLUME, { scopes: { depth: 2 } }),
678
+ keepOriginals: ["pdf"],
679
+ originals: fileOriginals(VOLUME),
680
+ requireOwner: true,
681
+ requireScope: true,
682
+ });
683
+
684
+ /** Ingests an upload your route saved at <VOLUME>/<user>/<chat>/uploads/<uploadId>. */
685
+ export function ingestSaved(userId: string, chatId: string, uploadId: string, name: string) {
686
+ const ref = `${userId}/${chatId}/uploads/${uploadId}`;
687
+ return files.ingest({
688
+ name,
689
+ source: { path: path.join(VOLUME, ref) }, // read at its turn, not held while it waits
690
+ original: { ref },
691
+ owner: userId,
692
+ scope: [userId, chatId],
693
+ id: uploadId,
694
+ });
695
+ }
696
+ ```
697
+
698
+ - **The ref** is a string of 1 to 1,024 characters that your reader understands: for
699
+ `fileOriginals(root)`, a path relative to `root`. It is never sent to the model, nor in a summary.
700
+ An event holds it only with `eventResults: true`, in the full plan of `run.finish` and
701
+ `run.error` ([events](../reference/events.md#documents-eventresults-and-eventresult)). An ingest with `original` in a library without `originals` throws a `TypeError`. A
702
+ format that `keepOriginals` does not list records nothing, whatever the ref.
703
+ - **What is recorded.** `meta.original` is `{ ref, bytes, sha256 }`: the ref, and the size and
704
+ SHA-256 of the file at ingest. `meta.originalKept` is true, as for a copy. The store's
705
+ `putOriginal` is not called.
706
+ - **Each read is checked.** `getOriginal` and `view_pages` read the ref the store holds (never one
707
+ from metadata handed in), ask the store for the metadata again, then compare the file with the
708
+ size and SHA-256 recorded. A file that has changed gives `undefined` from `getOriginal`, and
709
+ `view_pages` tells the model: "report.pdf changed on the server since it was read. Attach it
710
+ again to look at its pages." A file that is gone reads as missing.
711
+ - **The library never writes, moves or deletes it.** `files.delete` and the sweep leave it. Remove
712
+ it with its chat: over a scoped store, `rm` of the chat's folder removes the store's files and
713
+ your uploads together.
714
+ - **`fileOriginals(root)`** resolves a ref under `root`, and refuses one that leads out of it with a
715
+ `TypeError`, which the library passes on as a `DocumentStoreError`. A link at any level below
716
+ `root` reads as missing. It reads a file once, at most one byte past the size recorded, and never
717
+ writes ([`fileOriginals`](../reference/node.md#fileoriginalsroot)).
718
+ - **A reader of your own** is an object with `read(ref, context)`, which returns the bytes, or
719
+ `undefined` when the file is not there: a bucket key, a database ID. `context` has the scope and
720
+ owner of the call, the document's `id`, and `bytes`, the size recorded; a reader may stop one
721
+ byte past it. What it throws becomes a `DocumentStoreError` (operation `"read"`) with its error as
722
+ `cause` ([`OriginalsReader`](../reference/library.md#originalsreader)).
723
+ - **The same file twice.** Every document of 0.9.0 has `meta.sha256`, the SHA-256 of the upload,
724
+ for bytes and for paths. The library does not look for another document of the same file: to
725
+ give a user the document of a file already in the chat, compare it with the `sha256` your
726
+ session record keeps for the chat's documents. Never across owners.
727
+
389
728
  ## Writing a store of your own
390
729
 
391
730
  A store of your own implements `DocumentStore`: four methods are required, six are optional. The
392
731
  library calls them. Your application calls them only to test the store, or to sweep a store that no
393
732
  library uses.
394
733
 
734
+ Every method takes a last, optional `context`, new in 0.9.0: the scope and the owner of the call
735
+ ([`DocumentContext`](../reference/library.md#documentcontext)), as in `getMeta(id, context?)`. The
736
+ table below leaves it out. A store written for 0.8, without it, still compiles and works, unless
737
+ a method takes a parameter of its own in its place
738
+ ([Does my code compile?](../upgrading-0.9.md#does-my-code-compile)).
739
+
740
+ - Use `context.scope` as the boundary of your storage, if you want one: a key prefix, a folder, a
741
+ filter on a collection. `context.owner` lets you index documents by user. A store that ignores
742
+ the context still keeps scopes apart for the library, through `meta.scope`; an application's IDs
743
+ must then be unique in the whole store.
744
+ - A store that wraps another one, or a subclass that overrides a method, passes the context on.
745
+ One that drops it loses the scope of every call: over a store that keeps scopes apart, such a
746
+ call does not find the documents stored in a scope. Over a `FileDocumentStore` with `scopes`,
747
+ every call but `sweep` throws; with `unscoped: "root"`, the documents go to the root folder,
748
+ outside the chat's folder, without an error. A `sweep` that drops it sweeps every scope.
749
+
750
+ ```ts
751
+ import { FileDocumentStore, type DocumentContext, type DocumentMeta } from "llm-large-files";
752
+
753
+ /** Counts the reads of metadata, and passes the context on, as every method of a wrapper must. */
754
+ export class CountingStore extends FileDocumentStore {
755
+ reads = 0;
756
+
757
+ override async getMeta(id: string, context?: DocumentContext): Promise<DocumentMeta | undefined> {
758
+ this.reads++;
759
+ return super.getMeta(id, context); // not super.getMeta(id)
760
+ }
761
+ }
762
+ ```
763
+
764
+ Which context a call carries:
765
+
766
+ - At ingest, every write and every look-up carries the owner and the scope of the new document.
767
+ - `getMeta`, `getOriginal` and `delete` carry those of the caller.
768
+ - The reads of a document's text carry the caller's scope and the document's owner: `get`,
769
+ `readTextRange`, `getIndex`, and `putIndex` when an index is built again. The library reads them
770
+ only once `getMeta` has found, in the caller's scope, a document the caller may use. So the scope
771
+ is where the document was found, even when its metadata has none (a document of 0.8 that you moved
772
+ into a scope). The owner is left out when the document has none, whoever asked. The library keeps
773
+ one copy of a document for all callers of a scope: its reads carry one context whoever made them.
774
+ A store that logs who reads should log the caller from `getMeta`.
775
+ - A wrapper or a cache in front of a store must never keep what `readTextRange` or `getIndex` gave
776
+ by ID alone: key it by the context too. Bytes read by range carry nothing that the library can
777
+ check them by (see [Reading by range](#reading-by-range)).
778
+ - A store keeps at most one document of an ID in a scope. It may keep the scopes apart; it must not
779
+ keep a document of one ID for each owner in one scope.
780
+
395
781
  ### The methods
396
782
 
397
783
  | Method | Required | When the library calls it | What it must do |
398
784
  |---|---|---|---|
399
785
  | `put(document)` | Yes | `ingest`, last, after `putOriginal` and `putIndex`. | Keep `document.meta` whole, as one object, and `document.text`. Keep the text exactly, as UTF-8: `readTextRange` offsets point into those bytes. Let the document appear only once all of it is written. |
400
- | `getMeta(id)` | Yes | Before every use of a document: `getMeta`, `getOriginal`, `delete`, `prepare` (once a document), and every tool call that reads one. | Return the metadata, or undefined when there is no such document. Keep it cheap: one look-up by key, without reading the text. |
786
+ | `getMeta(id)` | Yes | Before every use of a document: `getMeta`, `getOriginal`, `delete`, `prepare` (once a document), and every tool call that reads one. Once more after a document is read by range, or its original file is read. | Return the metadata, or undefined when there is no such document. Keep it cheap: one look-up by key, without reading the text. Return a field that was left out (`owner`, `scope`) absent, not `null`. |
401
787
  | `get(id)` | Yes | To load a document whole: one whose text is at most `wholeDocumentBytes`, or any document when the store has no `readTextRange`. Once a library while the document stays in the cache. | Return `{ meta, text }` with the text exactly as `put` got it, or undefined. |
402
- | `delete(id)` | Yes | `files.delete`, after the owner check. And `ingest`, to clean up after a write that failed. | Remove the metadata first, then the text, the index and the original. Return true when the document was there. Cope with a document that was only partly written. |
788
+ | `delete(id)` | Yes | `files.delete`, after the owner check. And `ingest`: to clean up after a write that failed, or a listener that threw on `ingest.finish`, only while the document under the ID is that ingest's own; and with `ifExists: "replace"`, to remove the document it replaces. | Remove the metadata first, then the text, the index and the original. When the metadata cannot be removed, throw, and leave the rest. Return true when the document was there. Cope with a document that was only partly written. |
403
789
  | `sweep(now?)` | No | `files.sweep()`, with the library's clock. | Remove the documents whose `expiresAt` is at or before `now`, with all their parts. Return how many. |
404
790
  | `putOriginal(id, bytes)` | No | `ingest`, first, when `keepOriginals` lists the format. | Keep the bytes as they are now: the caller may reuse its buffer afterwards. |
405
791
  | `getOriginal(id)` | No | `files.getOriginal` and `view_pages`, for a document whose `meta.originalKept` is true. | Return the bytes, or undefined. |
@@ -408,15 +794,20 @@ library uses.
408
794
  | `getIndex(id)` | No | When a document read by range is opened. | Return the bytes `putIndex` kept, or undefined. A damaged index is noticed and built again. |
409
795
 
410
796
  The library checks `expiresAt` itself, with its own clock, before every use. Your `getMeta` and
411
- `get` may return a document that has expired; your `sweep` must remove it.
797
+ `get` may return a document that has expired; your `sweep` must remove it. If they remove an expired
798
+ document when they meet one, as the built-in stores do, they return undefined even when the removal
799
+ fails: an error there reaches the user as "try again" for a document that is gone, on every try.
412
800
 
413
801
  Keep every field of `meta`, including those your store does not know. Later versions add optional
414
- fields: 0.4.1 added `jsonBytes`, and 0.6.0 `encoding` and `replacedCharacters`, which say how a
415
- text file that was not valid UTF-8 was read ([PDFs and other formats](./pdfs.md#text-encodings)).
802
+ fields: 0.4.1 added `jsonBytes`, 0.6.0 `encoding` and `replacedCharacters`, which say how a
803
+ text file that was not valid UTF-8 was read ([PDFs and other formats](./pdfs.md#text-encodings)),
804
+ and 0.9.0 `metaVersion`, on every document it ingests
805
+ ([`DOCUMENT_META_VERSION`](../reference/library.md#document_meta_version)).
416
806
  A store that checks `meta` against a fixed list of fields (a `$jsonSchema` with
417
807
  `additionalProperties: false`, a Mongoose schema in strict mode that throws) refuses the ingest of
418
808
  every file that has them: a text file not in UTF-8, a UTF-8 log cut at a byte count, an ASCII log
419
- with a stray byte. `createDocumentHandlers` then answers 500 "Upload failed.". A store that keeps
809
+ with a stray byte. `createDocumentHandlers` then answers 503 "The document could not be stored. Try
810
+ again." (a 500 "Upload failed." before 0.9.0), and a retry fails the same way. A store that keeps
420
811
  fixed columns and drops the others keeps the text, read right, but the model is no longer told how
421
812
  the file was read. [The example below](#example-object-storage-and-a-database) stores `meta` whole.
422
813
 
@@ -442,12 +833,24 @@ time ([the cache](#the-cache) has the sizes). The rules:
442
833
  - Return every byte asked for, unless the text ends first. A read that comes back short in the
443
834
  middle of the text is taken for a text that does not match its index: that call answers "The
444
835
  stored text of report.log did not match its index. Try the call again.", and the index is built
445
- again.
836
+ again. When the index built again has another number of lines or characters than the metadata
837
+ says, the text is not the one that was ingested, and the document reads as missing (new in 0.9.0;
838
+ before, that text was read).
839
+ - When a document is opened through its saved index, one byte is read across the end of the text
840
+ that the index gives (new in 0.9.0): a text that does not end there has its index built again, and
841
+ compared with the metadata as above.
446
842
  - Return fewer bytes at the end of the text, and an empty array when `start` is at or past its end.
447
843
  That happens: the index is built by reading 4 MB at a time until a read comes back short, so a
448
844
  text whose size is a multiple of 4 MB ends with a read that starts at its end.
449
845
  - Return undefined when the document is gone. The call then answers "doc_… is no longer available on
450
846
  the server. Ask the user to attach the file again."
847
+ - The bytes carry nothing to check them by: the library cannot tell them from the text of another
848
+ document laid out the same way. So, since 0.9.0, once a tool call or `prepare` has read a document
849
+ by range, the library asks `getMeta` once more (one call, however many ranges were read). The read
850
+ is missing unless the store still describes the same document, of the same owner and scope. That
851
+ catches a document deleted, and another stored under its ID, while it was read. It cannot catch a
852
+ store whose `readTextRange` or `getIndex` answers from another document while its `getMeta` is
853
+ right, such as a cache keyed by ID alone. Key any cache of those reads by the context too.
451
854
 
452
855
  How that maps to common storage:
453
856
 
@@ -469,7 +872,8 @@ What the library does with what you throw depends on the call:
469
872
 
470
873
  - **Reads** (`get`, `getMeta`, `getOriginal`, `readTextRange`): whatever you throw is passed on as a
471
874
  `DocumentStoreError`. Its message is "The document store could not be read (EIO). Try again.", with
472
- the code in parentheses only when your error has a string `code`. Its `code` and `syscall` are
875
+ the code in parentheses only when your error has a `code` that reads as one (capitals, digits and
876
+ `_`, as `EIO`): a host a driver put in `code` is left out. Its `code` and `syscall` are
473
877
  those of your error, when they are strings, as a Node system error has them. Its `cause` is your
474
878
  error: log that one. The message names no path or host, so it can be shown to a user or a model.
475
879
  `prepare`, `askWithFiles` and `files.getMeta` throw it; a tool call answers the model with its
@@ -478,19 +882,33 @@ What the library does with what you throw depends on the call:
478
882
  to. What to show the user is in [Errors and reliability](./errors-and-reliability.md).
479
883
  - **`getIndex`**: an error is not passed on. The index is built from the text instead.
480
884
  - **Writes at ingest** (`putOriginal`, `putIndex`, `put`): the library calls `delete(id)` to remove
481
- what was written, ignores any error of that, and throws your error as it came. Through the `upload`
482
- handler of `createDocumentHandlers`, an error with a `status` (or `statusCode`) from 400 to 599 is
483
- answered with that status and its message (a 413 with "The file is larger than the … upload
484
- limit.", and an empty message with "Upload failed."). A Node system error (a string `code` and
485
- `syscall`) is answered 500 "Upload failed (CODE).". Any other error, or a thrown value that is not
486
- an `Error`, is answered 500 "Upload failed.", without its message, which may name a database host.
487
- The handlers log nothing: log your error in the store before you throw. Two paths cannot tell
488
- your error from a file that cannot be read, and answer it 422 with its message, host and all: an
489
- `ingest` of your own that throws a new error in place of yours, and a route of your own. See the
490
- [node reference](../reference/node.md#uploadrequest-response). Give your write errors a status and
491
- a message of your own, as the example below does: every path keeps that status.
492
- - **`delete` and `sweep`**: your error comes out of `files.delete` and `files.sweep` as it came. The
493
- DELETE handler answers it 500 without its message, unless it has a status.
885
+ what was written, ignores any error of that, and throws a `DocumentStoreError` of operation
886
+ `"write"`, whose `cause` is your error (new in 0.9.0: it threw your error as it came). Its message
887
+ is "The document could not be stored (EIO). Try again.", with the code only when your error has a
888
+ string `code`, and its status 503. A write that does not end within `ingestTimeoutMs` is one of
889
+ code `"ETIMEDOUT"`. The `upload` handler of `createDocumentHandlers` answers it 503 with that
890
+ message, which names no host or path, and `Retry-After: 5` (before 0.9.0, a 500). The handlers log nothing: log your
891
+ error in the store before you throw, or log `error.cause`. See the
892
+ [node reference](../reference/node.md#uploadrequest-response). Under an application's ID, the
893
+ library first asks `getMeta(id)`, and calls `delete(id)` only when nothing is there or the document
894
+ there is this ingest's own (the same `createdAt`, owner and scope). Another document there is left.
895
+ When it has not expired and is of another owner or scope, stored by another server meanwhile, the
896
+ ingest throws an `IngestError` `"exists"` (409) instead: a `put` that refuses an ID it already has,
897
+ as an insert with a unique key does, ends that way. Such a `put` must refuse before it writes
898
+ anything under the ID. One that writes the text first and then fails at the insert has written
899
+ over the text of the document that is left. The library reads that document as missing when its
900
+ text has another length or number of lines than its metadata says, but cannot tell a text of the
901
+ same length and lines. The [example](#example-object-storage-and-a-database) claims the record
902
+ first, so it never writes over the text of the document that is left; two ingests of one ID that
903
+ overlap then usually both fail with a 503 (its notes say why). The document a replace was to
904
+ remove, when that `delete` failed, is left too, and the error is the 503 above.
905
+ - **`delete` and `sweep`**: your error comes out of `files.delete` and `files.sweep` as a
906
+ `DocumentStoreError` of operation `"delete"` or `"sweep"`, with your error as `cause` (new in
907
+ 0.9.0: it came out as it was). The DELETE handler answers it 503 with its message.
908
+ - **A scope you cannot keep**: throw a `DocumentScopeError` (`"scope_required"`, `"scope_invalid"`,
909
+ `"scope_missing"`). It is passed on as it is from every call, reads and writes alike: it is a
910
+ mistake of the call, not a store to try again. The handlers of `createDocumentHandlers` answer
911
+ `"scope_missing"` `404` "This chat no longer exists.", and the other two `500` (new in 0.9.0).
494
912
  - **`putIndex` on a later read**: an error is ignored. The index is used from memory, and built again
495
913
  the next time.
496
914
 
@@ -501,12 +919,25 @@ What the library does with what you throw depends on the call:
501
919
  the current one.
502
920
  - In one library, calls that open the same document at the same time share one opening: one `get`,
503
921
  or one `getIndex`.
504
- - A document is written once: its ID is new at every ingest. Only `putIndex` writes again, later, for
505
- a document whose index was missing or did not match its text. Several servers may do that at once,
506
- with the same bytes: let the last write win.
922
+ - A document is written once. With an ID the library makes, the ID is new at every ingest. With an
923
+ [application's ID](#application-ids), another document can be written under the ID later: after
924
+ `files.delete`, once the document has expired, or with `ifExists: "replace"`, which calls
925
+ `delete(id)` and then writes. The library forgets what it kept in memory of the old one. On other
926
+ servers, the old one is missing for a moment, and their copies are checked against the new
927
+ metadata before any use.
928
+ - Two servers may ingest one application's ID at the same moment, when both find it free. The
929
+ library takes them for the same upload sent twice: let the last write win. Its clean-up after a
930
+ failed write leaves a document whose metadata it finds. The parts of one still being written on
931
+ the other server at that moment may be removed (see [Errors](#errors)).
932
+ - Only `putIndex` writes again, later, for a document whose index was missing or did not match its
933
+ text. Several servers may do that at once, with the same bytes: let the last write win.
507
934
  - Make the metadata the point where a document exists. Write it last, in `put`, after the text, and
508
935
  remove it first in `delete`. A server that finds the metadata must be able to read all of the text.
509
- `FileDocumentStore` gets this on a shared volume by writing under a temporary name and renaming.
936
+ `FileDocumentStore` gets this on a shared volume by writing under a temporary name and renaming. A
937
+ store that inserts the metadata under a unique key can insert it first instead, hidden from
938
+ `getMeta`, and show it once the text is written, as the
939
+ [example](#example-object-storage-and-a-database) does. A `put` that loses a race for an ID then
940
+ fails before it writes over the text of the one that won.
510
941
  - A document deleted by another server between `getMeta` and a read is answered as gone: return
511
942
  undefined from that read.
512
943
 
@@ -520,7 +951,7 @@ SDK, following [Reading by range](#reading-by-range).
520
951
  ```ts
521
952
  // blob-document-store.ts
522
953
  import type { Collection } from "mongodb";
523
- import { DOCUMENT_ID_PATTERN, type DocumentMeta, type DocumentStore, type StoredDocument } from "llm-large-files";
954
+ import { APP_DOCUMENT_ID_PATTERN, type DocumentMeta, type DocumentStore, type StoredDocument } from "llm-large-files";
524
955
 
525
956
  /** The object storage calls the store needs. Write them over S3, Cloud Storage, Azure Blob Storage or a volume. */
526
957
  export interface Blobs {
@@ -543,6 +974,8 @@ export type DocumentRecord = {
543
974
  meta: DocumentMeta;
544
975
  owner: string | null;
545
976
  expiresAt: Date;
977
+ /** Set while `put` writes the text: the document is not there yet. */
978
+ writing?: true;
546
979
  };
547
980
 
548
981
  /** A write that failed: a 503 from createDocumentHandlers, with a message that names no host. */
@@ -558,25 +991,32 @@ export class BlobDocumentStore implements DocumentStore {
558
991
  private readonly prefix = "llm-large-files",
559
992
  ) {}
560
993
 
561
- /** Only a document ID becomes part of a key, as in the built-in stores. */
994
+ /** Only a document ID becomes part of a key, as in the built-in stores: the library's, or the application's. */
562
995
  private key(id: string, kind: "txt" | "idx" | "bin"): string {
563
- if (!DOCUMENT_ID_PATTERN.test(id)) throw new Error("Invalid document ID.");
996
+ if (!APP_DOCUMENT_ID_PATTERN.test(id)) throw new Error("Invalid document ID.");
564
997
  return `${this.prefix}/${id}.${kind}`;
565
998
  }
566
999
 
567
- /** Called last at ingest. The text first, the record last: a document exists once its record does. */
1000
+ /**
1001
+ * Called last at ingest. The record first, marked as being written: a put that loses a race for
1002
+ * the ID fails at the unique `_id`, before it writes over the text of the one that won. Then the
1003
+ * text, then the mark goes: a document exists once its record is there without the mark.
1004
+ */
568
1005
  async put({ meta, text }: StoredDocument): Promise<void> {
569
1006
  try {
1007
+ await this.records.insertOne({ _id: meta.id, meta, owner: meta.owner ?? null, expiresAt: new Date(meta.expiresAt), writing: true });
570
1008
  await this.blobs.write(this.key(meta.id, "txt"), new TextEncoder().encode(text));
571
- await this.records.insertOne({ _id: meta.id, meta, owner: meta.owner ?? null, expiresAt: new Date(meta.expiresAt) });
1009
+ // This put's record only: another server may have removed it meanwhile.
1010
+ const { matchedCount } = await this.records.updateOne({ _id: meta.id, writing: true, "meta.createdAt": meta.createdAt }, { $unset: { writing: "" } });
1011
+ if (matchedCount === 0) throw new Error(`The record of ${meta.id} was removed while its text was written.`);
572
1012
  } catch (error) {
573
1013
  throw notStored(error);
574
1014
  }
575
1015
  }
576
1016
 
577
- /** Called before every use of a document: one look-up by key. */
1017
+ /** Called before every use of a document: one look-up by key. A record still being written is not a document yet. */
578
1018
  async getMeta(id: string): Promise<DocumentMeta | undefined> {
579
- return (await this.records.findOne({ _id: id }))?.meta;
1019
+ return (await this.records.findOne({ _id: id, writing: { $exists: false } }))?.meta;
580
1020
  }
581
1021
 
582
1022
  async get(id: string): Promise<StoredDocument | undefined> {
@@ -617,7 +1057,7 @@ export class BlobDocumentStore implements DocumentStore {
617
1057
 
618
1058
  /** The record first: if removing it fails, nothing else is touched and the document stays whole. */
619
1059
  async delete(id: string): Promise<boolean> {
620
- if (!DOCUMENT_ID_PATTERN.test(id)) return false;
1060
+ if (!APP_DOCUMENT_ID_PATTERN.test(id)) return false;
621
1061
  const { deletedCount } = await this.records.deleteOne({ _id: id });
622
1062
  // Also what a failed ingest left behind: an original or an index without a record.
623
1063
  await Promise.all((["txt", "idx", "bin"] as const).map((kind) => this.blobs.remove(this.key(id, kind))));
@@ -655,9 +1095,23 @@ export const files = createLargeFiles({
655
1095
  ```
656
1096
 
657
1097
  - Reads let their errors through: the library turns them into a `DocumentStoreError`. Writes log
658
- theirs, then turn them into an error with status 503 and a message of their own, so an upload that
659
- meets a database that is down is answered 503 "The file could not be stored. Try again.", not 500
660
- "Upload failed.".
1098
+ theirs, then throw. Since 0.9.0 the library turns them into a `DocumentStoreError` too, so an
1099
+ upload that meets a database that is down is answered 503 "The document could not be stored. Try
1100
+ again.", with `Retry-After: 5`, whatever the store's own error says.
1101
+ - `put` inserts the record first, marked `writing`, and `getMeta` does not see it until the text is
1102
+ written. When two servers ingest one ID at the same moment, the one whose insert fails has written
1103
+ no text. Its index and its original were written before `put`, so they can still land over the
1104
+ other's. The library checks both: an index that does not match the metadata is built again from
1105
+ the text, and an original of another size or SHA-256 reads as missing.
1106
+ - While one server's record is still marked, another server's ingest of that ID cannot see it. Its
1107
+ insert fails, and its clean-up finds nothing with `getMeta`, so it calls `delete`, which removes
1108
+ the marked record and its text. Both ingests then fail with a 503, even for one upload sent twice,
1109
+ and nothing wrong is served. If the first `put` ended between that look and the `delete`, its
1110
+ document is removed after its 201 and reads as missing. An ID of its own for each upload, as
1111
+ `attach()` makes, avoids all of this.
1112
+ - A record left marked by a server that stopped in the middle of a `put` is not a document. `sweep`
1113
+ removes it once it has expired. A later ingest of that ID fails once with a 503, and removes it as
1114
+ it cleans up.
661
1115
  - `delete` removes the record first. If removing an object fails after that, the document is gone
662
1116
  and the object stays behind. A lifecycle rule on the bucket that removes objects under the prefix
663
1117
  some time after `ttlMs` cleans those up, when `ttlMs` is finite.
@@ -668,23 +1122,48 @@ export const files = createLargeFiles({
668
1122
 
669
1123
  ### Checking your store
670
1124
 
671
- Before you trust a store with users' files, check these with the library over it:
1125
+ `documentStoreChecks` from `llm-large-files/testing` (new in 0.9.0) checks a store against this
1126
+ page: copies of the metadata, fields it does not know, `null` for a field left out, expiry, every
1127
+ part removed by `delete`, ranges across multi-byte characters, the index, the original byte for
1128
+ byte, the sweep's clock, the application's IDs, the context on every call, scopes kept apart, two
1129
+ servers over one storage, and the library over the store against `MemoryDocumentStore`. Run them
1130
+ in your tests:
1131
+
1132
+ ```ts
1133
+ // blob-document-store.test.ts, with Vitest. Jest: the same with `test`. node:test:
1134
+ // test(check.name, { timeout: check.timeoutMs }, check.run).
1135
+ import { it } from "vitest";
1136
+ import { documentStoreChecks } from "llm-large-files/testing";
1137
+ import { BlobDocumentStore } from "./blob-document-store.js";
1138
+ import { blobsFor, recordsFor, dropStorage } from "./test-storage.js"; // a bucket prefix and a collection for each name
1139
+
1140
+ for (const check of documentStoreChecks({
1141
+ create: ({ storage }) => new BlobDocumentStore(blobsFor(storage), recordsFor(storage)),
1142
+ dispose: (_store, { storage }) => dropStorage(storage),
1143
+ })) it(check.name, check.run, check.timeoutMs);
1144
+ ```
1145
+
1146
+ - `create` makes a store over new storage for each check, named by `storage`. Called twice with
1147
+ the same name, it must give two stores over the same storage, as two servers.
1148
+ - Say what your store does: `isolatesScopes: true` if it keeps the documents of each scope apart,
1149
+ `requiresScope: true` if it refuses a call without a scope, and `skip` for the parts it does not
1150
+ have (`"originals"`, `"ranges"`, `"index"`, `"sweep"`, `"shared"`).
1151
+ - A failed check says what it expected and what came back. The options and every check are in
1152
+ [the reference](../reference/testing.md#documentstorechecksoptions).
1153
+
1154
+ The library's own tests run them on `MemoryDocumentStore`, `FileDocumentStore` in one folder, and
1155
+ `FileDocumentStore` with `scopes`.
1156
+
1157
+ What the checks cannot do for you, by hand:
672
1158
 
673
- - A file ingested, then `prepare` and a `search_document` call give the same results as with
674
- `MemoryDocumentStore`. Do it once more with `wholeDocumentBytes: 0`, which reads every document by
675
- range.
676
1159
  - With the database stopped, `files.getMeta(id)` rejects with a `DocumentStoreError` instead of
677
1160
  giving undefined, and a tool call answers "The document store could not be read. Try again.",
678
1161
  with a code in parentheses when your error has one.
679
- - A text file that is not UTF-8, such as a CSV saved by Excel in windows-1255, is ingested, and
680
- `files.getMeta(id)` gives back its `encoding` (and `replacedCharacters`, for a UTF-8 log cut at a
681
- byte count): your store keeps fields it does not know.
682
1162
  - With a write that fails, `files.ingest` throws, and leaves no record and no object behind.
683
- - `files.delete` removes every part. `getMeta` then gives undefined, and a second delete gives false.
684
- - With a clock past `expiresAt` (the `now` option of `createLargeFiles`), `files.sweep()` removes
685
- the document, every part of it, and counts it.
686
- - `readTextRange(id, size, size + 10)` gives an empty array, where `size` is `meta.textBytes`.
687
- - With `keepOriginals`, `files.getOriginal` gives the uploaded bytes, byte for byte.
1163
+ - A text file that is not UTF-8, such as a CSV saved by Excel in windows-1255, is ingested, and
1164
+ `files.getMeta(id)` gives back its `encoding`. A schema of your database may refuse fields the
1165
+ checks' metadata does not have.
1166
+ - An expired document whose removal fails is still read as missing.
688
1167
 
689
1168
  ## The cache
690
1169
 
@@ -704,7 +1183,16 @@ just those lines.
704
1183
  - The cache never decides whether a document exists. Every use asks the store first (`getMeta`), so
705
1184
  a document deleted or expired on another server is never served from memory here. A kept copy is
706
1185
  used only while the store describes the same text (the same `createdAt`, size, characters and
707
- lines), so a store restored from a backup is read again.
1186
+ lines), so a store restored from a backup is read again. Since 0.9.0 it must also be of the same
1187
+ owner and scope: a document stored under a reused [application's ID](#application-ids) by another
1188
+ owner is read again, even within the same millisecond and with a text of the same size.
1189
+ - A document loaded whole is used only when the document `get` returns is the one `getMeta`
1190
+ described, of the same owner, scope and version (new in 0.9.0). If another server replaced it in
1191
+ between, it is missing for this call.
1192
+ - A document read by range is checked after its reads instead (new in 0.9.0): once a tool call or
1193
+ `prepare` has read it, the store is asked again (`getMeta`). If it no longer describes the same
1194
+ document, the call answers that the document is no longer available, and the copy kept of it, its
1195
+ pieces included, is forgotten.
708
1196
  - A document loaded whole takes, once searched, about twice its size in memory when its text is all
709
1197
  ASCII, and four bytes a character otherwise: the text and a lowercased copy.
710
1198
  - A document read by range keeps its line index in memory, about 8 bytes a line, and, within