Skip to content

Commit 84b63dc

Browse files
committed
feat(standalone): /context 响应加 tier 档位信号,嵌入降级不再静默(#383)
嵌入降级在调用方视角原本完全静默:items 看着正常,只是召回质量悄悄变差。 以 /context 为唯一注入来源的第三方(Mneme Bridge 的 remote 模式)无法感知 自己长期跑在降级档上——它的回落逻辑只在 404 / 网络失败 / 响应形状不符时 触发,静默降级不触发。 fail-closed:判不出来报 unknown,不报 full。降级原因回收进 diag 走 daemon 日志枚举,不为它加第二个响应键。比 /search 的 mode 更精确——那边把空查询与 向量失败混为一路报 keyword,这里能分开。 纯增量:现有四键的语义与形状不动,不加配置键。 Refs #383
1 parent cecd2b5 commit 84b63dc

3 files changed

Lines changed: 149 additions & 18 deletions

File tree

‎dsh-mneme/lib/api-standalone.js‎

Lines changed: 43 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -226,16 +226,27 @@ async function handlePutBody(res, service, logger, id, text) {
226226
* /context 的查询嵌入:best-effort,embedder 接口宽容与 searchMemories 同款
227227
* (embedSingle 优先,兼容 embed-only 的 OpenAI 兼容客户端,issue #10)。
228228
* 调用方负责 catch——嵌入失败降级规则档,绝不因此 500。
229+
*
230+
* `diag`(optional,issue #383):拿不到向量时把原因写进去(`embed-unavailable`
231+
* 无可用接口 / `embed-empty` 空或非数组向量),供 daemon 侧日志枚举降级原因。
232+
* 不传则行为与既往逐字节一致。
229233
*/
230-
async function embedQueryVector(embedder, q) {
234+
async function embedQueryVector(embedder, q, diag) {
231235
const embedSingle = typeof embedder.embedSingle === "function"
232236
? embedder.embedSingle.bind(embedder)
233237
: typeof embedder.embed === "function"
234238
? embedder.embed.bind(embedder)
235239
: null;
236-
if (!embedSingle) return undefined;
240+
if (!embedSingle) {
241+
if (diag) diag.reason = "embed-unavailable";
242+
return undefined;
243+
}
237244
const vector = await embedSingle(q);
238-
return Array.isArray(vector) && vector.length ? vector : undefined;
245+
if (!Array.isArray(vector) || !vector.length) {
246+
if (diag) diag.reason = "embed-empty";
247+
return undefined;
248+
}
249+
return vector;
239250
}
240251

241252
/**
@@ -244,11 +255,16 @@ async function embedQueryVector(embedder, q) {
244255
* 按嵌入缺失处理,降级规则档。输掉的 embed promise 无法取消、自行结束后被丢弃,
245256
* 无害;挂起的主要成本是一个泄漏的挂起任务,可接受。嵌入先完成时清掉定时器
246257
* (CodeRabbit 同轮 Minor:别让每个请求都留一枚要等满超时的计时器)。
258+
*
259+
* `diag`(optional,issue #383):超时写 `embed-timeout`,与上面两个原因同一套枚举。
247260
*/
248-
function withEmbedTimeout(promise, timeoutMs) {
261+
function withEmbedTimeout(promise, timeoutMs, diag) {
249262
let timer;
250263
const timeout = new Promise((resolve) => {
251-
timer = setTimeout(() => resolve(undefined), timeoutMs);
264+
timer = setTimeout(() => {
265+
if (diag) diag.reason = "embed-timeout";
266+
resolve(undefined);
267+
}, timeoutMs);
252268
});
253269
return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
254270
}
@@ -671,16 +687,35 @@ export function createStandaloneApi({ service, store, config = {}, logger, setti
671687
const thresholdRaw = Number(url.searchParams.get("threshold") ?? 3);
672688
const threshold = Number.isFinite(thresholdRaw) ? thresholdRaw : 3;
673689
const scope = scopeFromSearchParams(url);
674-
void Promise.resolve(q && embedder ? withEmbedTimeout(embedQueryVector(embedder, q), embedTimeoutMs) : undefined)
675-
.catch(() => undefined) // 查询嵌入失败降级规则档(与 searchMemories 同口径)
690+
// #383:降级原因记账用。embedQueryVector / withEmbedTimeout 只负责「拿不到
691+
// 向量时返回 undefined」,原因(无可用接口 / 空向量 / 超时)在这里回收,
692+
// 供 daemon 侧日志枚举——响应体只多 tier 一个键,不加第二个字段。
693+
const diag = {};
694+
void Promise.resolve(q && embedder ? withEmbedTimeout(embedQueryVector(embedder, q, diag), embedTimeoutMs, diag) : undefined)
695+
.catch((err) => { diag.reason = "embed-error"; return undefined; }) // 查询嵌入失败降级规则档(与 searchMemories 同口径)
676696
.then((queryVector) => {
677697
const pinnedStats = {};
678698
const items = service.injectCandidates({ query: q, maxItems, threshold, queryVector, scope, pinnedStats });
699+
// #383 档位信号:嵌入降级在调用方视角原本完全静默(items 看着正常,只是
700+
// 召回质量悄悄变差),外部集成方无从感知自己长期跑在降级档上。
701+
// 三态 fail-closed——判不出来报 unknown,不报 full:
702+
// full 语义档,查询嵌入真的成功了
703+
// degraded 规则档,且是因为 embedder 缺 / 嵌入超时 / 不可用向量
704+
// unknown 语义路未启用(空 q)——那不是降级,但也不能宣称 full
705+
// 比 /search 的 mode 更精确:/search 把「空查询」和「向量失败」都报
706+
// keyword,这里能分开(空 q 直接可观测)。
707+
let tier = "unknown";
708+
if (q && queryVector) tier = "full";
709+
else if (q) {
710+
tier = "degraded";
711+
logger?.warn?.(`dsh-mneme: /context degraded to the rule tier (${diag.reason ?? (embedder ? "embed-failed" : "no-embedder")})`);
712+
}
679713
sendJson(res, 200, {
680714
profile: (settings?.getProfile?.() ?? "").trim(),
681715
rules: settings?.getRules?.() ?? [],
682716
items: service.toApiList(items),
683-
pinnedCount: pinnedStats.shown ?? 0
717+
pinnedCount: pinnedStats.shown ?? 0,
718+
tier
684719
});
685720
})
686721
.catch(() => {

‎dsh-mneme/src/api-standalone.js‎

Lines changed: 43 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -226,16 +226,27 @@ async function handlePutBody(res, service, logger, id, text) {
226226
* /context 的查询嵌入:best-effort,embedder 接口宽容与 searchMemories 同款
227227
* (embedSingle 优先,兼容 embed-only 的 OpenAI 兼容客户端,issue #10)。
228228
* 调用方负责 catch——嵌入失败降级规则档,绝不因此 500。
229+
*
230+
* `diag`(optional,issue #383):拿不到向量时把原因写进去(`embed-unavailable`
231+
* 无可用接口 / `embed-empty` 空或非数组向量),供 daemon 侧日志枚举降级原因。
232+
* 不传则行为与既往逐字节一致。
229233
*/
230-
async function embedQueryVector(embedder, q) {
234+
async function embedQueryVector(embedder, q, diag) {
231235
const embedSingle = typeof embedder.embedSingle === "function"
232236
? embedder.embedSingle.bind(embedder)
233237
: typeof embedder.embed === "function"
234238
? embedder.embed.bind(embedder)
235239
: null;
236-
if (!embedSingle) return undefined;
240+
if (!embedSingle) {
241+
if (diag) diag.reason = "embed-unavailable";
242+
return undefined;
243+
}
237244
const vector = await embedSingle(q);
238-
return Array.isArray(vector) && vector.length ? vector : undefined;
245+
if (!Array.isArray(vector) || !vector.length) {
246+
if (diag) diag.reason = "embed-empty";
247+
return undefined;
248+
}
249+
return vector;
239250
}
240251

241252
/**
@@ -244,11 +255,16 @@ async function embedQueryVector(embedder, q) {
244255
* 按嵌入缺失处理,降级规则档。输掉的 embed promise 无法取消、自行结束后被丢弃,
245256
* 无害;挂起的主要成本是一个泄漏的挂起任务,可接受。嵌入先完成时清掉定时器
246257
* (CodeRabbit 同轮 Minor:别让每个请求都留一枚要等满超时的计时器)。
258+
*
259+
* `diag`(optional,issue #383):超时写 `embed-timeout`,与上面两个原因同一套枚举。
247260
*/
248-
function withEmbedTimeout(promise, timeoutMs) {
261+
function withEmbedTimeout(promise, timeoutMs, diag) {
249262
let timer;
250263
const timeout = new Promise((resolve) => {
251-
timer = setTimeout(() => resolve(undefined), timeoutMs);
264+
timer = setTimeout(() => {
265+
if (diag) diag.reason = "embed-timeout";
266+
resolve(undefined);
267+
}, timeoutMs);
252268
});
253269
return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
254270
}
@@ -671,16 +687,35 @@ export function createStandaloneApi({ service, store, config = {}, logger, setti
671687
const thresholdRaw = Number(url.searchParams.get("threshold") ?? 3);
672688
const threshold = Number.isFinite(thresholdRaw) ? thresholdRaw : 3;
673689
const scope = scopeFromSearchParams(url);
674-
void Promise.resolve(q && embedder ? withEmbedTimeout(embedQueryVector(embedder, q), embedTimeoutMs) : undefined)
675-
.catch(() => undefined) // 查询嵌入失败降级规则档(与 searchMemories 同口径)
690+
// #383:降级原因记账用。embedQueryVector / withEmbedTimeout 只负责「拿不到
691+
// 向量时返回 undefined」,原因(无可用接口 / 空向量 / 超时)在这里回收,
692+
// 供 daemon 侧日志枚举——响应体只多 tier 一个键,不加第二个字段。
693+
const diag = {};
694+
void Promise.resolve(q && embedder ? withEmbedTimeout(embedQueryVector(embedder, q, diag), embedTimeoutMs, diag) : undefined)
695+
.catch((err) => { diag.reason = "embed-error"; return undefined; }) // 查询嵌入失败降级规则档(与 searchMemories 同口径)
676696
.then((queryVector) => {
677697
const pinnedStats = {};
678698
const items = service.injectCandidates({ query: q, maxItems, threshold, queryVector, scope, pinnedStats });
699+
// #383 档位信号:嵌入降级在调用方视角原本完全静默(items 看着正常,只是
700+
// 召回质量悄悄变差),外部集成方无从感知自己长期跑在降级档上。
701+
// 三态 fail-closed——判不出来报 unknown,不报 full:
702+
// full 语义档,查询嵌入真的成功了
703+
// degraded 规则档,且是因为 embedder 缺 / 嵌入超时 / 不可用向量
704+
// unknown 语义路未启用(空 q)——那不是降级,但也不能宣称 full
705+
// 比 /search 的 mode 更精确:/search 把「空查询」和「向量失败」都报
706+
// keyword,这里能分开(空 q 直接可观测)。
707+
let tier = "unknown";
708+
if (q && queryVector) tier = "full";
709+
else if (q) {
710+
tier = "degraded";
711+
logger?.warn?.(`dsh-mneme: /context degraded to the rule tier (${diag.reason ?? (embedder ? "embed-failed" : "no-embedder")})`);
712+
}
679713
sendJson(res, 200, {
680714
profile: (settings?.getProfile?.() ?? "").trim(),
681715
rules: settings?.getRules?.() ?? [],
682716
items: service.toApiList(items),
683-
pinnedCount: pinnedStats.shown ?? 0
717+
pinnedCount: pinnedStats.shown ?? 0,
718+
tier
684719
});
685720
})
686721
.catch(() => {

‎dsh-mneme/test/standalone-api.test.js‎

Lines changed: 63 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -588,8 +588,11 @@ test("GET /context returns the injection-shaped aggregate; empty q still serves
588588
const res = await fetch(`${base}/context`, { headers: auth });
589589
assert.equal(res.status, 200);
590590
const body = await res.json();
591-
// 形状锁:四键响应——bridge 等调用方按这四个键渲染,漂移(加塞/漏带)在此变红。
592-
assert.deepEqual(Object.keys(body).sort(), ["items", "pinnedCount", "profile", "rules"]);
591+
// 形状锁:五键响应——bridge 等调用方按这些键渲染,漂移(加塞/漏带)在此变红。
592+
// #383 新增 tier(档位信号);空 q 时语义路未启用,报 unknown 而不是 full。
593+
assert.deepEqual(Object.keys(body).sort(), ["items", "pinnedCount", "profile", "rules", "tier"]);
594+
assert.equal(typeof body.tier, "string", "tier 必填");
595+
assert.equal(body.tier, "unknown", "空 q = 语义路未启用,不宣称档位(fail-closed,不报 full)");
593596
assert.equal(body.profile, "我是后端工程师");
594597
assert.deepEqual(body.rules, ["先验证再修改"]);
595598
assert.equal(body.pinnedCount, 0, "pinnedInjectBudget 默认 0(opt-in 纪律,issue #370 取舍 3)");
@@ -749,3 +752,61 @@ test("strictPort: busy port rejects instead of hopping; default path still hops"
749752
store.close();
750753
}
751754
});
755+
756+
// --- GET /context 的档位信号(issue #383)---------------------------------------
757+
// 嵌入降级在调用方视角是完全静默的:items 看起来正常,只是召回质量悄悄变差。
758+
// 外部集成方(Mneme Bridge 的 remote 模式)无法据此降级自己的期望或打日志。
759+
// 三态 fail-closed:判不出来报 unknown,不报 full。
760+
761+
/** 可用的 embedder:任何查询都回一个固定向量。 */
762+
const okEmbedder = { embedSingle: async () => [1, 0, 0], embed: async () => [1, 0, 0] };
763+
764+
test("GET /context tier=full when the query embedding succeeds", async () => {
765+
const { base, auth, close } = await setup({ embedder: okEmbedder });
766+
try {
767+
await saveMemory(base, auth, { type: "decision", title: "核心决策", content: "选定 SQLite 单文件库", importance: 5 });
768+
const body = await (await fetch(`${base}/context?q=${encodeURIComponent("数据库选型")}`, { headers: auth })).json();
769+
assert.equal(body.tier, "full", "嵌入成功 → 语义档");
770+
} finally {
771+
close();
772+
}
773+
});
774+
775+
test("GET /context tier=degraded when no embedder is injected", async () => {
776+
// 缺省(不传 embedder):daemon 与宿主都可能走到这条——embedder 未装配。
777+
const { base, auth, close } = await setup();
778+
try {
779+
await saveMemory(base, auth, { type: "decision", title: "核心决策", content: "选定 SQLite 单文件库", importance: 5 });
780+
const body = await (await fetch(`${base}/context?q=${encodeURIComponent("数据库选型")}`, { headers: auth })).json();
781+
assert.equal(body.tier, "degraded", "无 embedder → 降级到规则档,且必须说出来");
782+
} finally {
783+
close();
784+
}
785+
});
786+
787+
test("GET /context tier=degraded when the query embedding times out", async () => {
788+
// embedder 挂起(不抛错)时由 withEmbedTimeout 兜底——这是最难自查的一种降级,
789+
// 因为接口是好的、只是没有响应。
790+
const hanging = { embedSingle: () => new Promise(() => {}), embed: () => new Promise(() => {}) };
791+
const { base, auth, close } = await setup({ embedder: hanging, embedTimeoutMs: 30 });
792+
try {
793+
await saveMemory(base, auth, { type: "decision", title: "核心决策", content: "选定 SQLite 单文件库", importance: 5 });
794+
const body = await (await fetch(`${base}/context?q=${encodeURIComponent("数据库选型")}`, { headers: auth })).json();
795+
assert.equal(body.tier, "degraded", "嵌入超时 → 降级到规则档");
796+
} finally {
797+
close();
798+
}
799+
});
800+
801+
test("GET /context tier=degraded when the embedder returns an unusable vector", async () => {
802+
// 空数组 / 非数组同样让语义路走不通(embedQueryVector 的既有兜底),一并报降级。
803+
const empty = { embedSingle: async () => [], embed: async () => [] };
804+
const { base, auth, close } = await setup({ embedder: empty });
805+
try {
806+
await saveMemory(base, auth, { type: "decision", title: "核心决策", content: "选定 SQLite 单文件库", importance: 5 });
807+
const body = await (await fetch(`${base}/context?q=${encodeURIComponent("数据库选型")}`, { headers: auth })).json();
808+
assert.equal(body.tier, "degraded", "不可用向量 → 降级到规则档");
809+
} finally {
810+
close();
811+
}
812+
});

0 commit comments

Comments
 (0)