From 3e4b55cc25b2ff4655ea6bcc58307d7be78cbd6e Mon Sep 17 00:00:00 2001 From: creatixchu Date: Wed, 11 Nov 2026 21:14:11 +0800 Subject: [PATCH 1/6] Back off timed-out Files uploads across image requests --- packages/llm/llm-deepseek/README.i18n.yaml | 8 +- packages/llm/llm-deepseek/README.md | 6 +- packages/llm/llm-deepseek/README.zh.md | 6 +- packages/llm/llm-deepseek/src/config.ts | 2 +- packages/llm/llm-deepseek/src/defaults.ts | 2 +- packages/llm/llm-deepseek/src/file-store.ts | 58 +++++++++++-- .../llm/llm-deepseek/src/request-files.ts | 8 +- packages/llm/llm-deepseek/src/upload-index.ts | 8 +- .../llm/llm-deepseek/tests/file-store.spec.ts | 81 ++++++++++++++++++- packages/llm/llm-deepseek/tests/files.spec.ts | 2 +- .../llm/llm-deepseek/tests/runtime.spec.ts | 52 ++++++------ 11 files changed, 183 insertions(+), 50 deletions(-) diff --git a/packages/llm/llm-deepseek/README.i18n.yaml b/packages/llm/llm-deepseek/README.i18n.yaml index 18c1efe0dc..69528d9c25 100644 --- a/packages/llm/llm-deepseek/README.i18n.yaml +++ b/packages/llm/llm-deepseek/README.i18n.yaml @@ -21,8 +21,8 @@ en: 6850d08bc091ad23 zh: 2906e6cf1dfed6ce /deepseek-ai-dsh-llm-deepseek/use-this-package/minimal-configuration: - en: 6a15f2e0efec4c37 - zh: 7fb5f1e4a92b01ad + en: ad01714ddbd0a791 + zh: f936398331d6fb85 /deepseek-ai-dsh-llm-deepseek/use-this-package/endpoint-and-wire-format: en: 2a634ead5b47fe97 zh: 46f199ee79a8c5dc @@ -30,8 +30,8 @@ en: d3f232309f4963ef zh: 2e0ccd028de26f3e /deepseek-ai-dsh-llm-deepseek/use-this-package/streaming-with-thinking-and-images: - en: 81bf213499f015ba - zh: e9107ef322213e56 + en: 2725460b95b490f2 + zh: aec8b5abec1d79aa /deepseek-ai-dsh-llm-deepseek/use-this-package/dynamic-configuration: en: 49290fc5647136b4 zh: 96fa9ce0f9e83c13 diff --git a/packages/llm/llm-deepseek/README.md b/packages/llm/llm-deepseek/README.md index 3c25fee26e..136752e0c1 100644 --- a/packages/llm/llm-deepseek/README.md +++ b/packages/llm/llm-deepseek/README.md @@ -47,7 +47,7 @@ Choose this adapter for DeepSeek's official API or a Messages-compatible gateway maxRequestFilesBytes: 134217728 maxInlineRequestImageBytes: 20971520 maxImagesPerRequest: 600 - filesApiTimeoutMs: 60000 + filesApiTimeoutMs: 20000 ``` A request selects the route with `provider: deepseek-official`; the model id passes through to the wire, so new DeepSeek models need no re-registration. Omitted `models` advertises the text- and image-capable `deepseek-flash` alongside the text-only `deepseek-v4-pro`, each with the 1,048,576-token context window the official model listing declares. An explicit list replaces those defaults, and core calls still pass unlisted model ids through as text-only routes. On the official endpoint the API-key route follows the service's model listing while `models` holds those defaults ([listing rules](../llm-deepseek-api-key/README.md#use-this-package)). GUI selection requires a catalog entry; a saved selection can still submit requests after its catalog entry disappears. Clients, including model discovery tools, can read the advisory entries through `ctx.llm.listModels('deepseek-official')`. Image-capable entries may set `imagePixelBudget` to a positive integer or `low`, and may set `imageMaxBytes`. An entry may declare `systemPromptUpdate: in-history` when its endpoint reads the latest `system` message at any position of `messages` as the complete effective system prompt; the adapter reports the mode on the resolved model and the prepared call, and the agent loop then appends a changed prompt after the cached history instead of rewriting the leading system message ([decision rule](../../core/agent-loop/README.md#understand-the-implementation)). The default `deepseek-flash` entry declares this mode; other models require an explicit `models` declaration, and any value other than `in-history` fails at load with `llm-deepseek: catalog model "" systemPromptUpdate must be "in-history" when present`. @@ -67,7 +67,7 @@ A request selects the route with `provider: deepseek-official`; the model id pas | `imageOffloadByteQuantum` | `64 MiB` | Files-mode oldest-prefix removal quantum | | `inlineImageOffloadByteQuantum` | `10 MiB` | Inline-mode oldest-prefix removal quantum | | `imageOffloadCountQuantum` | `20` | Count-overflow removal quantum | -| `filesApiTimeoutMs` | `60,000` | Per-image Files resolution deadline | +| `filesApiTimeoutMs` | `20,000` | Per-image Files resolution deadline | | `fileExpiresAfterSeconds` | `604,800` | Requested uploaded-image lifetime and local reuse bound | | `fileRefreshMarginSeconds` | `3,600` | Remaining reuse lifetime below which an id is replaced | | `fileQuotaCleanupBatch` | `100` | Oldest harness-owned files removed before one quota retry | @@ -99,6 +99,8 @@ An image-capable route chooses each durable reference's request target and resol The adapter normally uploads those exact request bytes through `/v1/files` and sends file-id references. Files requests and model requests containing file ids include `anthropic-beta: files-api-2025-04-14`. All requests reject redirects so credentials remain on the configured origin. A failed or timed-out file resolution rebuilds the whole model request with inline base64 under the inline budget; one request never mixes file ids and inline images. Caller cancellation stops the request. +After an upload times out, the next model request that needs a new upload uses inline images immediately. Each consecutive upload timeout doubles the number of such requests to skip (1, 2, 4, 8, …), regardless of elapsed time. The adapter counts each request once for its endpoint and credential. Text-only requests and requests served entirely by cached file ids do not count. A successful upload resets the count. + Cached ids are scoped by endpoint and credential, refreshed before expiry, invalidated from provider stale-file errors, and resolved through singleflight with waiter-local cancellation. Uploads request expiry through `expires_after[anchor]=created_at` and `expires_after[seconds]`. Messages file metadata omits remote expiry, so its local reuse deadline uses the original upload time plus `fileExpiresAfterSeconds`; this does not guarantee remote deletion. Quota failure deletes one configured batch of the oldest harness-owned files before one upload retry. Files mode bounds retained request versions by `maxRequestFilesBytes` and `maxImagesPerRequest`; inline fallback has its own base64 budget. Both remove an oldest prefix in configured byte or count quanta. Each omitted image gets its own model-visible placeholder with its display name or attachment id and, when available, normalized dimensions, media type, and current read-only path. The stepped high-watermark policy avoids rewriting an old request prefix after every new image. diff --git a/packages/llm/llm-deepseek/README.zh.md b/packages/llm/llm-deepseek/README.zh.md index 3d1b6beeb4..03b290f9a1 100644 --- a/packages/llm/llm-deepseek/README.zh.md +++ b/packages/llm/llm-deepseek/README.zh.md @@ -47,7 +47,7 @@ kind: "package-reference" maxRequestFilesBytes: 134217728 maxInlineRequestImageBytes: 20971520 maxImagesPerRequest: 600 - filesApiTimeoutMs: 60000 + filesApiTimeoutMs: 20000 ``` 请求用 `provider: deepseek-official` 选择路由;模型 id 原样传到协议,因此新增 DeepSeek 模型无需重新注册。省略 `models` 时公布支持文本和图像的 `deepseek-flash`,以及仅支持文本的 `deepseek-v4-pro`,各自的上下文窗口均为官方模型列表声明的 1,048,576 token。显式列表会替换这些默认值,核心调用中未列出的模型 id 仍作为纯文本路由原样通过。在官方端点上,当 `models` 保持这些默认值时,API key 路由改为使用服务端的模型列表([列表规则](../llm-deepseek-api-key/README.zh.md#use-this-package))。GUI 选择要求模型具有目录条目;条目消失后,已保存的选择仍可提交请求。包括模型发现工具在内的客户端可通过 `ctx.llm.listModels('deepseek-official')` 读取这些建议性条目。支持图片的条目可把 `imagePixelBudget` 设置为正整数或 `low`,也可以设置 `imageMaxBytes`。当端点把 `messages` 中任意位置最新的 `system` 消息读作完整的有效系统提示词时,条目可以声明 `systemPromptUpdate: in-history`;适配器会在已解析模型与已准备调用上报告该模式,agent loop(智能体循环)随后把变化后的提示词追加到已缓存历史之后,而不是改写开头的 system 消息([决策规则](../../core/agent-loop/README.zh.md#understand-the-implementation))。默认的 `deepseek-flash` 条目声明该模式;其他模型需通过 `models` 显式声明,`in-history` 以外的任何值都会在加载时以 `llm-deepseek: catalog model "" systemPromptUpdate must be "in-history" when present` 失败。 @@ -67,7 +67,7 @@ kind: "package-reference" | `imageOffloadByteQuantum` | `64 MiB` | Files 模式最旧前缀移除量子 | | `inlineImageOffloadByteQuantum` | `10 MiB` | 内联模式最旧前缀移除量子 | | `imageOffloadCountQuantum` | `20` | 数量超限移除量子 | -| `filesApiTimeoutMs` | `60,000` | 每张图片 Files 解析截止时间 | +| `filesApiTimeoutMs` | `20,000` | 每张图片 Files 解析截止时间 | | `fileExpiresAfterSeconds` | `604,800` | 请求的上传图片生存期与本地复用期限 | | `fileRefreshMarginSeconds` | `3,600` | 低于此剩余复用期时替换 id | | `fileQuotaCleanupBatch` | `100` | 配额重试前删除的、归 harness 所有的最旧文件数 | @@ -99,6 +99,8 @@ Messages 和 Files 请求通过 `x-dsh-auth-token` 发送账号 token,不加 B 适配器通常通过 `/v1/files` 上传这些确切请求字节,并发送 file-id 引用。Files 请求与包含 file id 的模型请求均携带 `anthropic-beta: files-api-2025-04-14`。全部请求拒绝重定向,确保凭据仅发送到配置的源。文件解析失败或超时会按内联预算,用内联 base64 重建整份模型请求;一次请求绝不混用 file id 与内联图片。调用方取消会停止请求。 +上传超时后,下一次需要上传图片的模型请求直接使用内联图片。连续上传超时时,跳过的请求数依次为 1、2、4、8 次,之后继续翻倍,不受经过时间的影响。同一端点和凭据按请求计数,多张图片只算一次。纯文本请求和所有图片都命中文件 ID 缓存的请求不计数。实际上传成功后清零。 + 缓存 id 按端点与凭据限定作用域,在到期前刷新,根据提供方的陈旧文件错误失效,并通过带等待方局部取消的 singleflight 解析。上传通过 `expires_after[anchor]=created_at` 与 `expires_after[seconds]` 请求过期。Messages 文件元数据不含远端过期时间,因此本地复用期限使用原始上传时间加 `fileExpiresAfterSeconds`;这不保证远端文件删除。配额失败会先删除一批配置数量的最旧 harness 文件,再重试一次上传。 Files 模式通过 `maxRequestFilesBytes` 与 `maxImagesPerRequest` 限制保留请求版本;内联回退有独立 base64 预算。两种模式都按配置的字节或数量量子移除最旧前缀。每张省略图片都有自己的模型可见占位符,包含显示名或附件 id,以及可用时的规范化尺寸、媒体类型与当前只读路径。分阶高水位策略避免每新增一张图片都改写旧请求前缀。 diff --git a/packages/llm/llm-deepseek/src/config.ts b/packages/llm/llm-deepseek/src/config.ts index 630ccea010..494797f8b0 100644 --- a/packages/llm/llm-deepseek/src/config.ts +++ b/packages/llm/llm-deepseek/src/config.ts @@ -43,7 +43,7 @@ export interface Config { inlineImageOffloadByteQuantum: Volatile /** Image-count removal step after the request exceeds its count bound (default 20). */ imageOffloadCountQuantum: Volatile - /** Maximum duration of one request-image Files API resolution (default one minute). */ + /** Maximum duration of one request-image Files API resolution (default 20 seconds). */ filesApiTimeoutMs: Volatile /** Explicit lifetime assigned to each uploaded image (default seven days). */ fileExpiresAfterSeconds: Volatile diff --git a/packages/llm/llm-deepseek/src/defaults.ts b/packages/llm/llm-deepseek/src/defaults.ts index 21ad79538e..b89a36e86b 100644 --- a/packages/llm/llm-deepseek/src/defaults.ts +++ b/packages/llm/llm-deepseek/src/defaults.ts @@ -21,4 +21,4 @@ export const DEFAULT_FILE_REFRESH_MARGIN_SECONDS = 60 * 60 /** Default number of oldest harness-owned files removed on quota recovery. */ export const DEFAULT_FILE_QUOTA_CLEANUP_BATCH = 100 /** Default deadline for resolving one request image through the Files API. */ -export const DEFAULT_FILES_API_TIMEOUT_MS = 60_000 +export const DEFAULT_FILES_API_TIMEOUT_MS = 20_000 diff --git a/packages/llm/llm-deepseek/src/file-store.ts b/packages/llm/llm-deepseek/src/file-store.ts index da6f87654a..921f7b71a1 100644 --- a/packages/llm/llm-deepseek/src/file-store.ts +++ b/packages/llm/llm-deepseek/src/file-store.ts @@ -1,5 +1,7 @@ /** DeepSeek Files API upload reuse, invalidation, and quota recovery. @module dsh-llm-deepseek/file-store */ +import { addAbortListener } from 'node:events' +import { timeoutOf } from '@deepseek-ai/dsh-timeout' import type { RequestImageAttachment } from '@deepseek-ai/dsh-attachment' import { LlmError } from '@deepseek-ai/dsh-llm' import { DeepSeekFilesClient, isFilesQuotaError } from './files-api.ts' @@ -11,6 +13,18 @@ import type { DeepSeekUploadRecord } from './upload-index.ts' /** Shared Files-store limit for each request image, including file-id references. */ export const MAX_IMAGE_BYTES = 32 * 1024 * 1024 const OWNED_FILE_PREFIX = 'dsh-' +/** Per-image deadline whose expiry during upload starts Files backoff. */ +export const FILES_API_TIMEOUT = 'DEEPSEEK_FILES_API_TIMEOUT' + +interface UploadBackoff { + interval: bigint + remaining: bigint +} + +/** Shared by all image resolutions of one model request, including stale-id recovery. */ +export interface FileUploadRequest { + skipped?: boolean +} /** Resolved file-store policy from the plugin configuration. */ export interface DeepSeekFilePolicy { @@ -122,6 +136,7 @@ export class DeepSeekFileStore { private readonly index: DeepSeekUploadIndex private readonly now: () => number private readonly fetchImpl: typeof fetch | undefined + private readonly backoffs = new Map() private readonly inflight = new Map() /** @@ -147,16 +162,41 @@ export class DeepSeekFileStore { * @param connection - endpoint and API-key snapshot. * @param policy - expiry and quota-recovery policy. * @param signal - cancellation of this wait; shared transport stops when no waiter remains. - * @returns a reusable file id and whether this call published a new upload. + * @param request - one model request's skip decision, shared across its images. Omit for an independent resolution. + * @returns a reusable file id and whether this call published a new upload. A skipped upload rejects with TIMEOUT. */ ensureUploaded( version: RequestImageAttachment, connection: DeepSeekFileConnection, policy: DeepSeekFilePolicy, signal?: AbortSignal, + request: FileUploadRequest = {}, ): Promise { signal?.throwIfAborted() + if (version.bytes > MAX_IMAGE_BYTES) { + return Promise.reject(new LlmError('DeepSeek image exceeds the 32 MiB per-image limit.', 'INVALID_REQUEST')) + } const scope = fileScope(connection) + if (request.skipped || this.backoffs.get(scope)?.remaining) { + return this.index.get(scope, version.variantId, this.now(), policy.refreshMarginSeconds * 1_000, signal).then((cached) => { + signal?.throwIfAborted() + if (cached) return { record: cached, uploaded: false } + const backoff = this.backoffs.get(scope) + if (!request.skipped && backoff?.remaining) { + backoff.remaining-- + request.skipped = true + } + if (request.skipped) throw new LlmError('DeepSeek Files API upload skipped after a timeout.', 'TIMEOUT') + return this.sharedUpload(version, connection, policy, scope, signal) + }) + } + return this.sharedUpload(version, connection, policy, scope, signal) + } + + private sharedUpload( + version: RequestImageAttachment, connection: DeepSeekFileConnection, policy: DeepSeekFilePolicy, + scope: DeepSeekUploadRecord['scope'], signal?: AbortSignal, + ): Promise { const key = `${scope}\0${version.variantId}` let active = this.inflight.get(key) if (active?.controller.signal.aborted) { @@ -171,7 +211,7 @@ export class DeepSeekFileStore { waiters: 0, promise: undefined as never, } - shared.promise = this.ensureUploadedOnce(version, connection, policy, controller.signal).then((value) => { + shared.promise = this.ensureUploadedOnce(version, connection, policy, scope, controller.signal).then((value) => { shared.settled = true return value }, (error: unknown) => { @@ -189,12 +229,9 @@ export class DeepSeekFileStore { version: RequestImageAttachment, connection: DeepSeekFileConnection, policy: DeepSeekFilePolicy, + scope: DeepSeekUploadRecord['scope'], signal: AbortSignal, ): Promise { - if (version.bytes > MAX_IMAGE_BYTES) { - throw new LlmError('DeepSeek image exceeds the 32 MiB per-image limit.', 'INVALID_REQUEST') - } - const scope = fileScope(connection) const now = this.now() const marginMs = policy.refreshMarginSeconds * 1_000 const cached = await this.index.get(scope, version.variantId, now, marginMs) @@ -202,6 +239,14 @@ export class DeepSeekFileStore { const client = this.client(connection) const upload = async (): Promise => { + signal.throwIfAborted() + const previous = this.backoffs.get(scope) + // Count overlapping uploads from one failure interval once, even if an aborted transport never settles. + using _listener = addAbortListener(signal, () => { + if (!timeoutOf(signal, FILES_API_TIMEOUT) || this.backoffs.get(scope) !== previous) return + const interval = previous ? previous.interval * 2n : 1n + this.backoffs.set(scope, { interval, remaining: interval }) + }) const remote = await client.upload({ data: version.data, mediaType: version.mediaType, @@ -212,6 +257,7 @@ export class DeepSeekFileStore { if (remote.bytes !== version.data.byteLength) { throw new LlmError('DeepSeek Files API upload response does not match the submitted image.', 'INVALID_RESPONSE') } + if (!signal.aborted) this.backoffs.delete(scope) return { scope, attachmentId: version.attachment.attachmentId, diff --git a/packages/llm/llm-deepseek/src/request-files.ts b/packages/llm/llm-deepseek/src/request-files.ts index 85e1460903..21e325f828 100644 --- a/packages/llm/llm-deepseek/src/request-files.ts +++ b/packages/llm/llm-deepseek/src/request-files.ts @@ -1,8 +1,9 @@ /** Shared Files resolution, bounded stale-id recovery, and normalized-image diagnostics. */ import type { RequestImageAttachment } from '@deepseek-ai/dsh-attachment' +import { FILES_API_TIMEOUT } from './file-store.ts' import { deadline } from '@deepseek-ai/dsh-timeout' -import type { DeepSeekFileStore, DeepSeekFileConnection, DeepSeekFilePolicy } from './file-store.ts' +import type { DeepSeekFileStore, DeepSeekFileConnection, DeepSeekFilePolicy, FileUploadRequest } from './file-store.ts' import type { DeepSeekFileId } from './file-id.ts' /** Position of an image occurrence in the request's conversation messages. */ @@ -94,6 +95,7 @@ function normalizedImageDiagnostic( export class RequestFiles { private used: UsedRequestFile[] = [] private retried = false + private readonly uploadRequest: FileUploadRequest = {} constructor( private readonly files: DeepSeekFileStore, @@ -114,10 +116,10 @@ export class RequestFiles { * @returns the reusable provider id. */ async resolve(version: RequestImageAttachment, location: ImageWireLocation): Promise { - using limit = deadline(this.signal, this.timeoutMs, 'DEEPSEEK_FILES_API_TIMEOUT') + using limit = deadline(this.signal, this.timeoutMs, FILES_API_TIMEOUT) let resolved: Awaited> try { - resolved = await this.files.ensureUploaded(version, this.connection, this.policy, limit.signal) + resolved = await this.files.ensureUploaded(version, this.connection, this.policy, limit.signal, this.uploadRequest) } catch (error) { if (this.signal.aborted) throw error throw new FileResolutionFailure(error) diff --git a/packages/llm/llm-deepseek/src/upload-index.ts b/packages/llm/llm-deepseek/src/upload-index.ts index 49c9ea62ce..db48b0c416 100644 --- a/packages/llm/llm-deepseek/src/upload-index.ts +++ b/packages/llm/llm-deepseek/src/upload-index.ts @@ -119,9 +119,9 @@ export class DeepSeekUploadIndex { this.path = path } - private async load(): Promise { + private async load(signal?: AbortSignal): Promise { try { - return parseIndex(await readFile(this.path, 'utf8')) + return parseIndex(await readFile(this.path, { encoding: 'utf8', signal })) } catch (error: unknown) { if (absent(error) || error instanceof InvalidUploadIndexError) { return { formatVersion: 3, records: [] } @@ -143,6 +143,7 @@ export class DeepSeekUploadIndex { * @param variantId - complete request-image transformation identity. * @param now - current Unix time in milliseconds. * @param refreshMarginMs - remaining lifetime below which a mapping is not reused. + * @param signal - cancellation of the index read. * @returns the mapping when it has enough lifetime remaining. */ async get( @@ -150,8 +151,9 @@ export class DeepSeekUploadIndex { variantId: ImageVariantIdType, now: number, refreshMarginMs: number, + signal?: AbortSignal, ): Promise { - const record = (await this.load()).records.find(candidate => ( + const record = (await this.load(signal)).records.find(candidate => ( candidate.scope === scope && candidate.variantId === variantId )) return record !== undefined && reusable(record, now, refreshMarginMs) ? record : undefined diff --git a/packages/llm/llm-deepseek/tests/file-store.spec.ts b/packages/llm/llm-deepseek/tests/file-store.spec.ts index 46e7a1cb66..9edf910b2b 100644 --- a/packages/llm/llm-deepseek/tests/file-store.spec.ts +++ b/packages/llm/llm-deepseek/tests/file-store.spec.ts @@ -5,7 +5,8 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import { brandString } from '@deepseek-ai/dsh-brand' import type { AttachmentId, ImageVariantId } from '@deepseek-ai/dsh-attachment/types' import type { ImageAttachmentRef, RequestImageAttachment } from '@deepseek-ai/dsh-attachment' -import { DeepSeekFileStore, MAX_IMAGE_BYTES } from '../src/file-store.ts' +import { TimeoutReason } from '@deepseek-ai/dsh-timeout' +import { DeepSeekFileStore, FILES_API_TIMEOUT, MAX_IMAGE_BYTES } from '../src/file-store.ts' import type { DeepSeekFileId } from '../src/file-id.ts' import { deepSeekFileScope, DeepSeekUploadIndex } from '../src/upload-index.ts' @@ -68,6 +69,84 @@ function uploadFetch(now: () => number = () => NOW) { } describe('DeepSeekFileStore', () => { + it('skips 1, 2, 4 and 8 upload-bearing requests between timeouts, and resets after an upload', async () => { + const dir = await mkdtemp(join(tmpdir(), 'dsh-files-backoff-')) + roots.push(dir) + const fetch = vi.fn(uploadFetch().fetchImpl) + const store = new DeepSeekFileStore({ fetch, now: () => NOW, index: new DeepSeekUploadIndex(join(dir, 'index.json')) }) + const cached = { ...VERSION, variantId: brandString(`sha256:${'c'.repeat(64)}`) } + await store.ensureUploaded(cached, CONNECTION, POLICY) + async function expire(image: RequestImageAttachment) { + const started = Promise.withResolvers() + fetch.mockImplementationOnce((_url, init) => new Promise((_resolve, reject) => { + started.resolve(undefined) + init!.signal!.addEventListener('abort', () => { reject(new Error('upload aborted')) }, { once: true }) + })) + const controller = new AbortController() + const pending = store.ensureUploaded(image, CONNECTION, POLICY, controller.signal) + await started.promise + const reason = new TimeoutReason(FILES_API_TIMEOUT, 20_000) + controller.abort(reason) + await expect(pending).rejects.toBe(reason) + } + + for (const count of [1, 2, 4, 8]) { + await expire(VERSION) + const calls = fetch.mock.calls.length + for (let i = 0; i < count; i++) { + await expect(store.ensureUploaded(cached, CONNECTION, POLICY)).resolves.toMatchObject({ uploaded: false }) + // The two cache misses are images from one model request. + const request = {} + const missing = [VERSION, { ...VERSION, variantId: brandString(`sha256:${'e'.repeat(64)}`) }] + await Promise.all(missing.map(image => expect(store.ensureUploaded(image, CONNECTION, POLICY, undefined, request)) + .rejects.toMatchObject({ code: 'TIMEOUT' }))) + } + expect(fetch).toHaveBeenCalledTimes(calls) + await expect(store.ensureUploaded(VERSION, { ...CONNECTION, headers: { 'x-api-key': 'other' } }, POLICY)).resolves.toBeDefined() + await expect(store.ensureUploaded(VERSION, { ...CONNECTION, baseURL: 'https://other.example' }, POLICY)).resolves.toBeDefined() + } + await expect(store.ensureUploaded(VERSION, CONNECTION, POLICY)).resolves.toMatchObject({ uploaded: true }) + const fresh = { ...VERSION, variantId: brandString(`sha256:${'d'.repeat(64)}`) } + await expire(fresh) + await expect(store.ensureUploaded(fresh, CONNECTION, POLICY)).rejects.toMatchObject({ code: 'TIMEOUT' }) + await expect(store.ensureUploaded(fresh, CONNECTION, POLICY)).resolves.toMatchObject({ uploaded: true }) + }) + + it('counts overlapping timeouts once and keeps an abandoned response from clearing backoff', async () => { + const dir = await mkdtemp(join(tmpdir(), 'dsh-files-overlap-')) + roots.push(dir) + const now = NOW + const remote = uploadFetch(() => now) + const fetch = vi.fn(remote.fetchImpl) + const store = new DeepSeekFileStore({ fetch, now: () => now, index: new DeepSeekUploadIndex(join(dir, 'index.json')) }) + const stalled = async (variantId: string) => { + const started = Promise.withResolvers() + const response = Promise.withResolvers() + fetch.mockImplementationOnce(() => { started.resolve(undefined); return response.promise }) + const image = { ...VERSION, variantId: brandString(variantId) } + const controller = new AbortController() + const pending = store.ensureUploaded(image, CONNECTION, POLICY, controller.signal) + await started.promise + return { image, response, pending, controller } + } + const first = await stalled('first') + const second = await stalled('second') + for (const upload of [first, second]) { + const reason = new TimeoutReason(FILES_API_TIMEOUT, 20_000) + upload.controller.abort(reason) + await expect(upload.pending).rejects.toBe(reason) + upload.response.resolve(await remote.fetchImpl(CONNECTION.baseURL, { method: 'POST' })) + } + // A settled index write makes the late responses observable before checking the backoff. + await vi.waitFor(async () => { + const scope = deepSeekFileScope(CONNECTION.baseURL + '/v1', JSON.stringify(Object.entries(CONNECTION.headers))) + const index = new DeepSeekUploadIndex(join(dir, 'index.json')) + expect(await index.get(scope, second.image.variantId, now, 0)).toBeDefined() + }) + await expect(store.ensureUploaded(VERSION, CONNECTION, POLICY)).rejects.toMatchObject({ code: 'TIMEOUT' }) + await expect(store.ensureUploaded(VERSION, CONNECTION, POLICY)).resolves.toMatchObject({ uploaded: true }) + }) + it('isolates credential values and header kinds while reusing reordered headers', async () => { const dir = await mkdtemp(join(tmpdir(), 'dsh-file-credentials-')) roots.push(dir) diff --git a/packages/llm/llm-deepseek/tests/files.spec.ts b/packages/llm/llm-deepseek/tests/files.spec.ts index de09e7b1c2..e358fed0bc 100644 --- a/packages/llm/llm-deepseek/tests/files.spec.ts +++ b/packages/llm/llm-deepseek/tests/files.spec.ts @@ -57,7 +57,7 @@ describe('Messages Files requests', () => { createToolResultMessage({ callId, isError: false, content: [{ type: 'image', attachment: ref }, { type: 'image', attachment: ref }] })] await chunks(h.adapter.stream(options({ model, messages }))) expect(h.readImageRequest).toHaveBeenCalledTimes(1) - expect(h.ensureUploaded).toHaveBeenCalledWith(expect.anything(), { baseURL: 'https://gateway.example/custom', headers: { 'x-api-key': 'test-key' } }, expect.anything(), expect.any(AbortSignal)) + expect(h.ensureUploaded).toHaveBeenCalledWith(expect.anything(), { baseURL: 'https://gateway.example/custom', headers: { 'x-api-key': 'test-key' } }, expect.anything(), expect.any(AbortSignal), expect.anything()) const [url, init] = fetchImpl.mock.calls[0]! expect(url).toBe('https://gateway.example/custom/v1/messages') expect(new Headers(init?.headers).get('anthropic-beta')).toBe('files-api-2025-04-14') diff --git a/packages/llm/llm-deepseek/tests/runtime.spec.ts b/packages/llm/llm-deepseek/tests/runtime.spec.ts index fd942595f5..c13180805d 100644 --- a/packages/llm/llm-deepseek/tests/runtime.spec.ts +++ b/packages/llm/llm-deepseek/tests/runtime.spec.ts @@ -536,39 +536,39 @@ describe('DeepSeekAdapter against a mock server', () => { expect(JSON.stringify(body)).not.toContain('file-api-partial') }) - it('falls back after the configured Files API deadline without aborting the model request', async () => { + it('sends successive image requests inline after one 20-second upload timeout', async () => { vi.useFakeTimers() const started = Promise.withResolvers() - const files = fileStoreOf((_version, _connection, _policy, signal) => new Promise((_resolve, reject) => { + const upload = vi.fn((_url, init) => new Promise((_resolve, reject) => { started.resolve(undefined) - signal?.addEventListener('abort', () => { - const reason: unknown = signal.reason - reject(reason instanceof Error ? reason : new Error('files operation aborted')) - }, { once: true }) + init!.signal!.addEventListener('abort', () => { reject(new Error('upload aborted')) }, { once: true }) })) + const files = new Protocol.DeepSeekFileStore({ fetch: upload }) const attachments = attachmentStoreOf(ref => Promise.resolve(requestImage(ref))).store - const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(successfulSseResponse()) - const adapter = adapterOf({ - baseURL: 'https://deepseek.invalid', - filesApiTimeoutMs: 50, - models: [{ id: 'deepseek-v4-flash-vision-exp', inputModalities: ['text', 'image'] }], - }, attachments, files.store) - - const pending = drain(adapter.stream({ - provider: 'deepseek-official', - model: 'deepseek-v4-flash-vision-exp', - messages: [createUserMessage({ - content: [{ type: 'image', attachment: imageRef }], - source: { kind: 'model', provider: 'deepseek-official', model: 'deepseek-v4-flash' }, - })], + const messages = vi.spyOn(globalThis, 'fetch').mockImplementation(async () => successfulSseResponse()) + const adapter = adapterOf({ baseURL: 'https://deepseek.invalid' }, attachments, files) + const request = () => drain(adapter.stream({ + provider: 'deepseek-official', model: 'deepseek-flash', + messages: [createUserMessage({ content: [{ type: 'image', attachment: imageRef }], source: { kind: 'user' } })], })) - await started.promise - await vi.advanceTimersByTimeAsync(50) - await pending - expect(fetchSpy).toHaveBeenCalledTimes(1) - expect(fetchSpy.mock.calls[0]?.[1]?.body).toEqual(expect.stringContaining('base64')) - fetchSpy.mockRestore() + try { + const first = request() + await started.promise + await vi.advanceTimersByTimeAsync(19_999) + expect(messages).not.toHaveBeenCalled() + await vi.advanceTimersByTimeAsync(1) + await first + await vi.advanceTimersByTimeAsync(3_600_000) + await drain(adapter.stream({ provider: 'deepseek-official', model: 'deepseek-flash', messages: [] })) + await request() + expect(upload).toHaveBeenCalledTimes(1) + expect(messages).toHaveBeenCalledTimes(3) + expect(messages.mock.calls[0]?.[1]?.body).toEqual(expect.stringContaining('base64')) + expect(messages.mock.calls[2]?.[1]?.body).toEqual(expect.stringContaining('base64')) + } finally { + messages.mockRestore() + } }) it('does not turn caller cancellation during file resolution into base64 fallback', async () => { From 92994f4d323be780ace96e8d301b03b004f0eedc Mon Sep 17 00:00:00 2001 From: creatixchu Date: Wed, 11 Nov 2026 21:16:06 +0800 Subject: [PATCH 2/6] Wait for both late upload responses in the backoff regression --- .../llm/llm-deepseek/tests/file-store.spec.ts | 27 ++++++++++--------- 1 file changed, 15 insertions(+), 12 deletions(-) diff --git a/packages/llm/llm-deepseek/tests/file-store.spec.ts b/packages/llm/llm-deepseek/tests/file-store.spec.ts index 9edf910b2b..08bf27dc7c 100644 --- a/packages/llm/llm-deepseek/tests/file-store.spec.ts +++ b/packages/llm/llm-deepseek/tests/file-store.spec.ts @@ -115,10 +115,18 @@ describe('DeepSeekFileStore', () => { it('counts overlapping timeouts once and keeps an abandoned response from clearing backoff', async () => { const dir = await mkdtemp(join(tmpdir(), 'dsh-files-overlap-')) roots.push(dir) - const now = NOW - const remote = uploadFetch(() => now) + const remote = uploadFetch() const fetch = vi.fn(remote.fetchImpl) - const store = new DeepSeekFileStore({ fetch, now: () => now, index: new DeepSeekUploadIndex(join(dir, 'index.json')) }) + const index = new DeepSeekUploadIndex(join(dir, 'index.json')) + const writes = Promise.withResolvers() + let written = 0 + const commit = index.commit.bind(index) + vi.spyOn(index, 'commit').mockImplementation(async (...args) => { + const result = await commit(...args) + if (++written === 2) writes.resolve(undefined) + return result + }) + const store = new DeepSeekFileStore({ fetch, now: () => NOW, index }) const stalled = async (variantId: string) => { const started = Promise.withResolvers() const response = Promise.withResolvers() @@ -127,22 +135,17 @@ describe('DeepSeekFileStore', () => { const controller = new AbortController() const pending = store.ensureUploaded(image, CONNECTION, POLICY, controller.signal) await started.promise - return { image, response, pending, controller } + return { response, pending, controller } } - const first = await stalled('first') - const second = await stalled('second') + const first = await stalled(`sha256:${'c'.repeat(64)}`) + const second = await stalled(`sha256:${'d'.repeat(64)}`) for (const upload of [first, second]) { const reason = new TimeoutReason(FILES_API_TIMEOUT, 20_000) upload.controller.abort(reason) await expect(upload.pending).rejects.toBe(reason) upload.response.resolve(await remote.fetchImpl(CONNECTION.baseURL, { method: 'POST' })) } - // A settled index write makes the late responses observable before checking the backoff. - await vi.waitFor(async () => { - const scope = deepSeekFileScope(CONNECTION.baseURL + '/v1', JSON.stringify(Object.entries(CONNECTION.headers))) - const index = new DeepSeekUploadIndex(join(dir, 'index.json')) - expect(await index.get(scope, second.image.variantId, now, 0)).toBeDefined() - }) + await writes.promise await expect(store.ensureUploaded(VERSION, CONNECTION, POLICY)).rejects.toMatchObject({ code: 'TIMEOUT' }) await expect(store.ensureUploaded(VERSION, CONNECTION, POLICY)).resolves.toMatchObject({ uploaded: true }) }) From 9fd05ac4f458a40b2e4a5d84fdbf45902fc91a5e Mon Sep 17 00:00:00 2001 From: creatixchu Date: Wed, 11 Nov 2026 21:17:45 +0800 Subject: [PATCH 3/6] Count a timed-out upload waiter while shared transport continues --- packages/llm/llm-deepseek/src/file-store.ts | 16 +++++---- .../llm/llm-deepseek/tests/file-store.spec.ts | 34 ++++++++++++++++--- 2 files changed, 39 insertions(+), 11 deletions(-) diff --git a/packages/llm/llm-deepseek/src/file-store.ts b/packages/llm/llm-deepseek/src/file-store.ts index 921f7b71a1..db434eee65 100644 --- a/packages/llm/llm-deepseek/src/file-store.ts +++ b/packages/llm/llm-deepseek/src/file-store.ts @@ -1,6 +1,5 @@ /** DeepSeek Files API upload reuse, invalidation, and quota recovery. @module dsh-llm-deepseek/file-store */ -import { addAbortListener } from 'node:events' import { timeoutOf } from '@deepseek-ai/dsh-timeout' import type { RequestImageAttachment } from '@deepseek-ai/dsh-attachment' import { LlmError } from '@deepseek-ai/dsh-llm' @@ -57,6 +56,7 @@ interface SharedUpload { promise: Promise settled: boolean waiters: number + onUploadTimeout?: () => void } /** The Files resource's parent URL identifies the upload namespace. */ @@ -100,6 +100,7 @@ function waitForUpload(operation: SharedUpload, signal: AbortSignal | undefined) return new Promise((resolve, reject) => { const abort = (): void => { const reason = abortReason(signal) + if (timeoutOf(signal, FILES_API_TIMEOUT)) operation.onUploadTimeout?.() release(reason) reject(reason) } @@ -211,7 +212,7 @@ export class DeepSeekFileStore { waiters: 0, promise: undefined as never, } - shared.promise = this.ensureUploadedOnce(version, connection, policy, scope, controller.signal).then((value) => { + shared.promise = this.ensureUploadedOnce(version, connection, policy, scope, shared).then((value) => { shared.settled = true return value }, (error: unknown) => { @@ -230,8 +231,9 @@ export class DeepSeekFileStore { connection: DeepSeekFileConnection, policy: DeepSeekFilePolicy, scope: DeepSeekUploadRecord['scope'], - signal: AbortSignal, + shared: SharedUpload, ): Promise { + const signal = shared.controller.signal const now = this.now() const marginMs = policy.refreshMarginSeconds * 1_000 const cached = await this.index.get(scope, version.variantId, now, marginMs) @@ -242,18 +244,18 @@ export class DeepSeekFileStore { signal.throwIfAborted() const previous = this.backoffs.get(scope) // Count overlapping uploads from one failure interval once, even if an aborted transport never settles. - using _listener = addAbortListener(signal, () => { - if (!timeoutOf(signal, FILES_API_TIMEOUT) || this.backoffs.get(scope) !== previous) return + shared.onUploadTimeout = () => { + if (this.backoffs.get(scope) !== previous) return const interval = previous ? previous.interval * 2n : 1n this.backoffs.set(scope, { interval, remaining: interval }) - }) + } const remote = await client.upload({ data: version.data, mediaType: version.mediaType, filename: filename(version), expiresAfterSeconds: policy.expiresAfterSeconds, signal, - }) + }).finally(() => { delete shared.onUploadTimeout }) if (remote.bytes !== version.data.byteLength) { throw new LlmError('DeepSeek Files API upload response does not match the submitted image.', 'INVALID_RESPONSE') } diff --git a/packages/llm/llm-deepseek/tests/file-store.spec.ts b/packages/llm/llm-deepseek/tests/file-store.spec.ts index 08bf27dc7c..d5ecaacf31 100644 --- a/packages/llm/llm-deepseek/tests/file-store.spec.ts +++ b/packages/llm/llm-deepseek/tests/file-store.spec.ts @@ -108,8 +108,32 @@ describe('DeepSeekFileStore', () => { await expect(store.ensureUploaded(VERSION, CONNECTION, POLICY)).resolves.toMatchObject({ uploaded: true }) const fresh = { ...VERSION, variantId: brandString(`sha256:${'d'.repeat(64)}`) } await expire(fresh) - await expect(store.ensureUploaded(fresh, CONNECTION, POLICY)).rejects.toMatchObject({ code: 'TIMEOUT' }) - await expect(store.ensureUploaded(fresh, CONNECTION, POLICY)).resolves.toMatchObject({ uploaded: true }) + // Two independent requests race for the last skip. The other must upload. + const competing = await Promise.allSettled([ + store.ensureUploaded(fresh, CONNECTION, POLICY), store.ensureUploaded(fresh, CONNECTION, POLICY), + ]) + expect(competing).toEqual(expect.arrayContaining([ + expect.objectContaining({ status: 'rejected', reason: expect.objectContaining({ code: 'TIMEOUT' }) }), + expect.objectContaining({ status: 'fulfilled', value: expect.objectContaining({ uploaded: true }) }), + ])) + }) + + it('does not count a Files deadline reached before the upload starts', async () => { + const dir = await mkdtemp(join(tmpdir(), 'dsh-files-index-timeout-')) + roots.push(dir) + const index = new DeepSeekUploadIndex(join(dir, 'index.json')) + const lookup = Promise.withResolvers() + vi.spyOn(index, 'get').mockReturnValueOnce(lookup.promise) + const remote = uploadFetch() + const store = new DeepSeekFileStore({ index, fetch: remote.fetchImpl, now: () => NOW }) + const controller = new AbortController() + const pending = store.ensureUploaded(VERSION, CONNECTION, POLICY, controller.signal) + const reason = new TimeoutReason(FILES_API_TIMEOUT, 20_000) + controller.abort(reason) + lookup.resolve(undefined) + await expect(pending).rejects.toBe(reason) + await expect(store.ensureUploaded(VERSION, CONNECTION, POLICY)).resolves.toMatchObject({ uploaded: true }) + expect(remote.uploads()).toBe(1) }) it('counts overlapping timeouts once and keeps an abandoned response from clearing backoff', async () => { @@ -252,7 +276,7 @@ describe('DeepSeekFileStore', () => { expect(remote.uploads()).toBe(1) }) - it('keeps a shared upload alive while another waiter remains', async () => { + it.each([new Error('cancel one upload waiter'), new TimeoutReason(FILES_API_TIMEOUT, 20_000)])('keeps a shared upload alive after one waiter exits with %s', async (reason) => { const dir = await mkdtemp(join(tmpdir(), 'dsh-file-store-')) roots.push(dir) const index = new DeepSeekUploadIndex(join(dir, 'index.json')) @@ -275,11 +299,13 @@ describe('DeepSeekFileStore', () => { await vi.waitFor(() => { expect(fetchImpl).toHaveBeenCalledTimes(1) }) - const reason = new Error('cancel one upload waiter') controller.abort(reason) await expect(cancelled).rejects.toBe(reason) expect(uploadSignal?.aborted).toBe(false) + if (reason instanceof TimeoutReason) { + await expect(store.ensureUploaded(VERSION, CONNECTION, POLICY)).rejects.toMatchObject({ code: 'TIMEOUT' }) + } complete?.(new Response(JSON.stringify({ id: 'file-api-shared', type: 'file', From bbd971ba80ddbfaf66b2b415e572a53c2071467c Mon Sep 17 00:00:00 2001 From: creatixchu Date: Fri, 13 Nov 2026 11:22:24 +0800 Subject: [PATCH 4/6] Reset Files backoff in completion order and count the first uncached image --- .../deepseek-files-timeout/guide.i18n.yaml | 16 +++++ .../deepseek-files-timeout/guide.md | 15 +++++ .../deepseek-files-timeout/guide.zh.md | 15 +++++ packages/llm/llm-deepseek/README.i18n.yaml | 20 +++--- packages/llm/llm-deepseek/README.md | 10 +-- packages/llm/llm-deepseek/README.zh.md | 10 +-- packages/llm/llm-deepseek/src/file-store.ts | 67 +++++++------------ .../llm/llm-deepseek/src/request-files.ts | 6 +- .../llm/llm-deepseek/tests/file-store.spec.ts | 45 ++++++++++--- packages/llm/llm-deepseek/tests/files.spec.ts | 2 +- .../llm/llm-deepseek/tests/runtime.spec.ts | 16 +++-- 11 files changed, 140 insertions(+), 82 deletions(-) create mode 100644 docs/upgrade-guide/v0.2.2-rc.2/deepseek-files-timeout/guide.i18n.yaml create mode 100644 docs/upgrade-guide/v0.2.2-rc.2/deepseek-files-timeout/guide.md create mode 100644 docs/upgrade-guide/v0.2.2-rc.2/deepseek-files-timeout/guide.zh.md diff --git a/docs/upgrade-guide/v0.2.2-rc.2/deepseek-files-timeout/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.2/deepseek-files-timeout/guide.i18n.yaml new file mode 100644 index 0000000000..dd3bc094b3 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.2/deepseek-files-timeout/guide.i18n.yaml @@ -0,0 +1,16 @@ +# Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.2-rc.2/deepseek-files-timeout/guide.md +/: + en: 1370bf136032cde9 + zh: 851fe36b91456e4b +/deepseek-image-upload-timeout: + en: 6105efb69d8b3524 + zh: baf5c376969d9493 +/deepseek-image-upload-timeout/change: + en: 2fcab2b99d847c24 + zh: e7b7a7104ebffa68 +/deepseek-image-upload-timeout/migration: + en: aef253836119c9e2 + zh: 6f569fb7cc8dd724 diff --git a/docs/upgrade-guide/v0.2.2-rc.2/deepseek-files-timeout/guide.md b/docs/upgrade-guide/v0.2.2-rc.2/deepseek-files-timeout/guide.md new file mode 100644 index 0000000000..2f754bfccf --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.2/deepseek-files-timeout/guide.md @@ -0,0 +1,15 @@ +--- +kind: upgrade-guide +description: "Keep a longer image upload deadline on slow DeepSeek gateways." +--- +# DeepSeek image upload timeout + +English | [中文](guide.zh.md) + +## Change + +The default `filesApiTimeoutMs` falls from 60,000 to 20,000 milliseconds. After an upload times out, the adapter sends inline images for the next request that needs an upload. Further timeouts double the number of requests skipped. A successful upload resets the count. + +## Migration + +If your gateway needs the previous deadline, set `filesApiTimeoutMs: 60000` on the DeepSeek provider in the active profile’s `cordis.patch.yml`. Existing explicit values take effect as configured. Run `dsh --profile --dump-config` and check the value on the provider entry. diff --git a/docs/upgrade-guide/v0.2.2-rc.2/deepseek-files-timeout/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.2/deepseek-files-timeout/guide.zh.md new file mode 100644 index 0000000000..ec73994df9 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.2/deepseek-files-timeout/guide.zh.md @@ -0,0 +1,15 @@ +--- +kind: upgrade-guide +description: "为上传较慢的 DeepSeek 网关保留较长的图片上传时限。" +--- +# DeepSeek 图片上传时限 + +[English](guide.md) | 中文 + +## 变更 + +`filesApiTimeoutMs` 的默认值从 60,000 毫秒缩短到 20,000 毫秒。上传超时后,下一次需要上传图片的请求直接使用内联图片。连续超时会使跳过的请求次数翻倍,上传成功后清零。 + +## 迁移 + +如果网关需要原先的时限,在当前配置的 `cordis.patch.yml` 中为 DeepSeek 提供方设置 `filesApiTimeoutMs: 60000`。已显式设置的值继续生效。运行 `dsh --profile --dump-config`,检查提供方条目中的值。 diff --git a/packages/llm/llm-deepseek/README.i18n.yaml b/packages/llm/llm-deepseek/README.i18n.yaml index 69528d9c25..efd29634d1 100644 --- a/packages/llm/llm-deepseek/README.i18n.yaml +++ b/packages/llm/llm-deepseek/README.i18n.yaml @@ -30,8 +30,8 @@ en: d3f232309f4963ef zh: 2e0ccd028de26f3e /deepseek-ai-dsh-llm-deepseek/use-this-package/streaming-with-thinking-and-images: - en: 2725460b95b490f2 - zh: aec8b5abec1d79aa + en: f880b79feebb9e63 + zh: 0dbbb2378e6f9af3 /deepseek-ai-dsh-llm-deepseek/use-this-package/dynamic-configuration: en: 49290fc5647136b4 zh: 96fa9ce0f9e83c13 @@ -63,14 +63,14 @@ en: 1dc50052999253c6 zh: 7abf968fc18bffcd /deepseek-ai-dsh-llm-deepseek/model-experience/deepseek-request/what-the-model-sees: - en: fd508ab91893e9dc - zh: c653e55a47353d08 + en: 183ffdbbfd511182 + zh: 0f15e0da9c4489c7 /deepseek-ai-dsh-llm-deepseek/model-experience/deepseek-request/token-effect: - en: 67f4bfa42cbee911 - zh: 5e9dc9bc07253686 + en: 840b31f506916dcb + zh: 6083c2bbbd85b4cb /deepseek-ai-dsh-llm-deepseek/model-experience/deepseek-request/kv-cache-effect: - en: 87ac92776176ee15 - zh: bb49edf3a68dda07 + en: d5829c148a2a7f36 + zh: faaa3db1411f3c7c /deepseek-ai-dsh-llm-deepseek/model-experience/deepseek-response: en: 957d6665495e5ca5 zh: 0aa72b2c2dc07167 @@ -84,8 +84,8 @@ en: ddfbea043596878d zh: 4fbf5864a684c053 /deepseek-ai-dsh-llm-deepseek/known-limitations-and-deferred-work: - en: 05fe57d81d8d8202 - zh: 61e85a6f610842dd + en: 232b09e9f33d9b1a + zh: bf838648f8ba4e62 /deepseek-ai-dsh-llm-deepseek/known-limitations-and-deferred-work/dev-note: en: 267aab8281b59242 zh: 491b454fe920a17e diff --git a/packages/llm/llm-deepseek/README.md b/packages/llm/llm-deepseek/README.md index 136752e0c1..3af6e623fd 100644 --- a/packages/llm/llm-deepseek/README.md +++ b/packages/llm/llm-deepseek/README.md @@ -99,7 +99,7 @@ An image-capable route chooses each durable reference's request target and resol The adapter normally uploads those exact request bytes through `/v1/files` and sends file-id references. Files requests and model requests containing file ids include `anthropic-beta: files-api-2025-04-14`. All requests reject redirects so credentials remain on the configured origin. A failed or timed-out file resolution rebuilds the whole model request with inline base64 under the inline budget; one request never mixes file ids and inline images. Caller cancellation stops the request. -After an upload times out, the next model request that needs a new upload uses inline images immediately. Each consecutive upload timeout doubles the number of such requests to skip (1, 2, 4, 8, …), regardless of elapsed time. The adapter counts each request once for its endpoint and credential. Text-only requests and requests served entirely by cached file ids do not count. A successful upload resets the count. +After an upload times out, the next model request that needs a new upload uses inline images immediately. Each consecutive upload timeout doubles the number of such requests to skip (1, 2, 4, 8, …), regardless of elapsed time. The adapter counts each request once for its endpoint and credential. Text-only requests and requests served entirely by cached file ids do not count. A successful upload resets the count for that endpoint and credential, including timeouts from concurrent uploads. A timeout after that success starts a new count. The adapter tries a recovered endpoint again once the skip count reaches zero. Cached ids are scoped by endpoint and credential, refreshed before expiry, invalidated from provider stale-file errors, and resolved through singleflight with waiter-local cancellation. Uploads request expiry through `expires_after[anchor]=created_at` and `expires_after[seconds]`. Messages file metadata omits remote expiry, so its local reuse deadline uses the original upload time plus `fileExpiresAfterSeconds`; this does not guarantee remote deletion. Quota failure deletes one configured batch of the oldest harness-owned files before one upload retry. @@ -175,15 +175,15 @@ Read these pages when the package-level contract is not enough. They move from t #### What the model sees -The selected DeepSeek model receives the harness system prompt, message history, tool schemas, stop sequences, and call config (`maxTokens`, `reasoningEffort`, `temperature`) without adapter-authored prompt prose. Provider-specific request-extension fields remain outside model input. The vision model normally receives retained user and tool-result images as Files API references beside attachment handles and request-preview dimensions. It also receives a normalized-object path when the current execution filesystem maps the attachment provider's host object; the descriptor marks this copy read-only and warns that normalization may have resized or re-encoded the upload. A Files resolution failure sends all retained images as inline base64 instead, and an over-budget older image keeps the access resolved for that request in its placeholder. Reasoning content from a prior assistant turn is passed back verbatim, whether or not that turn called a tool. Messages sends `{}` for historical tool arguments that are malformed JSON or are not objects. This argument fallback preserves call ids, tool names, and tool results; the original arguments stay in the Session log. Newly generated Messages tool arguments still require valid JSON objects. Messages omits `reasoning` and `tool-call` blocks inside user messages and tool results. This also permits replay of saved subagent notices containing assistant output; the original Session content remains intact. Empty user messages are skipped after conversion, while empty tool results retain their call ids and error flags. Other unsupported input blocks still fail with `UNSUPPORTED_CONTENT`. The adapter sends all-deferred tool lists unchanged and propagates provider rejection without adding a placeholder or activating real tools. The shared [tool-update projection](../llm/README.md#known-limitations-and-deferred-work) rebuilds an addition-only baseline when a tool is removed or tools are added to an empty set, while keeping later additions deferred. +The selected DeepSeek model receives the harness system prompt, message history, tool schemas, stop sequences, and call config (`maxTokens`, `reasoningEffort`, `temperature`) without adapter-authored prompt prose. Provider-specific request-extension fields remain outside model input. The vision model normally receives retained user and tool-result images as Files API references beside attachment handles and request-preview dimensions. It also receives a normalized-object path when the current execution filesystem maps the attachment provider's host object; the descriptor marks this copy read-only and warns that normalization may have resized or re-encoded the upload. If one image upload fails or is skipped, all retained images in that request use inline base64, including images with cached file ids. An older image omitted to meet the inline budget keeps its attachment access in a placeholder. Reasoning content from a prior assistant turn is passed back verbatim, whether or not that turn called a tool. Messages sends `{}` for historical tool arguments that are malformed JSON or are not objects. This argument fallback preserves call ids, tool names, and tool results; the original arguments stay in the Session log. Newly generated Messages tool arguments still require valid JSON objects. Messages omits `reasoning` and `tool-call` blocks inside user messages and tool results. This also permits replay of saved subagent notices containing assistant output; the original Session content remains intact. Empty user messages are skipped after conversion, while empty tool results retain their call ids and error flags. Other unsupported input blocks still fail with `UNSUPPORTED_CONTENT`. The adapter sends all-deferred tool lists unchanged and propagates provider rejection without adding a placeholder or activating real tools. The shared [tool-update projection](../llm/README.md#known-limitations-and-deferred-work) rebuilds an addition-only baseline when a tool is removed or tools are added to an empty set, while keeping later additions deferred. #### Token effect -Provider tokenization governs exact text and image-token input. The adapter declares per-route `imageRequestPricing`: it prices each occurrence selected by a logged image-offload decision as its placeholder text and each retained image at its projected dimensions with the published vision accounting (14px patch grid, 3:1 downsampling, 544×544 scale-up floor, 1024-token cap). This lets the token meter price image pressure before a request; reported usage remains authoritative. Reasoning passback carries every reasoned turn's chain of thought into later requests, while offloaded images stop costing visual tokens. A request whose retained occurrences exceed the file-mode or inline-fallback budget (`maxRequestFilesBytes`, `maxImagesPerRequest`, both quanta) at their exact request-version bytes fails with `IMAGE_OFFLOAD_REQUIRED` naming the additional oldest occurrences to offload, and `dsh-compaction-image-offload` records the selected occurrences in an `image/offload` event and retries. Cache-read usage is reported when available. Messages totals include uncached input, output, cache-read, and cache-write tokens. `imageRequestTarget(provider, model, image)` exposes the same request-image dimensions and byte target to screenshot consumers; adapters without image resizing preserve the normalized source. +Provider tokenization governs exact text and image-token input. The adapter declares per-route `imageRequestPricing`: it prices each occurrence selected by a logged image-offload decision as its placeholder text and each retained image at its projected dimensions with the published vision accounting (14px patch grid, 3:1 downsampling, 544×544 scale-up floor, 1024-token cap). This lets the token meter price image pressure before a request; reported usage remains authoritative. Reasoning passback carries every reasoned turn's chain of thought into later requests, while offloaded images stop costing visual tokens. Files requests allow 128 MiB of image bytes by default, while inline requests allow 20 MiB after base64 encoding. If the retained images exceed the applicable budget, the adapter raises `IMAGE_OFFLOAD_REQUIRED` with the number of oldest occurrences to omit. The [image offload plugin](../../compaction/compaction-image-offload/README.md) records them in `image/offload` and retries. Those occurrences remain placeholders after Files recovers. Cache-read usage is reported when available. Messages totals include uncached input, output, cache-read, and cache-write tokens. `imageRequestTarget(provider, model, image)` exposes the same request-image dimensions and byte target to screenshot consumers; adapters without image resizing preserve the normalized source. #### KV Cache effect -An unchanged assembled prefix is eligible for DeepSeek cache reuse, which this adapter reports in usage. Deterministic request-image bytes do not make the full prefix immutable: a changed execution-world path rewrites historical descriptor text, a refreshed upload can replace a `file_id`, and Files-to-base64 fallback changes the image representation. Any of these, or a model-route, prompt, schema, history, or image-budget change, may prevent reuse from the first affected token; reasoning passback appends on every reasoned turn. On a catalog entry declaring `systemPromptUpdate: in-history`, a system prompt change inside a continuing request series is appended after the cached history, so the prefix through that history stays reusable; a tool-schema change still prevents reuse from the first altered token. +An unchanged assembled prefix is eligible for DeepSeek cache reuse, which this adapter reports in usage. Deterministic request-image bytes do not make the full prefix immutable: a changed execution-world path rewrites historical descriptor text, a refreshed upload can replace a `file_id`, and switching to inline images during backoff or back to file ids after recovery changes the image representation. Any of these, or a model-route, prompt, schema, history, or image-budget change, may prevent reuse from the first affected token; reasoning passback appends on every reasoned turn. On a catalog entry declaring `systemPromptUpdate: in-history`, a system prompt change inside a continuing request series is appended after the cached history, so the prefix through that history stays reusable; a tool-schema change still prevents reuse from the first altered token. ### DeepSeek response @@ -211,7 +211,7 @@ These limits define where the adapter stops and future work begins. They are cur - **`tool_choice` is not mapped** — not part of the core vocabulary (shared with the pi-ai twin). - **Requests use raw `fetch`, not `@cordisjs/plugin-http`** — no shared proxy or interception configuration. - **Messages in-history system updates require a retained user or tool-result turn** — if all user input after an update is omitted and the preceding wire turn is assistant, serialization fails with `UNSUPPORTED_CONTENT` before the next assistant or at the end of the request. Text or an empty tool result can retain that turn. Moving the update to an earlier turn is not supported; the [input-history reference](README.md) records the ordering constraint. -- **Images are input-only durable attachments** — direct external URLs and assistant image output are not supported; DeepSeek input normally uses the Files API and uses inline base64 only for per-request recovery. +- **Images are input-only durable attachments** — direct external URLs and assistant image output are not supported; a gateway that recovers during backoff receives new uploads only after the remaining eligible requests have been skipped. - The default catalog advertises `deepseek-flash` and its text/image and in-history capabilities without probing gateway availability. Requests can fail with `INVALID_REQUEST` until the gateway enables the id. - Real API checks in [adapter.e2e.ts](tests/adapter.e2e.ts) and [runtime.e2e.ts](tests/runtime.e2e.ts) require `DEEPSEEK_API_KEY`. Set `DEEPSEEK_IN_HISTORY_MODEL` to a supported nonempty model id to run system-update checks: the adapter suite uses `high` effort, while the runtime suite compares cache reuse with thinking disabled and can be sensitive to instruction-following instability. The runtime image cases additionally require `DEEPSEEK_FLASH_E2E=1` or `DEEPSEEK_VISION_E2E=1`. diff --git a/packages/llm/llm-deepseek/README.zh.md b/packages/llm/llm-deepseek/README.zh.md index 03b290f9a1..6a24456782 100644 --- a/packages/llm/llm-deepseek/README.zh.md +++ b/packages/llm/llm-deepseek/README.zh.md @@ -99,7 +99,7 @@ Messages 和 Files 请求通过 `x-dsh-auth-token` 发送账号 token,不加 B 适配器通常通过 `/v1/files` 上传这些确切请求字节,并发送 file-id 引用。Files 请求与包含 file id 的模型请求均携带 `anthropic-beta: files-api-2025-04-14`。全部请求拒绝重定向,确保凭据仅发送到配置的源。文件解析失败或超时会按内联预算,用内联 base64 重建整份模型请求;一次请求绝不混用 file id 与内联图片。调用方取消会停止请求。 -上传超时后,下一次需要上传图片的模型请求直接使用内联图片。连续上传超时时,跳过的请求数依次为 1、2、4、8 次,之后继续翻倍,不受经过时间的影响。同一端点和凭据按请求计数,多张图片只算一次。纯文本请求和所有图片都命中文件 ID 缓存的请求不计数。实际上传成功后清零。 +上传超时后,下一次需要上传图片的模型请求直接使用内联图片。连续上传超时时,跳过的请求数依次为 1、2、4、8 次,之后继续翻倍,不受经过时间的影响。同一端点和凭据按请求计数,多张图片只算一次。纯文本请求和所有图片都命中文件 ID 缓存的请求不计数。同一端点和凭据下,实际上传成功会清除之前的超时计数,包括并发上传的超时。之后再超时,从跳过一次重新开始。即使网关已经恢复,也要等跳过规定次数后才会试传。 缓存 id 按端点与凭据限定作用域,在到期前刷新,根据提供方的陈旧文件错误失效,并通过带等待方局部取消的 singleflight 解析。上传通过 `expires_after[anchor]=created_at` 与 `expires_after[seconds]` 请求过期。Messages 文件元数据不含远端过期时间,因此本地复用期限使用原始上传时间加 `fileExpiresAfterSeconds`;这不保证远端文件删除。配额失败会先删除一批配置数量的最旧 harness 文件,再重试一次上传。 @@ -175,15 +175,15 @@ Files 模式通过 `maxRequestFilesBytes` 与 `maxImagesPerRequest` 限制保留 #### 模型看到什么 -所选 DeepSeek 模型会收到 harness 系统提示词、消息历史、工具 schema、停止序列与调用配置(`maxTokens`、`reasoningEffort`、`temperature`),不包含适配器撰写的提示词散文。提供方专用请求扩展字段留在模型输入之外。视觉模型通常接收 Files API 引用形式的用户与工具结果图片,其旁带附件句柄和请求预览尺寸。当前执行文件系统可以映射附件提供方的宿主对象时,它还会收到规范化对象路径;描述符会把该副本标记为只读,并警告规范化可能缩放或重新编码上传内容。Files 解析失败时,全部保留图片改用内联 base64;超出预算的较旧图片则在占位文本中保留当前请求已解析的访问方式。此前 assistant 轮次的推理内容会原样传回,无论该轮次是否调用了工具。 对于非法 JSON 或非对象的历史工具参数,Messages 发送 `{}`。此参数兜底保留调用 ID、工具名和工具结果;原始参数仍保留在 Session 日志中。新生成的 Messages 工具参数仍须是有效 JSON 对象。 Messages 会省略用户消息和工具结果中的 `reasoning` 与 `tool-call` 块。这也允许回放包含助手输出的已保存子 Agent 通知;原始 Session 内容保持完整。转换后的空用户消息会被跳过,空工具结果则保留调用 id 和错误标记。其他不支持的输入块仍会以 `UNSUPPORTED_CONTENT` 失败。 适配器原样发送全延迟工具列表,并传递提供方的拒绝错误,不添加占位工具或激活真实工具。共享的[工具更新投影](../llm/README.zh.md#known-limitations-and-deferred-work)在移除任何工具或向空工具集添加工具时重建 addition-only 基线,后续添加仍保持延迟加载。 +所选 DeepSeek 模型会收到 harness 系统提示词、消息历史、工具 schema、停止序列与调用配置(`maxTokens`、`reasoningEffort`、`temperature`),不包含适配器撰写的提示词散文。提供方专用请求扩展字段留在模型输入之外。视觉模型通常接收 Files API 引用形式的用户与工具结果图片,其旁带附件句柄和请求预览尺寸。当前执行文件系统可以映射附件提供方的宿主对象时,它还会收到规范化对象路径;描述符会把该副本标记为只读,并警告规范化可能缩放或重新编码上传内容。只要一张图片上传失败或被跳过,本次请求的全部保留图片都改用内联 base64,包括已有文件 ID 的图片。因内联预算而省略的旧图片会在占位文本中保留附件访问方式。此前 assistant 轮次的推理内容会原样传回,无论该轮次是否调用了工具。 对于非法 JSON 或非对象的历史工具参数,Messages 发送 `{}`。此参数兜底保留调用 ID、工具名和工具结果;原始参数仍保留在 Session 日志中。新生成的 Messages 工具参数仍须是有效 JSON 对象。 Messages 会省略用户消息和工具结果中的 `reasoning` 与 `tool-call` 块。这也允许回放包含助手输出的已保存子 Agent 通知;原始 Session 内容保持完整。转换后的空用户消息会被跳过,空工具结果则保留调用 id 和错误标记。其他不支持的输入块仍会以 `UNSUPPORTED_CONTENT` 失败。 适配器原样发送全延迟工具列表,并传递提供方的拒绝错误,不添加占位工具或激活真实工具。共享的[工具更新投影](../llm/README.zh.md#known-limitations-and-deferred-work)在移除任何工具或向空工具集添加工具时重建 addition-only 基线,后续添加仍保持延迟加载。 #### Token 影响 -提供方分词决定精确的文本与图片 token 输入。适配器声明按路由的 `imageRequestPricing`:把日志中的图片省略决策选中的每个出现位置按其占位文本计价,并按投影后的尺寸使用公开的视觉计量规则(14 px patch 网格、3:1 降采样、544×544 放大下限、单图 1024 token 上限)为每张保留图片计价。这使 token 计量服务可以在请求发出前为图片压力定价;上报的 usage 仍是权威值。推理回传会把每个推理轮次的思维链带进后续请求,而已省略的图片不再消耗视觉 token。保留的出现位置按精确请求版本字节超过 file 模式或内联回退预算(`maxRequestFilesBytes`、`maxImagesPerRequest` 与两个量子)的请求,以 `IMAGE_OFFLOAD_REQUIRED` 失败并说明还需省略多少最老的出现位置,由 `dsh-compaction-image-offload` 用 `image/offload` 事件记录所选位置并重试。可用时报告缓存读取用量。Messages 的 token 总数包含未缓存输入、输出、缓存读取与缓存写入 token。 `imageRequestTarget(provider, model, image)` 向截图调用方提供与模型请求一致的图片尺寸和字节目标;不缩放图片的适配器保留归一化后的原图。 +提供方分词决定精确的文本与图片 token 输入。适配器声明按路由的 `imageRequestPricing`:把日志中的图片省略决策选中的每个出现位置按其占位文本计价,并按投影后的尺寸使用公开的视觉计量规则(14 px patch 网格、3:1 降采样、544×544 放大下限、单图 1024 token 上限)为每张保留图片计价。这使 token 计量服务可以在请求发出前为图片压力定价;上报的 usage 仍是权威值。推理回传会把每个推理轮次的思维链带进后续请求,而已省略的图片不再消耗视觉 token。Files 请求默认允许 128 MiB 图片数据,内联请求默认允许 base64 编码后的图片占用 20 MiB。保留图片超过当前预算时,适配器以 `IMAGE_OFFLOAD_REQUIRED` 报告需省略多少个最早出现的图片。[图片省略插件](../../compaction/compaction-image-offload/README.zh.md) 通过 `image/offload` 记录这些位置并重试。Files 恢复后,这些位置仍然只显示占位文本。可用时报告缓存读取用量。Messages 的 token 总数包含未缓存输入、输出、缓存读取与缓存写入 token。 `imageRequestTarget(provider, model, image)` 向截图调用方提供与模型请求一致的图片尺寸和字节目标;不缩放图片的适配器保留归一化后的原图。 #### KV Cache 影响 -未改变的已组装前缀有资格获得 DeepSeek 缓存复用,本适配器会在用量中报告。确定性的请求图片字节并不意味着完整前缀固定不变:执行世界路径变化会改写历史描述符文本,刷新上传会替换 `file_id`,Files 到 base64 的回退也会改变图片表示。这些变化以及模型路由、提示词、schema、历史或图片预算变化,都可能从首个受影响 token 起阻止复用;推理回传在每个推理轮次上追加内容。在声明了 `systemPromptUpdate: in-history` 的目录条目上,同一请求序列延续期间的系统提示词变化会追加到已缓存历史之后,因此直到该历史末尾的前缀仍可复用;工具 schema 变化仍会从第一个改变的 token 起阻止复用。 +未改变的已组装前缀有资格获得 DeepSeek 缓存复用,本适配器会在用量中报告。确定性的请求图片字节并不意味着完整前缀固定不变:执行世界路径变化会改写历史描述符文本,刷新上传会替换 `file_id`,退避期间切换到内联图片,以及恢复后切回文件 ID,都会改变历史中的图片表示。这些变化以及模型路由、提示词、schema、历史或图片预算变化,都可能从首个受影响 token 起阻止复用;推理回传在每个推理轮次上追加内容。在声明了 `systemPromptUpdate: in-history` 的目录条目上,同一请求序列延续期间的系统提示词变化会追加到已缓存历史之后,因此直到该历史末尾的前缀仍可复用;工具 schema 变化仍会从第一个改变的 token 起阻止复用。 ### DeepSeek 响应 @@ -211,7 +211,7 @@ loop 保留的响应块会追加到下一个请求,并保留其更早的可复 - **不映射 `tool_choice`**——不属于核心词汇(与 pi-ai 孪生共享)。 - **请求使用原始 `fetch`,而非 `@cordisjs/plugin-http`**——没有共享代理或拦截配置。 - **Messages 历史内 system 更新需要保留用户或工具结果轮次**——若更新后的全部用户输入都被省略,且前一个协议轮次是 assistant,序列化会在下一个 assistant 之前或请求结束处以 `UNSUPPORTED_CONTENT` 失败。文本或空工具结果可以保留该轮次。不支持将更新移到更早的轮次;[输入历史参考](README.zh.md)记录了排序约束。 -- **图片是仅用于输入的持久附件**——不支持直接外部 URL 与 assistant 图片输出;DeepSeek 输入通常使用 Files API,仅在单次请求恢复时使用内联 base64。 +- **图片仅作为持久附件输入**。适配器不支持直接外部 URL 和 assistant 图片输出。网关在退避期间恢复后,要等跳过规定次数的请求才会收到新上传。 - 默认目录公布 `deepseek-flash` 及其文本、图片和历史内更新能力,不探测网关可用性。网关开放该 ID 前,请求可能以 `INVALID_REQUEST` 失败。 - [adapter.e2e.ts](tests/adapter.e2e.ts) 与 [runtime.e2e.ts](tests/runtime.e2e.ts) 中的真实 API 检查需要 `DEEPSEEK_API_KEY`。将 `DEEPSEEK_IN_HISTORY_MODEL` 设为受支持的非空模型 ID 可运行 system 更新检查:适配器套件使用 `high` 思考强度,运行时套件则在关闭思考时比较缓存复用,可能受到指令遵循不稳定的影响。运行时图片用例还需要 `DEEPSEEK_FLASH_E2E=1` 或 `DEEPSEEK_VISION_E2E=1`。 diff --git a/packages/llm/llm-deepseek/src/file-store.ts b/packages/llm/llm-deepseek/src/file-store.ts index db434eee65..68468a50a6 100644 --- a/packages/llm/llm-deepseek/src/file-store.ts +++ b/packages/llm/llm-deepseek/src/file-store.ts @@ -1,6 +1,6 @@ /** DeepSeek Files API upload reuse, invalidation, and quota recovery. @module dsh-llm-deepseek/file-store */ -import { timeoutOf } from '@deepseek-ai/dsh-timeout' +import { timeoutOf, type TimeoutReason } from '@deepseek-ai/dsh-timeout' import type { RequestImageAttachment } from '@deepseek-ai/dsh-attachment' import { LlmError } from '@deepseek-ai/dsh-llm' import { DeepSeekFilesClient, isFilesQuotaError } from './files-api.ts' @@ -17,14 +17,10 @@ export const FILES_API_TIMEOUT = 'DEEPSEEK_FILES_API_TIMEOUT' interface UploadBackoff { interval: bigint + reason: TimeoutReason remaining: bigint } -/** Shared by all image resolutions of one model request, including stale-id recovery. */ -export interface FileUploadRequest { - skipped?: boolean -} - /** Resolved file-store policy from the plugin configuration. */ export interface DeepSeekFilePolicy { expiresAfterSeconds: number @@ -56,7 +52,7 @@ interface SharedUpload { promise: Promise settled: boolean waiters: number - onUploadTimeout?: () => void + onUploadTimeout?: (reason: TimeoutReason) => void } /** The Files resource's parent URL identifies the upload namespace. */ @@ -100,7 +96,8 @@ function waitForUpload(operation: SharedUpload, signal: AbortSignal | undefined) return new Promise((resolve, reject) => { const abort = (): void => { const reason = abortReason(signal) - if (timeoutOf(signal, FILES_API_TIMEOUT)) operation.onUploadTimeout?.() + const timeout = timeoutOf(signal, FILES_API_TIMEOUT) + if (timeout) operation.onUploadTimeout?.(timeout) release(reason) reject(reason) } @@ -163,41 +160,31 @@ export class DeepSeekFileStore { * @param connection - endpoint and API-key snapshot. * @param policy - expiry and quota-recovery policy. * @param signal - cancellation of this wait; shared transport stops when no waiter remains. - * @param request - one model request's skip decision, shared across its images. Omit for an independent resolution. - * @returns a reusable file id and whether this call published a new upload. A skipped upload rejects with TIMEOUT. + * @returns a reusable file id and whether this call published a new upload. + * @throws During backoff a cache miss consumes one skip and rejects with FILES_API_SKIPPED. */ - ensureUploaded( + async ensureUploaded( version: RequestImageAttachment, connection: DeepSeekFileConnection, policy: DeepSeekFilePolicy, signal?: AbortSignal, - request: FileUploadRequest = {}, ): Promise { signal?.throwIfAborted() if (version.bytes > MAX_IMAGE_BYTES) { - return Promise.reject(new LlmError('DeepSeek image exceeds the 32 MiB per-image limit.', 'INVALID_REQUEST')) + throw new LlmError('DeepSeek image exceeds the 32 MiB per-image limit.', 'INVALID_REQUEST') } const scope = fileScope(connection) - if (request.skipped || this.backoffs.get(scope)?.remaining) { - return this.index.get(scope, version.variantId, this.now(), policy.refreshMarginSeconds * 1_000, signal).then((cached) => { - signal?.throwIfAborted() - if (cached) return { record: cached, uploaded: false } - const backoff = this.backoffs.get(scope) - if (!request.skipped && backoff?.remaining) { - backoff.remaining-- - request.skipped = true - } - if (request.skipped) throw new LlmError('DeepSeek Files API upload skipped after a timeout.', 'TIMEOUT') - return this.sharedUpload(version, connection, policy, scope, signal) - }) + const marginMs = policy.refreshMarginSeconds * 1_000 + const cached = await this.index.get(scope, version.variantId, this.now(), marginMs, signal) + signal?.throwIfAborted() + if (cached) return { record: cached, uploaded: false } + const backoff = this.backoffs.get(scope) + if (backoff && backoff.remaining > 0n) { + backoff.remaining-- + throw LlmError.fromFailure({ + message: 'DeepSeek Files API upload skipped after a timeout.', code: 'FILES_API_SKIPPED', + }, { cause: backoff.reason }) } - return this.sharedUpload(version, connection, policy, scope, signal) - } - - private sharedUpload( - version: RequestImageAttachment, connection: DeepSeekFileConnection, policy: DeepSeekFilePolicy, - scope: DeepSeekUploadRecord['scope'], signal?: AbortSignal, - ): Promise { const key = `${scope}\0${version.variantId}` let active = this.inflight.get(key) if (active?.controller.signal.aborted) { @@ -212,7 +199,7 @@ export class DeepSeekFileStore { waiters: 0, promise: undefined as never, } - shared.promise = this.ensureUploadedOnce(version, connection, policy, scope, shared).then((value) => { + shared.promise = this.uploadOnce(version, connection, policy, scope, shared).then((value) => { shared.settled = true return value }, (error: unknown) => { @@ -226,7 +213,7 @@ export class DeepSeekFileStore { return waitForUpload(shared, signal) } - private async ensureUploadedOnce( + private async uploadOnce( version: RequestImageAttachment, connection: DeepSeekFileConnection, policy: DeepSeekFilePolicy, @@ -234,20 +221,18 @@ export class DeepSeekFileStore { shared: SharedUpload, ): Promise { const signal = shared.controller.signal - const now = this.now() const marginMs = policy.refreshMarginSeconds * 1_000 - const cached = await this.index.get(scope, version.variantId, now, marginMs) - if (cached !== undefined) return { record: cached, uploaded: false } const client = this.client(connection) const upload = async (): Promise => { signal.throwIfAborted() const previous = this.backoffs.get(scope) // Count overlapping uploads from one failure interval once, even if an aborted transport never settles. - shared.onUploadTimeout = () => { - if (this.backoffs.get(scope) !== previous) return - const interval = previous ? previous.interval * 2n : 1n - this.backoffs.set(scope, { interval, remaining: interval }) + shared.onUploadTimeout = (reason) => { + const current = this.backoffs.get(scope) + if (current && current !== previous) return + const interval = current ? current.interval * 2n : 1n + this.backoffs.set(scope, { interval, remaining: interval, reason }) } const remote = await client.upload({ data: version.data, diff --git a/packages/llm/llm-deepseek/src/request-files.ts b/packages/llm/llm-deepseek/src/request-files.ts index 21e325f828..dcebd508d4 100644 --- a/packages/llm/llm-deepseek/src/request-files.ts +++ b/packages/llm/llm-deepseek/src/request-files.ts @@ -1,9 +1,8 @@ /** Shared Files resolution, bounded stale-id recovery, and normalized-image diagnostics. */ import type { RequestImageAttachment } from '@deepseek-ai/dsh-attachment' -import { FILES_API_TIMEOUT } from './file-store.ts' import { deadline } from '@deepseek-ai/dsh-timeout' -import type { DeepSeekFileStore, DeepSeekFileConnection, DeepSeekFilePolicy, FileUploadRequest } from './file-store.ts' +import { FILES_API_TIMEOUT, type DeepSeekFileStore, type DeepSeekFileConnection, type DeepSeekFilePolicy } from './file-store.ts' import type { DeepSeekFileId } from './file-id.ts' /** Position of an image occurrence in the request's conversation messages. */ @@ -95,7 +94,6 @@ function normalizedImageDiagnostic( export class RequestFiles { private used: UsedRequestFile[] = [] private retried = false - private readonly uploadRequest: FileUploadRequest = {} constructor( private readonly files: DeepSeekFileStore, @@ -119,7 +117,7 @@ export class RequestFiles { using limit = deadline(this.signal, this.timeoutMs, FILES_API_TIMEOUT) let resolved: Awaited> try { - resolved = await this.files.ensureUploaded(version, this.connection, this.policy, limit.signal, this.uploadRequest) + resolved = await this.files.ensureUploaded(version, this.connection, this.policy, limit.signal) } catch (error) { if (this.signal.aborted) throw error throw new FileResolutionFailure(error) diff --git a/packages/llm/llm-deepseek/tests/file-store.spec.ts b/packages/llm/llm-deepseek/tests/file-store.spec.ts index d5ecaacf31..7cf8bd9d06 100644 --- a/packages/llm/llm-deepseek/tests/file-store.spec.ts +++ b/packages/llm/llm-deepseek/tests/file-store.spec.ts @@ -95,11 +95,8 @@ describe('DeepSeekFileStore', () => { const calls = fetch.mock.calls.length for (let i = 0; i < count; i++) { await expect(store.ensureUploaded(cached, CONNECTION, POLICY)).resolves.toMatchObject({ uploaded: false }) - // The two cache misses are images from one model request. - const request = {} - const missing = [VERSION, { ...VERSION, variantId: brandString(`sha256:${'e'.repeat(64)}`) }] - await Promise.all(missing.map(image => expect(store.ensureUploaded(image, CONNECTION, POLICY, undefined, request)) - .rejects.toMatchObject({ code: 'TIMEOUT' }))) + await expect(store.ensureUploaded(VERSION, CONNECTION, POLICY)) + .rejects.toMatchObject({ code: 'FILES_API_SKIPPED', cause: { code: FILES_API_TIMEOUT } }) } expect(fetch).toHaveBeenCalledTimes(calls) await expect(store.ensureUploaded(VERSION, { ...CONNECTION, headers: { 'x-api-key': 'other' } }, POLICY)).resolves.toBeDefined() @@ -108,14 +105,39 @@ describe('DeepSeekFileStore', () => { await expect(store.ensureUploaded(VERSION, CONNECTION, POLICY)).resolves.toMatchObject({ uploaded: true }) const fresh = { ...VERSION, variantId: brandString(`sha256:${'d'.repeat(64)}`) } await expire(fresh) + await expect(store.ensureUploaded(fresh, CONNECTION, POLICY)).rejects.toMatchObject({ code: 'FILES_API_SKIPPED' }) + // The failed probe starts while the old interval still exists; another image succeeds before it times out. + const started = Promise.withResolvers() + fetch.mockImplementationOnce((_url, init) => new Promise((_resolve, reject) => { + started.resolve(undefined) + init!.signal!.addEventListener('abort', () => { reject(new Error('upload aborted')) }, { once: true }) + })) + const controller = new AbortController() + const probe = store.ensureUploaded(fresh, CONNECTION, POLICY, controller.signal) + await started.promise + const other = { ...VERSION, variantId: brandString(`sha256:${'f'.repeat(64)}`) } + await expect(store.ensureUploaded(other, CONNECTION, POLICY)).resolves.toMatchObject({ uploaded: true }) + const reason = new TimeoutReason(FILES_API_TIMEOUT, 20_000) + controller.abort(reason) + await expect(probe).rejects.toBe(reason) // Two independent requests race for the last skip. The other must upload. const competing = await Promise.allSettled([ store.ensureUploaded(fresh, CONNECTION, POLICY), store.ensureUploaded(fresh, CONNECTION, POLICY), ]) - expect(competing).toEqual(expect.arrayContaining([ - expect.objectContaining({ status: 'rejected', reason: expect.objectContaining({ code: 'TIMEOUT' }) }), - expect.objectContaining({ status: 'fulfilled', value: expect.objectContaining({ uploaded: true }) }), - ])) + expect(competing.find(result => result.status === 'rejected')).toMatchObject({ reason: { code: 'FILES_API_SKIPPED' } }) + expect(competing.find(result => result.status === 'fulfilled')).toMatchObject({ value: { uploaded: true } }) + }) + + it.each([ + [503, '{}', 'SERVER'], [200, '{}', 'INVALID_RESPONSE'], + ] as const)('retries the next upload after HTTP %i fails with %s', async (status, body, code) => { + const dir = await mkdtemp(join(tmpdir(), 'dsh-files-http-failure-')) + roots.push(dir) + const fetch = vi.fn(uploadFetch().fetchImpl).mockResolvedValueOnce(new Response(body, { status })) + const store = new DeepSeekFileStore({ fetch, now: () => NOW, index: new DeepSeekUploadIndex(join(dir, 'index.json')) }) + await expect(store.ensureUploaded(VERSION, CONNECTION, POLICY)).rejects.toMatchObject({ code }) + await expect(store.ensureUploaded(VERSION, CONNECTION, POLICY)).resolves.toMatchObject({ uploaded: true }) + expect(fetch).toHaveBeenCalledTimes(2) }) it('does not count a Files deadline reached before the upload starts', async () => { @@ -170,7 +192,7 @@ describe('DeepSeekFileStore', () => { upload.response.resolve(await remote.fetchImpl(CONNECTION.baseURL, { method: 'POST' })) } await writes.promise - await expect(store.ensureUploaded(VERSION, CONNECTION, POLICY)).rejects.toMatchObject({ code: 'TIMEOUT' }) + await expect(store.ensureUploaded(VERSION, CONNECTION, POLICY)).rejects.toMatchObject({ code: 'FILES_API_SKIPPED' }) await expect(store.ensureUploaded(VERSION, CONNECTION, POLICY)).resolves.toMatchObject({ uploaded: true }) }) @@ -291,6 +313,7 @@ describe('DeepSeekFileStore', () => { }, { once: true }) }) }) as typeof fetch + vi.spyOn(index, 'get').mockResolvedValue(undefined) const store = new DeepSeekFileStore({ index, now: () => NOW, fetch: fetchImpl }) const controller = new AbortController() @@ -304,7 +327,7 @@ describe('DeepSeekFileStore', () => { await expect(cancelled).rejects.toBe(reason) expect(uploadSignal?.aborted).toBe(false) if (reason instanceof TimeoutReason) { - await expect(store.ensureUploaded(VERSION, CONNECTION, POLICY)).rejects.toMatchObject({ code: 'TIMEOUT' }) + await expect(store.ensureUploaded(VERSION, CONNECTION, POLICY)).rejects.toMatchObject({ code: 'FILES_API_SKIPPED' }) } complete?.(new Response(JSON.stringify({ id: 'file-api-shared', diff --git a/packages/llm/llm-deepseek/tests/files.spec.ts b/packages/llm/llm-deepseek/tests/files.spec.ts index e358fed0bc..de09e7b1c2 100644 --- a/packages/llm/llm-deepseek/tests/files.spec.ts +++ b/packages/llm/llm-deepseek/tests/files.spec.ts @@ -57,7 +57,7 @@ describe('Messages Files requests', () => { createToolResultMessage({ callId, isError: false, content: [{ type: 'image', attachment: ref }, { type: 'image', attachment: ref }] })] await chunks(h.adapter.stream(options({ model, messages }))) expect(h.readImageRequest).toHaveBeenCalledTimes(1) - expect(h.ensureUploaded).toHaveBeenCalledWith(expect.anything(), { baseURL: 'https://gateway.example/custom', headers: { 'x-api-key': 'test-key' } }, expect.anything(), expect.any(AbortSignal), expect.anything()) + expect(h.ensureUploaded).toHaveBeenCalledWith(expect.anything(), { baseURL: 'https://gateway.example/custom', headers: { 'x-api-key': 'test-key' } }, expect.anything(), expect.any(AbortSignal)) const [url, init] = fetchImpl.mock.calls[0]! expect(url).toBe('https://gateway.example/custom/v1/messages') expect(new Headers(init?.headers).get('anthropic-beta')).toBe('files-api-2025-04-14') diff --git a/packages/llm/llm-deepseek/tests/runtime.spec.ts b/packages/llm/llm-deepseek/tests/runtime.spec.ts index c13180805d..08782cb564 100644 --- a/packages/llm/llm-deepseek/tests/runtime.spec.ts +++ b/packages/llm/llm-deepseek/tests/runtime.spec.ts @@ -539,7 +539,9 @@ describe('DeepSeekAdapter against a mock server', () => { it('sends successive image requests inline after one 20-second upload timeout', async () => { vi.useFakeTimers() const started = Promise.withResolvers() - const upload = vi.fn((_url, init) => new Promise((_resolve, reject) => { + const upload = vi.fn(async () => new Response(JSON.stringify({ + id: 'file-probe', type: 'file', size_bytes: 3, created_at: new Date().toISOString(), filename: 'probe.png', mime_type: 'image/png', + }))).mockImplementationOnce((_url, init) => new Promise((_resolve, reject) => { started.resolve(undefined) init!.signal!.addEventListener('abort', () => { reject(new Error('upload aborted')) }, { once: true }) })) @@ -547,9 +549,10 @@ describe('DeepSeekAdapter against a mock server', () => { const attachments = attachmentStoreOf(ref => Promise.resolve(requestImage(ref))).store const messages = vi.spyOn(globalThis, 'fetch').mockImplementation(async () => successfulSseResponse()) const adapter = adapterOf({ baseURL: 'https://deepseek.invalid' }, attachments, files) - const request = () => drain(adapter.stream({ + const second = { ...imageRef, attachmentId: brandString(`sha256:${'c'.repeat(64)}`) } + const request = (images = [imageRef]) => drain(adapter.stream({ provider: 'deepseek-official', model: 'deepseek-flash', - messages: [createUserMessage({ content: [{ type: 'image', attachment: imageRef }], source: { kind: 'user' } })], + messages: [createUserMessage({ content: images.map(attachment => ({ type: 'image', attachment })), source: { kind: 'user' } })], })) try { @@ -561,11 +564,14 @@ describe('DeepSeekAdapter against a mock server', () => { await first await vi.advanceTimersByTimeAsync(3_600_000) await drain(adapter.stream({ provider: 'deepseek-official', model: 'deepseek-flash', messages: [] })) - await request() + await request([imageRef, second]) expect(upload).toHaveBeenCalledTimes(1) expect(messages).toHaveBeenCalledTimes(3) expect(messages.mock.calls[0]?.[1]?.body).toEqual(expect.stringContaining('base64')) - expect(messages.mock.calls[2]?.[1]?.body).toEqual(expect.stringContaining('base64')) + expect(String(messages.mock.calls[2]?.[1]?.body).match(/"type":"base64"/gu)).toHaveLength(2) + await request() + expect(upload).toHaveBeenCalledTimes(2) + expect(messages.mock.calls[3]?.[1]?.body).toEqual(expect.stringContaining('file-probe')) } finally { messages.mockRestore() } From 5f5665ceaddbaa072114d584639547b2100b0aa0 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Fri, 13 Nov 2026 11:23:09 +0800 Subject: [PATCH 5/6] Preserve normalized upload-index failures on cache reads --- packages/llm/llm-deepseek/src/file-store.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/packages/llm/llm-deepseek/src/file-store.ts b/packages/llm/llm-deepseek/src/file-store.ts index 68468a50a6..e21cab2637 100644 --- a/packages/llm/llm-deepseek/src/file-store.ts +++ b/packages/llm/llm-deepseek/src/file-store.ts @@ -176,6 +176,7 @@ export class DeepSeekFileStore { const scope = fileScope(connection) const marginMs = policy.refreshMarginSeconds * 1_000 const cached = await this.index.get(scope, version.variantId, this.now(), marginMs, signal) + .catch((error: unknown) => { throw uploadFailure(error) }) signal?.throwIfAborted() if (cached) return { record: cached, uploaded: false } const backoff = this.backoffs.get(scope) From 6c034edcead114c46678d47d5d2c65a89d222b97 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Fri, 13 Nov 2026 11:24:03 +0800 Subject: [PATCH 6/6] Hold cancelled transport open across the next lookup in the recovery test --- .../llm/llm-deepseek/tests/file-store.spec.ts | 20 +++++++++---------- .../llm/llm-deepseek/tests/runtime.spec.ts | 3 ++- 2 files changed, 11 insertions(+), 12 deletions(-) diff --git a/packages/llm/llm-deepseek/tests/file-store.spec.ts b/packages/llm/llm-deepseek/tests/file-store.spec.ts index 7cf8bd9d06..72a2958bf3 100644 --- a/packages/llm/llm-deepseek/tests/file-store.spec.ts +++ b/packages/llm/llm-deepseek/tests/file-store.spec.ts @@ -398,18 +398,11 @@ describe('DeepSeekFileStore', () => { it('starts a fresh upload while the cancelled transport is settling', async () => { const dir = await mkdtemp(join(tmpdir(), 'dsh-file-store-')) roots.push(dir) + const firstResponse = Promise.withResolvers() let requests = 0 - const fetchImpl = vi.fn((_url: string | URL | Request, init?: RequestInit) => { + const fetchImpl = vi.fn(() => { requests += 1 - if (requests === 1) { - return new Promise((_resolve, reject) => { - init?.signal?.addEventListener('abort', () => { - queueMicrotask(() => { - reject(new Error('upload aborted', { cause: init.signal?.reason })) - }) - }, { once: true }) - }) - } + if (requests === 1) return firstResponse.promise return Promise.resolve(new Response(JSON.stringify({ id: 'file-api-retry', type: 'file', size_bytes: 3, created_at: new Date(NOW).toISOString(), filename: 'dsh-retry.png', mime_type: 'image/png', @@ -429,7 +422,12 @@ describe('DeepSeekFileStore', () => { const retried = store.ensureUploaded(VERSION, CONNECTION, POLICY) await expect(cancelled).rejects.toThrow('cancel first') - await expect(retried).resolves.toMatchObject({ record: { fileId: 'file-api-retry' } }) + try { + await expect(retried).resolves.toMatchObject({ record: { fileId: 'file-api-retry' } }) + expect(requests).toBe(2) + } finally { + firstResponse.reject(new Error('cancelled transport closed')) + } }) it('rejects a request version above the per-image limit before transport', async () => { diff --git a/packages/llm/llm-deepseek/tests/runtime.spec.ts b/packages/llm/llm-deepseek/tests/runtime.spec.ts index 08782cb564..07432e6b14 100644 --- a/packages/llm/llm-deepseek/tests/runtime.spec.ts +++ b/packages/llm/llm-deepseek/tests/runtime.spec.ts @@ -568,7 +568,8 @@ describe('DeepSeekAdapter against a mock server', () => { expect(upload).toHaveBeenCalledTimes(1) expect(messages).toHaveBeenCalledTimes(3) expect(messages.mock.calls[0]?.[1]?.body).toEqual(expect.stringContaining('base64')) - expect(String(messages.mock.calls[2]?.[1]?.body).match(/"type":"base64"/gu)).toHaveLength(2) + const inline = messages.mock.calls[2]?.[1]?.body + expect(typeof inline === 'string' && inline.match(/"type":"base64"/gu)).toHaveLength(2) await request() expect(upload).toHaveBeenCalledTimes(2) expect(messages.mock.calls[3]?.[1]?.body).toEqual(expect.stringContaining('file-probe'))