@gmickel/gno 2.14.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 (205) 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.14.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 +88 -45
  9. package/spec/db/schema.sql +45 -0
  10. package/spec/output-schemas/embed-receipt.schema.json +89 -0
  11. package/src/cli/commands/agents/commands.ts +1 -1
  12. package/src/cli/commands/ask.ts +1 -1
  13. package/src/cli/commands/context-build.ts +1 -1
  14. package/src/cli/commands/embed.ts +341 -20
  15. package/src/cli/commands/links.ts +1 -1
  16. package/src/cli/commands/mcp/install.ts +2 -2
  17. package/src/cli/commands/mcp/status.ts +1 -1
  18. package/src/cli/commands/mcp/uninstall.ts +1 -1
  19. package/src/cli/commands/query.ts +1 -1
  20. package/src/cli/commands/shared.ts +4 -4
  21. package/src/cli/commands/skill/install.ts +1 -1
  22. package/src/cli/commands/skill/paths-cmd.ts +1 -1
  23. package/src/cli/commands/skill/uninstall.ts +1 -1
  24. package/src/cli/commands/status.ts +75 -58
  25. package/src/cli/config-cache.ts +86 -0
  26. package/src/cli/globals.ts +64 -0
  27. package/src/cli/options.ts +23 -0
  28. package/src/cli/program.ts +44 -37
  29. package/src/cli/run.ts +121 -67
  30. package/src/cli/runtime-health.ts +132 -122
  31. package/src/cli/session-binding.ts +11 -2
  32. package/src/config/saver.ts +8 -0
  33. package/src/converters/adapters/browser-export/formats.ts +25 -15
  34. package/src/converters/adapters/email/adapter.ts +37 -53
  35. package/src/converters/adapters/email/html.ts +37 -20
  36. package/src/converters/adapters/email/mime.ts +71 -39
  37. package/src/converters/adapters/ical/adapter.ts +20 -12
  38. package/src/converters/adapters/jsonl/adapter.ts +8 -6
  39. package/src/converters/adapters/shared/html-text.ts +55 -37
  40. package/src/converters/adapters/shared/ooxml-protection.ts +5 -13
  41. package/src/converters/adapters/shared/utf8-lines.ts +69 -31
  42. package/src/converters/adapters/transcript/adapter.ts +12 -7
  43. package/src/converters/adapters/xlsx/adapter.ts +10 -7
  44. package/src/converters/adapters/xlsx/sheet-markdown.ts +93 -50
  45. package/src/converters/canonicalize.ts +17 -3
  46. package/src/converters/native/markdown.ts +24 -17
  47. package/src/converters/native/plaintext.ts +5 -6
  48. package/src/converters/registry.ts +130 -8
  49. package/src/core/activation-status.ts +4 -8
  50. package/src/core/change-diff.ts +38 -11
  51. package/src/core/context-compiler.ts +17 -18
  52. package/src/core/context-evidence.ts +116 -25
  53. package/src/core/context-verifier.ts +70 -31
  54. package/src/core/file-lock.ts +10 -2
  55. package/src/core/graph-analysis.ts +3 -3
  56. package/src/core/link-inventory-markdown.ts +2 -2
  57. package/src/core/links.ts +20 -87
  58. package/src/core/memory-fence.ts +16 -9
  59. package/src/core/memory-recall.ts +168 -34
  60. package/src/core/path-rules.ts +143 -0
  61. package/src/core/section-parse.ts +16 -6
  62. package/src/core/typed-metadata.ts +68 -0
  63. package/src/core/wiki-link-syntax.ts +88 -0
  64. package/src/embed/backlog.ts +173 -60
  65. package/src/embed/batch.ts +83 -12
  66. package/src/embed/resume-cursor.ts +103 -0
  67. package/src/embed/retry.ts +41 -32
  68. package/src/embed/variant-backlog.ts +697 -63
  69. package/src/embed/variant-plan.ts +41 -45
  70. package/src/embed/variant-retry.ts +157 -44
  71. package/src/index.ts +3 -3
  72. package/src/ingestion/budget-error-codes.ts +13 -0
  73. package/src/ingestion/chunker.ts +60 -49
  74. package/src/ingestion/compiled-context.ts +4 -5
  75. package/src/ingestion/convert-file.ts +1 -1
  76. package/src/ingestion/document-metadata.ts +16 -9
  77. package/src/ingestion/excluded-ranges.ts +97 -0
  78. package/src/ingestion/file-processor.ts +122 -37
  79. package/src/ingestion/frontmatter.ts +35 -7
  80. package/src/ingestion/graph-reconciliation.ts +187 -51
  81. package/src/ingestion/language.ts +66 -61
  82. package/src/ingestion/position.ts +5 -5
  83. package/src/ingestion/prepare-file.ts +50 -29
  84. package/src/ingestion/record-adapter-canonical.ts +37 -26
  85. package/src/ingestion/record-adapter.ts +46 -26
  86. package/src/ingestion/record-container.ts +121 -53
  87. package/src/ingestion/record-path.ts +5 -2
  88. package/src/ingestion/source-availability/darwin-io.ts +10 -7
  89. package/src/ingestion/source-availability/darwin-path.ts +21 -3
  90. package/src/ingestion/source-availability/readers.ts +51 -0
  91. package/src/ingestion/strip.ts +39 -105
  92. package/src/ingestion/sync.ts +692 -386
  93. package/src/ingestion/typed-metadata.ts +10 -4
  94. package/src/ingestion/walker.ts +485 -158
  95. package/src/llm/cache.ts +128 -84
  96. package/src/llm/http-inference.ts +112 -35
  97. package/src/llm/http-policy.ts +101 -0
  98. package/src/llm/httpEmbedding.ts +8 -1
  99. package/src/llm/httpGeneration.ts +5 -1
  100. package/src/llm/httpRerank.ts +5 -1
  101. package/src/llm/inference-scope.ts +15 -2
  102. package/src/llm/lazy-ports.ts +33 -3
  103. package/src/llm/lockfile.ts +34 -7
  104. package/src/llm/model-cleanup.ts +24 -0
  105. package/src/llm/native-worker/client.ts +23 -12
  106. package/src/llm/native-worker/dispatcher.ts +19 -9
  107. package/src/llm/native-worker/embedding-identity.ts +42 -16
  108. package/src/llm/native-worker/entry.ts +2 -1
  109. package/src/llm/native-worker/owner.ts +1 -0
  110. package/src/llm/native-worker/ports.ts +86 -23
  111. package/src/llm/native-worker/protocol.ts +386 -55
  112. package/src/llm/nodeLlamaCpp/adapter.ts +46 -29
  113. package/src/llm/nodeLlamaCpp/embedding.ts +93 -40
  114. package/src/llm/nodeLlamaCpp/generation.ts +194 -30
  115. package/src/llm/nodeLlamaCpp/lifecycle.ts +2 -0
  116. package/src/llm/nodeLlamaCpp/rerank-capacity.ts +101 -23
  117. package/src/llm/nodeLlamaCpp/rerank.ts +253 -44
  118. package/src/llm/types.ts +14 -0
  119. package/src/mcp/context.ts +342 -23
  120. package/src/mcp/http-transport.ts +21 -3
  121. package/src/mcp/tool-profile-types.ts +62 -0
  122. package/src/mcp/tool-profile.ts +32 -56
  123. package/src/mcp/tools/context.ts +5 -1
  124. package/src/mcp/tools/index.ts +269 -191
  125. package/src/mcp/tools/links.ts +7 -5
  126. package/src/mcp/tools/query.ts +60 -37
  127. package/src/mcp/tools/vsearch.ts +25 -14
  128. package/src/pipeline/answer.ts +133 -40
  129. package/src/pipeline/claim-verification.ts +293 -189
  130. package/src/pipeline/claim-verifier.ts +6 -7
  131. package/src/pipeline/egress-lineage.ts +37 -26
  132. package/src/pipeline/exclude.ts +34 -11
  133. package/src/pipeline/expansion.ts +233 -19
  134. package/src/pipeline/filters.ts +169 -33
  135. package/src/pipeline/graph-retrieval.ts +117 -61
  136. package/src/pipeline/hybrid.ts +598 -329
  137. package/src/pipeline/hydration.ts +86 -24
  138. package/src/pipeline/intent.ts +15 -7
  139. package/src/pipeline/owner-fusion.ts +61 -19
  140. package/src/pipeline/query-language.ts +15 -2
  141. package/src/pipeline/rerank.ts +15 -22
  142. package/src/pipeline/search.ts +193 -72
  143. package/src/pipeline/snippet.ts +15 -2
  144. package/src/pipeline/temporal.ts +51 -10
  145. package/src/pipeline/vsearch.ts +250 -152
  146. package/src/publish/attachment-raster.ts +2 -16
  147. package/src/publish/encrypted-export.ts +15 -5
  148. package/src/serve/browse-tree.ts +50 -42
  149. package/src/serve/connectors.ts +2 -1
  150. package/src/serve/context.ts +13 -4
  151. package/src/serve/doc-events.ts +3 -0
  152. package/src/serve/public/app.tsx +49 -21
  153. package/src/serve/public/components/BrowseTreeSidebar.tsx +163 -23
  154. package/src/serve/public/components/CaptureModal.tsx +14 -10
  155. package/src/serve/public/components/ai-elements/code-block.tsx +87 -50
  156. package/src/serve/public/components/editor/MarkdownPreview.tsx +99 -67
  157. package/src/serve/public/globals.built.css +1 -1
  158. package/src/serve/public/globals.css +19 -0
  159. package/src/serve/public/hooks/useCaptureModal.tsx +23 -10
  160. package/src/serve/public/lib/metadata-filter.ts +234 -9
  161. package/src/serve/public/pages/Browse.tsx +61 -27
  162. package/src/serve/public/pages/DocView.tsx +44 -25
  163. package/src/serve/public/pages/GraphView.tsx +8 -3
  164. package/src/serve/resident-runtime.ts +199 -48
  165. package/src/serve/routes/api.ts +98 -67
  166. package/src/serve/routes/links.ts +18 -4
  167. package/src/serve/server.ts +1370 -1180
  168. package/src/serve/spa-bundle-source.ts +52 -27
  169. package/src/serve/status.ts +101 -52
  170. package/src/serve/watch-reconciliation-fallback.ts +11 -7
  171. package/src/serve/watch-reconciliation-shared.ts +42 -4
  172. package/src/serve/watch-reconciliation.ts +21 -8
  173. package/src/serve/watch-service-events.ts +7 -1
  174. package/src/serve/watch-service-hosts.ts +3 -1
  175. package/src/serve/watch-service.ts +46 -21
  176. package/src/serve/watch-snapshot-scan.ts +6 -15
  177. package/src/sessions/archive.ts +20 -8
  178. package/src/sessions/sanitize.ts +38 -18
  179. package/src/sessions/service.ts +180 -102
  180. package/src/store/migrations/036-vector-mirror-state.ts +83 -0
  181. package/src/store/migrations/037-performance-indexes.ts +56 -0
  182. package/src/store/migrations/index.ts +4 -0
  183. package/src/store/sqlite/adapter.ts +1217 -651
  184. package/src/store/sqlite/chunking-policy.ts +15 -1
  185. package/src/store/sqlite/eligibility.ts +110 -70
  186. package/src/store/sqlite/graph-neighbors.ts +71 -46
  187. package/src/store/sqlite/graph-reference-state.ts +27 -3
  188. package/src/store/sqlite/graph-similarity.ts +59 -12
  189. package/src/store/sqlite/metadata-predicate.ts +123 -28
  190. package/src/store/sqlite/retrieval-trace-management-store.ts +126 -33
  191. package/src/store/sqlite/retrieval-trace-retention.ts +88 -76
  192. package/src/store/sqlite/retrieval-trace-rows.ts +7 -3
  193. package/src/store/types.ts +32 -0
  194. package/src/store/vector/eligibility.ts +39 -0
  195. package/src/store/vector/lazy.ts +17 -0
  196. package/src/store/vector/partition-index.ts +49 -47
  197. package/src/store/vector/proof-cache.ts +103 -0
  198. package/src/store/vector/sqlite-vec.ts +230 -139
  199. package/src/store/vector/stats.ts +29 -73
  200. package/src/store/vector/status.ts +151 -52
  201. package/src/store/vector/stored-vectors.ts +131 -45
  202. package/src/store/vector/types.ts +10 -0
  203. package/src/store/vector/variant-search.ts +771 -109
  204. package/src/store/vector/variants.ts +785 -144
  205. package/browser-extension/artifacts/gno-browser-clipper-v2.14.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,21 +11,48 @@ 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";
