@gmickel/gno 2.15.0 → 2.16.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 (198) hide show
  1. package/README.md +1 -1
  2. package/assets/skill/cli-reference.md +4 -2
  3. package/assets/spa-production.json.gz +0 -0
  4. package/browser-extension/artifacts/{gno-browser-clipper-v2.15.0.zip → gno-browser-clipper-v2.16.0.zip} +0 -0
  5. package/browser-extension/artifacts/gno-browser-clipper-v2.16.0.zip.sha256 +1 -0
  6. package/browser-extension/dist/manifest.json +1 -1
  7. package/package.json +1 -1
  8. package/spec/cli.md +1 -1
  9. package/src/cli/commands/agents/commands.ts +1 -1
  10. package/src/cli/commands/ask.ts +1 -1
  11. package/src/cli/commands/context-build.ts +1 -1
  12. package/src/cli/commands/embed.ts +2 -2
  13. package/src/cli/commands/links.ts +1 -1
  14. package/src/cli/commands/mcp/install.ts +2 -2
  15. package/src/cli/commands/mcp/status.ts +1 -1
  16. package/src/cli/commands/mcp/uninstall.ts +1 -1
  17. package/src/cli/commands/query.ts +1 -1
  18. package/src/cli/commands/shared.ts +4 -4
  19. package/src/cli/commands/skill/install.ts +1 -1
  20. package/src/cli/commands/skill/paths-cmd.ts +1 -1
  21. package/src/cli/commands/skill/uninstall.ts +1 -1
  22. package/src/cli/commands/status.ts +75 -58
  23. package/src/cli/config-cache.ts +86 -0
  24. package/src/cli/globals.ts +64 -0
  25. package/src/cli/program.ts +20 -36
  26. package/src/cli/run.ts +121 -67
  27. package/src/cli/runtime-health.ts +132 -122
  28. package/src/cli/session-binding.ts +11 -2
  29. package/src/config/saver.ts +8 -0
  30. package/src/converters/adapters/browser-export/formats.ts +25 -15
  31. package/src/converters/adapters/email/adapter.ts +37 -53
  32. package/src/converters/adapters/email/html.ts +37 -20
  33. package/src/converters/adapters/email/mime.ts +71 -39
  34. package/src/converters/adapters/ical/adapter.ts +20 -12
  35. package/src/converters/adapters/jsonl/adapter.ts +8 -6
  36. package/src/converters/adapters/shared/html-text.ts +55 -37
  37. package/src/converters/adapters/shared/ooxml-protection.ts +5 -13
  38. package/src/converters/adapters/shared/utf8-lines.ts +69 -31
  39. package/src/converters/adapters/transcript/adapter.ts +12 -7
  40. package/src/converters/adapters/xlsx/adapter.ts +10 -7
  41. package/src/converters/adapters/xlsx/sheet-markdown.ts +93 -50
  42. package/src/converters/canonicalize.ts +17 -3
  43. package/src/converters/native/markdown.ts +24 -17
  44. package/src/converters/native/plaintext.ts +5 -6
  45. package/src/converters/registry.ts +130 -8
  46. package/src/core/activation-status.ts +4 -8
  47. package/src/core/change-diff.ts +38 -11
  48. package/src/core/context-compiler.ts +17 -18
  49. package/src/core/context-evidence.ts +116 -25
  50. package/src/core/context-verifier.ts +70 -31
  51. package/src/core/file-lock.ts +10 -2
  52. package/src/core/graph-analysis.ts +3 -3
  53. package/src/core/link-inventory-markdown.ts +2 -2
  54. package/src/core/links.ts +20 -87
  55. package/src/core/memory-fence.ts +16 -9
  56. package/src/core/memory-recall.ts +168 -34
  57. package/src/core/path-rules.ts +143 -0
  58. package/src/core/section-parse.ts +16 -6
  59. package/src/core/typed-metadata.ts +68 -0
  60. package/src/core/wiki-link-syntax.ts +88 -0
  61. package/src/embed/backlog.ts +142 -60
  62. package/src/embed/retry.ts +39 -33
  63. package/src/embed/variant-backlog.ts +546 -114
  64. package/src/embed/variant-retry.ts +157 -48
  65. package/src/index.ts +3 -3
  66. package/src/ingestion/budget-error-codes.ts +13 -0
  67. package/src/ingestion/chunker.ts +60 -49
  68. package/src/ingestion/compiled-context.ts +4 -5
  69. package/src/ingestion/convert-file.ts +1 -1
  70. package/src/ingestion/document-metadata.ts +16 -9
  71. package/src/ingestion/excluded-ranges.ts +97 -0
  72. package/src/ingestion/file-processor.ts +122 -37
  73. package/src/ingestion/frontmatter.ts +35 -7
  74. package/src/ingestion/graph-reconciliation.ts +187 -51
  75. package/src/ingestion/language.ts +66 -61
  76. package/src/ingestion/position.ts +5 -5
  77. package/src/ingestion/prepare-file.ts +50 -29
  78. package/src/ingestion/record-adapter-canonical.ts +37 -26
  79. package/src/ingestion/record-adapter.ts +46 -26
  80. package/src/ingestion/record-container.ts +121 -53
  81. package/src/ingestion/record-path.ts +5 -2
  82. package/src/ingestion/source-availability/darwin-io.ts +10 -7
  83. package/src/ingestion/source-availability/darwin-path.ts +21 -3
  84. package/src/ingestion/source-availability/readers.ts +51 -0
  85. package/src/ingestion/strip.ts +39 -105
  86. package/src/ingestion/sync.ts +692 -386
  87. package/src/ingestion/typed-metadata.ts +10 -4
  88. package/src/ingestion/walker.ts +485 -158
  89. package/src/llm/cache.ts +128 -84
  90. package/src/llm/http-inference.ts +112 -35
  91. package/src/llm/http-policy.ts +101 -0
  92. package/src/llm/httpEmbedding.ts +8 -1
  93. package/src/llm/httpGeneration.ts +5 -1
  94. package/src/llm/httpRerank.ts +5 -1
  95. package/src/llm/inference-scope.ts +15 -2
  96. package/src/llm/lazy-ports.ts +33 -3
  97. package/src/llm/lockfile.ts +34 -7
  98. package/src/llm/model-cleanup.ts +24 -0
  99. package/src/llm/native-worker/client.ts +23 -12
  100. package/src/llm/native-worker/dispatcher.ts +19 -9
  101. package/src/llm/native-worker/embedding-identity.ts +42 -16
  102. package/src/llm/native-worker/entry.ts +2 -1
  103. package/src/llm/native-worker/owner.ts +1 -0
  104. package/src/llm/native-worker/ports.ts +86 -23
  105. package/src/llm/native-worker/protocol.ts +386 -55
  106. package/src/llm/nodeLlamaCpp/adapter.ts +46 -29
  107. package/src/llm/nodeLlamaCpp/embedding.ts +93 -40
  108. package/src/llm/nodeLlamaCpp/generation.ts +194 -30
  109. package/src/llm/nodeLlamaCpp/lifecycle.ts +2 -0
  110. package/src/llm/nodeLlamaCpp/rerank-capacity.ts +101 -23
  111. package/src/llm/nodeLlamaCpp/rerank.ts +253 -44
  112. package/src/llm/types.ts +14 -0
  113. package/src/mcp/context.ts +342 -23
  114. package/src/mcp/http-transport.ts +21 -3
  115. package/src/mcp/tool-profile-types.ts +62 -0
  116. package/src/mcp/tool-profile.ts +32 -56
  117. package/src/mcp/tools/context.ts +5 -1
  118. package/src/mcp/tools/index.ts +269 -191
  119. package/src/mcp/tools/links.ts +7 -5
  120. package/src/mcp/tools/query.ts +60 -37
  121. package/src/mcp/tools/vsearch.ts +25 -14
  122. package/src/pipeline/answer.ts +133 -40
  123. package/src/pipeline/claim-verification.ts +293 -189
  124. package/src/pipeline/claim-verifier.ts +6 -7
  125. package/src/pipeline/egress-lineage.ts +37 -26
  126. package/src/pipeline/exclude.ts +34 -11
  127. package/src/pipeline/expansion.ts +233 -19
  128. package/src/pipeline/filters.ts +169 -33
  129. package/src/pipeline/graph-retrieval.ts +117 -61
  130. package/src/pipeline/hybrid.ts +598 -329
  131. package/src/pipeline/hydration.ts +86 -24
  132. package/src/pipeline/intent.ts +15 -7
  133. package/src/pipeline/owner-fusion.ts +61 -19
  134. package/src/pipeline/query-language.ts +15 -2
  135. package/src/pipeline/rerank.ts +15 -22
  136. package/src/pipeline/search.ts +193 -72
  137. package/src/pipeline/snippet.ts +15 -2
  138. package/src/pipeline/temporal.ts +51 -10
  139. package/src/pipeline/vsearch.ts +250 -152
  140. package/src/publish/attachment-raster.ts +2 -16
  141. package/src/publish/encrypted-export.ts +15 -5
  142. package/src/serve/browse-tree.ts +50 -42
  143. package/src/serve/connectors.ts +2 -1
  144. package/src/serve/context.ts +13 -4
  145. package/src/serve/doc-events.ts +3 -0
  146. package/src/serve/public/app.tsx +49 -21
  147. package/src/serve/public/components/BrowseTreeSidebar.tsx +163 -23
  148. package/src/serve/public/components/CaptureModal.tsx +14 -10
  149. package/src/serve/public/components/ai-elements/code-block.tsx +87 -50
  150. package/src/serve/public/components/editor/MarkdownPreview.tsx +99 -67
  151. package/src/serve/public/globals.built.css +1 -1
  152. package/src/serve/public/globals.css +19 -0
  153. package/src/serve/public/hooks/useCaptureModal.tsx +23 -10
  154. package/src/serve/public/lib/metadata-filter.ts +234 -9
  155. package/src/serve/public/pages/Browse.tsx +61 -27
  156. package/src/serve/public/pages/DocView.tsx +44 -25
  157. package/src/serve/public/pages/GraphView.tsx +8 -3
  158. package/src/serve/resident-runtime.ts +199 -48
  159. package/src/serve/routes/api.ts +98 -67
  160. package/src/serve/routes/links.ts +18 -4
  161. package/src/serve/server.ts +1370 -1180
  162. package/src/serve/spa-bundle-source.ts +52 -27
  163. package/src/serve/status.ts +101 -52
  164. package/src/serve/watch-reconciliation-fallback.ts +11 -7
  165. package/src/serve/watch-reconciliation-shared.ts +42 -4
  166. package/src/serve/watch-reconciliation.ts +21 -8
  167. package/src/serve/watch-service-events.ts +7 -1
  168. package/src/serve/watch-service-hosts.ts +3 -1
  169. package/src/serve/watch-service.ts +46 -21
  170. package/src/serve/watch-snapshot-scan.ts +6 -15
  171. package/src/sessions/archive.ts +20 -8
  172. package/src/sessions/sanitize.ts +38 -18
  173. package/src/sessions/service.ts +180 -102
  174. package/src/store/migrations/037-performance-indexes.ts +56 -0
  175. package/src/store/migrations/index.ts +2 -0
  176. package/src/store/sqlite/adapter.ts +1217 -651
  177. package/src/store/sqlite/chunking-policy.ts +15 -1
  178. package/src/store/sqlite/eligibility.ts +110 -70
  179. package/src/store/sqlite/graph-neighbors.ts +71 -46
  180. package/src/store/sqlite/graph-reference-state.ts +27 -3
  181. package/src/store/sqlite/graph-similarity.ts +59 -12
  182. package/src/store/sqlite/metadata-predicate.ts +123 -28
  183. package/src/store/sqlite/retrieval-trace-management-store.ts +126 -33
  184. package/src/store/sqlite/retrieval-trace-retention.ts +88 -76
  185. package/src/store/sqlite/retrieval-trace-rows.ts +7 -3
  186. package/src/store/types.ts +32 -0
  187. package/src/store/vector/eligibility.ts +39 -0
  188. package/src/store/vector/lazy.ts +17 -0
  189. package/src/store/vector/partition-index.ts +28 -45
  190. package/src/store/vector/proof-cache.ts +103 -0
  191. package/src/store/vector/sqlite-vec.ts +230 -139
  192. package/src/store/vector/stats.ts +29 -73
  193. package/src/store/vector/status.ts +151 -52
  194. package/src/store/vector/stored-vectors.ts +131 -45
  195. package/src/store/vector/types.ts +10 -0
  196. package/src/store/vector/variant-search.ts +771 -109
  197. package/src/store/vector/variants.ts +495 -139
  198. package/browser-extension/artifacts/gno-browser-clipper-v2.15.0.zip.sha256 +0 -1
