AI 生成的任务组可靠吗:九组 JavaScript 实验审查动态登记、封口与完成令牌

10-19 4阅读

本文从 AI 容易生成的裸计数器出发,审查一个 JavaScript 动态任务组完成跟踪器。重点是任务名单仍然开放时如何等待、什么时候允许封口,以及完成令牌、错误收集、观察取消与关闭如何各自承担清楚的责任。

AI 生成的任务组可靠吗:九组 JavaScript 实验审查动态登记、封口与完成令牌
AI 生成的概念插图:开放登记的任务入口、最终封口的闸门与独立观察者,用来帮助理解完成跟踪的边界,并非真实程序界面。

运行方式与审查范围

九段示例均为完整的 .mjs 程序,可分别保存后执行 node --unhandled-rejections=strict 文件名.mjs。本文使用 Node.js v24.19.0 实测,所有标准输出都列在对应代码之后。程序只使用 Node 内建模块,不访问网络、不依赖定时等待,也不涉及跨进程共享状态。第一段用于复现缺陷,其余八段重复附带相同完整实现,便于独立验证。

本文设计的是一次性登记账本。它记录任务已经登记和已经交账的事实,不调度任务,不限制并发,不计算依赖关系,也没有重复使用的屏障轮次。所有状态变化发生在同一个 JavaScript 执行环境,业务工作本身由调用方负责。

1.先证明当前为零不等于以后没有任务

让 AI 写一个等待所有任务结束的小工具,最容易得到的答案就是一个计数器:登记时加一,完成时减一,归零时唤醒等待者。这个答案遗漏了决定性的问题:任务名单现在已经确定了吗?在目录扫描、插件发现、增量解析这类流程中,第一个任务可能还没有登记,或者上一个任务刚结束,下一批任务仍在发现中。瞬间的零只能说明此刻没有欠账,无法证明以后不会再记账。

下面故意保留有问题的候选实现。先调用等待,再登记一个任务,等待已经完成,而任务数量变成一。断言用于确认缺陷确实被复现,输出不是正确语义。单线程也不能消除这种时间顺序错误,因为 Promise 的完成承诺不会随着后来增加的计数自动撤回。

import assert from 'node:assert/strict';
let pending = 0;
const waiters = [];
function badJoin() {
  return pending === 0 ? Promise.resolve() : new Promise(r => waiters.push(r));
}
function badRegister() {
  pending++;
  return () => { if (--pending === 0) waiters.splice(0).forEach(r => r()); };
}
let observed = false;
const observation = badJoin().then(() => { observed = true; });
await observation;
const finish = badRegister();
assert.equal(observed, true);
assert.equal(pending, 1);
console.log(`joined=${observed}, pending=${pending}`);
finish();

输出:

joined=true, pending=1

修复方向不是延迟一个微任务再看计数。发现过程可能跨越多次异步操作,延迟多久都无法推导任务名单是否完整。必须增加一个由生产者明确发出的信号:seal 表示从此不再接受登记。只有登记已封口且未完成数量为零,两项条件同时成立,才允许产生最终结果。

2.完整实现:把封口作为不可撤销的边界

从这一节开始,每段代码都包含完整的 TaskGroup 实现,可以单独复制运行,不依赖其他段落或第三方包。open 允许登记;sealed 只等待已有令牌交账;completed 保存最终报告;closed 表示提前放弃这份跟踪记录。seal 可以在数量为零时调用,也可以在任务仍运行时调用。完成与关闭都是终态,不提供重置、下一轮或自动重新开放。

实现把任务结果装入一个无原型的报告对象,再冻结报告、结果数组和结果记录。冻结只保护结构,任务返回的业务对象仍然由业务方管理。join 的 Promise 只接收报告对象,不直接接收任务载荷。这里先验证最重要的负面事实:即使任务已经交账,只要没有封口,等待者仍然不能得到完成报告。

