akm-cli 0.9.15 → 0.9.16-alpha.1
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.
- package/CHANGELOG.md +144 -0
- package/dist/assets/tasks/core/index-refresh.yml +1 -1
- package/dist/cli/retired-commands.js +2 -0
- package/dist/cli/unknown-flags.js +36 -3
- package/dist/commands/improve/collapse-detector.js +2 -2
- package/dist/commands/improve/consolidate.js +6 -4
- package/dist/commands/improve/improve-cli.js +1 -1
- package/dist/commands/proposal/repository.js +12 -3
- package/dist/commands/read/curate.js +34 -44
- package/dist/commands/read/search.js +50 -2
- package/dist/commands/sources/index-status.js +99 -0
- package/dist/commands/sources/info.js +8 -8
- package/dist/commands/sources/installed-stashes.js +33 -12
- package/dist/commands/sources/source-add.js +21 -6
- package/dist/commands/sources/stash-cli.js +119 -111
- package/dist/core/adapter/adapters/akm-adapter.js +35 -3
- package/dist/core/adapter/adapters/akm-metadata.js +11 -1
- package/dist/core/asset/asset-placement.js +35 -0
- package/dist/core/config/schema/embedding.js +7 -30
- package/dist/core/config/schema/search.js +11 -9
- package/dist/core/errors.js +5 -2
- package/dist/core/hash.js +18 -0
- package/dist/core/maintenance-barrier.js +8 -6
- package/dist/core/paths.js +0 -11
- package/dist/core/run-lock.js +5 -2
- package/dist/core/state/migrations.js +26 -1
- package/dist/core/state-db.js +63 -27
- package/dist/indexer/drain.js +306 -0
- package/dist/indexer/embedding-identity.js +20 -0
- package/dist/indexer/enrich.js +260 -0
- package/dist/indexer/ensure-index.js +5 -0
- package/dist/indexer/index-written-assets.js +133 -171
- package/dist/indexer/indexer.js +458 -1621
- package/dist/indexer/lookup/adapter-concept-owner.js +19 -5
- package/dist/indexer/passes/metadata.js +18 -1
- package/dist/indexer/reconcile.js +890 -0
- package/dist/indexer/scan/drain-dir.js +27 -70
- package/dist/indexer/scan/parse-file.js +66 -0
- package/dist/indexer/search/db-search.js +373 -89
- package/dist/indexer/search/ranking-contributors.js +21 -16
- package/dist/indexer/search/ranking.js +135 -57
- package/dist/indexer/units/unit.js +159 -0
- package/dist/llm/client.js +10 -1
- package/dist/llm/embedder.js +10 -3
- package/dist/llm/embedders/provider-limits.js +288 -0
- package/dist/llm/embedders/remote.js +133 -104
- package/dist/llm/feature-gate.js +4 -2
- package/dist/llm/rerank-client.js +3 -3
- package/dist/output/shapes/passthrough.js +1 -0
- package/dist/output/text/command-format.js +19 -13
- package/dist/output/text/helpers.js +1 -1
- package/dist/output/text/index.js +5 -2
- package/dist/scripts/akm-migrate-node.js +1141 -1237
- package/dist/scripts/akm-migrate.js +1141 -1237
- package/dist/setup/semantic-assets.js +2 -2
- package/dist/setup/steps/connection.js +3 -2
- package/dist/storage/repositories/files-repository.js +181 -0
- package/dist/storage/repositories/index-connection.js +1 -3
- package/dist/storage/repositories/index-entries-repository.js +77 -68
- package/dist/storage/repositories/index-entry-schema.js +16 -25
- package/dist/storage/repositories/index-fts-repository.js +29 -263
- package/dist/storage/repositories/index-meta-repository.js +0 -29
- package/dist/storage/repositories/index-schema.js +115 -122
- package/dist/storage/repositories/index-utility-repository.js +1 -1
- package/dist/storage/repositories/index-vec-repository.js +21 -334
- package/dist/storage/repositories/units-repository.js +510 -0
- package/docs/migration/release-notes/0.9.15.md +34 -36
- package/docs/migration/release-notes/0.9.16.md +110 -0
- package/docs/migration/release-notes/README.md +5 -0
- package/docs/reference/cli.md +93 -87
- package/docs/reference/configuration.md +128 -89
- package/docs/reference/data-and-telemetry.md +2 -1
- package/package.json +1 -1
- package/schemas/akm-config.json +2 -58
- package/dist/indexer/index-db-contention.js +0 -56
- package/dist/indexer/index-rebuild-lock.js +0 -73
- package/dist/indexer/materialize-embeddings.js +0 -771
- package/dist/indexer/passes/dir-staleness.js +0 -161
- package/dist/storage/repositories/embedding-salvage-repository.js +0 -184
|
@@ -1,771 +0,0 @@
|
|
|
1
|
-
// This Source Code Form is subject to the terms of the Mozilla Public
|
|
2
|
-
// License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
3
|
-
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
4
|
-
import { getConfigPath } from "../core/paths.js";
|
|
5
|
-
import { isVerbose, warn, warnVerbose } from "../core/warn.js";
|
|
6
|
-
import { embedBatch } from "../llm/embedder.js";
|
|
7
|
-
import { DETERMINISTIC_EMBED_MODEL_ID, isDeterministicEmbedEnabled } from "../llm/embedders/deterministic.js";
|
|
8
|
-
import { DEFAULT_LOCAL_MODEL } from "../llm/embedders/local.js";
|
|
9
|
-
import { buildTokenBoundedBatches, capEmbeddingText, DEFAULT_MAX_INPUT_TOKENS, DEFAULT_REMOTE_BATCH_SIZE, DEFAULT_TOKEN_BUDGET, describeEmbeddingCredential, estimateTokenCount, hasRemoteEndpoint, normalizeEmbeddingEndpoint, } from "../llm/embedders/remote.js";
|
|
10
|
-
import { cosineSimilarity } from "../llm/embedders/types.js";
|
|
11
|
-
import { purgeEmbeddingSalvage, relabelEmbeddingSalvageFingerprint, reuseSalvagedEmbeddings, } from "../storage/repositories/embedding-salvage-repository.js";
|
|
12
|
-
import { getEmbeddableEntryCount } from "../storage/repositories/index-entries-repository.js";
|
|
13
|
-
import { deleteMeta, getMeta, setMeta } from "../storage/repositories/index-meta-repository.js";
|
|
14
|
-
import { getAllEntriesForEmbedding, getEmbeddingCount, isVecFastPathComplete, isVecFastPathReady, purgeEmbeddings, sampleEmbeddedEntriesForCanary, setVecFastPathReady, upsertEmbedding, } from "../storage/repositories/index-vec-repository.js";
|
|
15
|
-
import { reclassifyIndexDbContention } from "./index-db-contention.js";
|
|
16
|
-
/** Identifies the embedding provider+model+dimension a stored vector was generated with. */
|
|
17
|
-
export function deriveSemanticProviderFingerprint(embedding) {
|
|
18
|
-
if (isDeterministicEmbedEnabled()) {
|
|
19
|
-
return `deterministic:${DETERMINISTIC_EMBED_MODEL_ID}`;
|
|
20
|
-
}
|
|
21
|
-
if (embedding?.endpoint) {
|
|
22
|
-
// Fingerprint keys on vector identity only (model + dimension). The endpoint
|
|
23
|
-
// is transport/routing and has no bearing on vector compatibility, so moving
|
|
24
|
-
// the same model+dimension to a different host must not force a full re-embed.
|
|
25
|
-
return `remote:${embedding.model}|${embedding.dimension ?? "default"}`;
|
|
26
|
-
}
|
|
27
|
-
return `local:${embedding?.localModel ?? DEFAULT_LOCAL_MODEL}`;
|
|
28
|
-
}
|
|
29
|
-
/**
|
|
30
|
-
* The heartbeat text emitted every 15s while a provider request is in
|
|
31
|
-
* flight, and by default (not `--verbose`-only) since silence indistinguishable
|
|
32
|
-
* from a hang was the field report's own symptom (#954).
|
|
33
|
-
*/
|
|
34
|
-
export function formatEmbeddingHeartbeat(storedCount, total, failedCount) {
|
|
35
|
-
return `Still generating embeddings: ${storedCount}/${total} stored, ${failedCount} failed; waiting on embedding provider.`;
|
|
36
|
-
}
|
|
37
|
-
/**
|
|
38
|
-
* Number of already-embedded entries sampled for the fingerprint-rename
|
|
39
|
-
* canary (#955) — small and cheap even against a slow local server; a
|
|
40
|
-
* handful of chunks is a strong compatibility signal (a different model
|
|
41
|
-
* cannot plausibly land near-identical vectors by chance).
|
|
42
|
-
*/
|
|
43
|
-
const CANARY_SAMPLE_SIZE = 8;
|
|
44
|
-
/**
|
|
45
|
-
* Minimum median cosine similarity between stored and freshly re-embedded
|
|
46
|
-
* canary vectors for a fingerprint-string change to be treated as a
|
|
47
|
-
* same-model rename rather than a real model change (#955).
|
|
48
|
-
*/
|
|
49
|
-
const CANARY_SIMILARITY_THRESHOLD = 0.999;
|
|
50
|
-
/**
|
|
51
|
-
* Consecutive transport failures after which the embedding pass stops
|
|
52
|
-
* dispatching further requests and ends the run as a failure rather than
|
|
53
|
-
* grinding through every remaining batch against a dead endpoint (#954).
|
|
54
|
-
* Two independent trip conditions
|
|
55
|
-
* share this threshold — see `onSkip` below: 3 consecutive failures at
|
|
56
|
-
* single-document size (timeout OR network error — a multi-document
|
|
57
|
-
* timeout is not by itself evidence the endpoint is dead, since
|
|
58
|
-
* `RemoteEmbedder.embedBatch` already retries and splits it smaller before
|
|
59
|
-
* ever reporting it as failed at single-document size), or 3 consecutive
|
|
60
|
-
* network errors at ANY size (a network error is never retried, so it is
|
|
61
|
-
* trusted immediately regardless of how large the request was).
|
|
62
|
-
* `context-window-exceeded` never counts — that reason proves the provider
|
|
63
|
-
* IS reachable, and split-and-retry already handles it; it resets both
|
|
64
|
-
* streaks instead.
|
|
65
|
-
*/
|
|
66
|
-
const CIRCUIT_BREAKER_THRESHOLD = 3;
|
|
67
|
-
/**
|
|
68
|
-
* Pure decision: do stored vectors remain valid against freshly re-embedded
|
|
69
|
-
* canary samples? The ONE place that computes the canary's similarity
|
|
70
|
-
* numbers — callers must use this result rather than recomputing it (#955).
|
|
71
|
-
*
|
|
72
|
-
* An empty sample means nothing is stored to lose or verify against, so
|
|
73
|
-
* there is nothing to decide — keep.
|
|
74
|
-
*
|
|
75
|
-
* A sample whose re-embed FAILED (`fresh === undefined`, e.g. a provider
|
|
76
|
-
* sub-batch that was skipped) is EXCLUDED from the similarity computation
|
|
77
|
-
* entirely, not scored as zero: a partial provider failure is not evidence
|
|
78
|
-
* of a different model (#955). A dimension mismatch on a successful
|
|
79
|
-
* re-embed still counts as zero similarity via {@link cosineSimilarity}'s
|
|
80
|
-
* own dimension-mismatch guard — that IS evidence. When half or fewer of
|
|
81
|
-
* the sampled entries re-embedded successfully, the sample is too thin to
|
|
82
|
-
* trust either verdict — the outcome is `unverifiable`, the same outcome a
|
|
83
|
-
* total canary failure already produces.
|
|
84
|
-
*
|
|
85
|
-
* Otherwise the MEDIAN pairwise cosine similarity of the verified samples
|
|
86
|
-
* must clear {@link CANARY_SIMILARITY_THRESHOLD}; the median (not the
|
|
87
|
-
* minimum or mean) tolerates one stale or lightly-edited sample without
|
|
88
|
-
* either discarding a real match or being fooled by it.
|
|
89
|
-
*/
|
|
90
|
-
export function decideEmbeddingCompatibility(pairs) {
|
|
91
|
-
if (pairs.length === 0)
|
|
92
|
-
return { outcome: "keep", medianSimilarity: undefined, verifiedSamples: 0 };
|
|
93
|
-
const verified = pairs.filter((pair) => pair.fresh !== undefined);
|
|
94
|
-
if (verified.length * 2 <= pairs.length) {
|
|
95
|
-
return { outcome: "unverifiable", medianSimilarity: undefined, verifiedSamples: verified.length };
|
|
96
|
-
}
|
|
97
|
-
const similarities = verified.map((pair) => cosineSimilarity(pair.stored, pair.fresh));
|
|
98
|
-
const medianSimilarity = medianOf(similarities);
|
|
99
|
-
return {
|
|
100
|
-
outcome: medianSimilarity >= CANARY_SIMILARITY_THRESHOLD ? "keep" : "rebuild",
|
|
101
|
-
medianSimilarity,
|
|
102
|
-
verifiedSamples: verified.length,
|
|
103
|
-
};
|
|
104
|
-
}
|
|
105
|
-
function medianOf(values) {
|
|
106
|
-
const sorted = [...values].sort((a, b) => a - b);
|
|
107
|
-
const mid = Math.floor(sorted.length / 2);
|
|
108
|
-
return sorted.length % 2 === 0
|
|
109
|
-
? (sorted[mid - 1] + sorted[mid]) / 2
|
|
110
|
-
: sorted[mid];
|
|
111
|
-
}
|
|
112
|
-
/**
|
|
113
|
-
* Identity of the embedding vectors actually observed on a run — as opposed
|
|
114
|
-
* to {@link deriveSemanticProviderFingerprint}'s CONFIG-derived string. Keys
|
|
115
|
-
* on what the server (or local model) actually reported plus the observed
|
|
116
|
-
* vector width, so a gateway/transport change that keeps returning the same
|
|
117
|
-
* underlying model can be told apart from a genuine model change without
|
|
118
|
-
* relying on the operator's config string (#955).
|
|
119
|
-
* Returns undefined when nothing was actually observed this call (no vector
|
|
120
|
-
* to measure yet).
|
|
121
|
-
*/
|
|
122
|
-
function deriveObservedEmbeddingIdentity(embedding, observedModel, observedVectorLen) {
|
|
123
|
-
if (isDeterministicEmbedEnabled()) {
|
|
124
|
-
return `deterministic:${DETERMINISTIC_EMBED_MODEL_ID}`;
|
|
125
|
-
}
|
|
126
|
-
if (observedVectorLen === undefined)
|
|
127
|
-
return undefined;
|
|
128
|
-
if (embedding?.endpoint) {
|
|
129
|
-
return `remote:${observedModel ?? embedding.model ?? "unknown"}|${observedVectorLen}`;
|
|
130
|
-
}
|
|
131
|
-
return `local:${embedding?.localModel ?? DEFAULT_LOCAL_MODEL}|${observedVectorLen}`;
|
|
132
|
-
}
|
|
133
|
-
/**
|
|
134
|
-
* Run the fingerprint-rename canary: re-embed a small sample of already-
|
|
135
|
-
* stored entries with the CURRENT config and decide whether the stored
|
|
136
|
-
* index survives. Goes through the standard {@link embedBatch} facade (not a
|
|
137
|
-
* direct `RemoteEmbedder`) so every embedder branch — remote, local,
|
|
138
|
-
* deterministic, and test overrides via `_setEmbedderForTests` — is
|
|
139
|
-
* exercised identically to the main embedding pass.
|
|
140
|
-
*
|
|
141
|
-
* `maxInputTokens` must be the SAME cap the main pass below applies via
|
|
142
|
-
* {@link capEmbeddingText} — the stored vector for each sampled entry was
|
|
143
|
-
* produced from its capped text, so comparing against a fresh vector of the
|
|
144
|
-
* uncapped text would compare unlike inputs for any entry over the cap
|
|
145
|
-
* (#955).
|
|
146
|
-
*/
|
|
147
|
-
async function runEmbeddingCanary(db, config, signal, maxInputTokens) {
|
|
148
|
-
const samples = sampleEmbeddedEntriesForCanary(db, CANARY_SAMPLE_SIZE);
|
|
149
|
-
if (samples.length === 0) {
|
|
150
|
-
return { outcome: "keep", verified: false, viaIdentityMatch: false };
|
|
151
|
-
}
|
|
152
|
-
let observedModel;
|
|
153
|
-
const skips = [];
|
|
154
|
-
let canaryVectors;
|
|
155
|
-
try {
|
|
156
|
-
canaryVectors = await embedBatch(
|
|
157
|
-
// #955: the stored vector for each sample was produced from
|
|
158
|
-
// capEmbeddingText(searchText, maxInputTokens) — the main pass below
|
|
159
|
-
// caps every document before embedding it. The canary must re-embed
|
|
160
|
-
// the SAME capped text, or an entry over the cap compares a fresh
|
|
161
|
-
// vector of a different input against a stored vector of the capped
|
|
162
|
-
// one, and a genuine model match can read as a rebuild-worthy
|
|
163
|
-
// mismatch for reasons unrelated to the model.
|
|
164
|
-
samples.map((sample) => capEmbeddingText(sample.searchText, maxInputTokens).text), config.embedding, signal, (skip) => skips.push(skip), (_indices, _embeddings, model) => {
|
|
165
|
-
if (model)
|
|
166
|
-
observedModel = model;
|
|
167
|
-
});
|
|
168
|
-
}
|
|
169
|
-
catch (error) {
|
|
170
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
171
|
-
return {
|
|
172
|
-
outcome: "unverifiable",
|
|
173
|
-
message: `could not verify embedding compatibility (${message}); keeping existing vectors — rerun akm index when the endpoint is reachable`,
|
|
174
|
-
};
|
|
175
|
-
}
|
|
176
|
-
const observedVectorLen = canaryVectors.find((vector) => vector !== undefined)?.length;
|
|
177
|
-
const observedIdentity = deriveObservedEmbeddingIdentity(config.embedding, observedModel, observedVectorLen);
|
|
178
|
-
const storedIdentity = getMeta(db, "embeddingIdentity");
|
|
179
|
-
if (storedIdentity && observedIdentity && storedIdentity === observedIdentity) {
|
|
180
|
-
// The server reports the same model identity as last time — no need to
|
|
181
|
-
// even look at the cosines; the config string alone was misleading.
|
|
182
|
-
return { outcome: "keep", verified: true, identity: observedIdentity, viaIdentityMatch: true };
|
|
183
|
-
}
|
|
184
|
-
const pairs = samples.map((sample, i) => ({ stored: sample.vector, fresh: canaryVectors[i] }));
|
|
185
|
-
const decision = decideEmbeddingCompatibility(pairs);
|
|
186
|
-
if (decision.outcome === "unverifiable") {
|
|
187
|
-
// Covers both a total provider failure (RemoteEmbedder skips a failing
|
|
188
|
-
// request rather than throwing, #874, so an unreachable endpoint
|
|
189
|
-
// surfaces here as an all-`undefined` canary result, not a caught
|
|
190
|
-
// exception) and a partial one thin enough that neither verdict can be
|
|
191
|
-
// trusted (#955) — same message path either way.
|
|
192
|
-
const message = skips[0]?.message ?? "embedding provider returned no vectors for the canary sample";
|
|
193
|
-
return {
|
|
194
|
-
outcome: "unverifiable",
|
|
195
|
-
message: `could not verify embedding compatibility (${message}); keeping existing vectors — rerun akm index when the endpoint is reachable`,
|
|
196
|
-
};
|
|
197
|
-
}
|
|
198
|
-
if (decision.outcome === "keep") {
|
|
199
|
-
return {
|
|
200
|
-
outcome: "keep",
|
|
201
|
-
verified: true,
|
|
202
|
-
identity: observedIdentity,
|
|
203
|
-
viaIdentityMatch: false,
|
|
204
|
-
medianSimilarity: decision.medianSimilarity,
|
|
205
|
-
};
|
|
206
|
-
}
|
|
207
|
-
return {
|
|
208
|
-
outcome: "rebuild",
|
|
209
|
-
identity: observedIdentity,
|
|
210
|
-
reason: `vectors differ (median similarity ${decision.medianSimilarity?.toFixed(3)})`,
|
|
211
|
-
};
|
|
212
|
-
}
|
|
213
|
-
function throwIfAborted(signal) {
|
|
214
|
-
if (signal?.aborted) {
|
|
215
|
-
throw signal.reason instanceof Error ? signal.reason : new Error("index interrupted");
|
|
216
|
-
}
|
|
217
|
-
}
|
|
218
|
-
export async function generateEmbeddingsForDb(db, config, onProgress, signal, entryIds, opts) {
|
|
219
|
-
// Drift guard (#954): refuse an ambient transaction. Every
|
|
220
|
-
// per-batch `db.transaction()` below is meant to be its own durable commit
|
|
221
|
-
// (#954) — inside an already-open outer transaction it would nest as an
|
|
222
|
-
// unobservable SAVEPOINT instead, so an interruption (competing-process
|
|
223
|
-
// collision, SIGKILL) could lose the whole pass rather than only the batch
|
|
224
|
-
// in flight. This is an internal contract error (a caller bug), not a
|
|
225
|
-
// user-facing failure class: callers with their own transaction (e.g. `akm
|
|
226
|
-
// bundle update`'s unified update transaction) must run the embedding
|
|
227
|
-
// phase on a separate connection AFTER their own transaction commits — see
|
|
228
|
-
// `runEmbeddingPass` in `src/indexer/indexer.ts`.
|
|
229
|
-
if (db.inTransaction) {
|
|
230
|
-
throw new Error("generateEmbeddingsForDb was called with an ambient transaction already open on `db`: per-batch commits " +
|
|
231
|
-
"would become SAVEPOINTs inside it, losing the crash-durability contract per-batch commit exists for. " +
|
|
232
|
-
"Run the embedding phase on a connection with no open transaction.");
|
|
233
|
-
}
|
|
234
|
-
throwIfAborted(signal);
|
|
235
|
-
if (config.semanticSearchMode === "off") {
|
|
236
|
-
// #955: salvage is self-emptying only if every path that skips reuse
|
|
237
|
-
// also drains it — otherwise a full rebuild performed with semantic
|
|
238
|
-
// search disabled leaves permanent orphaned rows behind (nothing will
|
|
239
|
-
// ever consume them, since this path never reaches the reuse step).
|
|
240
|
-
purgeEmbeddingSalvage(db);
|
|
241
|
-
onProgress({ phase: "embeddings", message: "Semantic search disabled; skipping embeddings." });
|
|
242
|
-
return { success: false, message: "Semantic search is disabled." };
|
|
243
|
-
}
|
|
244
|
-
// #953 field gap: the actionable outcome is a self-diagnosing run, not a
|
|
245
|
-
// fix (every RemoteEmbedder path already resolves secret:// through one
|
|
246
|
-
// boundary — a keyless request can only mean embedding.apiKey was absent
|
|
247
|
-
// from the config THIS run loaded). One default-level line, before the
|
|
248
|
-
// first provider request of the phase (the canary probe or the main
|
|
249
|
-
// pass, whichever runs first below), naming the endpoint/model/credential
|
|
250
|
-
// SOURCE — never the credential value.
|
|
251
|
-
if (hasRemoteEndpoint(config.embedding ?? {})) {
|
|
252
|
-
const endpoint = normalizeEmbeddingEndpoint(config.embedding?.endpoint ?? "");
|
|
253
|
-
const credential = describeEmbeddingCredential(config.embedding?.apiKey);
|
|
254
|
-
const configFileSuffix = isVerbose() ? `; config: ${getConfigPath()}` : "";
|
|
255
|
-
onProgress({
|
|
256
|
-
phase: "embeddings",
|
|
257
|
-
message: `[embed] endpoint ${endpoint}, model ${config.embedding?.model ?? "unknown"}; credential: ${credential}${configFileSuffix}`,
|
|
258
|
-
});
|
|
259
|
-
}
|
|
260
|
-
// A targeted call starts from an already-published generation. Preserve its
|
|
261
|
-
// trust decision in O(1): successful writes for the changed IDs keep a
|
|
262
|
-
// healthy fast path healthy, but can never promote a generation already
|
|
263
|
-
// marked degraded. Global runs can afford to verify the entire derived set.
|
|
264
|
-
const vecFastPathWasReady = isVecFastPathReady(db);
|
|
265
|
-
const currentFingerprint = deriveSemanticProviderFingerprint(config.embedding);
|
|
266
|
-
const storedFingerprint = getMeta(db, "embeddingFingerprint");
|
|
267
|
-
let targetEntryIds = entryIds;
|
|
268
|
-
/** Set only on an actual rebuild, so the up-front "Re-embedding N entries" line names why. */
|
|
269
|
-
let rebuildReason;
|
|
270
|
-
// Resolved once and reused by both the canary (below) and the main pass's
|
|
271
|
-
// cap loop (further down) — the same cap must apply to both, or the canary
|
|
272
|
-
// compares a differently-capped text against the stored vector (#955).
|
|
273
|
-
const maxInputTokens = config.embedding?.maxInputTokens ?? DEFAULT_MAX_INPUT_TOKENS;
|
|
274
|
-
if (opts?.forceReembed) {
|
|
275
|
-
// `akm index --reembed`: an explicit operator override, skips the canary
|
|
276
|
-
// entirely. The new fingerprint (and identity, now stale/unknown until
|
|
277
|
-
// the next successful pass observes it) is written in the SAME
|
|
278
|
-
// transaction as the purge, before any embedding request — a restart
|
|
279
|
-
// then sees a matching fingerprint and only heals what is still missing
|
|
280
|
-
// instead of purging again from zero (#955/#956).
|
|
281
|
-
db.transaction(() => {
|
|
282
|
-
purgeEmbeddings(db, { dropVecTable: true });
|
|
283
|
-
// #955: an explicit forced rebuild must re-embed everything, not
|
|
284
|
-
// quietly satisfy some of it from stale salvage.
|
|
285
|
-
purgeEmbeddingSalvage(db);
|
|
286
|
-
deleteMeta(db, "embeddingDim");
|
|
287
|
-
setMeta(db, "embeddingFingerprint", currentFingerprint);
|
|
288
|
-
deleteMeta(db, "embeddingIdentity");
|
|
289
|
-
})();
|
|
290
|
-
targetEntryIds = undefined;
|
|
291
|
-
rebuildReason = "forced by --reembed";
|
|
292
|
-
}
|
|
293
|
-
else if (storedFingerprint && storedFingerprint !== currentFingerprint) {
|
|
294
|
-
const decision = await runEmbeddingCanary(db, config, signal, maxInputTokens);
|
|
295
|
-
if (decision.outcome === "unverifiable") {
|
|
296
|
-
// Destroying a good index because the server happens to be down right
|
|
297
|
-
// now is worse than leaving a rename unverified until the next run —
|
|
298
|
-
// keep the vectors AND the old fingerprint so the next `akm index`
|
|
299
|
-
// retries the canary instead of silently treating this as resolved.
|
|
300
|
-
warn(`[embed] ${decision.message}`);
|
|
301
|
-
onProgress({ phase: "embeddings", message: decision.message });
|
|
302
|
-
return { success: false, message: decision.message };
|
|
303
|
-
}
|
|
304
|
-
if (decision.outcome === "rebuild") {
|
|
305
|
-
db.transaction(() => {
|
|
306
|
-
purgeEmbeddings(db, { dropVecTable: true });
|
|
307
|
-
// #955: the stored vectors AND any leftover salvage both belong to
|
|
308
|
-
// a different model now — neither is reusable, so both go.
|
|
309
|
-
purgeEmbeddingSalvage(db);
|
|
310
|
-
deleteMeta(db, "embeddingDim");
|
|
311
|
-
setMeta(db, "embeddingFingerprint", currentFingerprint);
|
|
312
|
-
if (decision.identity)
|
|
313
|
-
setMeta(db, "embeddingIdentity", decision.identity);
|
|
314
|
-
else
|
|
315
|
-
deleteMeta(db, "embeddingIdentity");
|
|
316
|
-
})();
|
|
317
|
-
targetEntryIds = undefined;
|
|
318
|
-
rebuildReason = decision.reason;
|
|
319
|
-
}
|
|
320
|
-
else {
|
|
321
|
-
// Keep: adopt the new fingerprint (and identity, when observed)
|
|
322
|
-
// immediately rather than deferring to end-of-run — nothing was
|
|
323
|
-
// purged, so there is nothing an interruption could lose, and an
|
|
324
|
-
// immediate write means a crash right after this decision does not
|
|
325
|
-
// re-run the canary needlessly on the next attempt.
|
|
326
|
-
setMeta(db, "embeddingFingerprint", currentFingerprint);
|
|
327
|
-
// #955: the model did not actually change, only the fingerprint
|
|
328
|
-
// STRING did (e.g. a gateway rename) — any leftover salvage rows
|
|
329
|
-
// tagged with the OLD string are still valid vectors. Relabel them so
|
|
330
|
-
// the reuse step below (and any later pass) can still find them.
|
|
331
|
-
relabelEmbeddingSalvageFingerprint(db, storedFingerprint, currentFingerprint);
|
|
332
|
-
if (decision.identity)
|
|
333
|
-
setMeta(db, "embeddingIdentity", decision.identity);
|
|
334
|
-
if (decision.verified) {
|
|
335
|
-
const keptCount = getEmbeddingCount(db);
|
|
336
|
-
const detail = decision.viaIdentityMatch
|
|
337
|
-
? "server-reported model unchanged"
|
|
338
|
-
: `stored vectors are compatible (median similarity ${decision.medianSimilarity?.toFixed(3)})`;
|
|
339
|
-
const message = `[embed] embedding model renamed (${storedFingerprint} → ${currentFingerprint}); ${detail}, keeping ${keptCount} embedding${keptCount === 1 ? "" : "s"}.`;
|
|
340
|
-
warn(message);
|
|
341
|
-
onProgress({ phase: "embeddings", message });
|
|
342
|
-
}
|
|
343
|
-
// Empty-sample case (decision.verified === false): nothing stored to
|
|
344
|
-
// lose or verify against — adopt the label silently, no purge line.
|
|
345
|
-
}
|
|
346
|
-
}
|
|
347
|
-
else {
|
|
348
|
-
// No rename to verify (either this is the very first
|
|
349
|
-
// pass ever for this db, or the fingerprint already matches the last
|
|
350
|
-
// successful one) — still record it NOW rather than deferring to a
|
|
351
|
-
// fully successful pass, mirroring the rebuild/keep branches above
|
|
352
|
-
// (#955/#956). Without this, an interrupted FIRST-EVER pass left
|
|
353
|
-
// `embeddingFingerprint` unset despite a per-batch commit below (#954)
|
|
354
|
-
// already having durably written real vectors — a later `akm index
|
|
355
|
-
// --full`'s salvage-before-discard step tags rows by this meta
|
|
356
|
-
// (`salvageEmbeddingsBeforeDiscard`) and treats an unset fingerprint as
|
|
357
|
-
// "nothing was ever verified", silently turning genuinely-embedded
|
|
358
|
-
// vectors into a full re-embed instead of a salvage-and-reuse.
|
|
359
|
-
setMeta(db, "embeddingFingerprint", currentFingerprint);
|
|
360
|
-
}
|
|
361
|
-
try {
|
|
362
|
-
throwIfAborted(signal);
|
|
363
|
-
const allEntries = getAllEntriesForEmbedding(db, targetEntryIds);
|
|
364
|
-
let vecFailedCount = 0;
|
|
365
|
-
let vecUnavailableCount = 0;
|
|
366
|
-
// #955: before any provider call, hand back vectors salvaged from a
|
|
367
|
-
// full rebuild or a generation bump for entries whose search_text is
|
|
368
|
-
// byte-identical to what was salvaged under the SAME fingerprint — a
|
|
369
|
-
// fingerprint mismatch or a single-byte content change both correctly
|
|
370
|
-
// fall through to the provider below instead.
|
|
371
|
-
const { reusedCount, remaining: candidateEntries } = reuseSalvagedEmbeddings(db, allEntries, currentFingerprint, (entry, embedding) => {
|
|
372
|
-
const result = upsertEmbedding(db, entry.id, embedding);
|
|
373
|
-
if (result.vec === "failed")
|
|
374
|
-
vecFailedCount++;
|
|
375
|
-
if (result.vec === "unavailable")
|
|
376
|
-
vecUnavailableCount++;
|
|
377
|
-
return result.stored;
|
|
378
|
-
});
|
|
379
|
-
if (reusedCount > 0) {
|
|
380
|
-
onProgress({
|
|
381
|
-
phase: "embeddings",
|
|
382
|
-
message: `Reused ${reusedCount} embedding${reusedCount === 1 ? "" : "s"} from the previous generation; embedding ${candidateEntries.length} new.`,
|
|
383
|
-
});
|
|
384
|
-
}
|
|
385
|
-
if (candidateEntries.length === 0) {
|
|
386
|
-
onProgress({ phase: "embeddings", message: "Embeddings already up to date." });
|
|
387
|
-
setMeta(db, "embeddingFingerprint", currentFingerprint);
|
|
388
|
-
if (reusedCount > 0) {
|
|
389
|
-
const vecGenerationComplete = targetEntryIds === undefined ? isVecFastPathComplete(db) : vecFastPathWasReady;
|
|
390
|
-
setVecFastPathReady(db, vecFailedCount === 0 && vecUnavailableCount === 0 && vecGenerationComplete);
|
|
391
|
-
}
|
|
392
|
-
// A pass that completes (even one that did nothing but reuse) purges
|
|
393
|
-
// whatever is left — salvage is consumed by the NEXT pass, never kept
|
|
394
|
-
// around as a second cache.
|
|
395
|
-
purgeEmbeddingSalvage(db);
|
|
396
|
-
return reusedCount > 0 ? { success: true, vecInsertFailures: vecFailedCount } : { success: true };
|
|
397
|
-
}
|
|
398
|
-
// Cap each document's embedded text at
|
|
399
|
-
// embedding.maxInputTokens (default DEFAULT_MAX_INPUT_TOKENS, resolved
|
|
400
|
-
// once above so the canary uses the identical cap) instead of ever
|
|
401
|
-
// failing a whole batch over one oversized entry — truncation keeps the
|
|
402
|
-
// head of the text, unicode-safe. A document is skipped only when its
|
|
403
|
-
// head is empty (the impossible case: nothing left to embed), never
|
|
404
|
-
// merely for being long.
|
|
405
|
-
let truncatedCount = 0;
|
|
406
|
-
const texts = [];
|
|
407
|
-
const pendingEntries = [];
|
|
408
|
-
for (const entry of candidateEntries) {
|
|
409
|
-
const capped = capEmbeddingText(entry.searchText, maxInputTokens);
|
|
410
|
-
if (capped.text.length === 0)
|
|
411
|
-
continue;
|
|
412
|
-
if (capped.truncated)
|
|
413
|
-
truncatedCount++;
|
|
414
|
-
pendingEntries.push(entry);
|
|
415
|
-
texts.push(capped.text);
|
|
416
|
-
}
|
|
417
|
-
if (truncatedCount > 0) {
|
|
418
|
-
// Through onProgress ONLY, not warn() too — onProgress already reaches
|
|
419
|
-
// stderr at the default level in every output mode (#954), and the
|
|
420
|
-
// index CLI's progress handler writes it through info() (log-file
|
|
421
|
-
// aware), so calling warn() as well printed the identical sentence
|
|
422
|
-
// twice in text mode.
|
|
423
|
-
const message = `[embed] ${truncatedCount} entr${truncatedCount === 1 ? "y" : "ies"} truncated to the ${maxInputTokens}-token embedding cap (embedding.maxInputTokens); rerun with a higher cap to embed the full text.`;
|
|
424
|
-
onProgress({ phase: "embeddings", message });
|
|
425
|
-
}
|
|
426
|
-
if (rebuildReason) {
|
|
427
|
-
// See the truncation notice above: onProgress ONLY.
|
|
428
|
-
const message = `[embed] Re-embedding ${pendingEntries.length} entr${pendingEntries.length === 1 ? "y" : "ies"} because ${rebuildReason}`;
|
|
429
|
-
onProgress({ phase: "embeddings", message });
|
|
430
|
-
}
|
|
431
|
-
onProgress({
|
|
432
|
-
phase: "embeddings",
|
|
433
|
-
message: `Generating embeddings for ${pendingEntries.length} entr${pendingEntries.length === 1 ? "y" : "ies"}.`,
|
|
434
|
-
});
|
|
435
|
-
if (isVerbose()) {
|
|
436
|
-
// Mirror RemoteEmbedder's actual token-bounded batching (#874) so this
|
|
437
|
-
// log reflects the real request grouping rather than a fixed count of
|
|
438
|
-
// 100 that no longer matches what gets sent over the wire. Local runs
|
|
439
|
-
// don't batch by size at all (LocalEmbedder chunks by a fixed count
|
|
440
|
-
// for inference throughput only, never fails/skips), so there's
|
|
441
|
-
// nothing meaningful to report per-batch for them.
|
|
442
|
-
if (hasRemoteEndpoint(config.embedding ?? {})) {
|
|
443
|
-
// Mirrors RemoteEmbedder.embedBatch's own tokenBudget resolution
|
|
444
|
-
// (#956: contextLength no longer feeds this).
|
|
445
|
-
const tokenBudget = config.embedding?.maxTokens ?? DEFAULT_TOKEN_BUDGET;
|
|
446
|
-
const maxCount = config.embedding?.batchSize ?? DEFAULT_REMOTE_BATCH_SIZE;
|
|
447
|
-
const batches = buildTokenBoundedBatches(texts, tokenBudget, maxCount);
|
|
448
|
-
const batchNumberByIndex = new Map();
|
|
449
|
-
batches.forEach((batch, batchIdx) => {
|
|
450
|
-
for (const i of batch.indices)
|
|
451
|
-
batchNumberByIndex.set(i, batchIdx + 1);
|
|
452
|
-
});
|
|
453
|
-
for (const [i, entry] of pendingEntries.entries()) {
|
|
454
|
-
const chars = entry.searchText.length;
|
|
455
|
-
const tokens = estimateTokenCount(entry.searchText);
|
|
456
|
-
const batch = batches[batchNumberByIndex.get(i) - 1];
|
|
457
|
-
const label = batch?.oversized
|
|
458
|
-
? "oversized (skipped)"
|
|
459
|
-
: `batch ${batchNumberByIndex.get(i)}/${batches.length}`;
|
|
460
|
-
warnVerbose(`[embed] ${entry.itemRef} (${chars} chars, est. ${tokens} tokens) → ${label}`);
|
|
461
|
-
}
|
|
462
|
-
}
|
|
463
|
-
else {
|
|
464
|
-
for (const entry of pendingEntries) {
|
|
465
|
-
warnVerbose(`[embed] ${entry.itemRef} (${entry.searchText.length} chars, est. ${estimateTokenCount(entry.searchText)} tokens)`);
|
|
466
|
-
}
|
|
467
|
-
}
|
|
468
|
-
}
|
|
469
|
-
let heartbeatTimer;
|
|
470
|
-
let storedCount = 0;
|
|
471
|
-
let skippedCount = 0;
|
|
472
|
-
let embedFailedCount = 0;
|
|
473
|
-
let storedTokens = 0;
|
|
474
|
-
try {
|
|
475
|
-
heartbeatTimer = setInterval(() => {
|
|
476
|
-
onProgress({
|
|
477
|
-
phase: "embeddings",
|
|
478
|
-
message: formatEmbeddingHeartbeat(storedCount, pendingEntries.length, embedFailedCount),
|
|
479
|
-
});
|
|
480
|
-
}, 15000);
|
|
481
|
-
// A failing sub-batch or an oversized document is SKIPPED by embedBatch,
|
|
482
|
-
// not thrown (#874) — collect what couldn't be embedded and why, so a
|
|
483
|
-
// few bad documents don't discard every other entry's embedding.
|
|
484
|
-
const skips = [];
|
|
485
|
-
const embedStart = Date.now();
|
|
486
|
-
// Circuit breaker (#954): stop
|
|
487
|
-
// dispatching further batches once either consecutive-failure streak
|
|
488
|
-
// below reaches CIRCUIT_BREAKER_THRESHOLD — a dead/hung provider used
|
|
489
|
-
// to grind through every remaining batch for hours, one 30s (now
|
|
490
|
-
// configurable, and now backed off/retried/split first — see
|
|
491
|
-
// RemoteEmbedder.embedBatch) timeout at a time, ending in one
|
|
492
|
-
// aggregate warning and `ok: true`. Counted per BATCH
|
|
493
|
-
// (`skip.batchStart`), not per document: a single failed 100-document
|
|
494
|
-
// batch must not look like 100 consecutive failures.
|
|
495
|
-
let consecutiveSingleDocFailures = 0;
|
|
496
|
-
let consecutiveNetworkErrorFailures = 0;
|
|
497
|
-
let circuitBreakerReason;
|
|
498
|
-
const onSkip = (skip) => {
|
|
499
|
-
skips.push(skip);
|
|
500
|
-
if (!skip.batchStart)
|
|
501
|
-
return undefined;
|
|
502
|
-
if (skip.reason === "context-window-exceeded") {
|
|
503
|
-
consecutiveSingleDocFailures = 0;
|
|
504
|
-
consecutiveNetworkErrorFailures = 0;
|
|
505
|
-
return undefined;
|
|
506
|
-
}
|
|
507
|
-
// "batch-request-failed": a timeout only counts once retries have
|
|
508
|
-
// already narrowed it down to a single document (embedBatch backs
|
|
509
|
-
// off, retries, and splits a multi-document timeout before ever
|
|
510
|
-
// reporting it here); a network error counts immediately at any
|
|
511
|
-
// size — it was never retried, so it is trusted right away.
|
|
512
|
-
consecutiveSingleDocFailures = skip.batchSize === 1 ? consecutiveSingleDocFailures + 1 : 0;
|
|
513
|
-
consecutiveNetworkErrorFailures =
|
|
514
|
-
skip.failureKind === "network-error" ? consecutiveNetworkErrorFailures + 1 : 0;
|
|
515
|
-
if (consecutiveSingleDocFailures >= CIRCUIT_BREAKER_THRESHOLD ||
|
|
516
|
-
consecutiveNetworkErrorFailures >= CIRCUIT_BREAKER_THRESHOLD) {
|
|
517
|
-
circuitBreakerReason = skip.message;
|
|
518
|
-
return false;
|
|
519
|
-
}
|
|
520
|
-
return undefined;
|
|
521
|
-
};
|
|
522
|
-
// Commit each provider batch in its own short transaction as it lands,
|
|
523
|
-
// rather than buffering the whole run in memory for one transaction at
|
|
524
|
-
// the very end (#954) — a competing-process lock error or any other
|
|
525
|
-
// interruption partway through now keeps whatever already committed
|
|
526
|
-
// instead of losing the entire pass.
|
|
527
|
-
// Tracks what this run actually observed, so a successful pass can
|
|
528
|
-
// record `embeddingIdentity` from real data rather than the config
|
|
529
|
-
// string alone (#955) — only the first non-empty batch's vector width
|
|
530
|
-
// is kept; every batch from one run shares the same provider/model.
|
|
531
|
-
let observedModel;
|
|
532
|
-
let observedVectorLen;
|
|
533
|
-
// Whether the remote provider's endpoint/model/token language is
|
|
534
|
-
// meaningful for this run — the per-batch diagnostic line below is
|
|
535
|
-
// remote-only, same gate the credential diagnostic (#953) above uses.
|
|
536
|
-
const reportPerBatchLine = hasRemoteEndpoint(config.embedding ?? {});
|
|
537
|
-
const onBatch = (indices, batchEmbeddings, model, outcome) => {
|
|
538
|
-
// #954 field-report follow-up: a "retrying" event carries nothing to
|
|
539
|
-
// commit — the request hasn't settled yet — only the notice that a
|
|
540
|
-
// back-off is about to be waited out, default-level so a run is
|
|
541
|
-
// never silently stalled indistinguishably from a hang.
|
|
542
|
-
if (outcome?.outcome === "retrying") {
|
|
543
|
-
if (reportPerBatchLine) {
|
|
544
|
-
onProgress({
|
|
545
|
-
phase: "embeddings",
|
|
546
|
-
message: `[embed] batch ${outcome.batchIndex}/${outcome.batchCount}: ${outcome.docCount} docs, ${outcome.requestTokens.toLocaleString()} tokens → retrying after ${(outcome.elapsedMs / 1000).toFixed(1)} s`,
|
|
547
|
-
});
|
|
548
|
-
}
|
|
549
|
-
return;
|
|
550
|
-
}
|
|
551
|
-
// #954: a "budget-lowered" event is the same kind of notice as
|
|
552
|
-
// "retrying" above — the run's first context-size rejection just
|
|
553
|
-
// shrank the request budget for everything not yet dispatched, but
|
|
554
|
-
// THIS rejected batch's own indices are still being split and
|
|
555
|
-
// retried by the embedder (their real stored/failed outcome lands in
|
|
556
|
-
// a later onBatch call). Nothing here has settled, so it must never
|
|
557
|
-
// touch storage, only report the notice — one line, at most once per
|
|
558
|
-
// run.
|
|
559
|
-
if (outcome?.outcome === "budget-lowered") {
|
|
560
|
-
if (reportPerBatchLine) {
|
|
561
|
-
onProgress({
|
|
562
|
-
phase: "embeddings",
|
|
563
|
-
message: `[embed] batch ${outcome.batchIndex}/${outcome.batchCount}: ${outcome.docCount} docs, ${outcome.requestTokens.toLocaleString()} tokens → ${outcome.reason}`,
|
|
564
|
-
});
|
|
565
|
-
}
|
|
566
|
-
return;
|
|
567
|
-
}
|
|
568
|
-
if (model)
|
|
569
|
-
observedModel = model;
|
|
570
|
-
// A batch that delivered at least one real embedding proves the
|
|
571
|
-
// provider is currently answering — reset both circuit-breaker
|
|
572
|
-
// streaks. (A wholly failed batch's `batchEmbeddings` are all
|
|
573
|
-
// `undefined`, per commitBatch's skip path, so this never
|
|
574
|
-
// re-triggers what onSkip just counted moments earlier.)
|
|
575
|
-
if (batchEmbeddings.some((embedding) => embedding !== undefined)) {
|
|
576
|
-
consecutiveSingleDocFailures = 0;
|
|
577
|
-
consecutiveNetworkErrorFailures = 0;
|
|
578
|
-
}
|
|
579
|
-
db.transaction(() => {
|
|
580
|
-
for (let k = 0; k < indices.length; k++) {
|
|
581
|
-
const index = indices[k];
|
|
582
|
-
const entry = pendingEntries[index];
|
|
583
|
-
if (!entry)
|
|
584
|
-
continue;
|
|
585
|
-
const embedding = batchEmbeddings[k];
|
|
586
|
-
if (!embedding) {
|
|
587
|
-
embedFailedCount++;
|
|
588
|
-
continue;
|
|
589
|
-
}
|
|
590
|
-
if (observedVectorLen === undefined)
|
|
591
|
-
observedVectorLen = embedding.length;
|
|
592
|
-
const result = upsertEmbedding(db, entry.id, embedding);
|
|
593
|
-
if (result.stored) {
|
|
594
|
-
storedCount++;
|
|
595
|
-
// #954: sum the estimate of the text actually sent —
|
|
596
|
-
// `texts[index]` is the capped string `embedBatch` was handed,
|
|
597
|
-
// parallel to `pendingEntries` by construction above (the
|
|
598
|
-
// `entry` guard covers both) — not `entry.searchText`, which is
|
|
599
|
-
// the pre-cap original and overstates throughput for every
|
|
600
|
-
// entry over the cap.
|
|
601
|
-
storedTokens += estimateTokenCount(texts[index]);
|
|
602
|
-
}
|
|
603
|
-
else {
|
|
604
|
-
skippedCount++;
|
|
605
|
-
}
|
|
606
|
-
if (result.vec === "failed")
|
|
607
|
-
vecFailedCount++;
|
|
608
|
-
if (result.vec === "unavailable")
|
|
609
|
-
vecUnavailableCount++;
|
|
610
|
-
}
|
|
611
|
-
})();
|
|
612
|
-
// Default level, one line per provider batch (#954, field-report
|
|
613
|
-
// follow-up): oversized documents never made a request
|
|
614
|
-
// (`reason === "oversized"`), so there is no batch outcome to
|
|
615
|
-
// report — they are covered by the run's final oversized-skip
|
|
616
|
-
// count and list instead.
|
|
617
|
-
if (outcome && outcome.reason !== "oversized" && reportPerBatchLine) {
|
|
618
|
-
const elapsedSeconds = (outcome.elapsedMs / 1000).toFixed(1);
|
|
619
|
-
const outcomeLabel = outcome.outcome === "stored"
|
|
620
|
-
? `${outcome.docCount} stored (${elapsedSeconds} s)`
|
|
621
|
-
: `failed: ${outcome.reason}`;
|
|
622
|
-
onProgress({
|
|
623
|
-
phase: "embeddings",
|
|
624
|
-
message: `[embed] batch ${outcome.batchIndex}/${outcome.batchCount}: ${outcome.docCount} docs, ${outcome.requestTokens.toLocaleString()} tokens → ${outcomeLabel}`,
|
|
625
|
-
});
|
|
626
|
-
}
|
|
627
|
-
// Every committed batch, not just every 500 stored entries (#954)
|
|
628
|
-
// — the prior bucketing left a non-verbose run silent
|
|
629
|
-
// for the entire embedding phase on anything smaller than 500
|
|
630
|
-
// entries, indistinguishable from a hang.
|
|
631
|
-
onProgress({
|
|
632
|
-
phase: "embeddings",
|
|
633
|
-
message: `Embedded ${storedCount}/${pendingEntries.length} entries.`,
|
|
634
|
-
});
|
|
635
|
-
};
|
|
636
|
-
await embedBatch(texts, config.embedding, signal, onSkip, onBatch);
|
|
637
|
-
throwIfAborted(signal);
|
|
638
|
-
const elapsedSeconds = Math.max((Date.now() - embedStart) / 1000, 0.001);
|
|
639
|
-
if (skippedCount > 0) {
|
|
640
|
-
warn(`[embed] ${skippedCount} embedding${skippedCount === 1 ? "" : "s"} skipped (entry deleted between queue and write)`);
|
|
641
|
-
}
|
|
642
|
-
const vecGenerationComplete = targetEntryIds === undefined ? isVecFastPathComplete(db) : vecFastPathWasReady;
|
|
643
|
-
setVecFastPathReady(db, vecFailedCount === 0 && vecUnavailableCount === 0 && vecGenerationComplete);
|
|
644
|
-
if (vecFailedCount > 0) {
|
|
645
|
-
warn(`[embed] ${vecFailedCount} sqlite-vec fast-path insert${vecFailedCount === 1 ? "" : "s"} failed — ` +
|
|
646
|
-
"semantic search will use the slower JS-cosine fallback over stored embeddings. " +
|
|
647
|
-
"Rebuild with 'akm index --full' after resolving the vec table (often a vector-dimension mismatch).");
|
|
648
|
-
}
|
|
649
|
-
const entriesPerSec = storedCount / elapsedSeconds;
|
|
650
|
-
const tokensPerSec = storedTokens / elapsedSeconds;
|
|
651
|
-
const totalStored = storedCount + reusedCount;
|
|
652
|
-
// #954, field-report follow-up: the final line
|
|
653
|
-
// reports every outcome, not just what was stored — counts come from
|
|
654
|
-
// the same collected `skips` the circuit breaker already uses,
|
|
655
|
-
// categorized by `reason`/`failureKind`. "oversized skipped" =
|
|
656
|
-
// context-window-exceeded (never fit any request, at any size);
|
|
657
|
-
// "timed out" = a batch-request-failed skip whose last attempt timed
|
|
658
|
-
// out (retries/splits already exhausted before this counted); "failed"
|
|
659
|
-
// = every other batch-request-failed skip (a genuine, never-retried
|
|
660
|
-
// network/HTTP failure).
|
|
661
|
-
const oversizedSkips = skips.filter((skip) => skip.reason === "context-window-exceeded");
|
|
662
|
-
const timedOutSkips = skips.filter((skip) => skip.reason === "batch-request-failed" && skip.failureKind === "timeout");
|
|
663
|
-
const failedSkips = skips.filter((skip) => skip.reason === "batch-request-failed" && skip.failureKind !== "timeout");
|
|
664
|
-
const throughputLine = reusedCount > 0
|
|
665
|
-
? // #955: report reused and newly-embedded counts separately — the
|
|
666
|
-
// rate figures below are provider throughput only (reuse is a
|
|
667
|
-
// plain DB write, not provider work) and would be misleadingly
|
|
668
|
-
// inflated if reused entries were folded into them.
|
|
669
|
-
`Stored ${totalStored} embedding${totalStored === 1 ? "" : "s"} (${reusedCount} reused, ${storedCount} newly embedded) in ${elapsedSeconds.toFixed(1)}s (${entriesPerSec.toFixed(1)} entries/s, ~${Math.round(tokensPerSec)} tokens/s)`
|
|
670
|
-
: `Stored ${storedCount} embedding${storedCount === 1 ? "" : "s"} in ${elapsedSeconds.toFixed(1)}s (${entriesPerSec.toFixed(1)} entries/s, ~${Math.round(tokensPerSec)} tokens/s)`;
|
|
671
|
-
onProgress({
|
|
672
|
-
phase: "embeddings",
|
|
673
|
-
message: `${throughputLine}; ${oversizedSkips.length} oversized skipped, ${timedOutSkips.length} timed out, ${failedSkips.length} failed.`,
|
|
674
|
-
});
|
|
675
|
-
// Bounded itemRef-level detail for every skip category, not just
|
|
676
|
-
// oversized — the aggregate counts above say HOW MANY documents timed
|
|
677
|
-
// out or failed, but give the operator no way to find out WHICH ones
|
|
678
|
-
// short of rerunning with --verbose and re-reading the whole log.
|
|
679
|
-
// Default level caps each list (there is nothing actionable about the
|
|
680
|
-
// 21st identical failure); --verbose prints every one, matching the
|
|
681
|
-
// per-document mapping lines' own verbosity gate above.
|
|
682
|
-
const printSkipList = (label, skipList) => {
|
|
683
|
-
if (skipList.length === 0)
|
|
684
|
-
return;
|
|
685
|
-
const limit = isVerbose() ? skipList.length : 20;
|
|
686
|
-
const listed = skipList
|
|
687
|
-
.slice(0, limit)
|
|
688
|
-
.map((skip) => ` - ${pendingEntries[skip.index]?.itemRef ?? skip.index}: ${skip.message}`)
|
|
689
|
-
.join("\n");
|
|
690
|
-
const more = skipList.length > limit ? `\n ...and ${skipList.length - limit} more` : "";
|
|
691
|
-
onProgress({ phase: "embeddings", message: `[embed] ${label} skipped:\n${listed}${more}` });
|
|
692
|
-
};
|
|
693
|
-
printSkipList("oversized documents", oversizedSkips);
|
|
694
|
-
printSkipList("timed-out documents", timedOutSkips);
|
|
695
|
-
printSkipList("failed documents", failedSkips);
|
|
696
|
-
setMeta(db, "embeddingFingerprint", currentFingerprint);
|
|
697
|
-
const observedIdentity = deriveObservedEmbeddingIdentity(config.embedding, observedModel, observedVectorLen);
|
|
698
|
-
if (observedIdentity)
|
|
699
|
-
setMeta(db, "embeddingIdentity", observedIdentity);
|
|
700
|
-
// Circuit breaker tripped (#954): committed batches are
|
|
701
|
-
// kept (nothing above discards them), but the pass is not a success —
|
|
702
|
-
// the provider looks dead, not just occasionally flaky.
|
|
703
|
-
if (circuitBreakerReason !== undefined) {
|
|
704
|
-
const message = `embedding provider failed ${CIRCUIT_BREAKER_THRESHOLD} consecutive batches ` +
|
|
705
|
-
`(last: ${circuitBreakerReason}); stopped after ${storedCount} embedding${storedCount === 1 ? "" : "s"} ` +
|
|
706
|
-
"were stored — rerun akm index when the endpoint is healthy";
|
|
707
|
-
warn(`[embed] ${message}`);
|
|
708
|
-
onProgress({ phase: "embeddings", message });
|
|
709
|
-
return { success: false, message, vecInsertFailures: vecFailedCount };
|
|
710
|
-
}
|
|
711
|
-
// Only a total failure (nothing at all embedded, despite having entries
|
|
712
|
-
// to embed) turns into a phase failure. Any partial success — the vast
|
|
713
|
-
// majority of a large bundle embedding fine around a handful of skips —
|
|
714
|
-
// must not discard what DID get stored (#874).
|
|
715
|
-
if (storedCount === 0 && embedFailedCount > 0) {
|
|
716
|
-
const firstMessage = skips[0]?.message ?? "All embeddings failed.";
|
|
717
|
-
// #873 removed the persisted semantic verdict, so there is no failure
|
|
718
|
-
// class to record — just report what happened on this run.
|
|
719
|
-
return {
|
|
720
|
-
success: false,
|
|
721
|
-
message: `All ${embedFailedCount} embedding batch(es) failed: ${firstMessage}`,
|
|
722
|
-
};
|
|
723
|
-
}
|
|
724
|
-
// A pass that completes without abort or circuit-break purges
|
|
725
|
-
// whatever salvage is left — consumed by this pass's reuse step
|
|
726
|
-
// above, or superseded by what it just embedded.
|
|
727
|
-
purgeEmbeddingSalvage(db);
|
|
728
|
-
return { success: true, vecInsertFailures: vecFailedCount };
|
|
729
|
-
}
|
|
730
|
-
finally {
|
|
731
|
-
if (heartbeatTimer)
|
|
732
|
-
clearInterval(heartbeatTimer);
|
|
733
|
-
}
|
|
734
|
-
}
|
|
735
|
-
catch (error) {
|
|
736
|
-
// Field follow-up to #956 (dev-team field review 2026-09-10): a
|
|
737
|
-
// contention-shaped error (another akm process writing index.db right
|
|
738
|
-
// now) used to escape this catch as a raw driver string ("database is
|
|
739
|
-
// locked"), reaching this user-facing message unclassified even though
|
|
740
|
-
// the acquisition-time path (`akmIndex`'s outer catch) already
|
|
741
|
-
// reclassifies the same shape into `TransientError("INDEX_DB_CONTENDED")`.
|
|
742
|
-
// Reuses that ONE shared classifier rather than a second one — see
|
|
743
|
-
// `index-db-contention.ts`. This catch stays non-fatal (a caller sees
|
|
744
|
-
// `success: false` and a message, never a thrown error): the run
|
|
745
|
-
// continues through the remaining index phases exactly as it did
|
|
746
|
-
// before, only the message is now classified when the error is
|
|
747
|
-
// contention-shaped.
|
|
748
|
-
const reclassified = reclassifyIndexDbContention(error);
|
|
749
|
-
const message = reclassified instanceof Error ? reclassified.message : String(reclassified);
|
|
750
|
-
warn("Embedding generation failed, continuing without:", message);
|
|
751
|
-
onProgress({ phase: "embeddings", message: `Embedding generation failed: ${message}` });
|
|
752
|
-
return {
|
|
753
|
-
success: false,
|
|
754
|
-
message: `Semantic search verification failed: ${message}`,
|
|
755
|
-
};
|
|
756
|
-
}
|
|
757
|
-
}
|
|
758
|
-
/**
|
|
759
|
-
* Update the `hasEmbeddings` DB fact after a targeted mutation, from the
|
|
760
|
-
* index's actual current embedding coverage — read fresh, not cached.
|
|
761
|
-
*/
|
|
762
|
-
export function publishTargetedEmbeddingMeta(db, config) {
|
|
763
|
-
if (config.semanticSearchMode === "off") {
|
|
764
|
-
setMeta(db, "hasEmbeddings", "0");
|
|
765
|
-
return;
|
|
766
|
-
}
|
|
767
|
-
const entryCount = getEmbeddableEntryCount(db);
|
|
768
|
-
const embeddingCount = getEmbeddingCount(db);
|
|
769
|
-
const ready = entryCount > 0 && embeddingCount >= entryCount;
|
|
770
|
-
setMeta(db, "hasEmbeddings", ready ? "1" : "0");
|
|
771
|
-
}
|