From 08a606ccb8616e1e015f8e5b096a7b68c0f98f52 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Wed, 11 Nov 2026 15:24:50 +0800 Subject: [PATCH] Coordinate quota recovery and bound file retries by their deadline --- .../deepseek-file-policy/guide.i18n.yaml | 16 ++++ .../v0.2.2-rc.2/deepseek-file-policy/guide.md | 17 ++++ .../deepseek-file-policy/guide.zh.md | 17 ++++ packages/llm/llm-deepseek/README.i18n.yaml | 8 +- packages/llm/llm-deepseek/README.md | 4 +- packages/llm/llm-deepseek/README.zh.md | 4 +- packages/llm/llm-deepseek/src/adapter.ts | 4 +- packages/llm/llm-deepseek/src/config.ts | 3 +- packages/llm/llm-deepseek/src/file-store.ts | 43 +++++++--- packages/llm/llm-deepseek/src/images.ts | 5 +- .../llm/llm-deepseek/src/request-files.ts | 8 +- packages/llm/llm-deepseek/src/types.ts | 2 - .../llm/llm-deepseek/tests/file-store.spec.ts | 78 +++++++++++++++---- python/sdk/tests/test_commands_runtime.py | 34 +++++++- 14 files changed, 195 insertions(+), 48 deletions(-) create mode 100644 docs/upgrade-guide/v0.2.2-rc.2/deepseek-file-policy/guide.i18n.yaml create mode 100644 docs/upgrade-guide/v0.2.2-rc.2/deepseek-file-policy/guide.md create mode 100644 docs/upgrade-guide/v0.2.2-rc.2/deepseek-file-policy/guide.zh.md diff --git a/docs/upgrade-guide/v0.2.2-rc.2/deepseek-file-policy/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.2/deepseek-file-policy/guide.i18n.yaml new file mode 100644 index 0000000000..e83171514a --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.2/deepseek-file-policy/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-file-policy/guide.md +/: + en: a63d2d172b0f3536 + zh: e5c370889a1b4e7b +/resolve-the-file-policy-for-deepseekfilestore: + en: a27c476b947fc36b + zh: e5da712c4f097bfd +/resolve-the-file-policy-for-deepseekfilestore/change: + en: ec9035d819d611a0 + zh: ab2b7518ee3a15d8 +/resolve-the-file-policy-for-deepseekfilestore/migration: + en: e1f60e47f0dcb901 + zh: 2b7ca950bf00faa7 diff --git a/docs/upgrade-guide/v0.2.2-rc.2/deepseek-file-policy/guide.md b/docs/upgrade-guide/v0.2.2-rc.2/deepseek-file-policy/guide.md new file mode 100644 index 0000000000..a51a937f3d --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.2/deepseek-file-policy/guide.md @@ -0,0 +1,17 @@ +--- +kind: upgrade-guide +description: "Direct DeepSeekFileStore callers must supply a resolved file upload policy." +--- + +# Resolve the file policy for DeepSeekFileStore + +English | [中文](guide.zh.md) + +## Change + +The published `DeepSeekFilePolicy` type now requires `uploadConcurrency`, `uploadMaxRetries`, `uploadRetryDelayMs`, and `uploadTimeoutMs`. This affects TypeScript callers that construct their own policy for `DeepSeekFileStore`. + +## Migration + +1. Import `resolveAdapterOptions` from `@deepseek-ai/dsh-llm-deepseek`. Pass `resolveAdapterOptions(options).filePolicy` where you previously assembled a policy. To carry over custom expiry, refresh and cleanup values, supply `fileExpiresAfterSeconds`, `fileRefreshMarginSeconds` and `fileQuotaCleanupBatch` in `options`. +2. Type-check the caller and upload an image using `ensureUploaded`. The returned record contains its Files API id. diff --git a/docs/upgrade-guide/v0.2.2-rc.2/deepseek-file-policy/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.2/deepseek-file-policy/guide.zh.md new file mode 100644 index 0000000000..6bca50f1c4 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.2/deepseek-file-policy/guide.zh.md @@ -0,0 +1,17 @@ +--- +kind: upgrade-guide +description: "直接调用 DeepSeekFileStore 的代码需要传入解析后的文件上传策略。" +--- + +# 为 DeepSeekFileStore 解析文件上传策略 + +[English](guide.md) | 中文 + +## 变更 + +已发布的 `DeepSeekFilePolicy` 类型新增四个必填字段,分别为 `uploadConcurrency`、`uploadMaxRetries`、`uploadRetryDelayMs` 和 `uploadTimeoutMs`。自行构造策略并调用 `DeepSeekFileStore` 的 TypeScript 代码需要更新。 + +## 迁移 + +1. 从 `@deepseek-ai/dsh-llm-deepseek` 导入 `resolveAdapterOptions`。将原先手动构造的策略替换为 `resolveAdapterOptions(options).filePolicy`。如果用过自定义的文件有效期、提前刷新时间或清理数量,在 `options` 中分别传入 `fileExpiresAfterSeconds`、`fileRefreshMarginSeconds` 和 `fileQuotaCleanupBatch`。 +2. 对调用代码运行类型检查,再用 `ensureUploaded` 上传一张图片。返回的记录中应包含该图片的 Files API ID。 diff --git a/packages/llm/llm-deepseek/README.i18n.yaml b/packages/llm/llm-deepseek/README.i18n.yaml index 6173e6333f..8d900b6517 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: a035acd6e4099dcc - zh: 84b53b81be9856be + en: b25107fe7a1390ce + zh: 2b64a136ebc6a1b2 /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: e95c05a4c581217b + zh: 2b61e654afb63d2e /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 1e8efe0033..45987f0dc4 100644 --- a/packages/llm/llm-deepseek/README.md +++ b/packages/llm/llm-deepseek/README.md @@ -68,7 +68,7 @@ A request selects the route with `provider: deepseek-official`; the model id pas | `inlineImageOffloadByteQuantum` | `10 MiB` | Inline-mode oldest-prefix removal quantum | | `imageOffloadCountQuantum` | `20` | Count-overflow removal quantum | | `fileUploadConcurrency` | `3` | Simultaneous uploads of distinct images per model request (1–3), including stale-id replacements | -| `fileUploadMaxRetries` | `2` | Extra upload attempts per image (0–2). HTTP 429 and one successful storage-quota cleanup share this budget. Exhaustion triggers request-wide inline fallback. | +| `fileUploadMaxRetries` | `2` | Extra upload attempts per image (0–2). HTTP 429 and one successful storage-quota cleanup share this budget. Zero disables quota cleanup and upload retries. | | `fileUploadRetryDelayMs` | `500` | Minimum wait after rate limiting. A longer Retry-After takes precedence and the per-image deadline covers all attempts. | | `filesApiTimeoutMs` | `60,000` | Per-image Files resolution deadline | | `fileExpiresAfterSeconds` | `604,800` | Requested uploaded-image lifetime and local reuse bound | @@ -102,7 +102,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. -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. +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. Each request resolves distinct images concurrently. Uploads rejected with HTTP 429 can retry within the image deadline. A wait that would exhaust the deadline triggers immediate inline fallback. During overlapping quota recovery on one endpoint and credential, each retry claims one deleted file slot. A new batch of the oldest harness-owned files is deleted only when those slots run out. 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 6b1a618b94..4787021da5 100644 --- a/packages/llm/llm-deepseek/README.zh.md +++ b/packages/llm/llm-deepseek/README.zh.md @@ -68,7 +68,7 @@ kind: "package-reference" | `inlineImageOffloadByteQuantum` | `10 MiB` | 内联模式最旧前缀移除量子 | | `imageOffloadCountQuantum` | `20` | 数量超限移除量子 | | `fileUploadConcurrency` | `3` | 每个模型请求同时上传 1 至 3 张不同图片,file ID 失效后的重传也遵守此限制 | -| `fileUploadMaxRetries` | `2` | 每张图片最多额外上传 0 至 2 次,普通 429 重试和一次存储配额清理后的重试共用次数。次数用尽后,整个请求尝试改用内联图片。 | +| `fileUploadMaxRetries` | `2` | 每张图片最多额外上传 0 至 2 次,普通 429 重试和一次存储配额清理后的重试共用次数。设为 0 时跳过配额清理和上传重试。 | | `fileUploadRetryDelayMs` | `500` | 遇到限流后至少等待的毫秒数。服务端要求的 Retry-After 更长时按其要求等待,所有尝试共用单张图片的超时期限。 | | `filesApiTimeoutMs` | `60,000` | 每张图片 Files 解析截止时间 | | `fileExpiresAfterSeconds` | `604,800` | 请求的上传图片生存期与本地复用期限 | @@ -102,7 +102,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 与内联图片。调用方取消会停止请求。 -缓存 id 按端点与凭据限定作用域,在到期前刷新,根据提供方的陈旧文件错误失效,并通过带等待方局部取消的 singleflight 解析。上传通过 `expires_after[anchor]=created_at` 与 `expires_after[seconds]` 请求过期。Messages 文件元数据不含远端过期时间,因此本地复用期限使用原始上传时间加 `fileExpiresAfterSeconds`;这不保证远端文件删除。配额失败会先删除一批配置数量的最旧 harness 文件,再重试一次上传。 +缓存 id 按端点与凭据限定作用域,在到期前刷新,根据提供方的陈旧文件错误失效,并通过带等待方局部取消的 singleflight 解析。上传通过 `expires_after[anchor]=created_at` 与 `expires_after[seconds]` 请求过期。Messages 文件元数据不含远端过期时间,因此本地复用期限使用原始上传时间加 `fileExpiresAfterSeconds`;这不保证远端文件删除。每个请求并发解析不同图片。上传收到 429 时可在单图期限内重试,等待时间达到或超过剩余期限时,立即改用内联图片。同一端点和凭据下的多个上传同时遇到存储配额错误时,每次重试使用一个已删除文件腾出的名额。名额用完后,才会再删除一批最旧的 harness 文件。 Files 模式通过 `maxRequestFilesBytes` 与 `maxImagesPerRequest` 限制保留请求版本;内联回退有独立 base64 预算。两种模式都按配置的字节或数量量子移除最旧前缀。每张省略图片都有自己的模型可见占位符,包含显示名或附件 id,以及可用时的规范化尺寸、媒体类型与当前只读路径。分阶高水位策略避免每新增一张图片都改写旧请求前缀。 diff --git a/packages/llm/llm-deepseek/src/adapter.ts b/packages/llm/llm-deepseek/src/adapter.ts index 5ab13bb11e..2dc8318fda 100644 --- a/packages/llm/llm-deepseek/src/adapter.ts +++ b/packages/llm/llm-deepseek/src/adapter.ts @@ -100,7 +100,7 @@ export class DeepSeekAdapter extends LlmAdapt const files = new RequestFiles(this.files, { baseURL: connection.baseURL, headers: auth.headers, }, - connection.filePolicy, connection.filesApiTimeoutMs, signal, activity) + connection.filePolicy, signal, activity) let inline = false while (true) { signal.throwIfAborted() @@ -108,7 +108,7 @@ export class DeepSeekAdapter extends LlmAdapt let fileIds: Awaited> | undefined if (!inline) { try { - fileIds = await prepareFileIds(messages, versions, files, connection.fileUploadConcurrency) + fileIds = await prepareFileIds(messages, versions, files) } catch (error) { if (!(error instanceof FileResolutionFailure)) throw error inline = true diff --git a/packages/llm/llm-deepseek/src/config.ts b/packages/llm/llm-deepseek/src/config.ts index 003fd2b4c5..23420a3b4e 100644 --- a/packages/llm/llm-deepseek/src/config.ts +++ b/packages/llm/llm-deepseek/src/config.ts @@ -351,8 +351,9 @@ export function resolveAdapterOptions(config: Options, environment?: LaunchEnvir inlineImageOffloadByteQuantum, imageOffloadCountQuantum, filesApiTimeoutMs, - fileUploadConcurrency, filePolicy: { + uploadConcurrency: fileUploadConcurrency, + uploadTimeoutMs: filesApiTimeoutMs, expiresAfterSeconds: fileExpiresAfterSeconds, refreshMarginSeconds: fileRefreshMarginSeconds, quotaCleanupBatch: fileQuotaCleanupBatch, diff --git a/packages/llm/llm-deepseek/src/file-store.ts b/packages/llm/llm-deepseek/src/file-store.ts index 23c2994793..11c077ace8 100644 --- a/packages/llm/llm-deepseek/src/file-store.ts +++ b/packages/llm/llm-deepseek/src/file-store.ts @@ -1,8 +1,6 @@ /** DeepSeek Files API upload reuse, invalidation, and quota recovery. @module dsh-llm-deepseek/file-store */ import { setTimeout as delay } from 'node:timers/promises' -import { MAX_TIMER_DELAY_MS } from '@deepseek-ai/dsh-timeout' -import { MAX_FILE_UPLOAD_RETRIES, DEFAULT_FILE_UPLOAD_RETRY_DELAY_MS } from './defaults.ts' import type { RequestImageAttachment } from '@deepseek-ai/dsh-attachment' import { LlmError } from '@deepseek-ai/dsh-llm' import { DeepSeekFilesClient, DeepSeekFilesError, isFilesQuotaError } from './files-api.ts' @@ -20,10 +18,14 @@ export interface DeepSeekFilePolicy { expiresAfterSeconds: number refreshMarginSeconds: number quotaCleanupBatch: number - /** Additional attempts shared by rate-limit and quota recovery (default two). */ - uploadMaxRetries?: number + /** Maximum simultaneous file resolutions in one model request. */ + uploadConcurrency: number + /** Per-image resolution deadline, including retry delays. */ + uploadTimeoutMs: number + /** Additional attempts shared by rate-limit and quota recovery. */ + uploadMaxRetries: number /** Local delay after HTTP 429, in milliseconds. */ - uploadRetryDelayMs?: number + uploadRetryDelayMs: number } /** Connection facts needed by file operations. */ @@ -130,6 +132,8 @@ export class DeepSeekFileStore { private readonly now: () => number private readonly fetchImpl: typeof fetch | undefined private readonly inflight = new Map() + /** Unclaimed slots from the preceding cleanup in each active Files namespace. */ + private readonly quotaRecoveries = new Map>() /** * @param options - testable index, clock, and transport boundaries. @@ -203,6 +207,7 @@ export class DeepSeekFileStore { } const scope = fileScope(connection) const now = this.now() + const retryUntil = now + policy.uploadTimeoutMs 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 } @@ -231,7 +236,6 @@ export class DeepSeekFileStore { } let candidate: DeepSeekUploadRecord - const maxRetries = policy.uploadMaxRetries ?? MAX_FILE_UPLOAD_RETRIES let reclaimed = false for (let attempt = 0; ; attempt++) { signal.throwIfAborted() @@ -239,14 +243,14 @@ export class DeepSeekFileStore { candidate = await upload() break } catch (error) { - if (attempt >= maxRetries) throw error + if (attempt >= policy.uploadMaxRetries) throw error if (isFilesQuotaError(error)) { - if (reclaimed || await this.reclaimOldestOwned(connection, policy.quotaCleanupBatch, signal) === 0) throw error + if (reclaimed || !await this.reserveQuotaSlot(scope, connection, policy.quotaCleanupBatch, signal)) throw error reclaimed = true } else { if (!(error instanceof DeepSeekFilesError) || error.code !== 'RATE_LIMIT') throw error - const wait = Math.max(error.failure.providerRetryAfterMs ?? 0, policy.uploadRetryDelayMs ?? DEFAULT_FILE_UPLOAD_RETRY_DELAY_MS) - if (wait > MAX_TIMER_DELAY_MS) throw error + const wait = Math.max(error.failure.providerRetryAfterMs ?? 0, policy.uploadRetryDelayMs) + if (wait >= retryUntil - this.now()) throw error await delay(wait, undefined, { signal }) } } @@ -262,6 +266,25 @@ export class DeepSeekFileStore { return { record: committed.record, uploaded: committed.accepted } } + /** Overlapping quota failures claim distinct deleted slots, listing again only when the batch runs out. */ + private async reserveQuotaSlot(scope: DeepSeekUploadRecord['scope'], connection: DeepSeekFileConnection, count: number, signal: AbortSignal) { + const previous = this.quotaRecoveries.get(scope) + const next = Promise.withResolvers() + this.quotaRecoveries.set(scope, next.promise) + let available = 0 + try { + available = previous === undefined ? 0 : await previous + signal.throwIfAborted() + if (available === 0) available = await this.reclaimOldestOwned(connection, count, signal) + if (available === 0) return false + available-- + return true + } finally { + next.resolve(available) + if (this.quotaRecoveries.get(scope) === next.promise) this.quotaRecoveries.delete(scope) + } + } + /** * Invalidate exact local mappings in one index update after a model request rejects their remote ids. * @param generations - request-image variants with the exact file id the request used for each. diff --git a/packages/llm/llm-deepseek/src/images.ts b/packages/llm/llm-deepseek/src/images.ts index dced74f27d..70c662118c 100644 --- a/packages/llm/llm-deepseek/src/images.ts +++ b/packages/llm/llm-deepseek/src/images.ts @@ -5,7 +5,6 @@ import { contentHasImage, IMAGE_OFFLOAD_REQUIRED_CODE, LlmError, offloadedImageT import type { ContentBlock, ImageAttachmentAccessResolver, RequestMessage } from '@deepseek-ai/dsh-llm' import type { DeepSeekConnectionOptions as Connection } from './types.ts' import { resolveRequestImageTarget } from './request-pricing.ts' -import { MAX_FILE_UPLOAD_CONCURRENCY } from './defaults.ts' import type { DeepSeekFileId } from './file-id.ts' import type { RequestFiles } from './request-files.ts' @@ -95,14 +94,12 @@ function assertImagesFit( * @param messages - history within the Files byte/count budget. * @param versions - normalized versions for every retained reference. * @param files - request-owned Files resolution and recovery. - * @param concurrency - maximum simultaneous Files resolutions for this request. * @returns ids keyed by durable attachment identity. */ export async function prepareFileIds( messages: readonly RequestMessage[], versions: ReadonlyMap, files: RequestFiles, - concurrency = MAX_FILE_UPLOAD_CONCURRENCY, ): Promise> { - const ids = await files.resolveAll(versions, concurrency) + const ids = await files.resolveAll(versions) for (const [index, message] of messages.entries()) { let image = 0 for (const ref of imageRefs(message.content)) { diff --git a/packages/llm/llm-deepseek/src/request-files.ts b/packages/llm/llm-deepseek/src/request-files.ts index 4d4c065092..acf64b82fb 100644 --- a/packages/llm/llm-deepseek/src/request-files.ts +++ b/packages/llm/llm-deepseek/src/request-files.ts @@ -100,7 +100,6 @@ export class RequestFiles { private readonly files: DeepSeekFileStore, private readonly connection: DeepSeekFileConnection, private readonly policy: DeepSeekFilePolicy, - private readonly timeoutMs: number, private readonly signal: AbortSignal, private readonly activity: () => void, ) {} @@ -110,11 +109,10 @@ export class RequestFiles { /** Resolve each distinct attachment once. A failed resolution cancels its sibling waits. * @param versions - retained request images keyed by attachment id. - * @param concurrency - maximum simultaneous resolutions in this request. * @returns provider ids for every retained attachment. */ async resolveAll( - versions: ReadonlyMap, concurrency: number, + versions: ReadonlyMap, ): Promise> { const ids = new Map() const pending = versions.entries() @@ -123,7 +121,7 @@ export class RequestFiles { const worker = async () => { for (const [id, version] of pending) { if (signal.aborted) return - using limit = deadline(signal, this.timeoutMs, 'DEEPSEEK_FILES_API_TIMEOUT') + using limit = deadline(signal, this.policy.uploadTimeoutMs, 'DEEPSEEK_FILES_API_TIMEOUT') try { const result = await this.files.ensureUploaded(version, this.connection, this.policy, limit.signal) ids.set(id, result.record.fileId) @@ -134,7 +132,7 @@ export class RequestFiles { this.activity() } } - await Promise.all(Array.from({ length: Math.min(versions.size, concurrency) }, worker)) + await Promise.all(Array.from({ length: Math.min(versions.size, this.policy.uploadConcurrency) }, worker)) this.signal.throwIfAborted() if (batch.signal.aborted) throw new FileResolutionFailure(batch.signal.reason) return ids diff --git a/packages/llm/llm-deepseek/src/types.ts b/packages/llm/llm-deepseek/src/types.ts index 6985bb9bc9..c682bba792 100644 --- a/packages/llm/llm-deepseek/src/types.ts +++ b/packages/llm/llm-deepseek/src/types.ts @@ -75,8 +75,6 @@ export interface DeepSeekConnectionOptions { imageOffloadCountQuantum: number /** Maximum duration of one request-image Files API resolution. */ filesApiTimeoutMs: number - /** Per-request parallel Files resolutions (defaults to three). */ - fileUploadConcurrency?: number /** Upload expiry, refresh, and quota-recovery policy. */ filePolicy: DeepSeekFilePolicy /** Provider-owned model-request retry policy, already resolved. */ diff --git a/packages/llm/llm-deepseek/tests/file-store.spec.ts b/packages/llm/llm-deepseek/tests/file-store.spec.ts index f26c639478..ba7e736f1b 100644 --- a/packages/llm/llm-deepseek/tests/file-store.spec.ts +++ b/packages/llm/llm-deepseek/tests/file-store.spec.ts @@ -32,7 +32,10 @@ const VERSION: RequestImageAttachment = { hasAlpha: true, } const CONNECTION = { baseURL: 'https://api.deepseek.com', headers: { 'x-api-key': 'key' } } -const POLICY = { expiresAfterSeconds: 604_800, refreshMarginSeconds: 3_600, quotaCleanupBatch: 100 } +const POLICY = { + expiresAfterSeconds: 604_800, refreshMarginSeconds: 3_600, quotaCleanupBatch: 100, + uploadMaxRetries: 2, uploadRetryDelayMs: 500, uploadConcurrency: 3, uploadTimeoutMs: 60_000, +} const NOW = 1_700_000_000_000 /** Every temp store root created by this file, removed after each test. */ @@ -136,24 +139,26 @@ describe('DeepSeekFileStore', () => { }) it.each([ - { errors: ['quota', 'quota'], attempts: 2 }, - { errors: ['limit', 'quota', 'limit'], attempts: 3 }, - ])('shares the retry budget and cleans quota once for $errors', async ({ errors, attempts }) => { + { errors: ['quota'], retries: 0, attempts: 1, cleanups: 0 }, + { errors: ['quota', 'quota'], retries: 2, attempts: 2, cleanups: 1 }, + { errors: ['limit', 'quota', 'limit'], retries: 2, attempts: 3, cleanups: 1 }, + ])('shares the retry budget across $errors with $retries retries', async ({ errors, retries, attempts, cleanups }) => { const dir = await mkdtemp(join(tmpdir(), 'dsh-file-quota-retries-')) roots.push(dir) const fetchImpl = vi.fn() for (const message of errors) fetchImpl.mockResolvedValueOnce(Response.json({ error: { message } }, { status: 429 })) const store = new DeepSeekFileStore({ index: new DeepSeekUploadIndex(join(dir, 'index.json')), fetch: fetchImpl }) const reclaim = vi.spyOn(store, 'reclaimOldestOwned').mockResolvedValue(1) - await expect(store.ensureUploaded(VERSION, CONNECTION, { ...POLICY, uploadRetryDelayMs: 1 })).rejects.toMatchObject({ code: 'RATE_LIMIT' }) + const policy = { ...POLICY, uploadMaxRetries: retries, uploadRetryDelayMs: 1 } + await expect(store.ensureUploaded(VERSION, CONNECTION, policy)).rejects.toMatchObject({ code: 'RATE_LIMIT' }) expect(fetchImpl).toHaveBeenCalledTimes(attempts) - expect(reclaim).toHaveBeenCalledTimes(1) + expect(reclaim).toHaveBeenCalledTimes(cleanups) }) it('cancels a server-requested retry delay without sending the upload again', async () => { const dir = await mkdtemp(join(tmpdir(), 'dsh-file-retry-after-abort-')) roots.push(dir) - const fetchImpl = vi.fn().mockResolvedValueOnce(new Response('busy', { status: 429, headers: { 'retry-after': '60' } })) + const fetchImpl = vi.fn().mockResolvedValueOnce(new Response('busy', { status: 429, headers: { 'retry-after': '30' } })) const store = new DeepSeekFileStore({ index: new DeepSeekUploadIndex(join(dir, 'index.json')), fetch: fetchImpl }) const scheduled = Promise.withResolvers() const timers = await vi.importActual('node:timers/promises') @@ -165,7 +170,7 @@ describe('DeepSeekFileStore', () => { const pending = store.ensureUploaded(VERSION, CONNECTION, POLICY, controller.signal) const result = expect(pending).rejects.toThrow('caller cancelled') try { - expect(await scheduled.promise).toBe(60_000) + expect(await scheduled.promise).toBe(30_000) } finally { controller.abort(new Error('caller cancelled')) await result @@ -173,17 +178,64 @@ describe('DeepSeekFileStore', () => { expect(fetchImpl).toHaveBeenCalledTimes(1) }) - it('preserves a Retry-After beyond the supported timer range without posting again', async () => { + it('falls back immediately when Retry-After exceeds the remaining image deadline', async () => { const dir = await mkdtemp(join(tmpdir(), 'dsh-file-retry-after-')) roots.push(dir) - const response = new Response('busy', { status: 429, headers: { 'retry-after': '3000000' } }) - const fetchImpl = vi.fn().mockResolvedValueOnce(response) - const store = new DeepSeekFileStore({ index: new DeepSeekUploadIndex(join(dir, 'index.json')), fetch: fetchImpl }) + let now = NOW + const fetchImpl = vi.fn(async () => { + now += 45_000 + return new Response('busy', { status: 429, headers: { 'retry-after': '20' } }) + }) + const store = new DeepSeekFileStore({ index: new DeepSeekUploadIndex(join(dir, 'index.json')), fetch: fetchImpl, now: () => now }) await expect(store.ensureUploaded(VERSION, CONNECTION, POLICY)) - .rejects.toMatchObject({ failure: { providerRetryAfterMs: 3_000_000_000 } }) + .rejects.toMatchObject({ failure: { providerRetryAfterMs: 20_000 } }) expect(fetchImpl).toHaveBeenCalledTimes(1) }) + it.each([1, 3])('reserves distinct file slots across concurrent quota failures with cleanup batch %i', async (batch) => { + const dir = await mkdtemp(join(tmpdir(), 'dsh-file-quota-slots-')) + roots.push(dir) + const index = new DeepSeekUploadIndex(join(dir, 'index.json')) + vi.spyOn(index, 'get').mockResolvedValue(undefined) + const file = (id: string, created: number) => ({ + id, type: 'file', size_bytes: 3, created_at: new Date(created).toISOString(), filename: 'dsh-owned.png', mime_type: 'image/png', + }) + const stored = new Map(['old-1', 'old-2', 'old-3'].map(id => [id, file(id, NOW - 1000)])) + const deleted: string[] = [] + let lists = 0 + let attempts = 0 + const full = Promise.withResolvers() + const fetchImpl: typeof fetch = async (url, init) => { + if (init?.method === 'POST') { + const ordinal = ++attempts + if (stored.size === 3) { + if (ordinal === 3) full.resolve(undefined) + await full.promise + return Response.json({ error: { message: 'stored files quota' } }, { status: 429 }) + } + const fresh = file(`new-${ordinal}`, NOW) + stored.set(fresh.id, fresh) + return Response.json(fresh) + } + if (init?.method === 'DELETE') { + const id = requestUrl(url).split('/').at(-1)! + if (!stored.delete(id)) return new Response(null, { status: 404 }) + deleted.push(id) + return Response.json({ id, type: 'file_deleted' }) + } + lists++ + return Response.json({ data: [...stored.values()], has_more: false }) + } + const store = new DeepSeekFileStore({ index, fetch: fetchImpl, now: () => NOW }) + const results = await Promise.all(['c', 'd', 'e'].map(digit => store.ensureUploaded({ + ...VERSION, variantId: brandString(`sha256:${digit.repeat(64)}`), + }, CONNECTION, { ...POLICY, quotaCleanupBatch: batch }))) + expect(deleted.toSorted()).toEqual(['old-1', 'old-2', 'old-3']) + expect(lists).toBe(3 / batch) + expect(attempts).toBe(6) + expect(results.map(result => result.record.fileId).toSorted()).toEqual([...stored.keys()].toSorted()) + }) + it('reclaims the oldest owned native file across descending pages before retrying an upload', async () => { const dir = await mkdtemp(join(tmpdir(), 'dsh-native-file-quota-')) roots.push(dir) diff --git a/python/sdk/tests/test_commands_runtime.py b/python/sdk/tests/test_commands_runtime.py index 25825df4be..37b46b0557 100644 --- a/python/sdk/tests/test_commands_runtime.py +++ b/python/sdk/tests/test_commands_runtime.py @@ -90,12 +90,26 @@ class _ModelServer: self.request.settimeout(_WAIT_SECONDS) super().setup() + def handle_one_request(self) -> None: + self.raw_requestline = b"" + try: + super().handle_one_request() + except (ConnectionAbortedError, ConnectionResetError): + if self.raw_requestline: + raise + # A cancelled upload can close a newly opened socket before sending a request. + self.close_connection = True + def do_POST(self) -> None: - payload = self.rfile.read(int(self.headers["Content-Length"])) if self.path == "/v1/files": - # The model fixture accepts inline images through the provider's Files fallback. - self.send_error(404, "Images are accepted inline") + # The first 404 selects inline images and cancels concurrent file uploads. + try: + self.rfile.read(int(self.headers["Content-Length"])) + self.send_error(404, "Images are accepted inline") + except (BrokenPipeError, ConnectionResetError, ConnectionAbortedError): + self.close_connection = True return + payload = self.rfile.read(int(self.headers["Content-Length"])) assert self.path == "/v1/messages", f"unexpected model endpoint: {self.path}" body = json.loads(payload) assert isinstance(body, dict) and isinstance(body.get("model"), str) @@ -199,6 +213,20 @@ def test_model_server_only_allows_expected_connection_aborts( assert not model.thread.is_alive() +def test_model_server_accepts_cancelled_file_upload(monkeypatch: pytest.MonkeyPatch) -> None: + model = _ModelServer([]) + + def reset(_handler: BaseHTTPRequestHandler) -> None: + raise ConnectionResetError("sibling upload selected inline fallback") + + monkeypatch.setattr(model.server.RequestHandlerClass, "end_headers", reset) + with model, closing(HTTPConnection(*model.server.server_address, timeout=_WAIT_SECONDS)) as connection: + connection.request("POST", "/v1/files", body=b"image") + with pytest.raises(RemoteDisconnected): + connection.getresponse() + assert model.captured() == [] + + def _dsh_bin() -> str | None: mode = os.environ.get("DSH_COMMANDS_TEST_RUNTIME", "built") if mode == "installed":