Back off timed-out Files uploads across image requests
This commit is contained in:
1 parent
300f3f3498
commit
3e4b55cc25
11 files changed
+183
-50
No files matched your search
@@ -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
|
||||
|
||||
@@ -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 "<id>" 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.
|
||||
|
||||
@@ -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 "<id>" 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,以及可用时的规范化尺寸、媒体类型与当前只读路径。分阶高水位策略避免每新增一张图片都改写旧请求前缀。
|
||||
|
||||
@@ -43,7 +43,7 @@ export interface Config {
|
||||
inlineImageOffloadByteQuantum: Volatile<number>
|
||||
/** Image-count removal step after the request exceeds its count bound (default 20). */
|
||||
imageOffloadCountQuantum: Volatile<number>
|
||||
/** 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<number>
|
||||
/** Explicit lifetime assigned to each uploaded image (default seven days). */
|
||||
fileExpiresAfterSeconds: Volatile<number>
|
||||
|
||||
@@ -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
|
||||
@@ -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<DeepSeekUploadRecord['scope'], UploadBackoff>()
|
||||
private readonly inflight = new Map<string, SharedUpload>()
|
||||
|
||||
/**
|
||||
@@ -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<DeepSeekFileReference> {
|
||||
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<DeepSeekFileReference> {
|
||||
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<DeepSeekFileReference> {
|
||||
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<DeepSeekUploadRecord> => {
|
||||
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,
|
||||
|
||||
@@ -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<DeepSeekFileId> {
|
||||
using limit = deadline(this.signal, this.timeoutMs, 'DEEPSEEK_FILES_API_TIMEOUT')
|
||||
using limit = deadline(this.signal, this.timeoutMs, FILES_API_TIMEOUT)
|
||||
let resolved: Awaited<ReturnType<DeepSeekFileStore['ensureUploaded']>>
|
||||
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)
|
||||
|
||||
@@ -119,9 +119,9 @@ export class DeepSeekUploadIndex {
|
||||
this.path = path
|
||||
}
|
||||
|
||||
private async load(): Promise<StoredIndex> {
|
||||
private async load(signal?: AbortSignal): Promise<StoredIndex> {
|
||||
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<DeepSeekUploadRecord | undefined> {
|
||||
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
|
||||
|
||||
@@ -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<ImageVariantId>(`sha256:${'c'.repeat(64)}`) }
|
||||
await store.ensureUploaded(cached, CONNECTION, POLICY)
|
||||
async function expire(image: RequestImageAttachment) {
|
||||
const started = Promise.withResolvers<undefined>()
|
||||
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<ImageVariantId>(`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<ImageVariantId>(`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<undefined>()
|
||||
const response = Promise.withResolvers<Response>()
|
||||
fetch.mockImplementationOnce(() => { started.resolve(undefined); return response.promise })
|
||||
const image = { ...VERSION, variantId: brandString<ImageVariantId>(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)
|
||||
|
||||
@@ -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')
|
||||
|
||||
@@ -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<undefined>()
|
||||
const files = fileStoreOf((_version, _connection, _policy, signal) => new Promise((_resolve, reject) => {
|
||||
const upload = vi.fn<typeof fetch>((_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 () => {
|
||||
|
||||
Reference in new issue
Block a user