File size: 13,588 Bytes
87dab07 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 | // Web fetch benchmark covers direct response loading, HTML extraction, and fallback cleanup.
import { mkdir, writeFile } from "node:fs/promises";
import path from "node:path";
import { performance } from "node:perf_hooks";
import type { OpenClawConfig } from "../src/config/types.openclaw.js";
import type { LookupFn } from "../src/infra/net/ssrf.js";
import * as cliArgs from "./lib/arg-utils.mts";
type BenchmarkCaseId =
| "tool-create"
| "tool-text"
| "tool-markdown"
| "tool-html-article"
| "tool-html-article-text"
| "tool-html-shell"
| "extract-readable-article"
| "extract-readable-article-text"
| "extract-basic-shell";
type BenchmarkCase = {
id: BenchmarkCaseId;
label: string;
run: () => Promise<void> | void;
};
type Options = {
cases: BenchmarkCaseId[];
json: boolean;
output?: string;
runs: number;
warmup: number;
};
type SummaryStats = {
avg: number;
max: number;
min: number;
p50: number;
p95: number;
};
type CaseReport = {
id: BenchmarkCaseId;
label: string;
samplesMs: number[];
summaryMs: SummaryStats;
};
type BenchmarkReport = {
cases: CaseReport[];
node: string;
options: Omit<Options, "json">;
rssMb: number;
};
const ALL_CASE_IDS = [
"tool-create",
"tool-text",
"tool-markdown",
"tool-html-article",
"tool-html-article-text",
"tool-html-shell",
"extract-readable-article",
"extract-readable-article-text",
"extract-basic-shell",
] as const satisfies readonly BenchmarkCaseId[];
const SPLIT_VALUE_FLAG_OPTIONS = { allowInline: false, rejectShortOptions: true } as const;
class CliArgumentError extends Error {
override name = "CliArgumentError";
}
const ARTICLE_HTML = `<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Web Fetch Benchmark Article</title>
</head>
<body>
<nav>${Array.from({ length: 24 }, (_, index) => `<a href="/nav-${index}">Nav ${index}</a>`).join("")}</nav>
<main>
<article>
<h1>Web Fetch Benchmark Article</h1>
${Array.from(
{ length: 180 },
(_, index) =>
`<p>Paragraph ${index} carries readable benchmark content with enough prose for Readability to score it as article body text.</p>`,
).join("\n")}
</article>
</main>
<footer>Repeated footer chrome that should not dominate extracted content.</footer>
</body>
</html>`;
const SHELL_HTML = `<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Shell App</title>
</head>
<body>
<div id="app"></div>
<script>window.__APP__ = true;</script>
<noscript>Enable JavaScript to load this page.</noscript>
</body>
</html>`;
const TEXT_BODY = "OpenClaw web_fetch direct text benchmark body.".repeat(160);
const MARKDOWN_BODY = "# Web Fetch Benchmark\n\n" + "- markdown list item\n".repeat(220);
const OFFLINE_PROVIDER_ENV_VARS = ["FIRECRAWL_API_KEY"] as const;
const lookupFn = (async () => [{ address: "93.184.216.34", family: 4 }]) as unknown as LookupFn;
const toolConfig: OpenClawConfig = {
tools: {
web: {
fetch: {
cacheTtlMinutes: 0,
},
},
},
};
function parseCases(requested: string[]): BenchmarkCaseId[] {
if (requested.length === 0 || requested.includes("all")) {
return [...ALL_CASE_IDS];
}
const valid = new Set<string>(ALL_CASE_IDS);
for (const id of requested) {
if (!valid.has(id)) {
throw new CliArgumentError(
`--case must be one of all, ${ALL_CASE_IDS.join(", ")}; got ${JSON.stringify(id)}`,
);
}
}
return requested as BenchmarkCaseId[];
}
function parseBenchmarkCount(raw: string, flag: string, minimum: 0 | 1): number {
const parsed = cliArgs.classifyBoundedUnsignedDecimal(raw, minimum, Number.MAX_SAFE_INTEGER);
if (parsed.kind === "value") {
return parsed.value;
}
const kind = minimum === 0 ? "non-negative" : "positive";
throw new CliArgumentError(`${flag} must be a ${kind} integer`);
}
function parseOptions(args = process.argv.slice(2)): Options {
const normalizedArgs = cliArgs.stripLeadingPackageManagerSeparator(args);
try {
const parsed = cliArgs.parseFlagArgs(
normalizedArgs,
{
cases: [] as string[],
json: false,
output: undefined as string | undefined,
runs: "20",
warmup: "3",
},
[
cliArgs.stringListFlag("--case", "cases", SPLIT_VALUE_FLAG_OPTIONS),
cliArgs.stringFlag("--output", "output", SPLIT_VALUE_FLAG_OPTIONS),
cliArgs.stringFlag("--runs", "runs", SPLIT_VALUE_FLAG_OPTIONS),
cliArgs.stringFlag("--warmup", "warmup", SPLIT_VALUE_FLAG_OPTIONS),
cliArgs.booleanFlag("--json", "json", true, { repeatable: true }),
],
{
ignoreDoubleDash: false,
onUnhandledArg(arg) {
throw new CliArgumentError(`Unknown argument: ${arg}`);
},
},
);
return {
cases: parseCases(parsed.cases),
json: parsed.json,
output: parsed.output,
runs: parseBenchmarkCount(parsed.runs, "--runs", 1),
warmup: parseBenchmarkCount(parsed.warmup, "--warmup", 0),
};
} catch (error) {
throw new CliArgumentError(error instanceof Error ? error.message : String(error));
}
}
function printUsage(): void {
process.stdout.write(`OpenClaw web_fetch benchmark
Usage:
pnpm perf:web-fetch -- [options]
node --import tsx scripts/bench-web-fetch.ts [options]
Options:
--case <id> Case to run; repeatable. Use "all" for every case.
--runs <n> Measured runs per case (default: 20)
--warmup <n> Warmup runs per case (default: 3)
--output <path> Write JSON report
--json Print JSON report
--help, -h Show this text
Cases:
${ALL_CASE_IDS.join("\n ")}
`);
}
function round(value: number): number {
return Math.round(value * 1000) / 1000;
}
function percentile(values: number[], p: number): number {
if (values.length === 0) {
return 0;
}
const sorted = values.toSorted((left, right) => left - right);
const index = Math.min(sorted.length - 1, Math.floor((sorted.length - 1) * p));
return round(sorted[index] ?? 0);
}
function stats(values: number[]): SummaryStats {
if (values.length === 0) {
return { avg: 0, max: 0, min: 0, p50: 0, p95: 0 };
}
const total = values.reduce((sum, value) => sum + value, 0);
return {
avg: round(total / values.length),
max: round(Math.max(...values)),
min: round(Math.min(...values)),
p50: percentile(values, 0.5),
p95: percentile(values, 0.95),
};
}
function installMockFetch(params: { body: string; contentType: string }) {
const fetchImpl = (async () =>
new Response(params.body, {
status: 200,
headers: {
"content-type": params.contentType,
},
})) as unknown as typeof globalThis.fetch & { mock: object };
// fetchWithSsrFGuard preserves dispatcher support unless global fetch is a
// test double. The marker keeps this benchmark offline and deterministic.
fetchImpl.mock = {};
globalThis.fetch = fetchImpl;
}
async function withOfflineProviderEnv<T>(run: () => Promise<T>): Promise<T> {
const previous = new Map<string, string | undefined>();
for (const name of OFFLINE_PROVIDER_ENV_VARS) {
previous.set(name, process.env[name]);
process.env[name] = "";
}
try {
return await run();
} finally {
for (const [name, value] of previous) {
if (value === undefined) {
delete process.env[name];
} else {
process.env[name] = value;
}
}
}
}
async function loadCaseFactory(): Promise<() => Record<BenchmarkCaseId, BenchmarkCase>> {
const { extractBasicHtmlContent } = await import("../src/agents/tools/web-fetch-utils.js");
const { createWebFetchTool } = await import("../src/agents/tools/web-fetch.js");
const { extractReadableContent } = await import("../src/web-fetch/content-extractors.runtime.js");
function createTool() {
const tool = createWebFetchTool({
config: toolConfig,
lookupFn,
sandboxed: false,
});
if (!tool?.execute) {
throw new Error("web_fetch tool was not created");
}
return tool;
}
return () => {
const textTool = createTool();
const markdownTool = createTool();
const articleTool = createTool();
const articleTextTool = createTool();
const shellTool = createTool();
return {
"tool-create": {
id: "tool-create",
label: "create web_fetch tool",
run: () => {
createTool();
},
},
"tool-text": {
id: "tool-text",
label: "execute text/plain fetch",
run: async () => {
installMockFetch({ body: TEXT_BODY, contentType: "text/plain; charset=utf-8" });
await textTool.execute("bench", { url: "https://example.com/plain" });
},
},
"tool-markdown": {
id: "tool-markdown",
label: "execute text/markdown fetch",
run: async () => {
installMockFetch({ body: MARKDOWN_BODY, contentType: "text/markdown; charset=utf-8" });
await markdownTool.execute("bench", { url: "https://example.com/markdown" });
},
},
"tool-html-article": {
id: "tool-html-article",
label: "execute article HTML fetch",
run: async () => {
installMockFetch({ body: ARTICLE_HTML, contentType: "text/html; charset=utf-8" });
await articleTool.execute("bench", { url: "https://example.com/article" });
},
},
"tool-html-article-text": {
id: "tool-html-article-text",
label: "execute article HTML fetch as text",
run: async () => {
installMockFetch({ body: ARTICLE_HTML, contentType: "text/html; charset=utf-8" });
await articleTextTool.execute("bench", {
url: "https://example.com/article-text",
extractMode: "text",
});
},
},
"tool-html-shell": {
id: "tool-html-shell",
label: "execute shell HTML fallback fetch",
run: async () => {
installMockFetch({ body: SHELL_HTML, contentType: "text/html; charset=utf-8" });
await shellTool.execute("bench", { url: "https://example.com/shell" });
},
},
"extract-readable-article": {
id: "extract-readable-article",
label: "extract readable article HTML",
run: async () => {
await extractReadableContent({
html: ARTICLE_HTML,
url: "https://example.com/article",
extractMode: "markdown",
config: toolConfig,
});
},
},
"extract-readable-article-text": {
id: "extract-readable-article-text",
label: "extract readable article HTML as text",
run: async () => {
await extractReadableContent({
html: ARTICLE_HTML,
url: "https://example.com/article-text",
extractMode: "text",
config: toolConfig,
});
},
},
"extract-basic-shell": {
id: "extract-basic-shell",
label: "extract basic shell HTML",
run: async () => {
await extractBasicHtmlContent({
html: SHELL_HTML,
extractMode: "markdown",
});
},
},
};
};
}
async function measureCase(testCase: BenchmarkCase, options: Options): Promise<CaseReport> {
for (let index = 0; index < options.warmup; index += 1) {
await testCase.run();
}
const samplesMs: number[] = [];
for (let index = 0; index < options.runs; index += 1) {
const started = performance.now();
await testCase.run();
samplesMs.push(round(performance.now() - started));
}
return {
id: testCase.id,
label: testCase.label,
samplesMs,
summaryMs: stats(samplesMs),
};
}
function printProofLines(report: BenchmarkReport): void {
for (const testCase of report.cases) {
const summary = testCase.summaryMs;
console.log(
`WEB_FETCH_BENCH_CASE=${testCase.id} avg_ms=${summary.avg.toFixed(3)} p50_ms=${summary.p50.toFixed(3)} p95_ms=${summary.p95.toFixed(3)} max_ms=${summary.max.toFixed(3)}`,
);
}
console.log(`WEB_FETCH_BENCH_RSS_MB=${report.rssMb.toFixed(1)}`);
}
async function main(): Promise<void> {
const args = process.argv.slice(2);
if (args.includes("--help") || args.includes("-h")) {
printUsage();
return;
}
const options = parseOptions(args);
// Preserve runtime import environment, then construct tools inside the offline scope.
const createCases = await loadCaseFactory();
const report = await withOfflineProviderEnv(async () => {
const casesById = createCases();
const cases: CaseReport[] = [];
for (const caseId of options.cases) {
cases.push(await measureCase(casesById[caseId], options));
}
return {
cases,
node: process.version,
options: {
cases: options.cases,
output: options.output,
runs: options.runs,
warmup: options.warmup,
},
rssMb: Math.round((process.memoryUsage().rss / 1024 / 1024) * 10) / 10,
};
});
if (options.output) {
await mkdir(path.dirname(options.output), { recursive: true });
await writeFile(options.output, `${JSON.stringify(report, null, 2)}\n`);
}
if (options.json) {
console.log(JSON.stringify(report, null, 2));
} else {
printProofLines(report);
}
}
main().catch((error: unknown) => {
if (error instanceof CliArgumentError) {
console.error(error.message);
process.exitCode = 2;
return;
}
throw error;
});
|