Skip to content

fix(watch): preemptible condition evaluation — 25 ms budget in a worker, over budget = no match (#113) - #114

Merged
zzjcool merged 6 commits into
mainfrom
pi-subagent/piasync-113-preempt-1fd02167
Nov 24, 2026
Merged

zzjcool merged 6 commits into
mainfrom
pi-subagent/piasync-113-preempt-1fd02167

Conversation

@zzjcool

@zzjcool zzjcool commented Nov 24, 2026 •

Copy link
Copy Markdown
Owner

Fixes #113

output_matches 的正则求值从主线程搬到可抢占的 worker thread,单次求值硬预算 25 ms;越预算 = 该轮未命中,不是失败。

为什么这不是"加个超时"

docs/reports/redos-benchmark.md(#112)已经量到:26 码元的 "a"*25+"!" 配 (a|a)*$ 冷路径 5.02 s,期间事件循环完全停摆——先上弦的 100 ms 定时器被拖到 3.12 s。所以"求值完再检查耗时"是无效实现:那段时间进程里什么都跑不了。求值必须离开这个线程。同一份证据也证伪了契约里"64K 限制 ReDoS 影响面"的说法(19 码元就越过 25 ms),那条理由先被改掉(docs/CONTRACT.md §4 / §20.2),再谈实现。

契约(docs/CONTRACT.md §26,REV-34,冻结)

  • 裁决 1:求值必须在可抢占上下文里,单次预算 25 ms;worker 复用,越预算即 terminate() 并重建;worker 冷启动不计入预算(否则良性形状第一轮就会被误判)。
  • 裁决 2:越预算 = 该轮该条件未命中。不累计 blind_checks、不动 timeoutMs/intervalMs、绝不判失败或 kill。每任务计数器 matchBudgetExceeded(async_status + TUI 详情),每条任务只提示一次。
  • 裁决 3:64K 窗口保留,理由是内存 / 取舍边界,不是 ReDoS 防线。
  • 裁决 4:形状黑名单是深度防御,不是防线(4 个已知形状只挡住 (a+)+$)。
  • 裁决 5:异步化后的交错——await 之后必须重判 isTerminal / stopped / suspended,终态快照是唯一记录。

落点

位置 内容
src/core/regex-worker.ts(新) worker 池:复用、25 ms 预算、越界 terminate+重建、ref/unref(空闲不钉住宿主,在途不早退)、按 pattern 缓存 RegExp(保持 main 的"首次冷、之后热"代价形状)
src/core/watch.ts:345 output_matches 只经 evaluateWithBudget;evalConditions / evaluateConditionsDetailed 变异步(没有同步入口留给灾难正则)
src/core/watch.ts:162 / :260 onMatchBudgetExceeded(count) → noteBudget(),纯计数,不参与失败判定
src/core/watch.ts:232 / :239 每个 await 之后重判 stopped/finished(裁决 5)
src/core/registry.ts:737 计数器 + 一次性提示的闩锁(持久化,reload 不重播)
src/core/registry.ts:475 / :481 进程退出路径同样走预算,await 后重判 isTerminal/suspended/retired
src/core/task.ts:118 TaskSnapshot.matchBudgetExceeded(进 async_status)
src/core/regex-worker.ts:109 预算杀 worker 时邻居那轮答 budget(不是 error)——否则一个病态正则能把别的 watch 的 blind_checks 花光
src/tui/panel.ts:109 详情页一行:"N abandoned verdicts (25 ms budget) · no verdict, not a failure"
src/core/notify.ts:213 一次性提示(async-watch-notice,followUp,不触发新回合)

验收

  1. 事件循环未被冻结:10 ms 定时器在 26 码元与 30 码元两种输入下都在 ~11 ms 触发(修前 5547 / 13308 ms)。测试:tests/w3-preemption.test.ts 第 1 例。
  2. 不是失败:matchBudgetExceeded ≥ 1(async_status 可见),任务仍 running,无 failureKind,watchDeadline 不动,blind_checks: 1 也不触发 blind(若越预算被当 error 会立刻 blind_exhausted)。提示恰好 1 次(跨 2 轮)。
  3. 良性逐字不变:scripts/watch-preemption-bench.mjs --tree <main> vs 本分支,15 行对照表 verdict 全同(见报告 §4)。
  4. timeoutMs 仍生效:挂住场景下 2 s 的 watch timeout 在 < 4.5 s 内结算(修前被 5 s 求值饿死)。
  5. 变异 2 条必红:① 去掉预算回到同步 → 验收 1 红(the 10 ms timer was starved: it fired after 5034 ms);② 越预算当失败 → 验收 2 红(an over-budget round must never settle the task: 'failed' !== 'running')。
  6. 契约改动与 REV 条目单独成提交(fe24dc6),先于实现提交(6bf7feb)。

对抗式复核(fresh context)

三个只读 reviewer(正确性/回归、测试覆盖、简洁性/契约可读性)。第三个给出 1 blocker + 9 major + 8 minor,
逐条处置写进报告 §9:退出路径漏记预算(真缺陷,已修 + 回归测试)、详情行破坏 §21.1/§24 冻结的 2 行 header
(改为显式修订契约)、新措辞"影响面与窗口大小无关"本身不成立(已改准)、文案把"被放弃的裁决"说成"测量到
未命中"(已改,并新增裁决 4b)、§26 缺 §16 强制的「影响面」段(已补)、裁决 4 与测试量具冲突(已澄清)、
~25 行死代码(已删)、裁决 3/5 无测试(已补两条)。另外两个 reviewer 的宿主连接在运行中被 provider 反复
ECONNRESET(空转,已强制回收,无产出)——所以复核覆盖只有一个完整清单,这是它的诚实边界。
另外自查抓到一条复核没提的真缺陷:共享 worker 被预算 terminate 时,同一窗口里在飞的邻居求值被答成
error(会花掉别的任务的 blind_checks,三轮后误判失败)——已修 + 并发回归测试(报告 §5 变异 ④)。另外把"同一轮里 failure_when 越预算、
success_when 命中"的优先级钉成契约条目 + 测试(按 success 结算,仍记一次 burned budget)。

仓库健康

  • npm run typecheck exit 0。
  • npm test:本机 macOS 501 tests / 472 pass / 16 fail / 13 skip;origin/main 同机基线 489 / 460 / 16 fail / 13 skip,失败集合逐条同名(diff 为空);新增 12 例全绿。
  • 证据与原始日志:docs/reports/watch-preemption.md;复跑 node --experimental-strip-types scripts/watch-preemption-bench.mjs。

…113)

CONTRACT.md:159 and :1164 explained MAX_MATCH_CHARS (64K code units) as
"limiting the ReDoS blast radius". The #112 evidence falsifies that cause:
19 code units already blow a 25 ms budget and 26 code units froze the host
for 5 s, so the blast radius has nothing to do with the window size.

- both places now say: memory / trade-off bound, NOT a ReDoS defence
- new \u00a726 REV-34 (draft, semantics frozen now): every output_matches
  evaluation runs in a preemptible worker with a hard 25 ms budget, worker
  reused, terminate+rebuild on overrun; over-budget == not matched this
  round (no blind accumulation, no timeoutMs change, never a failure),
  per-task matchBudgetExceeded counter, one notice per task
- REV-34 ruling 4: the shape blacklist is depth defence, never the defence
- src comments (watch.ts window/blacklist, registry.ts WATCH_READ_BYTES)
  aligned with the corrected cause
- CHANGELOG: new Unreleased 0.5.3 (fix) section

No behaviour change in this commit.
…113)

