@modusensus/dsh-mneme 0.11.0 → 0.13.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.
- package/README.md +54 -21
- package/docs/CONFIGURATION.md +45 -4
- package/docs/DIRECTORIES.md +114 -0
- package/docs/DISTILL.md +64 -0
- package/docs/DSH-GO.md +97 -0
- package/docs/ENTITIES.md +5 -3
- package/docs/FORGET.md +77 -0
- package/docs/KB.md +110 -0
- package/docs/SLEEP.md +28 -3
- package/docs/STORAGE.md +23 -0
- package/lib/api-standalone.js +4 -1
- package/lib/api.js +744 -26
- package/lib/attachment-text.js +122 -0
- package/lib/choro-command.js +9 -2
- package/lib/client.js +3752 -819
- package/lib/config.js +171 -2
- package/lib/continuity.js +7 -6
- package/lib/diary/auto.js +190 -0
- package/lib/diary/compose.js +440 -0
- package/lib/diary/dir.js +59 -0
- package/lib/diary/export.js +97 -0
- package/lib/diary/index.js +26 -0
- package/lib/diary/library.js +189 -0
- package/lib/diary/qq-inbox.js +142 -0
- package/lib/diary/rollover.js +61 -0
- package/lib/diary/session-provider.js +122 -0
- package/lib/document.js +9 -3
- package/lib/dream/clustering.js +6 -1
- package/lib/dream/decisions.js +56 -5
- package/lib/dream/sleep.js +616 -15
- package/lib/dream.js +45 -13
- package/lib/dsh-go/host.js +162 -0
- package/lib/dsh-go/panel.js +2091 -0
- package/lib/dsh-go/text.js +342 -0
- package/lib/dsh-go/views/common.js +68 -0
- package/lib/dsh-go/views/entity.js +48 -0
- package/lib/dsh-go/views/memory.js +198 -0
- package/lib/dsh-go/views/root.js +30 -0
- package/lib/dsh-go/views/settings.js +398 -0
- package/lib/dsh-go/views/status.js +51 -0
- package/lib/embedding.js +42 -8
- package/lib/entities/extractor.js +36 -7
- package/lib/hot-memory.js +8 -9
- package/lib/index.js +131 -5
- package/lib/inject.js +192 -19
- package/lib/kb/index.js +309 -0
- package/lib/kb/routes.js +220 -0
- package/lib/kb/tools.js +148 -0
- package/lib/lang.js +115 -4
- package/lib/peak-hours.js +57 -2
- package/lib/profile-facts.js +356 -0
- package/lib/semantic.js +347 -60
- package/lib/service.js +302 -70
- package/lib/settings.js +117 -14
- package/lib/store.js +830 -55
- package/lib/summarize.js +38 -11
- package/lib/tools.js +173 -25
- package/lib/user-settings.js +175 -23
- package/lib/vector-index.js +76 -6
- package/lib/wiki/cli-hint.js +90 -0
- package/lib/wiki/queries.js +264 -10
- package/lib/wiki/t1-jobs.js +232 -0
- package/lib/wiki/t1.js +7 -1
- package/package.json +25 -1
- package/scripts/sync-test-badge.mjs +1 -1
- package/scripts/test-count-sync.mjs +9 -5
- package/src/api-standalone.js +4 -1
- package/src/api.js +744 -26
- package/src/attachment-text.js +122 -0
- package/src/choro-command.js +9 -2
- package/src/config.js +171 -2
- package/src/continuity.js +7 -6
- package/src/diary/auto.js +190 -0
- package/src/diary/compose.js +440 -0
- package/src/diary/dir.js +59 -0
- package/src/diary/export.js +97 -0
- package/src/diary/index.js +26 -0
- package/src/diary/library.js +189 -0
- package/src/diary/qq-inbox.js +142 -0
- package/src/diary/rollover.js +61 -0
- package/src/diary/session-provider.js +122 -0
- package/src/document.js +9 -3
- package/src/dream/clustering.js +6 -1
- package/src/dream/decisions.js +56 -5
- package/src/dream/sleep.js +616 -15
- package/src/dream.js +45 -13
- package/src/dsh-go/host.js +162 -0
- package/src/dsh-go/panel.js +2091 -0
- package/src/dsh-go/text.js +342 -0
- package/src/dsh-go/views/common.js +68 -0
- package/src/dsh-go/views/entity.js +48 -0
- package/src/dsh-go/views/memory.js +198 -0
- package/src/dsh-go/views/root.js +30 -0
- package/src/dsh-go/views/settings.js +398 -0
- package/src/dsh-go/views/status.js +51 -0
- package/src/embedding.js +42 -8
- package/src/entities/extractor.js +36 -7
- package/src/hot-memory.js +8 -9
- package/src/index.js +131 -5
- package/src/inject.js +192 -19
- package/src/kb/index.js +309 -0
- package/src/kb/routes.js +220 -0
- package/src/kb/tools.js +148 -0
- package/src/lang.js +115 -4
- package/src/peak-hours.js +57 -2
- package/src/profile-facts.js +356 -0
- package/src/semantic.js +347 -60
- package/src/service.js +302 -70
- package/src/settings.js +117 -14
- package/src/store.js +830 -55
- package/src/summarize.js +38 -11
- package/src/tools.js +173 -25
- package/src/user-settings.js +175 -23
- package/src/vector-index.js +76 -6
- package/src/wiki/cli-hint.js +90 -0
- package/src/wiki/queries.js +264 -10
- package/src/wiki/t1-jobs.js +232 -0
- package/src/wiki/t1.js +7 -1
- package/test/api-routes-gaps.test.js +63 -0
- package/test/api.test.js +377 -4
- package/test/attachment-text.test.js +140 -0
- package/test/bm25-corpus-cache.test.js +145 -0
- package/test/capacity-warning.test.js +262 -0
- package/test/client.test.js +908 -138
- package/test/config.test.js +79 -0
- package/test/conflict-freeze.test.js +45 -1
- package/test/continuity.test.js +8 -1
- package/test/diary-library.test.js +187 -0
- package/test/diary.test.js +576 -0
- package/test/document.test.js +32 -0
- package/test/dream-maxtokens-fallback.test.js +3 -3
- package/test/dream.test.js +62 -1
- package/test/dsh-go-host.test.js +134 -0
- package/test/dsh-go-panel-actions.test.js +854 -0
- package/test/dsh-go-panel.test.js +251 -0
- package/test/embedding-cache-f32.test.js +276 -0
- package/test/embedding-ready.test.js +33 -3
- package/test/entities.test.js +73 -0
- package/test/forget-corrections.test.js +70 -0
- package/test/image-memory.test.js +171 -0
- package/test/inject-pin-explicit.test.js +300 -0
- package/test/inject-pin-vector-crowd.test.js +225 -0
- package/test/issue-617-step1-query-and-fusion.test.js +361 -0
- package/test/kb-api-wiring.test.js +128 -0
- package/test/kb-collections.test.js +272 -0
- package/test/kb-routes.test.js +379 -0
- package/test/mint-source.test.js +26 -0
- package/test/peak-hours-observability.test.js +70 -0
- package/test/persona-api.test.js +3 -3
- package/test/persona-by-session.test.js +568 -0
- package/test/persona-settings.test.js +38 -7
- package/test/profile-facts.test.js +492 -0
- package/test/reflection-update-gate.test.js +129 -0
- package/test/reindex-backfill.test.js +334 -0
- package/test/reindex-scheduler.test.js +369 -0
- package/test/scope-candidates.test.js +249 -0
- package/test/session-gate.test.js +1 -1
- package/test/sleep-action-set.test.js +14 -0
- package/test/sleep-heat.test.js +49 -0
- package/test/sleep.test.js +598 -0
- package/test/standalone-api.test.js +24 -0
- package/test/store.test.js +20 -0
- package/test/summarize.test.js +26 -0
- package/test/test-count-sync.test.js +14 -3
- package/test/tool-state-ignore.test.js +65 -0
- package/test/tools-dto-schema-matrix.test.js +23 -2
- package/test/tools.test.js +144 -7
- package/test/user-settings-segments.test.js +528 -0
- package/test/vector-index.test.js +120 -6
- package/test/wiki-api.test.js +476 -1
- package/test/wiki-cli-hint.test.js +118 -0
- package/test/wiki-queries.test.js +91 -1
- package/test/wiki-t1-jobs.test.js +125 -0
- package/test/wiki-tools.test.js +131 -76
package/lib/semantic.js
CHANGED
|
@@ -43,23 +43,84 @@ export async function backfillMissingEmbeddings({
|
|
|
43
43
|
? store.needsEmbeddingFor(model, n)
|
|
44
44
|
: store.needsEmbedding(n));
|
|
45
45
|
const unlimited = !(maxTotal > 0);
|
|
46
|
+
// #604: a failed row stays stale, so the next pick() hands it straight back
|
|
47
|
+
// and it eats the budget again — measured 9 of 20 slots burned on one
|
|
48
|
+
// permanently failing row, and with maxTotal: 0 the loop never terminated
|
|
49
|
+
// (the failed row never leaves the queue, so "done" never reaches a bound
|
|
50
|
+
// that does not exist). Remembering what THIS run already tried makes the
|
|
51
|
+
// queue strictly shrink, which fixes both shapes with one mechanism.
|
|
52
|
+
//
|
|
53
|
+
// Deliberately in-memory only: a transient provider outage must not become a
|
|
54
|
+
// permanent exclusion. A row skipped here is retried on the next boot, which
|
|
55
|
+
// is the same contract #128 established for the fingerprint gate.
|
|
56
|
+
const attempted = new Set();
|
|
57
|
+
// #604 follow-up: a fixed-size window starves the queue tail. pick() is
|
|
58
|
+
// ORDER BY updated_at DESC and a failed row is never written, so its
|
|
59
|
+
// updated_at never moves: a batch of permanently failing rows at the head is
|
|
60
|
+
// re-selected every round, filtered out by `attempted`, and the run ends
|
|
61
|
+
// `stalled` with every healthy row behind it never tried once. Measured on
|
|
62
|
+
// this code: 20 rows (10 good written first, 10 failing at the head),
|
|
63
|
+
// maxTotal 500 / batchSize 10 → {indexed: 0, finishReason: "stalled"},
|
|
64
|
+
// okCalls 0. Widening the window by the number already tried keeps the dead
|
|
65
|
+
// prefix in view and always reaches past it, so the budget is spent on real
|
|
66
|
+
// work. Still memory-only, still no persistent blacklist.
|
|
67
|
+
// The window is bounded: widening by the whole dead prefix is what makes the
|
|
68
|
+
// tail reachable, but an unbounded window turns "provider down, every row
|
|
69
|
+
// fails" into a quadratic walk that materialises the entire table once per
|
|
70
|
+
// round. 500 rows keeps the query cheap (≈ the default maxTotal) and still
|
|
71
|
+
// tolerates hundreds of permanent failures at the head before honestly
|
|
72
|
+
// reporting `stalled`.
|
|
73
|
+
const maxWindow = Math.max(batchSize, 500);
|
|
74
|
+
const pickFresh = (n) => pick(Math.min(n + attempted.size, maxWindow));
|
|
46
75
|
let indexed = 0;
|
|
47
76
|
let processed = 0;
|
|
48
77
|
let failed = 0;
|
|
78
|
+
let stalled = false;
|
|
79
|
+
const failureReasons = Object.create(null);
|
|
80
|
+
const noteFailure = (reason) => {
|
|
81
|
+
failed++;
|
|
82
|
+
failureReasons[reason] = (failureReasons[reason] ?? 0) + 1;
|
|
83
|
+
};
|
|
49
84
|
for (let done = 0; unlimited || done < maxTotal;) {
|
|
50
|
-
const
|
|
51
|
-
if (!
|
|
85
|
+
const picked = pickFresh(batchSize);
|
|
86
|
+
if (!picked.length) break;
|
|
87
|
+
const rows = picked.filter((row) => !attempted.has(row.id)).slice(0, batchSize);
|
|
88
|
+
if (!rows.length) {
|
|
89
|
+
// Everything still queued already failed during this run. Stop instead of
|
|
90
|
+
// spinning; the next boot starts with a fresh ledger.
|
|
91
|
+
stalled = true;
|
|
92
|
+
break;
|
|
93
|
+
}
|
|
52
94
|
for (const row of rows) {
|
|
95
|
+
attempted.add(row.id);
|
|
53
96
|
try {
|
|
54
97
|
const text = [row.title, row.content].filter(Boolean).join("\n");
|
|
55
|
-
|
|
98
|
+
// Prefer the adapter that reports why it failed. Without it a legacy
|
|
99
|
+
// OpenAI-compatible embedder (the default `embedProvider: "openai"`
|
|
100
|
+
// path, and the one this install actually runs) returns a bare null for
|
|
101
|
+
// both "this row is unembeddable" and "the provider was unreachable",
|
|
102
|
+
// so every provider outage was filed as a permanent row failure and the
|
|
103
|
+
// run reported `stalled` — deferring the retry to the next boot when
|
|
104
|
+
// the provider had already recovered. Older adapters have no
|
|
105
|
+
// embedSingleDetailed and keep the old, less precise behaviour.
|
|
106
|
+
const detailed = typeof embedder.embedSingleDetailed === "function"
|
|
107
|
+
? await embedder.embedSingleDetailed(text)
|
|
108
|
+
: null;
|
|
109
|
+
const vector = detailed ? detailed.vector : await embedder.embedSingle(text);
|
|
56
110
|
if (vector?.length) {
|
|
57
111
|
store.setEmbedding(row.id, vector, model);
|
|
58
112
|
indexed++;
|
|
113
|
+
} else if (detailed?.reason) {
|
|
114
|
+
// Keep the `error:` prefix the finishReason split keys on. The reason
|
|
115
|
+
// domain is embedTextDetailed's: http-<status>, request-failed:<kind>,
|
|
116
|
+
// config-incomplete:<field>, response-no-vector.
|
|
117
|
+
noteFailure(`error:${detailed.reason}`);
|
|
59
118
|
} else {
|
|
60
|
-
|
|
119
|
+
// No reason available (older adapter): "no vector came back" is all
|
|
120
|
+
// we can honestly claim, and it is treated as permanent.
|
|
121
|
+
noteFailure("empty-vector");
|
|
61
122
|
}
|
|
62
|
-
} catch {
|
|
123
|
+
} catch (error) { noteFailure(`error:${String(error)}`); }
|
|
63
124
|
}
|
|
64
125
|
done += rows.length;
|
|
65
126
|
processed += rows.length;
|
|
@@ -67,22 +128,260 @@ export async function backfillMissingEmbeddings({
|
|
|
67
128
|
if (pick(1).length) await new Promise((r) => setTimeout(r, rateLimitMs));
|
|
68
129
|
}
|
|
69
130
|
if (indexed > 0 && model) vectorIndex.markModel?.(model, embedder.dimension);
|
|
70
|
-
//
|
|
71
|
-
//
|
|
72
|
-
//
|
|
131
|
+
// Two independent dimensions, because one number cannot answer both
|
|
132
|
+
// questions the caller actually has:
|
|
133
|
+
// finishReason — why the loop stopped;
|
|
134
|
+
// failed/failureReasons — what was lost along the way.
|
|
135
|
+
//
|
|
136
|
+
// The old ternary had an unreachable branch: "all-failed" required
|
|
137
|
+
// `!stillStale && failed > 0`, but a failed row is never written, so it is
|
|
138
|
+
// still stale and `stillStale` is always true once anything failed. Four
|
|
139
|
+
// failing rows out of four reported "capped" — as if the budget had run out
|
|
140
|
+
// with work to spare. Invariant worth stating: failed > 0 implies
|
|
141
|
+
// stillStale === true, therefore "drained" is only reachable with zero
|
|
142
|
+
// failures.
|
|
143
|
+
//
|
|
144
|
+
// "capped" must mean *real work is left and the budget stopped us*, because
|
|
145
|
+
// the scheduler re-runs on it. Two ways to be stuck without having made
|
|
146
|
+
// progress, and both have to report "stalled":
|
|
147
|
+
// - `stalled`: the pick window held nothing but rows already attempted
|
|
148
|
+
// this run (small dead prefix, exhausted);
|
|
149
|
+
// - `indexed === 0`: a whole run produced not one vector. Measured on a
|
|
150
|
+
// dead prefix of >= maxWindow rows: every round's window is filled by
|
|
151
|
+
// failing rows, so `rows` is never empty, the loop exits on the budget
|
|
152
|
+
// with `stalled === false`, and "capped" made the scheduler re-run 21
|
|
153
|
+
// times — 10,500 provider calls, 0 rows embedded. With `indexed === 0`
|
|
154
|
+
// folded into "stalled", that run stops and the next boot is the retry
|
|
155
|
+
// point, exactly like any other no-progress run.
|
|
156
|
+
// A run that embedded *something* and ran out of budget is still "capped":
|
|
157
|
+
// the tail behind the dead prefix may well be reachable next round.
|
|
158
|
+
//
|
|
159
|
+
// But "no progress" alone cannot tell a dead row from a dead provider. Ten
|
|
160
|
+
// healthy rows that all hit a 503 in one batch produce the same indexed === 0
|
|
161
|
+
// as ten permanently broken ones — and reporting "stalled" for the former
|
|
162
|
+
// sends the retry to the next boot, minutes or hours away, when the provider
|
|
163
|
+
// was back a second later. The distinction is already in failureReasons:
|
|
164
|
+
// adapter throws land in `error:`-prefixed buckets (transient), while a null
|
|
165
|
+
// vector lands in `empty-vector` (permanent for that row, as far as we can
|
|
166
|
+
// tell). So a no-progress run splits in two:
|
|
167
|
+
// - `errored`: nothing got through AND at least one throw — the provider
|
|
168
|
+
// was unreachable. Worth another round, but a much smaller budget than
|
|
169
|
+
// "capped", because a genuinely dead provider must not become an endless
|
|
170
|
+
// retry loop.
|
|
171
|
+
// - `stalled`: nothing got through and every failure was permanent. The
|
|
172
|
+
// next boot is the honest retry point.
|
|
73
173
|
const stillStale = pick(1).length > 0;
|
|
74
|
-
|
|
174
|
+
// A reason is transient when the same request could plausibly succeed later.
|
|
175
|
+
// Both a thrown adapter error and a detailed failure arrive here as
|
|
176
|
+
// `error:<reason>`, so the prefix alone is too coarse: a missing config field
|
|
177
|
+
// and a row the provider refuses to embed fail identically every time, and
|
|
178
|
+
// retrying those only burns the error budget. Only rate limiting, server-side
|
|
179
|
+
// faults, transport failures and unclassified throws earn a retry.
|
|
180
|
+
const isTransient = (reason) => {
|
|
181
|
+
if (!reason.startsWith("error:")) return false;
|
|
182
|
+
const detail = reason.slice("error:".length);
|
|
183
|
+
if (detail.startsWith("config-incomplete")) return false;
|
|
184
|
+
if (detail.startsWith("response-no-vector")) return false;
|
|
185
|
+
const status = /^http-(\d{3})/.exec(detail);
|
|
186
|
+
if (status) {
|
|
187
|
+
const code = Number(status[1]);
|
|
188
|
+
return code === 429 || code >= 500;
|
|
189
|
+
}
|
|
190
|
+
// request-failed:<timeout|network> and bare thrown Errors: blame the
|
|
191
|
+
// provider, not the row.
|
|
192
|
+
return true;
|
|
193
|
+
};
|
|
194
|
+
const transient = Object.keys(failureReasons).some(isTransient);
|
|
195
|
+
const noProgress = stalled || indexed === 0;
|
|
196
|
+
const finishReason = !stillStale
|
|
197
|
+
? "drained"
|
|
198
|
+
: noProgress
|
|
199
|
+
? (transient ? "errored" : "stalled")
|
|
200
|
+
: "capped";
|
|
75
201
|
logger?.info?.(
|
|
76
202
|
`[dsh-mneme] auto-reindex backfilled ${indexed} embeddings (processed=${processed}, failed=${failed}, finish=${finishReason})`
|
|
77
203
|
);
|
|
78
204
|
return {
|
|
79
205
|
indexed, processed, failed, finishReason, stillStale,
|
|
206
|
+
// Keep this flag consistent with finishReason: a run that embedded nothing
|
|
207
|
+
// also made no progress, and callers should not have to know that it got
|
|
208
|
+
// there via the budget rather than via an exhausted window.
|
|
209
|
+
stalled: finishReason === "stalled",
|
|
210
|
+
// Only the reasons we can name; absent when nothing failed.
|
|
211
|
+
failureReasons: failed > 0 ? { ...failureReasons } : null,
|
|
80
212
|
startedAt,
|
|
81
213
|
finishedAt: new Date().toISOString(),
|
|
82
214
|
model: model ?? null
|
|
83
215
|
};
|
|
84
216
|
}
|
|
85
217
|
|
|
218
|
+
/**
|
|
219
|
+
* Boot 回填调度器(#604)。
|
|
220
|
+
*
|
|
221
|
+
* 抽成模块级函数而不是留在 createSemantic 闭包里,是因为闭包形态此前**零测试
|
|
222
|
+
* 覆盖**(全仓只有 index.js / serve.js 引用 createSemantic),而「一次启动只跑
|
|
223
|
+
* 一轮、撞 cap 就停」正是靠这个缺口活了很久:没有任何用例能观察到「第二轮没
|
|
224
|
+
* 排上」。
|
|
225
|
+
*
|
|
226
|
+
* 续排规则:
|
|
227
|
+
* - finishReason === "capped"(队列还有、额度用完)→ 排下一轮;
|
|
228
|
+
* - finishReason === "errored"(一条都没嵌上、且失败里有抛错)→ 排下一轮,
|
|
229
|
+
* 但走更小的 maxErrorContinuations(默认 3):瞬时 503 值得重试,provider
|
|
230
|
+
* 真挂了不能靠 20 轮 × 500 行陪着耗;
|
|
231
|
+
* - finishReason === "stalled"(剩下的本轮全失败且都是永久性失败)→ 不排,
|
|
232
|
+
* 下一轮启动再试;
|
|
233
|
+
* - 抛错 → 也排,但走同一个计数器,硬故障不会变成无限重试;
|
|
234
|
+
* - 计数到 maxContinuations 就停并告警。
|
|
235
|
+
*
|
|
236
|
+
* 计时器只有一个槽位:dispose 清它,且 disposed 后任何已排的回调都不再执行
|
|
237
|
+
* —— 否则会对已关闭的库继续查 needsEmbedding(#365 CodeRabbit 踩过同一坑)。
|
|
238
|
+
*
|
|
239
|
+
* @param {object} opts
|
|
240
|
+
* store / vectorIndex / logger / cfg — 与 createSemantic 同形;
|
|
241
|
+
* getEmbedder() — 取当前 embedder(可能为 null 或尚未 ready);
|
|
242
|
+
* onStatus(next) — 接收 running / finished / error 快照;
|
|
243
|
+
* timing — 仅供测试压缩等待:initialDelayMs / continueDelayMs /
|
|
244
|
+
* maxContinuations / maxErrorContinuations /
|
|
245
|
+
* readyRetryDelayMs,默认值与生产一致。
|
|
246
|
+
* @returns {{ dispose: () => void, status: () => object|null }}
|
|
247
|
+
*/
|
|
248
|
+
export function scheduleBootBackfill({
|
|
249
|
+
store, vectorIndex, logger, cfg,
|
|
250
|
+
getEmbedder, onStatus = () => {},
|
|
251
|
+
timing = {}
|
|
252
|
+
}) {
|
|
253
|
+
const initialDelayMs = timing.initialDelayMs ?? 5000;
|
|
254
|
+
const continueDelayMs = timing.continueDelayMs ?? 3000;
|
|
255
|
+
const readyRetryDelayMs = timing.readyRetryDelayMs ?? 2000;
|
|
256
|
+
// Hard stop on continuations: a provider that fails every row must not turn
|
|
257
|
+
// into an endless retry loop for the life of the process. Reset per boot.
|
|
258
|
+
const maxContinuations = timing.maxContinuations ?? 20;
|
|
259
|
+
// Transient outages get their own, much smaller budget. A 503 that clears in
|
|
260
|
+
// seconds deserves a retry; a provider that stays down must not be retried 20
|
|
261
|
+
// times × 500 rows just because the failures look like throws rather than
|
|
262
|
+
// nulls. Three rounds is enough to ride out a restart or a rate-limit blip.
|
|
263
|
+
const maxErrorContinuations = timing.maxErrorContinuations ?? 3;
|
|
264
|
+
|
|
265
|
+
let timer = null;
|
|
266
|
+
let disposed = false;
|
|
267
|
+
let continuations = 0;
|
|
268
|
+
let errorContinuations = 0;
|
|
269
|
+
let status = null;
|
|
270
|
+
|
|
271
|
+
const publish = (next) => { status = next; onStatus(next); };
|
|
272
|
+
const scheduleNext = (fn, delay) => {
|
|
273
|
+
if (disposed) return;
|
|
274
|
+
timer = setTimeout(fn, delay);
|
|
275
|
+
};
|
|
276
|
+
|
|
277
|
+
const attempt = (tries) => {
|
|
278
|
+
if (disposed) return;
|
|
279
|
+
try {
|
|
280
|
+
const embedder = getEmbedder();
|
|
281
|
+
if (!embedder || typeof embedder.embedSingle !== "function") return;
|
|
282
|
+
if ("ready" in embedder && embedder.ready !== true) {
|
|
283
|
+
// Local/ollama embedders init asynchronously; give them a moment
|
|
284
|
+
// before giving up on this boot (next boot retries).
|
|
285
|
+
// CodeRabbit on #365:嵌套重试计时器同样入册,否则 dispose 后仍可能
|
|
286
|
+
// 对已关库跑 needsEmbedding(有 try/catch 兜底只是日志噪声,但状态要收干净)。
|
|
287
|
+
if (tries > 0) scheduleNext(() => attempt(tries - 1), readyRetryDelayMs);
|
|
288
|
+
return;
|
|
289
|
+
}
|
|
290
|
+
const model = embedder.modelHash;
|
|
291
|
+
const stale = typeof store.hasStaleEmbedding === "function"
|
|
292
|
+
? store.hasStaleEmbedding(model)
|
|
293
|
+
: store.needsEmbedding(1).length > 0;
|
|
294
|
+
if (!stale) return; // nothing missing and nothing from another model
|
|
295
|
+
// Issue #128: no fingerprint gate here anymore — a matching fingerprint
|
|
296
|
+
// used to return early and permanently orphan rows whose embed failed
|
|
297
|
+
// at write time. See backfillMissingEmbeddings().
|
|
298
|
+
// Cap and pacing are configuration now (reindexMaxPerBoot /
|
|
299
|
+
// reindexBatchSize / reindexRateLimitMs) instead of hardcoded 500/10/200.
|
|
300
|
+
const startedAt = new Date().toISOString();
|
|
301
|
+
publish({
|
|
302
|
+
state: "running", startedAt,
|
|
303
|
+
maxTotal: cfg.reindexMaxPerBoot, batchSize: cfg.reindexBatchSize,
|
|
304
|
+
continuation: continuations
|
|
305
|
+
});
|
|
306
|
+
backfillMissingEmbeddings({
|
|
307
|
+
store, embedder, vectorIndex, logger,
|
|
308
|
+
maxTotal: cfg.reindexMaxPerBoot,
|
|
309
|
+
batchSize: cfg.reindexBatchSize,
|
|
310
|
+
rateLimitMs: cfg.reindexRateLimitMs
|
|
311
|
+
})
|
|
312
|
+
.then((summary) => {
|
|
313
|
+
if (disposed) return;
|
|
314
|
+
publish({ ...summary, state: "finished", continuation: continuations });
|
|
315
|
+
// Only "capped" means real work is left AND the budget ran out.
|
|
316
|
+
// "stalled" means everything left already failed permanently this
|
|
317
|
+
// run — trying again immediately would just burn the same rows, so
|
|
318
|
+
// the next boot is the honest retry point.
|
|
319
|
+
// "errored" means nothing got through because the provider threw:
|
|
320
|
+
// that is worth a retry, but on its own short leash (see
|
|
321
|
+
// maxErrorContinuations) so a provider that stays down cannot keep
|
|
322
|
+
// the process busy for the life of the boot.
|
|
323
|
+
if (summary.finishReason === "errored") {
|
|
324
|
+
if (errorContinuations < maxErrorContinuations) {
|
|
325
|
+
errorContinuations++;
|
|
326
|
+
continuations++;
|
|
327
|
+
scheduleNext(() => attempt(0), continueDelayMs);
|
|
328
|
+
} else {
|
|
329
|
+
logger?.warn?.(
|
|
330
|
+
`[dsh-mneme] auto-reindex: the embedder kept failing (${maxErrorContinuations} retries); `
|
|
331
|
+
+ `${summary.indexed} embedded, the rest waits for the next start`
|
|
332
|
+
);
|
|
333
|
+
}
|
|
334
|
+
return;
|
|
335
|
+
}
|
|
336
|
+
if (summary.finishReason !== "capped") return;
|
|
337
|
+
if (continuations < maxContinuations) {
|
|
338
|
+
continuations++;
|
|
339
|
+
scheduleNext(() => attempt(0), continueDelayMs);
|
|
340
|
+
} else {
|
|
341
|
+
logger?.warn?.(
|
|
342
|
+
`[dsh-mneme] auto-reindex hit the continuation limit (${maxContinuations}); `
|
|
343
|
+
+ `${summary.indexed} embedded, the rest waits for the next start`
|
|
344
|
+
);
|
|
345
|
+
}
|
|
346
|
+
})
|
|
347
|
+
.catch((error) => {
|
|
348
|
+
if (disposed) return;
|
|
349
|
+
publish({
|
|
350
|
+
state: "error", error: String(error),
|
|
351
|
+
startedAt: status?.startedAt ?? startedAt,
|
|
352
|
+
continuation: continuations
|
|
353
|
+
});
|
|
354
|
+
logger?.warn?.(`[dsh-mneme] auto-reindex failed: ${String(error)}`);
|
|
355
|
+
// A throwing backfill (closed database, bug) is retried too, but
|
|
356
|
+
// under the same cap so a hard failure cannot loop forever.
|
|
357
|
+
if (continuations < maxContinuations) {
|
|
358
|
+
continuations++;
|
|
359
|
+
scheduleNext(() => attempt(0), continueDelayMs);
|
|
360
|
+
}
|
|
361
|
+
});
|
|
362
|
+
} catch (error) {
|
|
363
|
+
// Synchronous throw before the promise exists: record it, otherwise the
|
|
364
|
+
// panel shows "never ran" instead of "ran and failed".
|
|
365
|
+
publish({
|
|
366
|
+
state: "error", error: String(error),
|
|
367
|
+
startedAt: status?.startedAt ?? new Date().toISOString(),
|
|
368
|
+
continuation: continuations
|
|
369
|
+
});
|
|
370
|
+
logger?.warn?.(`[dsh-mneme] auto-reindex failed: ${String(error)}`);
|
|
371
|
+
}
|
|
372
|
+
};
|
|
373
|
+
|
|
374
|
+
if (cfg.autoReindexOnBoot !== false) scheduleNext(() => attempt(5), initialDelayMs);
|
|
375
|
+
|
|
376
|
+
return {
|
|
377
|
+
dispose() {
|
|
378
|
+
disposed = true;
|
|
379
|
+
if (timer !== null) { clearTimeout(timer); timer = null; }
|
|
380
|
+
},
|
|
381
|
+
status: () => status
|
|
382
|
+
};
|
|
383
|
+
}
|
|
384
|
+
|
|
86
385
|
/**
|
|
87
386
|
* 组装语义管线(embedder + reranker)并挂到 service 上,随后调度 boot 自动回填。
|
|
88
387
|
* @param {object} opts
|
|
@@ -101,9 +400,6 @@ export function createSemantic({ store, service, settings, cfg, logger, vectorIn
|
|
|
101
400
|
let reranker = null;
|
|
102
401
|
// #118: pending embedder-init retry timer, cleared on unload.
|
|
103
402
|
let embedRetryTimer = null;
|
|
104
|
-
// boot 回填首查计时器。搬移前在 index.js 是裸 setTimeout(不参与卸载清理);
|
|
105
|
-
// 纳入 dispose 是修悬挂,不改变启动行为。
|
|
106
|
-
let reindexTimer = null;
|
|
107
403
|
// Last boot-backfill summary, exposed via backfillStatus() so "did it
|
|
108
404
|
// finish?" has an answer other than a log line.
|
|
109
405
|
let lastBackfill = null;
|
|
@@ -222,53 +518,18 @@ export function createSemantic({ store, service, settings, cfg, logger, vectorIn
|
|
|
222
518
|
// delay. Gated on cfg.autoReindexOnBoot; rate-limited in small batches so a
|
|
223
519
|
// large backlog never floods the provider. Failures degrade silently —
|
|
224
520
|
// search stays keyword.
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
}
|
|
238
|
-
const model = embedder.modelHash;
|
|
239
|
-
const stale = typeof store.hasStaleEmbedding === "function"
|
|
240
|
-
? store.hasStaleEmbedding(model)
|
|
241
|
-
: store.needsEmbedding(1).length > 0;
|
|
242
|
-
if (!stale) return; // nothing missing and nothing from another model
|
|
243
|
-
// Issue #128: no fingerprint gate here anymore — a matching fingerprint
|
|
244
|
-
// used to return early and permanently orphan rows whose embed failed
|
|
245
|
-
// at write time. See backfillMissingEmbeddings().
|
|
246
|
-
// Cap and pacing are configuration now (reindexMaxPerBoot /
|
|
247
|
-
// reindexBatchSize / reindexRateLimitMs) instead of hardcoded 500/10/200.
|
|
248
|
-
lastBackfill = {
|
|
249
|
-
state: "running", startedAt: new Date().toISOString(),
|
|
250
|
-
maxTotal: cfg.reindexMaxPerBoot, batchSize: cfg.reindexBatchSize
|
|
251
|
-
};
|
|
252
|
-
backfillMissingEmbeddings({
|
|
253
|
-
store, embedder, vectorIndex, logger,
|
|
254
|
-
maxTotal: cfg.reindexMaxPerBoot,
|
|
255
|
-
batchSize: cfg.reindexBatchSize,
|
|
256
|
-
rateLimitMs: cfg.reindexRateLimitMs
|
|
257
|
-
})
|
|
258
|
-
.then((summary) => {
|
|
259
|
-
lastBackfill = { ...summary, state: "finished" };
|
|
260
|
-
})
|
|
261
|
-
.catch((error) => {
|
|
262
|
-
lastBackfill = { state: "error", error: String(error), startedAt: lastBackfill?.startedAt };
|
|
263
|
-
logger?.warn?.(`[dsh-mneme] auto-reindex failed: ${String(error)}`);
|
|
264
|
-
});
|
|
265
|
-
} catch (error) {
|
|
266
|
-
logger?.warn?.(`[dsh-mneme] auto-reindex failed: ${String(error)}`);
|
|
267
|
-
}
|
|
268
|
-
};
|
|
269
|
-
reindexTimer = setTimeout(() => attempt(5), 5000);
|
|
270
|
-
}
|
|
271
|
-
scheduleAutoReindex();
|
|
521
|
+
//
|
|
522
|
+
// #604: a capped run used to be the end of the road until the next process
|
|
523
|
+
// start — the boot backfill fired once, wrote lastBackfill, and nothing ever
|
|
524
|
+
// rescheduled it. On this machine that meant a 500-row cap cleared the
|
|
525
|
+
// backlog only across several restarts, and the only trace was a log line
|
|
526
|
+
// nobody could see from the panel. The scheduler now continues inside the
|
|
527
|
+
// same boot (bounded), and records why it stopped where it did.
|
|
528
|
+
const backfill = scheduleBootBackfill({
|
|
529
|
+
store, vectorIndex, logger, cfg,
|
|
530
|
+
getEmbedder: () => embedder,
|
|
531
|
+
onStatus: (next) => { lastBackfill = next; }
|
|
532
|
+
});
|
|
272
533
|
|
|
273
534
|
return {
|
|
274
535
|
embedder,
|
|
@@ -277,9 +538,35 @@ export function createSemantic({ store, service, settings, cfg, logger, vectorIn
|
|
|
277
538
|
backfillStatus() {
|
|
278
539
|
return lastBackfill;
|
|
279
540
|
},
|
|
541
|
+
/**
|
|
542
|
+
* Embedding diagnostics for the status endpoint (#604): "is the vector
|
|
543
|
+
* layer silently dead right now?" had no answer outside the process.
|
|
544
|
+
* backfillStatus() covers the boot sweep, embedReceipts() covers writes.
|
|
545
|
+
* Both are read-only snapshots; neither touches the database.
|
|
546
|
+
*/
|
|
547
|
+
embeddingDiagnostics() {
|
|
548
|
+
const receipts = typeof embedder?.embedReceipts === "function"
|
|
549
|
+
? embedder.embedReceipts()
|
|
550
|
+
: null;
|
|
551
|
+
return {
|
|
552
|
+
backfill: lastBackfill,
|
|
553
|
+
receipts: receipts
|
|
554
|
+
? {
|
|
555
|
+
totals: receipts.totals,
|
|
556
|
+
lastOkAt: receipts.lastOkAt,
|
|
557
|
+
lastFailAt: receipts.lastFailAt,
|
|
558
|
+
lastFailReason: receipts.lastFailReason,
|
|
559
|
+
recent: Array.isArray(receipts.recent) ? receipts.recent.slice(-20) : []
|
|
560
|
+
}
|
|
561
|
+
: null
|
|
562
|
+
};
|
|
563
|
+
},
|
|
280
564
|
dispose() {
|
|
281
565
|
if (embedRetryTimer !== null) { clearTimeout(embedRetryTimer); embedRetryTimer = null; }
|
|
282
|
-
|
|
566
|
+
// #604: the backfill scheduler owns its own (single) timer slot and its
|
|
567
|
+
// own disposed flag, so a continuation that was already queued cannot
|
|
568
|
+
// fire against a closed database after unload.
|
|
569
|
+
backfill.dispose();
|
|
283
570
|
}
|
|
284
571
|
};
|
|
285
572
|
}
|