Repository navigation
perf: adaptive DOM-quiet settle and parallel audit_site crawl - #158
JustasMonkev wants to merge 1 commit into
Conversation
Two changes that together roughly halve total tool latency on the MCP benchmark and cut interactive-action latency by 3-4x: 1. Adaptive settle after actions. waitForCompletion slept a fixed 500ms (plus a 100ms quiet window) after every action, even on a page that did nothing. The settle is now an in-page MutationObserver wait that ends once the DOM has been mutation-free for 100ms, with the configured settle timeout as the unchanged ceiling; the quiet window is folded into it, since the settle lasts at least the quiet threshold with the request listeners still armed. Child-frame navigations are tracked explicitly so a srcdoc/data: frame swap still earns a post-work settle the top-document observer cannot see. Falls back to the fixed delay when the page cannot host the observer. 2. Parallel audit_site crawl. Pages are crawled by a pool of worker tabs (new `concurrency` parameter, default 4, max 8) instead of one tab in series, overlapping navigation, settle and scan time. maxPages accounting and per-page error handling are unchanged; cookie-loss monitoring is serialized under a lock, so under concurrency a loss is attributed to the page whose check first observed it, and `concurrency: 1` restores exact attribution (the MCP harness session-loss scenarios pin that). bench/mcp-bench.mjs medians, before -> after (3 iterations, local fixtures): browser_click 752 -> 210ms, browser_type 688 -> 167ms, browser_press_key 677 -> 155ms, audit_keyboard (12 tabs) 7425 -> 1381ms, audit_site (6 pages) 2809 -> 1282ms; total end-to-end tool latency 21540 -> 9934ms. audit_keyboard with its default of 50 tab stops and audit_site on real (non-localhost) sites gain the most, since the removed fixed sleeps and the overlapped navigations dominate there. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Wqxm62TvhTxCndqSFLMdP1
📝 WalkthroughWalkthroughThe change adds configurable parallel crawling to ChangesAudit runtime behavior
Estimated code review effort: 4 (Complex) | ~45 minutes Possibly related PRs
Suggested reviewers: Sequence Diagram(s)sequenceDiagram
participant audit_site
participant WorkerTabs
participant URLQueue
participant CookieJar
participant AxeScanner
audit_site->>WorkerTabs: Create configured worker tabs
WorkerTabs->>URLQueue: Claim unique URLs
WorkerTabs->>CookieJar: Read and compare cookies through the shared lock
WorkerTabs->>AxeScanner: Scan pages and enqueue discovered links
WorkerTabs->>URLQueue: Report completion and wake idle workers
audit_site->>WorkerTabs: Close all worker tabs
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/tools/auditSite.ts (1)
641-668: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick winProtect the serialized cookie work from aborting the crawl.
processQueueItemcatches failures fromnavigate,readPage, andrunAxeScan, but thefinallyblock is unprotected.findCookieLosscallspage.url()and can throw if the worker tab closed. A throw insidefinallyreplaces the per-page error and propagates out ofprocessQueueItem, so the page-level isolation is lost.Wrap the cookie-loss check so a failure degrades to "no loss detected" instead of failing the run.
🛡️ Proposed fix
if (baselineCookies.size) { - await withCookieLock(async () => { + await withCookieLock(async () => { if (!baselineCookies.size) return; const loss = await findCookieLoss(workerTab.page, cookieScopeUrls, baselineCookies, item.url, urlBeforeNavigation); if (loss) { sessionLosses.push({ url: loss.url, cookies: loss.cookies }); // Removed from the jar snapshot too, or a later-discovered URL // could re-admit an already-reported cookie to the baseline and // report the same loss twice. for (const identity of loss.identities) { baselineCookies.delete(identity); initialCookieIdentities.delete(identity); } } - }); + }).catch(() => undefined); }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/tools/auditSite.ts` around lines 641 - 668, Protect the cookie-loss handling in the finally block of processQueueItem by catching failures from withCookieLock and findCookieLoss, including worker-tab closure errors. Treat any such failure as no cookie loss detected, preserve existing loss recording and baseline cleanup when successful, and prevent the exception from escaping processQueueItem or replacing the page-level result.
🧹 Nitpick comments (2)
src/tools/auditSite.ts (1)
526-526: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueAlign the local fallback with the schema default.
The schema defaults
concurrencyto4. This line falls back to1whenparams.concurrencyisundefined. The two defaults disagree. Callers that reachhandlewithout schema parsing get sequential crawling instead of the documented default.♻️ Proposed change
- const concurrency = Math.max(1, Math.min(params.concurrency ?? 1, 8)); + const concurrency = Math.max(1, Math.min(params.concurrency ?? 4, 8));🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/tools/auditSite.ts` at line 526, Update the concurrency fallback in the handle flow to use the schema’s default of 4 instead of 1, while preserving the existing minimum and maximum bounds.README.md (1)
378-378: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueState the accepted
concurrencyrange.The schema in
src/tools/auditSite.tsaccepts 1 to 8 and rejects other values. The bullet documents only the default of4. A caller that passes10gets a validation error with no documented bound.📝 Proposed doc change
-- Crawls up to `concurrency` pages in parallel (default `4`), each in its own tab of the shared context; set `concurrency: 1` for strictly sequential crawling — when exact session-loss attribution matters, or when the target server should not receive concurrent page loads +- Crawls up to `concurrency` pages in parallel (`1`–`8`, default `4`), each in its own tab of the shared context; set `concurrency: 1` for strictly sequential crawling — when exact session-loss attribution matters, or when the target server should not receive concurrent page loads🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@README.md` at line 378, Update the README crawling bullet to document that concurrency accepts values from 1 through 8, while retaining the existing default of 4 and sequential-crawling guidance.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@src/tools/auditSite.ts`:
- Around line 674-723: Update the crawl orchestration around crawlWorker and
Promise.all to capture each worker’s failure, await all workers’ completion with
Promise.allSettled, and only then run the existing tab cleanup in finally.
Preserve the first worker error for the crawl result while ensuring sibling
workers finish against open tabs and their rejections are observed.
In `@src/tools/utils.ts`:
- Around line 74-86: Update the promise passed to raceTimeout in the settle flow
around callOnPageNoTrace so the page.evaluate promise has a rejection handler
attached before racing. Consume any late rejection from the losing evaluate
operation while preserving the existing timeout and fallback behavior.
---
Outside diff comments:
In `@src/tools/auditSite.ts`:
- Around line 641-668: Protect the cookie-loss handling in the finally block of
processQueueItem by catching failures from withCookieLock and findCookieLoss,
including worker-tab closure errors. Treat any such failure as no cookie loss
detected, preserve existing loss recording and baseline cleanup when successful,
and prevent the exception from escaping processQueueItem or replacing the
page-level result.
---
Nitpick comments:
In `@README.md`:
- Line 378: Update the README crawling bullet to document that concurrency
accepts values from 1 through 8, while retaining the existing default of 4 and
sequential-crawling guidance.
In `@src/tools/auditSite.ts`:
- Line 526: Update the concurrency fallback in the handle flow to use the
schema’s default of 4 instead of 1, while preserving the existing minimum and
maximum bounds.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro Plus
Run ID: bb3ec738-91ef-4ac4-83c8-bd0a62b5bb51
📒 Files selected for processing (7)
.claude/run-mcp-direct-harness.mjsREADME.mdsrc/program.tssrc/tools/auditSite.tssrc/tools/utils.tstests/tools-auditSite.integration.test.tstests/tools-utils.test.ts
| const crawlWorker = async (workerTab: typeof tab) => { | ||
| while (pages.length < params.maxPages) { | ||
| const item = queue.shift(); | ||
| if (!item) { | ||
| // Pages still in flight may discover more links; when nothing is in | ||
| // flight, nothing can be discovered and the crawl is done. | ||
| if (!inFlight) | ||
| return; | ||
| await new Promise<void>(resolve => idleWaiters.push(resolve)); | ||
| continue; | ||
| } | ||
| queued.delete(item.url); | ||
| if (visited.has(item.url)) { | ||
| skippedUrls++; | ||
| continue; | ||
| } | ||
| visited.add(item.url); | ||
| inFlight++; | ||
| try { | ||
| await processQueueItem(workerTab, item); | ||
| } finally { | ||
| inFlight--; | ||
| wakeIdleWorkers(); | ||
| } | ||
| } | ||
| }; | ||
|
|
||
| try { | ||
| // Tab creation and the baseline reads live inside the try so a failure | ||
| // mid-pool still closes the tabs already opened. | ||
| for (let index = 0; index < Math.min(concurrency, params.maxPages); index++) | ||
| crawlTabs.push(await context.newTab()); | ||
| // The whole jar is snapshotted once, so a URL discovered mid-crawl can only | ||
| // add identities that existed when the crawl started. Without this, a cookie | ||
| // minted by an earlier crawled page would enter the baseline at discovery | ||
| // and its later removal would be misreported as losing a crawl-start cookie. | ||
| initialCookieIdentities = new Set( | ||
| (await crawlTabs[0].page.context().cookies().catch(() => [])) | ||
| .map(cookie => `${cookie.name}\n${cookie.domain}\n${cookie.path}`)); | ||
| baselineCookies = await readCrawlCookies(crawlTabs[0].page, cookieScopeUrls); | ||
| await Promise.all(crawlTabs.map(workerTab => crawlWorker(workerTab))); | ||
| } finally { | ||
| const crawlTabIndex = context.tabs().indexOf(crawlTab); | ||
| if (crawlTabIndex !== -1) | ||
| await context.closeTab(crawlTabIndex); | ||
| // A worker failing must still release every idle sibling, or the crawl | ||
| // would hang on waiters nobody wakes again. | ||
| wakeIdleWorkers(); | ||
| for (const workerTab of crawlTabs) { | ||
| const workerTabIndex = context.tabs().indexOf(workerTab); | ||
| if (workerTabIndex !== -1) | ||
| await context.closeTab(workerTabIndex); | ||
| } |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift
One failing worker abandons its siblings and then closes their tabs.
Promise.all rejects as soon as one crawlWorker rejects. The other worker promises keep running. The finally block then closes every tab in crawlTabs, including tabs that in-flight workers still use. Those workers continue against closed pages and their rejections are no longer awaited, so they surface as unhandled rejections. The whole crawl also loses the report even though most pages scanned successfully.
Capture per-worker failures and wait for every worker before cleanup.
🛡️ Proposed fix
- await Promise.all(crawlTabs.map(workerTab => crawlWorker(workerTab)));
+ // Every worker must finish before the finally block closes the tabs;
+ // a sibling still navigating a closed tab would fail for no reason.
+ const workerResults = await Promise.allSettled(crawlTabs.map(workerTab => crawlWorker(workerTab)));
+ const failed = workerResults.find(result => result.status === 'rejected');
+ if (failed && !pages.length)
+ throw (failed as PromiseRejectedResult).reason;Note: wakeIdleWorkers() in the finally block already assumes a worker can fail. With Promise.allSettled the waiters are released by the loop condition instead, so the crawl still terminates.
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| const crawlWorker = async (workerTab: typeof tab) => { | |
| while (pages.length < params.maxPages) { | |
| const item = queue.shift(); | |
| if (!item) { | |
| // Pages still in flight may discover more links; when nothing is in | |
| // flight, nothing can be discovered and the crawl is done. | |
| if (!inFlight) | |
| return; | |
| await new Promise<void>(resolve => idleWaiters.push(resolve)); | |
| continue; | |
| } | |
| queued.delete(item.url); | |
| if (visited.has(item.url)) { | |
| skippedUrls++; | |
| continue; | |
| } | |
| visited.add(item.url); | |
| inFlight++; | |
| try { | |
| await processQueueItem(workerTab, item); | |
| } finally { | |
| inFlight--; | |
| wakeIdleWorkers(); | |
| } | |
| } | |
| }; | |
| try { | |
| // Tab creation and the baseline reads live inside the try so a failure | |
| // mid-pool still closes the tabs already opened. | |
| for (let index = 0; index < Math.min(concurrency, params.maxPages); index++) | |
| crawlTabs.push(await context.newTab()); | |
| // The whole jar is snapshotted once, so a URL discovered mid-crawl can only | |
| // add identities that existed when the crawl started. Without this, a cookie | |
| // minted by an earlier crawled page would enter the baseline at discovery | |
| // and its later removal would be misreported as losing a crawl-start cookie. | |
| initialCookieIdentities = new Set( | |
| (await crawlTabs[0].page.context().cookies().catch(() => [])) | |
| .map(cookie => `${cookie.name}\n${cookie.domain}\n${cookie.path}`)); | |
| baselineCookies = await readCrawlCookies(crawlTabs[0].page, cookieScopeUrls); | |
| await Promise.all(crawlTabs.map(workerTab => crawlWorker(workerTab))); | |
| } finally { | |
| const crawlTabIndex = context.tabs().indexOf(crawlTab); | |
| if (crawlTabIndex !== -1) | |
| await context.closeTab(crawlTabIndex); | |
| // A worker failing must still release every idle sibling, or the crawl | |
| // would hang on waiters nobody wakes again. | |
| wakeIdleWorkers(); | |
| for (const workerTab of crawlTabs) { | |
| const workerTabIndex = context.tabs().indexOf(workerTab); | |
| if (workerTabIndex !== -1) | |
| await context.closeTab(workerTabIndex); | |
| } | |
| const crawlWorker = async (workerTab: typeof tab) => { | |
| while (pages.length < params.maxPages) { | |
| const item = queue.shift(); | |
| if (!item) { | |
| // Pages still in flight may discover more links; when nothing is in | |
| // flight, nothing can be discovered and the crawl is done. | |
| if (!inFlight) | |
| return; | |
| await new Promise<void>(resolve => idleWaiters.push(resolve)); | |
| continue; | |
| } | |
| queued.delete(item.url); | |
| if (visited.has(item.url)) { | |
| skippedUrls++; | |
| continue; | |
| } | |
| visited.add(item.url); | |
| inFlight++; | |
| try { | |
| await processQueueItem(workerTab, item); | |
| } finally { | |
| inFlight--; | |
| wakeIdleWorkers(); | |
| } | |
| } | |
| }; | |
| try { | |
| // Tab creation and the baseline reads live inside the try so a failure | |
| // mid-pool still closes the tabs already opened. | |
| for (let index = 0; index < Math.min(concurrency, params.maxPages); index++) | |
| crawlTabs.push(await context.newTab()); | |
| // The whole jar is snapshotted once, so a URL discovered mid-crawl can only | |
| // add identities that existed when the crawl started. Without this, a cookie | |
| // minted by an earlier crawled page would enter the baseline at discovery | |
| // and its later removal would be misreported as losing a crawl-start cookie. | |
| initialCookieIdentities = new Set( | |
| (await crawlTabs[0].page.context().cookies().catch(() => [])) | |
| .map(cookie => `${cookie.name}\n${cookie.domain}\n${cookie.path}`)); | |
| baselineCookies = await readCrawlCookies(crawlTabs[0].page, cookieScopeUrls); | |
| // Every worker must finish before the finally block closes the tabs; | |
| // a sibling still navigating a closed tab would fail for no reason. | |
| const workerResults = await Promise.allSettled(crawlTabs.map(workerTab => crawlWorker(workerTab))); | |
| const failed = workerResults.find(result => result.status === 'rejected'); | |
| if (failed && !pages.length) | |
| throw (failed as PromiseRejectedResult).reason; | |
| } finally { | |
| // A worker failing must still release every idle sibling, or the crawl | |
| // would hang on waiters nobody wakes again. | |
| wakeIdleWorkers(); | |
| for (const workerTab of crawlTabs) { | |
| const workerTabIndex = context.tabs().indexOf(workerTab); | |
| if (workerTabIndex !== -1) | |
| await context.closeTab(workerTabIndex); | |
| } |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@src/tools/auditSite.ts` around lines 674 - 723, Update the crawl
orchestration around crawlWorker and Promise.all to capture each worker’s
failure, await all workers’ completion with Promise.allSettled, and only then
run the existing tab cleanup in finally. Preserve the first worker error for the
crawl result while ensuring sibling workers finish against open tabs and their
rejections are observed.
| await raceTimeout( | ||
| callOnPageNoTrace(tab.page, page => page.evaluate(inPageDomQuietWait, { | ||
| quietMs: Math.min(domQuietMs, settleMs), | ||
| maxMs: settleMs, | ||
| })), | ||
| settleMs, | ||
| ); | ||
| return; | ||
| } catch { | ||
| // The page could not host the observer - a navigation racing the settle, | ||
| // or the page closing. Fall back to the fixed delay for whatever remains | ||
| // of the budget, through the path that understands blocked JavaScript. | ||
| } |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Locate raceTimeout and inspect how it handles the losing promise.
rg -nP -C 15 'function raceTimeout|const raceTimeout' --type=tsRepository: JustasMonkev/mcp-accessibility-scanner
Length of output: 176
🏁 Script executed:
#!/bin/bash
set -u
echo "TRAVIS-ish?"; env | rg -i 'TRAVIS|CI' || true
echo "Top-level files:"
git ls-files | sed -n '1,120p'
echo "Find utils.ts:"
fd -a 'utils\.ts$' . || true
echo "Find raceTimeout text all tracked files:"
rg -n -C 8 'raceTimeout|settleAfterAction|domQuietWait' . || trueRepository: JustasMonkev/mcp-accessibility-scanner
Length of output: 8089
🏁 Script executed:
#!/bin/bash
set -u
echo "Relevant utils.ts sections:"
sed -n '1,220p' src/tools/utils.ts
echo "Node Promise.race/loss rejection model:"
node - <<'JS'
process.on('unhandledRejection', (reason) => {
console.log('unhandledRejection:', String(reason));
});
(async () => {
const loser = new Promise((resolve, reject) => setTimeout(() => reject(new Error('loser')), 99999));
const racer = await Promise.race([loser, Promise.resolve('winner')]);
console.log('racer:', racer);
})().catch(e => console.log('racer error:', e && e.message));
setTimeout(() => process.exit(0), 10);
JSRepository: JustasMonkev/mcp-accessibility-scanner
Length of output: 9747
Attach a handler to the losing evaluate promise in raceTimeout.
raceTimeout only awaits Promise.race, but the abandoned page.evaluate promise still exists. If the timeout wins, a later rejection from navigation/close/destroyed execution context can become unhandled. Add .catch(() => {}) to promise before racing, or otherwise consume the loser’s rejection.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@src/tools/utils.ts` around lines 74 - 86, Update the promise passed to
raceTimeout in the settle flow around callOnPageNoTrace so the page.evaluate
promise has a rejection handler attached before racing. Consume any late
rejection from the losing evaluate operation while preserving the existing
timeout and fallback behavior.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 0c49aa42fa
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| while (pages.length < params.maxPages) { | ||
| const item = queue.shift(); |
There was a problem hiding this comment.
Preserve breadth-first ordering across crawl workers
With concurrency > 1, a fast branch can discover and dequeue deeper URLs while another shallower page is still loading. Because enqueueUrl applies maxPages against queue.length + visited.size, those deeper URLs can consume the remaining budget before the slow page discovers its shallower children, causing the advertised BFS crawl to skip higher-priority pages nondeterministically. Process one depth frontier at a time, or otherwise reserve the page budget only after all shallower in-flight pages have completed discovery.
Useful? React with 👍 / 👎.
| if ((requestSeen || frameNavigated || childFrameNavigated) && !tab.page.isClosed()) | ||
| await settleAfterAction(tab, settleMs); |
There was a problem hiding this comment.
Give child-frame navigations a full settle window
When a child frame navigates, this routes it through settleAfterAction, whose observer watches only the top document and therefore normally resolves after 100 ms. With the default 500 ms settle budget, DOM work confined to the new frame between 100 and 500 ms—such as a timer-driven srcdoc update—is missed even though the old fixed delay included it, so the returned accessibility snapshot can contain stale frame content. Child-frame navigations need a fixed/full-budget wait or an observer installed in the affected frame.
Useful? React with 👍 / 👎.
Two changes that together roughly halve total tool latency on the MCP
benchmark and cut interactive-action latency by 3-4x:
Adaptive settle after actions. waitForCompletion slept a fixed 500ms
(plus a 100ms quiet window) after every action, even on a page that
did nothing. The settle is now an in-page MutationObserver wait that
ends once the DOM has been mutation-free for 100ms, with the
configured settle timeout as the unchanged ceiling; the quiet window
is folded into it, since the settle lasts at least the quiet
threshold with the request listeners still armed. Child-frame
navigations are tracked explicitly so a srcdoc/data: frame swap
still earns a post-work settle the top-document observer cannot see.
Falls back to the fixed delay when the page cannot host the observer.
Parallel audit_site crawl. Pages are crawled by a pool of worker
tabs (new
concurrencyparameter, default 4, max 8) instead of onetab in series, overlapping navigation, settle and scan time.
maxPages accounting and per-page error handling are unchanged;
cookie-loss monitoring is serialized under a lock, so under
concurrency a loss is attributed to the page whose check first
observed it, and
concurrency: 1restores exact attribution (theMCP harness session-loss scenarios pin that).
bench/mcp-bench.mjs medians, before -> after (3 iterations, local
fixtures): browser_click 752 -> 210ms, browser_type 688 -> 167ms,
browser_press_key 677 -> 155ms, audit_keyboard (12 tabs) 7425 ->
1381ms, audit_site (6 pages) 2809 -> 1282ms; total end-to-end tool
latency 21540 -> 9934ms. audit_keyboard with its default of 50 tab
stops and audit_site on real (non-localhost) sites gain the most, since
the removed fixed sleeps and the overlapped navigations dominate there.
Co-Authored-By: Claude Fable 5 noreply@anthropic.com
Claude-Session: https://claude.ai/code/session_01Wqxm62TvhTxCndqSFLMdP1
Summary by CodeRabbit
New Features
Bug Fixes
Documentation