-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdebug.py
More file actions
2219 lines (1866 loc) · 73.8 KB
/
Copy pathdebug.py
File metadata and controls
2219 lines (1866 loc) · 73.8 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
import os
import sys
import re
import io
import json
import time
import math
import gzip
import queue
import random
import signal
import string
import hashlib
import argparse
import threading
import traceback
import statistics
import subprocess
import contextlib
import multiprocessing as mp
from pathlib import Path
from collections import deque, defaultdict, Counter, OrderedDict
from dataclasses import dataclass, field, asdict
from enum import Enum
from typing import Any, Callable, Optional
import psutil
sys.path.insert(0, str(Path(__file__).resolve().parent))
from urllib.parse import urlparse, urljoin, urldefrag
from folder_manager import FolderManager
# ============================================================================
# LOGGING INFRASTRUCTURE
# ============================================================================
class Level(Enum):
TRACE = 5
DEBUG = 10
INFO = 20
PASS = 25
WARN = 30
FAIL = 35
ERROR = 40
FATAL = 50
LEVEL_LABELS = {
Level.TRACE: ("TRCE", "\033[90m"),
Level.DEBUG: ("DBUG", "\033[36m"),
Level.INFO: ("INFO", "\033[37m"),
Level.PASS: ("PASS", "\033[92m"),
Level.WARN: ("WARN", "\033[93m"),
Level.FAIL: ("FAIL", "\033[91m"),
Level.ERROR: ("ERRO", "\033[91m"),
Level.FATAL: ("FATL", "\033[1;91m"),
}
RESET = "\033[0m"
def _colorize(text, color):
if os.name == "nt" and not os.environ.get("WT_SESSION"):
return text
return f"{color}{text}{RESET}"
class RingBuffer:
__slots__ = ("_buf", "_lock", "_total")
def __init__(self, maxlen=50000):
self._buf = deque(maxlen=maxlen)
self._lock = threading.Lock()
self._total = 0
def append(self, item):
with self._lock:
self._buf.append(item)
self._total += 1
def drain(self):
with self._lock:
items = list(self._buf)
self._buf.clear()
return items
def snapshot(self):
with self._lock:
return list(self._buf)
def __len__(self):
return len(self._buf)
@property
def total(self):
return self._total
class AsyncFileWriter:
def __init__(self, path, batch_size=200, flush_interval=1.0):
self.path = Path(path)
self.path.parent.mkdir(parents=True, exist_ok=True)
self._queue = queue.Queue(maxsize=100000)
self._batch_size = batch_size
self._flush_interval = flush_interval
self._thread = None
self._stop = threading.Event()
self._written = 0
self._dropped = 0
self._start()
def _start(self):
self._thread = threading.Thread(target=self._run, daemon=True)
self._thread.start()
def _run(self):
buffer = []
last_flush = time.monotonic()
try:
fh = open(self.path, "ab", buffering=65536)
except Exception:
return
try:
while not self._stop.is_set() or not self._queue.empty():
try:
item = self._queue.get(timeout=0.2)
buffer.append(item)
except queue.Empty:
pass
now = time.monotonic()
if (len(buffer) >= self._batch_size
or now - last_flush >= self._flush_interval):
if buffer:
try:
fh.write(b"".join(buffer))
fh.flush()
self._written += len(buffer)
except Exception:
pass
buffer.clear()
last_flush = now
finally:
if buffer:
try:
fh.write(b"".join(buffer))
fh.flush()
self._written += len(buffer)
except Exception:
pass
try:
fh.close()
except Exception:
pass
def write(self, data):
try:
self._queue.put_nowait(data)
return True
except queue.Full:
self._dropped += 1
return False
def stop(self, timeout=3.0):
self._stop.set()
if self._thread is not None:
self._thread.join(timeout=timeout)
@property
def stats(self):
return {"written": self._written, "dropped": self._dropped,
"pending": self._queue.qsize()}
class Logger:
__slots__ = ("name", "_min_level", "_console", "_file", "_ring",
"_context", "_lock", "_events", "_counters", "_timings")
_global_min_level = Level.DEBUG
_global_console = True
_global_file = None
_global_ring = None
_global_lock = threading.Lock()
def __init__(self, name, min_level=None, console=None, file=None):
self.name = name
self._min_level = min_level or Logger._global_min_level
self._console = console if console is not None else Logger._global_console
self._file = file if file is not None else Logger._global_file
self._ring = Logger._global_ring
self._context = {}
self._lock = threading.Lock()
self._events = Counter()
self._counters = defaultdict(int)
self._timings = defaultdict(list)
@classmethod
def configure(cls, min_level=None, console=None, file_path=None,
ring_buffer_size=50000):
if min_level is not None:
cls._global_min_level = min_level
if console is not None:
cls._global_console = console
if file_path is not None:
cls._global_file = AsyncFileWriter(file_path)
if cls._global_ring is None:
cls._global_ring = RingBuffer(maxlen=ring_buffer_size)
@classmethod
def shutdown(cls):
if cls._global_file is not None:
cls._global_file.stop()
def with_context(self, **kwargs):
ctx = dict(self._context)
ctx.update(kwargs)
return _ContextLogger(self, ctx)
def _enabled(self, level):
return level.value >= self._min_level.value
def _emit(self, level, msg, args=None, exc_info=None, **extra):
if not self._enabled(level):
return
label, color = LEVEL_LABELS[level]
if args:
try:
message = msg % args
except Exception:
message = msg + " " + repr(args)
else:
message = msg
ts = time.time()
tid = threading.get_ident() % 10000
prefix = f"{self.name}[{tid:04d}]"
if self._context:
ctx_str = " ".join(f"{k}={v}" for k, v in self._context.items())
prefix = f"{prefix} {ctx_str}"
record = {
"ts": ts,
"level": level.name,
"logger": self.name,
"thread": tid,
"context": dict(self._context),
"message": message,
"extra": extra or {},
}
if exc_info is not None:
record["exception"] = "".join(
traceback.format_exception(*exc_info)
)
if self._console:
stamp = time.strftime("%H:%M:%S", time.localtime(ts))
tag = _colorize(label, color)
line = f"{stamp} {tag} {prefix} {message}"
try:
print(line)
except Exception:
pass
if self._file is not None:
try:
line = json.dumps(record, default=str) + "\n"
self._file.write(line.encode("utf-8"))
except Exception:
pass
if self._ring is not None:
self._ring.append(record)
def _emit_simple(self, level, msg, *args, **kwargs):
self._emit(level, msg, args if args else None, **kwargs)
def trace(self, msg, *a, **k):
self._emit_simple(Level.TRACE, msg, *a, **k)
def debug(self, msg, *a, **k):
self._emit_simple(Level.DEBUG, msg, *a, **k)
def info(self, msg, *a, **k):
self._emit_simple(Level.INFO, msg, *a, **k)
def pass_(self, msg, *a, **k):
self._emit_simple(Level.PASS, msg, *a, **k)
def warn(self, msg, *a, **k):
self._emit_simple(Level.WARN, msg, *a, **k)
def fail(self, msg, *a, **k):
self._emit_simple(Level.FAIL, msg, *a, **k)
def error(self, msg, *a, **k):
self._emit_simple(Level.ERROR, msg, *a, **k)
def fatal(self, msg, *a, **k):
self._emit_simple(Level.FATAL, msg, *a, **k)
def exception(self, e, msg="exception"):
self._emit(Level.ERROR, f"{msg}: {e!r}",
exc_info=(type(e), e, e.__traceback__))
@contextlib.contextmanager
def timer(self, label):
t0 = time.perf_counter_ns()
try:
yield
finally:
elapsed_ms = (time.perf_counter_ns() - t0) / 1e6
with self._lock:
self._timings[label].append(elapsed_ms)
self.debug("timing[%s] = %.2f ms", label, elapsed_ms)
def event(self, name, **fields):
with self._lock:
self._events[name] += 1
self.debug("event[%s] %s", name,
" ".join(f"{k}={v}" for k, v in fields.items()))
def counter(self, name, delta=1):
with self._lock:
self._counters[name] += delta
def timing_stats(self):
with self._lock:
return {
k: {
"count": len(v),
"min_ms": round(min(v), 3),
"max_ms": round(max(v), 3),
"mean_ms": round(statistics.mean(v), 3),
"median_ms": round(statistics.median(v), 3),
"p95_ms": round(
sorted(v)[int(len(v) * 0.95)] if v else 0, 3
),
}
for k, v in self._timings.items() if v
}
def event_counts(self):
with self._lock:
return dict(self._events)
def counter_snapshot(self):
with self._lock:
return dict(self._counters)
class _ContextLogger:
__slots__ = ("_logger", "_ctx")
def __init__(self, logger, ctx):
self._logger = logger
self._ctx = ctx
def _emit(self, level, msg, *args):
old = self._logger._context
self._logger._context = self._ctx
try:
self._logger._emit_simple(level, msg, *args)
finally:
self._logger._context = old
def trace(self, msg, *a): self._emit(Level.TRACE, msg, *a)
def debug(self, msg, *a): self._emit(Level.DEBUG, msg, *a)
def info(self, msg, *a): self._emit(Level.INFO, msg, *a)
def pass_(self, msg, *a): self._emit(Level.PASS, msg, *a)
def warn(self, msg, *a): self._emit(Level.WARN, msg, *a)
def fail(self, msg, *a): self._emit(Level.FAIL, msg, *a)
def error(self, msg, *a): self._emit(Level.ERROR, msg, *a)
# ============================================================================
# TEST FRAMEWORK
# ============================================================================
class Status(Enum):
PASS = "PASS"
FAIL = "FAIL"
WARN = "WARN"
EMPTY = "EMPTY"
SLOW = "SLOW"
SKIP = "SKIP"
ERROR = "ERROR"
@dataclass
class TestResult:
category: str
name: str
status: str
detail: str = ""
elapsed_ms: float = 0.0
rss_mb: float = 0.0
cpu_pct: float = 0.0
extra: dict = field(default_factory=dict)
logs: list = field(default_factory=list)
traceback: str = ""
def to_dict(self):
d = asdict(self)
if not self.logs:
d.pop("logs", None)
if not self.traceback:
d.pop("traceback", None)
return d
class AssertionError(FolderAssertionError := type("FolderAssertionError", (AssertionError,), {})):
pass
class TestContext:
__slots__ = ("name", "category", "log", "start_ns", "_proc",
"_failures", "_warnings")
def __init__(self, category, name):
self.category = category
self.name = name
self.log = Logger(f"{category}.{name[:24]}")
self.start_ns = time.perf_counter_ns()
self._proc = psutil.Process(os.getpid())
self._failures = []
self._warnings = []
def expect(self, condition, message="assertion failed"):
if not condition:
raise AssertionError(message)
def expect_eq(self, a, b, label=""):
if a != b:
raise AssertionError(f"{label}: {a!r} != {b!r}")
def expect_neq(self, a, b, label=""):
if a == b:
raise AssertionError(f"{label}: {a!r} == {b!r}")
def expect_in(self, needle, haystack, label=""):
if needle not in haystack:
raise AssertionError(f"{label}: {needle!r} not in {haystack!r}")
def expect_gt(self, a, b, label=""):
if not a > b:
raise AssertionError(f"{label}: {a!r} <= {b!r}")
def expect_lt(self, a, b, label=""):
if not a < b:
raise AssertionError(f"{label}: {a!r} >= {b!r}")
def expect_raises(self, exc_type, fn, *args, **kwargs):
try:
fn(*args, **kwargs)
except exc_type:
return True
except Exception as e:
raise AssertionError(
f"expected {exc_type.__name__}, got {type(e).__name__}: {e!r}"
)
raise AssertionError(f"expected {exc_type.__name__}, no exception raised")
def warn(self, message):
self._warnings.append(message)
self.log.warn(message)
def rss_mb(self):
try:
return self._proc.memory_info().rss / (1024 * 1024)
except Exception:
return 0.0
def cpu_pct(self):
try:
return self._proc.cpu_percent(interval=None)
except Exception:
return 0.0
def elapsed_ms(self):
return (time.perf_counter_ns() - self.start_ns) / 1e6
def run(self, fn):
result = TestResult(
category=self.category,
name=self.name,
status=Status.PASS.value,
rss_mb=round(self.rss_mb(), 2),
)
try:
rv = fn(self)
if isinstance(rv, tuple) and len(rv) == 2:
status, detail = rv
result.status = status
result.detail = detail
except AssertionError as e:
result.status = Status.FAIL.value
result.detail = f"assert: {e}"
result.traceback = traceback.format_exc()
except Exception as e:
result.status = Status.ERROR.value
result.detail = f"{type(e).__name__}: {e}"
result.traceback = traceback.format_exc()
result.elapsed_ms = round(self.elapsed_ms(), 3)
result.cpu_pct = round(self.cpu_pct(), 2)
result.extra = {
"events": self.log.event_counts(),
"timings": self.log.timing_stats(),
"counters": self.log.counter_snapshot(),
}
return result
_REGISTRY = OrderedDict()
def test(category, name, skip_if=None, timeout=None):
def decorator(fn):
_REGISTRY.setdefault(category, []).append({
"name": name, "fn": fn, "skip_if": skip_if, "timeout": timeout,
})
return fn
return decorator
# ============================================================================
# ENVIRONMENT / DISCOVERY
# ============================================================================
class Env:
PROCESS = psutil.Process(os.getpid())
START = time.time()
CWD = str(Path.cwd())
PYTHON = sys.version.split()[0]
PLATFORM = f"{os.name} {sys.platform}"
CPU_COUNT = os.cpu_count() or 1
MEM_TOTAL_GB = round(psutil.virtual_memory().total / (1024 ** 3), 2)
DISK_FREE_GB = 0.0
try:
DISK_FREE_GB = round(psutil.disk_usage(".").free / (1024 ** 3), 2)
except Exception:
pass
@classmethod
def banner(cls):
return (
f"NEXUS debug harness v6 :: python {cls.PYTHON} :: "
f"{cls.PLATFORM} :: {cls.CPU_COUNT} cores :: "
f"{cls.MEM_TOTAL_GB} GB RAM :: {cls.DISK_FREE_GB} GB free"
)
# ============================================================================
# T0 — ENVIRONMENT
# ============================================================================
@test("T0", "environment info")
def t0_env(ctx):
ctx.log.info("python=%s", Env.PYTHON)
ctx.log.info("platform=%s", Env.PLATFORM)
ctx.log.info("cpu_count=%d", Env.CPU_COUNT)
ctx.log.info("mem_total_gb=%.2f", Env.MEM_TOTAL_GB)
ctx.log.info("disk_free_gb=%.2f", Env.DISK_FREE_GB)
ctx.expect(Env.CPU_COUNT >= 1)
return Status.PASS.value, f"cores={Env.CPU_COUNT} mem={Env.MEM_TOTAL_GB}GB"
@test("T0", "cleanup stale artifacts")
def t0_cleanup(ctx):
from folder_manager import FolderManager
appdata = os.environ.get("APPDATA", "")
if appdata:
nltk_dir = Path(appdata) / "nltk_data"
if nltk_dir.exists():
import shutil
shutil.rmtree(nltk_dir, ignore_errors=True)
ctx.log.info("removed nltk_data")
stale = [
"bloom.dbg.bin", "bloom.dbg2.bin",
"dedup.dbg.sqlite", "dedup.dbg2.sqlite",
"mos_budget.dbg.json", "mos_prefs.dbg.json",
"budget_score.dbg.json", "prefs_score.dbg.json",
"dlq.dbg.jsonl", "blocked.test.txt",
]
removed = 0
for name in stale:
p = Path(name)
if p.exists():
try:
p.unlink()
removed += 1
except Exception:
pass
FolderManager.bootstrap()
return Status.PASS.value, f"removed={removed}"
@test("T0", "folder manager bootstrap")
def t0_fm_bootstrap(ctx):
from folder_manager import FolderManager
FolderManager.bootstrap(force=True)
report = FolderManager.report()
ctx.expect(len(report["tiers"]) == len(FolderManager.TIERS))
for tier, entry in report["tiers"].items():
ctx.expect(Path(entry["path"]).exists(),
f"tier {tier} path missing")
return Status.PASS.value, f"tiers={len(report['tiers'])}"
# ============================================================================
# T1 — IMPORTS
# ============================================================================
MODULES = [
"config", "folder_manager", "spoof", "crawler",
"scraper", "api_router", "se_api",
]
def _make_import_test(modname):
@test("T1", f"import {modname}")
def _t(ctx, _m=modname):
mod = __import__(_m)
ctx.expect(hasattr(mod, "__file__") or hasattr(mod, "__name__"))
path = getattr(mod, "__file__", "?")
ctx.log.info("loaded from %s", path)
return Status.PASS.value, Path(path).name if path != "?" else "ok"
return _t
for _m in MODULES:
_make_import_test(_m)
# ============================================================================
# T2 — CONFIG INVARIANTS
# ============================================================================
def _cfg_check(name, predicate, detail=""):
@test("T2", name)
def _t(ctx, _p=predicate, _n=name, _d=detail):
import config as c
ctx.expect(_p(c), _n)
return Status.PASS.value, _d
return _t
_cfg_check("MAX_WORKERS >= 1", lambda c: c.MAX_WORKERS >= 1)
_cfg_check("MAX_QUEUE_SIZE == 500 or 5000",
lambda c: c.MAX_QUEUE_SIZE in (500, 5000, 50000))
_cfg_check("MAX_DEPTH > 0", lambda c: c.MAX_DEPTH > 0)
_cfg_check("REQUEST_TIMEOUT tuple",
lambda c: isinstance(c.REQUEST_TIMEOUT, tuple)
and len(c.REQUEST_TIMEOUT) == 2)
_cfg_check("BLOCKED_RETRY range",
lambda c: 0 < c.BLOCKED_RETRY_MIN < c.BLOCKED_RETRY_MAX)
_cfg_check("BROWSER_PROFILES >= 3",
lambda c: len(c.BROWSER_PROFILES) >= 3)
_cfg_check("LOCALES >= 3", lambda c: len(c.LOCALES) >= 3)
_cfg_check("BLOOM_BITS > 0", lambda c: c.BLOOM_BITS > 0)
_cfg_check("CONFIG_VERSION string",
lambda c: isinstance(c.CONFIG_VERSION, str))
_cfg_check("EXTRACTOR_VERSION present",
lambda c: isinstance(c.EXTRACTOR_VERSION, str) and c.EXTRACTOR_VERSION)
_cfg_check("MOS config",
lambda c: hasattr(c, "MOS_ENABLED") and hasattr(c, "MOS_DAILY_BUDGET"))
_cfg_check("API_ROUTER_ENABLED bool",
lambda c: isinstance(c.API_ROUTER_ENABLED, bool))
_cfg_check("SE config",
lambda c: hasattr(c, "SE_API_ENABLED") and hasattr(c, "SE_API_TIMEOUT"))
_cfg_check("BROWSER_PROFILES have family",
lambda c: all("family" in p for p in c.BROWSER_PROFILES))
@test("T2", "BROWSER_PROFILES impersonate resolvable")
def t2_impersonate_resolvable(ctx):
import config as c
import curl_cffi
for p in c.BROWSER_PROFILES:
imp = p.get("impersonate")
ctx.expect(imp, "missing impersonate")
try:
s = curl_cffi.requests.Session(impersonate=imp)
s.close()
except Exception as e:
ctx.log.warn("profile %s failed: %r", imp, e)
raise
return Status.PASS.value, f"profiles={len(c.BROWSER_PROFILES)}"
# ============================================================================
# T3 — SPOOF ENGINE
# ============================================================================
@test("T3", "SpoofedSession init normal")
def t3_session_normal(ctx):
from spoof import SpoofedSession
s = SpoofedSession("example.com", fast=False)
ctx.expect(s.impersonate)
ctx.expect(s.locale)
s.close()
return Status.PASS.value, f"imp={s.impersonate}"
@test("T3", "SpoofedSession init fast")
def t3_session_fast(ctx):
from spoof import SpoofedSession
s = SpoofedSession("example.com", fast=True)
ctx.expect(s.fast is True)
s.close()
return Status.PASS.value, ""
@test("T3", "fast jitter bypass")
def t3_fast_jitter(ctx):
from spoof import SpoofedSession
s = SpoofedSession("example.com", fast=True)
t0 = time.monotonic()
s._jitter()
el = time.monotonic() - t0
s.close()
ctx.expect_lt(el, 0.05, "fast jitter")
return Status.PASS.value, f"{el*1000:.1f}ms"
@test("T3", "slow jitter enforced")
def t3_slow_jitter(ctx):
from spoof import SpoofedSession
s = SpoofedSession("example.com", fast=False)
s._last_ts = time.monotonic()
t0 = time.monotonic()
s._jitter()
el = time.monotonic() - t0
s.close()
ctx.expect_gt(el, 0.4, "slow jitter")
return Status.PASS.value, f"{el:.2f}s"
@test("T3", "header order chrome profile")
def t3_header_chrome(ctx):
from spoof import SpoofedSession
from config import BROWSER_PROFILES
chrome = next((p for p in BROWSER_PROFILES if p.get("family") == "chrome"),
None)
if chrome is None:
return Status.SKIP.value, "no chrome profile"
s = SpoofedSession("example.com", fast=True, profile_override=chrome)
h = s._build_headers("https://example.com/x", "https://example.com/p")
keys = list(h.keys())
s.close()
ctx.expect_in("User-Agent", keys)
ctx.expect_in("Accept", keys)
ctx.expect_in("Referer", keys)
ctx.expect_lt(keys.index("User-Agent"), keys.index("Accept"),
"UA should precede Accept")
return Status.PASS.value, ""
@test("T3", "header order firefox profile")
def t3_header_firefox(ctx):
from spoof import SpoofedSession
from config import BROWSER_PROFILES
ff = next((p for p in BROWSER_PROFILES if p.get("family") == "firefox"),
None)
if ff is None:
return Status.SKIP.value, "no firefox profile"
s = SpoofedSession("example.com", fast=True, profile_override=ff)
h = s._build_headers("https://example.com/x", None)
keys = list(h.keys())
s.close()
ctx.expect_in("User-Agent", keys)
ctx.expect("Referer" not in keys, "firefox no-referer should not send Referer")
return Status.PASS.value, ""
@test("T3", "sec-fetch-site computation")
def t3_sec_fetch(ctx):
import spoof
same = spoof._sec_fetch_site("https://example.com/a", "example.com")
cross = spoof._sec_fetch_site("https://other.com/a", "example.com")
none = spoof._sec_fetch_site(None, "example.com")
ctx.expect_eq(same, "same-origin", "same")
ctx.expect_eq(cross, "cross-site", "cross")
ctx.expect_eq(none, "none", "none")
return Status.PASS.value, ""
@test("T3", "referer chain")
def t3_referer_chain(ctx):
from spoof import SpoofedSession
s = SpoofedSession("example.com", fast=True)
r1 = s._referer("https://example.com/a", None)
ctx.expect(r1 is None, "first should have no referer")
s._last_url = "https://example.com/a"
r2 = s._referer("https://example.com/b", None)
ctx.expect_eq(r2, "https://example.com/a", "chain")
s.close()
return Status.PASS.value, ""
@test("T3", "rotate_fingerprint changes identity")
def t3_rotate(ctx):
from spoof import SpoofedSession
s = SpoofedSession("example.com", fast=True)
old = s.impersonate
o, n = s.rotate_fingerprint()
ctx.expect_eq(o, old, "old")
ctx.expect_eq(n, s.impersonate, "new")
s.close()
return Status.PASS.value, ""
@test("T3", "SOD pool acquire")
def t3_sod_pool(ctx):
try:
from spoof import SODPool
except ImportError:
return Status.SKIP.value, "SODPool not present"
pool = SODPool(size=3)
w1 = pool.acquire("example.com")
w2 = pool.acquire("example.com")
ctx.expect_eq(w1.worker_id, w2.worker_id, "sticky domain")
pool.close()
return Status.PASS.value, ""
# ============================================================================
# T4 — CRAWLER INTERNALS
# ============================================================================
@test("T4", "bloom filter 200 inserts")
def t4_bloom(ctx):
from crawler import BloomFilter
bf = BloomFilter(nbits=1 << 16, nhash=5)
for i in range(200):
bf.add(f"item-{i}")
hits = sum(1 for i in range(200) if f"item-{i}" in bf)
ctx.expect_eq(hits, 200, "hits")
return Status.PASS.value, f"{hits}/200"
@test("T4", "bloom filter persistence")
def t4_bloom_persist(ctx):
from crawler import BloomFilter
tmp = "bloom.dbg.bin"
try:
bf = BloomFilter(nbits=1 << 16, nhash=5)
bf.add("persist-test")
bf.save(tmp)
bf2 = BloomFilter.load(tmp)
ctx.expect("persist-test" in bf2, "persisted key")
finally:
Path(tmp).unlink(missing_ok=True)
return Status.PASS.value, ""
@test("T4", "simhash determinism")
def t4_simhash(ctx):
from crawler import _simhash64
h1 = _simhash64(["hello", "world", "foo"])
h2 = _simhash64(["hello", "world", "foo"])
h3 = _simhash64(["different", "tokens", "here"])
ctx.expect_eq(h1, h2, "determinism")
ctx.expect_neq(h1, h3, "different tokens")
return Status.PASS.value, ""
@test("T4", "hamming distance")
def t4_hamming(ctx):
from crawler import _hamming
ctx.expect_eq(_hamming(0b1011, 0b1001), 1, "one bit")
ctx.expect_eq(_hamming(0, 0xFFFFFFFFFFFFFFFF), 64, "all bits")
return Status.PASS.value, ""
@test("T4", "minhash signature")
def t4_minhash(ctx):
from crawler import _minhash_signature, _minhash_jaccard
a = _minhash_signature(["a", "b", "c"])
b = _minhash_signature(["a", "b", "c"])
c = _minhash_signature(["x", "y", "z"])
ctx.expect_eq(a, b, "identical sigs")
ctx.expect_eq(_minhash_jaccard(a, b), 1.0, "jaccard self")
ctx.expect_lt(_minhash_jaccard(a, c), 1.0, "jaccard diff")
return Status.PASS.value, ""
@test("T4", "TLD+1 same")
def t4_tld_same(ctx):
from crawler import _same_tld_plus_one
ctx.expect(_same_tld_plus_one(
"https://en.wikipedia.org/wiki/X",
"https://fr.wikipedia.org/wiki/Y"
), "same TLD")
return Status.PASS.value, ""
@test("T4", "TLD+1 cross")
def t4_tld_cross(ctx):
from crawler import _same_tld_plus_one
ctx.expect(not _same_tld_plus_one(
"https://en.wikipedia.org/wiki/X",
"https://example.com/"
), "cross TLD")
return Status.PASS.value, ""
@test("T4", "domain token bucket")
def t4_domain_tracker(ctx):
from crawler import DomainTracker
import config as c
dt = DomainTracker()
for _ in range(c.DOMAIN_TOKEN_BUCKET_BURST):
ctx.expect(dt.try_acquire("x.com"), "burst exhausted early")
ctx.expect(not dt.try_acquire("x.com"), "should be rate-limited")
return Status.PASS.value, ""
@test("T4", "host health decay")
def t4_health(ctx):
from crawler import HostHealth
h = HostHealth()
ctx.expect_eq(h.score, 1.0, "start")
h.record_failure(1.0)
ctx.expect_lt(h.score, 1.0, "after fail")
h.record_success()
ctx.expect_gt(h.score, 0.5, "after recovery")
return Status.PASS.value, f"score={h.score:.2f}"
@test("T4", "trap detector 6 cases")
def t4_trap(ctx):
from crawler import _detect_trap
cases = [
("https://x.com/a/b/c/a/b/c/a/b/c/a/b/c", True),
("https://x.com/2030/12/25/", True),
("https://x.com/?jsessionid=abc123", True),
("https://x.com/normal/path", False),
("https://x.com/2027/12/25/", False),
("https://x.com/?a=" + "a" * 40, True),
]
for url, expected in cases:
trap, reason = _detect_trap(url)
ctx.expect_eq(trap, expected,
f"{url[:60]} reason={reason}")
return Status.PASS.value, ""
@test("T4", "mercator frontier push/pop")
def t4_mercator(ctx):
from crawler import MercatorFrontier
f = MercatorFrontier(cap=100)
for i in range(50):
ctx.expect(f.push(f"https://a.com/{i}", 0, 0, 0.5), f"push {i}")
ctx.expect_eq(len(f), 50, "len")
popped = f.pop()
ctx.expect(popped is not None, "pop")
ctx.expect_eq(len(f), 49, "len after pop")
return Status.PASS.value, ""
@test("T4", "mercator frontier cap")
def t4_mercator_cap(ctx):
from crawler import MercatorFrontier
f = MercatorFrontier(cap=10)
for i in range(20):
f.push(f"https://a.com/{i}", 0, 0)
ctx.expect_eq(len(f), 10, "cap")
return Status.PASS.value, ""
@test("T4", "dead letter queue")
def t4_dlq(ctx):
from crawler import DeadLetterQueue
tmp = "dlq.dbg.jsonl"
try:
Path(tmp).unlink(missing_ok=True)
dlq = DeadLetterQueue(tmp)
dlq.add("https://x.com/a", "err", 3)
dlq.close()
ctx.expect(Path(tmp).exists())
size = Path(tmp).stat().st_size
ctx.expect_gt(size, 10, "file size")
finally:
Path(tmp).unlink(missing_ok=True)
return Status.PASS.value, ""
@test("T4", "change detector etag")
def t4_change(ctx):
from crawler import ChangeDetector
cd = ChangeDetector()
cd.observe("https://x.com/a", {"etag": '"v1"'})
changed = cd.observe("https://x.com/a", {"etag": '"v2"'})
ctx.expect(changed is True, "change detected")
return Status.PASS.value, ""
@test("T4", "yield tracker records")