concurrency.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. /**
  2. * 自适应并发控制器:一个 provider key 上的纯 AIMD 状态机。
  3. *
  4. * 纯包纪律:不读时钟、不做 I/O——`now`(ms since epoch)一律由调用方传入;本类只回答
  5. * 「cap 现在是多少、能不能准入、这次信号让 cap 变了没有」。谁喂信号、谁排队(bootstrap 的进程级
  6. * 治理器)都在包外。
  7. *
  8. * 度量单位是**模型请求**(每一次尝试):`inFlight` = 已准入、尚未 release 的请求数。
  9. * 没有 ask 级计数——一个子代理同时只有一个请求在飞,「≤ N 个请求」与「≤ N 个子代理在跑」等价。
  10. *
  11. * 批次阻尼靠 **epoch**:每次准入记下当时的 epoch,每次限流裁决 epoch += 1。一个 429 只在
  12. * 它的请求是在**当前** cap 下发出(epoch 相同)时才评价当前 cap;旧 epoch 的 429 评价的是一个已被
  13. * 砍掉的 cap,只清 streak、刷新 cooldown。成功同理:只有当前 epoch 的成功计入 streak。
  14. *
  15. * 信号方法都返回本次信号引起的 cap 变化列表(通常 0 或 1 条;空闲重置紧接着一次限流时会是 2 条),
  16. * 调用方原样扇出成 `concurrency-changed` 事件。
  17. */
  18. import type { ConcurrencyChange, ConcurrencyChangeReason } from "./types.js";
  19. /**
  20. * 限流即 `cap = max(FLOOR, floor(cap × 0.75))`(系数从 0.5 改为 0.75):
  21. * 减半对「只多了一两个」的越界反应过猛——闸门是请求级的,一次 429 说明 cap 高了,很少说明高了一倍。
  22. */
  23. export const CONCURRENCY_DECREASE_FACTOR = 0.75;
  24. /** 加性递增步长。 */
  25. export const CONCURRENCY_INCREASE_STEP = 1;
  26. /**
  27. * 每 +1 需要的连续成功模型请求数 K。只有一档。该值从 40 降到 4:
  28. * 探测失败的代价只是一个请求撞一次 429 然后退回 `lastGood`(已证明可用的水位),不值得用 40 次
  29. * 成功去换一次试探。
  30. */
  31. export const CONCURRENCY_INCREASE_AFTER_SUCCESSES = 4;
  32. /** 永远至少有一个探针在跑。 */
  33. export const CONCURRENCY_FLOOR = 1;
  34. /** 某 key 空闲这么久(且无在飞)后遗忘学到的 cap,回起点 `initial`(决策 20)。 */
  35. export const CONCURRENCY_IDLE_RESET_MS = 300_000;
  36. /** 会令 cap 减少的限流类原因。 */
  37. export type ConcurrencyThrottleReason = Extract<
  38. ConcurrencyChangeReason,
  39. "rate_limited" | "provider_overloaded" | "offpeak_queued"
  40. >;
  41. /** 控制器的只读快照(供测试断言与治理器投影 run 头的 `concurrency`)。 */
  42. export interface ConcurrencyControllerSnapshot {
  43. readonly key: string;
  44. /** 起点与空闲重置的落点:默认并发 D。 */
  45. readonly initial: number;
  46. /** 自动增长的上界(治理器定,可随时挪动;恒 ≥ initial)。 */
  47. readonly growthLimit: number;
  48. readonly cap: number;
  49. /** 限流裁决计数;准入时发给请求,请求结束时带回来比对。 */
  50. readonly epoch: number;
  51. readonly inFlight: number;
  52. readonly waiters: number;
  53. readonly successStreak: number;
  54. readonly cooldownUntil?: number;
  55. readonly lastRequestAt?: number;
  56. readonly lastGood?: number;
  57. readonly lastBad?: number;
  58. /** 最近一次被拒(不论 epoch)的时刻;五分钟内有它就不起跳({@link ConcurrencyController.seed})。 */
  59. readonly lastThrottledAt?: number;
  60. }
  61. export class ConcurrencyController {
  62. private cap: number;
  63. private growthLimit_: number;
  64. private epoch = 0;
  65. private inFlight = 0;
  66. private waiters_ = 0;
  67. private successStreak = 0;
  68. private cooldownUntil?: number;
  69. private lastRequestAt?: number;
  70. private lastGood?: number;
  71. private lastBad?: number;
  72. private lastThrottledAt?: number;
  73. /**
  74. * @param key provider key(`${providerId}/${modelId}`),只用于填进 change 事件——控制器自己
  75. * 对它无感。放在构造参数而不是每次信号传入:一个控制器只服务一个 key,这是身份不是参数。
  76. * @param initial 默认并发 D(docs/dynamic-workflow/concurrency.md「Two bounds on a run」):cap 的
  77. * 起点,也是空闲重置的落点。它**不是**上界。
  78. * @param growthLimit 自动增长的上界;缺省即 `initial`(只回落、不越过起点的旧行为)。治理器按
  79. * `max(2D, 用过这个 key 的在飞 run 的最大上界)` 给出并随时经 {@link setGrowthLimit} 挪动。
  80. */
  81. constructor(
  82. readonly key: string,
  83. readonly initial: number,
  84. growthLimit: number = initial,
  85. ) {
  86. this.cap = initial;
  87. this.growthLimit_ = Math.max(initial, growthLimit);
  88. }
  89. snapshot(): ConcurrencyControllerSnapshot {
  90. return {
  91. key: this.key,
  92. initial: this.initial,
  93. growthLimit: this.growthLimit_,
  94. cap: this.cap,
  95. epoch: this.epoch,
  96. inFlight: this.inFlight,
  97. waiters: this.waiters_,
  98. successStreak: this.successStreak,
  99. ...(this.cooldownUntil === undefined ? {} : { cooldownUntil: this.cooldownUntil }),
  100. ...(this.lastRequestAt === undefined ? {} : { lastRequestAt: this.lastRequestAt }),
  101. ...(this.lastGood === undefined ? {} : { lastGood: this.lastGood }),
  102. ...(this.lastBad === undefined ? {} : { lastBad: this.lastBad }),
  103. ...(this.lastThrottledAt === undefined ? {} : { lastThrottledAt: this.lastThrottledAt }),
  104. };
  105. }
  106. /**
  107. * 闸门(准入条件):在飞请求数低于 cap 且不在 Retry-After 冷却中。纯查询,不做空闲重置——
  108. * 调用方(治理器)在准入路径上先调 {@link observe}(准入也是一次「信号」,空闲一小时后的第一个
  109. * run 要立刻从起点 `initial` 起步,决策 20)。
  110. */
  111. canAdmit(now: number): boolean {
  112. return (
  113. this.inFlight < this.cap && (this.cooldownUntil === undefined || now >= this.cooldownUntil)
  114. );
  115. }
  116. /** 只做空闲重置检查的「空信号」(准入前、observer 放行前用)。 */
  117. observe(now: number): ConcurrencyChange[] {
  118. return this.idleReset(now);
  119. }
  120. /**
  121. * 一个请求被准入:`inFlight++`、刷新 `lastRequestAt`,返回它所属的 epoch(请求结束时带回来)。
  122. * 不做空闲重置——调用方已在 {@link observe} 里做过;这里若再做,一个刚被 observe 判定「不空闲」
  123. * 的准入不可能变成空闲。
  124. */
  125. admitted(now: number): number {
  126. this.lastRequestAt = now;
  127. this.inFlight += 1;
  128. return this.epoch;
  129. }
  130. /**
  131. * 一个请求成功结束:`inFlight--`;只有**当前 epoch** 的成功使
  132. * `successStreak++`——旧 epoch 的成功证明的是旧 cap 下退避压低后的负载,不是新 cap 可以更高。
  133. * `successStreak ≥ K` 即**证明**当前 cap 可用:`lastGood = max(lastGood, cap)`(决策 40:只有
  134. * 完成的 streak 能设 lastGood,减少 cap 不能)。再满足有等待者 **且** `cap < growthLimit` → +1。
  135. * 无等待者时 streak 照累积但不兑现(决策 15)。
  136. */
  137. succeeded(now: number, epoch: number): ConcurrencyChange[] {
  138. const changes = this.idleReset(now);
  139. this.inFlight = Math.max(0, this.inFlight - 1);
  140. if (epoch !== this.epoch) return changes;
  141. this.successStreak += 1;
  142. if (this.successStreak < CONCURRENCY_INCREASE_AFTER_SUCCESSES) return changes;
  143. // 这一级被一整段 streak 证明可用——不论此刻有没有人等着往上爬。
  144. if (this.lastGood === undefined || this.cap > this.lastGood) this.lastGood = this.cap;
  145. if (this.waiters_ <= 0 || this.cap >= this.growthLimit_) return changes;
  146. const previous = this.cap;
  147. this.cap = Math.min(this.growthLimit_, previous + CONCURRENCY_INCREASE_STEP);
  148. this.successStreak = 0;
  149. changes.push(this.change(previous, "recovered"));
  150. return changes;
  151. }
  152. /**
  153. * 被限流/过载。一律 `inFlight--`、清 streak、带 Retry-After 则把 cooldown
  154. * 推到更晚者。
  155. *
  156. * 只有 `epoch === 当前 epoch` 的 429 才动 cap:它是在当前 cap 下发出的请求,是对当前 cap 的评价;
  157. * 旧 epoch 的 429 忽略(不发事件)。当前 epoch 的分两档:在 `lastGood` **之上**探测被限流 → 退回
  158. * `lastGood`(记 `lastBad`,不按系数减);否则(`lastGood` 缺席或 `cap ≤ lastGood`:墙下移了)→
  159. * `cap = max(FLOOR, floor(cap × 0.75))`,记 `lastBad = 旧 cap`,并**清掉** `lastGood`——它刚被
  160. * 证伪,而新 cap 还没被任何 streak 证明(减 cap 不设 lastGood)。两档之后 `epoch += 1`——
  161. * 即便 cap 已在地板、数值没变,也翻一页:同一批请求只能触发一次裁决。
  162. */
  163. throttled(
  164. now: number,
  165. epoch: number,
  166. reason: ConcurrencyThrottleReason,
  167. retryAfterMs?: number,
  168. ): ConcurrencyChange[] {
  169. const changes = this.idleReset(now);
  170. this.inFlight = Math.max(0, this.inFlight - 1);
  171. this.successStreak = 0;
  172. // 旧 epoch 的拒绝同样记:它不评价当前 cap,却足以说明 provider 此刻就在墙上(起跳看它)。
  173. this.lastThrottledAt = now;
  174. const cooldownMs = retryAfterMs !== undefined && retryAfterMs > 0 ? retryAfterMs : undefined;
  175. if (cooldownMs !== undefined) {
  176. this.cooldownUntil = Math.max(this.cooldownUntil ?? 0, now + cooldownMs);
  177. }
  178. if (epoch !== this.epoch) return changes;
  179. const previous = this.cap;
  180. if (this.lastGood !== undefined && this.cap > this.lastGood) {
  181. this.lastBad = this.cap;
  182. this.cap = this.lastGood;
  183. } else {
  184. this.cap = Math.max(CONCURRENCY_FLOOR, Math.floor(this.cap * CONCURRENCY_DECREASE_FACTOR));
  185. this.lastBad = previous;
  186. this.lastGood = undefined;
  187. }
  188. this.epoch += 1;
  189. // cap 已在地板且无 Retry-After 时确实什么都没变,不发事件;带 Retry-After 的限流即便 cap 不动
  190. // 也要让 run 头知道「冷却至…」,所以带 cooldownMs 的一律发。
  191. if (previous === this.cap && cooldownMs === undefined) return changes;
  192. changes.push(this.change(previous, reason, cooldownMs));
  193. return changes;
  194. }
  195. /** 瞬态但非限流的失败(timeout / 5xx / 网络):`inFlight--`、清 streak,cap 不动。 */
  196. failedTransient(now: number): ConcurrencyChange[] {
  197. const changes = this.idleReset(now);
  198. this.inFlight = Math.max(0, this.inFlight - 1);
  199. this.successStreak = 0;
  200. return changes;
  201. }
  202. /** 一个请求以永久失败 / 取消终结,或 ticket 只见 release 没见终结事件:只做 `inFlight--`。 */
  203. ended(now: number): ConcurrencyChange[] {
  204. const changes = this.idleReset(now);
  205. this.inFlight = Math.max(0, this.inFlight - 1);
  206. return changes;
  207. }
  208. /** 治理器在队列变化时喂入的等待者数(有需求才加 cap)。 */
  209. waiters(now: number, count: number): ConcurrencyChange[] {
  210. const changes = this.idleReset(now);
  211. this.waiters_ = Math.max(0, count);
  212. return changes;
  213. }
  214. /**
  215. * 挪动自动增长的上界(docs/dynamic-workflow/concurrency.md「Increase」)。这是控制器里唯一一个
  216. * 不归它自己管的数:治理器按「2D 与用过这个 key 的在飞 run 的最大上界取大」算出来,run 来去、
  217. * retune 都会让它变。恒夹到 ≥ initial。
  218. *
  219. * 抬高什么都不立刻改:cap 照旧一级一级爬。压低到 cap 之下则当场把 cap 拉到新上界并发一条
  220. * `limit_lowered`——否则一个为大 run 学到的高 cap 会留给之后的默认 run 共用,直到空闲重置。
  221. * 同时夹 `lastGood`、清 streak、翻 epoch:旧 cap 下发出的请求撞的 429 不是对新 cap 的裁决。
  222. */
  223. setGrowthLimit(now: number, limit: number): ConcurrencyChange[] {
  224. const changes = this.idleReset(now);
  225. this.growthLimit_ = Math.max(this.initial, Math.floor(limit));
  226. if (this.cap <= this.growthLimit_) return changes;
  227. const previous = this.cap;
  228. this.cap = this.growthLimit_;
  229. if (this.lastGood !== undefined && this.lastGood > this.cap) this.lastGood = this.cap;
  230. this.successStreak = 0;
  231. this.epoch += 1;
  232. changes.push(this.change(previous, "limit_lowered"));
  233. return changes;
  234. }
  235. /**
  236. * 起跳(docs/dynamic-workflow/concurrency.md「Seeding」):用户把一个 run 的上界调高时,治理器请
  237. * cap 直接跳到 `min(target, growthLimit)`,而不是每 K 次成功爬一级——从 8 爬到 32 要约 96 次
  238. * 成功,用户看到的是「设置没生效」。
  239. *
  240. * 清 `lastGood`:起跳点是新的起点,不是在已证明水位之上的探测;否则第一次 429 会一路退回旧的
  241. * 已证明水位,而不是按系数减(32 → 24 → 18 …)。同时清 `lastBad`、清 streak、翻 epoch。
  242. *
  243. * 两种情况不跳:目标不高于 cap;五分钟内(空闲重置同一窗口)有过任何一次拒绝——那时起跳就是
  244. * 明知故犯地对着刚撞过的墙再冲一波,cap 改为照常一级一级爬。
  245. */
  246. seed(now: number, target: number): ConcurrencyChange[] {
  247. const changes = this.idleReset(now);
  248. const next = Math.min(this.growthLimit_, Math.floor(target));
  249. if (next <= this.cap) return changes;
  250. if (
  251. this.lastThrottledAt !== undefined &&
  252. now - this.lastThrottledAt < CONCURRENCY_IDLE_RESET_MS
  253. ) {
  254. return changes;
  255. }
  256. const previous = this.cap;
  257. this.cap = next;
  258. this.lastGood = undefined;
  259. this.lastBad = undefined;
  260. this.successStreak = 0;
  261. this.epoch += 1;
  262. changes.push(this.change(previous, "seeded"));
  263. return changes;
  264. }
  265. // ——————————————————————————————— 内部 ———————————————————————————————
  266. /**
  267. * 空闲重置(决策 20):`now − lastRequestAt ≥ IDLE_RESET_MS` 且无在飞 → cap 回起点 `initial`,
  268. * 清 streak / cooldown / lastGood / lastBad,epoch += 1。惰性发生在任一信号到达时(无定时器)。
  269. */
  270. private idleReset(now: number): ConcurrencyChange[] {
  271. if (
  272. this.lastRequestAt === undefined ||
  273. this.inFlight !== 0 ||
  274. now - this.lastRequestAt < CONCURRENCY_IDLE_RESET_MS
  275. ) {
  276. return [];
  277. }
  278. const previous = this.cap;
  279. // 幂等:已在起点且状态干净时什么都不做(否则每个空闲信号都翻一页 epoch)。
  280. if (
  281. previous === this.initial &&
  282. this.successStreak === 0 &&
  283. this.cooldownUntil === undefined &&
  284. this.lastGood === undefined &&
  285. this.lastBad === undefined &&
  286. this.lastThrottledAt === undefined
  287. ) {
  288. return [];
  289. }
  290. this.cap = this.initial;
  291. this.successStreak = 0;
  292. this.cooldownUntil = undefined;
  293. this.lastGood = undefined;
  294. this.lastBad = undefined;
  295. this.lastThrottledAt = undefined;
  296. this.epoch += 1;
  297. // lastRequestAt 保留:下一次仍空闲的信号不该再「重置」一次;反正状态已在起点。
  298. return previous === this.cap ? [] : [this.change(previous, "idle_reset")];
  299. }
  300. private change(
  301. previous: number,
  302. reason: ConcurrencyChangeReason,
  303. cooldownMs?: number,
  304. ): ConcurrencyChange {
  305. return {
  306. key: this.key,
  307. previous,
  308. next: this.cap,
  309. reason,
  310. ...(this.lastGood === undefined ? {} : { lastGood: this.lastGood }),
  311. ...(this.lastBad === undefined ? {} : { lastBad: this.lastBad }),
  312. ...(cooldownMs === undefined ? {} : { cooldownMs }),
  313. };
  314. }
  315. }