Repository navigation
fix(watch): preemptible condition evaluation — 25 ms budget in a worker, over budget = no match (#113) - #114
Merged
Conversation
…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)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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,冻结)terminate()并重建;worker 冷启动不计入预算(否则良性形状第一轮就会被误判)。blind_checks、不动timeoutMs/intervalMs、绝不判失败或 kill。每任务计数器matchBudgetExceeded(async_status+ TUI 详情),每条任务只提示一次。(a+)+$)。await之后必须重判isTerminal/stopped/suspended,终态快照是唯一记录。落点
src/core/regex-worker.ts(新)ref/unref(空闲不钉住宿主,在途不早退)、按 pattern 缓存RegExp(保持 main 的"首次冷、之后热"代价形状)src/core/watch.ts:345output_matches只经evaluateWithBudget;evalConditions/evaluateConditionsDetailed变异步(没有同步入口留给灾难正则)src/core/watch.ts:162/:260onMatchBudgetExceeded(count)→noteBudget(),纯计数,不参与失败判定src/core/watch.ts:232/:239await之后重判stopped/finished(裁决 5)src/core/registry.ts:737src/core/registry.ts:475/:481await后重判isTerminal/suspended/retiredsrc/core/task.ts:118TaskSnapshot.matchBudgetExceeded(进async_status)src/core/regex-worker.ts:109budget(不是error)——否则一个病态正则能把别的 watch 的blind_checks花光src/tui/panel.ts:109src/core/notify.ts:213async-watch-notice,followUp,不触发新回合)验收
tests/w3-preemption.test.ts第 1 例。matchBudgetExceeded ≥ 1(async_status可见),任务仍running,无failureKind,watchDeadline不动,blind_checks: 1也不触发 blind(若越预算被当 error 会立刻blind_exhausted)。提示恰好 1 次(跨 2 轮)。scripts/watch-preemption-bench.mjs --tree <main>vs 本分支,15 行对照表 verdict 全同(见报告 §4)。timeoutMs仍生效:挂住场景下 2 s 的 watch timeout 在 < 4.5 s 内结算(修前被 5 s 求值饿死)。the 10 ms timer was starved: it fired after 5034 ms);② 越预算当失败 → 验收 2 红(an over-budget round must never settle the task: 'failed' !== 'running')。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 typecheckexit 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。