The regex ran on the main thread, so a pathological shape froze the whole
host: 26 code units of (a|a)*$ took 5.02 s cold and dragged an already-armed
100 ms timer out to 3.12 s, which means timeoutMs/intervalMs could not
preempt it either.

- new src/core/regex-worker.ts: single reused worker thread, hard 25 ms
  per-evaluation budget, terminate+rebuild on overrun (worker start-up stays
  outside the budget so a benign first round is never a false positive),
  ref/unref so an idle worker never pins the host, per-pattern RegExp cache
  to keep main's cold-then-warm cost shape
- evalConditions / evaluateConditionsDetailed are async: no synchronous
  regex path is left to freeze on
- over budget == not matched this round: no blind_checks consumption, no
  timeoutMs change, never failed/killed; per-task matchBudgetExceeded
  counter in the snapshot (async_status), the TUI detail line, and one
  notice per task through the notification channel
- WatchLoop awaits with an in-flight guard and re-checks stopped/finished
  after every await (REV-R5); the process-exit evaluation does the same and
  re-checks isTerminal/suspended/retired
- tests: w2/b-watch-conditions converted to await; new tests/w3-preemption
  covers acceptance 1 (10 ms timer within 200 ms), 2 (counter, no failure),
  4 (timeout still fires), worker rebuild and 64K benign parity rows
