DeepSeek Harness 防御性编程:报告、清理与凭据
对自建子进程、临时文件与内存会话验证边界条件。
学完这一章,你能够
- 对自建子进程、临时文件与内存会话验证边界条件。
先确定需要观察哪些事实
插件在结束、取消、异步回调及边界资源处理时也要维持契约。用固定的小任务分别观察每个结果字段、退出后的资源状态、环境筛选、链接与其目标,以及异常之后的分发顺序。下面的例子只管理自己创建的进程和文件。
把超时、退出码与信号分开记录
timedOut 记录本次期限是否已经到达,signal 表示实际终止信号,exitCode 是进程报告的退出码。三项各自读取,不能因为 exitCode 是 0 就清除超时。超时后退出码仍是 0 可来自程序配合退出,不能据此判断它被强制终止。实验用真实子进程的协作停止消息观察超时加 0,再单独观察由信号终止的结果。
清理到实际完成再返回
创建进程时先把 close、error 与输出收集接好。清理时停止可选通知,保留完成等待和最终输出收集。发出停止请求后等待 close,同一个组件重复 dispose 复用同一个完成承诺。超出宽限期可终止该组件启动的子进程,仍等待实际关闭并清理计时器。通用代码不能只等待 kill 返回或超时计时器完成。实验分别观察协作停止与忽略停止后的强制结束。
给子进程和暂存文件各自设边界
子进程只接收确实需要的环境项。Harness 过滤带 KEY、SECRET、TOKEN、PASSWORD 的键以及内部 DSH_ 前缀。名称过滤对值中的秘密无能为力,按用途传允许清单更稳妥。用合成值验证筛选,避免把实际凭据写进日志或测试输出。Unix 风格的暂存建议是随机目录、目录权限 0700、文件权限 0600、独占方式 wx;Windows 的实际访问控制由 ACL 负责。实验观察重复创建收到 EEXIST,原字节仍在。
移除链接对象,确认目标还在
lstat 查看路径项本身。仅对已知应清理且确认是链接的本地路径使用 unlink,再检查目标仍存在。真实目录属于独立的删除分支,先验证所有权和范围。早期说明提过 Windows junction 的非递归 rmSync 可能报告 ERR_FS_EISDIR,本次 Node.js 24.22.3 在 Windows 实测成功移除临时 junction,目标保留。这里用 unlink 表达删除链接的意图,并验证真实目录拒绝该操作。
单独处置观察者失败和外部结果契约
对观察型回调逐个捕获同步异常,并接住 Promise 拒绝。记录各错误,继续调用健康观察者。已提交的事件仍有效,监听器自身的状态恢复由它负责。实验在真实 SessionStore 注册两个失败观察者和一个健康观察者,并核对写入的 turn/start 仍然存在。
公共 API 应把同一类别的结果归一为稳定形状,便于使用者按原因判断。区分观察整个 Agent 的 whenIdle 和单条输入的 followup。需要报告某次运行时,使用调用方实际拥有且能观测的区间,交代多个输入共用区间及无需等转换的分支。最后复查超时加退出码 0、强制停止后等待和链接目标保留三个案例。
两组容易混淆的约定
| 模式 | 实际含义 |
|---|---|
| 公共约定两侧一致 | 在公共接口记录及返回可区分的规范结果。样本观察实际适配器的错误归一函数;应用级分片行为沿用第25章的运行证据。 |
| 异步状态有自己的观察范围 | Agent 进入 idle 可能覆盖多条输入。依据调用方明确拥有的区间报告,避免把状态当某条 followup 的逐条结果。 |
边界行为自测
| 问题 | 结论 |
|---|---|
| 超时与 0 是否能同时出现? | 可以。样本期限已过,同时收到工作进程的正常退出码。 |
| 发出终止请求就完成清理了吗? | 还须等待实际关闭;样本在更强终止分支也等待 close。 |
| 怎样移除一个已知的链接? | 用 lstat 识别路径项后 unlink,并验证真实目标及内容仍在。 |
观察进程退出、暂存文件和会话分发
import assert from 'node:assert/strict'
import { createHash, randomUUID } from 'node:crypto'
import { spawn } from 'node:child_process'
import fs from 'node:fs'
import { createRequire, isBuiltin, registerHooks } from 'node:module'
import path from 'node:path'
import { pathToFileURL, fileURLToPath } from 'node:url'
const repo = path.resolve(process.argv[2])
const fixture = path.resolve(process.argv[3])
assert.deepEqual(fs.readdirSync(fixture), [], 'Use an empty temporary directory')
const base = pathToFileURL(repo + path.sep).href
const store = path.join(repo, 'node_modules', '.pnpm')
const require = createRequire(import.meta.url)
const ts = require(path.join(store, 'typescript@6.0.3/node_modules/typescript/lib/typescript.js'))
const cachedPackages = fs.readdirSync(store)
const pinned = new Map([['ajv', 'ajv@8.20.0']])
const packageRoots = new Map()
const sourceHashes = {}
const digest = (text) => createHash('sha256').update(text).digest('hex')
const fileUrl = (name) => pathToFileURL(name).href
const directories = (folder) => fs.readdirSync(folder, { withFileTypes: true })
.filter((entry) => entry.isDirectory()).map((entry) => path.join(folder, entry.name))
const read = (name) => JSON.parse(fs.readFileSync(name, 'utf8'))
for (const folder of [
...directories(path.join(repo, 'vendor')),
...directories(path.join(repo, 'packages')).flatMap(directories),
...directories(path.join(repo, 'apps')),
]) {
const manifest = path.join(folder, 'package.json')
if (fs.existsSync(manifest)) packageRoots.set(read(manifest).name, folder)
}
registerHooks({
resolve(specifier, context, nextResolve) {
if (isBuiltin(specifier) || /^(?:[./]|[a-z]+:)/i.test(specifier)) {
return nextResolve(specifier, context)
}
const segments = specifier.split('/')
const name = segments.splice(0, specifier.startsWith('@') ? 2 : 1).join('/')
const subpath = segments.join('/')
const root = packageRoots.get(name)
if (root) {
return nextResolve(fileUrl(path.join(root, subpath || 'src/index.ts')), context)
}
try {
return nextResolve(specifier, context)
} catch (error) {
if (error.code !== 'ERR_MODULE_NOT_FOUND' && error.code !== 'MODULE_NOT_FOUND') throw error
if (!context.parentURL?.startsWith(base)) throw error
const matches = cachedPackages.filter((entry) => entry.startsWith(name.replace('/', '+') + '@'))
const cached = pinned.get(name) ?? (matches.length === 1 ? matches[0] : undefined)
if (!cached) throw error
return nextResolve(specifier, { ...context, parentURL: fileUrl(path.join(store, cached, 'loader.mjs')) })
}
},
load(url, context, nextLoad) {
if (!url.startsWith(base) || !url.endsWith('.ts')) return nextLoad(url, context)
const filename = fileURLToPath(url)
const input = fs.readFileSync(filename, 'utf8')
sourceHashes[path.relative(repo, filename).split(path.sep).join('/')] = digest(input)
const output = ts.transpileModule(input, { compilerOptions: { module: ts.ModuleKind.ESNext, target: ts.ScriptTarget.ES2022 } })
return { format: 'module', source: output.outputText, shortCircuit: true }
},
})
const cases = []
function expect(name, input, expected, actual) {
assert.deepEqual(actual, expected, name)
cases.push({ name, input, expected, actual, passed: true })
}
const workerSource = [
'process.send({ type: "ready", exposed: Object.keys(process.env).filter(name => /^LESSON_/.test(name)).sort() })',
'process.on("message", (msg) => {',
' if (msg === "stop" && process.argv[1] !== "ignore-stop") {',
' process.send({ type: "optional" })',
' process.stdout.write("final card result", () => process.disconnect())',
' }',
'})',
].join('\n')
const approvedNames = new Set(['LESSON_LOCALE', 'SYSTEMROOT'])
function selectEnvironment(entries) {
return Object.fromEntries(Object.entries(entries).filter(([name, value]) =>
typeof value === 'string' && approvedNames.has(name.toUpperCase())))
}
const synthetic = {
LESSON_LOCALE: 'zh-CN', LESSON_API_KEY: 'not-a-credential', LESSON_SECRET: 'not-a-credential',
LESSON_TOKEN: 'not-a-credential', LESSON_PASSWORD: 'not-a-credential', LESSON_PRIVATE_CONTEXT: 'omit too',
}
const env = selectEnvironment({ ...synthetic, SystemRoot: process.env.SystemRoot ?? process.env.SYSTEMROOT })
function startWorker(mode = 'normal') {
const child = spawn(process.execPath, ['-e', workerSource, mode], {
shell: false, windowsHide: true, cwd: fixture, env, stdio: ['ignore', 'pipe', 'pipe', 'ipc'],
})
const ready = Promise.withResolvers()
const stdout = []
const stderr = []
const listeners = new Set()
let deadlinePassed = false
let closed = false
let disposing
let error
let graceTimer
const watchdog = setTimeout(() => child.kill('SIGKILL'), 5000)
child.stdout.on('data', (data) => stdout.push(data))
child.stderr.on('data', (data) => stderr.push(data))
child.on('message', (message) => {
if (message.type === 'ready') ready.resolve(message.exposed)
if (message.type === 'optional') for (const listener of listeners) listener()
})
child.once('error', (e) => { error = e; ready.reject(e) })
const done = new Promise((resolve, reject) => {
child.once('close', (exitCode, signal) => {
closed = true
clearTimeout(watchdog)
clearTimeout(graceTimer)
ready.reject(error ?? new Error('Worker closed before its handshake'))
if (error) reject(error)
else resolve({ timedOut: deadlinePassed, exitCode, signal,
stdout: Buffer.concat(stdout).toString('utf8'), stderr: Buffer.concat(stderr).toString('utf8') })
})
})
void ready.promise.catch(() => {})
void done.catch(() => {})
function dispose() {
if (disposing !== undefined) return disposing
listeners.clear()
if (!closed) {
if (child.connected) child.send('stop', () => {})
graceTimer = setTimeout(() => child.kill('SIGKILL'), 300)
}
disposing = done
return disposing
}
return { ready: ready.promise, done, listen: (listener) => listeners.add(listener), dispose,
deadline: () => { deadlinePassed = true; return dispose() },
signal: () => child.kill('SIGTERM'),
hasClosed: () => closed }
}
let run = startWorker()
const exposed = await run.ready
expect('only_allowlisted_synthetic_variables_reach_real_child', 'launch only the owned local worker',
{ exposed: ['LESSON_LOCALE'], sourceKeysRemain: 6 }, { exposed, sourceKeysRemain: Object.keys(synthetic).length })
let notifications = 0
run.listen(() => { notifications += 1 })
const returned = run.dispose()
const sameClose = run.dispose()
const disposed = await returned
expect('dispose_waits_for_close_and_final_output', 'dispose after handshake without exposing late optional notifications',
{ closed: true, output: 'final card result', notifications: 0, samePromise: true },
{ closed: run.hasClosed(), output: disposed.stdout, notifications, samePromise: returned === sameClose })
expect('normal_worker_reports_all_fields', 'graceful stop with no expired timer',
[false, 0, null], [disposed.timedOut, disposed.exitCode, disposed.signal])
run = startWorker()
await run.ready
const deadline = await new Promise((resolve, reject) => {
setTimeout(() => run.deadline().then(resolve, reject), 20)
})
expect('deadline_can_coexist_with_zero_exit', '20ms real deadline followed by cooperative IPC shutdown',
[true, 0, null, 'final card result'], [deadline.timedOut, deadline.exitCode, deadline.signal, deadline.stdout])
run = startWorker()
await run.ready
assert.equal(run.signal(), true)
const signalled = await run.done
expect('signalled_child_reports_signal_without_exit_code', 'signal only the owned worker after its handshake',
[false, null, 'SIGTERM'], [signalled.timedOut, signalled.exitCode, signalled.signal])
run = startWorker('ignore-stop')
await run.ready
const forced = await run.dispose()
expect('forced_stop_still_awaits_actual_child_close', 'ignore cooperative stop and terminate the owned child after the grace window',
[true, null, 'SIGKILL'], [run.hasClosed(), forced.exitCode, forced.signal])
const privateDir = path.join(fixture, 'spill-' + randomUUID())
fs.mkdirSync(privateDir, { mode: 0o700 })
const spillPath = path.join(privateDir, randomUUID() + '.txt')
const fd = fs.openSync(spillPath, 'wx', 0o600)
try { fs.writeFileSync(fd, 'public demo line\n', 'utf8') } finally { fs.closeSync(fd) }
let collision
try {
const duplicate = fs.openSync(spillPath, 'wx', 0o600)
fs.closeSync(duplicate)
} catch (error) {
collision = error.code
}
expect('exclusive_spill_creation_preserves_existing_bytes', 'try exclusive creation twice at the owned test path',
{ second: 'EEXIST', bytes: 'public demo line\n' }, { second: collision, bytes: fs.readFileSync(spillPath, 'utf8') })
if (process.platform !== 'win32') {
expect('posix_rights_restrict_access_to_owner', 'stat own spill directory and file',
[0o700, 0o600], [fs.statSync(privateDir).mode & 0o777, fs.statSync(spillPath).mode & 0o777])
}
const target = path.join(fixture, 'actual-directory')
fs.mkdirSync(target)
const marker = path.join(target, 'keep.txt')
fs.writeFileSync(marker, 'preserve target', 'utf8')
const link = path.join(fixture, 'owned-directory-link')
fs.symlinkSync(target, link, process.platform === 'win32' ? 'junction' : 'dir')
const isLink = fs.lstatSync(link).isSymbolicLink()
assert.equal(isLink, true)
fs.unlinkSync(link)
expect('unlink_preserves_actual_directory_and_contents', 'unlink a verified lab-owned link',
{ linkRemoved: true, originalDirectory: true, marker: 'preserve target' },
{ linkRemoved: !fs.existsSync(link), originalDirectory: fs.statSync(target).isDirectory(), marker: fs.readFileSync(marker, 'utf8') })
if (process.platform === 'win32') {
const secondLink = path.join(fixture, 'test-nonrecursive-rm')
fs.symlinkSync(target, secondLink, 'junction')
let result
try {
fs.rmSync(secondLink)
result = 'removed'
} catch (error) {
result = error.code
} finally {
if (fs.existsSync(secondLink)) {
assert.equal(fs.lstatSync(secondLink).isSymbolicLink(), true)
fs.unlinkSync(secondLink)
}
}
expect('nonrecursive_rm_on_windows_junction', 'call nonrecursive rmSync on a lab-owned junction',
{ result: 'removed', untouched: true }, { result, untouched: fs.existsSync(marker) })
}
let realDirectoryRefused = false
try { fs.unlinkSync(target) } catch { realDirectoryRefused = true }
expect('unlink_rejects_a_real_directory', 'try unlink on actual lab-owned directory',
{ refused: true, marker: true }, { refused: realDirectoryRefused, marker: fs.existsSync(marker) })
const { Context } = await import('@deepseek-ai/cordis')
const { default: Sessions } = await import('@deepseek-ai/dsh-session')
const ctx = new Context()
try {
await ctx.plugin(Sessions)
const session = ctx.sessions.create('defensive-lesson-session')
const path = []
ctx.on('session/event', (owner) => {
if (owner !== session) return
path.push('sync')
throw new Error('synthetic synchronous failure')
})
ctx.on('session/event', async (owner) => {
if (owner !== session) return
path.push('async')
throw new Error('synthetic rejected observer')
})
ctx.on('session/event', (owner, event) => { if (owner === session) path.push(event.type) })
const event = session.append('turn/start', { turn: 1 })
await Promise.resolve()
expect('committed_append_survives_observer_failures', 'two failing real session observers followed by a healthy one',
{ order: ['sync', 'async', 'turn/start'], committed: true },
{ order: path, committed: session.snapshotEvents().some(({ seq }) => seq === event.seq && event.type === 'turn/start') })
} finally {
await ctx.fiber.dispose()
}
const { normalizeLlmFailure } = await import(base + 'packages/llm/llm/src/adapter-failure.ts')
const { LlmError } = await import('@deepseek-ai/dsh-llm')
const raw = { message: 'Synthetic provider busy', code: 'LESSON_BUSY', status: 503 }
expect('structured_provider_failure_normalises_without_losing_facts', 'use actual adapter-side normalizer',
{ structured: raw, fallback: { message: 'synthetic unknown', code: 'UNKNOWN' } },
{ structured: normalizeLlmFailure(LlmError.fromFailure(raw)), fallback: normalizeLlmFailure(new Error('synthetic unknown')) })
console.log(JSON.stringify({
cases, node: process.version, typescript: ts.version, platform: process.platform,
code_sha256: digest(fs.readFileSync(fileURLToPath(import.meta.url))),
source_hashes: Object.fromEntries(Object.entries(sourceHashes).sort(([a], [b]) => a.localeCompare(b))),
posix_modes_checked: process.platform !== 'win32', windows_acl_checked: false, live_agent_interval_tested: false,
subprocess_scope: 'owned Node worker only', environment_fixture_only: true,
}, null, 2))
- 验证超时和零退出码共存、强制停止后等待关闭,以及 Junction 删除后目标保留。健康观察者在前面两个观察者失败后仍收到已提交事件。
所需环境:Windows、Node.js 24.22.3、TypeScript 6.0.3、固定版本源码、临时目录。
当前源码 SHA256:616b0d3c1f75eaa399c852c0682b082cadd852f77fd45ec3554fbd39ee8a1331
本地复跑
按 ZIP 内的 README 准备空临时目录并运行。
所需环境:Windows、Node.js 24.22.3、TypeScript 6.0.3、固定版本源码、临时目录。
ZIP SHA256:f74a7b511f863f0bbc6dc7fb8b3b26c435c13bf5ab96fc122bc7ef171be4e902
常见错误与边界
- 独立判断超时、退出码与信号。
- 先判断资源所有权,再选择清理原语。
练习与解答
进程处于关闭流程中就能宣告退出吗?
展开参考解答
等待实际 close 并保留终态输出。