From 41b08488f4cf181ae040074c8068a9e1161cc43f Mon Sep 17 00:00:00 2001 From: Nanda Pranesh Date: Mon, 30 Nov 2026 19:19:35 +0530 Subject: [PATCH 1/2] Group discovery errors in GlitchTip by code path, not scan folder (WEB-6914) The GlitchTip copy gets a fingerprint of error type, agent frames and HTTP code, so the per-scan temp folder no longer opens a new issue each scan. The Sentry copy is unchanged. Co-Authored-By: Claude Opus 5.5 --- scripts/coding_discovery_tools/utils.py | 52 ++++++++++++++++++-- tests/test_discovery_flow.py | 63 ++++++++++++++++++++++--- 2 files changed, 105 insertions(+), 10 deletions(-) diff --git a/scripts/coding_discovery_tools/utils.py b/scripts/coding_discovery_tools/utils.py index e7dd83af..972695b3 100644 --- a/scripts/coding_discovery_tools/utils.py +++ b/scripts/coding_discovery_tools/utils.py @@ -3692,8 +3692,39 @@ def _post_sentry_event(dsn: Dict[str, str], payload_path: str, timeout: int) -> return sent_ok -def _copy_event_to_glitchtip(payload_path: str, timeout: int, priority: bool) -> None: - """Send the same event file to GlitchTip. Never raises, and never touches the Sentry breaker.""" +_AGENT_PACKAGE_DIR = "coding_discovery_tools/" + + +def _frame_location(filename: str) -> str: + """The frame's path inside the agent package, without the per-scan temp folder.""" + path = filename.replace("\\", "/") + if _AGENT_PACKAGE_DIR in path: + return path.rsplit(_AGENT_PACKAGE_DIR, 1)[1] + return path.rsplit("/", 1)[-1] + + +def _grouping_fingerprint(payload: Dict) -> Optional[List[str]]: + """Group by error type and code path, since GlitchTip would otherwise split on the temp folder.""" + exception = payload["exception"]["values"][-1] + frames = exception["stacktrace"]["frames"] + # Python 3.12 inlines comprehensions, so -style frames would split the same bug by version. + named_frames = [frame for frame in frames if not str(frame.get("function", "")).startswith("<")] + agent_frames = [ + frame for frame in named_frames if _AGENT_PACKAGE_DIR in str(frame.get("filename", "")).replace("\\", "/") + ] + chosen_frames = agent_frames or named_frames[-1:] or frames[-1:] + if not chosen_frames: + return None + fingerprint = [str(exception["type"])] + fingerprint += [f"{_frame_location(str(frame['filename']))}:{frame['function']}" for frame in chosen_frames[-10:]] + http_code = payload["extra"].get("http_code") + if http_code: + fingerprint.append(f"HTTP {http_code}") + return fingerprint + + +def _copy_event_to_glitchtip(payload: Dict, timeout: int, priority: bool) -> None: + """Send the event to GlitchTip with a grouping fingerprint. Never raises or touches the Sentry breaker.""" global _glitchtip_consecutive_fails try: dsn = _parse_sentry_dsn(_GLITCHTIP_DSN) if _GLITCHTIP_DSN else None @@ -3701,11 +3732,26 @@ def _copy_event_to_glitchtip(payload_path: str, timeout: int, priority: bool) -> return if _glitchtip_consecutive_fails >= _SENTRY_BREAKER_THRESHOLD and not priority: return + try: + fingerprint = _grouping_fingerprint(payload) + except Exception as fingerprint_err: + logger.debug(f"GlitchTip fingerprint failed; sending with default grouping: {fingerprint_err}") + fingerprint = None + glitchtip_payload = {**payload, "fingerprint": fingerprint} if fingerprint else payload sent_ok = False + fd, payload_path = tempfile.mkstemp(prefix="ai-discovery-glitchtip-", suffix=".json") try: + try: + os.write(fd, json.dumps(glitchtip_payload).encode("utf-8")) + finally: + os.close(fd) sent_ok = _post_sentry_event(dsn, payload_path, timeout) finally: _glitchtip_consecutive_fails = 0 if sent_ok else _glitchtip_consecutive_fails + 1 + try: + os.unlink(payload_path) + except OSError: + pass except Exception as glitchtip_err: logger.debug(f"GlitchTip reporting failed: {glitchtip_err}") @@ -3811,7 +3857,7 @@ def report_to_sentry( finally: glitchtip_timeout = event_timeout if max_seconds is None else int( min(event_timeout, max_seconds - (time.monotonic() - post_started))) - _copy_event_to_glitchtip(tmp_path, glitchtip_timeout, priority) + _copy_event_to_glitchtip(payload, glitchtip_timeout, priority) finally: try: os.unlink(tmp_path) diff --git a/tests/test_discovery_flow.py b/tests/test_discovery_flow.py index 38fda1ef..11e8b025 100644 --- a/tests/test_discovery_flow.py +++ b/tests/test_discovery_flow.py @@ -790,7 +790,7 @@ def test_cap_limits_events_per_run(self, mock_run): report_to_sentry(RuntimeError("x"), {"phase": f"p{i}"}) self.assertEqual(mock_run.call_count, 30) - def test_same_event_is_copied_to_glitchtip(self): + def _sentry_and_glitchtip_servers(self): servers = [HTTPServer(("127.0.0.1", 0), _CLIMockHandler) for _ in range(2)] for server in servers: server.requests, server.default_code = [], 200 @@ -798,13 +798,62 @@ def test_same_event_is_copied_to_glitchtip(self): self.addCleanup(server.server_close) self.addCleanup(server.shutdown) sentry_port, glitchtip_port = (server.server_address[1] for server in servers) - with patch.object(utils_mod, "_SENTRY_DSN", f"http://k@127.0.0.1:{sentry_port}/1"), \ - patch.object(utils_mod, "_GLITCHTIP_DSN", f"http://k@127.0.0.1:{glitchtip_port}/2"): + for name, port, project in (("_SENTRY_DSN", sentry_port, 1), ("_GLITCHTIP_DSN", glitchtip_port, 2)): + patcher = patch.object(utils_mod, name, f"http://k@127.0.0.1:{port}/{project}") + patcher.start() + self.addCleanup(patcher.stop) + return servers + + def test_same_event_is_copied_to_glitchtip(self): + sentry, glitchtip = self._sentry_and_glitchtip_servers() + report_to_sentry(RuntimeError("x"), {"phase": "extract"}) + self.assertEqual(1, len(sentry.requests)) + self.assertEqual([event["event_id"] for event in sentry.requests], + [event["event_id"] for event in glitchtip.requests]) + + def test_glitchtip_copy_groups_the_same_bug_across_scan_folders(self): + sentry, glitchtip = self._sentry_and_glitchtip_servers() + + def frames_in(scan_folder): + return [{"filename": f"/private/var/folders/0z/T/{scan_folder}/scripts/coding_discovery_tools/utils.py", + "lineno": 1840, "function": "send_report_to_backend"}] + + for scan_folder, http_code in (("tmp.wUJAK3PwWf", 413), ("tmp.2obfHXgZ3i", 413), ("tmp.2obfHXgZ3i", 401)): + utils_mod.reset_sentry_run_state() + with patch.object(utils_mod, "_extract_frames", return_value=frames_in(scan_folder)): + report_to_sentry(RuntimeError(f"HTTP {http_code}: body from {scan_folder}"), + {"phase": "send_report", "http_code": http_code}) + fingerprints = [event.get("fingerprint") for event in glitchtip.requests] + self.assertEqual(["RuntimeError", "utils.py:send_report_to_backend", "HTTP 413"], fingerprints[0]) + self.assertEqual(fingerprints[0], fingerprints[1]) + self.assertNotEqual(fingerprints[0], fingerprints[2]) + self.assertEqual([None, None, None], [event.get("fingerprint") for event in sentry.requests]) + + def test_glitchtip_copy_without_a_fingerprint_when_building_it_fails(self): + sentry, glitchtip = self._sentry_and_glitchtip_servers() + with patch.object(utils_mod, "_grouping_fingerprint", side_effect=KeyError("frames")): report_to_sentry(RuntimeError("x"), {"phase": "extract"}) - sentry_events, glitchtip_events = (server.requests for server in servers) - self.assertEqual(1, len(sentry_events)) - self.assertEqual([event["event_id"] for event in sentry_events], - [event["event_id"] for event in glitchtip_events]) + self.assertEqual(1, len(glitchtip.requests)) + self.assertNotIn("fingerprint", glitchtip.requests[0]) + + def test_glitchtip_fingerprint_keeps_os_folders_and_skips_version_specific_frames(self): + scan_folder = "C:\\Users\\x\\AppData\\Local\\Temp\\tmpabc\\scripts\\coding_discovery_tools\\" + frames = [ + {"filename": scan_folder + "ai_tools_discovery.py", "function": "main"}, + {"filename": scan_folder + "windows\\cursor\\mcp_config_extractor.py", "function": ""}, + {"filename": scan_folder + "windows\\cursor\\mcp_config_extractor.py", "function": "extract"}, + {"filename": "C:\\Python312\\Lib\\json\\decoder.py", "function": "decode"}, + ] + + def fingerprint_for(event_frames): + exception = {"type": "ValueError", "stacktrace": {"frames": event_frames}} + return utils_mod._grouping_fingerprint({"exception": {"values": [exception]}, "extra": {}}) + + self.assertEqual( + ["ValueError", "ai_tools_discovery.py:main", "windows/cursor/mcp_config_extractor.py:extract"], + fingerprint_for(frames)) + self.assertEqual(["ValueError", "decoder.py:decode"], fingerprint_for(frames[3:])) + self.assertIsNone(fingerprint_for([])) def test_glitchtip_copy_is_off_when_the_sentry_dsn_is_overridden(self): probe = "import scripts.coding_discovery_tools.utils as u; print(bool(u._GLITCHTIP_DSN))" From bfdac805a89d3d72d1c967ebcb68fddc6606596b Mon Sep 17 00:00:00 2001 From: Nanda Pranesh Date: Mon, 30 Nov 2026 19:39:32 +0530 Subject: [PATCH 2/2] Split GlitchTip network-failure issues by curl exit code (WEB-6914) DNS, refused and TLS failures each get their own GlitchTip issue instead of one shared one. Co-Authored-By: Claude Opus 5.5 --- scripts/coding_discovery_tools/utils.py | 5 ++++- tests/test_discovery_flow.py | 13 +++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/scripts/coding_discovery_tools/utils.py b/scripts/coding_discovery_tools/utils.py index 972695b3..6bf2d717 100644 --- a/scripts/coding_discovery_tools/utils.py +++ b/scripts/coding_discovery_tools/utils.py @@ -1809,7 +1809,7 @@ def _note(kind: str) -> bool: try: raise RuntimeError(error_msg) except RuntimeError as exc: - report_to_sentry(exc, {**ctx, "phase": "send_report", "attempt": attempt, "curl_stderr": (result.stderr.strip() or "")[:1024]}, level="warning", + report_to_sentry(exc, {**ctx, "phase": "send_report", "attempt": attempt, "curl_exit_code": result.returncode, "curl_stderr": (result.stderr.strip() or "")[:1024]}, level="warning", max_seconds=_left_for_telemetry()) return (False, True) @@ -3720,6 +3720,9 @@ def _grouping_fingerprint(payload: Dict) -> Optional[List[str]]: http_code = payload["extra"].get("http_code") if http_code: fingerprint.append(f"HTTP {http_code}") + curl_exit_code = payload["extra"].get("curl_exit_code") + if curl_exit_code: + fingerprint.append(f"curl exit {curl_exit_code}") return fingerprint diff --git a/tests/test_discovery_flow.py b/tests/test_discovery_flow.py index 11e8b025..06937b08 100644 --- a/tests/test_discovery_flow.py +++ b/tests/test_discovery_flow.py @@ -855,6 +855,19 @@ def fingerprint_for(event_frames): self.assertEqual(["ValueError", "decoder.py:decode"], fingerprint_for(frames[3:])) self.assertIsNone(fingerprint_for([])) + def test_glitchtip_fingerprint_splits_network_failures_by_curl_exit_code(self): + frames = [{"filename": "/tmp/tmp.a/scripts/coding_discovery_tools/utils.py", + "function": "send_report_to_backend"}] + + def fingerprint_for(extra): + exception = {"type": "RuntimeError", "stacktrace": {"frames": frames}} + return utils_mod._grouping_fingerprint({"exception": {"values": [exception]}, "extra": extra}) + + extras = ({"curl_exit_code": 6}, {"curl_exit_code": 35}, {}) + dns, tls, no_exit_code = (fingerprint_for(extra) for extra in extras) + self.assertEqual(["RuntimeError", "utils.py:send_report_to_backend", "curl exit 6"], dns) + self.assertEqual(3, len({tuple(dns), tuple(tls), tuple(no_exit_code)})) + def test_glitchtip_copy_is_off_when_the_sentry_dsn_is_overridden(self): probe = "import scripts.coding_discovery_tools.utils as u; print(bool(u._GLITCHTIP_DSN))" base_env = {name: value for name, value in os.environ.items() if name != "AI_DISCOVERY_SENTRY_DSN"}