…idence harness

- README + skills/async-tasks/SKILL.md: output_matches has a hard 25 ms
  per-evaluation worker budget; over budget is a no-match (counter in
  async_status, told once), never a failure
- scripts/watch-preemption-bench.mjs: pre/post event-loop freeze demo and a
  benign parity matrix that can target any checkout (--tree) so main and the
  branch produce diffable rows
- tests/w3-preemption: assert the freeze line (timer) before the verdict, and
  pin 'not a failure' right after the first burned budget so a mutation that
  fails the task trips on the assertion that names it
…section

Adversarial review (fresh context, read-only) findings, all addressed:

- M2: the process-exit evaluation threw away its budget count; it now goes
  through evaluateConditionsDetailed and credits the same per-task counter
  (REV-34 ruling 5 says the exit path is a round like any other) + a
  regression test that fails without the fix
- M3: the extra detail status line changes the frozen 'header = 2 lines'
  invariant, so §21.1/§24 are amended explicitly (1-2 lines) instead of the
  contract silently drifting
- M4: 'the blast radius is independent of the window size' was itself false
  (cost grows with length); now: the window caps cost, but the cap is already
  far above the budget at ~16 code units, so it is neither a defence nor an
  acceptable upper bound
- M5: copy said 'treated as no match' for an abandoned verdict; the shape
  actually does match eventually, so the notice/TUI/README/skill now say the
  verdict was abandoned and a real match or failure can be missed (new
  ruling 4b in §26)
- M6: §26 gains the §16-mandated 影响面 section (async-watch-notice delivery
  semantics, new optional snapshot field judged non-breaking, metadata latch,
  internal API becoming async)
- M7: ruling 4 now says the three pathological shapes are deliberately still
  accepted (they are #113's test vehicle) and any tightening must switch the
  vehicle in the same change
- M8: delete dead code (disposeRegexWorker, regexWorkerAlive, budgetMs param,
  unused registry param ~25 lines); MATCH_BUDGET_MS moves to watch.ts so the
  TUI no longer pulls worker_threads into its module graph
- M9: add the missing tests: contract drift guard (the 64K sentences must stay
  gone) and 'a round in flight when stop() lands reports nothing' (ruling 5)
- minors: stale self-pointers, dangling 'REV-R3 below', README unit mix-up,
  CHANGELOG quoting a string that does not exist, logOnce permanently muted
- docs/reports/watch-preemption.md: the full evidence report (pre/post raw
  logs, 15-row parity table with the diff, three mutations, health, review
  disposition, the zero-width-match trap, the jiti loader check)
Several watch loops share one worker. When the budget overrun terminates it,
the evaluations that were in flight alongside were answered as `error` — which
is the infrastructure-failure channel and spends ANOTHER task's blind_checks,
so three rounds of a healthy watch could be failed by a neighbour's
pathological regex.

teardown()/failAll() now carry the distinction: a worker killed for burning
its budget interrupts its neighbours with `budget` (no verdict → counts as a
no-match round, REV-34 ruling 2), while a worker that actually died still
answers `error`. Regression test starts two pathological evaluations in one
tick and requires zero errors.

Report updated: mutation 4, the shared-worker rule in the semantics table, the
per-pattern cache bound, and the final numbers (500 tests / 471 pass / 16 fail
/ 13 skip, failure set identical to origin/main).
… vs real hit)

A round can burn failure_when's budget and still hit success_when. The groups
are OR-ed and failure_when runs first (unchanged), so the real hit settles the
watch and the burned failure verdict is only counted — refusing a genuine match
because another condition's verdict was abandoned would be strictly worse.

- CONTRACT §26 ruling 2 gains that bullet
- test pins it: pathological failure_when + matching success_when → success,
  zero failures, exactly one burned-budget report
- report: the row, and the final numbers (501 tests / 472 pass / 16 fail /
  13 skip, failure set identical to origin/main)
@zzjcool
zzjcool merged commit adb03eb into main Nov 24, 2026
5 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix(watch): 条件求值可抢占 —— 26 码元即可冻死事件循环(64K 不是 ReDoS 防线)

1 participant