15
+ import {
16
+ compareOwnerCursor,
17
+ isOwnerCursor,
18
+ type OwnerCursor,
19
+ readResumeCursor,
20
+ resumeCursorKey,
21
+ writeResumeCursor,
22
+ } from "./resume-cursor";
12
23
  import { inWriteTurn } from "./retry";
13
24
  import { variantBacklogPage } from "./variant-plan";
14
- 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;
15
35
 
16
36
  /** One bounded owner pass plus one retry; mutations stay durably pending for the next pass. */
17
37
  export async function embedVariantBacklog(
18
38
  deps: EmbedBacklogDeps,
19
39
  store: VectorVariantStore
20
40
  ): Promise<StoreResult<EmbedBacklogResult>> {
21
- const identityStillCurrent = deps.identityStillCurrent;
22
- if (!identityStillCurrent)
41
+ const checkIdentity = deps.identityStillCurrent;
42
+ if (!checkIdentity)
23
43
  return err(
24
44
  "INVALID_INPUT",
25
45
  "Variant embedding requires an effective runtime identity check"
26
46
  );
47
+ // The predicate can throw while a port is half re-initialized (its
48
+ // dimensions are cleared); treat that as "not current" everywhere.
49
+ const identityStillCurrent = (): boolean => {
50
+ try {
51
+ return checkIdentity();
52
+ } catch {
53
+ return false;
54
+ }
55
+ };
27
56
  const db = getVectorStatsDatabase(deps.statsPort);
28
57
  if (deps.collection && !db)
29
58
  return err(
@@ -33,84 +62,689 @@ export async function embedVariantBacklog(
33
62
  const background = isBackgroundInference();
34
63
  const batchSize = background
35
64
  ? Math.min(deps.batchSize ?? 32, 32)
36
- : (deps.batchSize ?? 32);
65
+ : (deps.batchSize ?? DEFAULT_FOREGROUND_BATCH_SIZE);
37
66
  if (!Number.isSafeInteger(batchSize) || batchSize < 1)
38
67
  return err("INVALID_INPUT", "Invalid embedding batch size");
39
68
  const total = { embedded: 0, errors: 0, contentionErrors: 0 };
40
- let after: { documentId: number; seq: number } | undefined;
69
+ const limits = deps.limits;
70
+ const startedAt = performance.now();
71
+ // Chunks charged against --max-chunks: every text submitted to the
72
+ // provider, adaptive recovery resubmissions included. Owners that share an
73
+ // input or reuse a stored vector cost nothing. The limit is checked at
74
+ // batch boundaries.
75
+ let attempted = limits?.spent ?? 0;
76
+ let pagesStarted = 0;
77
+ const onSubmit = (texts: number): void => {
78
+ attempted += texts;
79
+ };
80
+ let identityLost = false;
81
+ // Bounded runs resume after the previous slice and wrap to the start, so a
82
+ // chunk that keeps failing stays pending without blocking later chunks.
83
+ const resumeKey = db
84
+ ? resumeCursorKey(store.partitionId, deps.collection || undefined)
85
+ : undefined;
86
+ const resumeFrom =
87
+ limits && db && resumeKey
88
+ ? readResumeCursor(db, resumeKey, isOwnerCursor)
89
+ : undefined;
90
+ let after: OwnerCursor | undefined = resumeFrom;
91
+ let wrapped = !resumeFrom;
92
+ const saveResume = async (cursor: OwnerCursor | undefined) => {
93
+ if (!db || !resumeKey) return;
94
+ if (!cursor && !readResumeCursor(db, resumeKey, isOwnerCursor)) return;
95
+ // Advisory: a busy database must not turn a finished slice into a
96
+ // failure. The next run then starts from the previous position.
97
+ try {
98
+ await inWriteTurn(deps.acquireWriteTurn, async () =>
99
+ writeResumeCursor(db, resumeKey, cursor)
100
+ );
101
+ } catch {
102
+ // Keep the receipt; resumption is best effort.
103
+ }
104
+ };
105
+ const identityHolds = identityStillCurrent;
106
+ /**
107
+ * A failed request can drop the port's cached identity (a native worker is
108
+ * retired). Reload it once before treating the runtime as changed, so a
109
+ * chunk that keeps failing is a failure, not an identity change.
110
+ */
111
+ const identityCurrent = async (): Promise<boolean> => {
112
+ if (identityHolds()) return true;
113
+ if (background) return false;
114
+ let reloaded: { ok: boolean } | undefined;
115
+ try {
116
+ reloaded = await deps.embedPort.init();
117
+ } catch {
118
+ return false;
119
+ }
120
+ return !!reloaded?.ok && identityHolds();
121
+ };
122
+ const limitReached = (): boolean =>
123
+ !!limits &&
124
+ ((limits.maxChunks !== undefined && attempted >= limits.maxChunks) ||
125
+ (limits.maxSeconds !== undefined &&
126
+ (performance.now() - startedAt) / 1000 >= limits.maxSeconds));
127
+ /**
128
+ * At a batch boundary: "limit" once a bound is reached while owners in
129
+ * scope are still pending, "incomplete" when the runtime cannot be
130
+ * re-established there (never another batch past the limit), else
131
+ * "continue".
132
+ */
133
+ const stopAtLimit = async (): Promise<
134
+ "limit" | "incomplete" | "continue"
135
+ > => {
136
+ if (!limitReached()) return "continue";
137
+ // A runtime change is an incomplete pass, never a limit stop.
138
+ if (!(await identityCurrent())) return "incomplete";
139
+ // A bound reached on the batch that empties the backlog is a finished
140
+ // pass. Under the CLI write lease the starting backlog minus what was
141
+ // committed is exact (failed owners stay pending), so no scan is needed.
142
+ const pending =
143
+ limits?.pendingAtStart !== undefined
144
+ ? limits.pendingAtStart - total.embedded > 0
145
+ : // Otherwise probe: owners after the cursor first, then the first
146
+ // pending owner from the start (including this run's failures).
147
+ variantBacklogPage(deps, store, 1, after).length > 0 ||
148
+ variantBacklogPage(deps, store, 1).length > 0;
149
+ return pending ? "limit" : "continue";
150
+ };
151
+ const stop = async () => {
152
+ await saveResume(after);
153
+ return ok({ ...total, stopped: "limit" as const });
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
+
41
202
  try {
42
- while (true) {
43
- // A failed request drops the port's cached identity (a timed-out native
44
- // worker is retired); reload it so one failed page cannot end the pass.
45
- if (background) {
46
- const reloaded = await withInferencePage(() => deps.embedPort.init());
47
- // Without an identity the pass cannot continue. Failing it schedules
48
- // the scheduler's bounded retry instead of ending with pages pending.
49
- if (!reloaded?.ok)
50
- throw new Error(
51
- reloaded?.error.message ??
52
- "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 }
53
265
  );
54
- }
55
- if (!identityStillCurrent()) break;
56
- assertInferenceActive();
57
- const pending = variantBacklogPage(deps, store, batchSize, after);
58
- if (!pending.length) break;
59
- const last = pending.at(-1)!;
60
- after = { documentId: last.documentId, seq: last.seq };
61
- const owners = deps.collection
62
- ? pending.filter(
63
- (owner) =>
64
- !!db!
65
- .query(
66
- "SELECT 1 FROM documents WHERE id = ? AND collection = ? AND active = 1"
67
- )
68
- .get(owner.documentId, deps.collection!)
69
- )
70
- : pending;
71
- const embedPage = () =>
72
- embedVariantBatch({
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())) {
292
+ identityLost = true;
293
+ break;
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;
302
+ }
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({
73
333
  store,
74
- embedPort: deps.embedPort,
75
- owners,
334
+ owners: entry.prepared.owners,
335
+ reusable: entry.prepared.reusable,
336
+ vectors,
76
337
  identityStillCurrent,
77
- force: deps.force,
78
- acquireWriteTurn: deps.acquireWriteTurn,
79
338
  });
80
- let result = background
81
- ? await withInferencePage(embedPage)
82
- : await embedPage();
83
- if (!result) {
84
- // Past its deadline: this page stays pending for the next pass.
85
- total.errors += owners.length;
86
- deps.onProgress?.(total.embedded, total.errors);
87
- await Bun.sleep(0);
88
- continue;
339
+ await handleForegroundOutcome(entry.owners.length, outcome);
340
+ await fillWindow();
341
+ }
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;
89
350
  }
90
- if (result.deferred) return ok({ ...total, deferred: true });
91
- total.embedded += result.embedded;
92
- total.errors += result.errors;
93
- total.contentionErrors += result.contentionErrors;
94
- if (background) total.errors += result.retryOwners.length;
95
- if (!background && result.retryOwners.length) {
96
- 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({
97
365
  store,
98
- embedPort: deps.embedPort,
99
- owners: result.retryOwners,
100
- identityStillCurrent,
366
+ owners: pending,
101
367
  force: deps.force,
368
+ inFlightHashes,
102
369
  });
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()) {
658
+ total.errors += Math.max(
659
+ 0,
660
+ owners.length -
661
+ result.embedded -
662
+ result.errors -
663
+ result.contentionErrors -
664
+ result.retryOwners.length
665
+ );
666
+ }
103
667
  total.embedded += result.embedded;
104
- total.errors += result.errors + result.retryOwners.length;
668
+ total.errors += result.errors;
105
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);
106
708
  }
107
- deps.onProgress?.(total.embedded, total.errors);
108
- if (background) await Bun.sleep(0);
109
709
  }
710
+ // A traversal that reached its end leaves nothing to resume.
711
+ if (!identityLost) await saveResume(undefined);
110
712
  assertInferenceActive();
713
+ // Retrieval authority was established by the first activation, and
714
+ // search validates every owner at query time, so a later pass does not
715
+ // re-prove index-wide coverage (O(index) on every run) while the vec0
716
+ // mirror is known to be current. A dirty mirror is rebuilt whether or not
717
+ // other collections are still pending, and the partition is re-activated
718
+ // when coverage is complete. Databases without mirror tracking, or without
719
+ // sqlite-vec, keep the full check below.
720
+ if (identityStillCurrent() && store.hasActivated()) {
721
+ const mirror = store.mirrorState();
722
+ if (mirror === "clean") {
723
+ assertInferenceActive();
724
+ return ok(total);
725
+ }
726
+ if (mirror === "dirty") {
727
+ const repairEpoch = store.epoch();
728
+ const turn = await inWriteTurn(deps.acquireWriteTurn, async () => {
729
+ try {
730
+ store.syncIndex();
731
+ if (identityStillCurrent() && !store.hasPending())
732
+ store.activate(repairEpoch);
733
+ return undefined;
734
+ } catch (cause) {
735
+ return cause instanceof Error ? cause.message : String(cause);
736
+ }
737
+ });
738
+ if (turn.deferred) return ok({ ...total, deferred: true });
739
+ if (turn.value !== undefined)
740
+ return ok({ ...total, syncError: turn.value });
741
+ assertInferenceActive();
742
+ return ok(total);
743
+ }
744
+ }
111
745
  // Capture the epoch before checking completeness; activate rechecks under write lock.
112
746
  const epoch = store.epoch();
113
- if (identityStillCurrent() && !store.pending({ limit: 1 }).length) {
747
+ if (identityStillCurrent() && !store.hasPending()) {
114
748
  const turn = await inWriteTurn(deps.acquireWriteTurn, async () => {
115
749
  try {
116
750
  if (!store.isActive()) store.syncIndex();
@@ -125,7 +759,7 @@ export async function embedVariantBacklog(
125
759
  return ok({ ...total, syncError: turn.value });
126
760
  }
127
761
  assertInferenceActive();
128
- return ok(total);
762
+ return ok(identityLost ? { ...total, incomplete: true } : total);
129
763
  } catch (cause) {
130
764
  return err(
131
765
  "QUERY_FAILED",