diff --git a/docs/upgrade-guide/v0.2.2-rc.3/deepseek-file-policy/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.3/deepseek-file-policy/guide.i18n.yaml new file mode 100644 index 0000000000..929426347b --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.3/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.3/deepseek-file-policy/guide.md +/: + en: a63d2d172b0f3536 + zh: e5c370889a1b4e7b +/resolve-the-file-policy-for-deepseekfilestore: + en: d51f1bd3ffe80469 + zh: 5c507e956ded97d7 +/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.3/deepseek-file-policy/guide.md b/docs/upgrade-guide/v0.2.2-rc.3/deepseek-file-policy/guide.md new file mode 100644 index 0000000000..a51a937f3d --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.3/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.3/deepseek-file-policy/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.3/deepseek-file-policy/guide.zh.md new file mode 100644 index 0000000000..6bca50f1c4 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.3/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 efd29634d1..507daed1b8 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: ad01714ddbd0a791 - zh: f936398331d6fb85 + en: 027d877820d26c65 + zh: 080705c5c20d1032 /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: f880b79feebb9e63 - zh: 0dbbb2378e6f9af3 + en: f20f2cfbb38e4ba9 + zh: c527b91c8b747886 /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 3af6e623fd..61c6cbfad7 100644 --- a/packages/llm/llm-deepseek/README.md +++ b/packages/llm/llm-deepseek/README.md @@ -67,6 +67,9 @@ 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 | +| `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. 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` | `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 | @@ -99,9 +102,9 @@ 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 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. +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. Concurrent images in one request share one skip for its endpoint and credential. An upload timeout triggers inline fallback immediately. Only an HTTP 429 response starts a rate-limit retry. 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. +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 6a24456782..cb0f455794 100644 --- a/packages/llm/llm-deepseek/README.zh.md +++ b/packages/llm/llm-deepseek/README.zh.md @@ -67,6 +67,9 @@ kind: "package-reference" | `imageOffloadByteQuantum` | `64 MiB` | Files 模式最旧前缀移除量子 | | `inlineImageOffloadByteQuantum` | `10 MiB` | 内联模式最旧前缀移除量子 | | `imageOffloadCountQuantum` | `20` | 数量超限移除量子 | +| `fileUploadConcurrency` | `3` | 每个模型请求同时上传 1 至 3 张不同图片,file ID 失效后的重传也遵守此限制 | +| `fileUploadMaxRetries` | `2` | 每张图片最多额外上传 0 至 2 次,普通 429 重试和一次存储配额清理后的重试共用次数。设为 0 时跳过配额清理和上传重试。 | +| `fileUploadRetryDelayMs` | `500` | 遇到限流后至少等待的毫秒数。服务端要求的 Retry-After 更长时按其要求等待,所有尝试共用单张图片的超时期限。 | | `filesApiTimeoutMs` | `20,000` | 每张图片 Files 解析截止时间 | | `fileExpiresAfterSeconds` | `604,800` | 请求的上传图片生存期与本地复用期限 | | `fileRefreshMarginSeconds` | `3,600` | 低于此剩余复用期时替换 id | @@ -99,9 +102,9 @@ 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 次,之后继续翻倍,不受经过时间的影响。同一端点和凭据按模型请求计数,一次请求并发处理多张图片也只扣一次。上传超时立即回退到内联图片,只有收到 HTTP 429 才触发限流重试。纯文本请求和所有图片都命中文件 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 a6129f26fd..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() diff --git a/packages/llm/llm-deepseek/src/config.ts b/packages/llm/llm-deepseek/src/config.ts index 494797f8b0..c88208a5ff 100644 --- a/packages/llm/llm-deepseek/src/config.ts +++ b/packages/llm/llm-deepseek/src/config.ts @@ -10,7 +10,7 @@ import type { LaunchEnvironmentSnapshot } from '@deepseek-ai/dsh-launch-environm import { MAX_TIMER_DELAY_MS } from '@deepseek-ai/dsh-timeout' import type { DeepSeekCatalogModel, DeepSeekConnectionOptions } from './types.ts' import { DEFAULT_MODELS } from './models.ts' -import { DEFAULT_STREAM_IDLE_TIMEOUT_MS, DEFAULT_CONTEXT_WINDOW, DEFAULT_MAX_TOKENS, DEFAULT_MAX_INLINE_REQUEST_IMAGE_BYTES, DEFAULT_IMAGE_OFFLOAD_BYTE_QUANTUM, DEFAULT_INLINE_IMAGE_OFFLOAD_BYTE_QUANTUM, DEFAULT_IMAGE_OFFLOAD_COUNT_QUANTUM, DEFAULT_FILE_EXPIRY_SECONDS, DEFAULT_FILE_REFRESH_MARGIN_SECONDS, DEFAULT_FILE_QUOTA_CLEANUP_BATCH, DEFAULT_FILES_API_TIMEOUT_MS } from './defaults.ts' +import { MAX_FILE_UPLOAD_CONCURRENCY, MAX_FILE_UPLOAD_RETRIES, DEFAULT_FILE_UPLOAD_RETRY_DELAY_MS, DEFAULT_STREAM_IDLE_TIMEOUT_MS, DEFAULT_CONTEXT_WINDOW, DEFAULT_MAX_TOKENS, DEFAULT_MAX_INLINE_REQUEST_IMAGE_BYTES, DEFAULT_IMAGE_OFFLOAD_BYTE_QUANTUM, DEFAULT_INLINE_IMAGE_OFFLOAD_BYTE_QUANTUM, DEFAULT_IMAGE_OFFLOAD_COUNT_QUANTUM, DEFAULT_FILE_EXPIRY_SECONDS, DEFAULT_FILE_REFRESH_MARGIN_SECONDS, DEFAULT_FILE_QUOTA_CLEANUP_BATCH, DEFAULT_FILES_API_TIMEOUT_MS } from './defaults.ts' import { DEFAULT_MAX_IMAGES_PER_REQUEST, DEFAULT_MAX_REQUEST_FILES_BYTES, DEFAULT_REQUEST_IMAGE_MAX_BYTES } from './request-pricing.ts' const MODEL_MODALITIES = ['text', 'image'] as const satisfies readonly ModelModality[] @@ -43,6 +43,12 @@ export interface Config { inlineImageOffloadByteQuantum: Volatile /** Image-count removal step after the request exceeds its count bound (default 20). */ imageOffloadCountQuantum: Volatile + /** Simultaneous Files uploads per model request (1–3, default 3). */ + fileUploadConcurrency: Volatile + /** Additional attempts per image after throttling or quota recovery (0–2, default 2). */ + fileUploadMaxRetries: Volatile + /** Local wait after upload throttling, in milliseconds (default 500). */ + fileUploadRetryDelayMs: Volatile /** Maximum duration of one request-image Files API resolution (default 20 seconds). */ filesApiTimeoutMs: Volatile /** Explicit lifetime assigned to each uploaded image (default seven days). */ @@ -103,6 +109,9 @@ export const deepSeekConfigFields = { imageOffloadByteQuantum: z.number().step(1).min(1).default(DEFAULT_IMAGE_OFFLOAD_BYTE_QUANTUM).volatile(), inlineImageOffloadByteQuantum: z.number().step(1).min(1).default(DEFAULT_INLINE_IMAGE_OFFLOAD_BYTE_QUANTUM).volatile(), imageOffloadCountQuantum: z.number().step(1).min(1).default(DEFAULT_IMAGE_OFFLOAD_COUNT_QUANTUM).volatile(), + fileUploadConcurrency: z.number().step(1).min(1).max(MAX_FILE_UPLOAD_CONCURRENCY).default(MAX_FILE_UPLOAD_CONCURRENCY).volatile(), + fileUploadMaxRetries: z.number().step(1).min(0).max(MAX_FILE_UPLOAD_RETRIES).default(MAX_FILE_UPLOAD_RETRIES).volatile(), + fileUploadRetryDelayMs: z.number().step(1).min(1).max(MAX_TIMER_DELAY_MS).default(DEFAULT_FILE_UPLOAD_RETRY_DELAY_MS).volatile(), filesApiTimeoutMs: z.number().min(Number.MIN_VALUE).max(MAX_TIMER_DELAY_MS).default(DEFAULT_FILES_API_TIMEOUT_MS).volatile(), fileExpiresAfterSeconds: z.number().step(1).min(3_600).max(2_592_000).default(DEFAULT_FILE_EXPIRY_SECONDS).volatile(), fileRefreshMarginSeconds: z.number().step(1).min(0).default(DEFAULT_FILE_REFRESH_MARGIN_SECONDS).volatile(), @@ -282,6 +291,18 @@ export function resolveAdapterOptions(config: Options, environment?: LaunchEnvir if (imageOffloadCountQuantum > maxImagesPerRequest) { throw new Error('llm-deepseek: imageOffloadCountQuantum must not exceed maxImagesPerRequest') } + const fileUploadConcurrency = config.fileUploadConcurrency ?? MAX_FILE_UPLOAD_CONCURRENCY + if (!Number.isInteger(fileUploadConcurrency) || fileUploadConcurrency < 1 || fileUploadConcurrency > MAX_FILE_UPLOAD_CONCURRENCY) { + throw new Error(`llm-deepseek: fileUploadConcurrency must be an integer from 1 through ${MAX_FILE_UPLOAD_CONCURRENCY}`) + } + const fileUploadMaxRetries = config.fileUploadMaxRetries ?? MAX_FILE_UPLOAD_RETRIES + if (!Number.isInteger(fileUploadMaxRetries) || fileUploadMaxRetries < 0 || fileUploadMaxRetries > MAX_FILE_UPLOAD_RETRIES) { + throw new Error(`llm-deepseek: fileUploadMaxRetries must be an integer from 0 through ${MAX_FILE_UPLOAD_RETRIES}`) + } + const fileUploadRetryDelayMs = config.fileUploadRetryDelayMs ?? DEFAULT_FILE_UPLOAD_RETRY_DELAY_MS + if (!Number.isInteger(fileUploadRetryDelayMs) || fileUploadRetryDelayMs < 1 || fileUploadRetryDelayMs > MAX_TIMER_DELAY_MS) { + throw new Error(`llm-deepseek: fileUploadRetryDelayMs must be an integer from 1 through ${MAX_TIMER_DELAY_MS}`) + } const filesApiTimeoutMs = config.filesApiTimeoutMs ?? DEFAULT_FILES_API_TIMEOUT_MS if (!Number.isFinite(filesApiTimeoutMs) || filesApiTimeoutMs <= 0 @@ -331,9 +352,13 @@ export function resolveAdapterOptions(config: Options, environment?: LaunchEnvir imageOffloadCountQuantum, filesApiTimeoutMs, filePolicy: { + uploadConcurrency: fileUploadConcurrency, + uploadTimeoutMs: filesApiTimeoutMs, expiresAfterSeconds: fileExpiresAfterSeconds, refreshMarginSeconds: fileRefreshMarginSeconds, quotaCleanupBatch: fileQuotaCleanupBatch, + uploadMaxRetries: fileUploadMaxRetries, + uploadRetryDelayMs: fileUploadRetryDelayMs, }, retryPolicy: resolveRetryPolicy(config.retryPolicy, 'llm-deepseek: retryPolicy'), } diff --git a/packages/llm/llm-deepseek/src/defaults.ts b/packages/llm/llm-deepseek/src/defaults.ts index b89a36e86b..ad18472b62 100644 --- a/packages/llm/llm-deepseek/src/defaults.ts +++ b/packages/llm/llm-deepseek/src/defaults.ts @@ -20,5 +20,11 @@ export const DEFAULT_FILE_EXPIRY_SECONDS = 7 * 24 * 60 * 60 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 +/** Maximum simultaneous Files uploads per model request. */ +export const MAX_FILE_UPLOAD_CONCURRENCY = 3 +/** Maximum additional upload attempts per image. */ +export const MAX_FILE_UPLOAD_RETRIES = 2 +/** Local wait after an upload is rate limited, in milliseconds. */ +export const DEFAULT_FILE_UPLOAD_RETRY_DELAY_MS = 500 /** Default deadline for resolving one request image through the Files API. */ 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 e21cab2637..cc3c42390d 100644 --- a/packages/llm/llm-deepseek/src/file-store.ts +++ b/packages/llm/llm-deepseek/src/file-store.ts @@ -1,9 +1,10 @@ /** DeepSeek Files API upload reuse, invalidation, and quota recovery. @module dsh-llm-deepseek/file-store */ +import { setTimeout as delay } from 'node:timers/promises' 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' +import { DeepSeekFilesClient, DeepSeekFilesError, isFilesQuotaError } from './files-api.ts' import type { DeepSeekFileId } from './file-id.ts' import { messagesApiRoot } from './messages-api.ts' import { deepSeekFileScope, DeepSeekUploadIndex } from './upload-index.ts' @@ -26,6 +27,14 @@ export interface DeepSeekFilePolicy { expiresAfterSeconds: number refreshMarginSeconds: number quotaCleanupBatch: 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 } /** Connection facts needed by file operations. */ @@ -47,6 +56,12 @@ interface FileStoreOptions { fetch?: typeof fetch } +/** Timeout decision shared by all cache misses in one model request on the same endpoint and credential. */ +export interface FileRequestBackoff { + /** Undefined before the first cache miss, null when uploads are admitted, or the timeout behind the skip. */ + skippedAfter?: TimeoutReason | null +} + interface SharedUpload { controller: AbortController promise: Promise @@ -136,6 +151,8 @@ export class DeepSeekFileStore { private readonly fetchImpl: typeof fetch | undefined private readonly backoffs = new Map() 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. @@ -160,14 +177,16 @@ 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 - timeout backoff decision shared by images in the same request; standalone calls count independently. * @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. + * @throws During backoff the first cache miss consumes one skip for the request. Skipped uploads reject with FILES_API_SKIPPED. */ async ensureUploaded( version: RequestImageAttachment, connection: DeepSeekFileConnection, policy: DeepSeekFilePolicy, signal?: AbortSignal, + request: FileRequestBackoff = {}, ): Promise { signal?.throwIfAborted() if (version.bytes > MAX_IMAGE_BYTES) { @@ -175,16 +194,24 @@ 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) + const startedAt = this.now() + const cached = await this.index.get(scope, version.variantId, startedAt, marginMs, signal) .catch((error: unknown) => { throw uploadFailure(error) }) signal?.throwIfAborted() if (cached) return { record: cached, uploaded: false } - const backoff = this.backoffs.get(scope) - if (backoff && backoff.remaining > 0n) { - backoff.remaining-- + if (request.skippedAfter === undefined) { + const backoff = this.backoffs.get(scope) + if (backoff && backoff.remaining > 0n) { + backoff.remaining-- + request.skippedAfter = backoff.reason + } else { + request.skippedAfter = null + } + } + if (request.skippedAfter) { throw LlmError.fromFailure({ message: 'DeepSeek Files API upload skipped after a timeout.', code: 'FILES_API_SKIPPED', - }, { cause: backoff.reason }) + }, { cause: request.skippedAfter }) } const key = `${scope}\0${version.variantId}` let active = this.inflight.get(key) @@ -200,7 +227,7 @@ export class DeepSeekFileStore { waiters: 0, promise: undefined as never, } - shared.promise = this.uploadOnce(version, connection, policy, scope, shared).then((value) => { + shared.promise = this.uploadOnce(version, connection, policy, scope, shared, startedAt + policy.uploadTimeoutMs).then((value) => { shared.settled = true return value }, (error: unknown) => { @@ -220,6 +247,7 @@ export class DeepSeekFileStore { policy: DeepSeekFilePolicy, scope: DeepSeekUploadRecord['scope'], shared: SharedUpload, + retryUntil: number, ): Promise { const signal = shared.controller.signal const marginMs = policy.refreshMarginSeconds * 1_000 @@ -258,13 +286,23 @@ export class DeepSeekFileStore { } let candidate: DeepSeekUploadRecord - try { - candidate = await upload() - } catch (error: unknown) { - if (!isFilesQuotaError(error)) throw error - const deleted = await this.reclaimOldestOwned(connection, policy.quotaCleanupBatch, signal) - if (deleted === 0) throw error - candidate = await upload() + let reclaimed = false + for (let attempt = 0; ; attempt++) { + try { + candidate = await upload() + break + } catch (error) { + if (attempt >= policy.uploadMaxRetries) throw error + if (isFilesQuotaError(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) + if (wait >= retryUntil - this.now()) throw error + await delay(wait, undefined, { signal }) + } + } } const committed = await this.index.commit(candidate, this.now(), marginMs) if (!committed.accepted) { @@ -277,6 +315,28 @@ 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-- + return true + } + const deleted = await this.reclaimOldestOwned(connection, count, signal) + available = Math.max(0, deleted - 1) + return deleted > 0 + } 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/files-api.ts b/packages/llm/llm-deepseek/src/files-api.ts index 8b56cb9cdd..faa43984fd 100644 --- a/packages/llm/llm-deepseek/src/files-api.ts +++ b/packages/llm/llm-deepseek/src/files-api.ts @@ -3,6 +3,7 @@ import { attributionHeaders, LlmError } from '@deepseek-ai/dsh-llm' import type { ImageMediaType } from '@deepseek-ai/dsh-attachment' import { brandString } from '@deepseek-ai/dsh-brand' +import { retryAfterMs } from './transport.ts' import type { DeepSeekFileId as DeepSeekFileIdType } from './file-id.ts' import { messagesApiRoot, MESSAGES_FILES_BETA } from './messages-api.ts' @@ -44,15 +45,17 @@ export class DeepSeekFilesError extends LlmError { * @param message - user-readable provider failure. * @param status - HTTP status returned by the Files API. * @param detail - provider error fields joined for classification. + * @param headers - Files response headers carrying Retry-After. */ - constructor(message: string, status: number, detail: string) { + constructor(message: string, status: number, detail: string, headers?: Headers) { + const wait = retryAfterMs(headers) super(message, status === 401 || status === 403 ? 'AUTH' : status === 429 ? 'RATE_LIMIT' : status >= 500 ? 'SERVER' - : 'FILES_API', { status }) + : 'FILES_API', { status, ...wait === undefined ? {} : { providerRetryAfterMs: wait } }) this.name = 'DeepSeekFilesError' this.detail = detail } @@ -171,6 +174,7 @@ export class DeepSeekFilesClient { message ?? `DeepSeek Files API error (HTTP ${response.status})`, response.status, detail, + response.headers, ) } diff --git a/packages/llm/llm-deepseek/src/images.ts b/packages/llm/llm-deepseek/src/images.ts index 9d72f4c5dc..70c662118c 100644 --- a/packages/llm/llm-deepseek/src/images.ts +++ b/packages/llm/llm-deepseek/src/images.ts @@ -99,12 +99,12 @@ function assertImagesFit( export async function prepareFileIds( messages: readonly RequestMessage[], versions: ReadonlyMap, files: RequestFiles, ): Promise> { - const ids = new Map() + const ids = await files.resolveAll(versions) for (const [index, message] of messages.entries()) { let image = 0 for (const ref of imageRefs(message.content)) { const version = versions.get(ref.attachmentId) as RequestImageAttachment - ids.set(ref.attachmentId, await files.resolve(version, { message: index + 1, image: ++image })) + files.record(version, ids.get(ref.attachmentId) as DeepSeekFileId, { message: index + 1, image: ++image }) } } return ids diff --git a/packages/llm/llm-deepseek/src/request-files.ts b/packages/llm/llm-deepseek/src/request-files.ts index dcebd508d4..1657797754 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 { AttachmentId } from '@deepseek-ai/dsh-attachment/types' import type { RequestImageAttachment } from '@deepseek-ai/dsh-attachment' import { deadline } from '@deepseek-ai/dsh-timeout' -import { FILES_API_TIMEOUT, type DeepSeekFileStore, type DeepSeekFileConnection, type DeepSeekFilePolicy } from './file-store.ts' +import { FILES_API_TIMEOUT, type DeepSeekFileStore, type DeepSeekFileConnection, type DeepSeekFilePolicy, type FileRequestBackoff } from './file-store.ts' import type { DeepSeekFileId } from './file-id.ts' /** Position of an image occurrence in the request's conversation messages. */ @@ -94,12 +95,12 @@ function normalizedImageDiagnostic( export class RequestFiles { private used: UsedRequestFile[] = [] private retried = false + private readonly backoff: FileRequestBackoff = {} constructor( private readonly files: DeepSeekFileStore, private readonly connection: DeepSeekFileConnection, private readonly policy: DeepSeekFilePolicy, - private readonly timeoutMs: number, private readonly signal: AbortSignal, private readonly activity: () => void, ) {} @@ -107,24 +108,44 @@ export class RequestFiles { /** Reset occurrence tracking before serializing the next HTTP attempt. */ beginAttempt(): void { this.used = [] } - /** - * Resolve a retained image under its own upload deadline. - * @param version - prepared request image. - * @param location - occurrence used by provider-rejection diagnostics. - * @returns the reusable provider id. + /** Resolve each distinct attachment once. A failed resolution cancels its sibling waits. + * @param versions - retained request images keyed by attachment id. + * @returns provider ids for every retained attachment. */ - async resolve(version: RequestImageAttachment, location: ImageWireLocation): Promise { - 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) - } catch (error) { - if (this.signal.aborted) throw error - throw new FileResolutionFailure(error) + async resolveAll( + versions: ReadonlyMap, + ): Promise> { + const ids = new Map() + const pending = versions.entries() + const batch = new AbortController() + const signal = AbortSignal.any([this.signal, batch.signal]) + const worker = async () => { + for (const [id, version] of pending) { + if (signal.aborted) return + using limit = deadline(signal, this.policy.uploadTimeoutMs, FILES_API_TIMEOUT) + try { + const result = await this.files.ensureUploaded(version, this.connection, this.policy, limit.signal, this.backoff) + ids.set(id, result.record.fileId) + } catch (error) { + batch.abort(new FileResolutionFailure(error)) + return + } + this.activity() + } } - this.activity() - this.used.push({ version, fileId: resolved.record.fileId, location }) - return resolved.record.fileId + await Promise.all(Array.from({ length: Math.min(versions.size, this.policy.uploadConcurrency) }, worker)) + this.signal.throwIfAborted() + batch.signal.throwIfAborted() + return ids + } + + /** Record one image occurrence in wire order for provider diagnostics. + * @param version - prepared request image. + * @param fileId - resolved provider id. + * @param location - position in the request. + */ + record(version: RequestImageAttachment, fileId: DeepSeekFileId, location: ImageWireLocation): void { + this.used.push({ version, fileId, location }) } /** diff --git a/packages/llm/llm-deepseek/src/transport.ts b/packages/llm/llm-deepseek/src/transport.ts index 2072ec00b5..9a2e4dca4b 100644 --- a/packages/llm/llm-deepseek/src/transport.ts +++ b/packages/llm/llm-deepseek/src/transport.ts @@ -15,6 +15,16 @@ export function providerErrorDetail(raw: unknown): string { return [fields.code, fields.type, fields.message].filter((value): value is string => typeof value === 'string').join(' ') } +/** Provider-requested wait, in milliseconds, for an HTTP retry. + * @param headers - headers from the rejected response. + * @returns a positive delay for a numeric or HTTP-date Retry-After. + */ +export function retryAfterMs(headers?: Headers): number | undefined { + const retry = headers?.get('retry-after') + const delay = retry == null ? NaN : /^\d+(?:\.\d+)?$/u.test(retry) ? Number(retry) * 1000 : Date.parse(retry) - Date.now() + return Number.isFinite(delay) && delay > 0 ? delay : undefined +} + /** Classify a provider error without trusting arbitrary response fields. * @param raw - decoded response or in-band error event. * @param status - HTTP status when the error preceded streaming. @@ -35,12 +45,11 @@ export function providerError(raw: unknown, status: number | undefined, headers? else if (status === 400 || status === 413 || type === 'invalid_request_error') code = 'INVALID_REQUEST' else if ((status !== undefined && status >= 500) || ['api_error', 'overloaded_error'].includes(type)) code = 'SERVER' else code = status === undefined ? 'SERVER' : `HTTP_${status}` - const retry = headers?.get('retry-after') - const delay = retry == null ? NaN : /^\d+(?:\.\d+)?$/u.test(retry) ? Number(retry) * 1000 : Date.parse(retry) - Date.now() + const delay = retryAfterMs(headers) const id = headers?.get('request-id') ?? headers?.get('x-request-id') ?? headers?.get('x-deepseek-request-id') return new LlmError(message, code, { ...status === undefined ? {} : { status }, ...id ? { requestId: brandString(id) } : {}, - ...Number.isFinite(delay) && delay > 0 ? { providerRetryAfterMs: delay } : {}, + ...delay !== undefined ? { providerRetryAfterMs: delay } : {}, }) } diff --git a/packages/llm/llm-deepseek/tests/file-store.spec.ts b/packages/llm/llm-deepseek/tests/file-store.spec.ts index 72a2958bf3..fb7710f4b9 100644 --- a/packages/llm/llm-deepseek/tests/file-store.spec.ts +++ b/packages/llm/llm-deepseek/tests/file-store.spec.ts @@ -1,4 +1,5 @@ import { mkdtemp, rm } from 'node:fs/promises' +import { setTimeout as wait } from 'node:timers/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' @@ -9,6 +10,9 @@ 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' +import { adapter, chunks, options, requestImageStore, server, user } from './helpers.ts' + +vi.mock('node:timers/promises', { spy: true }) const REF: ImageAttachmentRef = { attachmentId: brandString(`sha256:${'a'.repeat(64)}`), @@ -30,7 +34,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. */ @@ -242,6 +249,139 @@ describe('DeepSeekFileStore', () => { expect(remote.uploads()).toBe(4) }) + it.each([ + { failures: [429, 429], retries: 2, uploads: 3, succeeds: true }, + { failures: [429, 429, 429], retries: 2, uploads: 3, succeeds: false }, + { failures: [429], retries: 0, uploads: 1, succeeds: false }, + { failures: [503], retries: 2, uploads: 1, succeeds: false }, + ])('bounds upload attempts for $failures with $retries retries', async ({ failures, retries, uploads, succeeds }) => { + const dir = await mkdtemp(join(tmpdir(), 'dsh-file-retries-')) + roots.push(dir) + const remote = uploadFetch() + const fetchImpl = vi.fn(remote.fetchImpl) + for (const status of failures) fetchImpl.mockResolvedValueOnce(new Response('busy', { status })) + const store = new DeepSeekFileStore({ index: new DeepSeekUploadIndex(join(dir, 'index.json')), fetch: fetchImpl, now: () => NOW }) + const result = store.ensureUploaded(VERSION, CONNECTION, { ...POLICY, uploadMaxRetries: retries, uploadRetryDelayMs: 1 }) + if (succeeds) await expect(result).resolves.toMatchObject({ uploaded: true }) + else await expect(result).rejects.toMatchObject({ failure: { status: failures.at(-1) } }) + expect(fetchImpl.mock.calls.map(([, init]) => init?.method)).toEqual(Array(uploads).fill('POST')) + }) + + it.each([ + { 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) + 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(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': '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') + vi.mocked(wait).mockImplementationOnce((ms, value, options) => { + scheduled.resolve(ms) + return timers.setTimeout(ms, value, options) + }) + const controller = new AbortController() + const pending = store.ensureUploaded(VERSION, CONNECTION, POLICY, controller.signal) + const result = expect(pending).rejects.toThrow('caller cancelled') + try { + expect(await scheduled.promise).toBe(30_000) + } finally { + controller.abort(new Error('caller cancelled')) + await result + } + expect(fetchImpl).toHaveBeenCalledTimes(1) + }) + + 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) + 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: 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 refs = ['c', 'd', 'e'].map(digit => ({ ...REF, attachmentId: brandString(`sha256:${digit.repeat(64)}`) })) + const attachments = requestImageStore(async ref => ({ + ...VERSION, attachment: ref, variantId: brandString(ref.attachmentId), + })) + const messages = await server() + try { + const route = adapter({ baseURL: messages.url, fileQuotaCleanupBatch: batch }, { + resolveAttachments: () => attachments, resolveFiles: () => store, + }) + await chunks(route.stream(options({ + model: 'deepseek-flash', + messages: [{ ...user(), content: refs.map(attachment => ({ type: 'image', attachment })) }], + }))) + expect(deleted.toSorted()).toEqual(['old-1', 'old-2', 'old-3']) + expect(lists).toBe(3 / batch) + expect(attempts).toBe(6) + expect(messages.requests).toHaveLength(1) + const body = JSON.stringify(messages.requests[0]!.body) + const wireIds = [...body.matchAll(/"file_id":"([^"]+)"/gu)].map(match => match[1]) + expect(wireIds.toSorted()).toEqual([...stored.keys()].toSorted()) + expect(body).not.toContain('"base64"') + } finally { + await messages.close() + } + }) + 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/packages/llm/llm-deepseek/tests/files.spec.ts b/packages/llm/llm-deepseek/tests/files.spec.ts index de09e7b1c2..3a86ad00c5 100644 --- a/packages/llm/llm-deepseek/tests/files.spec.ts +++ b/packages/llm/llm-deepseek/tests/files.spec.ts @@ -48,6 +48,60 @@ function harness(config: Config = {}) { afterEach(() => { vi.unstubAllGlobals() }) describe('Messages Files requests', () => { + it.each([undefined, 1] as const)('bounds concurrent uploads and preserves wire order with concurrency %s', async (limit) => { + const fetchImpl = vi.fn(async () => success()) + vi.stubGlobal('fetch', fetchImpl) + const h = harness(limit === undefined ? {} : { fileUploadConcurrency: limit }) + const images = ['a', 'b', 'c', 'd'].map(digit => ({ ...ref, attachmentId: brandString(`sha256:${digit.repeat(64)}`) })) + const gates = images.map(() => ({ started: Promise.withResolvers(), finish: Promise.withResolvers() })) + const resolve = h.ensureUploaded.getMockImplementation()! + h.ensureUploaded.mockImplementation(async (...args) => { + const index = images.indexOf(args[0].attachment) + gates[index]!.started.resolve(undefined) + await gates[index]!.finish.promise + const result = await resolve(...args) + return { ...result, record: { ...result.record, fileId: brandString(`file-${index}`) } } + }) + const stream = chunks(h.adapter.stream(request([...images, images[0]!]))) + const parallel = limit ?? 3 + try { + await gates[parallel - 1]!.started.promise + expect(h.ensureUploaded).toHaveBeenCalledTimes(parallel) + gates[parallel - 1]!.finish.resolve(undefined) + await gates[parallel]!.started.promise + } finally { + for (const gate of gates) gate.finish.resolve(undefined) + await stream + } + expect(h.ensureUploaded).toHaveBeenCalledTimes(4) + expect([...body(fetchImpl.mock.calls[0]![1]).matchAll(/"file_id":"(file-\d+)"/gu)].map(match => match[1])) + .toEqual(['file-0', 'file-1', 'file-2', 'file-3', 'file-0']) + }) + + it('cancels sibling uploads and leaves queued images for inline fallback', async () => { + const fetchImpl = vi.fn(async () => success()) + vi.stubGlobal('fetch', fetchImpl) + const h = harness() + const images = ['a', 'b', 'c', 'd'].map(digit => ({ ...ref, attachmentId: brandString(`sha256:${digit.repeat(64)}`) })) + const aborted = Promise.withResolvers() + const succeed = h.ensureUploaded.getMockImplementation()! + h.ensureUploaded + .mockRejectedValueOnce(new Error('offline')) + .mockImplementationOnce(async (...args) => { + await aborted.promise + return succeed(...args) + }) + .mockImplementationOnce(async (_version, _connection, _policy, signal) => new Promise((_resolve, reject) => { + signal!.addEventListener('abort', () => { + aborted.resolve(undefined) + reject(new Error('cancelled')) + }, { once: true }) + })) + await chunks(h.adapter.stream(request(images))) + expect(h.ensureUploaded).toHaveBeenCalledTimes(3) + expect(body(fetchImpl.mock.calls[0]![1]).match(/"type":"base64"/gu)).toHaveLength(4) + }) + it('keeps nested tool-result images in order and sends only Files ids with the beta header', async () => { const fetchImpl = vi.fn(async () => success()) vi.stubGlobal('fetch', fetchImpl) @@ -57,7 +111,10 @@ 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.any(Object), + ) 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 07432e6b14..9de52874d5 100644 --- a/packages/llm/llm-deepseek/tests/runtime.spec.ts +++ b/packages/llm/llm-deepseek/tests/runtime.spec.ts @@ -139,6 +139,22 @@ function fileStoreOf( } } +/** Opaque file ids reflect provider arrival order. Unrejected positions keep their original ids. */ +function expectFileReplacements(requests: readonly unknown[], count: number, rejected: readonly string[]): void { + expect(requests).toHaveLength(2) + const attempts = requests as Array<{ messages: Array<{ content: Array<{ type: string; source: { file_id: string } }> }> }> + const [first, second] = attempts.map(attempt => attempt.messages[0]!.content.filter(block => block.type === 'image').map(block => block.source.file_id)) + const ids = (start: number, size: number) => Array.from({ length: size }, (_, index) => `file-api-${start + index}`) + expect(first!.toSorted()).toEqual(ids(1, count).toSorted()) + expect(second).toHaveLength(count) + const replacements = [] + for (const [position, id] of first!.entries()) { + if (rejected.includes(id)) replacements.push(second![position]) + else expect(second![position]).toBe(id) + } + expect(replacements.toSorted()).toEqual(ids(count + 1, rejected.length).toSorted()) +} + function fileReference(fileId: string): Awaited> { return { record: { fileId: brandString(fileId) }, @@ -479,7 +495,7 @@ describe('DeepSeekAdapter against a mock server', () => { const body = server.requests[0] as { messages: Array<{ content: unknown }> } expect(JSON.stringify(body.messages[0]?.content).match(/"type":"image"/g)).toHaveLength(2) expect(JSON.stringify(body)).not.toContain('file_id') - expect(files.ensureUploaded).toHaveBeenCalledTimes(1) + expect(files.ensureUploaded).toHaveBeenCalledTimes(2) }) it('fails a base64 fallback whose retained images exceed the inline bound with the count to offload', async () => { @@ -536,43 +552,69 @@ describe('DeepSeekAdapter against a mock server', () => { expect(JSON.stringify(body)).not.toContain('file-api-partial') }) - it('sends successive image requests inline after one 20-second upload timeout', async () => { + it('counts each ten-image request once after upload timeouts and retries only after HTTP 429', async () => { vi.useFakeTimers() - const started = Promise.withResolvers() - const upload = vi.fn(async () => new Response(JSON.stringify({ + const started = Array.from({ length: 2 }, () => Promise.withResolvers()) + const throttled = Array.from({ length: 2 }, () => Promise.withResolvers()) + const upload = vi.fn(async () => Response.json({ 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 }) })) - const files = new Protocol.DeepSeekFileStore({ fetch: upload }) - const attachments = attachmentStoreOf(ref => Promise.resolve(requestImage(ref))).store + for (const [round, gate] of started.entries()) { + upload.mockImplementationOnce((_url, init) => new Promise((_resolve, reject) => { + gate.resolve(undefined) + init!.signal!.addEventListener('abort', () => { reject(new Error('upload aborted')) }, { once: true }) + })).mockImplementationOnce(async () => { + throttled[round]!.resolve(undefined) + return new Response(null, { status: 429 }) + }) + } + const index = new Protocol.DeepSeekUploadIndex() + vi.spyOn(index, 'get').mockResolvedValue(undefined) + const files = new Protocol.DeepSeekFileStore({ fetch: upload, index }) + const attachments = attachmentStoreOf(ref => Promise.resolve({ + ...requestImage(ref), variantId: brandString(ref.attachmentId), + })).store const messages = vi.spyOn(globalThis, 'fetch').mockImplementation(async () => successfulSseResponse()) const adapter = adapterOf({ baseURL: 'https://deepseek.invalid' }, attachments, files) - const second = { ...imageRef, attachmentId: brandString(`sha256:${'c'.repeat(64)}`) } + const ten = Array.from({ length: 10 }, (_, i) => ({ + ...imageRef, attachmentId: brandString(`sha256:${i.toString(16).repeat(64)}`), + })) const request = (images = [imageRef]) => drain(adapter.stream({ provider: 'deepseek-official', model: 'deepseek-flash', messages: [createUserMessage({ content: images.map(attachment => ({ type: 'image', attachment })), source: { kind: 'user' } })], })) 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([imageRef, second]) - expect(upload).toHaveBeenCalledTimes(1) - expect(messages).toHaveBeenCalledTimes(3) - expect(messages.mock.calls[0]?.[1]?.body).toEqual(expect.stringContaining('base64')) - 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')) + for (const [round, gate] of started.entries()) { + const timedOut = request() + const priorMessages = messages.mock.calls.length + if (round > 0) { + await throttled[round - 1]!.promise + await vi.advanceTimersByTimeAsync(500) + } + await gate.promise + await vi.advanceTimersByTimeAsync(round === 0 ? 19_999 : 19_499) + expect(messages).toHaveBeenCalledTimes(priorMessages) + await vi.advanceTimersByTimeAsync(1) + await timedOut + const expectedPosts = round === 0 ? 1 : 3 + expect(upload).toHaveBeenCalledTimes(expectedPosts) + expect(messages.mock.lastCall?.[1]?.body).toEqual(expect.stringContaining('base64')) + await vi.advanceTimersByTimeAsync(3_600_000) + await drain(adapter.stream({ provider: 'deepseek-official', model: 'deepseek-flash', messages: [] })) + for (let skip = 0; skip < 2 ** round; skip++) { + await request(ten) + const inline = messages.mock.lastCall?.[1]?.body + expect(typeof inline === 'string' && inline.match(/"type":"base64"/gu)).toHaveLength(10) + expect(upload).toHaveBeenCalledTimes(expectedPosts) + } + } + const recovered = request() + await throttled[1]!.promise + await vi.advanceTimersByTimeAsync(500) + await recovered + expect(upload).toHaveBeenCalledTimes(5) + expect(messages.mock.lastCall?.[1]?.body).toEqual(expect.stringContaining('file-probe')) } finally { messages.mockRestore() } @@ -959,11 +1001,7 @@ describe('DeepSeekAdapter against a mock server', () => { })) expect(server.fileRequests.filter(request => request.method === 'POST')).toHaveLength(3) - const retries = server.requests as Array<{ messages: Array<{ content: Array<{ type: string; file_id?: string }> }> }> - expect(retries[0]?.messages[0]?.content.filter(block => block.type === 'image')) - .toEqual([{ type: 'image', source: { type: 'file', file_id: 'file-api-1' } }, { type: 'image', source: { type: 'file', file_id: 'file-api-2' } }]) - expect(retries[1]?.messages[0]?.content.filter(block => block.type === 'image')) - .toEqual([{ type: 'image', source: { type: 'file', file_id: 'file-api-1' } }, { type: 'image', source: { type: 'file', file_id: 'file-api-3' } }]) + expectFileReplacements(server.requests, 2, ['file-api-2']) }) it('invalidates every listed missing file id and preserves unlisted mappings', async () => { @@ -1016,19 +1054,7 @@ describe('DeepSeekAdapter against a mock server', () => { })) expect(server.fileRequests.filter(request => request.method === 'POST')).toHaveLength(5) - const retries = server.requests as Array<{ messages: Array<{ content: Array<{ type: string; file_id?: string }> }> }> - expect(retries[0]?.messages[0]?.content.filter(block => block.type === 'image')) - .toEqual([ - { type: 'image', source: { type: 'file', file_id: 'file-api-1' } }, - { type: 'image', source: { type: 'file', file_id: 'file-api-2' } }, - { type: 'image', source: { type: 'file', file_id: 'file-api-3' } }, - ]) - expect(retries[1]?.messages[0]?.content.filter(block => block.type === 'image')) - .toEqual([ - { type: 'image', source: { type: 'file', file_id: 'file-api-4' } }, - { type: 'image', source: { type: 'file', file_id: 'file-api-2' } }, - { type: 'image', source: { type: 'file', file_id: 'file-api-5' } }, - ]) + expectFileReplacements(server.requests, 3, ['file-api-1', 'file-api-3']) }) it('recovers in one replacement request when the provider lists dozens of missing file ids', async () => { @@ -1071,15 +1097,7 @@ describe('DeepSeekAdapter against a mock server', () => { expect(server.requests).toHaveLength(2) expect(server.fileRequests.filter(request => request.method === 'POST')).toHaveLength(70) - const attempts = server.requests as Array<{ messages: Array<{ content: Array<{ type: string; source?: { file_id?: string } }> }> }> - const fileIds = (attempt: number) => attempts[attempt]?.messages[0]?.content - .filter(block => block.type === 'image') - .map(block => block.source?.file_id) - expect(fileIds(0)).toEqual(refs.map((_, index) => `file-api-${index + 1}`)) - expect(fileIds(1)).toEqual([ - ...missing.map((_, index) => `file-api-${41 + index}`), - ...refs.slice(30).map((_, index) => `file-api-${31 + index}`), - ]) + expectFileReplacements(server.requests, 40, missing) }) it('invalidates every used mapping when a stale-file response does not identify one file id', async () => { @@ -1117,9 +1135,7 @@ describe('DeepSeekAdapter against a mock server', () => { })) expect(server.fileRequests.filter(request => request.method === 'POST')).toHaveLength(4) - const retries = server.requests as Array<{ messages: Array<{ content: Array<{ type: string; file_id?: string }> }> }> - expect(retries[1]?.messages[0]?.content.filter(block => block.type === 'image')) - .toEqual([{ type: 'image', source: { type: 'file', file_id: 'file-api-3' } }, { type: 'image', source: { type: 'file', file_id: 'file-api-4' } }]) + expectFileReplacements(server.requests, 2, ['file-api-1', 'file-api-2']) }) it('returns the second stale-file rejection without a third model attempt', async () => { @@ -2182,6 +2198,15 @@ describe('plugin registration and config', () => { ['fileExpiresAfterSeconds', 2_592_001, /fileExpiresAfterSeconds must be an integer from 3600 through 2592000/], ['fileRefreshMarginSeconds', -1, /fileRefreshMarginSeconds must be a non-negative integer/], ['fileRefreshMarginSeconds', 604_800, /fileRefreshMarginSeconds must be a non-negative integer/], + ['fileUploadConcurrency', 0, /fileUploadConcurrency/], + ['fileUploadConcurrency', 4, /fileUploadConcurrency/], + ['fileUploadConcurrency', 1.5, /fileUploadConcurrency/], + ['fileUploadMaxRetries', -1, /fileUploadMaxRetries/], + ['fileUploadMaxRetries', 3, /fileUploadMaxRetries/], + ['fileUploadMaxRetries', 1.5, /fileUploadMaxRetries/], + ['fileUploadRetryDelayMs', 0, /fileUploadRetryDelayMs/], + ['fileUploadRetryDelayMs', MAX_TIMER_DELAY_MS + 1, /fileUploadRetryDelayMs/], + ['fileUploadRetryDelayMs', 1.5, /fileUploadRetryDelayMs/], ['fileQuotaCleanupBatch', 0, /fileQuotaCleanupBatch must be an integer from 1 through 1000/], ['fileQuotaCleanupBatch', 1_001, /fileQuotaCleanupBatch must be an integer from 1 through 1000/], ] as const)('rejects %s=%s', (field, value, message) => { diff --git a/python/sdk/tests/test_commands_runtime.py b/python/sdk/tests/test_commands_runtime.py index a0545ebc07..d72edcfcad 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":