diff --git a/sentry_sdk/_agent_hint.py b/sentry_sdk/_agent_hint.py index 90c1c2e56a..19c5f2e0f1 100644 --- a/sentry_sdk/_agent_hint.py +++ b/sentry_sdk/_agent_hint.py @@ -1,11 +1,11 @@ import atexit import os +import subprocess import sys import time from typing import TYPE_CHECKING from sentry_sdk.utils import ( - _git, _is_external_source, capture_internal_exceptions, env_to_bool, @@ -13,13 +13,12 @@ if TYPE_CHECKING: from types import FrameType - from typing import List, Optional, Tuple + from typing import List, Tuple from sentry_sdk.client import BaseClient SETUP_CHECKLIST_PATH = os.path.join(os.path.dirname(__file__), "SETUP_CHECKLIST.md") -# Set by coding agents in the commands they run, for the agents that don't set AI_AGENT. CODING_AGENT_ENV_VARS = ( "CLAUDECODE", "CODEX_THREAD_ID", @@ -28,7 +27,6 @@ "GEMINI_CLI", ) -# How long after a change to the file that calls init() the setup counts as in progress. # Without git we can't tell whose change it is, so the window is shorter. SETUP_IN_PROGRESS_SECONDS = 60 * 60 SETUP_IN_PROGRESS_SECONDS_WITHOUT_GIT = 10 * 60 @@ -38,7 +36,7 @@ _exit_hook_registered = False # What _write_coding_agent_hint can print at exit: one entry for each file that called # init() with tracing or logs off. -_hints_at_exit: "List[Tuple[str, str, str, str, str]]" = [] +_hints_at_exit: "List[Tuple[str, bool, bool]]" = [] def _running_under_coding_agent() -> bool: @@ -54,31 +52,7 @@ def _running_under_coding_agent() -> bool: return any(os.environ.get(name) for name in CODING_AGENT_ENV_VARS) -_MISSING_PRODUCTS = { - (False, False): ( - "Sentry will get errors from this app but not the request trace around them, " - "and none of its logs.", - "Tracing and logs are off, so Sentry only gets errors.", - "they're", - "them", - ), - (False, True): ( - "Sentry will get errors from this app but not the request trace around them.", - "Tracing is off, so Sentry gets errors and logs but no traces.", - "it's", - "it", - ), - (True, False): ( - "Sentry will get errors from this app but none of its logs.", - "Logs are off, so Sentry gets errors and traces but no logs.", - "they're", - "them", - ), -} - - def _setup_in_progress(init_file: str) -> bool: - """Whether this user changed the file that calls init() a short time ago.""" now = time.time() cutoff = now - SETUP_IN_PROGRESS_SECONDS try: @@ -88,20 +62,31 @@ def _setup_in_progress(init_file: str) -> bool: if changed < cutoff: return False - def git(*args: str) -> "Optional[str]": - # Read only: don't take the index lock (the user or an agent may be running - # git at the same time) and don't run a configured fsmonitor command. - return _git( - "--no-optional-locks", - "-c", - "core.fsmonitor=false", - *args, - cwd=os.path.dirname(init_file), - timeout=GIT_TIMEOUT_SECONDS, - ) + cwd = os.path.dirname(init_file) # --branch adds a header line, so an empty answer means git has no answer. - status = git("status", "--porcelain", "--branch", "--", init_file) + try: + status = subprocess.run( + [ + "git", + "--no-optional-locks", + "-c", + "core.fsmonitor=false", + "status", + "--porcelain", + "--branch", + "--", + init_file, + ], + cwd=cwd, + stdin=subprocess.DEVNULL, + stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL, + encoding="utf-8", + timeout=GIT_TIMEOUT_SECONDS, + ).stdout.strip() + except (OSError, subprocess.TimeoutExpired): + status = "" if not status: return changed >= now - SETUP_IN_PROGRESS_SECONDS_WITHOUT_GIT if "\n" in status: @@ -109,10 +94,52 @@ def git(*args: str) -> "Optional[str]": # A checkout also gives a clean file a new mtime, so only count a commit # that was made here. - committer = git( - "log", "-1", f"--since={int(cutoff)}", "--format=%ce", "--", init_file - ) - return bool(committer) and committer == git("config", "user.email") + try: + committer = subprocess.run( + [ + "git", + "--no-optional-locks", + "-c", + "core.fsmonitor=false", + "log", + "-1", + f"--since={int(cutoff)}", + "--format=%ce", + "--", + init_file, + ], + cwd=cwd, + stdin=subprocess.DEVNULL, + stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL, + encoding="utf-8", + timeout=GIT_TIMEOUT_SECONDS, + ).stdout.strip() + except (OSError, subprocess.TimeoutExpired): + return False + if not committer: + return False + + try: + user_email = subprocess.run( + [ + "git", + "--no-optional-locks", + "-c", + "core.fsmonitor=false", + "config", + "user.email", + ], + cwd=cwd, + stdin=subprocess.DEVNULL, + stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL, + encoding="utf-8", + timeout=GIT_TIMEOUT_SECONDS, + ).stdout.strip() + except (OSError, subprocess.TimeoutExpired): + return False + return committer == user_email def _logs_on(client: "BaseClient") -> bool: @@ -136,7 +163,7 @@ def register_coding_agent_hint_exit_hook() -> None: def _write_coding_agent_hint() -> None: with capture_internal_exceptions(): # One hint, for the first init() from a file that this user changed. - for init_file, not_shown, off, its, it in _hints_at_exit: + for init_file, tracing_on, logs_on in _hints_at_exit: if _setup_in_progress(init_file): break else: @@ -145,18 +172,51 @@ def _write_coding_agent_hint() -> None: codex = "codex" in (os.environ.get("AI_AGENT") or "").lower() or any( os.environ.get(name) for name in ("CODEX_THREAD_ID", "CODEX_SANDBOX") ) - if codex: + if codex and tracing_on: + hint = ( + "Logs are off, so Sentry gets errors and traces but no logs. If you " + "leave them off, tell the user they're off and that you can turn them " + "on if they want. Sentry's official setup checklist, included in the " + f"sentry-sdk package you installed: {SETUP_CHECKLIST_PATH}" + ) + elif codex and logs_on: + hint = ( + "Tracing is off, so Sentry gets errors and logs but no traces. If you " + "leave it off, tell the user it's off and that you can turn it on if " + "they want. Sentry's official setup checklist, included in the " + f"sentry-sdk package you installed: {SETUP_CHECKLIST_PATH}" + ) + elif codex: + hint = ( + "Tracing and logs are off, so Sentry only gets errors. If you leave " + "them off, tell the user they're off and that you can turn them on if " + "they want. Sentry's official setup checklist, included in the " + f"sentry-sdk package you installed: {SETUP_CHECKLIST_PATH}" + ) + elif tracing_on: + hint = ( + "Sentry will get errors from this app but none of its logs. The " + "checklist shows what to change. If you're setting " + "up Sentry, it is strongly recommended to check your setup against " + "Sentry's official setup checklist, included in the sentry-sdk " + f"package you installed: {SETUP_CHECKLIST_PATH}" + ) + elif logs_on: hint = ( - f"{off} If you leave {it} off, tell the user {its} off and that you can " - f"turn {it} on if they want. Sentry's official setup checklist, included " - f"in the sentry-sdk package you installed: {SETUP_CHECKLIST_PATH}" + "Sentry will get errors from this app but not the request trace " + "around them. The checklist shows what to change. If you're setting " + "up Sentry, it is strongly recommended to check your setup against " + "Sentry's official setup checklist, included in the sentry-sdk " + f"package you installed: {SETUP_CHECKLIST_PATH}" ) else: hint = ( - f"{not_shown} The checklist shows what to change. If you're setting up " - "Sentry, it is strongly recommended to check your setup against Sentry's " - "official setup checklist, included in the sentry-sdk package you " - f"installed: {SETUP_CHECKLIST_PATH}" + "Sentry will get errors from this app but not the request trace " + "around them, and none of its logs. The checklist shows " + "what to change. If you're setting up Sentry, it is strongly " + "recommended to check your setup against Sentry's official setup " + "checklist, included in the sentry-sdk package you installed: " + f"{SETUP_CHECKLIST_PATH}" ) sys.stdout.flush() sys.stderr.write(f"[sentry] {hint} (hide with SENTRY_AGENT_HINTS=0)\n") @@ -164,14 +224,13 @@ def _write_coding_agent_hint() -> None: def show_coding_agent_hint(client: "BaseClient", caller: "FrameType") -> None: - """Point a coding agent at the setup checklist while Sentry is being set up.""" options = client.options rate = options["traces_sample_rate"] tracing_on = options["traces_sampler"] is not None or rate not in (0, None) logs_on = _logs_on(client) if ( not _exit_hook_registered - # Only tested on macOS and Linux. + or sys.version_info < (3, 9) or sys.platform not in ("darwin", "linux") or not options["dsn"] or options["_experiments"].get("agent_setup_complete") @@ -179,11 +238,9 @@ def show_coding_agent_hint(client: "BaseClient", caller: "FrameType") -> None: ): return - # A script's own path is relative on Python 3.8 and older. - init_file = os.path.abspath(caller.f_code.co_filename) - # An installed tool that uses Sentry itself isn't the user's app. + init_file = caller.f_code.co_filename if _is_external_source(init_file): return - # Agents often cut a command's output with `| tail`, so the hint goes last, at exit. + # Agents often cut a command's output with `| tail`, so the hint goes last. if all(init_file != seen[0] for seen in _hints_at_exit): - _hints_at_exit.append((init_file, *_MISSING_PRODUCTS[(tracing_on, logs_on)])) + _hints_at_exit.append((init_file, tracing_on, logs_on)) diff --git a/sentry_sdk/utils.py b/sentry_sdk/utils.py index 1c3a1d9db6..da15448028 100644 --- a/sentry_sdk/utils.py +++ b/sentry_sdk/utils.py @@ -126,9 +126,7 @@ def json_dumps(data: "Any") -> bytes: return json.dumps(data, allow_nan=False, separators=(",", ":")).encode("utf-8") -def _git( - *args: str, cwd: "Optional[str]" = None, timeout: "Optional[float]" = None -) -> "Optional[str]": +def get_git_revision() -> "Optional[str]": try: with open(os.path.devnull, "w+") as null: # prevent command prompt windows from popping up on windows @@ -137,31 +135,22 @@ def _git( startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW - with subprocess.Popen( - ["git", *args], - cwd=cwd, - startupinfo=startupinfo, - stdout=subprocess.PIPE, - stderr=null, - stdin=null, - ) as process: - try: - output = ( - process.communicate(timeout=timeout)[0].strip().decode("utf-8") - ) - except subprocess.TimeoutExpired: - # Don't read the rest of the output: a child process of git can - # keep the pipe open after git is killed. - process.kill() - return None + revision = ( + subprocess.Popen( + ["git", "rev-parse", "HEAD"], + startupinfo=startupinfo, + stdout=subprocess.PIPE, + stderr=null, + stdin=null, + ) + .communicate()[0] + .strip() + .decode("utf-8") + ) except (OSError, IOError, FileNotFoundError): return None - return output - - -def get_git_revision() -> "Optional[str]": - return _git("rev-parse", "HEAD") + return revision def get_default_release() -> "Optional[str]": diff --git a/tests/test_agent_hint.py b/tests/test_agent_hint.py index df94fc3796..fd4ed8548e 100644 --- a/tests/test_agent_hint.py +++ b/tests/test_agent_hint.py @@ -16,7 +16,6 @@ @pytest.fixture def run_app(tmp_path, monkeypatch, capsys): - """Run a script that calls sentry_sdk.init() and return what the SDK prints at exit.""" for name in ("CI", "SENTRY_AGENT_HINTS", "AI_AGENT", *CODING_AGENT_ENV_VARS): monkeypatch.delenv(name, raising=False) monkeypatch.setattr(sentry_sdk._agent_hint, "_hints_at_exit", []) @@ -25,17 +24,10 @@ def run_app(tmp_path, monkeypatch, capsys): monkeypatch.setattr(sentry_sdk._agent_hint.atexit, "register", at_exit.append) app = tmp_path / "app.py" - def run( - env, - init_args="", - before_run=None, - inits=1, - dsn=AGENT_HINT_DSN, - filename=None, - ): + def run(env, init_args="", before_run=None, inits=1): for name, value in env.items(): monkeypatch.setenv(name, value) - init = f"sentry_sdk.init(dsn={dsn!r}, {init_args})\n" + init = f"sentry_sdk.init(dsn={AGENT_HINT_DSN!r}, {init_args})\n" imports = ( "import sentry_sdk\n" "from sentry_sdk.integrations.logging import LoggingIntegration\n" @@ -45,7 +37,7 @@ def run( before_run(app) try: - exec(compile(app.read_text(), filename or str(app), "exec"), {}) + exec(compile(app.read_text(), str(app), "exec"), {}) for hook in at_exit: hook() finally: @@ -55,6 +47,9 @@ def run( return run +@pytest.mark.skipif( + sys.version_info < (3, 9), reason="Python < 3.9 hits an early return" +) @pytest.mark.parametrize( "env, init_args", [ @@ -69,40 +64,18 @@ def test_coding_agent_hint(run_app, env, init_args): assert SETUP_CHECKLIST_PATH in run_app(env, init_args) -@pytest.mark.parametrize( - "env, init_args", - [ - ({}, "traces_sample_rate=0"), - ( - {"AI_AGENT": "claude-code"}, - "traces_sample_rate=0.1, integrations=[LoggingIntegration()]", - ), - ( - {"AI_AGENT": "claude-code"}, - "traces_sampler=lambda _: 1.0, integrations=[LoggingIntegration()]", - ), - ({"AI_AGENT": "claude-code"}, "_experiments={'agent_setup_complete': True}"), - ({"AI_AGENT": "0"}, "traces_sample_rate=0"), - ({"AI_AGENT": "claude-code", "CI": "true"}, "traces_sample_rate=0"), - ({"CLAUDECODE": "1", "SENTRY_AGENT_HINTS": "0"}, "traces_sample_rate=0"), - ], +@pytest.mark.skipif( + sys.version_info < (3, 9), reason="Python < 3.9 hits an early return" ) -def test_coding_agent_hint_not_shown(run_app, env, init_args): - assert "[sentry]" not in run_app(env, init_args) - - def test_coding_agent_hint_shown_when_ci_is_set_to_false(run_app): env = {"AI_AGENT": "claude-code", "CI": "false"} assert SETUP_CHECKLIST_PATH in run_app(env, "traces_sample_rate=0") -def test_coding_agent_hint_not_shown_without_dsn(run_app): - env = {"AI_AGENT": "claude-code", "SENTRY_DSN": ""} - - assert "[sentry]" not in run_app(env, "traces_sample_rate=0", dsn=None) - - +@pytest.mark.skipif( + sys.version_info < (3, 9), reason="Python < 3.9 hits an early return" +) @pytest.mark.parametrize( "env, init_args, hint", [ @@ -145,6 +118,9 @@ def test_coding_agent_hint_per_agent(run_app, env, init_args, hint): assert SETUP_CHECKLIST_PATH in printed +@pytest.mark.skipif( + sys.version_info < (3, 9), reason="Python < 3.9 hits an early return" +) def test_coding_agent_hint_when_the_logging_integration_sends_no_logs(run_app): printed = run_app( {"CLAUDECODE": "1"}, @@ -154,113 +130,75 @@ def test_coding_agent_hint_when_the_logging_integration_sends_no_logs(run_app): assert "but none of its logs." in printed -def test_coding_agent_hint_not_shown_for_an_installed_tool(run_app, tmp_path): - tool = tmp_path / "site-packages" / "sometool" / "cli.py" - tool.parent.mkdir(parents=True) - tool.write_text("") - - assert run_app({"AI_AGENT": "claude-code"}, filename=str(tool)) == "" - - +@pytest.mark.skipif( + sys.version_info < (3, 9), reason="Python < 3.9 hits an early return" +) def test_coding_agent_hint_shown_once(run_app): printed = run_app({"AI_AGENT": "claude-code"}, "traces_sample_rate=0", inits=2) assert printed.count(SETUP_CHECKLIST_PATH) == 1 -def _git(app, *args, committer="dev@example.com", date=None): +def _commit(app, date=None): env = { **os.environ, "GIT_CONFIG_GLOBAL": os.devnull, "GIT_CONFIG_SYSTEM": os.devnull, "GIT_AUTHOR_NAME": "Dev", - "GIT_AUTHOR_EMAIL": committer, + "GIT_AUTHOR_EMAIL": "dev@example.com", "GIT_COMMITTER_NAME": "Dev", - "GIT_COMMITTER_EMAIL": committer, + "GIT_COMMITTER_EMAIL": "dev@example.com", } if date: env["GIT_AUTHOR_DATE"] = env["GIT_COMMITTER_DATE"] = date - subprocess.run( - ["git", *args], - cwd=str(app.parent), - env=env, - check=True, - stdout=subprocess.PIPE, - stderr=subprocess.PIPE, - ) - - -def _commit(app, **kwargs): - _git(app, "init", "-q") - _git(app, "config", "user.email", "dev@example.com") - _git(app, "add", app.name) - _git(app, "commit", "-q", "-m", "Set up Sentry", **kwargs) - - -def _changed_minutes_ago(app, minutes): - changed = time.time() - minutes * 60 - os.utime(app, (changed, changed)) + for args in ( + ["init", "-q"], + ["config", "user.email", "dev@example.com"], + ["add", app.name], + ["commit", "-q", "-m", "Set up Sentry"], + ): + subprocess.run( + ["git", *args], + cwd=str(app.parent), + env=env, + check=True, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + ) def _committed_and_edited(app, minutes_ago=0): _commit(app, date="2020-01-01T00:00:00") app.write_text(app.read_text() + "\n") - _changed_minutes_ago(app, minutes_ago) - - -@pytest.mark.skipif(shutil.which("git") is None, reason="needs git") -def test_coding_agent_hint_with_a_relative_script_path(run_app, tmp_path, monkeypatch): - # Only git can tell that a change from 20 minutes ago is this user's. - monkeypatch.chdir(tmp_path) - printed = run_app( - {"AI_AGENT": "claude-code"}, - before_run=lambda app: _committed_and_edited(app, minutes_ago=20), - filename="app.py", - ) - - assert SETUP_CHECKLIST_PATH in printed + changed = time.time() - minutes_ago * 60 + os.utime(app, (changed, changed)) +@pytest.mark.skipif( + sys.version_info < (3, 9), reason="Python < 3.9 hits an early return" +) @pytest.mark.skipif(shutil.which("git") is None, reason="needs git") @pytest.mark.parametrize( - "before_run, shown", + "before_run", [ - pytest.param(None, True, id="new file, no git repo"), - pytest.param( - lambda app: _changed_minutes_ago(app, 20), - False, - id="no git repo, changed 20 minutes ago", - ), - pytest.param(_committed_and_edited, True, id="uncommitted change"), + pytest.param(None, id="new file, no git repo"), + pytest.param(_committed_and_edited, id="uncommitted change"), pytest.param( lambda app: _committed_and_edited(app, minutes_ago=20), - True, id="uncommitted change, 20 minutes ago", ), - pytest.param( - lambda app: _committed_and_edited(app, minutes_ago=120), - False, - id="uncommitted change, two hours ago", - ), - pytest.param(_commit, True, id="committed here a moment ago"), - pytest.param( - lambda app: _commit(app, committer="teammate@example.com"), - False, - id="a teammate's new commit", - ), - pytest.param( - lambda app: _commit(app, date="2020-01-01T00:00:00"), - False, - id="fresh checkout of an old commit", - ), + pytest.param(_commit, id="committed here a moment ago"), ], ) -def test_coding_agent_hint_only_during_setup(run_app, before_run, shown): +def test_coding_agent_hint_during_setup(run_app, before_run): printed = run_app({"AI_AGENT": "claude-code"}, before_run=before_run) - assert (SETUP_CHECKLIST_PATH in printed) is shown + assert SETUP_CHECKLIST_PATH in printed +@pytest.mark.skipif( + sys.version_info < (3, 9), reason="Python < 3.9 hits an early return" +) def test_coding_agent_hint_when_git_does_not_answer_in_time(run_app, monkeypatch): real_communicate = subprocess.Popen.communicate @@ -293,6 +231,9 @@ def client(*args, **kwargs): assert registered_first == [True] +@pytest.mark.skipif( + sys.version_info < (3, 9), reason="Python < 3.9 hits an early return" +) def test_coding_agent_hint_for_a_later_init_from_a_changed_file(run_app, tmp_path): # Changed in the last hour, but not in the last 10 minutes, and there is no git # here to say whose change it is.