llm-large-files 0.10.0 → 0.10.2

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 (62) hide show
  1. package/CHANGELOG.md +136 -7
  2. package/dist/ask.d.ts +16 -0
  3. package/dist/ask.d.ts.map +1 -1
  4. package/dist/ask.js +26 -2
  5. package/dist/ask.js.map +1 -1
  6. package/dist/cache.d.ts +27 -1
  7. package/dist/cache.d.ts.map +1 -1
  8. package/dist/cache.js +96 -21
  9. package/dist/cache.js.map +1 -1
  10. package/dist/citations.d.ts.map +1 -1
  11. package/dist/citations.js +14 -7
  12. package/dist/citations.js.map +1 -1
  13. package/dist/events.d.ts +2 -1
  14. package/dist/events.d.ts.map +1 -1
  15. package/dist/events.js.map +1 -1
  16. package/dist/index.d.ts +3 -3
  17. package/dist/index.d.ts.map +1 -1
  18. package/dist/index.js +2 -2
  19. package/dist/index.js.map +1 -1
  20. package/dist/ingest.d.ts +12 -1
  21. package/dist/ingest.d.ts.map +1 -1
  22. package/dist/ingest.js +146 -11
  23. package/dist/ingest.js.map +1 -1
  24. package/dist/library.d.ts +55 -5
  25. package/dist/library.d.ts.map +1 -1
  26. package/dist/library.js +74 -4
  27. package/dist/library.js.map +1 -1
  28. package/dist/stores.d.ts +38 -1
  29. package/dist/stores.d.ts.map +1 -1
  30. package/dist/stores.js +184 -6
  31. package/dist/stores.js.map +1 -1
  32. package/dist/testing/store-checks.d.ts +8 -3
  33. package/dist/testing/store-checks.d.ts.map +1 -1
  34. package/dist/testing/store-checks.js +74 -1
  35. package/dist/testing/store-checks.js.map +1 -1
  36. package/dist/types.d.ts +56 -0
  37. package/dist/types.d.ts.map +1 -1
  38. package/docs/guides/costs-and-limits.md +3 -2
  39. package/docs/guides/deployment.md +3 -3
  40. package/docs/guides/errors-and-reliability.md +2 -1
  41. package/docs/guides/storage.md +62 -8
  42. package/docs/guides/vertex-and-gemini.md +1 -1
  43. package/docs/measurements.md +4 -4
  44. package/docs/reference/ask.md +30 -6
  45. package/docs/reference/events.md +1 -1
  46. package/docs/reference/gemini.md +9 -4
  47. package/docs/reference/library.md +106 -11
  48. package/docs/reference/testing.md +10 -4
  49. package/docs/reference/tools.md +4 -2
  50. package/docs/security.md +2 -1
  51. package/docs/upgrading-0.10.md +27 -15
  52. package/package.json +1 -1
  53. package/src/ask.ts +35 -2
  54. package/src/cache.ts +95 -19
  55. package/src/citations.ts +14 -7
  56. package/src/events.ts +2 -1
  57. package/src/index.ts +3 -3
  58. package/src/ingest.ts +144 -12
  59. package/src/library.ts +122 -8
  60. package/src/stores.ts +174 -7
  61. package/src/testing/store-checks.ts +74 -3
  62. package/src/types.ts +55 -0
