Files
deepseek-harness/packages/experimental/forge-github/tests/plugin.spec.ts
T
LegGasai 5b7aaab289 fix(forge): give each provider call of a status fetch its own deadline
One fetch of the registry called the provider once with every due change
request of a forge, under one fetchTimeoutMs deadline. forge-github read
that call in several queries, so a read of many pull requests could
outlive the deadline as a whole, and a query whose gh run hung ended the
read before its own timeout isolated it. Either way the results of the
queries already answered were discarded.

A provider may now name snapshotBatchSize and briefBatchSize. The
registry then calls it once per that many due change requests of a host,
one call after another, each within its own fetchTimeoutMs, and settles
the watches of a call when it returns. A call that fails or outlives its
deadline fails only its own change requests. A change request that lost
its watchers while it waited is not read, and one whose watchers changed
what its polls read is read by the fetch of that level.

forge-github names its two query sizes, so one polling call holds one
query. briefBatchSize now defaults to 25: a query of 50 took up to 6.8
seconds against GitHub's 10-second limit, and one of 25 up to 3.4.

The subsystem page and the Cordis catalog also take in the signatures
the three commits before this one added.
2026-11-19 13:27:44 +08:00

203 lines
9.4 KiB
TypeScript

import { Context, Service } from '@deepseek-ai/cordis'
import ForgeService from '@deepseek-ai/dsh-experimental-forge'
import type { ChangeRequestKey } from '@deepseek-ai/dsh-experimental-forge'
import type { ForgeCommandRule } from '@deepseek-ai/dsh-experimental-forge-session'
import { chmod, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { GH_COMMANDS } from '../src/commands.ts'
import * as ForgeGitHub from '../src/index.ts'
import { briefNode, pull, pullRequestNode } from './fixtures.ts'
let ctx: Context | undefined
afterEach(async () => {
await ctx?.fiber.dispose()
ctx = undefined
})
/** Command rules registered with {@link RecordingForgeSession} whose registering fiber is live. */
const registered = new Set<ForgeCommandRule>()
/** A `forgeSession` service that records command rule registrations in {@link registered}. */
class RecordingForgeSession extends Service {
constructor(ctx: Context) {
super(ctx, 'forgeSession')
}
registerCommands(rule: ForgeCommandRule): () => void {
const dispose = this.ctx.effect(() => {
registered.add(rule)
return () => { registered.delete(rule) }
})
return () => void dispose()
}
}
async function forge(): Promise<Context> {
ctx = new Context()
await ctx.plugin(ForgeService)
return ctx
}
describe('forge-github plugin', () => {
it('registers the GitHub provider for the configured hosts', async () => {
const context = await forge()
await context.plugin(ForgeGitHub, { hosts: ['github.com', 'ghe.corp.example'] })
expect(context.forge.changeRequestFromUrl('https://github.com/octo/demo/pull/1')).toEqual({
repository: { forge: 'github', host: 'github.com', owner: 'octo', name: 'demo' },
number: 1,
})
expect(context.forge.repositoryFromRemote('[email protected]:team/svc.git')).toEqual({ forge: 'github', host: 'ghe.corp.example', owner: 'team', name: 'svc' })
})
it('serves github.com by default', async () => {
const context = await forge()
await context.plugin(ForgeGitHub, {})
expect(context.forge.repositoryFromRemote('https://github.com/octo/demo.git')).toBeDefined()
expect(context.forge.repositoryFromRemote('https://ghe.corp.example/team/svc.git')).toBeUndefined()
})
it('offers the three viewer lists on its hosts, 50 pull requests per read by default', async () => {
const context = await forge()
await context.plugin(ForgeGitHub, { hosts: ['github.com', 'ghe.corp.example'] })
expect(context.forge.viewerSources()).toEqual([{
forge: 'github', hosts: ['github.com', 'ghe.corp.example'], filters: new Set(['review-requested', 'authored', 'involved']), maxItems: 50,
}])
})
it('registers the gh commands with forge-session while both run', async () => {
const context = await forge()
await context.plugin(RecordingForgeSession)
const fiber = context.plugin(ForgeGitHub, {})
await fiber
expect([...registered]).toEqual([GH_COMMANDS])
await fiber.dispose()
expect(registered.size).toBe(0)
})
it('unregisters the provider when its fiber is disposed', async () => {
const context = await forge()
const fiber = context.plugin(ForgeGitHub, {})
await fiber
await fiber.dispose()
expect(context.forge.changeRequestFromUrl('https://github.com/octo/demo/pull/1')).toBeUndefined()
})
it.each([
[{ ghCommand: ' ' }, 'forge-github: ghCommand must not be empty'],
[{ hosts: [] }, 'forge-github: hosts must list at least one host'],
[{ hosts: ['https://github.com'] }, 'forge-github: invalid host "https://github.com"'],
[{ timeoutMs: 0 }, 'forge-github: timeoutMs must be a positive integer no greater than 2147483647'],
[{ timeoutMs: 2_147_483_648 }, 'forge-github: timeoutMs must be a positive integer no greater than 2147483647'],
[{ timeoutMs: 1.5 }, 'forge-github: timeoutMs must be a positive integer no greater than 2147483647'],
[{ maxOutputBytes: 1.5 }, 'forge-github: maxOutputBytes must be a positive safe integer'],
[{ maxOutputBytes: 0 }, 'forge-github: maxOutputBytes must be a positive safe integer'],
[{ maxOutputBytes: Number.MAX_SAFE_INTEGER + 1 }, 'forge-github: maxOutputBytes must be a positive safe integer'],
[{ snapshotBatchSize: 0 }, 'forge-github: snapshotBatchSize must be a positive safe integer'],
[{ snapshotBatchSize: 2.5 }, 'forge-github: snapshotBatchSize must be a positive safe integer'],
[{ maxCommits: 0 }, 'forge-github: maxCommits must be a positive safe integer'],
[{ maxCommits: 2.5 }, 'forge-github: maxCommits must be a positive safe integer'],
[{ maxReviewThreads: 0 }, 'forge-github: maxReviewThreads must be a positive safe integer'],
[{ maxReviewThreads: 2.5 }, 'forge-github: maxReviewThreads must be a positive safe integer'],
[{ briefBatchSize: 0 }, 'forge-github: briefBatchSize must be a positive safe integer'],
[{ briefBatchSize: 2.5 }, 'forge-github: briefBatchSize must be a positive safe integer'],
[{ maxViewerItems: 0 }, 'forge-github: maxViewerItems must be a positive safe integer'],
[{ maxViewerItems: 101 }, 'forge-github: maxViewerItems must be no greater than 100'],
])('rejects %j at load', async (config, message) => {
const context = await forge()
await expect(context.plugin(ForgeGitHub, config)).rejects.toThrow(message)
})
it('does not apply timer limits to the output byte budget', async () => {
const context = await forge()
await context.plugin(ForgeGitHub, { maxOutputBytes: 2_147_483_648 })
expect(context.forge.repositoryFromRemote('https://github.com/octo/demo.git')).toBeDefined()
})
})
// The recording `gh` is a POSIX shell script, as in gh.spec.ts.
describe.skipIf(process.platform === 'win32')('forge-github plugin status queries', () => {
const cleanups: (() => Promise<void>)[] = []
afterEach(async () => {
for (const cleanup of cleanups.splice(0).reverse()) await cleanup()
})
/**
* A `gh` that appends the pull request numbers of each query to a log and answers `node` for each; a query that
* names pull request `hangOn` never answers.
*/
async function recordingGh(
node: Record<string, unknown>, hangOn?: number,
): Promise<{ readonly command: string; readonly queries: () => Promise<number[][]> }> {
const root = await mkdtemp(join(tmpdir(), 'forge-github-status-'))
cleanups.push(async () => { await rm(root, { recursive: true, force: true }) })
const command = join(root, 'gh')
const log = join(root, 'queries.log')
await writeFile(command, [
'#!/bin/sh',
'numbers=$(printf "%s" "$*" | grep -o "pullRequest(number: [0-9]*)" | grep -o "[0-9]*" | tr "\\n" " ")',
`printf "%s\\n" "$numbers" >> ${JSON.stringify(log)}`,
...hangOn === undefined ? [] : [`case " $numbers" in *" ${hangOn} "*) exec sleep 60;; esac`],
'fields=""; index=0',
`for number in $numbers; do fields="$fields\${fields:+,}\\"p$index\\":"${JSON.stringify(JSON.stringify(node))}; index=$((index + 1)); done`,
'printf "{\\"data\\":{\\"r0\\":{%s}}}" "$fields"',
'',
].join('\n'))
await chmod(command, 0o755)
return {
command,
queries: async () => (await readFile(log, 'utf8')).trim().split('\n').map(line => line.trim().split(' ').map(Number)),
}
}
it.each([
['brief', {}, 51, [25, 25, 1]],
['brief', { briefBatchSize: 3 }, 4, [3, 1]],
['snapshot', {}, 9, [8, 1]],
['snapshot', { snapshotBatchSize: 3 }, 4, [3, 1]],
] as const)('polls %s watches of the forge service in queries of the configured size: %j', async (level, config, count, sizes) => {
const gh = await recordingGh(level === 'brief' ? briefNode(0) : pullRequestNode(0))
const context = new Context()
cleanups.push(async () => { await context.fiber.dispose() })
await context.plugin(ForgeService)
await context.plugin(ForgeGitHub, { ghCommand: gh.command, ...config })
const seen = new Set<ChangeRequestKey>()
for (const ref of Array.from({ length: count }, (_, index) => pull(index + 1))) {
if (level === 'brief') context.forge.watchBrief(ref, update => void ('brief' in update && seen.add(update.key)))
else context.forge.watch(ref, update => void ('snapshot' in update && seen.add(update.key)))
}
await vi.waitFor(() => { expect(seen.size).toBe(count) }, { timeout: 10_000 })
expect((await gh.queries()).map(numbers => numbers.length)).toEqual(sizes)
})
it('gives each query a fetch deadline of its own, so a query whose gh run hangs fails only its own pull requests', async () => {
const gh = await recordingGh(pullRequestNode(0), 1)
const context = new Context()
cleanups.push(async () => { await context.fiber.dispose() })
// The deadline of the registry equals the one of a `gh` run, as it does by default.
await context.plugin(ForgeService, { fetchTimeoutMs: 1_000 })
await context.plugin(ForgeGitHub, { ghCommand: gh.command, timeoutMs: 1_000, snapshotBatchSize: 2 })
const outcomes = new Map<number, string>()
for (const number of [1, 2, 3, 4]) {
context.forge.watch(pull(number), (update) => { outcomes.set(number, 'failure' in update ? update.failure.code : 'snapshot') })
}
await vi.waitFor(() => { expect(outcomes.size).toBe(4) }, { timeout: 10_000 })
expect([...outcomes].sort(([left], [right]) => left - right)).toEqual([[1, 'unavailable'], [2, 'unavailable'], [3, 'snapshot'], [4, 'snapshot']])
expect(await gh.queries()).toEqual([[1, 2], [3, 4]])
})
})