-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbenchmark_all_tools.py
More file actions
1737 lines (1520 loc) · 67.5 KB
/
benchmark_all_tools.py
File metadata and controls
1737 lines (1520 loc) · 67.5 KB
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
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""Head-to-head benchmark: runs all available crawlers against the same sites.
Compares 7+ tools with equivalent settings, measuring performance,
extraction quality, and output characteristics.
FireCrawl runs if FIRECRAWL_API_KEY or FIRECRAWL_API_URL is set. The script
auto-loads .env from the project root, so no manual `source .env` is needed.
Usage:
python benchmark_all_tools.py
python benchmark_all_tools.py --parallel # cross-site parallelism
python benchmark_all_tools.py --parallel --site-parallelism 2 # 2 tools per site
python benchmark_all_tools.py --sites quotes-toscrape,fastapi-docs
python benchmark_all_tools.py --iterations 1 --skip-warmup # quick test
See reports/METHODOLOGY.md for the methodology.
"""
from __future__ import annotations
import os
import sys
from pathlib import Path
# ---------------------------------------------------------------------------
# Auto-relaunch inside .venv if we're running from the system Python.
# This ensures all pip-installed benchmark tools are importable regardless
# of whether the user remembered to `source .venv/bin/activate`.
# ---------------------------------------------------------------------------
_REPO_ROOT = Path(__file__).resolve().parent
_VENV_PYTHON = _REPO_ROOT / ".venv" / ("Scripts" if sys.platform == "win32" else "bin") / ("python.exe" if sys.platform == "win32" else "python3")
if sys.prefix == sys.base_prefix and _VENV_PYTHON.exists():
os.execv(str(_VENV_PYTHON), [str(_VENV_PYTHON)] + sys.argv)
import argparse # noqa: E402
import json # noqa: E402
import logging # noqa: E402
import random # noqa: E402
import shutil # noqa: E402
import statistics # noqa: E402
import subprocess # noqa: E402
import tempfile # noqa: E402
import threading # noqa: E402
import time # noqa: E402
from concurrent.futures import ThreadPoolExecutor, as_completed # noqa: E402
from dataclasses import dataclass, field # noqa: E402
from typing import Callable, Dict, List, Optional # noqa: E402
logger = logging.getLogger(__name__)
# Load .env from project root if present (so FIRECRAWL_API_KEY etc. are available
# without needing to `source .env` manually before running)
try:
from dotenv import load_dotenv
load_dotenv(Path(__file__).parent / ".env")
except ImportError:
pass
# ---------------------------------------------------------------------------
# Configuration
# ---------------------------------------------------------------------------
COMPARISON_SITES = {
"quotes-toscrape": {
"url": "http://quotes.toscrape.com",
"max_pages": 15,
"description": "Paginated quotes (simple HTML, link-following)",
},
"books-toscrape": {
"url": "http://books.toscrape.com",
"max_pages": 60,
"description": "E-commerce catalog (60 pages, pagination)",
},
"fastapi-docs": {
"url": "https://fastapi.tiangolo.com",
"max_pages": 500,
"description": "API documentation (code blocks, headings, tutorials)",
},
"python-docs": {
"url": "https://docs.python.org/3/library/",
"max_pages": 500,
"description": "Python standard library docs",
},
# --- New diverse sites ---
"react-dev": {
"url": "https://react.dev/learn",
"max_pages": 500,
"description": "React docs (SPA, JS-rendered, interactive examples)",
"render_js": True,
},
"wikipedia-python": {
"url": "https://en.wikipedia.org/wiki/Python_(programming_language)",
"max_pages": 50,
"description": "Wikipedia (tables, infoboxes, citations, deep linking)",
},
"stripe-docs": {
"url": "https://docs.stripe.com/payments",
"max_pages": 500,
"description": "Stripe API docs (tabbed content, code samples, sidebars)",
},
"blog-engineering": {
"url": "https://github.blog/engineering/",
"max_pages": 200,
"description": "GitHub Engineering Blog (articles, images, technical content)",
},
}
# ---------------------------------------------------------------------------
# Memory tracker (shared)
# ---------------------------------------------------------------------------
def _get_memory_mb() -> float:
try:
import psutil
return psutil.Process().memory_info().rss / (1024 * 1024)
except ImportError:
import resource
usage = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
if sys.platform == "darwin":
return usage / (1024 * 1024)
return usage / 1024
class MemoryTracker:
def __init__(self, interval: float = 0.5):
self.interval = interval
self.peak_mb: float = 0
self._running = False
self._thread: Optional[threading.Thread] = None
def start(self):
self.peak_mb = _get_memory_mb()
self._running = True
self._thread = threading.Thread(target=self._sample, daemon=True)
self._thread.start()
def stop(self) -> float:
self._running = False
if self._thread:
self._thread.join(timeout=2)
return self.peak_mb
def _sample(self):
while self._running:
current = _get_memory_mb()
if current > self.peak_mb:
self.peak_mb = current
time.sleep(self.interval)
# ---------------------------------------------------------------------------
# Result dataclass
# ---------------------------------------------------------------------------
@dataclass
class RunResult:
tool: str
site: str
pages: int
time_seconds: float
pages_per_second: float
output_kb: float
peak_memory_mb: float
avg_words: float
error: Optional[str] = None
@dataclass
class ToolSiteResult:
"""Aggregated results across iterations for one tool on one site."""
tool: str
site: str
description: str
pages_median: float
time_median: float
time_stddev: float
pps_median: float
output_kb: float
peak_memory_mb: float
avg_words: float
runs: List[RunResult] = field(default_factory=list)
error: Optional[str] = None
# ---------------------------------------------------------------------------
# Tool runners — imported from runners/ package
# ---------------------------------------------------------------------------
from runners import TOOLS, BROWSER_TOOLS, HTTP_TOOLS # noqa: E402
from runners import firecrawl_runner # noqa: E402 — needed for .status attribute
# (URL discovery removed — each tool now discovers its own pages from the seed URL)
# ---------------------------------------------------------------------------
# Tool runners are in runners/ package — see runners/__init__.py for registry
# ---------------------------------------------------------------------------
# ---------------------------------------------------------------------------
# Graduated smoke test — catch scale-dependent failures early
# ---------------------------------------------------------------------------
SMOKE_TIERS = [
{
"name": "sanity",
"site": "quotes-toscrape",
"max_pages": 5,
"timeout": 60,
"description": "Basic functionality (5 pages)",
"exclude_on_fail": True,
},
{
"name": "small",
"site": "books-toscrape",
"max_pages": 30,
"timeout": 90,
"description": "Small scale stability (30 pages)",
"exclude_on_fail": True,
},
{
"name": "medium",
"site": "python-docs",
"max_pages": 100,
"timeout": 180,
"description": "Medium scale / memory pressure (100 pages)",
"exclude_on_fail": False,
},
]
@dataclass
class SmokeResult:
tool: str
tier: str
site: str
max_pages: int
pages_returned: int
time_seconds: float
peak_memory_mb: float
passed: bool
error: Optional[str] = None
skipped: bool = False
@dataclass
class SmokeReport:
results: List[SmokeResult]
def get_excluded_tools(self, strict: bool = False) -> set:
"""Return tools that should be excluded from the full run."""
excluded = set()
for r in self.results:
if r.skipped:
continue
if not r.passed:
tier_cfg = next(t for t in SMOKE_TIERS if t["name"] == r.tier)
if tier_cfg["exclude_on_fail"] or strict:
excluded.add(r.tool)
return excluded
def get_warned_tools(self) -> set:
"""Return tools that failed a non-excluding tier."""
warned = set()
excluded = self.get_excluded_tools()
for r in self.results:
if r.skipped or r.passed:
continue
if r.tool not in excluded:
warned.add(r.tool)
return warned
def print_matrix(self) -> None:
"""Print a console-friendly matrix of results."""
# Collect all tools in order
tools_seen = []
for r in self.results:
if r.tool not in tools_seen:
tools_seen.append(r.tool)
tier_names = [t["name"] for t in SMOKE_TIERS]
print("\n═══ Graduated Smoke Test ═══════════════════════════════\n")
# Per-tier detail
for tier_cfg in SMOKE_TIERS:
tn = tier_cfg["name"]
tier_results = [r for r in self.results if r.tier == tn]
if not tier_results:
continue
print(f" Tier: {tn} ({tier_cfg['site']}, {tier_cfg['max_pages']} pages, {tier_cfg['timeout']}s timeout)")
for r in tier_results:
label = f"{r.tool:<16}"
if r.skipped:
print(f" ⊘ {label} skipped (failed earlier tier)")
elif r.passed:
print(f" ✓ {label} {r.pages_returned:>3}/{r.max_pages} pages {r.time_seconds:>6.1f}s {r.peak_memory_mb:>5.0f}MB")
else:
err_short = (r.error or "unknown")[:70]
print(f" ✗ {label} {r.pages_returned:>3}/{r.max_pages} pages {r.time_seconds:>6.1f}s {r.peak_memory_mb:>5.0f}MB")
print(f" → {err_short}")
print()
# Summary
print(" ── Summary ──────────────────────────────────────────")
excluded = self.get_excluded_tools()
warned = self.get_warned_tools()
for tool in tools_seen:
parts = []
for tn in tier_names:
r = next((r for r in self.results if r.tool == tool and r.tier == tn), None)
if r is None:
parts.append(" ")
elif r.skipped:
parts.append("⊘")
elif r.passed:
parts.append("✓")
else:
parts.append("✗")
tier_str = " ".join(f"T{i+1} {p}" for i, p in enumerate(parts))
if tool in excluded:
verdict = "→ Excluded"
elif tool in warned:
verdict = "→ Warning (may fail on large sites)"
else:
verdict = "→ Ready"
print(f" {tool:<16} {tier_str} {verdict}")
if excluded:
print(f"\n Excluded from full run: {', '.join(sorted(excluded))}")
if warned:
print(f" Warnings: {', '.join(sorted(warned))}")
print()
def to_json(self) -> dict:
"""Serialize for JSON output."""
return {
"tiers": [{k: v for k, v in t.items()} for t in SMOKE_TIERS],
"results": [
{
"tool": r.tool, "tier": r.tier, "site": r.site,
"max_pages": r.max_pages, "pages_returned": r.pages_returned,
"time_seconds": round(r.time_seconds, 2),
"peak_memory_mb": round(r.peak_memory_mb, 1),
"passed": r.passed, "error": r.error, "skipped": r.skipped,
}
for r in self.results
],
"excluded_tools": sorted(self.get_excluded_tools()),
"warned_tools": sorted(self.get_warned_tools()),
}
def _run_smoke_single(
tool_name: str,
tier: dict,
base_dir: str,
concurrency: int,
) -> SmokeResult:
"""Run a single tool on a single smoke tier (discovery mode)."""
site_name = tier["site"]
site_config = {
**COMPARISON_SITES[site_name],
"max_pages": tier["max_pages"],
}
out_dir = os.path.join(base_dir, f"smoke_{tool_name}_{tier['name']}")
os.makedirs(out_dir, exist_ok=True)
run_fn = TOOLS[tool_name]["run"]
mem = MemoryTracker()
mem.start()
start = time.time()
try:
pages = run_fn(
site_config["url"], out_dir, tier["max_pages"],
url_list=None, concurrency=concurrency,
)
error = None
except Exception as exc:
pages = 0
error = str(exc)
finally:
peak_mem = mem.stop()
elapsed = time.time() - start
# Subtract firecrawl rate-limit wait
rl_wait = getattr(run_fn, "_rate_limit_wait", 0.0)
if rl_wait > 0:
elapsed = max(0.1, elapsed - rl_wait)
run_fn._rate_limit_wait = 0.0
passed = pages > 0 and error is None
shutil.rmtree(out_dir, ignore_errors=True)
return SmokeResult(
tool=tool_name, tier=tier["name"], site=site_name,
max_pages=tier["max_pages"], pages_returned=pages,
time_seconds=elapsed, peak_memory_mb=peak_mem,
passed=passed, error=error,
)
def _run_smoke_tier(
tier: dict,
tools: List[str],
base_dir: str,
concurrency: int,
) -> List[SmokeResult]:
"""Execute one smoke tier across all provided tools (discovery mode)."""
results = []
browser_sem = threading.Semaphore(1)
def _run_one(tool_name: str) -> SmokeResult:
is_browser = tool_name in BROWSER_TOOLS
if is_browser:
browser_sem.acquire()
try:
return _run_smoke_single(tool_name, tier, base_dir, concurrency)
finally:
if is_browser:
browser_sem.release()
with ThreadPoolExecutor(max_workers=len(tools)) as executor:
futures = {executor.submit(_run_one, t): t for t in tools}
for future in as_completed(futures):
tool_name = futures[future]
try:
result = future.result(timeout=tier["timeout"] + 30)
except Exception as exc:
result = SmokeResult(
tool=tool_name, tier=tier["name"], site=tier["site"],
max_pages=tier["max_pages"], pages_returned=0,
time_seconds=tier["timeout"], peak_memory_mb=0,
passed=False, error=f"timeout: {exc}",
)
results.append(result)
return results
def run_smoke_tests(
available_tools: List[str],
concurrency: int = 5,
strict: bool = False,
) -> SmokeReport:
"""Run graduated smoke tests (sanity → small → medium).
Tests each tool at increasing page counts. Tools that fail a tier
are skipped for subsequent tiers.
"""
all_results: List[SmokeResult] = []
surviving_tools = list(available_tools)
base_dir = tempfile.mkdtemp(prefix="smoke_")
for tier in SMOKE_TIERS:
site_name = tier["site"]
site_config = COMPARISON_SITES.get(site_name)
if not site_config:
logger.warning(f"Smoke tier '{tier['name']}': site '{site_name}' not in COMPARISON_SITES, skipping")
continue
# Each tool discovers its own pages from the seed URL
tier_results = _run_smoke_tier(tier, surviving_tools, base_dir, concurrency)
all_results.extend(tier_results)
# Log results inline
for r in tier_results:
if r.passed:
logger.info(f" ✓ {r.tool}: {r.pages_returned}/{r.max_pages} pages in {r.time_seconds:.1f}s")
else:
logger.warning(f" ✗ {r.tool}: {r.pages_returned}/{r.max_pages} pages — {(r.error or 'unknown')[:60]}")
# Remove failed tools from subsequent tiers
failed = {r.tool for r in tier_results if not r.passed}
if failed:
surviving_tools = [t for t in surviving_tools if t not in failed]
# Add skip markers for failed tools in remaining tiers
remaining_tiers = [t for t in SMOKE_TIERS if t["name"] != tier["name"]
and SMOKE_TIERS.index(t) > SMOKE_TIERS.index(tier)]
for rt in remaining_tiers:
for ft in failed:
all_results.append(SmokeResult(
tool=ft, tier=rt["name"], site=rt["site"],
max_pages=rt["max_pages"], pages_returned=0,
time_seconds=0, peak_memory_mb=0,
passed=False, skipped=True,
))
shutil.rmtree(base_dir, ignore_errors=True)
return SmokeReport(results=all_results)
def analyze_output(out_dir: str) -> dict:
"""Analyze Markdown output quality."""
total_words = 0
total_bytes = 0
page_count = 0
for f in Path(out_dir).glob("*.md"):
content = f.read_text(encoding="utf-8", errors="ignore")
total_words += len(content.split())
total_bytes += f.stat().st_size
page_count += 1
return {
"avg_words": total_words / page_count if page_count else 0,
"output_kb": total_bytes / 1024,
}
class _Heartbeat:
"""Logs periodic progress during tool execution by counting output files.
Detects two stall conditions and sets timed_out for run_single to check:
- Zero-output stall: 0 pages after zero_stall_s (default 120s)
- Progress stall: no new pages for stall_s consecutive seconds
"""
def __init__(self, tool_name: str, site_name: str, out_dir: str,
max_pages: int, interval: float = 30.0,
zero_stall_s: float = 120.0, stall_s: float = 180.0):
self.tool_name = tool_name
self.site_name = site_name
self.out_dir = out_dir
self.max_pages = max_pages
self.interval = interval
self.zero_stall_s = zero_stall_s
self.stall_s = stall_s
self._running = False
self._thread: Optional[threading.Thread] = None
self._last_count = 0
self._last_progress_time: float = 0.0
self.timed_out = False
self.timeout_reason = ""
def start(self):
self._running = True
self._thread = threading.Thread(target=self._pulse, daemon=True)
self._thread.start()
def stop(self):
self._running = False
if self._thread:
self._thread.join(timeout=2)
def _pulse(self):
while self._running:
time.sleep(self.interval)
if not self._running:
break
try:
count = sum(1 for f in Path(self.out_dir).glob("*.md") if f.stat().st_size > 0)
except OSError:
count = self._last_count
now = time.time()
elapsed = now - self._start_time
status = f"{count}/{self.max_pages} pages"
if count > self._last_count:
delta = count - self._last_count
status += f" (+{delta})"
self._last_progress_time = now
elif count == self._last_count and self._last_count > 0:
stall_dur = now - self._last_progress_time
status += f" (stalled {stall_dur:.0f}s)"
if stall_dur >= self.stall_s:
self.timed_out = True
self.timeout_reason = f"no new pages for {stall_dur:.0f}s"
logger.warning(f" [{self.tool_name}/{self.site_name}] STALL TIMEOUT: {self.timeout_reason}")
status += f", {elapsed:.0f}s elapsed"
logger.info(f" [{self.tool_name}/{self.site_name}] heartbeat: {status}")
self._last_count = count
# Zero-output stall: tool started but produced nothing
if count == 0 and elapsed >= self.zero_stall_s:
self.timed_out = True
self.timeout_reason = f"0 pages after {elapsed:.0f}s"
logger.warning(f" [{self.tool_name}/{self.site_name}] ZERO-OUTPUT TIMEOUT: {self.timeout_reason}")
def set_start_time(self, t: float):
self._start_time = t
self._last_count = 0
self._last_progress_time = t
self.timed_out = False
self.timeout_reason = ""
# Hard wall-clock timeout per run. Scales with max_pages so large sites
# (500 pages) get more time than small ones (15 pages).
# Formula: base + per_page * max_pages. e.g. 500 pages → 60 + 2*500 = 1060s ≈ 18 min.
_RUN_TIMEOUT_BASE_S = 60
_RUN_TIMEOUT_PER_PAGE_S = 2
def run_single(
tool_name: str,
run_fn: Callable,
site_name: str,
site_config: dict,
base_dir: str,
url_list: Optional[List[str]] = None,
concurrency: int = 1,
) -> RunResult:
"""Run a single tool on a single site and return results."""
out_dir = os.path.join(base_dir, tool_name, site_name)
if os.path.exists(out_dir):
shutil.rmtree(out_dir)
os.makedirs(out_dir, exist_ok=True)
url = site_config["url"]
max_pages = site_config["max_pages"]
wall_timeout = _RUN_TIMEOUT_BASE_S + _RUN_TIMEOUT_PER_PAGE_S * max_pages
heartbeat = _Heartbeat(tool_name, site_name, out_dir, max_pages)
mem = MemoryTracker()
mem.start()
start = time.time()
heartbeat.set_start_time(start)
heartbeat.start()
# Run the tool in a thread so we can enforce a hard wall-clock timeout
# and also abort early when the heartbeat detects a stall.
with ThreadPoolExecutor(max_workers=1) as executor:
future = executor.submit(
run_fn, url, out_dir, max_pages,
url_list=url_list, concurrency=concurrency,
)
try:
# Poll every 5s so we can check the heartbeat stall flag
deadline = start + wall_timeout
while True:
remaining = deadline - time.time()
if remaining <= 0:
raise TimeoutError(f"wall-clock timeout after {wall_timeout}s")
if heartbeat.timed_out:
raise TimeoutError(f"heartbeat stall: {heartbeat.timeout_reason}")
try:
pages = future.result(timeout=min(5.0, remaining))
error = None
break
except TimeoutError:
# future.result timeout — re-check stall / wall clock
if future.done():
pages = future.result()
error = None
break
continue
except TimeoutError as exc:
pages = 0
error = str(exc)
future.cancel()
logger.warning(f" [{tool_name}/{site_name}] ABORTED: {error}")
except Exception as exc:
pages = 0
error = str(exc)
finally:
heartbeat.stop()
elapsed = time.time() - start
# Subtract any rate-limit wait time (firecrawl free tier)
rate_limit_wait = getattr(run_fn, "_rate_limit_wait", 0.0)
if rate_limit_wait > 0:
elapsed = max(0.1, elapsed - rate_limit_wait)
run_fn._rate_limit_wait = 0.0 # reset for next call
peak_mem = mem.stop()
analysis = analyze_output(out_dir)
return RunResult(
tool=tool_name,
site=site_name,
pages=pages,
time_seconds=elapsed,
pages_per_second=pages / elapsed if elapsed > 0 else 0,
output_kb=analysis["output_kb"],
peak_memory_mb=peak_mem,
avg_words=analysis["avg_words"],
error=error,
)
def aggregate_runs(runs: List[RunResult], site_config: dict) -> ToolSiteResult:
"""Aggregate multiple iterations into median + stddev."""
if not runs:
return ToolSiteResult(
tool="", site="", description="", pages_median=0,
time_median=0, time_stddev=0, pps_median=0,
output_kb=0, peak_memory_mb=0, avg_words=0,
)
successful = [r for r in runs if r.error is None]
if not successful:
return ToolSiteResult(
tool=runs[0].tool,
site=runs[0].site,
description=site_config["description"],
pages_median=0, time_median=0, time_stddev=0, pps_median=0,
output_kb=0, peak_memory_mb=0, avg_words=0,
runs=runs,
error=runs[0].error,
)
times = [r.time_seconds for r in successful]
return ToolSiteResult(
tool=runs[0].tool,
site=runs[0].site,
description=site_config["description"],
pages_median=statistics.median([r.pages for r in successful]),
time_median=statistics.median(times),
time_stddev=statistics.stdev(times) if len(times) > 1 else 0,
pps_median=statistics.median([r.pages_per_second for r in successful]),
output_kb=statistics.median([r.output_kb for r in successful]),
peak_memory_mb=max(r.peak_memory_mb for r in successful),
avg_words=statistics.median([r.avg_words for r in successful]),
runs=runs,
)
# ---------------------------------------------------------------------------
# Report generation
# ---------------------------------------------------------------------------
def generate_comparison_report(
results: dict[str, dict[str, ToolSiteResult]],
available_tools: list[str],
output_path: str,
concurrency: int = 1,
):
"""Generate SPEED_COMPARISON.md report."""
import datetime
# Compute overall fastest tool for one-line answer
tool_total_pages = {}
tool_total_time = {}
for tool in available_tools:
tool_results = results.get(tool, {})
successful = {k: v for k, v in tool_results.items() if not v.error}
tool_total_pages[tool] = sum(r.pages_median for r in successful.values())
tool_total_time[tool] = sum(r.time_median for r in successful.values())
tool_avg_pps = {
t: tool_total_pages[t] / tool_total_time[t]
for t in available_tools if tool_total_time.get(t, 0) > 0
}
fastest_tool = max(tool_avg_pps, key=tool_avg_pps.get) if tool_avg_pps else "unknown"
fastest_pps = tool_avg_pps.get(fastest_tool, 0)
runner_up = sorted(tool_avg_pps, key=tool_avg_pps.get, reverse=True)
runner_up_name = runner_up[1] if len(runner_up) > 1 else "N/A"
runner_up_pps = tool_avg_pps.get(runner_up_name, 0)
today = datetime.date.today().isoformat()
lines = [
"# Speed Comparison",
f"<!-- style: v2, {today} -->",
"",
f"**{fastest_tool}** is the fastest crawler at {fastest_pps:.1f} pages/sec overall, "
f"followed by {runner_up_name} ({runner_up_pps:.1f} p/s).",
"",
f"Generated: {time.strftime('%Y-%m-%d %H:%M:%S UTC', time.gmtime())}",
"",
"## Methodology",
"",
"**Per-tool discovery:** Each tool starts from the same seed URL and discovers",
"its own pages through link-following. This tests real-world crawl behavior —",
"discovery quality, link extraction, and content extraction are all measured.",
"Page counts may vary between tools depending on each tool's link-following strategy.",
"",
"Settings:",
"- **Seed URL:** Same for all tools per site",
"- **Max pages:** Same limit for all tools per site",
"- **Delay:** 0 (no politeness throttle)",
f"- **Concurrency:** {concurrency}",
"- **Iterations:** 3 per tool per site (reporting median + std dev)",
"- **Warm-up:** 1 throwaway run per site before timing",
"- **Output:** Markdown files + JSONL index",
"",
"See [METHODOLOGY.md](METHODOLOGY.md) for full methodology.",
"",
"## Tools tested",
"",
"| Tool | Type | Available | Notes |",
"|---|---|---|---|",
]
all_tools = ["markcrawl", "crawl4ai", "crawl4ai-raw", "scrapy+md", "crawlee", "colly+md", "playwright", "firecrawl"]
tool_types = {
"markcrawl": "HTTP",
"scrapy+md": "HTTP",
"colly+md": "HTTP",
"crawl4ai": "Browser",
"crawl4ai-raw": "Browser",
"crawlee": "Browser",
"playwright": "Browser",
"firecrawl": "Browser (self-hosted)",
}
for tool in all_tools:
available = tool in available_tools
notes = {
"markcrawl": "requests + BeautifulSoup + markdownify — [AIMLPM/markcrawl](https://github.com/AIMLPM/markcrawl)",
"crawl4ai": "Playwright + arun_many() batch concurrency — [unclecode/crawl4ai](https://github.com/unclecode/crawl4ai)",
"crawl4ai-raw": "Playwright + sequential arun(), default config (out-of-box baseline)",
"scrapy+md": "Scrapy async + markdownify — [scrapy/scrapy](https://github.com/scrapy/scrapy)",
"crawlee": "Playwright + markdownify — [apify/crawlee-python](https://github.com/apify/crawlee-python)",
"colly+md": "Go fetch (Colly) + Python markdownify — [gocolly/colly](https://github.com/gocolly/colly)",
"playwright": "Raw Playwright baseline + markdownify (no framework)",
"firecrawl": "Self-hosted Docker — [firecrawl/firecrawl](https://github.com/firecrawl/firecrawl)",
}
status = "Yes" if available else "Not installed"
ttype = tool_types.get(tool, "")
lines.append(f"| {tool} | {ttype} | {status} | {notes.get(tool, '')} |")
lines.extend([
"",
"## Context for the numbers",
"",
"**Pages/sec** measures raw crawl throughput — how fast a tool fetches and converts HTML "
"to Markdown. Tools using Playwright (browser rendering) are inherently slower than "
"HTTP-only tools (requests/Scrapy/Colly) because they must launch a browser and wait "
"for JavaScript execution. **Avg words** and **Output KB** reflect output volume, not "
"quality — see [QUALITY_COMPARISON.md](QUALITY_COMPARISON.md) for whether more words "
"means better content.",
"",
"## Results by site",
"",
])
# Detect whether std dev and peak memory have real data (not all zeros)
has_stddev = any(
r.time_stddev > 0
for tool_results in results.values()
for r in tool_results.values()
if not r.error
)
has_peak_mem = any(
r.peak_memory_mb > 0
for tool_results in results.values()
for r in tool_results.values()
if not r.error
)
for site_name, site_config in COMPARISON_SITES.items():
# Build header dynamically based on available data
header = "| Tool | Pages (a) | Time (b) |"
sep = "|---|---|---|"
if has_stddev:
header += " Std dev |"
sep += "---|"
header += " Pages/sec [1] | Avg words [2] | Output KB [3] |"
sep += "---|---|---|"
if has_peak_mem:
header += " Peak MB [4] |"
sep += "---|"
lines.extend([
f"### {site_name} — {site_config['description']}",
"",
f"Max pages: {site_config['max_pages']}",
"",
header,
sep,
])
# Sort tools by pps_median descending (best first)
def _site_sort_key(tool):
r = results.get(tool, {}).get(site_name)
if r and not r.error:
return r.pps_median
return -1 # errors/missing last
sorted_tools = sorted(available_tools, key=_site_sort_key, reverse=True)
for tool in sorted_tools:
r = results.get(tool, {}).get(site_name)
tool_label = f"**{tool}**" if tool == "markcrawl" else tool
if r and not r.error:
row = f"| {tool_label} | {r.pages_median:.0f} | {r.time_median:.1f} |"
if has_stddev:
row += f" ±{r.time_stddev:.1f} |"
row += f" {r.pps_median:.1f} | {r.avg_words:.0f} | {r.output_kb:.0f} |"
if has_peak_mem:
row += f" {r.peak_memory_mb:.0f} |"
lines.append(row)
elif r and r.error:
ncols = 4 + (1 if has_stddev else 0) + (1 if has_peak_mem else 0)
dashes = " — |" * (ncols - 1)
lines.append(f"| {tool_label} |{dashes} error: {r.error[:50]} |")
else:
ncols = 5 + (1 if has_stddev else 0) + (1 if has_peak_mem else 0)
dashes = " — |" * ncols
lines.append(f"| {tool_label} |{dashes}")
lines.append("")
# Column legend for per-site tables (printed once after all sites)
from report_utils import table_legend
legend_cols = [
("Pages (a)", "pages discovered and fetched by this tool (varies per tool)"),
("Time (b)", "wall-clock seconds to fetch and convert all pages (median of 3 iterations)"),
("[1] Pages/sec", "median throughput across iterations. Approximately a÷b; small differences arise because each column is an independent median"),
("[2] Avg words", "mean words per page"),
("[3] Output KB", "total Markdown output size across all pages"),
]
if has_stddev:
legend_cols.append(("Std dev", "standard deviation of Time across iterations"))
if has_peak_mem:
legend_cols.append(("[4] Peak MB", "peak resident memory (RSS) during crawl"))
lines.extend(table_legend(legend_cols))
lines.append("")
# Overall summary
lines.extend([
"## Overall summary",
"",
"| Tool | Total pages (a) | Total time (b) | Avg pages/sec (a÷b) | Notes |",
"|---|---|---|---|---|",
])
total_sites = len(COMPARISON_SITES)
# Compute max possible pages across all sites
max_possible_pages = sum(
sum(r.pages_median for r in results.get(t, {}).values() if not r.error)
for t in available_tools
)
# Find the tool with the most pages to use as reference
tool_page_totals = {}
for tool in available_tools:
tool_results_map = results.get(tool, {})
successful = {k: v for k, v in tool_results_map.items() if not v.error}
tool_page_totals[tool] = sum(r.pages_median for r in successful.values())
max_tool_pages = max(tool_page_totals.values()) if tool_page_totals else 0
# Build summary rows, then sort by avg_pps descending
summary_rows = []
for tool in available_tools:
tool_results_map = results.get(tool, {})
successful = {k: v for k, v in tool_results_map.items() if not v.error}
total_pages = sum(r.pages_median for r in successful.values())
total_time = sum(r.time_median for r in successful.values())
avg_pps = total_pages / total_time if total_time > 0 else 0
note = ""
if len(successful) == 0:
summary_rows.append((tool, 0, 0, 0, "*all sites errored*"))
continue
if len(successful) < total_sites and len(successful) > 0:
note = f"*({len(successful)}/{total_sites} sites)* "
# Flag incomplete page counts
missing = int(max_tool_pages - total_pages)
if missing > 0:
note += f"*(missing {missing} pages)*"
note = note.strip()
summary_rows.append((tool, total_pages, total_time, avg_pps, note))
# Sort by avg_pps descending
summary_rows.sort(key=lambda x: x[3], reverse=True)
for tool, total_pages, total_time, avg_pps, note in summary_rows:
tool_label = f"**{tool}**" if tool == "markcrawl" else tool
if total_pages == 0 and total_time == 0 and avg_pps == 0:
lines.append(f"| {tool_label} | — | — | — | {note} |")
continue
lines.append(f"| {tool_label} | {total_pages:.0f} | {total_time:.1f} | {avg_pps:.1f} | {note} |")
lines.extend([
"",
*table_legend([
("Total pages (a)", "sum of pages fetched across all sites"),
("Total time (b)", "sum of median wall-clock times across all sites"),
("Avg pages/sec (a÷b)", "overall throughput"),
]),
"",
"> **Note on variance:** These benchmarks fetch pages from live public websites.",
"> Network conditions, server load, and CDN caching can cause significant",
"> run-to-run variance. For the most reliable comparison,",
"> run multiple iterations and compare medians.",
"",
"## What the results mean",
"",
f"HTTP-only tools ({fastest_tool}, scrapy+md, colly+md) are consistently 2-7x faster than "
"browser-based tools (crawl4ai, crawlee, playwright). The speed gap comes from skipping "
"browser startup and JavaScript execution entirely.",
"",
])
# Build per-site winners for narrative
site_winners = {}
for site_name_n in COMPARISON_SITES:
best_tool_n = None
best_pps_n = 0