Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): embedding 确定性 INVALID_MODEL 终态化并熔断 source (#3674)
fico-hub814e5548cd68
diff --git a/apps/desktop/src/main/embedding-host/EmbeddingWorker.ts b/apps/desktop/src/main/embedding-host/EmbeddingWorker.tsindex 7aa956ae12..d27c7279cf 100644--- a/apps/desktop/src/main/embedding-host/EmbeddingWorker.ts+++ b/apps/desktop/src/main/embedding-host/EmbeddingWorker.ts@@ -31,6 +31,7 @@ import {getProvider,isProviderSuspended,listSuspendedProviderSources,+ setProviderSuspended,type EmbeddingJobForProvider,} from './providers';@@ -335,11 +336,47 @@ export class EmbeddingWorker {count: modelJobs.length,}),);- // AUTH_FAILED / INVALID_MODEL 在 client 内已经判断为不可重试 — 但 worker 这层- // 不分代码, 一律走 backoff + attempts 计数, MAX_ATTEMPTS 后 → 'failed'。- // 这样 INVALID_MODEL 不会立刻冲 5 次烧 token, 因为 client 抛错前没打 API。- const fc = await this.recordFailureBatch(modelJobs, `[${code}] ${msg}`);+ // #3416:INVALID_MODEL 是确定性失败(模型 id 对当前端点必然 400,+ // 目录门禁只查打包 catalog、不碰真实端点,自配置网关下必失配)——+ // 重试永远不可能成功。整批立即终态 + 熔断该 source:后续 tick 的+ // SQL 过滤(listSuspendedProviderSources)不再取它的 job,语义索引+ // 停止空转;熔断态可经 isEmbeddingSourceSuspended 查询。挂起是+ // 内存态,重启后首批失败会再次熔断,端点修好后自然恢复。+ // 其余错误码(AUTH_FAILED 可因重登恢复、网络/限流为瞬态)维持+ // 既有 backoff + attempts 计数语义不变。+ //+ // 但 INVALID_MODEL 这个 code 本身语义过宽(review #3674 P1):client 的+ // mapStatusToCode 把 400/404/422 乃至一切未识别状态都映射成它,输入级+ // 400(单条超长/畸形输入)会被误判成模型级失配。code 不可靠,判据改成+ // 确定性是否跟着"模型"走 —— 用极小探针输入对同 model 补发一次探测:+ // - 探针同样 INVALID_MODEL → 端点确实不吃这个模型(#3416 场景)→ 终态+熔断;+ // - 探针成功 → 模型可用,是这批输入的问题 → 维持既有 backoff 语义+ // (确定性输入错误按 attempts 上限有界收敛,与修复前行为一致);+ // - 探针遇到其它错误(网络/限流)→ 不下结论,fail-open 不熔断。+ // 成本有界:模型级场景熔断后不再产生新探针;输入级场景每 (source, model)+ // 每 tick 至多一次。+ const terminal =+ code === 'INVALID_MODEL' && !this.aborted+ ? await this.probeModelLevelInvalidModel(source, modelId as string)+ : false;+ // 探针是一次网络往返,期间可能已触发 stop() —— 与 embed 后的检查点同款,+ // abort 后绝不再开写事务;该批 job 保持 pending,下次启动续跑。+ if (this.aborted) return;+ if (isProviderSuspended(source)) break;+ const fc = await this.recordFailureBatch(modelJobs, `[${code}] ${msg}`, terminal);failCount += fc;+ if (terminal && !isProviderSuspended(source)) {+ setProviderSuspended(source, true);+ this.opts.log.error(+ JSON.stringify({+ event: 'embeddingWorker.source.suspendedTerminal',+ source,+ modelId,+ code,+ reason: 'deterministic embedding failure; suspending source until restart or manual resume',+ }),+ );+ }}}}@@ -354,6 +391,46 @@ export class EmbeddingWorker {);}+ /**+ * INVALID_MODEL 的模型级/输入级仲裁探针(review #3674 P1)。+ * 返回 true = 端点对极小合法输入也报 INVALID_MODEL,确认模型级失配,+ * 调方可安全终态化并熔断;其余一律 false(探针成功 = 输入级;探针遇到+ * 别的错误 = 不下结论,fail-open 交回既有 backoff)。+ * 探针文本带时间戳后缀绕开 client 的 LRU 缓存 —— 命中旧缓存的"成功"+ * 证明不了端点现在的状态。本地 catalog 白名单外的模型在 client 入口+ * 同步抛 INVALID_MODEL,探针不打网络、零成本得出模型级结论。+ */+ private async probeModelLevelInvalidModel(source: string, modelId: string): Promise<boolean> {+ try {+ await this.opts.getClient().embed({+ texts: [`cindy embedding probe ${Date.now()}`],+ model: modelId as never,+ });+ this.opts.log.warn(+ JSON.stringify({+ event: 'embeddingWorker.invalidModelProbe.requestLevel',+ source,+ modelId,+ reason: 'probe input embedded fine; batch failure is input-specific, keeping backoff semantics',+ }),+ );+ return false;+ } catch (probeErr) {+ const probeCode = probeErr instanceof EmbeddingError ? probeErr.code : 'UNKNOWN';+ if (probeCode === 'INVALID_MODEL') return true;+ this.opts.log.warn(+ JSON.stringify({+ event: 'embeddingWorker.invalidModelProbe.inconclusive',+ source,+ modelId,+ probeCode,+ reason: 'probe failed with a different code; not suspending',+ }),+ );+ return false;+ }+ }+/*** 把一批 job 标 done (跳过实际嵌入). 同事务内只 UPDATE 状态, 不写 vec 表。*/@@ -390,12 +467,17 @@ export class EmbeddingWorker {* attempts >= MAX → status='failed' 终态。* 返回失败数量 (>= MAX 进 'failed' 终态的部分)。*/- private async recordFailureBatch(jobs: JobRow[], errMsg: string): Promise<number> {+ private async recordFailureBatch(+ jobs: JobRow[],+ errMsg: string,+ terminal = false,+ ): Promise<number> {const now = Date.now();const result = await this.opts.getDbClient().tx('embedding.recordFailures', {jobs: jobs.map((job) => ({ rowid: job.rowid, attempts: job.attempts })),errMsg: truncate(errMsg, 2000),now,+ terminal,});return result.failCount;}diff --git a/apps/desktop/src/main/embedding-host/__tests__/hostLifecycle.test.ts b/apps/desktop/src/main/embedding-host/__tests__/hostLifecycle.test.tsindex 194e1aa7ff..781967aba3 100644--- a/apps/desktop/src/main/embedding-host/__tests__/hostLifecycle.test.ts+++ b/apps/desktop/src/main/embedding-host/__tests__/hostLifecycle.test.ts@@ -293,6 +293,120 @@ describe('embedding-host 多 consumer 启停', () => {expect(tx).toHaveBeenCalledWith('embedding.markDone', { rowids: [1] });expect(embed).not.toHaveBeenCalled();});++ it('INVALID_MODEL 终态化:整批 terminal 记失败并熔断该 source;AUTH_FAILED 保持退避语义 (#3416)', async () => {+ const host = await loadHost();+ const { EmbeddingWorker } = await import('../EmbeddingWorker');+ const { registerProvider } = await import('../providers');+ const { EmbeddingError } = await import('@cindy/embedding-client');+ registerProvider({+ source: 'chat',+ getTextsForJobs: vi.fn().mockResolvedValue([{ rowid: 1, text: 'hello' }]),+ });+ const chatJob = {+ rowid: 1,+ source: 'chat',+ source_id: 'm1',+ chunk_index: 0,+ model_id: 'voyage/voyage-4',+ vec_table: 'chat_messages_vec_v1',+ attempts: 0,+ };+ const query = vi.fn().mockResolvedValue([chatJob]);+ const tx = vi.fn(async () => ({ failCount: 1 }));+ const embed = vi.fn().mockRejectedValue(+ new EmbeddingError('Invalid model name passed in model=voyage/voyage-4', 'INVALID_MODEL', 400),+ );+ const worker = new EmbeddingWorker({+ getDbClient: () => ({ query, tx }) as never,+ getClient: () => ({ embed }) as never,+ isVecAvailable: () => true,+ log: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() } as never,+ });+ const runTick = () => (worker as unknown as { tick(): Promise<void> }).tick();++ await runTick();+ // 确定性失败:整批 terminal 进 'failed',并熔断该 source(后续 tick 的+ // SQL 过滤不再取它的 job,语义索引失效不再静默空转 708 次)。+ expect(tx).toHaveBeenCalledWith(+ 'embedding.recordFailures',+ expect.objectContaining({ terminal: true }),+ );+ expect(host.isEmbeddingSourceSuspended('chat')).toBe(true);++ // 边界:AUTH_FAILED 可因重登恢复,保持既有退避语义、不熔断。+ host.setEmbeddingSourceSuspended('chat', false);+ tx.mockClear();+ embed.mockRejectedValue(new EmbeddingError('unauthorized', 'AUTH_FAILED', 401));+ await runTick();+ expect(tx).toHaveBeenCalledWith(+ 'embedding.recordFailures',+ expect.objectContaining({ terminal: false }),+ );+ expect(host.isEmbeddingSourceSuspended('chat')).toBe(false);+ });++ it('INVALID_MODEL 仲裁探针:输入级 400 保持退避不熔断;探针其它错误 fail-open (#3674 review P1)', async () => {+ const host = await loadHost();+ const { EmbeddingWorker } = await import('../EmbeddingWorker');+ const { registerProvider } = await import('../providers');+ const { EmbeddingError } = await import('@cindy/embedding-client');+ registerProvider({+ source: 'chat',+ getTextsForJobs: vi.fn().mockResolvedValue([{ rowid: 1, text: 'hello' }]),+ });+ const chatJob = {+ rowid: 1,+ source: 'chat',+ source_id: 'm1',+ chunk_index: 0,+ model_id: 'voyage/voyage-4',+ vec_table: 'chat_messages_vec_v1',+ attempts: 0,+ };+ const query = vi.fn().mockResolvedValue([chatJob]);+ const tx = vi.fn(async () => ({ failCount: 1 }));+ // client 的 mapStatusToCode 把 400/404/422 统一映射 INVALID_MODEL,单条坏+ // 输入的 400 与"端点不托管该模型"同码。批失败后 worker 用极小探针输入仲裁:+ // 探针成功 = 模型可用、是输入的问题 → 不熔断,整批走既有 backoff。+ const embed = vi+ .fn()+ .mockRejectedValueOnce(new EmbeddingError('input exceeds max length', 'INVALID_MODEL', 400))+ .mockResolvedValueOnce({+ embeddings: [[0.1]],+ modelUsed: 'voyage/voyage-4',+ tokensUsed: 1,+ cacheHits: 0,+ });+ const worker = new EmbeddingWorker({+ getDbClient: () => ({ query, tx }) as never,+ getClient: () => ({ embed }) as never,+ isVecAvailable: () => true,+ log: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() } as never,+ });+ const runTick = () => (worker as unknown as { tick(): Promise<void> }).tick();++ await runTick();+ expect(embed).toHaveBeenCalledTimes(2); // 批 + 探针+ expect(tx).toHaveBeenCalledWith(+ 'embedding.recordFailures',+ expect.objectContaining({ terminal: false }),+ );+ expect(host.isEmbeddingSourceSuspended('chat')).toBe(false);++ // 探针自己撞上别的错误(网络/5xx)→ 证据不足,fail-open 不熔断。+ tx.mockClear();+ embed.mockReset();+ embed+ .mockRejectedValueOnce(new EmbeddingError('bad request', 'INVALID_MODEL', 400))+ .mockRejectedValueOnce(new EmbeddingError('upstream boom', 'SERVER_ERROR', 500));+ await runTick();+ expect(tx).toHaveBeenCalledWith(+ 'embedding.recordFailures',+ expect.objectContaining({ terminal: false }),+ );+ expect(host.isEmbeddingSourceSuspended('chat')).toBe(false);+ });});describe('chat embedding availability wiring', () => {diff --git a/apps/desktop/src/main/localDb/client/__tests__/tx.test.ts b/apps/desktop/src/main/localDb/client/__tests__/tx.test.tsindex 9c0721448d..2b9a4c391b 100644--- a/apps/desktop/src/main/localDb/client/__tests__/tx.test.ts+++ b/apps/desktop/src/main/localDb/client/__tests__/tx.test.ts@@ -2548,6 +2548,23 @@ describe('db worker tx handlers', () => {});});+ it('embedding.recordFailures terminal=true 整批直接进 failed,不消耗退避尝试 (#3416)', async () => {+ await withClient(async (client) => {+ const freshRowid = await insertJob(client, { sourceId: 'fresh', attempts: 0 });+ const result = await client.tx('embedding.recordFailures', {+ jobs: [{ rowid: freshRowid, attempts: 0 }],+ errMsg: '[INVALID_MODEL] Invalid model name',+ now: 10_000,+ terminal: true,+ });++ expect(result).toEqual({ failCount: 1 });+ await expect(+ client.query('SELECT rowid, status, attempts FROM embedding_jobs ORDER BY rowid'),+ ).resolves.toEqual([{ rowid: freshRowid, status: 'failed', attempts: 1 }]);+ });+ });+it('embedding.enqueue inserts only new natural-key jobs', async () => {await withClient(async (client) => {const result = await client.tx('embedding.enqueue', {diff --git a/apps/desktop/src/main/localDb/client/tx/types.ts b/apps/desktop/src/main/localDb/client/tx/types.tsindex 62c7f981b1..bd35c8e3ff 100644--- a/apps/desktop/src/main/localDb/client/tx/types.ts+++ b/apps/desktop/src/main/localDb/client/tx/types.ts@@ -182,6 +182,8 @@ export interface EmbeddingRecordFailuresArgs {jobs: Array<{ rowid: number; attempts: number }>;errMsg: string;now: number;+ /** #3416:确定性失败(INVALID_MODEL 等)整批直接进 'failed' 终态,不走退避。 */+ terminal?: boolean;}export interface EmbeddingEnqueueArgs {diff --git a/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts b/apps/desktop/src/main/localDb/worker/opHandlers/tx.tsindex c83b8c9d41..7431c58394 100644--- a/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts+++ b/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts@@ -1729,6 +1729,9 @@ function embeddingRecordFailures(db: Database.Database, args: unknown): { failCoconst jobs = expectArray(payload.jobs, 'jobs');const errMsg = truncate(expectString(payload.errMsg, 'errMsg'), 2000);const now = expectNumber(payload.now, 'now');+ // #3416:确定性失败(如 INVALID_MODEL)重试永远不可能成功,terminal=true 时+ // 整批直接进 'failed' 终态,不再烧 5 次退避尝试。缺省 false 保持旧语义。+ const terminal = payload.terminal === true;const updReschedule = db.prepare(`UPDATE embedding_jobsSET attempts = ?, last_error = ?, scheduled_at = ?@@ -1745,7 +1748,7 @@ function embeddingRecordFailures(db: Database.Database, args: unknown): { failCoconst job = asRecord(rawJob, 'failure job');const rowid = expectNumber(job.rowid, 'job.rowid');const nextAttempts = expectNumber(job.attempts, 'job.attempts') + 1;- if (nextAttempts >= MAX_ATTEMPTS) {+ if (terminal || nextAttempts >= MAX_ATTEMPTS) {updFail.run(nextAttempts, errMsg, rowid);failCount++;} else {