An open source, non-profit web search engine
Fix crawler error reports filed twice or under the server's identity
Claude1bbc07921302
diff --git a/mwmbl/crawl.py b/mwmbl/crawl.pyindex 1136b9b..37e640a 100644--- a/mwmbl/crawl.py+++ b/mwmbl/crawl.py@@ -1,6 +1,7 @@import argparseimport loggingimport os+import sysimport timeimport tracebackfrom datetime import datetime, timedelta, timezone@@ -30,7 +31,15 @@ print("Mwmbl crawling statistics: https://mwmbl.org/stats")django.setup()-from mwmbl.crawler.batch import CrawlerErrorReport, ErrorFrame, HashedBatch, Result, Results+from mwmbl.crawler.batch import (+ MAX_ERROR_MESSAGE_LENGTH,+ CrawlerErrorReport,+ ErrorContext,+ ErrorFrame,+ HashedBatch,+ Result,+ Results,+)from mwmbl.crawler.device import get_device_namefrom mwmbl.crawler.env_vars import (CRAWL_DELAY_SECONDS,@@ -99,10 +108,29 @@ def _fetch_curated_domains() -> set[str]:# How long to wait before reporting the same error from the same process again. The loops# retry every ten seconds, so a persistent failure would otherwise send a report each time.ERROR_REPORT_INTERVAL_SECONDS = 3600.0-_error_last_reported_at: dict[tuple[str, str, str, int | None], float] = {}+_error_last_reported_at: dict[tuple[ErrorContext, str, str, int | None], float] = {}+++# The server accepts at most this many frames. A traceback deeper than that is almost always+# recursion, where the innermost frames are the ones that say what went wrong.+MAX_ERROR_FRAMES = 200+++def _module_path(filename: str) -> str:+ """+ The path of a source file relative to the Python path entry it was imported from.++ An absolute path names the volunteer's home directory, which often carries their name -+ the reason the crawler identifies itself by a generated device name, not its hostname.+ """+ containing_entries = [entry for entry in sys.path if entry and filename.startswith(entry.rstrip("/") + "/")]+ if not containing_entries:+ return os.path.basename(filename)+ longest_entry = max(containing_entries, key=len)+ return os.path.relpath(filename, longest_entry)-def report_error(context: str, error: Exception):+def report_error(context: ErrorContext, error: Exception):"""Send an error the crawl loops caught to the Mwmbl server, which passes it on to Sentry.@@ -124,13 +152,15 @@ def report_error(context: str, error: Exception):return_error_last_reported_at[error_key] = now+ # Messages can name local files too - "No such file or directory: '/home/...'".+ message = str(error).replace(str(Path.home()), "~")[:MAX_ERROR_MESSAGE_LENGTH]report = CrawlerErrorReport(context=context,exception_type=exception_type,- message=str(error),+ message=message,frames=[- ErrorFrame(filename=frame.filename, lineno=frame.lineno, function=frame.name, line=frame.line)- for frame in frames+ ErrorFrame(filename=_module_path(frame.filename), lineno=frame.lineno, function=frame.name, line=frame.line)+ for frame in frames[-MAX_ERROR_FRAMES:]],crawler_version=CRAWLER_VERSION,device_name=get_device_name(data_path),diff --git a/mwmbl/crawler/README.md b/mwmbl/crawler/README.mdindex 5cdf420..7e59229 100644--- a/mwmbl/crawler/README.md+++ b/mwmbl/crawler/README.md@@ -22,7 +22,7 @@ Batches crawled by different workers at the same time can share domains, since e- `CRAWL_DELAY_SECONDS` (default: 0.0) - Delay in seconds each crawl thread waits between the URLs it crawls. Includes 10% random fuzz (±10%) to avoid synchronized requests across workers. Set to 0 to disable delays.### Error Reporting-- `CRAWL_REPORT_ERRORS` (default: true) - Send the errors the crawler catches and recovers from to the Mwmbl server (`POST /api/v1/crawler/errors`), so the maintainers can see when crawlers are failing. A report holds the exception, its traceback, the crawler version and the device name. Each distinct error is reported at most once an hour per process. Set to `false` to opt out. Nothing is reported when `CRAWL_SUBMIT_MODE` is `off`.+- `CRAWL_REPORT_ERRORS` (default: true) - Send the errors the crawler catches and recovers from to the Mwmbl server (`POST /api/v1/crawler/errors`), so the maintainers can see when crawlers are failing. A report holds the exception, its traceback, the crawler version and the device name. File paths are sent relative to the Python path and your home directory is replaced with `~`, so reports do not name your account. Each distinct error is reported at most once an hour per process. Set to `false` to opt out. Nothing is reported when `CRAWL_SUBMIT_MODE` is `off`.### Redis Configuration- `REDIS_URL` (default: 'redis://127.0.0.1:6379') - Redis connection URL for URL queues and statsdiff --git a/mwmbl/crawler/app.py b/mwmbl/crawler/app.pyindex 5a4861b..c02f056 100644--- a/mwmbl/crawler/app.py+++ b/mwmbl/crawler/app.py@@ -293,9 +293,9 @@ def _register_routes(r: Router | NinjaAPI):if api_key is None:return 401, {"message": INVALID_CRAWL_KEY_MESSAGE}- logger.error(- f"Crawler error from user {api_key.user.id} ({report.context}): {report.exception_type}: {report.message}"- )+ # Info, not error: Sentry's logging integration sends every error log as an event of+ # its own, which would file each report a second time, under production.+ logger.info("Crawler error from user %s (%s): %s", api_key.user.id, report.context, report.exception_type)sentry_sdk.capture_event(_crawler_error_event(report, api_key.user.id))return {"status": "ok"}@@ -381,21 +381,14 @@ def _crawler_error_event(report: CrawlerErrorReport, user_id: int) -> dict:}for frame in report.frames]- tags = {- "source": "crawler",- "crawler_context": report.context,- "crawler_version": report.crawler_version,- "crawler_device": report.device_name,- }- # Set explicitly, or the SDK fills environment, release and server_name in from the server- # itself, filing a volunteer's crawler bug under production on our host. Its own- # environment puts crawler issues behind Sentry's environment filter, apart from ours.- release = f"mwmbl-crawler@{report.crawler_version}" if report.crawler_version else None+ # Set explicitly, and never to None, or the SDK fills environment, release and server_name+ # in from the server itself, filing a volunteer's crawler bug under production on our host.+ # Its own environment puts crawler issues behind Sentry's environment filter, apart from ours.return {"level": "error","logger": "mwmbl.crawler.remote","environment": "crawler",- "release": release,+ "release": f"mwmbl-crawler@{report.crawler_version}","server_name": report.device_name,"exception": {"values": [@@ -406,7 +399,12 @@ def _crawler_error_event(report: CrawlerErrorReport, user_id: int) -> dict:}]},- "tags": {tag: value for tag, value in tags.items() if value is not None},+ "tags": {+ "source": "crawler",+ "crawler_context": report.context,+ "crawler_version": report.crawler_version,+ "crawler_device": report.device_name,+ },"user": {"id": str(user_id)},}diff --git a/mwmbl/crawler/batch.py b/mwmbl/crawler/batch.pyindex 473f4eb..28224a7 100644--- a/mwmbl/crawler/batch.py+++ b/mwmbl/crawler/batch.py@@ -1,4 +1,4 @@-from typing import Optional+from typing import Literal, Optionalfrom ninja import Field, Schema@@ -222,30 +222,44 @@ class PostResultsResponse(Schema):)+# Every field of an error report ends up in Sentry, and anyone with a crawl key can send one,+# so each is bounded: well past anything a real report needs, short of a payload Sentry+# would drop. The tag-like fields stay inside Sentry's 200-character limit on tag values.+MAX_ERROR_MESSAGE_LENGTH = 8192+MAX_ERROR_FRAME_FIELD_LENGTH = 1024+MAX_ERROR_TAG_LENGTH = 200++# The crawler loop that caught an error.+ErrorContext = Literal["batch", "indexing"]++class ErrorFrame(Schema):"""One frame of the traceback of an exception a crawler caught."""- filename: str = Field(example="/venv/lib/python3.11/site-packages/mwmbl/crawl.py")+ filename: str = Field(max_length=MAX_ERROR_FRAME_FIELD_LENGTH, example="mwmbl/crawl.py")lineno: Optional[int] = Field(example=312)- function: str = Field(example="run_indexing")- line: Optional[str] = Field(default=None, example="response.raise_for_status()")+ function: str = Field(max_length=MAX_ERROR_FRAME_FIELD_LENGTH, example="run_indexing")+ line: Optional[str] = Field(+ default=None, max_length=MAX_ERROR_FRAME_FIELD_LENGTH, example="response.raise_for_status()"+ )class CrawlerErrorReport(Schema):"""An exception a crawler caught and recovered from, reported so it is not lost in local logs."""- context: str = Field(+ context: ErrorContext = Field(description="Which crawler loop caught the exception.",example="indexing",)- exception_type: str = Field(example="requests.exceptions.HTTPError")- message: str = Field(example="502 Server Error: Bad Gateway")+ exception_type: str = Field(max_length=MAX_ERROR_FRAME_FIELD_LENGTH, example="requests.exceptions.HTTPError")+ message: str = Field(max_length=MAX_ERROR_MESSAGE_LENGTH, example="502 Server Error: Bad Gateway")frames: list[ErrorFrame] = Field(- description="The traceback, outermost frame first.",+ description="The traceback, outermost frame first. File paths are relative to the Python path entry.",+ min_length=1,max_length=200,)- crawler_version: Optional[str] = Field(default=None, example="1.2.0")- device_name: Optional[str] = Field(default=None, example="crawler-3f7a1c9e")+ crawler_version: str = Field(max_length=MAX_ERROR_TAG_LENGTH, example="1.2.0")+ device_name: str = Field(max_length=MAX_ERROR_TAG_LENGTH, example="crawler-3f7a1c9e")class StatusResponse(Schema):diff --git a/mwmbl/crawler/env_vars.py b/mwmbl/crawler/env_vars.pyindex 173503f..1ab5bf8 100644--- a/mwmbl/crawler/env_vars.py+++ b/mwmbl/crawler/env_vars.py@@ -24,7 +24,8 @@ MWMBL_DEVICE_NAME = os.environ.get("MWMBL_DEVICE_NAME", "")# Whether to send the errors the crawl loops catch to the Mwmbl server, so we can see when# crawlers are failing. Reports carry the exception and traceback, the crawler version and-# the device name - nothing about the machine beyond the file paths in the traceback.+# the device name. File paths are sent relative to the Python path, and the home directory+# is replaced with ~ in the message, so a report does not name the volunteer's account.CRAWL_REPORT_ERRORS = os.environ.get("CRAWL_REPORT_ERRORS", "true").lower() == "true"# Bounds for running the crawler somewhere that is not a volunteer's machine - CI, mainly.diff --git a/test/test_crawler_error_reports.py b/test/test_crawler_error_reports.pyindex 4459d80..0227139 100644--- a/test/test_crawler_error_reports.py+++ b/test/test_crawler_error_reports.py@@ -10,10 +10,13 @@ from unittest.mock import patchimport pytestimport requests+import sentry_sdkfrom django.contrib.auth import get_user_modelfrom django.test import Client+from sentry_sdk.transport import Transportfrom mwmbl import crawl+from mwmbl.crawler.batch import MAX_ERROR_MESSAGE_LENGTH, MAX_ERROR_TAG_LENGTHfrom mwmbl.models import ApiKey, generate_api_keyUser = get_user_model()@@ -43,19 +46,36 @@ def make_api_key(scope):return user, raw_key-def post_report(raw_key):- return Client().post("/api/v1/crawler/errors", content_type="application/json", data=REPORT, HTTP_X_API_KEY=raw_key)+def post_report(raw_key, report=REPORT):+ return Client().post("/api/v1/crawler/errors", content_type="application/json", data=report, HTTP_X_API_KEY=raw_key)+++class CapturingTransport(Transport):+ def __init__(self, options):+ super().__init__(options)+ self.events = []++ def capture_envelope(self, envelope):+ self.events.extend(item.payload.json for item in envelope.items if item.type == "event")+++def sentry_events():+ """The events a real Sentry client sends, so the SDK's own defaults are part of the test."""+ with sentry_sdk.init(dsn="https://[email protected]/1", transport=CapturingTransport, release="server"):+ transport = sentry_sdk.get_client().transport+ yield transport.events@pytest.mark.django_db-def test_a_report_goes_to_sentry_as_an_exception_with_its_traceback():+def test_a_report_goes_to_sentry_once_as_a_crawler_exception(sentry_events):user, raw_key = make_api_key(ApiKey.Scope.CRAWL)- with patch("mwmbl.crawler.app.sentry_sdk.capture_event") as capture_event:- response = post_report(raw_key)+ response = post_report(raw_key)+ sentry_sdk.flush()assert response.status_code == 200- event = capture_event.call_args.args[0]+ [event] = sentry_eventsexception = event["exception"]["values"][0]assert exception["type"] == "requests.exceptions.HTTPError"assert exception["value"] == "502 Server Error: Bad Gateway"@@ -69,6 +89,28 @@ def test_a_report_goes_to_sentry_as_an_exception_with_its_traceback():assert event["user"] == {"id": str(user.id)}+ "change",+ [+ {"crawler_version": None},+ {"device_name": None},+ {"context": "anything"},+ {"frames": []},+ {"message": "x" * (MAX_ERROR_MESSAGE_LENGTH + 1)},+ {"device_name": "x" * (MAX_ERROR_TAG_LENGTH + 1)},+ ],+)+def test_a_report_sentry_could_misfile_or_drop_is_rejected(change):+ raw_key = make_api_key(ApiKey.Scope.CRAWL)[1]++ with patch("mwmbl.crawler.app.sentry_sdk.capture_event") as capture_event:+ response = post_report(raw_key, {**REPORT, **change})++ assert response.status_code == 422+ capture_event.assert_not_called()++@pytest.mark.django_db@pytest.mark.parametrize("scope", [ApiKey.Scope.SEARCH, None])def test_a_report_needs_a_crawl_key(scope):@@ -131,7 +173,26 @@ def test_nothing_is_reported_when_turned_off(reporting, monkeypatch, setting, vareporting.assert_not_called()-def test_a_failed_report_does_not_raise(reporting):+def test_the_report_does_not_name_the_volunteers_home_directory(reporting, monkeypatch, tmp_path):+ monkeypatch.setattr(crawl.Path, "home", lambda: tmp_path)+ error = raise_and_catch(FileNotFoundError(f"No such file: '{tmp_path}/.mwmbl/index'"))++ crawl.report_error("indexing", error)++ report = reporting.call_args.kwargs["json"]+ assert report["message"] == "No such file: '~/.mwmbl/index'"+ assert report["frames"][-1]["filename"] == "test_crawler_error_reports.py"+++def test_a_frame_path_is_relative_to_its_python_path_entry(monkeypatch):+ monkeypatch.setattr(crawl.sys, "path", ["/home/jane/venv/lib/site-packages", "/home/jane"])++ assert crawl._module_path("/home/jane/venv/lib/site-packages/mwmbl/crawl.py") == "mwmbl/crawl.py"+++def test_a_failed_report_is_logged_not_raised(reporting, caplog):reporting.side_effect = requests.ConnectionError("server down")crawl.report_error("indexing", raise_and_catch(ValueError("bad page")))++ assert "Failed to report error" in caplog.text