From 5e557779233ab2cd692d81ebc105fe2724a48dd9 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:08:41 +0000 Subject: [PATCH 1/5] feat: Point coding agents to a setup checklist Port of getsentry/sentry-python#8269. When a coding agent sets up Sentry and leaves tracing or logs off, print one line that points to a setup checklist shipped in the gem. `rails g sentry` points to it right away, and `rails server` logs it once the app loads. Co-Authored-By: Johannes Daxboeck <114897+dingsdax@users.noreply.github.com> --- .../lib/generators/sentry_generator.rb | 9 + sentry-rails/lib/sentry/rails/railtie.rb | 10 + sentry-rails/spec/sentry/generator_spec.rb | 12 ++ sentry-rails/spec/sentry/rails_spec.rb | 7 + sentry-ruby/lib/sentry-ruby.rb | 2 + sentry-ruby/lib/sentry/SETUP_CHECKLIST.md | 42 +++++ sentry-ruby/lib/sentry/agent_hint.rb | 119 ++++++++++++ sentry-ruby/lib/sentry/configuration.rb | 7 + sentry-ruby/spec/sentry/agent_hint_spec.rb | 178 ++++++++++++++++++ sentry-ruby/spec/spec_helper.rb | 3 + 10 files changed, 389 insertions(+) create mode 100644 sentry-ruby/lib/sentry/SETUP_CHECKLIST.md create mode 100644 sentry-ruby/lib/sentry/agent_hint.rb create mode 100644 sentry-ruby/spec/sentry/agent_hint_spec.rb diff --git a/sentry-rails/lib/generators/sentry_generator.rb b/sentry-rails/lib/generators/sentry_generator.rb index ae6be1d7c..b00824db8 100644 --- a/sentry-rails/lib/generators/sentry_generator.rb +++ b/sentry-rails/lib/generators/sentry_generator.rb @@ -28,4 +28,13 @@ def inject_code_into_layout " <%= Sentry.get_trace_propagation_meta.html_safe %>\n " end end + + # The generator only runs while Sentry is being set up, so a coding agent running + # it gets pointed at the checklist right away. + def point_coding_agent_to_checklist + return unless Sentry::AgentHint.coding_agent? + + say_status :checklist, "Check the setup against Sentry's official setup checklist before you finish: " \ + "#{Sentry::AgentHint::CHECKLIST_PATH}", :yellow + end end diff --git a/sentry-rails/lib/sentry/rails/railtie.rb b/sentry-rails/lib/sentry/rails/railtie.rb index c6798904f..dd52b7d3c 100644 --- a/sentry-rails/lib/sentry/rails/railtie.rb +++ b/sentry-rails/lib/sentry/rails/railtie.rb @@ -71,6 +71,16 @@ class Railtie < ::Rails::Railtie end end + # `rails server` runs until it's stopped, so the agent hint that Sentry.init would + # print at exit goes to the Rails logger once the app is loaded. In development the + # server logs to the console. Server blocks exist since Rails 6.1. + if respond_to?(:server) + server do + hint = Sentry::AgentHint.take + ::Rails.logger.warn(hint) if hint + end + end + runner do next unless Sentry.initialized? Sentry.configuration.background_worker_threads = 0 diff --git a/sentry-rails/spec/sentry/generator_spec.rb b/sentry-rails/spec/sentry/generator_spec.rb index 5f5c77b52..8d9cefc9a 100644 --- a/sentry-rails/spec/sentry/generator_spec.rb +++ b/sentry-rails/spec/sentry/generator_spec.rb @@ -76,6 +76,18 @@ expect(content).not_to include("Sentry.get_trace_propagation_meta.html_safe") end + it "points a coding agent at the setup checklist" do + allow(Sentry::AgentHint).to receive(:coding_agent?).and_return(true) + + expect(run_generator).to include(Sentry::AgentHint::CHECKLIST_PATH) + end + + it "doesn't mention the checklist to people" do + allow(Sentry::AgentHint).to receive(:coding_agent?).and_return(false) + + expect(run_generator).not_to include(Sentry::AgentHint::CHECKLIST_PATH) + end + context "with a DSN option" do it "creates a initializer file with the DSN" do run_generator %w[--dsn foobarbaz] diff --git a/sentry-rails/spec/sentry/rails_spec.rb b/sentry-rails/spec/sentry/rails_spec.rb index b93435cdd..941db3690 100644 --- a/sentry-rails/spec/sentry/rails_spec.rb +++ b/sentry-rails/spec/sentry/rails_spec.rb @@ -41,6 +41,13 @@ expect(Sentry.configuration.background_worker_threads).to eq(0) end + it "logs the coding agent hint when the server loads", skip: !Rails::Railtie.respond_to?(:server) && "needs Rails 6.1+" do + allow(Sentry::AgentHint).to receive(:take).and_return("[sentry] hint") + expect(Rails.logger).to receive(:warn).with("[sentry] hint") + + Rails.application.load_server + end + describe "logger detection" do it "sets a duplicated Rails logger as the SDK's logger" do if Gem::Version.new(Rails.version) > Gem::Version.new("7.1.0.beta") diff --git a/sentry-ruby/lib/sentry-ruby.rb b/sentry-ruby/lib/sentry-ruby.rb index 0532e622d..d54022389 100644 --- a/sentry-ruby/lib/sentry-ruby.rb +++ b/sentry-ruby/lib/sentry-ruby.rb @@ -33,6 +33,7 @@ require "sentry/vernier/profiler" require "sentry/metrics" require "sentry/job_extensions/extension" +require "sentry/agent_hint" [ "sentry/rake", @@ -294,6 +295,7 @@ def init(&block) @backpressure_monitor = config.enable_backpressure_handling ? Sentry::BackpressureMonitor.new(config, client) : nil exception_locals_tp.enable if config.data_collection.collect_stack_frame_variables? at_exit { close } + AgentHint.register(config, caller_locations(1, 1).first) end # Flushes pending events and cleans up SDK state. diff --git a/sentry-ruby/lib/sentry/SETUP_CHECKLIST.md b/sentry-ruby/lib/sentry/SETUP_CHECKLIST.md new file mode 100644 index 000000000..00be05960 --- /dev/null +++ b/sentry-ruby/lib/sentry/SETUP_CHECKLIST.md @@ -0,0 +1,42 @@ +# Sentry Ruby SDK: setup checklist + +This is Sentry's official setup guidance, shipped in the `sentry-ruby` gem and maintained by Sentry with the SDK. It matches the agent setup guide at https://docs.sentry.io/ai/agent-setup/get-started.md. + +## Required + +- **Errors.** This is Sentry's core product. Set it up unless the user asked you not to. It needs a DSN: if the user hasn't given you one and you can't get one yourself, ask for it. Read it from an environment variable (`SENTRY_DSN`) and don't commit it. In a Rails app, add `sentry-ruby` and `sentry-rails` to the Gemfile and put `Sentry.init` in `config/initializers/sentry.rb`. Before you finish, send a test error and check that it arrives. + +## Recommended + +Turn these on unless the user asked you not to. Sentry links errors, traces and logs, so an error shows the request that caused it and the logs around it. + +- **Tracing.** Shows which request caused an error and where the time went. Set `config.traces_sample_rate` by environment: `1.0` locally, so you can see a trace when you verify, and a low rate in production (`0.1` is a common start) unless the project already has one. Don't default it to `0`: a rate of `0` sends no traces at all. +- **Logs.** Add `config.enabled_patches << :logger`. The app's logs, including `Rails.logger`, show up next to the errors they belong to. In Rails, also set `config.rails.structured_logging.enabled = true` to send Active Record and Action Controller events as logs. `Sentry.logger.info(...)` sends a log directly. +- **Environment and release.** Set `config.environment` so production issues are separate from local ones. The SDK reads the release from `SENTRY_RELEASE` or the git commit. If the app runs without `.git` (for example in a Docker image), set `SENTRY_RELEASE` at build time or set `config.release` to the app's version, so you can see which deploy caused an issue. + +To tell production from local runs, use a check the app already has, such as `Rails.env.production?`. Don't add a new variable that nothing sets. + +```ruby +Sentry.init do |config| + config.dsn = ENV["SENTRY_DSN"] + config.environment = Rails.env + config.traces_sample_rate = Rails.env.production? ? 0.1 : 1.0 + config.enabled_patches << :logger + config.rails.structured_logging.enabled = true +end +``` + +## Situational + +Do the Required and Recommended items first. Then look at the ones below. Set them up only when the project matches. + +- **Crons**, if the app schedules jobs with sidekiq-cron, sidekiq-scheduler, GoodJob cron, Solid Queue recurring tasks or rufus-scheduler. Sentry alerts when a job fails or doesn't run, and every scheduled job gets a monitor, including ones added later. Add the matching patch: `config.enabled_patches += [:sidekiq_cron]`, `:sidekiq_scheduler`, `:good_job_cron`, `:solid_queue_recurring` or `:rufus_scheduler`. +- **Background jobs**, if the app uses Sidekiq, Resque or Delayed Job. Add `sentry-sidekiq`, `sentry-resque` or `sentry-delayed_job` to the Gemfile, so job errors and traces are captured and linked to the request that queued them. +- **Profiling**, if the user cares about the performance of specific code paths. Add the `stackprof` gem and set `config.profiles_sample_rate`. It is relative to `traces_sample_rate`. +- **Metrics**, if the user wants to track counts or values over time (signups, queue depth). Call `Sentry.metrics.count(...)`, `gauge(...)` or `distribution(...)` where they happen. + +## Before you finish + +Tell the user what you set up, the trace sample rate you chose for each environment, whether logs are on, and which situational items you included and why. + +Then set `config.agent_setup_complete = true` in `Sentry.init`. That tells the SDK the setup has been checked, so it stops pointing coding agents to this file. diff --git a/sentry-ruby/lib/sentry/agent_hint.rb b/sentry-ruby/lib/sentry/agent_hint.rb new file mode 100644 index 000000000..7e2469ce1 --- /dev/null +++ b/sentry-ruby/lib/sentry/agent_hint.rb @@ -0,0 +1,119 @@ +# frozen_string_literal: true + +module Sentry + # Points a coding agent at SETUP_CHECKLIST.md while it sets up Sentry and + # leaves tracing or logs off. People running the app never see it. + # @!visibility private + class AgentHint + CHECKLIST_PATH = File.expand_path("SETUP_CHECKLIST.md", __dir__) + + # AI_AGENT is the cross-tool convention; the rest cover agents that don't set it. + AGENT_ENV_VARS = %w[CLAUDECODE CODEX_THREAD_ID CODEX_SANDBOX CURSOR_AGENT GEMINI_CLI].freeze + + # How long after the last change to the file that calls Sentry.init the setup + # counts as in progress. Without git we can't tell whose change it is, so it's shorter. + SETUP_WINDOW = 60 * 60 + SETUP_WINDOW_WITHOUT_GIT = 10 * 60 + + # Say what Sentry won't show, not which settings are off. An agent that sees + # the setting names doesn't open the checklist. + NOT_SHOWN = { tracing: "the request trace around them", logs: "its logs" }.freeze + + class << self + # Called by Sentry.init with the location that called it. The hint prints at + # exit, unless an integration takes it earlier. + def register(config, caller_location) + init_file = caller_location&.absolute_path || caller_location&.path + return unless @hint.nil? && init_file && coding_agent? + + hint = new(config, init_file) + return unless hint.applies? + + @hint = hint + pid = Process.pid + + at_exit do + # Forked workers inherit at_exit blocks, so only the process that called init prints. + next unless Process.pid == pid && (message = take) + + # Piped stdout is only flushed at exit. Flush it first so the hint stays + # last for agents that cut the output with `| tail`. + $stdout.flush + warn(message) + end + rescue StandardError + # Best effort: the hint must never break Sentry.init. + nil + end + + # Returns the hint once, or nil when there's nothing to show. + def take + hint = @hint + @hint = false + hint.message if hint + end + + def coding_agent? + return false if ENV["CI"] + return false unless Utils::EnvHelper.env_to_bool(ENV.fetch("SENTRY_AGENT_HINTS", "1")) + return Utils::EnvHelper.env_to_bool(ENV["AI_AGENT"]) if ENV.key?("AI_AGENT") + + AGENT_ENV_VARS.any? { |name| ENV.key?(name) } + end + end + + def initialize(config, init_file) + @config = config + @init_file = File.expand_path(init_file) + end + + def applies? + @config.dsn && !@config.agent_setup_complete && missing.any? && changed_within?(SETUP_WINDOW) + end + + def message + return unless setup_in_progress? + + "[sentry] Sentry will get errors from this app but not #{missing.map { |product| NOT_SHOWN[product] }.join(", or ")}. " \ + "If you're setting up Sentry, check the setup against Sentry's official setup checklist. If you leave " \ + "it as is, tell the user. The checklist is included in the sentry-ruby gem you installed: " \ + "#{CHECKLIST_PATH} (hide with SENTRY_AGENT_HINTS=0)" + end + + private + + def missing + @missing ||= [].tap do |products| + products << :tracing unless @config.traces_sampler || @config.traces_sample_rate.to_f.positive? + # Rails.logger is a ::Logger too, so the :logger patch covers Rails apps. + products << :logs unless @config.enabled_patches.include?(:logger) + end + end + + def changed_within?(seconds) + Time.now - File.mtime(@init_file) <= seconds + rescue SystemCallError + false + end + + # Whether this user changed the file a short time ago. A checkout or a + # teammate's commit also gives the file a new mtime, so ask git. + def setup_in_progress? + status = git("status", "--porcelain", "--", @init_file) + return changed_within?(SETUP_WINDOW_WITHOUT_GIT) if status.nil? + return true unless status.empty? + + committer = git("log", "-1", "--since=#{SETUP_WINDOW} seconds ago", "--format=%ce", "--", @init_file) + !committer.to_s.empty? && committer == git("config", "user.email") + end + + # Returns nil when git isn't installed or the file isn't in a repo. Read only: + # no index lock, since the agent may be running git at the same time. + def git(*args) + output = IO.popen(["git", "--no-optional-locks", *args], chdir: File.dirname(@init_file), err: File::NULL, &:read) + output.strip if $CHILD_STATUS.success? + rescue SystemCallError + nil + end + end +end diff --git a/sentry-ruby/lib/sentry/configuration.rb b/sentry-ruby/lib/sentry/configuration.rb index b640676ac..30b725f4b 100644 --- a/sentry-ruby/lib/sentry/configuration.rb +++ b/sentry-ruby/lib/sentry/configuration.rb @@ -297,6 +297,12 @@ def include_local_variables=(value) # @return [StructuredLoggingConfiguration] attr_reader :structured_logging + # Set to true once the setup has been checked against SETUP_CHECKLIST.md in this gem. + # Coding agents running the app are then no longer pointed at the checklist. + # Default is false. + # @return [Boolean] + attr_accessor :agent_setup_complete + # Send diagnostic client reports about dropped events, true by default # tries to attach to an existing envelope max once every 30s # @return [Boolean] @@ -592,6 +598,7 @@ def initialize self.std_lib_logger_filter = nil self.rack_env_whitelist = RACK_ENV_WHITELIST_DEFAULT self.traces_sampler = nil + self.agent_setup_complete = false self.profiler_class = Sentry::Profiler self.profiles_sample_interval = DEFAULT_PROFILES_SAMPLE_INTERVAL diff --git a/sentry-ruby/spec/sentry/agent_hint_spec.rb b/sentry-ruby/spec/sentry/agent_hint_spec.rb new file mode 100644 index 000000000..6b6337d36 --- /dev/null +++ b/sentry-ruby/spec/sentry/agent_hint_spec.rb @@ -0,0 +1,178 @@ +# frozen_string_literal: true + +require "spec_helper" +require "open3" +require "stringio" +require "tmpdir" + +RSpec.describe Sentry::AgentHint do + let(:checklist) { described_class::CHECKLIST_PATH } + let(:app) { File.join(@dir, "app.rb") } + let(:at_exit_hooks) { [] } + + around do |example| + names = ["CI", "SENTRY_AGENT_HINTS", "AI_AGENT", *described_class::AGENT_ENV_VARS] + saved = ENV.to_h.slice(*names) + names.each { |name| ENV.delete(name) } + + Dir.mktmpdir do |dir| + @dir = dir + example.run + end + ensure + names.each { |name| ENV.delete(name) } + ENV.update(saved) + end + + before do + described_class.instance_variable_set(:@hint, nil) + allow(described_class).to receive(:at_exit) { |&hook| at_exit_hooks << hook } + end + + # Loads a file that calls Sentry.init, the way an app's initializer does. + def load_app(env, config = "", before_load: nil, path: app) + ENV.update(env) + File.write(path, <<~RUBY) + Sentry.init do |config| + config.sdk_logger = ::Logger.new(nil) + config.dsn = #{Sentry::TestHelper::DUMMY_DSN.inspect} + config.transport.transport_class = Sentry::DummyTransport + #{config} + end + RUBY + before_load&.call(path) + load(path) + end + + # Loads the app and returns what the SDK prints at exit. + def run_app(...) + load_app(...) + capture_stderr { at_exit_hooks.each(&:call) } + end + + def capture_stderr + original, $stderr = $stderr, StringIO.new + yield + $stderr.string + ensure + $stderr = original + end + + describe "who sees it" do + { + { "AI_AGENT" => "claude-code" } => true, + { "CLAUDECODE" => "1" } => true, + { "CODEX_THREAD_ID" => "abc" } => true, + { "CURSOR_AGENT" => "1" } => true, + {} => false, + { "AI_AGENT" => "0" } => false, + { "AI_AGENT" => "claude-code", "CI" => "true" } => false, + { "CLAUDECODE" => "1", "SENTRY_AGENT_HINTS" => "0" } => false + }.each do |env, shown| + it "is #{"not " unless shown}shown for #{env}" do + expect(run_app(env).include?(checklist)).to be(shown) + end + end + end + + describe "what it says" do + { + "" => "not the request trace around them, or its logs.", + "config.enabled_patches << :logger" => "not the request trace around them.", + "config.traces_sample_rate = 0.1" => "not its logs.", + "config.traces_sampler = ->(_) { 1.0 }" => "not its logs.", + "config.traces_sample_rate = 0.0" => "not the request trace around them, or its logs." + }.each do |config, missing| + it "says what's missing with #{config.inspect}" do + expect(run_app({ "AI_AGENT" => "claude-code" }, config)) + .to start_with("[sentry] Sentry will get errors from this app but #{missing}") + .and include(checklist) + end + end + end + + [ + "config.traces_sample_rate = 0.1; config.enabled_patches << :logger", + "config.agent_setup_complete = true", + "config.dsn = nil" + ].each do |config| + it "is not shown with #{config.inspect}" do + expect(run_app({ "AI_AGENT" => "claude-code" }, config)).to eq("") + end + end + + it "is shown once" do + load_app({ "AI_AGENT" => "claude-code" }) + + expect(run_app({})).to include(checklist) + expect(at_exit_hooks.size).to eq(1) + end + + it "isn't printed at exit when an integration took it" do + load_app({ "AI_AGENT" => "claude-code" }) + + expect(described_class.take).to include(checklist) + expect(described_class.take).to be_nil + expect(capture_stderr { at_exit_hooks.each(&:call) }).to eq("") + end + + it "isn't printed by a forked child" do + load_app({ "AI_AGENT" => "claude-code" }) + allow(Process).to receive(:pid).and_return(Process.pid + 1) + + expect(capture_stderr { at_exit_hooks.each(&:call) }).to eq("") + end + + describe "only while Sentry is being set up" do + before { skip("needs git") unless system("git", "--version", out: File::NULL) } + + def git(path, *args, committer: "dev@example.com", date: nil) + env = { + "GIT_CONFIG_GLOBAL" => File::NULL, "GIT_CONFIG_NOSYSTEM" => "1", + "GIT_COMMITTER_NAME" => "Dev", "GIT_COMMITTER_EMAIL" => committer, + "GIT_AUTHOR_NAME" => "Dev", "GIT_AUTHOR_EMAIL" => committer + } + env["GIT_AUTHOR_DATE"] = env["GIT_COMMITTER_DATE"] = date if date + _, status = Open3.capture2e(env, "git", *args, chdir: File.dirname(path)) + raise "git #{args.join(" ")} failed" unless status.success? + end + + def commit(path, **options) + git(path, "init", "-q") + git(path, "config", "user.email", "dev@example.com") + git(path, "add", File.basename(path)) + git(path, "commit", "-q", "-m", "Set up Sentry", **options) + end + + def touch(path, minutes_ago) + File.utime(Time.now - minutes_ago * 60, Time.now - minutes_ago * 60, path) + end + + def edit_old_commit(path, minutes_ago: 0) + commit(path, date: "2020-01-01T00:00:00") + File.write(path, "#{File.read(path)}\n") + touch(path, minutes_ago) + end + + { + "new file, no git repo" => [nil, true], + "no git repo, changed 20 minutes ago" => [->(path) { touch(path, 20) }, false], + "uncommitted change" => [->(path) { edit_old_commit(path) }, true], + "uncommitted change, 20 minutes ago" => [->(path) { edit_old_commit(path, minutes_ago: 20) }, true], + "uncommitted change, two hours ago" => [->(path) { edit_old_commit(path, minutes_ago: 120) }, false], + "committed here a moment ago" => [->(path) { commit(path) }, true], + "a teammate's new commit" => [->(path) { commit(path, committer: "teammate@example.com") }, false], + "fresh checkout of an old commit" => [->(path) { commit(path, date: "2020-01-01T00:00:00") }, false] + }.each do |name, (setup, shown)| + it "is #{"not " unless shown}shown for: #{name}" do + before_load = setup && ->(path) { instance_exec(path, &setup) } + + expect(run_app({ "AI_AGENT" => "claude-code" }, before_load: before_load).include?(checklist)).to be(shown) + end + end + end + + it "ships the setup checklist with the gem" do + expect(File.read(checklist)).to include("config.agent_setup_complete = true") + end +end diff --git a/sentry-ruby/spec/spec_helper.rb b/sentry-ruby/spec/spec_helper.rb index 20e055928..2c937663f 100644 --- a/sentry-ruby/spec/spec_helper.rb +++ b/sentry-ruby/spec/spec_helper.rb @@ -23,6 +23,9 @@ REDIS_HOST = ENV.fetch("REDIS_HOST", "127.0.0.1") +# The suite may itself run under a coding agent. The agent hint specs turn hints back on. +ENV["SENTRY_AGENT_HINTS"] = "0" + if ENV["CI"] require 'simplecov-cobertura' SimpleCov.formatter = SimpleCov::Formatter::CoberturaFormatter From 66140e0134f57dcc745be2e296244a69623a6e2e Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:16:23 +0000 Subject: [PATCH 2/5] fix: Keep the app's $? and support Rails < 6.1 in specs Run git through Open3 so the agent hint doesn't change the caller's $?. A failed `git status` left $? set, which broke release detection specs that run after it. On Rails < 6.1, `Rails::Railtie.respond_to?` raises because the class is abstract, so check `Sentry::Railtie` like the railtie does. --- sentry-rails/spec/sentry/rails_spec.rb | 2 +- sentry-ruby/lib/sentry/agent_hint.rb | 7 +++++-- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/sentry-rails/spec/sentry/rails_spec.rb b/sentry-rails/spec/sentry/rails_spec.rb index 941db3690..8b7a29ec3 100644 --- a/sentry-rails/spec/sentry/rails_spec.rb +++ b/sentry-rails/spec/sentry/rails_spec.rb @@ -41,7 +41,7 @@ expect(Sentry.configuration.background_worker_threads).to eq(0) end - it "logs the coding agent hint when the server loads", skip: !Rails::Railtie.respond_to?(:server) && "needs Rails 6.1+" do + it "logs the coding agent hint when the server loads", skip: !Sentry::Railtie.respond_to?(:server) && "needs Rails 6.1+" do allow(Sentry::AgentHint).to receive(:take).and_return("[sentry] hint") expect(Rails.logger).to receive(:warn).with("[sentry] hint") diff --git a/sentry-ruby/lib/sentry/agent_hint.rb b/sentry-ruby/lib/sentry/agent_hint.rb index 7e2469ce1..5a04acf69 100644 --- a/sentry-ruby/lib/sentry/agent_hint.rb +++ b/sentry-ruby/lib/sentry/agent_hint.rb @@ -1,5 +1,7 @@ # frozen_string_literal: true +require "open3" + module Sentry # Points a coding agent at SETUP_CHECKLIST.md while it sets up Sentry and # leaves tracing or logs off. People running the app never see it. @@ -109,9 +111,10 @@ def setup_in_progress? # Returns nil when git isn't installed or the file isn't in a repo. Read only: # no index lock, since the agent may be running git at the same time. + # Open3 leaves the app's $? alone. def git(*args) - output = IO.popen(["git", "--no-optional-locks", *args], chdir: File.dirname(@init_file), err: File::NULL, &:read) - output.strip if $CHILD_STATUS.success? + output, status = Open3.capture2("git", "--no-optional-locks", *args, chdir: File.dirname(@init_file), err: File::NULL) + output.strip if status.success? rescue SystemCallError nil end From dbef0b8cf93436d745ef29db743cbe22eb6ccb5f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Johannes=20Daxb=C3=B6ck?= Date: Mon, 23 Nov 2026 23:31:12 +0100 Subject: [PATCH 3/5] fix(ruby): Harden agent hint detection and match Python's env rules Skip the hint when Sentry.init is called from an installed gem or the Ruby stdlib, as Python does. A freshly installed tool otherwise looks like an app that's being set up. Compare real paths, since gem and tmp dirs are often symlinks. Run git with core.fsmonitor=false so the read-only status check can't run a command configured in the repo. Print with $stderr.puts. Kernel#warn prints nothing under ruby -W0. Match Python's env handling: an empty AI_AGENT no longer hides CLAUDECODE and the other agent vars, empty agent vars don't count, and only an explicit falsy SENTRY_AGENT_HINTS turns hints off. CI=false is no longer treated as CI. Guard the registered hint with a mutex, since the Rails server hook and at_exit can take it from different threads, and log failures to the SDK logger at debug instead of dropping them. Turn hints off in every gem's spec helper, and make the checklist exact about traces_sample_rate 0 vs nil. Recommend Vernier for profiling on Ruby 3.2.1+. Co-Authored-By: Claude Opus 5.5 --- sentry-delayed_job/spec/spec_helper.rb | 4 + sentry-opentelemetry/spec/spec_helper.rb | 4 + sentry-rails/spec/spec_helper.rb | 3 + sentry-resque/spec/spec_helper.rb | 4 + sentry-ruby/lib/sentry/SETUP_CHECKLIST.md | 4 +- sentry-ruby/lib/sentry/agent_hint.rb | 102 ++++++++++++++++----- sentry-ruby/spec/sentry/agent_hint_spec.rb | 33 ++++++- sentry-sidekiq/spec/spec_helper.rb | 4 + sentry-yabeda/spec/spec_helper.rb | 4 + 9 files changed, 137 insertions(+), 25 deletions(-) diff --git a/sentry-delayed_job/spec/spec_helper.rb b/sentry-delayed_job/spec/spec_helper.rb index af62fa7e6..9e40b9836 100644 --- a/sentry-delayed_job/spec/spec_helper.rb +++ b/sentry-delayed_job/spec/spec_helper.rb @@ -1,6 +1,10 @@ # frozen_string_literal: true require "bundler/setup" + +# The suite may itself run under a coding agent. Don't print the Sentry agent hint. +ENV["SENTRY_AGENT_HINTS"] = "0" + begin require "debug/prelude" rescue LoadError diff --git a/sentry-opentelemetry/spec/spec_helper.rb b/sentry-opentelemetry/spec/spec_helper.rb index e9d82a6ca..ad492a76a 100644 --- a/sentry-opentelemetry/spec/spec_helper.rb +++ b/sentry-opentelemetry/spec/spec_helper.rb @@ -1,6 +1,10 @@ # frozen_string_literal: true require "bundler/setup" + +# The suite may itself run under a coding agent. Don't print the Sentry agent hint. +ENV["SENTRY_AGENT_HINTS"] = "0" + begin require "debug/prelude" rescue LoadError diff --git a/sentry-rails/spec/spec_helper.rb b/sentry-rails/spec/spec_helper.rb index cde34bdbd..e1abb18cf 100644 --- a/sentry-rails/spec/spec_helper.rb +++ b/sentry-rails/spec/spec_helper.rb @@ -2,6 +2,9 @@ require "bundler/setup" +# The suite may itself run under a coding agent. Don't print the Sentry agent hint. +ENV["SENTRY_AGENT_HINTS"] = "0" + ENV["RAILS_ENV"] = "test" begin diff --git a/sentry-resque/spec/spec_helper.rb b/sentry-resque/spec/spec_helper.rb index 4d516832c..37c756384 100644 --- a/sentry-resque/spec/spec_helper.rb +++ b/sentry-resque/spec/spec_helper.rb @@ -1,6 +1,10 @@ # frozen_string_literal: true require "bundler/setup" + +# The suite may itself run under a coding agent. Don't print the Sentry agent hint. +ENV["SENTRY_AGENT_HINTS"] = "0" + begin require "debug/prelude" rescue LoadError diff --git a/sentry-ruby/lib/sentry/SETUP_CHECKLIST.md b/sentry-ruby/lib/sentry/SETUP_CHECKLIST.md index 00be05960..2d082d23c 100644 --- a/sentry-ruby/lib/sentry/SETUP_CHECKLIST.md +++ b/sentry-ruby/lib/sentry/SETUP_CHECKLIST.md @@ -10,7 +10,7 @@ This is Sentry's official setup guidance, shipped in the `sentry-ruby` gem and m Turn these on unless the user asked you not to. Sentry links errors, traces and logs, so an error shows the request that caused it and the logs around it. -- **Tracing.** Shows which request caused an error and where the time went. Set `config.traces_sample_rate` by environment: `1.0` locally, so you can see a trace when you verify, and a low rate in production (`0.1` is a common start) unless the project already has one. Don't default it to `0`: a rate of `0` sends no traces at all. +- **Tracing.** Shows which request caused an error and where the time went. Set `config.traces_sample_rate` by environment: `1.0` locally, so you can see a trace when you verify, and a low rate in production (`0.1` is a common start) unless the project already has one. Don't default it to `0`: a rate of `0` starts no traces of its own (it only continues traces from incoming requests), and `nil` turns tracing off. - **Logs.** Add `config.enabled_patches << :logger`. The app's logs, including `Rails.logger`, show up next to the errors they belong to. In Rails, also set `config.rails.structured_logging.enabled = true` to send Active Record and Action Controller events as logs. `Sentry.logger.info(...)` sends a log directly. - **Environment and release.** Set `config.environment` so production issues are separate from local ones. The SDK reads the release from `SENTRY_RELEASE` or the git commit. If the app runs without `.git` (for example in a Docker image), set `SENTRY_RELEASE` at build time or set `config.release` to the app's version, so you can see which deploy caused an issue. @@ -32,7 +32,7 @@ Do the Required and Recommended items first. Then look at the ones below. Set th - **Crons**, if the app schedules jobs with sidekiq-cron, sidekiq-scheduler, GoodJob cron, Solid Queue recurring tasks or rufus-scheduler. Sentry alerts when a job fails or doesn't run, and every scheduled job gets a monitor, including ones added later. Add the matching patch: `config.enabled_patches += [:sidekiq_cron]`, `:sidekiq_scheduler`, `:good_job_cron`, `:solid_queue_recurring` or `:rufus_scheduler`. - **Background jobs**, if the app uses Sidekiq, Resque or Delayed Job. Add `sentry-sidekiq`, `sentry-resque` or `sentry-delayed_job` to the Gemfile, so job errors and traces are captured and linked to the request that queued them. -- **Profiling**, if the user cares about the performance of specific code paths. Add the `stackprof` gem and set `config.profiles_sample_rate`. It is relative to `traces_sample_rate`. +- **Profiling**, if the user cares about the performance of specific code paths. On Ruby 3.2.1+, add the `vernier` gem and set `config.profiler_class = Sentry::Vernier::Profiler`. On older Rubies, add `stackprof` above `sentry-ruby` in the Gemfile. Then set `config.profiles_sample_rate`. It is relative to `traces_sample_rate`. - **Metrics**, if the user wants to track counts or values over time (signups, queue depth). Call `Sentry.metrics.count(...)`, `gauge(...)` or `distribution(...)` where they happen. ## Before you finish diff --git a/sentry-ruby/lib/sentry/agent_hint.rb b/sentry-ruby/lib/sentry/agent_hint.rb index 5a04acf69..e8a560fad 100644 --- a/sentry-ruby/lib/sentry/agent_hint.rb +++ b/sentry-ruby/lib/sentry/agent_hint.rb @@ -1,6 +1,7 @@ # frozen_string_literal: true require "open3" +require "rbconfig" module Sentry # Points a coding agent at SETUP_CHECKLIST.md while it sets up Sentry and @@ -21,46 +22,92 @@ class AgentHint # the setting names doesn't open the checklist. NOT_SHOWN = { tracing: "the request trace around them", logs: "its logs" }.freeze + @mutex = Mutex.new + @registered = false + @hint = nil + class << self # Called by Sentry.init with the location that called it. The hint prints at # exit, unless an integration takes it earlier. def register(config, caller_location) init_file = caller_location&.absolute_path || caller_location&.path - return unless @hint.nil? && init_file && coding_agent? + return if @registered || init_file.nil? || external_source?(init_file) || !coding_agent? hint = new(config, init_file) return unless hint.applies? - @hint = hint - pid = Process.pid + @mutex.synchronize do + return if @registered + + @registered = true + @hint = hint + end + pid = Process.pid at_exit do # Forked workers inherit at_exit blocks, so only the process that called init prints. - next unless Process.pid == pid && (message = take) + next unless Process.pid == pid - # Piped stdout is only flushed at exit. Flush it first so the hint stays - # last for agents that cut the output with `| tail`. - $stdout.flush - warn(message) + print_hint(config) end - rescue StandardError + rescue StandardError => e # Best effort: the hint must never break Sentry.init. - nil + log_failure(config, e) end # Returns the hint once, or nil when there's nothing to show. def take - hint = @hint - @hint = false - hint.message if hint + hint = @mutex.synchronize { @hint.tap { @hint = nil } } + hint&.message end def coding_agent? - return false if ENV["CI"] - return false unless Utils::EnvHelper.env_to_bool(ENV.fetch("SENTRY_AGENT_HINTS", "1")) - return Utils::EnvHelper.env_to_bool(ENV["AI_AGENT"]) if ENV.key?("AI_AGENT") + return false if Utils::EnvHelper.env_to_bool(ENV["CI"]) + # Only an explicit falsy value turns hints off, so SENTRY_AGENT_HINTS= keeps them on. + return false if Utils::EnvHelper.env_to_bool(ENV["SENTRY_AGENT_HINTS"], strict: true) == false + + # An empty AI_AGENT doesn't count, so it can't hide the agent-specific vars below. + ai_agent = ENV["AI_AGENT"].to_s + return Utils::EnvHelper.env_to_bool(ai_agent, strict: true) != false unless ai_agent.empty? + + AGENT_ENV_VARS.any? { |name| !ENV[name].to_s.empty? } + end + + private + + def print_hint(config) + message = take + return unless message - AGENT_ENV_VARS.any? { |name| ENV.key?(name) } + # Piped stdout is only flushed at exit. Flush it first so the hint stays + # last for agents that cut the output with `| tail`. + $stdout.flush + # Not Kernel#warn: it prints nothing when warnings are off (ruby -W0). + $stderr.puts(message) + rescue StandardError => e + log_failure(config, e) + end + + # An installed gem or tool that calls Sentry.init itself isn't the user's app, + # even when it was installed a moment ago. + def external_source?(path) + path = real_path(path) + [*Gem.path, RbConfig::CONFIG["rubylibdir"]].compact.any? do |dir| + path.start_with?(File.join(real_path(dir), "")) + end + end + + # Gem dirs and tmp dirs are often symlinks (/var -> /private/var on macOS). + def real_path(path) + File.realpath(path) + rescue SystemCallError + File.expand_path(path) + end + + def log_failure(config, error) + config.sdk_logger&.debug(LOGGER_PROGNAME) { "Skipped the coding agent hint: #{error.class}: #{error.message}" } + rescue StandardError + nil end end @@ -85,10 +132,17 @@ def message private def missing - @missing ||= [].tap do |products| - products << :tracing unless @config.traces_sampler || @config.traces_sample_rate.to_f.positive? + @missing ||= NOT_SHOWN.keys.reject { |product| enabled?(product) } + end + + def enabled?(product) + case product + when :tracing + # Configuration#validate already rejects a non-numeric rate. + !@config.traces_sampler.nil? || @config.traces_sample_rate.to_f.positive? + when :logs # Rails.logger is a ::Logger too, so the :logger patch covers Rails apps. - products << :logs unless @config.enabled_patches.include?(:logger) + @config.enabled_patches.include?(:logger) end end @@ -110,10 +164,14 @@ def setup_in_progress? end # Returns nil when git isn't installed or the file isn't in a repo. Read only: - # no index lock, since the agent may be running git at the same time. + # no index lock, since the agent may be running git at the same time, and no + # fsmonitor, which would run a command configured in the repo. # Open3 leaves the app's $? alone. def git(*args) - output, status = Open3.capture2("git", "--no-optional-locks", *args, chdir: File.dirname(@init_file), err: File::NULL) + output, status = Open3.capture2( + "git", "--no-optional-locks", "-c", "core.fsmonitor=false", *args, + chdir: File.dirname(@init_file), err: File::NULL + ) output.strip if status.success? rescue SystemCallError nil diff --git a/sentry-ruby/spec/sentry/agent_hint_spec.rb b/sentry-ruby/spec/sentry/agent_hint_spec.rb index 6b6337d36..b916b4125 100644 --- a/sentry-ruby/spec/sentry/agent_hint_spec.rb +++ b/sentry-ruby/spec/sentry/agent_hint_spec.rb @@ -26,6 +26,7 @@ before do described_class.instance_variable_set(:@hint, nil) + described_class.instance_variable_set(:@registered, false) allow(described_class).to receive(:at_exit) { |&hook| at_exit_hooks << hook } end @@ -67,7 +68,13 @@ def capture_stderr {} => false, { "AI_AGENT" => "0" } => false, { "AI_AGENT" => "claude-code", "CI" => "true" } => false, - { "CLAUDECODE" => "1", "SENTRY_AGENT_HINTS" => "0" } => false + { "CLAUDECODE" => "1", "SENTRY_AGENT_HINTS" => "0" } => false, + { "CLAUDECODE" => "" } => false, + { "AI_AGENT" => "", "CLAUDECODE" => "1" } => true, + { "CI" => "", "CLAUDECODE" => "1" } => true, + { "CI" => "false", "CLAUDECODE" => "1" } => true, + { "SENTRY_AGENT_HINTS" => "", "CLAUDECODE" => "1" } => true, + { "SENTRY_AGENT_HINTS" => "off", "CLAUDECODE" => "1" } => false }.each do |env, shown| it "is #{"not " unless shown}shown for #{env}" do expect(run_app(env).include?(checklist)).to be(shown) @@ -116,6 +123,30 @@ def capture_stderr expect(capture_stderr { at_exit_hooks.each(&:call) }).to eq("") end + it "is printed when Ruby warnings are off" do + load_app({ "AI_AGENT" => "claude-code" }) + verbose, $VERBOSE = $VERBOSE, nil + + expect(capture_stderr { at_exit_hooks.each(&:call) }).to include(checklist) + ensure + $VERBOSE = verbose + end + + it "isn't shown when an installed gem calls Sentry.init" do + allow(Gem).to receive(:path).and_return([@dir]) + + expect(run_app({ "AI_AGENT" => "claude-code" })).to eq("") + end + + it "runs git without fsmonitor or optional locks" do + allow(Open3).to receive(:capture2).and_call_original + + run_app({ "AI_AGENT" => "claude-code" }) + + expect(Open3).to have_received(:capture2) + .with("git", "--no-optional-locks", "-c", "core.fsmonitor=false", "status", any_args) + end + it "isn't printed by a forked child" do load_app({ "AI_AGENT" => "claude-code" }) allow(Process).to receive(:pid).and_return(Process.pid + 1) diff --git a/sentry-sidekiq/spec/spec_helper.rb b/sentry-sidekiq/spec/spec_helper.rb index 3908a2193..765e2d760 100644 --- a/sentry-sidekiq/spec/spec_helper.rb +++ b/sentry-sidekiq/spec/spec_helper.rb @@ -1,6 +1,10 @@ # frozen_string_literal: true require "bundler/setup" + +# The suite may itself run under a coding agent. Don't print the Sentry agent hint. +ENV["SENTRY_AGENT_HINTS"] = "0" + begin require "debug/prelude" rescue LoadError diff --git a/sentry-yabeda/spec/spec_helper.rb b/sentry-yabeda/spec/spec_helper.rb index 711ee6dd2..016ba3804 100644 --- a/sentry-yabeda/spec/spec_helper.rb +++ b/sentry-yabeda/spec/spec_helper.rb @@ -1,6 +1,10 @@ # frozen_string_literal: true require "bundler/setup" + +# The suite may itself run under a coding agent. Don't print the Sentry agent hint. +ENV["SENTRY_AGENT_HINTS"] = "0" + begin require "debug/prelude" rescue LoadError From 796365b680903c2da43093bf11a2a0ec7d13cee4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Johannes=20Daxb=C3=B6ck?= Date: Tue, 24 Nov 2026 11:35:33 +0100 Subject: [PATCH 4/5] fix: Use Rails structured logging for the agent hint and show it on boot In a Rails app, count logs as on when Rails structured logging is enabled, not when the :logger patch is. The patch sends every Rails.logger line, which the Rails docs call noisy, so the checklist now recommends structured logging and keeps the patch for non-Rails apps. Print the hint to stderr when rails server boots. Server blocks run when config.ru loads, before rails server sends Rails.logger to the console, so the hint only reached log/development.log and was never shown at exit either. Make every entry point safe: building the message and printing it log failures at debug instead of raising, so the hint can't break a Rails boot or turn an exit status into 1. Check the ENV before any file or git work, so apps outside a coding agent do nothing else. Co-Authored-By: Claude Opus 5.5 --- sentry-rails/lib/sentry/rails/railtie.rb | 11 +-- sentry-rails/spec/sentry/rails_spec.rb | 16 +++- sentry-ruby/lib/sentry/SETUP_CHECKLIST.md | 3 +- sentry-ruby/lib/sentry/agent_hint.rb | 89 +++++++++++++--------- sentry-ruby/spec/sentry/agent_hint_spec.rb | 42 +++++++++- 5 files changed, 111 insertions(+), 50 deletions(-) diff --git a/sentry-rails/lib/sentry/rails/railtie.rb b/sentry-rails/lib/sentry/rails/railtie.rb index dd52b7d3c..66084040d 100644 --- a/sentry-rails/lib/sentry/rails/railtie.rb +++ b/sentry-rails/lib/sentry/rails/railtie.rb @@ -71,14 +71,11 @@ class Railtie < ::Rails::Railtie end end - # `rails server` runs until it's stopped, so the agent hint that Sentry.init would - # print at exit goes to the Rails logger once the app is loaded. In development the - # server logs to the console. Server blocks exist since Rails 6.1. + # `rails server` runs until it's stopped, so show the agent hint while it boots. + # Not via Rails.logger: server blocks run before `rails server` sends it to the + # console, so the hint would only reach log/development.log. Rails 6.1+. if respond_to?(:server) - server do - hint = Sentry::AgentHint.take - ::Rails.logger.warn(hint) if hint - end + server { Sentry::AgentHint.show } end runner do diff --git a/sentry-rails/spec/sentry/rails_spec.rb b/sentry-rails/spec/sentry/rails_spec.rb index 8b7a29ec3..6b066d3e1 100644 --- a/sentry-rails/spec/sentry/rails_spec.rb +++ b/sentry-rails/spec/sentry/rails_spec.rb @@ -41,11 +41,21 @@ expect(Sentry.configuration.background_worker_threads).to eq(0) end - it "logs the coding agent hint when the server loads", skip: !Sentry::Railtie.respond_to?(:server) && "needs Rails 6.1+" do + it "prints the coding agent hint to stderr when the server loads", skip: !Sentry::Railtie.respond_to?(:server) && "needs Rails 6.1+" do allow(Sentry::AgentHint).to receive(:take).and_return("[sentry] hint") - expect(Rails.logger).to receive(:warn).with("[sentry] hint") - Rails.application.load_server + expect { Rails.application.load_server }.to output("[sentry] hint\n").to_stderr + end + + it "counts Rails structured logging, not the :logger patch, as logs for the coding agent hint" do + config = Sentry.configuration + missing = -> { Sentry::AgentHint.new(config, __FILE__).send(:missing) } + + config.enabled_patches << :logger + expect(missing.call).to include(:logs) + + config.rails.structured_logging.enabled = true + expect(missing.call).not_to include(:logs) end describe "logger detection" do diff --git a/sentry-ruby/lib/sentry/SETUP_CHECKLIST.md b/sentry-ruby/lib/sentry/SETUP_CHECKLIST.md index 2d082d23c..64bea8d84 100644 --- a/sentry-ruby/lib/sentry/SETUP_CHECKLIST.md +++ b/sentry-ruby/lib/sentry/SETUP_CHECKLIST.md @@ -11,7 +11,7 @@ This is Sentry's official setup guidance, shipped in the `sentry-ruby` gem and m Turn these on unless the user asked you not to. Sentry links errors, traces and logs, so an error shows the request that caused it and the logs around it. - **Tracing.** Shows which request caused an error and where the time went. Set `config.traces_sample_rate` by environment: `1.0` locally, so you can see a trace when you verify, and a low rate in production (`0.1` is a common start) unless the project already has one. Don't default it to `0`: a rate of `0` starts no traces of its own (it only continues traces from incoming requests), and `nil` turns tracing off. -- **Logs.** Add `config.enabled_patches << :logger`. The app's logs, including `Rails.logger`, show up next to the errors they belong to. In Rails, also set `config.rails.structured_logging.enabled = true` to send Active Record and Action Controller events as logs. `Sentry.logger.info(...)` sends a log directly. +- **Logs.** In Rails, set `config.rails.structured_logging.enabled = true`, so Active Record and Action Controller events show up as logs next to the errors they belong to. Outside Rails, add `config.enabled_patches << :logger` to send what the app writes to a `::Logger`. In Rails that patch also sends every `Rails.logger` line, which can be noisy, so add it only if the user wants that. `Sentry.logger.info(...)` sends a log directly. - **Environment and release.** Set `config.environment` so production issues are separate from local ones. The SDK reads the release from `SENTRY_RELEASE` or the git commit. If the app runs without `.git` (for example in a Docker image), set `SENTRY_RELEASE` at build time or set `config.release` to the app's version, so you can see which deploy caused an issue. To tell production from local runs, use a check the app already has, such as `Rails.env.production?`. Don't add a new variable that nothing sets. @@ -21,7 +21,6 @@ Sentry.init do |config| config.dsn = ENV["SENTRY_DSN"] config.environment = Rails.env config.traces_sample_rate = Rails.env.production? ? 0.1 : 1.0 - config.enabled_patches << :logger config.rails.structured_logging.enabled = true end ``` diff --git a/sentry-ruby/lib/sentry/agent_hint.rb b/sentry-ruby/lib/sentry/agent_hint.rb index e8a560fad..966a3ff3b 100644 --- a/sentry-ruby/lib/sentry/agent_hint.rb +++ b/sentry-ruby/lib/sentry/agent_hint.rb @@ -6,6 +6,9 @@ module Sentry # Points a coding agent at SETUP_CHECKLIST.md while it sets up Sentry and # leaves tracing or logs off. People running the app never see it. + # + # Best effort throughout: failures are logged at debug level and swallowed, so + # the hint can never break Sentry.init, a Rails boot or the app's exit status. # @!visibility private class AgentHint CHECKLIST_PATH = File.expand_path("SETUP_CHECKLIST.md", __dir__) @@ -27,11 +30,14 @@ class AgentHint @hint = nil class << self - # Called by Sentry.init with the location that called it. The hint prints at - # exit, unless an integration takes it earlier. + # Called by Sentry.init. The hint is shown at exit, unless an integration + # shows it earlier. def register(config, caller_location) + # ENV checks first: outside a coding agent this is the only work done. + return if @registered || !coding_agent? + init_file = caller_location&.absolute_path || caller_location&.path - return if @registered || init_file.nil? || external_source?(init_file) || !coding_agent? + return if init_file.nil? || external_source?(init_file) hint = new(config, init_file) return unless hint.applies? @@ -46,18 +52,32 @@ def register(config, caller_location) pid = Process.pid at_exit do # Forked workers inherit at_exit blocks, so only the process that called init prints. - next unless Process.pid == pid - - print_hint(config) + show if Process.pid == pid end rescue StandardError => e - # Best effort: the hint must never break Sentry.init. log_failure(config, e) end - # Returns the hint once, or nil when there's nothing to show. + def show + message = take + return unless message + + # Piped stdout is only flushed at exit. Flush it first so the hint stays + # last for agents that cut the output with `| tail`. + $stdout.flush + # Not Kernel#warn: it prints nothing when warnings are off (ruby -W0). + $stderr.puts(message) + rescue StandardError + # stderr may be closed. An error raised in at_exit would set exit status 1. + nil + end + + # Returns the message at most once per process. def take - hint = @mutex.synchronize { @hint.tap { @hint = nil } } + hint = @mutex.synchronize do + taken, @hint = @hint, nil + taken + end hint&.message end @@ -73,22 +93,15 @@ def coding_agent? AGENT_ENV_VARS.any? { |name| !ENV[name].to_s.empty? } end - private - - def print_hint(config) - message = take - return unless message - - # Piped stdout is only flushed at exit. Flush it first so the hint stays - # last for agents that cut the output with `| tail`. - $stdout.flush - # Not Kernel#warn: it prints nothing when warnings are off (ruby -W0). - $stderr.puts(message) - rescue StandardError => e - log_failure(config, e) + def log_failure(config, error) + config.sdk_logger&.debug(LOGGER_PROGNAME) { "Skipped the coding agent hint: #{error.class}: #{error.message}" } + rescue StandardError + nil end - # An installed gem or tool that calls Sentry.init itself isn't the user's app, + private + + # An installed gem or tool that calls Sentry.init isn't the user's app, # even when it was installed a moment ago. def external_source?(path) path = real_path(path) @@ -103,12 +116,6 @@ def real_path(path) rescue SystemCallError File.expand_path(path) end - - def log_failure(config, error) - config.sdk_logger&.debug(LOGGER_PROGNAME) { "Skipped the coding agent hint: #{error.class}: #{error.message}" } - rescue StandardError - nil - end end def initialize(config, init_file) @@ -116,6 +123,7 @@ def initialize(config, init_file) @init_file = File.expand_path(init_file) end + # Runs during Sentry.init, so the slower git checks wait for #message. def applies? @config.dsn && !@config.agent_setup_complete && missing.any? && changed_within?(SETUP_WINDOW) end @@ -127,6 +135,9 @@ def message "If you're setting up Sentry, check the setup against Sentry's official setup checklist. If you leave " \ "it as is, tell the user. The checklist is included in the sentry-ruby gem you installed: " \ "#{CHECKLIST_PATH} (hide with SENTRY_AGENT_HINTS=0)" + rescue StandardError => e + self.class.log_failure(@config, e) + nil end private @@ -138,11 +149,15 @@ def missing def enabled?(product) case product when :tracing - # Configuration#validate already rejects a non-numeric rate. !@config.traces_sampler.nil? || @config.traces_sample_rate.to_f.positive? when :logs - # Rails.logger is a ::Logger too, so the :logger patch covers Rails apps. - @config.enabled_patches.include?(:logger) + # sentry-rails adds config.rails. There, logs means Rails structured logging; + # the :logger patch would send every Rails.logger line, which is noisy. + if @config.respond_to?(:rails) + @config.rails.structured_logging.enabled? + else + @config.enabled_patches.include?(:logger) + end end end @@ -152,8 +167,8 @@ def changed_within?(seconds) false end - # Whether this user changed the file a short time ago. A checkout or a - # teammate's commit also gives the file a new mtime, so ask git. + # Whether this user changed the file recently. A checkout or a teammate's + # commit also gives the file a new mtime, so ask git. def setup_in_progress? status = git("status", "--porcelain", "--", @init_file) return changed_within?(SETUP_WINDOW_WITHOUT_GIT) if status.nil? @@ -163,9 +178,9 @@ def setup_in_progress? !committer.to_s.empty? && committer == git("config", "user.email") end - # Returns nil when git isn't installed or the file isn't in a repo. Read only: - # no index lock, since the agent may be running git at the same time, and no - # fsmonitor, which would run a command configured in the repo. + # Returns nil when git isn't installed or the file isn't in a repo. + # --no-optional-locks: the agent may be running git at the same time. + # core.fsmonitor=false: an fsmonitor would run a command configured in the repo. # Open3 leaves the app's $? alone. def git(*args) output, status = Open3.capture2( diff --git a/sentry-ruby/spec/sentry/agent_hint_spec.rb b/sentry-ruby/spec/sentry/agent_hint_spec.rb index b916b4125..b10114fd0 100644 --- a/sentry-ruby/spec/sentry/agent_hint_spec.rb +++ b/sentry-ruby/spec/sentry/agent_hint_spec.rb @@ -82,13 +82,22 @@ def capture_stderr end end + # Gives the config the config.rails.structured_logging.enabled? that sentry-rails adds. + def self.rails_config(structured_logging:) + "logging = Struct.new(:enabled?).new(#{structured_logging}); " \ + "config.define_singleton_method(:rails) { Struct.new(:structured_logging).new(logging) }" + end + describe "what it says" do { "" => "not the request trace around them, or its logs.", "config.enabled_patches << :logger" => "not the request trace around them.", "config.traces_sample_rate = 0.1" => "not its logs.", "config.traces_sampler = ->(_) { 1.0 }" => "not its logs.", - "config.traces_sample_rate = 0.0" => "not the request trace around them, or its logs." + "config.traces_sample_rate = 0.0" => "not the request trace around them, or its logs.", + "#{rails_config(structured_logging: true)}" => "not the request trace around them.", + "#{rails_config(structured_logging: false)}; config.enabled_patches << :logger" => + "not the request trace around them, or its logs." }.each do |config, missing| it "says what's missing with #{config.inspect}" do expect(run_app({ "AI_AGENT" => "claude-code" }, config)) @@ -147,6 +156,37 @@ def capture_stderr .with("git", "--no-optional-locks", "-c", "core.fsmonitor=false", "status", any_args) end + it "does no file or git work outside a coding agent" do + expect(File).not_to receive(:realpath) + expect(Open3).not_to receive(:capture2) + + expect(run_app({})).to eq("") + end + + it "doesn't raise or print when building the message fails" do + load_app({ "AI_AGENT" => "claude-code" }) + allow(Open3).to receive(:capture2).and_raise(IOError, "closed stream") + + expect(capture_stderr { at_exit_hooks.each(&:call) }).to eq("") + end + + it "doesn't raise when stderr is closed" do + load_app({ "AI_AGENT" => "claude-code" }) + closed = StringIO.new.tap(&:close) + original, $stderr = $stderr, closed + + expect { at_exit_hooks.each(&:call) }.not_to raise_error + ensure + $stderr = original + end + + it "doesn't break Sentry.init when registering fails" do + allow(described_class).to receive(:new).and_raise(NoMethodError, "boom") + + expect { load_app({ "AI_AGENT" => "claude-code" }) }.not_to raise_error + expect(Sentry.initialized?).to be(true) + end + it "isn't printed by a forked child" do load_app({ "AI_AGENT" => "claude-code" }) allow(Process).to receive(:pid).and_return(Process.pid + 1) From 686201a6959f0b77e2cd4ab44cae31b42ddbd42b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Johannes=20Daxb=C3=B6ck?= Date: Tue, 24 Nov 2026 11:49:28 +0100 Subject: [PATCH 5/5] fix: Time out slow git calls and show the agent hint under Spring Give each git call 2 seconds. A slow repo or network file system could otherwise hold up the app's exit or a Rails boot. On timeout, kill git's whole process group and skip the hint. Spring runs Sentry.init once in its preloaded app, with the ENV Spring was started with, and forks each command with the caller's ENV. The fork never printed because of the pid check, and a Spring started outside the agent never showed the hint at all. Decide again in Spring's after_fork, so the command run by the agent shows it. Co-Authored-By: Claude Opus 5.5 --- sentry-rails/lib/sentry/rails/railtie.rb | 5 ++ sentry-ruby/lib/sentry/agent_hint.rb | 95 +++++++++++++++------- sentry-ruby/spec/sentry/agent_hint_spec.rb | 60 +++++++++++++- 3 files changed, 127 insertions(+), 33 deletions(-) diff --git a/sentry-rails/lib/sentry/rails/railtie.rb b/sentry-rails/lib/sentry/rails/railtie.rb index 66084040d..5607621f9 100644 --- a/sentry-rails/lib/sentry/rails/railtie.rb +++ b/sentry-rails/lib/sentry/rails/railtie.rb @@ -78,6 +78,11 @@ class Railtie < ::Rails::Railtie server { Sentry::AgentHint.show } end + # Spring forks each command (rails runner, rspec, ...) from its preloaded app. + if defined?(::Spring) && ::Spring.respond_to?(:after_fork) + ::Spring.after_fork { Sentry::AgentHint.after_fork } + end + runner do next unless Sentry.initialized? Sentry.configuration.background_worker_threads = 0 diff --git a/sentry-ruby/lib/sentry/agent_hint.rb b/sentry-ruby/lib/sentry/agent_hint.rb index 966a3ff3b..5d9659262 100644 --- a/sentry-ruby/lib/sentry/agent_hint.rb +++ b/sentry-ruby/lib/sentry/agent_hint.rb @@ -21,6 +21,13 @@ class AgentHint SETUP_WINDOW = 60 * 60 SETUP_WINDOW_WITHOUT_GIT = 10 * 60 + # Per git call. A slow repo must not hold up the app's exit or a Rails boot. + GIT_TIMEOUT = 2 + # Its own process group, so a timeout also kills anything git started. + GIT_SPAWN_OPTIONS = Gem.win_platform? ? {} : { pgroup: true } + + class GitTimeout < StandardError; end + # Say what Sentry won't show, not which settings are off. An agent that sees # the setting names doesn't open the checklist. NOT_SHOWN = { tracing: "the request trace around them", logs: "its logs" }.freeze @@ -33,29 +40,18 @@ class << self # Called by Sentry.init. The hint is shown at exit, unless an integration # shows it earlier. def register(config, caller_location) - # ENV checks first: outside a coding agent this is the only work done. - return if @registered || !coding_agent? - - init_file = caller_location&.absolute_path || caller_location&.path - return if init_file.nil? || external_source?(init_file) - - hint = new(config, init_file) - return unless hint.applies? - - @mutex.synchronize do - return if @registered - - @registered = true - @hint = hint - end + @init = [config, caller_location&.absolute_path || caller_location&.path] + arm + end - pid = Process.pid - at_exit do - # Forked workers inherit at_exit blocks, so only the process that called init prints. - show if Process.pid == pid - end - rescue StandardError => e - log_failure(config, e) + # Spring runs Sentry.init once in its preloaded app, with the ENV Spring was + # started with, then forks each command with the caller's ENV. Decide again + # in the fork, so a command run by an agent shows the hint. + def after_fork + @mutex = Mutex.new + @registered = false + @hint = nil + arm end def show @@ -94,13 +90,38 @@ def coding_agent? end def log_failure(config, error) - config.sdk_logger&.debug(LOGGER_PROGNAME) { "Skipped the coding agent hint: #{error.class}: #{error.message}" } + config&.sdk_logger&.debug(LOGGER_PROGNAME) { "Skipped the coding agent hint: #{error.class}: #{error.message}" } rescue StandardError nil end private + def arm + config, init_file = @init + # ENV checks first: outside a coding agent this is the only work done. + return if config.nil? || @registered || !coding_agent? + return if init_file.nil? || external_source?(init_file) + + hint = new(config, init_file) + return unless hint.applies? + + @mutex.synchronize do + return if @registered + + @registered = true + @hint = hint + end + + pid = Process.pid + at_exit do + # Forked workers inherit at_exit blocks, so only the process that registered prints. + show if Process.pid == pid + end + rescue StandardError => e + log_failure(config, e) + end + # An installed gem or tool that calls Sentry.init isn't the user's app, # even when it was installed a moment ago. def external_source?(path) @@ -178,17 +199,33 @@ def setup_in_progress? !committer.to_s.empty? && committer == git("config", "user.email") end - # Returns nil when git isn't installed or the file isn't in a repo. + # Returns nil when git isn't installed or the file isn't in a repo, and raises + # GitTimeout when git is too slow, which skips the hint. # --no-optional-locks: the agent may be running git at the same time. # core.fsmonitor=false: an fsmonitor would run a command configured in the repo. # Open3 leaves the app's $? alone. def git(*args) - output, status = Open3.capture2( + Open3.popen2( "git", "--no-optional-locks", "-c", "core.fsmonitor=false", *args, - chdir: File.dirname(@init_file), err: File::NULL - ) - output.strip if status.success? - rescue SystemCallError + chdir: File.dirname(@init_file), err: File::NULL, **GIT_SPAWN_OPTIONS + ) do |stdin, stdout, wait_thread| + stdin.close + # Read while waiting, so a full pipe can't stall git until the timeout. + # Closing stdout after a timeout makes the read raise, which is expected. + reader = Thread.new do + Thread.current.report_on_exception = false + stdout.read + end + + unless wait_thread.join(GIT_TIMEOUT) + Process.kill(:KILL, Gem.win_platform? ? wait_thread.pid : -wait_thread.pid) + raise GitTimeout, "git #{args.first} took over #{GIT_TIMEOUT}s" + end + + output = reader.value + output.strip if wait_thread.value.success? + end + rescue SystemCallError, IOError nil end end diff --git a/sentry-ruby/spec/sentry/agent_hint_spec.rb b/sentry-ruby/spec/sentry/agent_hint_spec.rb index b10114fd0..0cb18a97f 100644 --- a/sentry-ruby/spec/sentry/agent_hint_spec.rb +++ b/sentry-ruby/spec/sentry/agent_hint_spec.rb @@ -27,6 +27,7 @@ before do described_class.instance_variable_set(:@hint, nil) described_class.instance_variable_set(:@registered, false) + described_class.instance_variable_set(:@init, nil) allow(described_class).to receive(:at_exit) { |&hook| at_exit_hooks << hook } end @@ -148,24 +149,24 @@ def self.rails_config(structured_logging:) end it "runs git without fsmonitor or optional locks" do - allow(Open3).to receive(:capture2).and_call_original + allow(Open3).to receive(:popen2).and_call_original run_app({ "AI_AGENT" => "claude-code" }) - expect(Open3).to have_received(:capture2) + expect(Open3).to have_received(:popen2) .with("git", "--no-optional-locks", "-c", "core.fsmonitor=false", "status", any_args) end it "does no file or git work outside a coding agent" do expect(File).not_to receive(:realpath) - expect(Open3).not_to receive(:capture2) + expect(Open3).not_to receive(:popen2) expect(run_app({})).to eq("") end it "doesn't raise or print when building the message fails" do load_app({ "AI_AGENT" => "claude-code" }) - allow(Open3).to receive(:capture2).and_raise(IOError, "closed stream") + allow(Open3).to receive(:popen2).and_raise(RuntimeError, "unexpected") expect(capture_stderr { at_exit_hooks.each(&:call) }).to eq("") end @@ -187,6 +188,57 @@ def self.rails_config(structured_logging:) expect(Sentry.initialized?).to be(true) end + it "isn't shown when git is too slow, and stops git", skip: Gem.win_platform? && "needs a shell script as git" do + fake_bin = File.join(@dir, "bin") + child_pid_file = File.join(@dir, "git_child.pid") + Dir.mkdir(fake_bin) + File.write(File.join(fake_bin, "git"), "#!/bin/sh\nsleep 5 &\necho $! > #{child_pid_file}.tmp\nmv #{child_pid_file}.tmp #{child_pid_file}\nwait\n") + File.chmod(0o755, File.join(fake_bin, "git")) + stub_const("#{described_class}::GIT_TIMEOUT", 0.5) + path = ENV["PATH"] + load_app({ "AI_AGENT" => "claude-code", "PATH" => "#{fake_bin}#{File::PATH_SEPARATOR}#{path}" }) + + started = Process.clock_gettime(Process::CLOCK_MONOTONIC) + expect(capture_stderr { at_exit_hooks.each(&:call) }).to eq("") + expect(Process.clock_gettime(Process::CLOCK_MONOTONIC) - started).to be < 2 + + child_pid = Integer(File.read(child_pid_file)) + sleep 0.1 + expect { Process.kill(0, child_pid) }.to raise_error(Errno::ESRCH) + ensure + ENV["PATH"] = path + end + + describe "under Spring" do + it "is shown by a forked command when Spring was started outside the agent" do + load_app({}) + expect(at_exit_hooks).to be_empty + + ENV["AI_AGENT"] = "claude-code" + allow(Process).to receive(:pid).and_return(Process.pid + 1) + described_class.after_fork + + expect(capture_stderr { at_exit_hooks.each(&:call) }).to include(checklist) + end + + it "is shown by the forked command, not only the preloaded app" do + load_app({ "AI_AGENT" => "claude-code" }) + allow(Process).to receive(:pid).and_return(Process.pid + 1) + described_class.after_fork + + expect(capture_stderr { at_exit_hooks.each(&:call) }.scan(checklist).size).to eq(1) + end + + it "isn't shown by a forked command run outside the agent" do + load_app({ "AI_AGENT" => "claude-code" }) + ENV.delete("AI_AGENT") + allow(Process).to receive(:pid).and_return(Process.pid + 1) + described_class.after_fork + + expect(capture_stderr { at_exit_hooks.each(&:call) }).to eq("") + end + end + it "isn't printed by a forked child" do load_app({ "AI_AGENT" => "claude-code" }) allow(Process).to receive(:pid).and_return(Process.pid + 1)