import assert from 'node:assert/strict';
import { getEventListeners } from 'node:events';
import { addAbortListener } from 'node:events';
const aborted = Object.getOwnPropertyDescriptor(AbortSignal.prototype, 'aborted').get;
const reasonOf = Object.getOwnPropertyDescriptor(AbortSignal.prototype, 'reason').get;
const record = fields => Object.freeze(Object.assign(Object.create(null), fields));
class TaskGroup {
  #state = 'open'; #pending = 0; #rows = []; #waiters = new Set();
  #result; #reason;
  get state() { return this.#state; }
  get pending() { return this.#pending; }
  get waiting() { return this.#waiters.size; }
  register(label = '') {
    if (this.#state !== 'open') throw new Error('registration sealed');
    if (typeof label !== 'string') throw new TypeError('label must be a string');
    const index = this.#rows.length;
    this.#rows.push(null); this.#pending++;
    let live = true;
    const settle = (status, payload) => {
      if (!live || this.#state === 'closed') return false;
      live = false;
      this.#rows[index] = record(status === 'fulfilled'
        ? { label, status, value: payload } : { label, status, reason: payload });
      this.#pending--; this.#flush(); return true;
    };
    return Object.freeze({
      finish: value => settle('fulfilled', value),
      fail: reason => settle('rejected', reason)
    });
  }
  seal() {
    if (this.#state !== 'open') return false;
    this.#state = 'sealed'; this.#flush(); return true;
  }
  join(signal) {
    return new Promise((resolve, reject) => {
      if (signal !== undefined) aborted.call(signal);
      const w = { resolve, reject, signal, live: true, subscription: null };
      this.#waiters.add(w);
      this.#deliver(w);
      if (!w.live || signal === undefined) return;
      try {
        const subscription = addAbortListener(signal, () => this.#deliver(w));
        if (w.live) w.subscription = subscription;
        else subscription[Symbol.dispose]();
        this.#deliver(w);
      } catch (error) { this.#settle(w, true, error); }
    });
  }
  close(reason = new Error('group closed')) {
    if (this.#state === 'closed' || this.#state === 'completed') return false;
    this.#state = 'closed'; this.#reason = reason;
    this.#rows = []; this.#pending = 0; this.#flush(); return true;
  }
  #settle(w, failed, value) {
    if (!w.live) return;
    w.live = false; this.#waiters.delete(w);
    const subscription = w.subscription; w.subscription = null;
    subscription?.[Symbol.dispose]();
    if (failed) w.reject(value); else w.resolve(value);
  }
  #deliver(w) {
    if (!w.live) return;
    if (w.signal !== undefined && aborted.call(w.signal)) {
      this.#settle(w, true, reasonOf.call(w.signal));
    } else if (this.#state === 'closed') this.#settle(w, true, this.#reason);
    else if (this.#state === 'completed') this.#settle(w, false, this.#result);
  }
  #flush() {
    if (this.#state === 'sealed' && this.#pending === 0) {
      this.#state = 'completed';
      this.#result = record({ results: Object.freeze(this.#rows.slice()) });
      this.#rows = [];
    }
    if (this.#state !== 'completed' && this.#state !== 'closed') return;
    for (const w of [...this.#waiters]) this.#deliver(w);
  }
}

const group = new TaskGroup();
let resolved = false;
const waiting = group.join().then(result => { resolved = true; return result; });
await Promise.resolve();
assert.equal(resolved, false);
const token = group.register('later');
token.finish(7);
await Promise.resolve();
assert.equal(resolved, false);
assert.equal(group.pending, 0);
console.log(`before seal: ${group.state}, joined=${resolved}`);
assert.equal(group.seal(), true);
const result = await waiting;
assert.equal(result.results[0].value, 7);
assert.equal(group.seal(), false);
assert.throws(() => group.register('too late'), /registration sealed/);
const empty = new TaskGroup();
empty.seal();
assert.equal((await empty.join()).results.length, 0);
console.log(`after seal: ${group.state}, empty=${empty.state}`);

输出:

before seal: open, joined=false
after seal: completed, empty=completed

状态转换发生在唤醒之前:先设置 completed,再保存结果,最后处理等待者。这样即便监听器清理或外部事件引发重入,观察者看到的也已经是终态。等待者同样先从集合中移除,再清理订阅,最后兑现 Promise。所有已经完成的等待者都得到同一份冻结报告;它们不共享取消状态。

空组也遵守同一条规则。一个从未登记任务的实例不会自动完成,但空组封口可以立即完成。这个区别让调用方能够在启动发现流程之前就安全地建立等待,避免“必须先登记第一个任务才能等待”的脆弱调用顺序。

3.完成令牌必须幂等,不能公开裸减法

如果公开 done 方法,任何调用方都能替别人减计数,异常路径与正常路径也容易重复交账。这里每次 register 返回独立令牌,令牌只拥有它对应的登记项。finish 表示成功,fail 表示失败,两者共享同一个只允许使用一次的状态。第一次调用返回 true,重复调用返回 false,重复失败也不能覆盖已经保存的成功。

使用两个方法还能避免另一类歧义:不能用 if(error) 判断任务成功与否。JavaScript 可以抛出零、空字符串或 undefined,成功结果也可能是 false。成功或失败应由显式操作表达,载荷只负责保存值。这一节先检查重复交账不改变首个结果、不导致负数,也不会替其他任务提前完成。

import assert from 'node:assert/strict';
import { getEventListeners } from 'node:events';
import { addAbortListener } from 'node:events';
const aborted = Object.getOwnPropertyDescriptor(AbortSignal.prototype, 'aborted').get;
const reasonOf = Object.getOwnPropertyDescriptor(AbortSignal.prototype, 'reason').get;
const record = fields => Object.freeze(Object.assign(Object.create(null), fields));
class TaskGroup {
  #state = 'open'; #pending = 0; #rows = []; #waiters = new Set();
  #result; #reason;
  get state() { return this.#state; }
  get pending() { return this.#pending; }
  get waiting() { return this.#waiters.size; }
  register(label = '') {
    if (this.#state !== 'open') throw new Error('registration sealed');
    if (typeof label !== 'string') throw new TypeError('label must be a string');
    const index = this.#rows.length;
    this.#rows.push(null); this.#pending++;
    let live = true;
    const settle = (status, payload) => {
      if (!live || this.#state === 'closed') return false;
      live = false;
      this.#rows[index] = record(status === 'fulfilled'
        ? { label, status, value: payload } : { label, status, reason: payload });
      this.#pending--; this.#flush(); return true;
    };
    return Object.freeze({
      finish: value => settle('fulfilled', value),
      fail: reason => settle('rejected', reason)
    });
  }
  seal() {
    if (this.#state !== 'open') return false;
    this.#state = 'sealed'; this.#flush(); return true;
  }
  join(signal) {
    return new Promise((resolve, reject) => {
      if (signal !== undefined) aborted.call(signal);
      const w = { resolve, reject, signal, live: true, subscription: null };
      this.#waiters.add(w);
      this.#deliver(w);
      if (!w.live || signal === undefined) return;
      try {
        const subscription = addAbortListener(signal, () => this.#deliver(w));
        if (w.live) w.subscription = subscription;
        else subscription[Symbol.dispose]();
        this.#deliver(w);
      } catch (error) { this.#settle(w, true, error); }
    });
  }
  close(reason = new Error('group closed')) {
    if (this.#state === 'closed' || this.#state === 'completed') return false;
    this.#state = 'closed'; this.#reason = reason;
    this.#rows = []; this.#pending = 0; this.#flush(); return true;
  }
  #settle(w, failed, value) {
    if (!w.live) return;
    w.live = false; this.#waiters.delete(w);
    const subscription = w.subscription; w.subscription = null;
    subscription?.[Symbol.dispose]();
    if (failed) w.reject(value); else w.resolve(value);
  }
  #deliver(w) {
    if (!w.live) return;
    if (w.signal !== undefined && aborted.call(w.signal)) {
      this.#settle(w, true, reasonOf.call(w.signal));
    } else if (this.#state === 'closed') this.#settle(w, true, this.#reason);
    else if (this.#state === 'completed') this.#settle(w, false, this.#result);
  }
  #flush() {
    if (this.#state === 'sealed' && this.#pending === 0) {
      this.#state = 'completed';
      this.#result = record({ results: Object.freeze(this.#rows.slice()) });
      this.#rows = [];
    }
    if (this.#state !== 'completed' && this.#state !== 'closed') return;
    for (const w of [...this.#waiters]) this.#deliver(w);
  }
}

const group = new TaskGroup();
const a = group.register('A'), b = group.register('B');
assert.equal(a.finish(10), true);
assert.equal(a.finish(99), false);
assert.equal(a.fail(new Error('late')), false);
assert.equal(group.pending, 1);
group.seal();
assert.equal(b.fail('B failed'), true);
assert.equal(b.finish(20), false);
const { results } = await group.join();
assert.equal(results[0].value, 10);
assert.equal(results[1].reason, 'B failed');
assert.equal(group.pending, 0);
console.log(`accepted=2, pending=${group.pending}`);
console.log(results.map(r => `${r.label}:${r.status}`).join(', '));

输出:

accepted=2, pending=0
A:fulfilled, B:rejected

幂等只意味着重复调用不会破坏账本,不代表业务允许重复执行。发送邮件、写入外部系统等副作用仍然需要自己的幂等设计。令牌解决的是完成报告的一次性归属,不承担重试、去重和事务提交职责。令牌被遗忘时,封口后的组会持续等待;调用方需要审查每条退出路径是否调用了 finish 或 fail。

4.动态发现任务时,封口权属于生产者

动态登记最有价值的地方,是任务数量在执行之前并不已知。下面的发现任务在一次异步边界之后才登记两个工作项。主流程先建立观察,然后等待发现结束,再调用 seal。登记时立即取得令牌,接着才启动对应工作,避免同步完成回调跑在登记之前。最终结果按登记顺序排列,不按完成先后排列。

真实系统可能有多个生产者,封口时必须确认所有生产者都承诺不再登记。这里采用最简单也最容易审查的策略:协调者等待全部发现阶段结束后统一封口。已登记的工作项如果还会继续发现子任务,就仍然属于生产者,不能仅因为外层循环结束便提前 seal。

import assert from 'node:assert/strict';
import { getEventListeners } from 'node:events';
import { addAbortListener } from 'node:events';
const aborted = Object.getOwnPropertyDescriptor(AbortSignal.prototype, 'aborted').get;
const reasonOf = Object.getOwnPropertyDescriptor(AbortSignal.prototype, 'reason').get;
const record = fields => Object.freeze(Object.assign(Object.create(null), fields));
class TaskGroup {
  #state = 'open'; #pending = 0; #rows = []; #waiters = new Set();
  #result; #reason;
  get state() { return this.#state; }
  get pending() { return this.#pending; }
  get waiting() { return this.#waiters.size; }
  register(label = '') {
    if (this.#state !== 'open') throw new Error('registration sealed');
    if (typeof label !== 'string') throw new TypeError('label must be a string');
    const index = this.#rows.length;
    this.#rows.push(null); this.#pending++;
    let live = true;
    const settle = (status, payload) => {
      if (!live || this.#state === 'closed') return false;
      live = false;
      this.#rows[index] = record(status === 'fulfilled'
        ? { label, status, value: payload } : { label, status, reason: payload });
      this.#pending--; this.#flush(); return true;
    };
    return Object.freeze({
      finish: value => settle('fulfilled', value),
      fail: reason => settle('rejected', reason)
    });
  }
  seal() {
    if (this.#state !== 'open') return false;
    this.#state = 'sealed'; this.#flush(); return true;
  }
  join(signal) {
    return new Promise((resolve, reject) => {
      if (signal !== undefined) aborted.call(signal);
      const w = { resolve, reject, signal, live: true, subscription: null };
      this.#waiters.add(w);
      this.#deliver(w);
      if (!w.live || signal === undefined) return;
      try {
        const subscription = addAbortListener(signal, () => this.#deliver(w));
        if (w.live) w.subscription = subscription;
        else subscription[Symbol.dispose]();
        this.#deliver(w);
      } catch (error) { this.#settle(w, true, error); }
    });
  }
  close(reason = new Error('group closed')) {
    if (this.#state === 'closed' || this.#state === 'completed') return false;
    this.#state = 'closed'; this.#reason = reason;
    this.#rows = []; this.#pending = 0; this.#flush(); return true;
  }
  #settle(w, failed, value) {
    if (!w.live) return;
    w.live = false; this.#waiters.delete(w);
    const subscription = w.subscription; w.subscription = null;
    subscription?.[Symbol.dispose]();
    if (failed) w.reject(value); else w.resolve(value);
  }
  #deliver(w) {
    if (!w.live) return;
    if (w.signal !== undefined && aborted.call(w.signal)) {
      this.#settle(w, true, reasonOf.call(w.signal));
    } else if (this.#state === 'closed') this.#settle(w, true, this.#reason);
    else if (this.#state === 'completed') this.#settle(w, false, this.#result);
  }
  #flush() {
    if (this.#state === 'sealed' && this.#pending === 0) {
      this.#state = 'completed';
      this.#result = record({ results: Object.freeze(this.#rows.slice()) });
      this.#rows = [];
    }
    if (this.#state !== 'completed' && this.#state !== 'closed') return;
    for (const w of [...this.#waiters]) this.#deliver(w);
  }
}

const group = new TaskGroup();
const root = group.register('discovery');
const workerJobs = [];
const observation = group.join();
async function discover() {
  await Promise.resolve();
  for (const label of ['image', 'index']) {
    const token = group.register(label);
    workerJobs.push(Promise.resolve().then(() => token.finish(label.length)));
  }
  root.finish('registered');
}
await discover();
group.seal();
const report = await observation;
await Promise.all(workerJobs);
assert.deepEqual(report.results.map(r => r.label), ['discovery', 'image', 'index']);
assert.deepEqual(report.results.map(r => r.value), ['registered', 5, 5]);
console.log(report.results.map(r => r.label).join(' -> '));
console.log(`state=${group.state}, pending=${group.pending}`);

输出:

discovery -> image -> index
state=completed, pending=0

这不是依赖图调度器,也不负责限制并发。实现不会启动、暂停或排队执行任何业务函数,只记录登记和完成事实。它也不是循环屏障:没有参与者轮次,没有下一代计数,没有集齐后重新开放。把这些边界写清楚,才能防止 AI 为了显得通用而偷偷引入另一套生命周期。

示例中的 workerJobs 用来接住示例创建的 Promise。生产代码应当为任务异常建立明确的处理路径,在业务成功时调用 finish,在业务失败时调用 fail。不要只在 finally 中无条件报告成功,也不要把一个无人处理的拒绝 Promise 当作普通数据交给 finish,期待跟踪器替你接管它。

5.错误收集不等于整个等待提前失败

本文选择收集全部结果。某个任务调用 fail 后,其他任务仍然需要交账,join 最终仍然成功返回报告,报告中的 status 告诉调用方哪些任务失败。这让批量审查或资源清理能够看到全部问题,而不是遇到第一个错误就失去其余结果。取消观察、关闭实例和无效信号则会使对应 join 拒绝,二者需要分开理解。

下面故意使用 undefined 和零作为失败原因,并使用 false 作为成功值。失败记录保留 reason 属性,即使它的值为 undefined;成功记录保留 value 属性。错误顺序由登记位置决定,因此业务方能稳定地把错误映射回输入项,而不受异步完成顺序影响。

import assert from 'node:assert/strict';
import { getEventListeners } from 'node:events';
import { addAbortListener } from 'node:events';
const aborted = Object.getOwnPropertyDescriptor(AbortSignal.prototype, 'aborted').get;
const reasonOf = Object.getOwnPropertyDescriptor(AbortSignal.prototype, 'reason').get;
const record = fields => Object.freeze(Object.assign(Object.create(null), fields));
class TaskGroup {
  #state = 'open'; #pending = 0; #rows = []; #waiters = new Set();
  #result; #reason;
  get state() { return this.#state; }
  get pending() { return this.#pending; }
  get waiting() { return this.#waiters.size; }
  register(label = '') {
    if (this.#state !== 'open') throw new Error('registration sealed');
    if (typeof label !== 'string') throw new TypeError('label must be a string');
    const index = this.#rows.length;
    this.#rows.push(null); this.#pending++;
    let live = true;
    const settle = (status, payload) => {
      if (!live || this.#state === 'closed') return false;
      live = false;
      this.#rows[index] = record(status === 'fulfilled'
        ? { label, status, value: payload } : { label, status, reason: payload });
      this.#pending--; this.#flush(); return true;
    };
    return Object.freeze({
      finish: value => settle('fulfilled', value),
      fail: reason => settle('rejected', reason)
    });
  }
  seal() {
    if (this.#state !== 'open') return false;
    this.#state = 'sealed'; this.#flush(); return true;
  }
  join(signal) {
    return new Promise((resolve, reject) => {
      if (signal !== undefined) aborted.call(signal);
      const w = { resolve, reject, signal, live: true, subscription: null };
      this.#waiters.add(w);
      this.#deliver(w);
      if (!w.live || signal === undefined) return;
      try {
        const subscription = addAbortListener(signal, () => this.#deliver(w));
        if (w.live) w.subscription = subscription;
        else subscription[Symbol.dispose]();
        this.#deliver(w);
      } catch (error) { this.#settle(w, true, error); }
    });
  }
  close(reason = new Error('group closed')) {
    if (this.#state === 'closed' || this.#state === 'completed') return false;
    this.#state = 'closed'; this.#reason = reason;
    this.#rows = []; this.#pending = 0; this.#flush(); return true;
  }
  #settle(w, failed, value) {
    if (!w.live) return;
    w.live = false; this.#waiters.delete(w);
    const subscription = w.subscription; w.subscription = null;
    subscription?.[Symbol.dispose]();
    if (failed) w.reject(value); else w.resolve(value);
  }
  #deliver(w) {
    if (!w.live) return;
    if (w.signal !== undefined && aborted.call(w.signal)) {
      this.#settle(w, true, reasonOf.call(w.signal));
    } else if (this.#state === 'closed') this.#settle(w, true, this.#reason);
    else if (this.#state === 'completed') this.#settle(w, false, this.#result);
  }
  #flush() {
    if (this.#state === 'sealed' && this.#pending === 0) {
      this.#state = 'completed';
      this.#result = record({ results: Object.freeze(this.#rows.slice()) });
      this.#rows = [];
    }
    if (this.#state !== 'completed' && this.#state !== 'closed') return;
    for (const w of [...this.#waiters]) this.#deliver(w);
  }
}

const group = new TaskGroup();
const first = group.register('one');
const second = group.register('two');
const third = group.register('three');
const observation = group.join();
second.fail(undefined);
third.fail(0);
group.seal();
assert.equal(group.pending, 1);
first.finish(false);
const report = await observation;
const errors = report.results.filter(r => r.status === 'rejected');
assert.equal(report.results[0].value, false);
assert.equal(errors[0].reason, undefined);
assert.equal(errors[1].reason, 0);
assert.deepEqual(errors.map(r => r.label), ['two', 'three']);
assert.ok(Object.isFrozen(report));
assert.ok(Object.isFrozen(report.results));
assert.ok(Object.isFrozen(errors[0]));
console.log(`fulfilled=${report.results.length - errors.length}, rejected=${errors.length}`);
console.log(`reason slots: ${'reason' in errors[0]}, ${errors[1].reason}`);

输出:

fulfilled=1, rejected=2
reason slots: true, 0

若业务要求最终抛出 AggregateError,应在拿到报告后由调用方明确转换,并决定是否保留部分成功结果。不要直接把此策略混进计数器,否则一次失败究竟是终止观察、放弃剩余工作,还是仅仅标记一个结果,会重新变得含糊。报告保存的是原始错误引用,不会擅自字符串化,也不会调用可能带副作用的 toString。

6.取消的是一个观察者,不是整组工作

两个页面可以同时观察同一组后台任务,一个页面离开并不意味着后台工作应当停止。join 接收的 AbortSignal 只属于这次等待:取消后移除这个等待者,其他等待者和任务令牌继续有效。本文没有给业务任务传入取消信号,因此无法也不会宣称终止网络请求或回滚外部副作用。

信号必须是真实 AbortSignal,省略参数表示不可取消。实现使用原生访问器验证信号并读取取消状态,避免把外形相似的对象当成信号。已取消信号直接拒绝,不额外挂监听器;错误原因按原值传递,包括 null。正常完成、取消与关闭路径都会清理已经安装的订阅。

import assert from 'node:assert/strict';
import { getEventListeners } from 'node:events';
import { addAbortListener } from 'node:events';
const aborted = Object.getOwnPropertyDescriptor(AbortSignal.prototype, 'aborted').get;
const reasonOf = Object.getOwnPropertyDescriptor(AbortSignal.prototype, 'reason').get;
const record = fields => Object.freeze(Object.assign(Object.create(null), fields));
class TaskGroup {
  #state = 'open'; #pending = 0; #rows = []; #waiters = new Set();
  #result; #reason;
  get state() { return this.#state; }
  get pending() { return this.#pending; }
  get waiting() { return this.#waiters.size; }
  register(label = '') {
    if (this.#state !== 'open') throw new Error('registration sealed');
    if (typeof label !== 'string') throw new TypeError('label must be a string');
    const index = this.#rows.length;
    this.#rows.push(null); this.#pending++;
    let live = true;
    const settle = (status, payload) => {
      if (!live || this.#state === 'closed') return false;
      live = false;
      this.#rows[index] = record(status === 'fulfilled'
        ? { label, status, value: payload } : { label, status, reason: payload });
      this.#pending--; this.#flush(); return true;
    };
    return Object.freeze({
      finish: value => settle('fulfilled', value),
      fail: reason => settle('rejected', reason)
    });
  }
  seal() {
    if (this.#state !== 'open') return false;
    this.#state = 'sealed'; this.#flush(); return true;
  }
  join(signal) {
    return new Promise((resolve, reject) => {
      if (signal !== undefined) aborted.call(signal);
      const w = { resolve, reject, signal, live: true, subscription: null };
      this.#waiters.add(w);
      this.#deliver(w);
      if (!w.live || signal === undefined) return;
      try {
        const subscription = addAbortListener(signal, () => this.#deliver(w));
        if (w.live) w.subscription = subscription;
        else subscription[Symbol.dispose]();
        this.#deliver(w);
      } catch (error) { this.#settle(w, true, error); }
    });
  }
  close(reason = new Error('group closed')) {
    if (this.#state === 'closed' || this.#state === 'completed') return false;
    this.#state = 'closed'; this.#reason = reason;
    this.#rows = []; this.#pending = 0; this.#flush(); return true;
  }
  #settle(w, failed, value) {
    if (!w.live) return;
    w.live = false; this.#waiters.delete(w);
    const subscription = w.subscription; w.subscription = null;
    subscription?.[Symbol.dispose]();
    if (failed) w.reject(value); else w.resolve(value);
  }
  #deliver(w) {
    if (!w.live) return;
    if (w.signal !== undefined && aborted.call(w.signal)) {
      this.#settle(w, true, reasonOf.call(w.signal));
    } else if (this.#state === 'closed') this.#settle(w, true, this.#reason);
    else if (this.#state === 'completed') this.#settle(w, false, this.#result);
  }
  #flush() {
    if (this.#state === 'sealed' && this.#pending === 0) {
      this.#state = 'completed';
      this.#result = record({ results: Object.freeze(this.#rows.slice()) });
      this.#rows = [];
    }
    if (this.#state !== 'completed' && this.#state !== 'closed') return;
    for (const w of [...this.#waiters]) this.#deliver(w);
  }
}

const group = new TaskGroup();
const token = group.register('work');
const controller = new AbortController();
const cancelReason = new Error('observer left');
const observed = group.join(controller.signal).then(
  () => assert.fail('must reject'), error => assert.equal(error, cancelReason)
);
const survivor = group.join();
assert.equal(getEventListeners(controller.signal, 'abort').length, 1);
controller.abort(cancelReason);
await observed;
assert.equal(group.pending, 1);
assert.equal(group.waiting, 1);
assert.equal(getEventListeners(controller.signal, 'abort').length, 0);
await assert.rejects(group.join({}), TypeError);
const already = AbortSignal.abort(null);
await group.join(already).then(() => assert.fail(), e => assert.equal(e, null));
assert.equal(getEventListeners(already, 'abort').length, 0);
token.finish('still worked');
group.seal();
assert.equal((await survivor).results[0].value, 'still worked');
console.log('cancelled observer, work remained pending');
console.log(`survivor=${group.state}, listeners=0`);

输出:

cancelled observer, work remained pending
survivor=completed, listeners=0

关于取消接口,依据是 Node.js 的 AbortSignal.reason 文档与 addAbortListener 文档。后者提供可释放的订阅,并保证其他监听器调用 stopImmediatePropagation 不会阻断它。本文仍然自行定义竞争规则:在一个等待者实际交付结果时,如果其信号已经取消,取消优先;已经兑现的 Promise 不会被后来的取消撤回。

拒绝必须及时接住。示例在触发取消以前就安装拒绝处理函数,并在严格的未处理拒绝模式下运行。取消结果不应成为测试进程的偶然警告,更不能用关闭警告的方式掩盖观察者清理遗漏。

7.取消回调里的重入,比普通取消更值得测

常见测试只覆盖先 join、再 abort,却没有覆盖更早注册的监听器在 abort 分发途中执行其他操作。下面的旧监听器先阻止普通事件传播,然后完成最后一个任务并封口。此时取消已经发生,但跟踪器自己的取消回调还没有获得执行机会。若完成路径只看计数,取消中的等待者便可能错误地收到成功。

修复依靠两道防线:订阅采用 addAbortListener;所有交付路径都会重新读取信号状态。因此旧监听器引发完成或 close,已经取消的观察者仍收到自己的取消原因,未取消的观察者则正常得到报告。另一个测试故意在安装监听器时重入 seal,验证返回的订阅句柄仍会被释放,不会因为等待者提前结算而遗留监听器。

import assert from 'node:assert/strict';
import { getEventListeners } from 'node:events';
import { addAbortListener } from 'node:events';
const aborted = Object.getOwnPropertyDescriptor(AbortSignal.prototype, 'aborted').get;
const reasonOf = Object.getOwnPropertyDescriptor(AbortSignal.prototype, 'reason').get;
const record = fields => Object.freeze(Object.assign(Object.create(null), fields));
class TaskGroup {
  #state = 'open'; #pending = 0; #rows = []; #waiters = new Set();
  #result; #reason;
  get state() { return this.#state; }
  get pending() { return this.#pending; }
  get waiting() { return this.#waiters.size; }
  register(label = '') {
    if (this.#state !== 'open') throw new Error('registration sealed');
    if (typeof label !== 'string') throw new TypeError('label must be a string');
    const index = this.#rows.length;
    this.#rows.push(null); this.#pending++;
    let live = true;
    const settle = (status, payload) => {
      if (!live || this.#state === 'closed') return false;
      live = false;
      this.#rows[index] = record(status === 'fulfilled'
        ? { label, status, value: payload } : { label, status, reason: payload });
      this.#pending--; this.#flush(); return true;
    };
    return Object.freeze({
      finish: value => settle('fulfilled', value),
      fail: reason => settle('rejected', reason)
    });
  }
  seal() {
    if (this.#state !== 'open') return false;
    this.#state = 'sealed'; this.#flush(); return true;
  }
  join(signal) {
    return new Promise((resolve, reject) => {
      if (signal !== undefined) aborted.call(signal);
      const w = { resolve, reject, signal, live: true, subscription: null };
      this.#waiters.add(w);
      this.#deliver(w);
      if (!w.live || signal === undefined) return;
      try {
        const subscription = addAbortListener(signal, () => this.#deliver(w));
        if (w.live) w.subscription = subscription;
        else subscription[Symbol.dispose]();
        this.#deliver(w);
      } catch (error) { this.#settle(w, true, error); }
    });
  }
  close(reason = new Error('group closed')) {
    if (this.#state === 'closed' || this.#state === 'completed') return false;
    this.#state = 'closed'; this.#reason = reason;
    this.#rows = []; this.#pending = 0; this.#flush(); return true;
  }
  #settle(w, failed, value) {
    if (!w.live) return;
    w.live = false; this.#waiters.delete(w);
    const subscription = w.subscription; w.subscription = null;
    subscription?.[Symbol.dispose]();
    if (failed) w.reject(value); else w.resolve(value);
  }
  #deliver(w) {
    if (!w.live) return;
    if (w.signal !== undefined && aborted.call(w.signal)) {
      this.#settle(w, true, reasonOf.call(w.signal));
    } else if (this.#state === 'closed') this.#settle(w, true, this.#reason);
    else if (this.#state === 'completed') this.#settle(w, false, this.#result);
  }
  #flush() {
    if (this.#state === 'sealed' && this.#pending === 0) {
      this.#state = 'completed';
      this.#result = record({ results: Object.freeze(this.#rows.slice()) });
      this.#rows = [];
    }
    if (this.#state !== 'completed' && this.#state !== 'closed') return;
    for (const w of [...this.#waiters]) this.#deliver(w);
  }
}

const group = new TaskGroup();
const token = group.register('work');
const controller = new AbortController();
controller.signal.addEventListener('abort', event => {
  event.stopImmediatePropagation();
  token.finish('done inside abort');
  group.seal();
}, { once: true });
const cancelled = group.join(controller.signal).then(
  () => assert.fail('aborted observer must reject'), e => assert.equal(e, 'leave')
);
const survivor = group.join();
controller.abort('leave');
await cancelled;
assert.equal((await survivor).results[0].value, 'done inside abort');
assert.equal(getEventListeners(controller.signal, 'abort').length, 0);
const other = new TaskGroup(), c2 = new AbortController();
c2.signal.addEventListener('abort', () => other.close('closed in abort'), { once: true });
const outcome = other.join(c2.signal).then(() => assert.fail(), e => assert.equal(e, 0));
c2.abort(0); await outcome;
assert.equal(other.waiting, 0);
const attaching = new TaskGroup(), c3 = new AbortController();
const nativeAdd = c3.signal.addEventListener;
c3.signal.addEventListener = function (...args) {
  const result = nativeAdd.apply(this, args);
  attaching.seal();
  return result;
};
assert.equal((await attaching.join(c3.signal)).results.length, 0);
assert.equal(getEventListeners(c3.signal, 'abort').length, 0);
console.log('abort wins during finish and close reentry');
console.log('attachment reentry: no retained listener');

输出:

abort wins during finish and close reentry
attachment reentry: no retained listener

第三个测试是有意构造的安装期重入,不代表支持任意恶意改写平台对象。本文以原生 Node.js Promise、AbortSignal 和事件机制为运行基础,不承诺在全局内建函数被替换、信号的 aborted 属性被遮蔽、信号安装或清理方法被任意篡改、或外部伪造事件的情况下保持相同保证。测试覆盖明确的交错顺序,比含糊宣称“完全无竞态”更有价值。

清理时先把等待者标记为不再存活,是为了让再次进入同一条路径立即成为无操作。与此同时,订阅句柄可能在重入结束之后才返回,因此安装完成后必须检查等待者是否还存活:存活才保存句柄,否则立即释放。少掉这一处分支,成功返回的测试也可能留下长期引用。

8.close 是放弃跟踪,不能冒充业务停止

有些任务源会失联,协调者也可能主动放弃本次收集。close 将未终结的实例永久关闭,让当前和后续等待者拒绝,并清空内部结果槽和未完成计数。已发出的令牌随后调用 finish 或 fail 都返回 false。这里的 pending 归零表示本实例已不再跟踪这些债务,绝不代表实际工作全部成功结束。

完成之后再 close 返回 false,保留已经生成的报告;反复 close 也返回 false,不覆盖第一次关闭原因。这个选择让终态具有稳定含义。关闭原因可以是 null;省略原因或传入 undefined 时则使用默认 Error。实例不会自动重开,新一批工作必须创建新的 TaskGroup。

import assert from 'node:assert/strict';
import { getEventListeners } from 'node:events';
import { addAbortListener } from 'node:events';
const aborted = Object.getOwnPropertyDescriptor(AbortSignal.prototype, 'aborted').get;
const reasonOf = Object.getOwnPropertyDescriptor(AbortSignal.prototype, 'reason').get;
const record = fields => Object.freeze(Object.assign(Object.create(null), fields));
class TaskGroup {
  #state = 'open'; #pending = 0; #rows = []; #waiters = new Set();
  #result; #reason;
  get state() { return this.#state; }
  get pending() { return this.#pending; }
  get waiting() { return this.#waiters.size; }
  register(label = '') {
    if (this.#state !== 'open') throw new Error('registration sealed');
    if (typeof label !== 'string') throw new TypeError('label must be a string');
    const index = this.#rows.length;
    this.#rows.push(null); this.#pending++;
    let live = true;
    const settle = (status, payload) => {
      if (!live || this.#state === 'closed') return false;
      live = false;
      this.#rows[index] = record(status === 'fulfilled'
        ? { label, status, value: payload } : { label, status, reason: payload });
      this.#pending--; this.#flush(); return true;
    };
    return Object.freeze({
      finish: value => settle('fulfilled', value),
      fail: reason => settle('rejected', reason)
    });
  }
  seal() {
    if (this.#state !== 'open') return false;
    this.#state = 'sealed'; this.#flush(); return true;
  }
  join(signal) {
    return new Promise((resolve, reject) => {
      if (signal !== undefined) aborted.call(signal);
      const w = { resolve, reject, signal, live: true, subscription: null };
      this.#waiters.add(w);
      this.#deliver(w);
      if (!w.live || signal === undefined) return;
      try {
        const subscription = addAbortListener(signal, () => this.#deliver(w));
        if (w.live) w.subscription = subscription;
        else subscription[Symbol.dispose]();
        this.#deliver(w);
      } catch (error) { this.#settle(w, true, error); }
    });
  }
  close(reason = new Error('group closed')) {
    if (this.#state === 'closed' || this.#state === 'completed') return false;
    this.#state = 'closed'; this.#reason = reason;
    this.#rows = []; this.#pending = 0; this.#flush(); return true;
  }
  #settle(w, failed, value) {
    if (!w.live) return;
    w.live = false; this.#waiters.delete(w);
    const subscription = w.subscription; w.subscription = null;
    subscription?.[Symbol.dispose]();
    if (failed) w.reject(value); else w.resolve(value);
  }
  #deliver(w) {
    if (!w.live) return;
    if (w.signal !== undefined && aborted.call(w.signal)) {
      this.#settle(w, true, reasonOf.call(w.signal));
    } else if (this.#state === 'closed') this.#settle(w, true, this.#reason);
    else if (this.#state === 'completed') this.#settle(w, false, this.#result);
  }
  #flush() {
    if (this.#state === 'sealed' && this.#pending === 0) {
      this.#state = 'completed';
      this.#result = record({ results: Object.freeze(this.#rows.slice()) });
      this.#rows = [];
    }
    if (this.#state !== 'completed' && this.#state !== 'closed') return;
    for (const w of [...this.#waiters]) this.#deliver(w);
  }
}

const group = new TaskGroup();
const token = group.register('unfinished');
const controller = new AbortController();
const waiting = group.join(controller.signal).then(
  () => assert.fail(), reason => assert.equal(reason, null)
);
assert.equal(group.close(null), true);
await waiting;
assert.equal(group.close('replacement'), false);
assert.equal(group.seal(), false);
assert.equal(token.finish('too late'), false);
assert.equal(token.fail('too late'), false);
assert.equal(group.pending, 0);
assert.equal(group.waiting, 0);
assert.equal(getEventListeners(controller.signal, 'abort').length, 0);
assert.throws(() => group.register(), /registration sealed/);
await group.join().then(() => assert.fail(), e => assert.equal(e, null));
const completed = new TaskGroup();
completed.seal();
const before = await completed.join();
assert.equal(completed.close(), false);
assert.equal(await completed.join(), before);
console.log(`closed=${group.state}, pending=${group.pending}, waiting=${group.waiting}`);
console.log(`completed snapshot preserved=${completed.state}`);

输出:

closed=closed, pending=0, waiting=0
completed snapshot preserved=completed

生命周期设计还需要考虑引用存活时间。完成报告保留所有任务载荷,持有报告就会持有这些引用;关闭能释放组内尚未交付的结果,但无法替调用方释放手中的令牌或业务对象。超大批次需要另外设计分段收集或外部存储,不能因为代码短就把它当作无限容量容器。

9.把 thenable 当数据保存,而不是重新等待一次

最后一个陷阱与计数无关。任务已经声明完成,它返回的数据却可能恰好有 then 方法,也可能本身就是 Promise。如果直接用这些值兑现 join,Promise 的解析过程会尝试采用它们的状态,甚至读取一个会抛错的 then getter。这样跟踪器明明已经完成,却可能永久等待或莫名拒绝。

ECMAScript Promise 解析算法说明了对象的 then 属性如何被读取以及可调用 then 如何参与解析。本文用无原型的报告对象包住结果数组,载荷只作为更深一层的属性保存,解析过程不递归遍历数组内容。下面同时测试抛错 getter、永远待定的 Promise 和可调用 thenable。

import assert from 'node:assert/strict';
import { getEventListeners } from 'node:events';
import { addAbortListener } from 'node:events';
const aborted = Object.getOwnPropertyDescriptor(AbortSignal.prototype, 'aborted').get;
const reasonOf = Object.getOwnPropertyDescriptor(AbortSignal.prototype, 'reason').get;
const record = fields => Object.freeze(Object.assign(Object.create(null), fields));
class TaskGroup {
  #state = 'open'; #pending = 0; #rows = []; #waiters = new Set();
  #result; #reason;
  get state() { return this.#state; }
  get pending() { return this.#pending; }
  get waiting() { return this.#waiters.size; }
  register(label = '') {
    if (this.#state !== 'open') throw new Error('registration sealed');
    if (typeof label !== 'string') throw new TypeError('label must be a string');
    const index = this.#rows.length;
    this.#rows.push(null); this.#pending++;
    let live = true;
    const settle = (status, payload) => {
      if (!live || this.#state === 'closed') return false;
      live = false;
      this.#rows[index] = record(status === 'fulfilled'
        ? { label, status, value: payload } : { label, status, reason: payload });
      this.#pending--; this.#flush(); return true;
    };
    return Object.freeze({
      finish: value => settle('fulfilled', value),
      fail: reason => settle('rejected', reason)
    });
  }
  seal() {
    if (this.#state !== 'open') return false;
    this.#state = 'sealed'; this.#flush(); return true;
  }
  join(signal) {
    return new Promise((resolve, reject) => {
      if (signal !== undefined) aborted.call(signal);
      const w = { resolve, reject, signal, live: true, subscription: null };
      this.#waiters.add(w);
      this.#deliver(w);
      if (!w.live || signal === undefined) return;
      try {
        const subscription = addAbortListener(signal, () => this.#deliver(w));
        if (w.live) w.subscription = subscription;
        else subscription[Symbol.dispose]();
        this.#deliver(w);
      } catch (error) { this.#settle(w, true, error); }
    });
  }
  close(reason = new Error('group closed')) {
    if (this.#state === 'closed' || this.#state === 'completed') return false;
    this.#state = 'closed'; this.#reason = reason;
    this.#rows = []; this.#pending = 0; this.#flush(); return true;
  }
  #settle(w, failed, value) {
    if (!w.live) return;
    w.live = false; this.#waiters.delete(w);
    const subscription = w.subscription; w.subscription = null;
    subscription?.[Symbol.dispose]();
    if (failed) w.reject(value); else w.resolve(value);
  }
  #deliver(w) {
    if (!w.live) return;
    if (w.signal !== undefined && aborted.call(w.signal)) {
      this.#settle(w, true, reasonOf.call(w.signal));
    } else if (this.#state === 'closed') this.#settle(w, true, this.#reason);
    else if (this.#state === 'completed') this.#settle(w, false, this.#result);
  }
  #flush() {
    if (this.#state === 'sealed' && this.#pending === 0) {
      this.#state = 'completed';
      this.#result = record({ results: Object.freeze(this.#rows.slice()) });
      this.#rows = [];
    }
    if (this.#state !== 'completed' && this.#state !== 'closed') return;
    for (const w of [...this.#waiters]) this.#deliver(w);
  }
}

const group = new TaskGroup();
let accesses = 0;
const payload = Object.defineProperty({}, 'then', {
  get() { accesses++; throw new Error('payload must remain opaque'); }
});
const a = group.register('opaque'), b = group.register('promise');
const never = new Promise(() => {});
a.finish(payload);
b.finish(never);
group.seal();
const report = await group.join();
assert.equal(report.results[0].value, payload);
assert.equal(report.results[1].value, never);
assert.equal(accesses, 0);
assert.equal(Object.getPrototypeOf(report), null);
const other = new TaskGroup();
const token = other.register('thenable');
let invoked = 0;
const thenable = { then() { invoked++; } };
token.finish(thenable); other.seal();
assert.equal((await other.join()).results[0].value, thenable);
assert.equal(invoked, 0);
console.log(`then accesses=${accesses}, calls=${invoked}`);
console.log('pending promise stored without adoption');

输出:

then accesses=0, calls=0
pending promise stored without adoption

这也限定了 finish 的含义:它是业务方声明交账,并不是请求框架执行 await。想等待一个 Promise,应先在业务任务中 await 它,再把成功或失败交给令牌。若故意把 Promise 作为数据保存,它未来的拒绝仍由拥有者负责处理。浅冻结不会替你消费它、复制它或深冻结它。

代码审查到这里,关键问题应当能够用断言回答:未封口的零会不会提前放行?重复交账能不能篡改结果?生产者是否拥有正确的封口时机?取消是否只影响一个观察者?取消分发中的重入会不会抢走结果?关闭是否保留首个原因?任务载荷是否会被意外采用为另一个异步操作?这些答案比方法名字或代码行数更能说明 AI 生成的工具是否可靠。

最后的边界检查

单次登记和非末次交账的账本操作为常数级;生成报告需要复制全部结果槽,最终唤醒需要遍历全部等待者,存储量随任务数和等待者数增加。这些是结构层面的成本,不包含业务任务,也不把事件订阅清理的底层成本藏进所谓的严格常数时间。没有上限的输入必须由调用方另行限制。

真正值得保留的接口约束只有几条:只有开放状态能登记;封口不可撤销;每个任务最多交账一次;最终完成必须同时满足封口和零欠账;观察取消不更改任务;关闭不宣称停止业务;最终报告不会重新解释任务载荷。让 AI 写出这些规则并不难,难的是逐条设计能推翻错误实现的测试,并且确认展示给读者的输出确实来自同一份代码。

文章版权声明:除非注明,否则均为云鹊BLOG原创文章,转载或复制请以超链接形式并注明出处。