package/src/cache.ts CHANGED
@@ -36,10 +36,18 @@ export function documentVersion(meta: DocumentMeta): string {
36
36
  * not served from here.
37
37
  */
38
38
  export class DocumentCache<T extends Sized> {
39
- private readonly entries = new Map<string, { version: string; value: T; bytes: number; owner?: string }>();
39
+ private readonly entries = new Map<string, { version: string; value: T; bytes: number; owner?: string; used: number }>();
40
+ /** A count of uses, to tell which of the documents and the one kept apart was used longest ago. */
41
+ private uses = 0;
40
42
  /** Entries that belong to no other: the documents. */
41
43
  private documents = 0;
42
44
  private total = 0;
45
+ /**
46
+ * The last document larger than the whole cache, kept apart for `OVERSIZE_KEEP_MS` after its
47
+ * last use (P4, 0.10.2): the tool calls of one question that read it again do not each load and
48
+ * index it again, as they did over a store without `readTextRange`. One at most.
49
+ */
50
+ private oversize: { id: string; version: string; value: T; bytes: number; timer: ReturnType<typeof setTimeout>; used: number } | undefined;
43
51
 
44
52
  constructor(
45
53
  private readonly maxBytes: number,
@@ -47,9 +55,9 @@ export class DocumentCache<T extends Sized> {
47
55
  private readonly maxEntries = Number.POSITIVE_INFINITY,
48
56
  ) {}
49
57
 
50
- /** Memory taken by the cached documents, by their own estimate. */
58
+ /** Memory taken by the cached documents, by their own estimate: the last oversize document too. */
51
59
  get bytes(): number {
52
- return this.total;
60
+ return this.total + (this.oversize?.bytes ?? 0);
53
61
  }
54
62
 
55
63
  get size(): number {
@@ -58,13 +66,14 @@ export class DocumentCache<T extends Sized> {
58
66
 
59
67
  get(id: string, version: string): T | undefined {
60
68
  const entry = this.entries.get(id);
61
- if (!entry) return undefined;
69
+ if (!entry) return this.lastOversize(id, version);
62
70
  if (entry.version !== version) {
63
71
  this.delete(id);
64
72
  return undefined;
65
73
  }
66
74
  // Most recently used last.
67
75
  this.entries.delete(id);
76
+ entry.used = ++this.uses;
68
77
  this.entries.set(id, entry);
69
78
  return entry.value;
70
79
  }
@@ -78,23 +87,19 @@ export class DocumentCache<T extends Sized> {
78
87
  if (existing?.value === value && existing.version === version) return;
79
88
  this.delete(id);
80
89
  const bytes = Math.max(0, value.memoryBytes);
81
- if (bytes > this.maxBytes || this.maxEntries < 1) return;
82
- this.entries.set(id, { version, value, bytes, ...(owner !== undefined ? { owner } : {}) });
83
- this.total += bytes;
84
- if (owner === undefined) this.documents++;
85
- // One document too many: the one used longest ago goes, with what belongs to it.
86
- while (this.documents > this.maxEntries) {
87
- let oldest: string | undefined;
88
- for (const [key, entry] of this.entries) {
89
- if (entry.owner === undefined) {
90
- oldest = key;
91
- break;
92
- }
90
+ if (this.maxEntries < 1) return;
91
+ if (bytes > this.maxBytes) {
92
+ // A document (not a piece), with a cache that keeps any: the last one is kept apart.
93
+ if (owner === undefined && this.maxBytes > 0) {
94
+ this.keepOversize(id, version, value, bytes);
95
+ this.withinEntries();
93
96
  }
94
- if (oldest === undefined) break;
95
- this.delete(oldest);
96
- for (const [key, entry] of [...this.entries]) if (entry.owner === oldest) this.delete(key);
97
+ return;
97
98
  }
99
+ this.entries.set(id, { version, value, bytes, ...(owner !== undefined ? { owner } : {}), used: ++this.uses });
100
+ this.total += bytes;
101
+ if (owner === undefined) this.documents++;
102
+ this.withinEntries();
98
103
  // Too much memory: the entries used longest ago go, whatever they are.
99
104
  for (const [oldest] of this.entries) {
100
105
  if (this.total <= this.maxBytes) break;
@@ -103,6 +108,7 @@ export class DocumentCache<T extends Sized> {
103
108
  }
104
109
 
105
110
  delete(id: string): void {
111
+ if (this.oversize?.id === id) this.dropOversize();
106
112
  const entry = this.entries.get(id);
107
113
  if (!entry) return;
108
114
  this.entries.delete(id);
@@ -117,6 +123,76 @@ export class DocumentCache<T extends Sized> {
117
123
 
118
124
  /** Drops every entry whose key passes `test`: one document in every scope, with its pieces. */
119
125
  deleteWhere(test: (key: string) => boolean): void {
126
+ if (this.oversize && test(this.oversize.id)) this.dropOversize();
120
127
  for (const key of [...this.entries.keys()]) if (test(key)) this.delete(key);
121
128
  }
129
+
130
+ /**
131
+ * Within `maxEntries` documents, the one kept apart counted (`cacheSize`): one too many, the
132
+ * document used longest ago goes, with what belongs to it, whether it is one of the others or the
133
+ * one kept apart.
134
+ */
135
+ private withinEntries(): void {
136
+ while (this.documents + (this.oversize ? 1 : 0) > this.maxEntries) {
137
+ let oldest: string | undefined;
138
+ for (const [key, entry] of this.entries) {
139
+ if (entry.owner === undefined) {
140
+ oldest = key;
141
+ break;
142
+ }
143
+ }
144
+ const apart = this.oversize;
145
+ if (oldest === undefined || (apart && apart.used < this.entries.get(oldest)!.used)) {
146
+ this.dropOversize();
147
+ if (oldest === undefined) break;
148
+ continue;
149
+ }
150
+ this.delete(oldest);
151
+ for (const [key, entry] of [...this.entries]) if (entry.owner === oldest) this.delete(key);
152
+ }
153
+ }
154
+
155
+ /** The last oversize document, when it is this one: its time is counted again from now. */
156
+ private lastOversize(id: string, version: string): T | undefined {
157
+ const kept = this.oversize;
158
+ if (kept?.id !== id) return undefined;
159
+ if (kept.version !== version) {
160
+ this.dropOversize();
161
+ return undefined;
162
+ }
163
+ kept.timer = this.oversizeTimer(kept.timer);
164
+ kept.used = ++this.uses;
165
+ return kept.value;
166
+ }
167
+
168
+ private keepOversize(id: string, version: string, value: T, bytes: number): void {
169
+ this.dropOversize();
170
+ this.oversize = { id, version, value, bytes, timer: this.oversizeTimer(), used: ++this.uses };
171
+ }
172
+
173
+ /**
174
+ * The timer that lets the document kept apart go: `timer` counted again from now, or a new one.
175
+ * It does not keep the process alive, and it holds the cache weakly: a library let go of with a
176
+ * document kept apart is collected at once, not a minute later with everything it kept.
177
+ */
178
+ private oversizeTimer(timer?: ReturnType<typeof setTimeout>): ReturnType<typeof setTimeout> {
179
+ if (timer && typeof timer.refresh === "function") {
180
+ timer.refresh();
181
+ return timer;
182
+ }
183
+ if (timer) clearTimeout(timer);
184
+ const cache = new WeakRef(this);
185
+ const next = setTimeout(() => cache.deref()?.dropOversize(), OVERSIZE_KEEP_MS);
186
+ next.unref?.();
187
+ return next;
188
+ }
189
+
190
+ private dropOversize(): void {
191
+ if (!this.oversize) return;
192
+ clearTimeout(this.oversize.timer);
193
+ this.oversize = undefined;
194
+ }
122
195
  }
196
+
197
+ /** How long the last document larger than the whole cache is kept after its last use (P4). New in 0.10.2. */
198
+ export const OVERSIZE_KEEP_MS = 60_000;
package/src/citations.ts CHANGED
@@ -37,20 +37,27 @@ const EDGE_AFTER = String.raw`(?![\p{L}\p{N}_])`;
37
37
  const RANGE_END = String.raw`(?:\s*[-–—־]\s*|\s+(?:to|עד)\s+)`;
38
38
  /** "L" or "l", and a space at most, before a line number: "L12", "l12", "L 12". */
39
39
  const LINE_LETTER = String.raw`[Ll][  ]?`;
40
+ /**
41
+ * A line number: digits, or digits in groups of three after commas ("1,200", "12,345,678"), as a
42
+ * model writes a large number. "L12,14" is line 12, then something else: a group has three digits.
43
+ */
44
+ const NUMBER = String.raw`(\d{1,3}(?:,\d{3}){1,2}|\d{1,9})`;
45
+ /** The value of a line number as `NUMBER` reads it: its commas left out. */
46
+ const numberOf = (written: string) => Number(written.replaceAll(",", ""));
40
47
 
41
48
  /**
42
49
  * The forms of a citation, each with the numbers it names:
43
- * - "L12", "L12-14", "L12-L14", "L 12", "l12": lines, as the tools and the closing request write them;
50
+ * - "L12", "L12-14", "L12-L14", "L 12", "l12", "L1,200": lines, as the tools and the closing request write them;
44
51
  * - "line 12", "lines 12-14": lines, in words;
45
52
  * - "Row 12": a row, which for a workbook may be Excel's row and not a line;
46
53
  * - "שורה 12", "שורות 12-14", with a prefix letter ("בשורה 12") or "מס'": in Hebrew "שורה" is
47
54
  * both a line and a row.
48
55
  */
49
56
  const FORMS: Array<{ pattern: RegExp; form: "line" | "row"; bare: boolean }> = [
50
- { pattern: new RegExp(String.raw`${EDGE_BEFORE}${LINE_LETTER}(\d{1,9})(?:${RANGE_END}(?:${LINE_LETTER})?(\d{1,9}))?${EDGE_AFTER}`, "gu"), form: "line", bare: true },
51
- { pattern: new RegExp(String.raw`${EDGE_BEFORE}[Ll]ines?\s+(\d{1,9})(?:${RANGE_END}(\d{1,9}))?${EDGE_AFTER}`, "gu"), form: "line", bare: false },
52
- { pattern: new RegExp(String.raw`${EDGE_BEFORE}[Rr]ows?\s+(\d{1,9})(?:${RANGE_END}(\d{1,9}))?${EDGE_AFTER}`, "gu"), form: "row", bare: false },
53
- { pattern: new RegExp(String.raw`${EDGE_BEFORE}[בלמוהכש]{0,2}שור(?:ה|ות)\s+(?:(?:מס['׳]?|מספר)\s*)?(\d{1,9})(?:${RANGE_END}(\d{1,9}))?${EDGE_AFTER}`, "gu"), form: "row", bare: false },
57
+ { pattern: new RegExp(String.raw`${EDGE_BEFORE}${LINE_LETTER}${NUMBER}(?:${RANGE_END}(?:${LINE_LETTER})?${NUMBER})?${EDGE_AFTER}`, "gu"), form: "line", bare: true },
58
+ { pattern: new RegExp(String.raw`${EDGE_BEFORE}[Ll]ines?\s+${NUMBER}(?:${RANGE_END}${NUMBER})?${EDGE_AFTER}`, "gu"), form: "line", bare: false },
59
+ { pattern: new RegExp(String.raw`${EDGE_BEFORE}[Rr]ows?\s+${NUMBER}(?:${RANGE_END}${NUMBER})?${EDGE_AFTER}`, "gu"), form: "row", bare: false },
60
+ { pattern: new RegExp(String.raw`${EDGE_BEFORE}[בלמוהכש]{0,2}שור(?:ה|ות)\s+(?:(?:מס['׳]?|מספר)\s*)?${NUMBER}(?:${RANGE_END}${NUMBER})?${EDGE_AFTER}`, "gu"), form: "row", bare: false },
54
61
  ];
55
62
 
56
63
  /** How far, in characters on one line, a file name may be from the citation it goes with. */
@@ -100,8 +107,8 @@ function citationsIn(text: string): Cited[] {
100
107
  const end = start + match[0].length;
101
108
  while (next < kept.length && kept[next]!.end <= start) next++;
102
109
  if (next < kept.length && kept[next]!.start < end) continue;
103
- const first = Number(match[1]);
104
- const second = match[2] === undefined ? first : Number(match[2]);
110
+ const first = numberOf(match[1]!);
111
+ const second = match[2] === undefined ? first : numberOf(match[2]);
105
112
  if (first < 1 || second < 1) continue;
106
113
  added.push({ start, end, from: Math.min(first, second), to: Math.max(first, second), form, bare });
107
114
  }
package/src/events.ts CHANGED
@@ -79,7 +79,8 @@ export type RequestPurpose = "turn" | "nudge" | "closing" | "answer_again" | "di
79
79
  * - "error": it ran, or was checked, and returned `{ error }` (bad arguments, a document it cannot
80
80
  * read, a regex that took too long…), or it was ended because its turn failed (the question was
81
81
  * stopped, or a listener threw): then the model was sent nothing;
82
- * - "refused": it was not run, for a limit of the question (cost, room, reads of a whole file);
82
+ * - "refused": it was not run: for a limit of the question (cost, room, reads of a whole file), a
83
+ * tool the question does not have (since 0.10.0), or a `{ reject }` of `onToolResult` (0.10.0);
83
84
  * - "already_shown": it repeated a call whose result is still in the conversation, and was answered
84
85
  * with a pointer to it;
85
86
  * - "not_run": the turn had more calls than `limits.callsPerTurn`;
package/src/index.ts CHANGED
@@ -1,11 +1,11 @@
1
1
  // Core: provider-neutral. The tool loop is `askWithFiles`, and a model provider is an adapter:
2
2
  // "llm-large-files/gemini", "llm-large-files/openai", "llm-large-files/anthropic", or your own.
3
3
  // Node HTTP handlers are in "llm-large-files/node".
4
- export { createLargeFiles, DEFAULT_CACHE_BYTES, DEFAULT_INGEST_TIMEOUT_MS, DEFAULT_MAX_PDF_PAGES, DEFAULT_MAX_TEXT_BYTES, DEFAULT_WHOLE_DOCUMENT_BYTES, isDocumentId, NEVER_EXPIRES, toDocumentSummary } from "./library.js";
4
+ export { createLargeFiles, DEFAULT_CACHE_BYTES, DEFAULT_INGEST_TIMEOUT_MS, DEFAULT_MAX_PDF_PAGES, DEFAULT_MAX_TEXT_BYTES, DEFAULT_WHOLE_DOCUMENT_BYTES, isDocumentId, MAX_APP_DATA_BYTES, NEVER_EXPIRES, toDocumentSummary } from "./library.js";
5
5
  export type { AccessOptions, CreatedLargeFiles, IngestFromSource, IngestInput, IngestSource, LargeFiles, LargeFilesOptions, LargeFilesStats, OriginalReadContext, OriginalsReader, PrepareOptions, ToolOptions } from "./library.js";
6
6
  export { DEFAULT_BUDGET, resolveBudget } from "./budget.js";
7
7
  export type { ModelLimits } from "./budget.js";
8
- export { askStream, askWithFiles, DEFAULT_INPUT_TOKENS, EXPLORER_INSTRUCTION, FINAL_ANSWER_AFTER_PAGES, FINAL_ANSWER_REQUEST, FINAL_ANSWER_WITHOUT_TOOLS, partialResultOf } from "./ask.js";
8
+ export { askStream, askWithFiles, compactToolTurns, DEFAULT_INPUT_TOKENS, EXPLORER_INSTRUCTION, FINAL_ANSWER_AFTER_PAGES, FINAL_ANSWER_REQUEST, FINAL_ANSWER_WITHOUT_TOOLS, partialResultOf } from "./ask.js";
9
9
  export type { AskLimits, AskOptions, AskResult, MissingDocumentsAction, MissingDocumentsContext, ToolResultContext, ToolResultVerdict } from "./ask.js";
10
10
  export * from "./answer-info.js";
11
11
  export * from "./citations.js";
@@ -54,7 +54,7 @@ export type { RetryNotice, RetryOptions } from "./retry.js";
54
54
  export { parseSseJson, SseEventTooLongError } from "./sse.js";
55
55
  export type { SseHooks } from "./sse.js";
56
56
  export { DEFAULT_FIRST_BYTE_TIMEOUT_MS, DEFAULT_IDLE_TIMEOUT_MS } from "./http.js";
57
- export type { IdleWaits } from "./http.js";
57
+ export type { HeaderContext, HeaderSource, IdleWaits } from "./http.js";
58
58
  export { DocumentScopeError, DocumentStoreError, IngestError, ingestErrorCodeOf } from "./errors.js";
59
59
  export type { DocumentScopeErrorCode, DocumentStoreOperation, IngestErrorCode } from "./errors.js";
60
60
  export { errorInfoOf } from "./error-info.js";
package/src/ingest.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  // `files.ingest`: reads a file, prepares its text, and stores it. Moved out of library.ts in 0.9.0:
2
2
  // the library hands it what it needs in an `IngestContext`.
3
3
  import { randomUUID } from "node:crypto";
4
- import { checkMetaVersion, checkOwner, checkStuck, formatDuration, heldBy, metaOf, OWNER_REQUIRED, SCOPE_REQUIRED, storeCall, storeContext, watchStuck, type AccessRules } from "./access.js";
4
+ import { checkMetaVersion, checkOwner, checkStuck, formatDuration, heldBy, isTimeLimit, metaOf, OWNER_REQUIRED, SCOPE_REQUIRED, storeCall, storeContext, watchStuck, type AccessRules } from "./access.js";
5
5
  import { buildLogProfileInSlices, buildOutlineInSlices, looksLikeLog } from "./analyze.js";
6
6
  import { DocumentScopeError, DocumentStoreError, IngestError, isStoreWriteFailure, noteStoreWriteFailure, toIngestError } from "./errors.js";
7
7
  import { EventEmitter, eventErrorOf, newRunId, type EventError, type IngestEvent, type IngestStage } from "./events.js";
@@ -14,10 +14,10 @@ import { formatBytes } from "./plan.js";
14
14
  import { measureQuality, type TextQuality } from "./quality.js";
15
15
  import { checkScope } from "./scope.js";
16
16
  import { absolutePath, isSha256, readRanges, readSource, sha256InSlices, statSource, type SourceRead } from "./source.js";
17
- import { APP_DOCUMENT_ID_PATTERN, DOCUMENT_META_VERSION } from "./stores.js";
17
+ import { APP_DOCUMENT_ID_PATTERN, DOCUMENT_META_VERSION, usableStoreMethod } from "./stores.js";
18
18
  import { buildTextIndexInSlices, canSerialize, serializeTextIndex } from "./text-index.js";
19
19
  import { measureText, prepareText, removeInvisible, sliceWhole } from "./text.js";
20
- import type { DocumentContext, DocumentFormat, DocumentMeta, DocumentScope, DocumentStore, DocumentSummary, ExtractedText, ExtractProgress, Extractor } from "./types.js";
20
+ import type { AppData, DocumentContext, DocumentFormat, DocumentMeta, DocumentScope, DocumentStore, DocumentSummary, ExtractedText, ExtractProgress, Extractor } from "./types.js";
21
21
 
22
22
  export { checkOwner } from "./access.js";
23
23
 
@@ -77,6 +77,10 @@ type Target = {
77
77
  readonly scope: DocumentScope | undefined;
78
78
  /** The context of every store call of the ingest. */
79
79
  readonly context: DocumentContext;
80
+ /** `IngestInput.appData`, checked and copied (0.10.2). */
81
+ readonly appData?: AppData;
82
+ /** `IngestInput.dedupe` (0.10.2). */
83
+ readonly dedupe: boolean;
80
84
  };
81
85
 
82
86
  /** The TypeError of an `IngestInput.id` of another shape. It does not repeat the ID, which may hold what it must not. */
@@ -91,7 +95,13 @@ function targetOf(input: IngestInput | IngestFromSource, rules: AccessRules): Ta
91
95
  const { id, ifExists = "fail" } = input;
92
96
  if (id !== undefined && (typeof id !== "string" || !APP_DOCUMENT_ID_PATTERN.test(id))) throw new TypeError(ID_SHAPE);
93
97
  if (ifExists !== "fail" && ifExists !== "replace") throw new TypeError('ifExists must be "fail" or "replace".');
94
- return { id, ifExists, owner: input.owner, scope, context: storeContext(scope, input.owner) };
98
+ // Null is none, as a database gives a field that was left out.
99
+ const given: unknown = input.appData ?? undefined;
100
+ const appData = given === undefined ? undefined : checkAppData(given, "appData");
101
+ const dedupe: unknown = input.dedupe ?? false;
102
+ if (typeof dedupe !== "boolean") throw new TypeError("dedupe must be true or false.");
103
+ if (dedupe && id !== undefined) throw new TypeError("dedupe and id cannot be given together: an application's ID names its own document.");
104
+ return { id, ifExists, owner: input.owner, scope, context: storeContext(scope, input.owner), ...(appData !== undefined ? { appData } : {}), dedupe };
95
105
  }
96
106
 
97
107
  /** The refusal of an application's ID that is taken (`ifExists`). It says nothing of the document that has it. */
@@ -121,6 +131,47 @@ async function claim(context: IngestContext, target: Target & { id: string }, na
121
131
  throw exists(name);
122
132
  }
123
133
 
134
+ /**
135
+ * The document of the same owner and scope whose file has this SHA-256 (`IngestInput.dedupe`), as
136
+ * the store lists them (`list`), when its text is still there: the latest stored, when several
137
+ * are. Expired documents (as `getMeta` reads the date), and those of a newer version, are not it.
138
+ * Its expiry is counted again from now when the store can change metadata alone (`patchMeta`), as
139
+ * `files.touch` does; a document the store then says is gone (deleted meanwhile) is not it either,
140
+ * and the next one is tried. Undefined when there is none. Each store call is refused at once while too many calls are stuck, and
141
+ * counts as stuck past `slotCapMs`, as the look-up of an application's ID does. New in 0.10.2.
142
+ */
143
+ async function sameDocument(context: IngestContext, target: Target, sha256: string): Promise<DocumentMeta | undefined> {
144
+ const { store, now, ttlMs, maxStuck, slotCapMs } = context;
145
+ const call = <T>(operation: "read" | "write", run: () => Promise<T>) => watchStuck(storeCall(operation, run, { maxStuck }), slotCapMs);
146
+ const list = usableStoreMethod(store, "list")!;
147
+ const listed: unknown = await call("read", () => list.call(store, target.context));
148
+ const at = now().getTime();
149
+ const candidates: DocumentMeta[] = [];
150
+ for (const item of Array.isArray(listed) ? listed : []) {
151
+ const meta = metaOf(item as DocumentMeta, (item as { id?: unknown } | null)?.id as string);
152
+ if (!meta || typeof meta.id !== "string" || !APP_DOCUMENT_ID_PATTERN.test(meta.id) || meta.sha256 !== sha256 || Date.parse(meta.expiresAt) <= at || !heldBy(meta, target.owner, target.scope)) continue;
153
+ const version: unknown = meta.metaVersion ?? 0;
154
+ if (typeof version === "number" && version <= DOCUMENT_META_VERSION) candidates.push(meta);
155
+ }
156
+ // The latest first: an older copy may be on its way out.
157
+ candidates.sort((left, right) => Date.parse(right.createdAt) - Date.parse(left.createdAt));
158
+ for (const meta of candidates) {
159
+ // Metadata whose text is gone is not a document: a byte of the text, or the whole text from a
160
+ // store that cannot read a range.
161
+ const there = typeof store.readTextRange === "function"
162
+ ? await call("read", () => store.readTextRange!(meta.id, 0, 1, target.context)) !== undefined
163
+ : await call("read", () => store.get(meta.id, target.context)) !== undefined;
164
+ if (!there) continue;
165
+ const patchMeta = usableStoreMethod(store, "patchMeta");
166
+ if (!patchMeta) return meta;
167
+ // The document of that `createdAt` only: one deleted and stored again under the ID is not it.
168
+ const one = { createdAt: meta.createdAt, ...(meta.owner !== undefined ? { owner: meta.owner } : {}), ...(meta.scope !== undefined ? { scope: meta.scope } : {}) };
169
+ const touched = metaOf(await call("write", () => patchMeta.call(store, meta.id, { ...one, expiresAt: expiryAfter(now(), ttlMs) }, target.context)), meta.id);
170
+ if (touched && touched.createdAt === meta.createdAt && heldBy(touched, target.owner, target.scope)) return touched;
171
+ }
172
+ return undefined;
173
+ }
174
+
124
175
  /**
125
176
  * Removes what an ingest wrote under its ID, after a write that failed or a listener that threw on
126
177
  * `ingest.finish`: only while the document there, if any, is the ingest's own (the same `createdAt`,
@@ -319,6 +370,37 @@ function fileOf(extracted: ExtractedText): { bytes: number; sha256: string } | u
319
370
  */
320
371
  export const NEVER_EXPIRES = "9999-12-31T23:59:59.999Z";
321
372
 
373
+ /** The expiry of a document stored, or used, at `at`: `ttlMs` later, or `NEVER_EXPIRES` past what a date can hold. */
374
+ export function expiryAfter(at: Date, ttlMs: number): string {
375
+ const expires = at.getTime() + ttlMs;
376
+ return expires >= Date.parse(NEVER_EXPIRES) ? NEVER_EXPIRES : new Date(expires).toISOString();
377
+ }
378
+
379
+ /** The most bytes `DocumentMeta.appData` may take, as JSON in UTF-8: 16 KB. New in 0.10.2. */
380
+ export const MAX_APP_DATA_BYTES = 16_384;
381
+
382
+ /**
383
+ * `appData` checked, and copied through JSON, as a store that keeps it as JSON gives it back. A
384
+ * value that is not an object (an array, a string, null), or that JSON cannot write (a BigInt, a
385
+ * loop), is a TypeError; one larger than `MAX_APP_DATA_BYTES` as JSON, a RangeError. What JSON
386
+ * leaves out (a function, undefined) is left out. `where` names the option in the message.
387
+ */
388
+ export function checkAppData(value: unknown, where: string): AppData {
389
+ const shape = `${where} must be a JSON object, such as { "rowId": "42" }`;
390
+ if (typeof value !== "object" || value === null || Array.isArray(value)) throw new TypeError(`${shape}.`);
391
+ let json: unknown;
392
+ try {
393
+ json = JSON.stringify(value);
394
+ } catch (error) {
395
+ throw new TypeError(`${shape}: ${error instanceof Error ? error.message : String(error)}`);
396
+ }
397
+ // A toJSON of its own may turn it into something else.
398
+ if (typeof json !== "string" || !json.startsWith("{")) throw new TypeError(`${shape}.`);
399
+ const bytes = Buffer.byteLength(json);
400
+ if (bytes > MAX_APP_DATA_BYTES) throw new RangeError(`${where} takes ${bytes} bytes as JSON; it may take ${MAX_APP_DATA_BYTES}.`);
401
+ return JSON.parse(json) as AppData;
402
+ }
403
+
322
404
  /** The refusal of a file whose text is larger than `maxTextBytes`. */
323
405
  const tooMuchText = (name: string, maxTextBytes: number) =>
324
406
  new Error(`${name} holds more than ${formatBytes(maxTextBytes)} of text, more than is kept from one file. Split it, and attach the part you need.`);
@@ -347,6 +429,9 @@ function settleWithin<T>(work: Promise<T>, ms: number, late: () => Error): Promi
347
429
  * itself cannot be stopped; it holds no turn.
348
430
  */
349
431
  function lookWithin<T>(look: Promise<T>, signal: AbortSignal | undefined, ms: number, syscall: "lstat" | "read"): Promise<T> {
432
+ // Counted as stuck past `ms`, as a store call is, until it ends (0.10.2): a volume that does not
433
+ // answer holds a thread of the pool either way.
434
+ watchStuck(look, ms);
350
435
  return settleWithin(signal ? untilAborted(look, signal) : look, ms, () =>
351
436
  Object.assign(new Error(`The file to ingest did not answer within ${formatDuration(ms)}.`), { code: "ETIMEDOUT", syscall }));
352
437
  }
@@ -530,6 +615,11 @@ type IngestWork = {
530
615
  * stays held in `ingesting` until they have ended, since they may still land.
531
616
  */
532
617
  writes?: Promise<unknown>;
618
+ /**
619
+ * The document the ingest gives back was stored before, by another ingest (`IngestInput.dedupe`):
620
+ * it is never removed for this one, whatever happens to it (0.10.2).
621
+ */
622
+ reused?: true;
533
623
  };
534
624
 
535
625
  /**
@@ -592,6 +682,8 @@ async function ingestFile(
592
682
  let sha256 = "";
593
683
  /** The bytes to keep in the store (`putOriginal`), until they are written. */
594
684
  let copy: Uint8Array | undefined;
685
+ /** The size and SHA-256 of a file at a path that its extractor reads, taken before for `dedupe`. */
686
+ let early: { bytes: number; sha256: string } | undefined;
595
687
  /**
596
688
  * A read of the file at `path`, or the signal's reason once it aborts. A volume that does not
597
689
  * answer within the ingest's time is the server's trouble, not the file's: a system error
@@ -599,6 +691,9 @@ async function ingestFile(
599
691
  * read (422, "split it"), since 0.10.0. The ingest keeps its turn until the read ends (`IngestSlot`).
600
692
  */
601
693
  const readWithin = async <T>(read: Promise<T>): Promise<T> => {
694
+ // Counted as stuck past the ingest's time, until it ends (0.10.2): only when the ingest has a
695
+ // time limit (`ingestTimeoutMs`), since a read without one may go on, and still be reading.
696
+ if (isTimeLimit(ingestTimeoutMs)) watchStuck(read, slotCapMs);
602
697
  work.abandoned = read;
603
698
  let got: T;
604
699
  try {
@@ -638,6 +733,34 @@ async function ingestFile(
638
733
  sha256 = got.sha256;
639
734
  got = undefined;
640
735
  }
736
+ // With `dedupe`, the document of the same owner and scope with the same SHA-256 is the answer,
737
+ // when there is one: the file is hashed first, and not extracted (0.10.2).
738
+ if (target.dedupe) {
739
+ if (path === undefined) sha256 = await sha256InSlices(bytes!, slicer);
740
+ else if (extractorReads) {
741
+ const got = await readWithin(readSource(path, maxUploadBytes, { keep: false, slicer, signal }));
742
+ early = { bytes: checkedSize(name, got.size, maxUploadBytes), sha256: got.sha256 };
743
+ sha256 = got.sha256;
744
+ }
745
+ // Within the time the ingest gives its store calls, and the caller's signal: a store that does
746
+ // not answer fails the ingest, which keeps its turn until the calls end (`IngestWork`).
747
+ const looking = sameDocument(context, target, sha256);
748
+ work.abandoned = looking;
749
+ let same: DocumentMeta | undefined;
750
+ try {
751
+ same = await settleWithin(untilAborted(looking, signal), slotCapMs, () => storeTimeout(name, slotCapMs, "read"));
752
+ } catch (error) {
753
+ // The ingest's time ran out while the store did not answer: the store's trouble (503), not
754
+ // a file that takes too long to read (422).
755
+ if (timedOut(error)) throw storeTimeout(name, ingestTimeoutMs, "read");
756
+ throw error;
757
+ }
758
+ work.abandoned = undefined;
759
+ if (same) {
760
+ work.reused = true;
761
+ return jsonCopy(same);
762
+ }
763
+ }
641
764
  // In a function of its own, so that the text as extracted is let go once it is prepared:
642
765
  // the steps after it hold only the prepared text.
643
766
  const read = async () => {
@@ -683,11 +806,11 @@ async function ingestFile(
683
806
  // Bytes given are hashed once the extractor is done with them, a slice at a time: the extractor
684
807
  // is called at once at the ingest's turn, as before 0.9.0, so the ingests of one turn reach it
685
808
  // in the order they came, and the SHA-256 is that of the bytes a kept copy holds.
686
- if (path === undefined) sha256 = await sha256InSlices(bytes!, slicer);
809
+ if (path === undefined && !target.dedupe) sha256 = await sha256InSlices(bytes!, slicer);
687
810
  if (path !== undefined && extractorReads) {
688
811
  // What the extractor read of the file: its size and SHA-256. One that did not say is hashed
689
812
  // here, a slice at a time, and nothing of it is kept.
690
- let hashed = done.file;
813
+ let hashed = done.file ?? early;
691
814
  if (!hashed) {
692
815
  const got = await readWithin(readSource(path, maxUploadBytes, { keep: false, slicer, signal }));
693
816
  hashed = { bytes: got.size, sha256: got.sha256 };
@@ -719,7 +842,6 @@ async function ingestFile(
719
842
  dispose();
720
843
  }
721
844
  const created = now();
722
- const expires = created.getTime() + ttlMs;
723
845
  // Kept by its ref, or as a copy in the store, which has the bytes to write.
724
846
  const keepOriginal = byRef ? keeps(format, true) : copy !== undefined;
725
847
  // A copy: the outline's headings and the log's timestamps are pieces of the text, and a piece
@@ -754,7 +876,9 @@ async function ingestFile(
754
876
  ...quality,
755
877
  createdAt: created.toISOString(),
756
878
  // Never, for a time to live without end (or one that runs past what a date can hold).
757
- expiresAt: expires >= Date.parse(NEVER_EXPIRES) ? NEVER_EXPIRES : new Date(expires).toISOString(),
879
+ expiresAt: expiryAfter(created, ttlMs),
880
+ // The application's own, checked when the ingest began. Never sent to the model.
881
+ ...(target.appData !== undefined ? { appData: target.appData } : {}),
758
882
  });
759
883
  const savedIndex = index && canSerialize(index) && index.lineCount === meta.lines && index.characters === meta.characters && index.textBytes === meta.textBytes
760
884
  ? serializeTextIndex(index)
@@ -880,6 +1004,7 @@ export async function ingestDocument(context: IngestContext, input: IngestInput
880
1004
  if (events.active) events.emit({ type: "ingest.start", ...startOf(input, stated?.size) });
881
1005
  checkOwner(input.owner);
882
1006
  const target = targetOf(input, context.rules);
1007
+ if (target.dedupe && !usableStoreMethod(context.store, "list")) throw new TypeError("dedupe needs a store with list(): MemoryDocumentStore and FileDocumentStore have it (a subclass of one, or one whose put, get, getMeta or delete was replaced, needs its own list).");
883
1008
  // The path looked at, as it was made absolute then (the working directory may have changed
884
1009
  // since); checked again for an input it was not taken from, which throws here.
885
1010
  const path = quietPath ?? sourcePathOf(input);
@@ -931,14 +1056,21 @@ export async function ingestDocument(context: IngestContext, input: IngestInput
931
1056
  throw toIngestError(error);
932
1057
  }
933
1058
  // Once more, before the document is told stored: a caller that has left by now gets its reason.
934
- if (input.signal?.aborted) await removeAbandoned(context, target, meta, work, input.signal.reason);
1059
+ // A document stored before (`dedupe`) is not this ingest's to remove.
1060
+ if (input.signal?.aborted) {
1061
+ if (work.reused) throw input.signal.reason;
1062
+ await removeAbandoned(context, target, meta, work, input.signal.reason);
1063
+ }
935
1064
  try {
936
1065
  events.emit({ type: "ingest.finish", document: toDocumentSummary(meta) });
937
1066
  } catch (error) {
938
1067
  // The caller never gets the id: the document goes, as on a throw of the listener a moment
939
- // earlier, while it is this ingest's own. The listener's error is passed on as it is.
940
- await removeOwn(context, target, meta).catch(() => undefined);
941
- forget(meta.id);
1068
+ // earlier, while it is this ingest's own (not one stored before, `dedupe`). The listener's
1069
+ // error is passed on as it is.
1070
+ if (!work.reused) {
1071
+ await removeOwn(context, target, meta).catch(() => undefined);
1072
+ forget(meta.id);
1073
+ }
942
1074
  throw error;
943
1075
  }
944
1076
  return meta;