@@ -1,7 +1,9 @@
1
1
  import type { StoreResult } from "../store/types";
2
+ import type { VectorOwnerInput } from "../store/vector/types";
2
3
  import type { VectorVariantStore } from "../store/vector/variants";
3
4
  import type { EmbedBacklogDeps, EmbedBacklogResult } from "./backlog";
4
5
 
6
+ import { isHttpModelUri } from "../llm/httpEmbedding";
5
7
  import {
6
8
  assertInferenceActive,
7
9
  isBackgroundInference,
@@ -9,6 +11,7 @@ import {
9
11
  } from "../llm/inference-scope";
10
12
  import { err, ok } from "../store/types";
11
13
  import { getVectorStatsDatabase } from "../store/vector/stats";
14
+ import { embedTextsWithRecovery } from "./batch";
12
15
  import {
13
16
  compareOwnerCursor,
14
17
  isOwnerCursor,
@@ -19,7 +22,16 @@ import {
19
22
  } from "./resume-cursor";
20
23
  import { inWriteTurn } from "./retry";
21
24
  import { variantBacklogPage } from "./variant-plan";
22
- import { embedVariantBatch } from "./variant-retry";
25
+ import {
26
+ commitVariantBatch,
27
+ embedVariantBatch,
28
+ type PreparedVariantBatch,
29
+ prepareVariantBatch,
30
+ type VariantBatchOutcome,
31
+ } from "./variant-retry";
32
+
33
+ const DEFAULT_FOREGROUND_BATCH_SIZE = 64;
34
+ const HTTP_EMBED_MAX_CONCURRENCY = 3;
23
35
 
24
36
  /** One bounded owner pass plus one retry; mutations stay durably pending for the next pass. */
25
37
  export async function embedVariantBacklog(
@@ -50,7 +62,7 @@ export async function embedVariantBacklog(
50
62
  const background = isBackgroundInference();
51
63
  const batchSize = background
52
64
  ? Math.min(deps.batchSize ?? 32, 32)
53
- : (deps.batchSize ?? 32);
65
+ : (deps.batchSize ?? DEFAULT_FOREGROUND_BATCH_SIZE);
54
66
  if (!Number.isSafeInteger(batchSize) || batchSize < 1)
55
67
  return err("INVALID_INPUT", "Invalid embedding batch size");
56
68
  const total = { embedded: 0, errors: 0, contentionErrors: 0 };
@@ -140,140 +152,560 @@ export async function embedVariantBacklog(
140
152
  await saveResume(after);
141
153
  return ok({ ...total, stopped: "limit" as const });
142
154
  };
155
+ const handleForegroundOutcome = async (
156
+ ownersCount: number,
157
+ outcome: VariantBatchOutcome
158
+ ): Promise<boolean> => {
159
+ if (outcome.deferred) return true;
160
+ if (!identityHolds()) {
161
+ total.errors += Math.max(
162
+ 0,
163
+ ownersCount -
164
+ outcome.embedded -
165
+ outcome.errors -
166
+ outcome.contentionErrors -
167
+ outcome.retryOwners.length
168
+ );
169
+ }
170
+ total.embedded += outcome.embedded;
171
+ total.errors += outcome.errors;
172
+ total.contentionErrors += outcome.contentionErrors;
173
+ if (outcome.retryOwners.length && !limitReached()) {
174
+ const retrying = outcome.retryOwners.length;
175
+ const retryResult = await embedVariantBatch({
176
+ store,
177
+ embedPort: deps.embedPort,
178
+ owners: outcome.retryOwners,
179
+ identityStillCurrent,
180
+ force: deps.force,
181
+ onSubmit,
182
+ });
183
+ total.embedded += retryResult.embedded;
184
+ total.errors += retryResult.errors + retryResult.retryOwners.length;
185
+ total.contentionErrors += retryResult.contentionErrors;
186
+ if (!identityHolds())
187
+ total.errors += Math.max(
188
+ 0,
189
+ retrying -
190
+ retryResult.embedded -
191
+ retryResult.errors -
192
+ retryResult.contentionErrors -
193
+ retryResult.retryOwners.length
194
+ );
195
+ } else {
196
+ total.errors += outcome.retryOwners.length;
197
+ }
198
+ deps.onProgress?.(total.embedded, total.errors);
199
+ return false;
200
+ };
201
+
143
202
  try {
144
- while (true) {
145
- // A failed request drops the port's cached identity (a timed-out native
146
- // worker is retired); reload it so one failed page cannot end the pass.
147
- if (background) {
148
- const reloaded = await withInferencePage(() => deps.embedPort.init());
149
- // Without an identity the pass cannot continue. Failing it schedules
150
- // the scheduler's bounded retry instead of ending with pages pending.
151
- if (!reloaded?.ok)
152
- throw new Error(
153
- reloaded?.error.message ??
154
- "Embedding model reload exceeded its inference deadline"
203
+ const canPipelineForeground =
204
+ !background && !deps.acquireWriteTurn && !limits;
205
+ const isHttpPort = isHttpModelUri(deps.modelUri);
206
+
207
+ if (canPipelineForeground && isHttpPort) {
208
+ // Bounded concurrent in-flight HTTP batches (up to HTTP_EMBED_MAX_CONCURRENCY)
209
+ // with in-flight inputHash deduplication across the active window.
210
+ type HttpInFlight = {
211
+ owners: VectorOwnerInput[];
212
+ prepared: PreparedVariantBatch;
213
+ keys: string[];
214
+ dependentHashes: string[];
215
+ endCursor: OwnerCursor;
216
+ promise: ReturnType<typeof embedTextsWithRecovery>;
217
+ };
218
+ const inFlight: HttpInFlight[] = [];
219
+ const inFlightHashes = new Set<string>();
220
+ // Retain completed vectors ONLY while at least one queued page depends on
221
+ // them; evict each hash as soon as its last dependent page commits.
222
+ const queuedDependentCount = new Map<string, number>();
223
+ const completedVectors = new Map<string, Float32Array>();
224
+ let exhausted = false;
225
+
226
+ const fillWindow = async (): Promise<void> => {
227
+ while (!exhausted && inFlight.length < HTTP_EMBED_MAX_CONCURRENCY) {
228
+ if (!(await identityCurrent())) {
229
+ identityLost = true;
230
+ exhausted = true;
231
+ return;
232
+ }
233
+ assertInferenceActive();
234
+ const pending = variantBacklogPage(deps, store, batchSize, after);
235
+ if (!pending.length) {
236
+ exhausted = true;
237
+ return;
238
+ }
239
+ const last = pending.at(-1)!;
240
+ const endCursor: OwnerCursor = {
241
+ documentId: last.documentId,
242
+ seq: last.seq,
243
+ };
244
+ after = endCursor;
245
+ const prepared = prepareVariantBatch({
246
+ store,
247
+ owners: pending,
248
+ force: deps.force,
249
+ inFlightHashes,
250
+ });
251
+ const dependentHashes: string[] = [];
252
+ for (const [hash] of prepared.sharedFromInFlight) {
253
+ dependentHashes.push(hash);
254
+ queuedDependentCount.set(
255
+ hash,
256
+ (queuedDependentCount.get(hash) ?? 0) + 1
257
+ );
258
+ }
259
+ const keys = [...prepared.inputs.keys()];
260
+ for (const key of keys) inFlightHashes.add(key);
261
+ const promise = embedTextsWithRecovery(
262
+ deps.embedPort,
263
+ [...prepared.inputs.values()],
264
+ { onSubmit }
155
265
  );
156
- }
157
- if (!(await identityCurrent())) {
158
- identityLost = true;
159
- break;
160
- }
161
- assertInferenceActive();
162
- let pending = variantBacklogPage(deps, store, batchSize, after);
163
- // After wrapping, stop where this run started.
164
- if (wrapped && resumeFrom)
165
- pending = pending.filter(
166
- (owner) => compareOwnerCursor(owner, resumeFrom) <= 0
167
- );
168
- if (!pending.length) {
169
- // Time can run out while this page is read. Owners this run failed
170
- // are still pending, so the same check as at a batch boundary decides
171
- // between a stopped run and a finished traversal.
172
- if (pagesStarted > 0) {
173
- const verdict = await stopAtLimit();
174
- if (verdict === "limit") return await stop();
175
- if (verdict === "incomplete") {
266
+ inFlight.push({
267
+ owners: pending,
268
+ prepared,
269
+ keys,
270
+ dependentHashes,
271
+ endCursor,
272
+ promise,
273
+ });
274
+ }
275
+ };
276
+
277
+ await fillWindow();
278
+ while (inFlight.length > 0) {
279
+ const entry = inFlight.shift()!;
280
+ const result = await entry.promise;
281
+ for (const key of entry.keys) inFlightHashes.delete(key);
282
+
283
+ if (!identityHolds()) {
284
+ await Promise.allSettled(inFlight.map((item) => item.promise));
285
+ inFlight.length = 0;
286
+ inFlightHashes.clear();
287
+ completedVectors.clear();
288
+ queuedDependentCount.clear();
289
+ total.errors += entry.owners.length;
290
+ deps.onProgress?.(total.embedded, total.errors);
291
+ if (!(await identityCurrent())) {
176
292
  identityLost = true;
177
293
  break;
178
294
  }
295
+ // Reloaded identity: rewind cursor to end of the failed batch so
296
+ // discarded in-flight pages are re-fetched cleanly and traversal
297
+ // continues across the rest of the backlog.
298
+ after = entry.endCursor;
299
+ exhausted = false;
300
+ await fillWindow();
301
+ continue;
179
302
  }
180
- if (wrapped) break;
181
- wrapped = true;
182
- after = undefined;
183
- continue;
184
- }
185
- // Time can run out while the page is fetched: stop before inference,
186
- // keeping this page eligible for the next run (the cursor stays put).
187
- // Every run processes at least one page, even one that submits nothing
188
- // or follows a runtime verification that spent the budget, so bounded
189
- // runs always progress.
190
- if (pagesStarted > 0 && limitReached()) return await stop();
191
- pagesStarted += 1;
192
- const last = pending.at(-1)!;
193
- after = { documentId: last.documentId, seq: last.seq };
194
- // Pages are already limited to deps.collection in SQL.
195
- const owners = pending;
196
- const embedPage = () =>
197
- embedVariantBatch({
303
+
304
+ const vectors = new Map<string, Float32Array>();
305
+ if (result.ok) {
306
+ for (const [index, key] of entry.keys.entries()) {
307
+ const vec = result.value.vectors[index];
308
+ if (vec) {
309
+ const typed = new Float32Array(vec);
310
+ vectors.set(key, typed);
311
+ if ((queuedDependentCount.get(key) ?? 0) > 0) {
312
+ completedVectors.set(key, typed);
313
+ }
314
+ }
315
+ }
316
+ }
317
+ // Attach vectors produced by earlier batches in the same window and
318
+ // release ref-counts immediately so completedVectors stays bounded.
319
+ for (const hash of entry.dependentHashes) {
320
+ const shared = completedVectors.get(hash);
321
+ if (shared && !vectors.has(hash)) {
322
+ vectors.set(hash, shared);
323
+ }
324
+ const remaining = (queuedDependentCount.get(hash) ?? 1) - 1;
325
+ if (remaining <= 0) {
326
+ queuedDependentCount.delete(hash);
327
+ completedVectors.delete(hash);
328
+ } else {
329
+ queuedDependentCount.set(hash, remaining);
330
+ }
331
+ }
332
+ const outcome = await commitVariantBatch({
198
333
  store,
199
- embedPort: deps.embedPort,
200
- owners,
334
+ owners: entry.prepared.owners,
335
+ reusable: entry.prepared.reusable,
336
+ vectors,
201
337
  identityStillCurrent,
202
- force: deps.force,
203
- acquireWriteTurn: deps.acquireWriteTurn,
204
- onSubmit,
205
338
  });
206
- let result = background
207
- ? await withInferencePage(embedPage)
208
- : await embedPage();
209
- if (!result) {
210
- // Past its deadline: this page stays pending for the next pass.
211
- total.errors += owners.length;
212
- deps.onProgress?.(total.embedded, total.errors);
213
- const verdict = await stopAtLimit();
214
- if (verdict === "limit") return await stop();
215
- if (verdict === "incomplete") {
216
- identityLost = true;
217
- break;
218
- }
219
- await Bun.sleep(0);
220
- continue;
339
+ await handleForegroundOutcome(entry.owners.length, outcome);
340
+ await fillWindow();
221
341
  }
222
- if (result.deferred) return ok({ ...total, deferred: true });
223
- // The identity dropped during inference: the batch discarded its
224
- // results. Its owners stay pending and count as this run's failures
225
- // (the port is reloaded at the top of the loop).
226
- if (!identityHolds()) {
227
- total.errors += Math.max(
228
- 0,
229
- owners.length -
230
- result.embedded -
231
- result.errors -
232
- result.contentionErrors -
233
- result.retryOwners.length
234
- );
342
+ } else if (canPipelineForeground) {
343
+ // Double-buffered foreground native embedding: overlap SQLite commit of
344
+ // page k-1 + prefetch/format of page k+1 with worker inference of page k.
345
+ interface PreparedPage {
346
+ owners: VectorOwnerInput[];
347
+ prepared: PreparedVariantBatch;
348
+ carriedVectors: Map<string, Float32Array>;
349
+ endCursor: OwnerCursor;
235
350
  }
236
- total.embedded += result.embedded;
237
- total.errors += result.errors;
238
- total.contentionErrors += result.contentionErrors;
239
- if (background) total.errors += result.retryOwners.length;
240
- // A retry counts toward the limits; once they are reached, failed
241
- // owners stay pending for the next run instead of a further batch.
242
- if (!background && result.retryOwners.length && !limitReached()) {
243
- const retrying = result.retryOwners.length;
244
- result = await embedVariantBatch({
351
+
352
+ const fetchPreparedPage = (
353
+ inFlightHashes?: ReadonlySet<string>
354
+ ): PreparedPage | null => {
355
+ assertInferenceActive();
356
+ const pending = variantBacklogPage(deps, store, batchSize, after);
357
+ if (!pending.length) return null;
358
+ const last = pending.at(-1)!;
359
+ const endCursor: OwnerCursor = {
360
+ documentId: last.documentId,
361
+ seq: last.seq,
362
+ };
363
+ after = endCursor;
364
+ const prepared = prepareVariantBatch({
245
365
  store,
246
- embedPort: deps.embedPort,
247
- owners: result.retryOwners,
248
- identityStillCurrent,
366
+ owners: pending,
249
367
  force: deps.force,
250
- onSubmit,
368
+ inFlightHashes,
251
369
  });
252
- total.embedded += result.embedded;
253
- total.errors += result.errors + result.retryOwners.length;
254
- total.contentionErrors += result.contentionErrors;
255
- // Same accounting when the identity drops during the retry.
256
- if (!identityHolds())
370
+ return {
371
+ owners: pending,
372
+ prepared,
373
+ carriedVectors: new Map<string, Float32Array>(),
374
+ endCursor,
375
+ };
376
+ };
377
+
378
+ const mergeCarriedVectors = (
379
+ page: PreparedPage,
380
+ inferred: Map<string, Float32Array>
381
+ ): Map<string, Float32Array> => {
382
+ if (page.carriedVectors.size === 0) return inferred;
383
+ for (const [hash, vec] of page.carriedVectors) {
384
+ if (!inferred.has(hash)) inferred.set(hash, vec);
385
+ }
386
+ return inferred;
387
+ };
388
+
389
+ const handoffSharedVectors = (
390
+ sourceVectors: ReadonlyMap<string, Float32Array>,
391
+ targetPage: PreparedPage | null
392
+ ): void => {
393
+ if (!targetPage) return;
394
+ for (const [hash, formatted] of targetPage.prepared
395
+ .sharedFromInFlight) {
396
+ const vec = sourceVectors.get(hash);
397
+ if (vec) {
398
+ // Carry the actual vector bytes instead of marking reusable before
399
+ // SQLite commits page k (page k's producer owners might go stale).
400
+ targetPage.carriedVectors.set(hash, vec);
401
+ } else {
402
+ targetPage.prepared.inputs.set(hash, formatted);
403
+ }
404
+ }
405
+ targetPage.prepared.sharedFromInFlight.clear();
406
+ };
407
+
408
+ if (!(await identityCurrent())) {
409
+ identityLost = true;
410
+ } else {
411
+ let currentPage = fetchPreparedPage();
412
+ while (currentPage) {
413
+ const keys = [...currentPage.prepared.inputs.keys()];
414
+ const activeHashes = new Set(keys);
415
+ const inferencePromise = embedTextsWithRecovery(
416
+ deps.embedPort,
417
+ [...currentPage.prepared.inputs.values()],
418
+ { onSubmit }
419
+ );
420
+
421
+ // While child worker runs inference for page k, prefetch and format page k+1.
422
+ const nextPage = fetchPreparedPage(activeHashes);
423
+
424
+ const result = await inferencePromise;
425
+ if (!identityHolds()) {
426
+ total.errors += currentPage.owners.length;
427
+ deps.onProgress?.(total.embedded, total.errors);
428
+ if (!(await identityCurrent())) {
429
+ identityLost = true;
430
+ break;
431
+ }
432
+ // Reloaded identity: rewind cursor to end of failed page so
433
+ // prefetched page k+1 is re-fetched cleanly with no skipped owners.
434
+ after = currentPage.endCursor;
435
+ currentPage = fetchPreparedPage();
436
+ continue;
437
+ }
438
+
439
+ const vectors = new Map<string, Float32Array>();
440
+ if (result.ok) {
441
+ for (const [index, key] of keys.entries()) {
442
+ const vec = result.value.vectors[index];
443
+ if (vec) vectors.set(key, new Float32Array(vec));
444
+ }
445
+ }
446
+ mergeCarriedVectors(currentPage, vectors);
447
+ handoffSharedVectors(vectors, nextPage);
448
+
449
+ // Launch page k+1's worker inference BEFORE committing page k to SQLite
450
+ // so SQLite commit of page k overlaps with worker inference of page k+1!
451
+ if (!nextPage) {
452
+ const outcome = await commitVariantBatch({
453
+ store,
454
+ owners: currentPage.prepared.owners,
455
+ reusable: currentPage.prepared.reusable,
456
+ vectors,
457
+ identityStillCurrent,
458
+ });
459
+ await handleForegroundOutcome(currentPage.owners.length, outcome);
460
+ break;
461
+ }
462
+
463
+ // Commit page k and continue the loop with page k+1 already started.
464
+ // When page k has retryOwners, finish page k's retry after page k+1's
465
+ // inference completes so only one worker inference runs at a time.
466
+ let pendingCommit: {
467
+ ownersCount: number;
468
+ prepared: PreparedVariantBatch;
469
+ vectors: Map<string, Float32Array>;
470
+ } | null = {
471
+ ownersCount: currentPage.owners.length,
472
+ prepared: currentPage.prepared,
473
+ vectors,
474
+ };
475
+ currentPage = nextPage;
476
+
477
+ while (currentPage) {
478
+ const nextKeys = [...currentPage.prepared.inputs.keys()];
479
+ const nextActiveHashes = new Set(nextKeys);
480
+ const nextInference = embedTextsWithRecovery(
481
+ deps.embedPort,
482
+ [...currentPage.prepared.inputs.values()],
483
+ { onSubmit }
484
+ );
485
+ // Yield one microtask so the IPC frame is flushed before the
486
+ // synchronous SQLite commit runs on the parent thread.
487
+ if (nextKeys.length > 0) {
488
+ await Promise.resolve();
489
+ }
490
+
491
+ // Overlapped with worker inference of currentPage:
492
+ // 1. Commit previous page to SQLite.
493
+ let deferredRetries: VectorOwnerInput[] = [];
494
+ if (pendingCommit) {
495
+ const prevOutcome = await commitVariantBatch({
496
+ store,
497
+ owners: pendingCommit.prepared.owners,
498
+ reusable: pendingCommit.prepared.reusable,
499
+ vectors: pendingCommit.vectors,
500
+ identityStillCurrent,
501
+ });
502
+ total.embedded += prevOutcome.embedded;
503
+ total.errors += prevOutcome.errors;
504
+ total.contentionErrors += prevOutcome.contentionErrors;
505
+ deferredRetries = prevOutcome.retryOwners;
506
+ if (!deferredRetries.length) {
507
+ deps.onProgress?.(total.embedded, total.errors);
508
+ }
509
+ pendingCommit = null;
510
+ }
511
+
512
+ // 2. Prefetch & prepare page k+2 while worker still runs page k+1.
513
+ const followingPage = fetchPreparedPage(nextActiveHashes);
514
+
515
+ // Wait for currentPage inference to complete.
516
+ const nextResult = await nextInference;
517
+ if (deferredRetries.length) {
518
+ await handleForegroundOutcome(deferredRetries.length, {
519
+ embedded: 0,
520
+ errors: 0,
521
+ contentionErrors: 0,
522
+ retryOwners: deferredRetries,
523
+ });
524
+ }
525
+
526
+ if (!identityHolds()) {
527
+ total.errors += currentPage.owners.length;
528
+ deps.onProgress?.(total.embedded, total.errors);
529
+ if (!(await identityCurrent())) {
530
+ identityLost = true;
531
+ currentPage = null;
532
+ break;
533
+ }
534
+ after = currentPage.endCursor;
535
+ currentPage = fetchPreparedPage();
536
+ break;
537
+ }
538
+
539
+ const nextVectors = new Map<string, Float32Array>();
540
+ if (nextResult.ok) {
541
+ for (const [index, key] of nextKeys.entries()) {
542
+ const vec = nextResult.value.vectors[index];
543
+ if (vec) nextVectors.set(key, new Float32Array(vec));
544
+ }
545
+ }
546
+ mergeCarriedVectors(currentPage, nextVectors);
547
+ handoffSharedVectors(nextVectors, followingPage);
548
+
549
+ if (followingPage) {
550
+ pendingCommit = {
551
+ ownersCount: currentPage.owners.length,
552
+ prepared: currentPage.prepared,
553
+ vectors: nextVectors,
554
+ };
555
+ currentPage = followingPage;
556
+ } else {
557
+ const lastOutcome = await commitVariantBatch({
558
+ store,
559
+ owners: currentPage.prepared.owners,
560
+ reusable: currentPage.prepared.reusable,
561
+ vectors: nextVectors,
562
+ identityStillCurrent,
563
+ });
564
+ await handleForegroundOutcome(
565
+ currentPage.owners.length,
566
+ lastOutcome
567
+ );
568
+ currentPage = null;
569
+ }
570
+ }
571
+ if (identityLost) break;
572
+ }
573
+ }
574
+ } else {
575
+ while (true) {
576
+ // A failed request drops the port's cached identity (a timed-out native
577
+ // worker is retired); reload it so one failed page cannot end the pass.
578
+ if (background) {
579
+ const reloaded = await withInferencePage(() => deps.embedPort.init());
580
+ // Without an identity the pass cannot continue. Failing it schedules
581
+ // the scheduler's bounded retry instead of ending with pages pending.
582
+ if (!reloaded?.ok)
583
+ throw new Error(
584
+ reloaded?.error.message ??
585
+ "Embedding model reload exceeded its inference deadline"
586
+ );
587
+ }
588
+ if (!(await identityCurrent())) {
589
+ identityLost = true;
590
+ break;
591
+ }
592
+ assertInferenceActive();
593
+ let pending = variantBacklogPage(deps, store, batchSize, after);
594
+ // After wrapping, stop where this run started.
595
+ if (wrapped && resumeFrom)
596
+ pending = pending.filter(
597
+ (owner) => compareOwnerCursor(owner, resumeFrom) <= 0
598
+ );
599
+ if (!pending.length) {
600
+ // Time can run out while this page is read. Owners this run failed
601
+ // are still pending, so the same check as at a batch boundary decides
602
+ // between a stopped run and a finished traversal.
603
+ if (pagesStarted > 0) {
604
+ const verdict = await stopAtLimit();
605
+ if (verdict === "limit") return await stop();
606
+ if (verdict === "incomplete") {
607
+ identityLost = true;
608
+ break;
609
+ }
610
+ }
611
+ if (wrapped) break;
612
+ wrapped = true;
613
+ after = undefined;
614
+ continue;
615
+ }
616
+ // Time can run out while the page is fetched: stop before inference,
617
+ // keeping this page eligible for the next run (the cursor stays put).
618
+ // Every run processes at least one page, even one that submits nothing
619
+ // or follows a runtime verification that spent the budget, so bounded
620
+ // runs always progress.
621
+ if (pagesStarted > 0 && limitReached()) return await stop();
622
+ pagesStarted += 1;
623
+ const last = pending.at(-1)!;
624
+ after = { documentId: last.documentId, seq: last.seq };
625
+ // Pages are already limited to deps.collection in SQL.
626
+ const owners = pending;
627
+ const embedPage = () =>
628
+ embedVariantBatch({
629
+ store,
630
+ embedPort: deps.embedPort,
631
+ owners,
632
+ identityStillCurrent,
633
+ force: deps.force,
634
+ acquireWriteTurn: deps.acquireWriteTurn,
635
+ onSubmit,
636
+ });
637
+ let result = background
638
+ ? await withInferencePage(embedPage)
639
+ : await embedPage();
640
+ if (!result) {
641
+ // Past its deadline: this page stays pending for the next pass.
642
+ total.errors += owners.length;
643
+ deps.onProgress?.(total.embedded, total.errors);
644
+ const verdict = await stopAtLimit();
645
+ if (verdict === "limit") return await stop();
646
+ if (verdict === "incomplete") {
647
+ identityLost = true;
648
+ break;
649
+ }
650
+ await Bun.sleep(0);
651
+ continue;
652
+ }
653
+ if (result.deferred) return ok({ ...total, deferred: true });
654
+ // The identity dropped during inference: the batch discarded its
655
+ // results. Its owners stay pending and count as this run's failures
656
+ // (the port is reloaded at the top of the loop).
657
+ if (!identityHolds()) {
257
658
  total.errors += Math.max(
258
659
  0,
259
- retrying -
660
+ owners.length -
260
661
  result.embedded -
261
662
  result.errors -
262
663
  result.contentionErrors -
263
664
  result.retryOwners.length
264
665
  );
265
- } else if (!background) {
266
- // Failed in this run; left pending without a retry past the limit.
267
- total.errors += result.retryOwners.length;
268
- }
269
- deps.onProgress?.(total.embedded, total.errors);
270
- const verdict = await stopAtLimit();
271
- if (verdict === "limit") return await stop();
272
- if (verdict === "incomplete") {
273
- identityLost = true;
274
- break;
666
+ }
667
+ total.embedded += result.embedded;
668
+ total.errors += result.errors;
669
+ total.contentionErrors += result.contentionErrors;
670
+ if (background) total.errors += result.retryOwners.length;
671
+ // A retry counts toward the limits; once they are reached, failed
672
+ // owners stay pending for the next run instead of a further batch.
673
+ if (!background && result.retryOwners.length && !limitReached()) {
674
+ const retrying = result.retryOwners.length;
675
+ result = await embedVariantBatch({
676
+ store,
677
+ embedPort: deps.embedPort,
678
+ owners: result.retryOwners,
679
+ identityStillCurrent,
680
+ force: deps.force,
681
+ onSubmit,
682
+ });
683
+ total.embedded += result.embedded;
684
+ total.errors += result.errors + result.retryOwners.length;
685
+ total.contentionErrors += result.contentionErrors;
686
+ // Same accounting when the identity drops during the retry.
687
+ if (!identityHolds())
688
+ total.errors += Math.max(
689
+ 0,
690
+ retrying -
691
+ result.embedded -
692
+ result.errors -
693
+ result.contentionErrors -
694
+ result.retryOwners.length
695
+ );
696
+ } else if (!background) {
697
+ // Failed in this run; left pending without a retry past the limit.
698
+ total.errors += result.retryOwners.length;
699
+ }
700
+ deps.onProgress?.(total.embedded, total.errors);
701
+ const verdict = await stopAtLimit();
702
+ if (verdict === "limit") return await stop();
703
+ if (verdict === "incomplete") {
704
+ identityLost = true;
705
+ break;
706
+ }
707
+ if (background) await Bun.sleep(0);
275
708
  }
276
- if (background) await Bun.sleep(0);
277
709
  }
278
710
  // A traversal that reached its end leaves nothing to resume.
279
711
  if (!identityLost) await saveResume(undefined);