From dd01bfbcc669ea7e7fd4a652503a7be30087016f Mon Sep 17 00:00:00 2001 From: Dan Fuller Date: Mon, 19 Oct 2026 16:17:34 -0700 Subject: [PATCH 01/20] feat(crons): Add GoodJob cron monitoring Sends check-ins for GoodJob cron entries when the :good_job_cron patch is enabled, using the cron key as the slug and the entry's schedule as the monitor config. Keys can be skipped with config.rails.good_job_exclude_cron_jobs. Co-Authored-By: Claude --- sentry-rails/lib/sentry/rails.rb | 1 + .../lib/sentry/rails/configuration.rb | 6 + .../lib/sentry/rails/good_job_cron.rb | 129 ++++++++++++++ .../spec/active_job/good_job_cron_spec.rb | 167 ++++++++++++++++++ 4 files changed, 303 insertions(+) create mode 100644 sentry-rails/lib/sentry/rails/good_job_cron.rb create mode 100644 sentry-rails/spec/active_job/good_job_cron_spec.rb diff --git a/sentry-rails/lib/sentry/rails.rb b/sentry-rails/lib/sentry/rails.rb index 462a035fe..55f625fdc 100644 --- a/sentry-rails/lib/sentry/rails.rb +++ b/sentry-rails/lib/sentry/rails.rb @@ -9,6 +9,7 @@ require "sentry/rails/structured_logging" require "sentry/rails/engine" require "sentry/rails/railtie" +require "sentry/rails/good_job_cron" require "sentry/rails/solid_queue_recurring" module Sentry diff --git a/sentry-rails/lib/sentry/rails/configuration.rb b/sentry-rails/lib/sentry/rails/configuration.rb index ecf899352..9eaab51cd 100644 --- a/sentry-rails/lib/sentry/rails/configuration.rb +++ b/sentry-rails/lib/sentry/rails/configuration.rb @@ -183,6 +183,11 @@ class Configuration # Defaults to true. Set to false to opt out. attr_accessor :active_job_propagate_traces + # GoodJob cron keys to skip when the :good_job_cron patch is enabled. + # Strings and Symbols match the key exactly; Regexps are matched against it. + # @return [Array] + attr_accessor :good_job_exclude_cron_jobs + # Solid Queue recurring task keys to skip when the :solid_queue_recurring patch is enabled. # Strings match the key exactly; Regexps are matched against it. # @return [Array] @@ -210,6 +215,7 @@ def initialize @active_support_logger_subscription_items = Sentry::Rails::ACTIVE_SUPPORT_LOGGER_SUBSCRIPTION_ITEMS_DEFAULT.dup @active_job_report_on_retry_error = false @active_job_propagate_traces = true + @good_job_exclude_cron_jobs = [] @solid_queue_exclude_recurring_tasks = [] @structured_logging = StructuredLoggingConfiguration.new end diff --git a/sentry-rails/lib/sentry/rails/good_job_cron.rb b/sentry-rails/lib/sentry/rails/good_job_cron.rb new file mode 100644 index 000000000..49534aaf6 --- /dev/null +++ b/sentry-rails/lib/sentry/rails/good_job_cron.rb @@ -0,0 +1,129 @@ +# frozen_string_literal: true + +module Sentry + module Rails + # Sends Crons check-ins for GoodJob cron entries. + # Enable with `config.enabled_patches << :good_job_cron`. + module GoodJobCron + PAYLOAD_KEY = "_sentry_good_job_cron" + CURRENT_ENTRY = :sentry_good_job_cron_entry + + module CronEntry + def enqueue(*args) + Thread.current[CURRENT_ENTRY] = self unless Sentry::Rails::GoodJobCron.excluded?(self) + super + ensure + Thread.current[CURRENT_ENTRY] = nil + end + end + + module Job + def serialize + @_sentry_good_job_cron ||= Sentry::Rails::GoodJobCron.monitor_for(Thread.current[CURRENT_ENTRY], self) + payload = super + payload[PAYLOAD_KEY] = @_sentry_good_job_cron if @_sentry_good_job_cron + payload + end + + def deserialize(job_data) + super + @_sentry_good_job_cron = job_data[PAYLOAD_KEY] + end + end + + class << self + def excluded?(entry) + return false unless Sentry.initialized? + + key = entry.key.to_s + Array(Sentry.configuration.rails.good_job_exclude_cron_jobs).any? do |pattern| + (pattern.is_a?(Symbol) ? pattern.to_s : pattern) === key + end + rescue StandardError => e + Sentry.sdk_logger.error(Sentry::LOGGER_PROGNAME) { "Could not check good_job_exclude_cron_jobs for #{entry.key}: #{e.class}: #{e.message}" } + false + end + + # Runs where GoodJob evaluates the schedule, so the time zone matches. + def monitor_for(entry, job) + return unless entry && Sentry.initialized? + + job_class = entry.job_class + return unless job_class.respond_to?(:call) || job.class.name == job_class.to_s.delete_prefix("::") + return if job.class < Sentry::Cron::MonitorCheckIns::Patch + + slug = entry.key.to_s.downcase.gsub(/[^a-z0-9_-]+/, "-").gsub(/\A-+|-+\z/, "") + slug = slug[0, Sentry::Cron::MonitorCheckIns::MAX_SLUG_LENGTH].delete_suffix("-") + return if slug.empty? + + # Entries whose cron is a proc can change schedule between runs. + cron = entry.params[:cron] + config = Sentry::Cron::FugitSchedule.from_cron(::Fugit.parse(cron)) if cron.is_a?(String) + { "slug" => slug, "crontab" => config&.schedule&.value, "timezone" => config&.timezone }.compact + rescue StandardError => e + Sentry.sdk_logger.error(Sentry::LOGGER_PROGNAME) { "Not monitoring GoodJob cron entry #{entry.key}: #{e.class}: #{e.message}" } + nil + end + + def perform(job) + data = job.instance_variable_get(:@_sentry_good_job_cron) + return yield unless data && Sentry.initialized? + + slug = data["slug"] + if data["crontab"] + cron_config = Sentry.configuration.cron + monitor_config = Sentry::Cron::MonitorConfig.from_crontab( + data["crontab"], + timezone: data["timezone"], + checkin_margin: cron_config.default_checkin_margin, + max_runtime: cron_config.default_max_runtime + ) + end + + check_in_id = Sentry.capture_check_in(slug, :in_progress, monitor_config: monitor_config) + start = Process.clock_gettime(Process::CLOCK_MONOTONIC) + + begin + ret = yield + rescue Exception + duration = Process.clock_gettime(Process::CLOCK_MONOTONIC) - start + Sentry.capture_check_in(slug, :error, check_in_id: check_in_id, duration: duration, monitor_config: monitor_config) + raise + end + + duration = Process.clock_gettime(Process::CLOCK_MONOTONIC) - start + Sentry.capture_check_in(slug, :ok, check_in_id: check_in_id, duration: duration, monitor_config: monitor_config) + ret + end + + def patch + return if @patched + + @patched = true + ActiveSupport.on_load(:active_job) do + prepend Sentry::Rails::GoodJobCron::Job + around_perform { |job, block| Sentry::Rails::GoodJobCron.perform(job, &block) } + end + + apply = proc do + # safe_constantize also loads it under the classic autoloader. + entry_class = "GoodJob::CronEntry".safe_constantize + if entry_class && !(entry_class < Sentry::Rails::GoodJobCron::CronEntry) + entry_class.prepend(Sentry::Rails::GoodJobCron::CronEntry) + end + end + ::Rails.application.reloader.to_prepare(&apply) + apply.call if ::Rails.application.initialized? + end + end + end + end +end + +Sentry.register_patch(:good_job_cron) do |config| + if defined?(::GoodJob) && defined?(::Rails.application) && ::Rails.application + Sentry::Rails::GoodJobCron.patch + else + config.sdk_logger.warn(Sentry::LOGGER_PROGNAME) { "You tried to enable the GoodJob cron integration but the `good_job` gem was not detected." } + end +end diff --git a/sentry-rails/spec/active_job/good_job_cron_spec.rb b/sentry-rails/spec/active_job/good_job_cron_spec.rb new file mode 100644 index 000000000..0d1a006af --- /dev/null +++ b/sentry-rails/spec/active_job/good_job_cron_spec.rb @@ -0,0 +1,167 @@ +# frozen_string_literal: true + +require "spec_helper" + +begin + require "good_job" +rescue LoadError +end + +if defined?(::GoodJob) + RSpec.describe Sentry::Rails::GoodJobCron, type: :job do + include_context "active_job backend harness", adapter: :test + include_context "test adapter" + + let(:excluded_jobs) { [] } + let(:configure_sentry) do + proc do |config| + config.enabled_patches << :good_job_cron + config.rails.good_job_exclude_cron_jobs = excluded_jobs + end + end + + # Runs jobs from their full serialized payload, like GoodJob does. + def queue_adapter_for_test + Rails52FullPayloadTestAdapter.new + end + + def drain + jobs = queue_adapter.enqueued_jobs.dup + queue_adapter.enqueued_jobs.clear + jobs.each { |payload| ::ActiveJob::Base.execute(payload[:_sentry_full_payload]) } + end + + def run_entry(key, **params) + GoodJob::CronEntry.new(params.merge(key: key)).enqueue(Time.now) + drain + end + + def check_ins + sentry_events.select { |event| event.is_a?(Sentry::CheckInEvent) } + end + + let(:report_job) do + job_fixture("ReportJob") do + def perform(*); end + end + end + + before { report_job } + + it "sends in_progress and ok check-ins with the cron key and schedule" do + run_entry(:nightly_report, class: "ReportJob", cron: "0 9 * * 1-5 Europe/Vienna") + + in_progress, ok = check_ins + expect(check_ins.size).to eq(2) + expect(in_progress.monitor_slug).to eq("nightly_report") + expect(in_progress.status).to eq(:in_progress) + expect(in_progress.monitor_config.to_h).to eq( + schedule: { type: :crontab, value: "0 9 * * 1-5" }, + timezone: "Europe/Vienna" + ) + expect(ok.status).to eq(:ok) + expect(ok.check_in_id).to eq(in_progress.check_in_id) + end + + it "sends an error check-in when the job fails" do + job_fixture("FailingReportJob") do + def perform + raise "boom" + end + end + + expect { run_entry(:failing_report, class: "FailingReportJob", cron: "every hour") }.to raise_error("boom") + expect(check_ins.map(&:status)).to eq([:in_progress, :error]) + expect(check_ins.first.monitor_config.to_h[:schedule]).to eq(type: :crontab, value: "0 * * * *") + end + + it "uses each entry's key and schedule when entries share a job class" do + run_entry(:report_eu, class: "ReportJob", args: ["eu"], cron: "0 9 * * * Europe/Berlin") + run_entry(:report_us, class: ReportJob, args: ["us"], cron: "0 9 * * * America/New_York") + + in_progress = check_ins.select { |check_in| check_in.status == :in_progress } + expect(in_progress.map { |check_in| [check_in.monitor_slug, check_in.monitor_config.timezone] }).to eq( + [["report_eu", "Europe/Berlin"], ["report_us", "America/New_York"]] + ) + end + + it "uses the zone GoodJob evaluates zoneless schedules in" do + Time.use_zone("Tokyo") do + run_entry(:tokyo_report, class: "ReportJob", cron: "0 9 * * *") + end + + expect(check_ins.first.monitor_config.timezone).to eq("Asia/Tokyo") + end + + it "sends check-ins without a config for schedules Crons cannot express" do + run_entry(:every_ten_seconds, class: "ReportJob", cron: "every 10 seconds") + + expect(check_ins.map(&:status)).to eq([:in_progress, :ok]) + expect(check_ins.map(&:monitor_config)).to all(be_nil) + end + + it "sends check-ins without a config for proc schedules" do + run_entry(:dynamic_report, class: "ReportJob", cron: ->(_last_ran) { "0 9 * * *" }) + + expect(check_ins.map(&:monitor_slug)).to eq(["dynamic_report", "dynamic_report"]) + expect(check_ins.map(&:monitor_config)).to all(be_nil) + end + + it "leaves jobs that include Sentry::Cron::MonitorCheckIns alone" do + job_fixture("MonitoredJob") do + include Sentry::Cron::MonitorCheckIns + sentry_monitor_check_ins slug: "own-slug" + + def perform; end + end + + run_entry(:monitored, class: "MonitoredJob", cron: "0 9 * * *") + + expect(check_ins.map(&:monitor_slug)).to eq(["own-slug", "own-slug"]) + end + + it "does not monitor jobs enqueued outside a cron entry" do + report_job.perform_later + drain + + expect(check_ins).to be_empty + end + + it "excludes nothing by default" do + expect(Sentry.configuration.rails.good_job_exclude_cron_jobs).to eq([]) + end + + context "with excluded jobs" do + let(:excluded_jobs) { [:clear_cache, "purge", /\Atmp_/] } + + it "skips entries whose key matches a symbol or string" do + run_entry(:clear_cache, class: "ReportJob", cron: "0 9 * * *") + run_entry(:purge, class: "ReportJob", cron: "0 9 * * *") + + expect(check_ins).to be_empty + end + + it "skips entries whose key matches a regexp" do + run_entry(:tmp_cleanup, class: "ReportJob", cron: "0 9 * * *") + + expect(check_ins).to be_empty + end + + it "monitors entries that do not match" do + run_entry(:clear_cache_daily, class: "ReportJob", cron: "0 9 * * *") + + expect(check_ins.map(&:monitor_slug)).to eq(["clear_cache_daily", "clear_cache_daily"]) + end + end + + context "with an exclusion pattern that raises" do + let(:excluded_jobs) { [->(_key) { raise "boom" }] } + + it "still enqueues and monitors the job" do + run_entry(:daily_report, class: "ReportJob", cron: "0 9 * * *") + + expect(check_ins.map(&:monitor_slug)).to eq(["daily_report", "daily_report"]) + end + end + end +end From 0f3b4461ec3e562e877b33e1020c1199a5cdc2f0 Mon Sep 17 00:00:00 2001 From: Dan Fuller Date: Tue, 20 Oct 2026 10:44:37 -0700 Subject: [PATCH 02/20] test(crons): Cover GoodJob cron retries Co-Authored-By: Claude --- .../spec/active_job/good_job_cron_spec.rb | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/sentry-rails/spec/active_job/good_job_cron_spec.rb b/sentry-rails/spec/active_job/good_job_cron_spec.rb index 0d1a006af..ea500b38a 100644 --- a/sentry-rails/spec/active_job/good_job_cron_spec.rb +++ b/sentry-rails/spec/active_job/good_job_cron_spec.rb @@ -75,6 +75,23 @@ def perform expect(check_ins.first.monitor_config.to_h[:schedule]).to eq(type: :crontab, value: "0 * * * *") end + it "checks in again when a failed run is retried" do + job_fixture("FlakyReportJob") do + retry_on RuntimeError, wait: 0, attempts: 2 + + def perform + raise "boom" if executions == 1 + end + end + + run_entry(:flaky_report, class: "FlakyReportJob", cron: "0 9 * * *") + drain + + expect(check_ins.map(&:status)).to eq([:in_progress, :error, :in_progress, :ok]) + expect(check_ins.map(&:monitor_slug).uniq).to eq(["flaky_report"]) + expect(check_ins[2].monitor_config.to_h[:schedule]).to eq(type: :crontab, value: "0 9 * * *") + end + it "uses each entry's key and schedule when entries share a job class" do run_entry(:report_eu, class: "ReportJob", args: ["eu"], cron: "0 9 * * * Europe/Berlin") run_entry(:report_us, class: ReportJob, args: ["us"], cron: "0 9 * * * America/New_York") From 684faf3779fe72602ef5df5107127fa0b487c78c Mon Sep 17 00:00:00 2001 From: Dan Fuller Date: Wed, 21 Oct 2026 14:43:19 -0700 Subject: [PATCH 03/20] ref(crons): Use the shared slug helper Co-Authored-By: Claude --- sentry-rails/lib/sentry/rails/good_job_cron.rb | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/sentry-rails/lib/sentry/rails/good_job_cron.rb b/sentry-rails/lib/sentry/rails/good_job_cron.rb index 49534aaf6..386d56347 100644 --- a/sentry-rails/lib/sentry/rails/good_job_cron.rb +++ b/sentry-rails/lib/sentry/rails/good_job_cron.rb @@ -52,9 +52,8 @@ def monitor_for(entry, job) return unless job_class.respond_to?(:call) || job.class.name == job_class.to_s.delete_prefix("::") return if job.class < Sentry::Cron::MonitorCheckIns::Patch - slug = entry.key.to_s.downcase.gsub(/[^a-z0-9_-]+/, "-").gsub(/\A-+|-+\z/, "") - slug = slug[0, Sentry::Cron::MonitorCheckIns::MAX_SLUG_LENGTH].delete_suffix("-") - return if slug.empty? + slug = Sentry::Cron::Slug.from(entry.key) + return unless slug # Entries whose cron is a proc can change schedule between runs. cron = entry.params[:cron] From db9a9cab8416faf615b3c45c3e2467984003f305 Mon Sep 17 00:00:00 2001 From: Dan Fuller Date: Wed, 28 Oct 2026 17:39:10 -0700 Subject: [PATCH 04/20] ref(crons): Use the shared check-in helper for GoodJob cron --- sentry-rails/lib/sentry/rails/good_job_cron.rb | 15 +-------------- 1 file changed, 1 insertion(+), 14 deletions(-) diff --git a/sentry-rails/lib/sentry/rails/good_job_cron.rb b/sentry-rails/lib/sentry/rails/good_job_cron.rb index 386d56347..9e9cea4d8 100644 --- a/sentry-rails/lib/sentry/rails/good_job_cron.rb +++ b/sentry-rails/lib/sentry/rails/good_job_cron.rb @@ -79,20 +79,7 @@ def perform(job) ) end - check_in_id = Sentry.capture_check_in(slug, :in_progress, monitor_config: monitor_config) - start = Process.clock_gettime(Process::CLOCK_MONOTONIC) - - begin - ret = yield - rescue Exception - duration = Process.clock_gettime(Process::CLOCK_MONOTONIC) - start - Sentry.capture_check_in(slug, :error, check_in_id: check_in_id, duration: duration, monitor_config: monitor_config) - raise - end - - duration = Process.clock_gettime(Process::CLOCK_MONOTONIC) - start - Sentry.capture_check_in(slug, :ok, check_in_id: check_in_id, duration: duration, monitor_config: monitor_config) - ret + Sentry::Cron::MonitorCheckIns.with_check_in(slug, monitor_config: monitor_config) { yield } end def patch From 368e0b72894dd97f70457253968a8f1075ff4ca5 Mon Sep 17 00:00:00 2001 From: Dan Fuller Date: Thu, 29 Oct 2026 11:01:15 -0700 Subject: [PATCH 05/20] fix(rails): Skip jobs with unsupported schedules when monitoring all jobs --- sentry-rails/lib/sentry/rails/good_job_cron.rb | 4 +++- sentry-rails/spec/active_job/good_job_cron_spec.rb | 10 ++++------ 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/sentry-rails/lib/sentry/rails/good_job_cron.rb b/sentry-rails/lib/sentry/rails/good_job_cron.rb index 9e9cea4d8..428785d4e 100644 --- a/sentry-rails/lib/sentry/rails/good_job_cron.rb +++ b/sentry-rails/lib/sentry/rails/good_job_cron.rb @@ -58,7 +58,9 @@ def monitor_for(entry, job) # Entries whose cron is a proc can change schedule between runs. cron = entry.params[:cron] config = Sentry::Cron::FugitSchedule.from_cron(::Fugit.parse(cron)) if cron.is_a?(String) - { "slug" => slug, "crontab" => config&.schedule&.value, "timezone" => config&.timezone }.compact + return unless config + + { "slug" => slug, "crontab" => config.schedule.value, "timezone" => config.timezone }.compact rescue StandardError => e Sentry.sdk_logger.error(Sentry::LOGGER_PROGNAME) { "Not monitoring GoodJob cron entry #{entry.key}: #{e.class}: #{e.message}" } nil diff --git a/sentry-rails/spec/active_job/good_job_cron_spec.rb b/sentry-rails/spec/active_job/good_job_cron_spec.rb index ea500b38a..d5cca81e6 100644 --- a/sentry-rails/spec/active_job/good_job_cron_spec.rb +++ b/sentry-rails/spec/active_job/good_job_cron_spec.rb @@ -110,18 +110,16 @@ def perform expect(check_ins.first.monitor_config.timezone).to eq("Asia/Tokyo") end - it "sends check-ins without a config for schedules Crons cannot express" do + it "skips schedules Crons cannot express" do run_entry(:every_ten_seconds, class: "ReportJob", cron: "every 10 seconds") - expect(check_ins.map(&:status)).to eq([:in_progress, :ok]) - expect(check_ins.map(&:monitor_config)).to all(be_nil) + expect(check_ins).to be_empty end - it "sends check-ins without a config for proc schedules" do + it "skips proc schedules" do run_entry(:dynamic_report, class: "ReportJob", cron: ->(_last_ran) { "0 9 * * *" }) - expect(check_ins.map(&:monitor_slug)).to eq(["dynamic_report", "dynamic_report"]) - expect(check_ins.map(&:monitor_config)).to all(be_nil) + expect(check_ins).to be_empty end it "leaves jobs that include Sentry::Cron::MonitorCheckIns alone" do From ce1016f99f4296b1e7ee2fa7c9b6a40219eee6d1 Mon Sep 17 00:00:00 2001 From: Dan Fuller Date: Wed, 11 Nov 2026 10:29:14 -0800 Subject: [PATCH 06/20] fix(crons): Skip GoodJob cron entries whose slugs collide Keys that map to the same slug, like long keys cut at 50 characters, would share one monitor with two schedules. Skip all of them and warn, and log at debug level when a schedule can't be expressed. Co-Authored-By: Claude --- .../lib/sentry/rails/good_job_cron.rb | 53 +++++++++++++------ .../spec/active_job/good_job_cron_spec.rb | 46 ++++++++++++++++ 2 files changed, 83 insertions(+), 16 deletions(-) diff --git a/sentry-rails/lib/sentry/rails/good_job_cron.rb b/sentry-rails/lib/sentry/rails/good_job_cron.rb index 428785d4e..805f92599 100644 --- a/sentry-rails/lib/sentry/rails/good_job_cron.rb +++ b/sentry-rails/lib/sentry/rails/good_job_cron.rb @@ -10,7 +10,7 @@ module GoodJobCron module CronEntry def enqueue(*args) - Thread.current[CURRENT_ENTRY] = self unless Sentry::Rails::GoodJobCron.excluded?(self) + Thread.current[CURRENT_ENTRY] = self unless Sentry::Rails::GoodJobCron.excluded?(key) super ensure Thread.current[CURRENT_ENTRY] = nil @@ -32,15 +32,15 @@ def deserialize(job_data) end class << self - def excluded?(entry) + def excluded?(key) return false unless Sentry.initialized? - key = entry.key.to_s + key = key.to_s Array(Sentry.configuration.rails.good_job_exclude_cron_jobs).any? do |pattern| (pattern.is_a?(Symbol) ? pattern.to_s : pattern) === key end rescue StandardError => e - Sentry.sdk_logger.error(Sentry::LOGGER_PROGNAME) { "Could not check good_job_exclude_cron_jobs for #{entry.key}: #{e.class}: #{e.message}" } + Sentry.sdk_logger.error(Sentry::LOGGER_PROGNAME) { "Could not check good_job_exclude_cron_jobs for #{key}: #{e.class}: #{e.message}" } false end @@ -54,11 +54,15 @@ def monitor_for(entry, job) slug = Sentry::Cron::Slug.from(entry.key) return unless slug + return if slug_shared?(entry.key, slug) # Entries whose cron is a proc can change schedule between runs. cron = entry.params[:cron] config = Sentry::Cron::FugitSchedule.from_cron(::Fugit.parse(cron)) if cron.is_a?(String) - return unless config + unless config + Sentry.sdk_logger.debug(Sentry::LOGGER_PROGNAME) { "Not monitoring GoodJob cron entry #{entry.key}: its schedule can't be expressed as a Crons schedule." } + return + end { "slug" => slug, "crontab" => config.schedule.value, "timezone" => config.timezone }.compact rescue StandardError => e @@ -70,18 +74,17 @@ def perform(job) data = job.instance_variable_get(:@_sentry_good_job_cron) return yield unless data && Sentry.initialized? - slug = data["slug"] - if data["crontab"] - cron_config = Sentry.configuration.cron - monitor_config = Sentry::Cron::MonitorConfig.from_crontab( - data["crontab"], - timezone: data["timezone"], - checkin_margin: cron_config.default_checkin_margin, - max_runtime: cron_config.default_max_runtime - ) - end + return yield unless data["crontab"] + + cron_config = Sentry.configuration.cron + monitor_config = Sentry::Cron::MonitorConfig.from_crontab( + data["crontab"], + timezone: data["timezone"], + checkin_margin: cron_config.default_checkin_margin, + max_runtime: cron_config.default_max_runtime + ) - Sentry::Cron::MonitorCheckIns.with_check_in(slug, monitor_config: monitor_config) { yield } + Sentry::Cron::MonitorCheckIns.with_check_in(data["slug"], monitor_config: monitor_config) { yield } end def patch @@ -103,6 +106,24 @@ def patch ::Rails.application.reloader.to_prepare(&apply) apply.call if ::Rails.application.initialized? end + + private + + # Different keys can share a slug, like long keys cut at the same length. + # One monitor can't follow two schedules, so none of them are monitored. + def slug_shared?(key, slug) + others = ::GoodJob.configuration.cron.keys.reject { |other| other.to_s == key.to_s || excluded?(other) } + colliding = others.select { |other| Sentry::Cron::Slug.from(other) == slug } + return false if colliding.empty? + + @slug_warnings ||= Concurrent::Map.new + if @slug_warnings.put_if_absent(key.to_s, true).nil? + Sentry.sdk_logger.warn(Sentry::LOGGER_PROGNAME) do + "Not monitoring GoodJob cron entry #{key}: its monitor slug #{slug} is also used by #{colliding.join(", ")}. Rename or exclude one of them." + end + end + true + end end end end diff --git a/sentry-rails/spec/active_job/good_job_cron_spec.rb b/sentry-rails/spec/active_job/good_job_cron_spec.rb index d5cca81e6..8a95b07b6 100644 --- a/sentry-rails/spec/active_job/good_job_cron_spec.rb +++ b/sentry-rails/spec/active_job/good_job_cron_spec.rb @@ -169,6 +169,52 @@ def perform; end end end + context "with cron keys that share a slug" do + let(:long_key) { "sync_salesforce_accounts_with_the_billing_provider" } + let(:cron) do + { + "#{long_key}_daily": { class: "ReportJob", cron: "0 9 * * *" }, + "#{long_key}_weekly": { class: "ReportJob", cron: "0 9 * * 1" }, + nightly_report: { class: "ReportJob", cron: "0 2 * * *" } + } + end + + around do |example| + configuration = GoodJob.configuration + GoodJob.configuration = GoodJob::Configuration.new({ cron: cron }) + example.run + ensure + GoodJob.configuration = configuration + end + + def run_configured(key) + GoodJob::CronEntry.find(key).enqueue(Time.now) + drain + end + + it "skips all of them and warns" do + string_io = StringIO.new + Sentry.configuration.sdk_logger = ::Logger.new(string_io) + + run_configured(:"#{long_key}_daily") + run_configured(:"#{long_key}_weekly") + run_configured(:nightly_report) + + expect(check_ins.map(&:monitor_slug).uniq).to eq(["nightly_report"]) + expect(string_io.string).to include("Not monitoring GoodJob cron entry #{long_key}_daily", "#{long_key}_weekly") + end + + context "when one of them is excluded" do + let(:excluded_jobs) { [:"#{long_key}_weekly"] } + + it "monitors the other" do + run_configured(:"#{long_key}_daily") + + expect(check_ins.map(&:monitor_slug).uniq).to eq([long_key]) + end + end + end + context "with an exclusion pattern that raises" do let(:excluded_jobs) { [->(_key) { raise "boom" }] } From 5a00e9ae36552051c9b9f68501b434f7ceac8973 Mon Sep 17 00:00:00 2001 From: Dan Fuller Date: Wed, 11 Nov 2026 11:40:33 -0800 Subject: [PATCH 07/20] fix(crons): Read GoodJob's own cron key to find the entry GoodJob sets its cron key only while an entry enqueues and clears it while jobs run, so a job a cron job enqueues inline isn't tagged. Zoneless schedules use the app's time zone rather than whatever zone the enqueue runs under. --- .../lib/sentry/rails/good_job_cron.rb | 48 +++++------ .../spec/active_job/good_job_cron_spec.rb | 84 ++++++++++++++----- 2 files changed, 82 insertions(+), 50 deletions(-) diff --git a/sentry-rails/lib/sentry/rails/good_job_cron.rb b/sentry-rails/lib/sentry/rails/good_job_cron.rb index 805f92599..5133bca1a 100644 --- a/sentry-rails/lib/sentry/rails/good_job_cron.rb +++ b/sentry-rails/lib/sentry/rails/good_job_cron.rb @@ -6,20 +6,10 @@ module Rails # Enable with `config.enabled_patches << :good_job_cron`. module GoodJobCron PAYLOAD_KEY = "_sentry_good_job_cron" - CURRENT_ENTRY = :sentry_good_job_cron_entry - - module CronEntry - def enqueue(*args) - Thread.current[CURRENT_ENTRY] = self unless Sentry::Rails::GoodJobCron.excluded?(key) - super - ensure - Thread.current[CURRENT_ENTRY] = nil - end - end module Job def serialize - @_sentry_good_job_cron ||= Sentry::Rails::GoodJobCron.monitor_for(Thread.current[CURRENT_ENTRY], self) + @_sentry_good_job_cron ||= Sentry::Rails::GoodJobCron.monitor_for(self) payload = super payload[PAYLOAD_KEY] = @_sentry_good_job_cron if @_sentry_good_job_cron payload @@ -44,11 +34,15 @@ def excluded?(key) false end - # Runs where GoodJob evaluates the schedule, so the time zone matches. - def monitor_for(entry, job) - return unless entry && Sentry.initialized? + # GoodJob sets the cron key while an entry enqueues its job and clears it while jobs run. + def monitor_for(job) + key = ::GoodJob::CurrentThread.cron_key + return unless key && Sentry.initialized? + return if excluded?(key) + entry = ::GoodJob::CronEntry.find(key) job_class = entry.job_class + # A callable class can't be checked without calling it again. return unless job_class.respond_to?(:call) || job.class.name == job_class.to_s.delete_prefix("::") return if job.class < Sentry::Cron::MonitorCheckIns::Patch @@ -56,9 +50,7 @@ def monitor_for(entry, job) return unless slug return if slug_shared?(entry.key, slug) - # Entries whose cron is a proc can change schedule between runs. - cron = entry.params[:cron] - config = Sentry::Cron::FugitSchedule.from_cron(::Fugit.parse(cron)) if cron.is_a?(String) + config = schedule_for(entry) unless config Sentry.sdk_logger.debug(Sentry::LOGGER_PROGNAME) { "Not monitoring GoodJob cron entry #{entry.key}: its schedule can't be expressed as a Crons schedule." } return @@ -66,7 +58,7 @@ def monitor_for(entry, job) { "slug" => slug, "crontab" => config.schedule.value, "timezone" => config.timezone }.compact rescue StandardError => e - Sentry.sdk_logger.error(Sentry::LOGGER_PROGNAME) { "Not monitoring GoodJob cron entry #{entry.key}: #{e.class}: #{e.message}" } + Sentry.sdk_logger.error(Sentry::LOGGER_PROGNAME) { "Not monitoring GoodJob cron entry #{key}: #{e.class}: #{e.message}" } nil end @@ -95,20 +87,20 @@ def patch prepend Sentry::Rails::GoodJobCron::Job around_perform { |job, block| Sentry::Rails::GoodJobCron.perform(job, &block) } end - - apply = proc do - # safe_constantize also loads it under the classic autoloader. - entry_class = "GoodJob::CronEntry".safe_constantize - if entry_class && !(entry_class < Sentry::Rails::GoodJobCron::CronEntry) - entry_class.prepend(Sentry::Rails::GoodJobCron::CronEntry) - end - end - ::Rails.application.reloader.to_prepare(&apply) - apply.call if ::Rails.application.initialized? end private + # Entries whose cron is a proc can change schedule between runs. GoodJob's + # scheduler threads read zoneless schedules in the app's time zone, which + # an enqueue from a request using Time.use_zone wouldn't see. + def schedule_for(entry) + cron = entry.params[:cron] + return unless cron.is_a?(String) + + Time.use_zone(Time.zone_default) { Sentry::Cron::FugitSchedule.from_cron(::Fugit.parse(cron)) } + end + # Different keys can share a slug, like long keys cut at the same length. # One monitor can't follow two schedules, so none of them are monitored. def slug_shared?(key, slug) diff --git a/sentry-rails/spec/active_job/good_job_cron_spec.rb b/sentry-rails/spec/active_job/good_job_cron_spec.rb index 8a95b07b6..8a83935a6 100644 --- a/sentry-rails/spec/active_job/good_job_cron_spec.rb +++ b/sentry-rails/spec/active_job/good_job_cron_spec.rb @@ -13,6 +13,7 @@ include_context "test adapter" let(:excluded_jobs) { [] } + let(:cron) { {} } let(:configure_sentry) do proc do |config| config.enabled_patches << :good_job_cron @@ -31,8 +32,17 @@ def drain jobs.each { |payload| ::ActiveJob::Base.execute(payload[:_sentry_full_payload]) } end + around do |example| + configuration = GoodJob.configuration + GoodJob.configuration = GoodJob::Configuration.new({ cron: cron }) + example.run + ensure + GoodJob.configuration = configuration + end + def run_entry(key, **params) - GoodJob::CronEntry.new(params.merge(key: key)).enqueue(Time.now) + cron[key] = params unless params.empty? + GoodJob::CronEntry.find(key).enqueue(Time.now) drain end @@ -102,12 +112,24 @@ def perform ) end - it "uses the zone GoodJob evaluates zoneless schedules in" do - Time.use_zone("Tokyo") do - run_entry(:tokyo_report, class: "ReportJob", cron: "0 9 * * *") + context "with an app time zone" do + around do |example| + zone_default = Time.zone_default + tz = ENV.delete("TZ") + Time.zone_default = Time.find_zone!("Asia/Tokyo") + example.run + ensure + Time.zone_default = zone_default + ENV["TZ"] = tz end - expect(check_ins.first.monitor_config.timezone).to eq("Asia/Tokyo") + it "uses it for zoneless schedules, whatever zone the enqueue runs in" do + Time.use_zone("America/Chicago") do + run_entry(:tokyo_report, class: "ReportJob", cron: "0 9 * * *") + end + + expect(check_ins.first.monitor_config.timezone).to eq("Asia/Tokyo") + end end it "skips schedules Crons cannot express" do @@ -135,6 +157,37 @@ def perform; end expect(check_ins.map(&:monitor_slug)).to eq(["own-slug", "own-slug"]) end + context "when GoodJob runs jobs inline" do + # GoodJob's inline mode runs the job inside the cron enqueue and resets its thread state first. + def queue_adapter_for_test + Class.new(::ActiveJob::QueueAdapters::TestAdapter) do + def enqueue(job) + payload = job.serialize + ::GoodJob::CurrentThread.within do |thread| + thread.reset + ::ActiveJob::Base.execute(payload) + end + end + + def enqueue_at(job, _timestamp) + enqueue(job) + end + end.new + end + + it "does not monitor a job the cron job enqueues of its own class" do + job_fixture("ChainedReportJob") do + def perform(again = true) + self.class.perform_later(false) if again + end + end + + run_entry(:chained_report, class: "ChainedReportJob", cron: "0 9 * * *") + + expect(check_ins.map(&:status)).to eq([:in_progress, :ok]) + end + end + it "does not monitor jobs enqueued outside a cron entry" do report_job.perform_later drain @@ -179,26 +232,13 @@ def perform; end } end - around do |example| - configuration = GoodJob.configuration - GoodJob.configuration = GoodJob::Configuration.new({ cron: cron }) - example.run - ensure - GoodJob.configuration = configuration - end - - def run_configured(key) - GoodJob::CronEntry.find(key).enqueue(Time.now) - drain - end - it "skips all of them and warns" do string_io = StringIO.new Sentry.configuration.sdk_logger = ::Logger.new(string_io) - run_configured(:"#{long_key}_daily") - run_configured(:"#{long_key}_weekly") - run_configured(:nightly_report) + run_entry(:"#{long_key}_daily") + run_entry(:"#{long_key}_weekly") + run_entry(:nightly_report) expect(check_ins.map(&:monitor_slug).uniq).to eq(["nightly_report"]) expect(string_io.string).to include("Not monitoring GoodJob cron entry #{long_key}_daily", "#{long_key}_weekly") @@ -208,7 +248,7 @@ def run_configured(key) let(:excluded_jobs) { [:"#{long_key}_weekly"] } it "monitors the other" do - run_configured(:"#{long_key}_daily") + run_entry(:"#{long_key}_daily") expect(check_ins.map(&:monitor_slug).uniq).to eq([long_key]) end From afe5f49ef1644481ac5418281e24a25c82f60733 Mon Sep 17 00:00:00 2001 From: Dan Fuller Date: Wed, 11 Nov 2026 11:41:23 -0800 Subject: [PATCH 08/20] fix(crons): Only count monitored GoodJob entries as slug collisions Excluded entries, unconvertible or proc schedules, and jobs that call sentry_monitor_check_ins don't send check-ins for the slug, so they shouldn't stop another entry from being monitored. The schedule check runs first so unmonitorable entries don't get the rename warning. --- .../lib/sentry/rails/good_job_cron.rb | 15 +++++++-- .../spec/active_job/good_job_cron_spec.rb | 33 +++++++++++++++++++ 2 files changed, 45 insertions(+), 3 deletions(-) diff --git a/sentry-rails/lib/sentry/rails/good_job_cron.rb b/sentry-rails/lib/sentry/rails/good_job_cron.rb index 5133bca1a..97f3aa20b 100644 --- a/sentry-rails/lib/sentry/rails/good_job_cron.rb +++ b/sentry-rails/lib/sentry/rails/good_job_cron.rb @@ -48,13 +48,13 @@ def monitor_for(job) slug = Sentry::Cron::Slug.from(entry.key) return unless slug - return if slug_shared?(entry.key, slug) config = schedule_for(entry) unless config Sentry.sdk_logger.debug(Sentry::LOGGER_PROGNAME) { "Not monitoring GoodJob cron entry #{entry.key}: its schedule can't be expressed as a Crons schedule." } return end + return if slug_shared?(entry.key, slug) { "slug" => slug, "crontab" => config.schedule.value, "timezone" => config.timezone }.compact rescue StandardError => e @@ -104,8 +104,9 @@ def schedule_for(entry) # Different keys can share a slug, like long keys cut at the same length. # One monitor can't follow two schedules, so none of them are monitored. def slug_shared?(key, slug) - others = ::GoodJob.configuration.cron.keys.reject { |other| other.to_s == key.to_s || excluded?(other) } - colliding = others.select { |other| Sentry::Cron::Slug.from(other) == slug } + colliding = ::GoodJob::CronEntry.all.select do |other| + other.key.to_s != key.to_s && Sentry::Cron::Slug.from(other.key) == slug && monitored?(other) + end.map(&:key) return false if colliding.empty? @slug_warnings ||= Concurrent::Map.new @@ -116,6 +117,14 @@ def slug_shared?(key, slug) end true end + + def monitored?(entry) + return false if excluded?(entry.key) || !schedule_for(entry) + + job_class = entry.job_class + job_class = job_class.safe_constantize if job_class.is_a?(String) + !(job_class.is_a?(Class) && job_class < Sentry::Cron::MonitorCheckIns::Patch) + end end end end diff --git a/sentry-rails/spec/active_job/good_job_cron_spec.rb b/sentry-rails/spec/active_job/good_job_cron_spec.rb index 8a83935a6..d3b69772e 100644 --- a/sentry-rails/spec/active_job/good_job_cron_spec.rb +++ b/sentry-rails/spec/active_job/good_job_cron_spec.rb @@ -244,6 +244,39 @@ def perform(again = true) expect(string_io.string).to include("Not monitoring GoodJob cron entry #{long_key}_daily", "#{long_key}_weekly") end + context "when the others sharing its slug aren't monitored" do + let(:excluded_jobs) { [:"#{long_key}_weekly"] } + let(:cron) do + { + "#{long_key}_daily": { class: "ReportJob", cron: "0 9 * * *" }, + "#{long_key}_weekly": { class: "ReportJob", cron: "0 9 * * 1" }, + "#{long_key}_fast": { class: "ReportJob", cron: "every 10 seconds" }, + "#{long_key}_dynamic": { class: "ReportJob", cron: ->(_last_ran) { "0 9 * * *" } }, + "#{long_key}_self": { class: "SelfMonitoredJob", cron: "0 9 * * *" } + } + end + + before do + job_fixture("SelfMonitoredJob") do + include Sentry::Cron::MonitorCheckIns + sentry_monitor_check_ins slug: "self-monitored" + + def perform; end + end + end + + it "monitors it and doesn't warn about the others" do + string_io = StringIO.new + Sentry.configuration.sdk_logger = ::Logger.new(string_io) + + run_entry(:"#{long_key}_daily") + run_entry(:"#{long_key}_fast") + + expect(check_ins.map(&:monitor_slug)).to eq([long_key, long_key]) + expect(string_io.string).not_to include("Rename or exclude") + end + end + context "when one of them is excluded" do let(:excluded_jobs) { [:"#{long_key}_weekly"] } From 3bdef46dd1ef107ee0f046cac5bbbd4383c69606 Mon Sep 17 00:00:00 2001 From: Dan Fuller Date: Wed, 11 Nov 2026 11:41:33 -0800 Subject: [PATCH 09/20] ref(crons): Drop GoodJob cron guards monitor_for already covers FugitSchedule.from_cron only returns a config with both a crontab and a time zone. --- sentry-rails/lib/sentry/rails/good_job_cron.rb | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/sentry-rails/lib/sentry/rails/good_job_cron.rb b/sentry-rails/lib/sentry/rails/good_job_cron.rb index 97f3aa20b..f78a0bc07 100644 --- a/sentry-rails/lib/sentry/rails/good_job_cron.rb +++ b/sentry-rails/lib/sentry/rails/good_job_cron.rb @@ -56,7 +56,7 @@ def monitor_for(job) end return if slug_shared?(entry.key, slug) - { "slug" => slug, "crontab" => config.schedule.value, "timezone" => config.timezone }.compact + { "slug" => slug, "crontab" => config.schedule.value, "timezone" => config.timezone } rescue StandardError => e Sentry.sdk_logger.error(Sentry::LOGGER_PROGNAME) { "Not monitoring GoodJob cron entry #{key}: #{e.class}: #{e.message}" } nil @@ -66,8 +66,6 @@ def perform(job) data = job.instance_variable_get(:@_sentry_good_job_cron) return yield unless data && Sentry.initialized? - return yield unless data["crontab"] - cron_config = Sentry.configuration.cron monitor_config = Sentry::Cron::MonitorConfig.from_crontab( data["crontab"], From 7aded6cb64e04fcd1cce0f223314a0e0ed1d2624 Mon Sep 17 00:00:00 2001 From: Dan Fuller Date: Wed, 11 Nov 2026 11:42:00 -0800 Subject: [PATCH 10/20] test(crons): Cover more GoodJob cron entry cases Other jobs enqueued during a cron enqueue, a failure while building the monitor, callable classes, unconfigured MonitorCheckIns, and a nil exclude list. --- .../spec/active_job/good_job_cron_spec.rb | 58 +++++++++++++++++++ 1 file changed, 58 insertions(+) diff --git a/sentry-rails/spec/active_job/good_job_cron_spec.rb b/sentry-rails/spec/active_job/good_job_cron_spec.rb index d3b69772e..45077daa0 100644 --- a/sentry-rails/spec/active_job/good_job_cron_spec.rb +++ b/sentry-rails/spec/active_job/good_job_cron_spec.rb @@ -157,6 +157,54 @@ def perform; end expect(check_ins.map(&:monitor_slug)).to eq(["own-slug", "own-slug"]) end + it "monitors jobs that include Sentry::Cron::MonitorCheckIns without configuring it" do + job_fixture("UnconfiguredJob") do + include Sentry::Cron::MonitorCheckIns + + def perform; end + end + + run_entry(:unconfigured, class: "UnconfiguredJob", cron: "0 9 * * *") + + expect(check_ins.map(&:monitor_slug)).to eq(["unconfigured", "unconfigured"]) + end + + it "monitors entries whose class is callable" do + skip "GoodJob #{GoodJob::VERSION} has no callable classes" if Gem::Version.new(GoodJob::VERSION) < Gem::Version.new("4.19.3") + + run_entry(:callable_report, class: -> { ReportJob }, cron: "0 9 * * *") + + expect(check_ins.map(&:monitor_slug)).to eq(["callable_report", "callable_report"]) + end + + it "does not monitor other jobs enqueued while an entry enqueues" do + job_fixture("AuditJob") do + def perform; end + end + job_fixture("AuditedReportJob") do + before_enqueue { AuditJob.perform_later } + + def perform; end + end + + run_entry(:audited_report, class: "AuditedReportJob", cron: "0 9 * * *") + + expect(check_ins.map(&:monitor_slug)).to eq(["audited_report", "audited_report"]) + end + + it "still enqueues the job when monitoring it fails" do + string_io = StringIO.new + Sentry.configuration.sdk_logger = ::Logger.new(string_io) + + # find raises for an entry missing from GoodJob's configuration. + GoodJob::CronEntry.new(key: :unlisted_report, class: "ReportJob", cron: "0 9 * * *").enqueue(Time.now) + + expect(queue_adapter.enqueued_jobs.size).to eq(1) + drain + expect(check_ins).to be_empty + expect(string_io.string).to include("Not monitoring GoodJob cron entry unlisted_report") + end + context "when GoodJob runs jobs inline" do # GoodJob's inline mode runs the job inside the cron enqueue and resets its thread state first. def queue_adapter_for_test @@ -288,6 +336,16 @@ def perform; end end end + context "with no excluded jobs set" do + let(:excluded_jobs) { nil } + + it "monitors the entry" do + run_entry(:daily_report, class: "ReportJob", cron: "0 9 * * *") + + expect(check_ins.map(&:monitor_slug)).to eq(["daily_report", "daily_report"]) + end + end + context "with an exclusion pattern that raises" do let(:excluded_jobs) { [->(_key) { raise "boom" }] } From 8fb361e054227c19661db3ab7755dcfb45720e88 Mon Sep 17 00:00:00 2001 From: Peter Solnica Date: Thu, 12 Nov 2026 12:58:58 +0000 Subject: [PATCH 11/20] fix(rails): Skip GoodJob cron check-ins for concurrency-rejected runs --- .../lib/sentry/rails/good_job_cron.rb | 9 ++- .../spec/active_job/good_job_cron_spec.rb | 72 +++++++++++++++++++ 2 files changed, 80 insertions(+), 1 deletion(-) diff --git a/sentry-rails/lib/sentry/rails/good_job_cron.rb b/sentry-rails/lib/sentry/rails/good_job_cron.rb index f78a0bc07..faf6ac6c6 100644 --- a/sentry-rails/lib/sentry/rails/good_job_cron.rb +++ b/sentry-rails/lib/sentry/rails/good_job_cron.rb @@ -18,9 +18,17 @@ def serialize def deserialize(job_data) super @_sentry_good_job_cron = job_data[PAYLOAD_KEY] + singleton_class.prepend(Perform) if @_sentry_good_job_cron end end + module Perform + def perform(*args, &block) + Sentry::Rails::GoodJobCron.perform(self) { super(*args, &block) } + end + ruby2_keywords(:perform) + end + class << self def excluded?(key) return false unless Sentry.initialized? @@ -83,7 +91,6 @@ def patch @patched = true ActiveSupport.on_load(:active_job) do prepend Sentry::Rails::GoodJobCron::Job - around_perform { |job, block| Sentry::Rails::GoodJobCron.perform(job, &block) } end end diff --git a/sentry-rails/spec/active_job/good_job_cron_spec.rb b/sentry-rails/spec/active_job/good_job_cron_spec.rb index 45077daa0..50a3c067d 100644 --- a/sentry-rails/spec/active_job/good_job_cron_spec.rb +++ b/sentry-rails/spec/active_job/good_job_cron_spec.rb @@ -356,4 +356,76 @@ def perform; end end end end + + if RAILS_VERSION >= 7.1 + RSpec.describe "Sentry::Rails::GoodJobCron on a GoodJob database", type: :job do + include_context "active_job backend harness", adapter: :good_job + include_context "good_job database" + + let(:cron) { {} } + let(:configure_sentry) do + proc { |config| config.enabled_patches << :good_job_cron } + end + + def queue_adapter_for_test + @queue_adapter_for_test ||= ::ActiveJob::QueueAdapters::GoodJobAdapter.new(execution_mode: :external) + end + + def boot_adapter(_adapter) + Sentry::Rails::Test::GoodJobDatabase.connect + end + + def reset_adapter(_adapter) + GoodJob::Execution.delete_all + GoodJob::Job.delete_all + end + + around do |example| + configuration = GoodJob.configuration + GoodJob.configuration = GoodJob::Configuration.new({ cron: cron }) + example.run + ensure + GoodJob.configuration = configuration + end + + def drain + lock_id = SecureRandom.uuid + + loop do + result = GoodJob::Job.perform_with_advisory_lock(lock_id: lock_id) + break if result.nil? + raise result.unhandled_error if result.unhandled_error + end + end + + def run_entry(key, at: Time.now.change(usec: 0), **params) + cron[key] = params unless params.empty? + GoodJob::CronEntry.find(key).enqueue(at) + drain + end + + def check_ins + sentry_events.select { |event| event.is_a?(Sentry::CheckInEvent) } + end + + it "sends no check-ins for an overlapping run that GoodJob's concurrency limit rejects" do + overlapping_run = method(:run_entry) + overlapping_at = 1.hour.from_now.change(usec: 0) + job_fixture("ExclusiveReportJob") do + include GoodJob::ActiveJobExtensions::Concurrency + self.good_job_labels = ["exclusive_report"] + good_job_concurrency_rule(label: "exclusive_report", perform_limit: 1) + + define_method(:perform) do + Thread.new { overlapping_run.call(:exclusive_report, at: overlapping_at) }.join + end + end + + run_entry(:exclusive_report, class: "ExclusiveReportJob", cron: "0 * * * * UTC") + + expect(GoodJob::Execution.where("error LIKE ?", "%ConcurrencyExceededError%")).to exist + expect(check_ins.map(&:status)).to eq([:in_progress, :ok, :in_progress, :ok]) + end + end + end end From 23091c1e94cab8ab13ddf6a2c1e63b6382f3d2b5 Mon Sep 17 00:00:00 2001 From: Peter Solnica Date: Thu, 12 Nov 2026 13:00:06 +0000 Subject: [PATCH 12/20] fix(rails): Send GoodJob cron monitor config only on in_progress check-ins --- .../lib/sentry/rails/good_job_cron.rb | 20 ++++++++++++++++++- .../spec/active_job/good_job_cron_spec.rb | 2 ++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/sentry-rails/lib/sentry/rails/good_job_cron.rb b/sentry-rails/lib/sentry/rails/good_job_cron.rb index faf6ac6c6..6fb134efa 100644 --- a/sentry-rails/lib/sentry/rails/good_job_cron.rb +++ b/sentry-rails/lib/sentry/rails/good_job_cron.rb @@ -82,7 +82,7 @@ def perform(job) max_runtime: cron_config.default_max_runtime ) - Sentry::Cron::MonitorCheckIns.with_check_in(data["slug"], monitor_config: monitor_config) { yield } + with_check_in(data["slug"], monitor_config) { yield } end def patch @@ -96,6 +96,24 @@ def patch private + def with_check_in(slug, monitor_config) + check_in_id = Sentry.capture_check_in(slug, :in_progress, monitor_config: monitor_config) + start = monotonic_now + + begin + result = yield + Sentry.capture_check_in(slug, :ok, check_in_id: check_in_id, duration: monotonic_now - start) + result + rescue Exception + Sentry.capture_check_in(slug, :error, check_in_id: check_in_id, duration: monotonic_now - start) + raise + end + end + + def monotonic_now + Process.clock_gettime(Process::CLOCK_MONOTONIC) + end + # Entries whose cron is a proc can change schedule between runs. GoodJob's # scheduler threads read zoneless schedules in the app's time zone, which # an enqueue from a request using Time.use_zone wouldn't see. diff --git a/sentry-rails/spec/active_job/good_job_cron_spec.rb b/sentry-rails/spec/active_job/good_job_cron_spec.rb index 50a3c067d..b91e8c4cd 100644 --- a/sentry-rails/spec/active_job/good_job_cron_spec.rb +++ b/sentry-rails/spec/active_job/good_job_cron_spec.rb @@ -71,6 +71,7 @@ def perform(*); end ) expect(ok.status).to eq(:ok) expect(ok.check_in_id).to eq(in_progress.check_in_id) + expect(ok.monitor_config).to be_nil end it "sends an error check-in when the job fails" do @@ -83,6 +84,7 @@ def perform expect { run_entry(:failing_report, class: "FailingReportJob", cron: "every hour") }.to raise_error("boom") expect(check_ins.map(&:status)).to eq([:in_progress, :error]) expect(check_ins.first.monitor_config.to_h[:schedule]).to eq(type: :crontab, value: "0 * * * *") + expect(check_ins.last.monitor_config).to be_nil end it "checks in again when a failed run is retried" do From 64a9af1adf2a4076dd0f16f254d920a6fc0af3db Mon Sep 17 00:00:00 2001 From: Peter Solnica Date: Thu, 12 Nov 2026 13:00:36 +0000 Subject: [PATCH 13/20] test(rails): Cover enabling GoodJob cron without the good_job gem --- .../good_job_cron_without_good_job_spec.rb | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 sentry-rails/spec/isolated/good_job_cron_without_good_job_spec.rb diff --git a/sentry-rails/spec/isolated/good_job_cron_without_good_job_spec.rb b/sentry-rails/spec/isolated/good_job_cron_without_good_job_spec.rb new file mode 100644 index 000000000..b8fad9f63 --- /dev/null +++ b/sentry-rails/spec/isolated/good_job_cron_without_good_job_spec.rb @@ -0,0 +1,23 @@ +# frozen_string_literal: true + +begin + require "simplecov" + SimpleCov.command_name "GoodJobCronWithoutGoodJob" +rescue LoadError +end + +RSpec.describe "Enabling the :good_job_cron patch without the good_job gem" do + let(:sdk_log) { StringIO.new } + + it "boots the app and logs a warning" do + expect(defined?(::GoodJob)).to be_nil + + make_basic_app do |config| + config.enabled_patches << :good_job_cron + config.sdk_logger = Logger.new(sdk_log) + end + + expect(Sentry).to be_initialized + expect(sdk_log.string).to include("You tried to enable the GoodJob cron integration but the `good_job` gem was not detected.") + end +end From 7864f5e9c792b5b9889d9685214c8f6eececfcff Mon Sep 17 00:00:00 2001 From: Peter Solnica Date: Mon, 16 Nov 2026 10:29:47 +0000 Subject: [PATCH 14/20] fix(rails): monitor GoodJob crons through execution notifications --- .../lib/sentry/rails/good_job_cron.rb | 91 +++++++--------- .../spec/active_job/good_job_cron_spec.rb | 100 +++++++++++++----- .../good_job_cron_subscriber_spec.rb | 86 +++++++++++++++ .../spec/isolated/good_job_cron_boot_spec.rb | 24 +++++ .../isolated/good_job_cron_reload_spec.rb | 37 +++++++ 5 files changed, 258 insertions(+), 80 deletions(-) create mode 100644 sentry-rails/spec/active_job/good_job_cron_subscriber_spec.rb create mode 100644 sentry-rails/spec/isolated/good_job_cron_boot_spec.rb create mode 100644 sentry-rails/spec/isolated/good_job_cron_reload_spec.rb diff --git a/sentry-rails/lib/sentry/rails/good_job_cron.rb b/sentry-rails/lib/sentry/rails/good_job_cron.rb index 6fb134efa..a5505f99c 100644 --- a/sentry-rails/lib/sentry/rails/good_job_cron.rb +++ b/sentry-rails/lib/sentry/rails/good_job_cron.rb @@ -5,29 +5,7 @@ module Rails # Sends Crons check-ins for GoodJob cron entries. # Enable with `config.enabled_patches << :good_job_cron`. module GoodJobCron - PAYLOAD_KEY = "_sentry_good_job_cron" - - module Job - def serialize - @_sentry_good_job_cron ||= Sentry::Rails::GoodJobCron.monitor_for(self) - payload = super - payload[PAYLOAD_KEY] = @_sentry_good_job_cron if @_sentry_good_job_cron - payload - end - - def deserialize(job_data) - super - @_sentry_good_job_cron = job_data[PAYLOAD_KEY] - singleton_class.prepend(Perform) if @_sentry_good_job_cron - end - end - - module Perform - def perform(*args, &block) - Sentry::Rails::GoodJobCron.perform(self) { super(*args, &block) } - end - ruby2_keywords(:perform) - end + EVENT_STATE = :sentry_good_job_cron class << self def excluded?(key) @@ -42,17 +20,15 @@ def excluded?(key) false end - # GoodJob sets the cron key while an entry enqueues its job and clears it while jobs run. + # The persisted record identifies the cron run, including retries and callable classes. def monitor_for(job) - key = ::GoodJob::CurrentThread.cron_key + key = job.cron_key return unless key && Sentry.initialized? return if excluded?(key) entry = ::GoodJob::CronEntry.find(key) - job_class = entry.job_class - # A callable class can't be checked without calling it again. - return unless job_class.respond_to?(:call) || job.class.name == job_class.to_s.delete_prefix("::") - return if job.class < Sentry::Cron::MonitorCheckIns::Patch + job_class = job.job_class.safe_constantize + return if job_class && job_class < Sentry::Cron::MonitorCheckIns::Patch slug = Sentry::Cron::Slug.from(entry.key) return unless slug @@ -64,50 +40,57 @@ def monitor_for(job) end return if slug_shared?(entry.key, slug) - { "slug" => slug, "crontab" => config.schedule.value, "timezone" => config.timezone } + [slug, config] rescue StandardError => e Sentry.sdk_logger.error(Sentry::LOGGER_PROGNAME) { "Not monitoring GoodJob cron entry #{key}: #{e.class}: #{e.message}" } nil end - def perform(job) - data = job.instance_variable_get(:@_sentry_good_job_cron) - return yield unless data && Sentry.initialized? + # Evented subscribers receive start before execution and finish afterwards. + # State belongs to the notification payload, so nested and concurrent runs are independent. + def start(_name, _id, payload) + return unless Sentry.initialized? && Sentry.configuration.enabled_patches.include?(:good_job_cron) + monitor = monitor_for(payload[:job]) + return unless monitor + + slug, schedule = monitor cron_config = Sentry.configuration.cron - monitor_config = Sentry::Cron::MonitorConfig.from_crontab( - data["crontab"], - timezone: data["timezone"], + config = Sentry::Cron::MonitorConfig.from_crontab( + schedule.schedule.value, + timezone: schedule.timezone, checkin_margin: cron_config.default_checkin_margin, max_runtime: cron_config.default_max_runtime ) + check_in_id = Sentry.capture_check_in(slug, :in_progress, monitor_config: config) + payload[EVENT_STATE] = { slug: slug, check_in_id: check_in_id, started_at: monotonic_now } + rescue StandardError => e + log_error(e) + end + + def finish(_name, _id, payload) + state = payload.delete(EVENT_STATE) + return unless state && Sentry.initialized? - with_check_in(data["slug"], monitor_config) { yield } + error = payload[:handled_error] || payload[:unhandled_error] || payload[:error] || payload[:exception] + Sentry.capture_check_in( + state[:slug], error ? :error : :ok, + check_in_id: state[:check_in_id], duration: monotonic_now - state[:started_at] + ) + rescue StandardError => e + log_error(e) end def patch - return if @patched + return if @subscriber - @patched = true - ActiveSupport.on_load(:active_job) do - prepend Sentry::Rails::GoodJobCron::Job - end + @subscriber = ActiveSupport::Notifications.subscribe("perform_job.good_job", self) end private - def with_check_in(slug, monitor_config) - check_in_id = Sentry.capture_check_in(slug, :in_progress, monitor_config: monitor_config) - start = monotonic_now - - begin - result = yield - Sentry.capture_check_in(slug, :ok, check_in_id: check_in_id, duration: monotonic_now - start) - result - rescue Exception - Sentry.capture_check_in(slug, :error, check_in_id: check_in_id, duration: monotonic_now - start) - raise - end + def log_error(error) + Sentry.sdk_logger.error(Sentry::LOGGER_PROGNAME) { "Could not send GoodJob cron check-in: #{error.class}: #{error.message}" } end def monotonic_now diff --git a/sentry-rails/spec/active_job/good_job_cron_spec.rb b/sentry-rails/spec/active_job/good_job_cron_spec.rb index b91e8c4cd..ae972eb2b 100644 --- a/sentry-rails/spec/active_job/good_job_cron_spec.rb +++ b/sentry-rails/spec/active_job/good_job_cron_spec.rb @@ -7,10 +7,10 @@ rescue LoadError end -if defined?(::GoodJob) +if defined?(::GoodJob) && RAILS_VERSION >= 7.1 RSpec.describe Sentry::Rails::GoodJobCron, type: :job do - include_context "active_job backend harness", adapter: :test - include_context "test adapter" + include_context "active_job backend harness", adapter: :good_job + include_context "good_job database" let(:excluded_jobs) { [] } let(:cron) { {} } @@ -21,15 +21,26 @@ end end - # Runs jobs from their full serialized payload, like GoodJob does. def queue_adapter_for_test - Rails52FullPayloadTestAdapter.new + @queue_adapter_for_test ||= ::ActiveJob::QueueAdapters::GoodJobAdapter.new(execution_mode: :external) + end + + def boot_adapter(_adapter) + Sentry::Rails::Test::GoodJobDatabase.connect + end + + def reset_adapter(_adapter) + GoodJob::Execution.delete_all + GoodJob::Job.delete_all end def drain - jobs = queue_adapter.enqueued_jobs.dup - queue_adapter.enqueued_jobs.clear - jobs.each { |payload| ::ActiveJob::Base.execute(payload[:_sentry_full_payload]) } + lock_id = SecureRandom.uuid + loop do + result = GoodJob::Job.perform_with_advisory_lock(lock_id: lock_id) + break if result.nil? + raise result.unhandled_error if result.unhandled_error + end end around do |example| @@ -179,7 +190,7 @@ def perform; end expect(check_ins.map(&:monitor_slug)).to eq(["callable_report", "callable_report"]) end - it "does not monitor other jobs enqueued while an entry enqueues" do + it "monitors only the cron record GoodJob persists when a callback enqueues another job" do job_fixture("AuditJob") do def perform; end end @@ -191,7 +202,33 @@ def perform; end run_entry(:audited_report, class: "AuditedReportJob", cron: "0 9 * * *") + # GoodJob gives the nested job the cron key and its unique cron slot; + # the parent enqueue is rejected as a duplicate. Sentry follows that persisted run. + expect(GoodJob::Job.pluck(:job_class, :cron_key)).to eq([["AuditJob", "audited_report"]]) + expect(check_ins.map(&:monitor_slug)).to eq(["audited_report", "audited_report"]) + end + + it "uses the persisted cron record for callable classes without reevaluating the callable" do + skip "GoodJob #{GoodJob::VERSION} has no callable classes" if Gem::Version.new(GoodJob::VERSION) < Gem::Version.new("4.19.3") + + job_fixture("AuditJob") do + def perform; end + end + job_fixture("AuditedReportJob") do + before_enqueue { AuditJob.perform_later } + + def perform; end + end + job_class = double("callable job class") + expect(job_class).to receive(:call).once.and_return(AuditedReportJob) + + run_entry(:audited_report, class: job_class, cron: "0 9 * * *") + + # GoodJob gives the nested job the cron key and its unique cron slot; + # the parent enqueue is rejected as a duplicate. Sentry follows that persisted run. + expect(GoodJob::Job.pluck(:job_class, :cron_key)).to eq([["AuditJob", "audited_report"]]) expect(check_ins.map(&:monitor_slug)).to eq(["audited_report", "audited_report"]) + expect(check_ins.map(&:status)).to eq([:in_progress, :ok]) end it "still enqueues the job when monitoring it fails" do @@ -201,28 +238,15 @@ def perform; end # find raises for an entry missing from GoodJob's configuration. GoodJob::CronEntry.new(key: :unlisted_report, class: "ReportJob", cron: "0 9 * * *").enqueue(Time.now) - expect(queue_adapter.enqueued_jobs.size).to eq(1) + expect(GoodJob::Job.count).to eq(1) drain expect(check_ins).to be_empty expect(string_io.string).to include("Not monitoring GoodJob cron entry unlisted_report") end context "when GoodJob runs jobs inline" do - # GoodJob's inline mode runs the job inside the cron enqueue and resets its thread state first. def queue_adapter_for_test - Class.new(::ActiveJob::QueueAdapters::TestAdapter) do - def enqueue(job) - payload = job.serialize - ::GoodJob::CurrentThread.within do |thread| - thread.reset - ::ActiveJob::Base.execute(payload) - end - end - - def enqueue_at(job, _timestamp) - enqueue(job) - end - end.new + @inline_adapter ||= ::ActiveJob::QueueAdapters::GoodJobAdapter.new(execution_mode: :inline) end it "does not monitor a job the cron job enqueues of its own class" do @@ -245,6 +269,30 @@ def perform(again = true) expect(check_ins).to be_empty end + it "keeps running the job if sending the initial check-in fails" do + performed = false + job_fixture("SafeReportJob") { define_method(:perform) { performed = true } } + allow(Sentry).to receive(:capture_check_in).and_raise("transport failed") + + expect { run_entry(:safe_report, class: "SafeReportJob", cron: "0 9 * * *") }.not_to raise_error + expect(performed).to be(true) + expect(GoodJob::Job.first.error).to be_nil + end + + it "does not fail a successful job if sending the final check-in fails" do + allow(Sentry).to receive(:capture_check_in).and_call_original + allow(Sentry).to receive(:capture_check_in).with(anything, :ok, any_args).and_raise("transport failed") + + expect { run_entry(:safe_report, class: "ReportJob", cron: "0 9 * * *") }.not_to raise_error + expect(GoodJob::Job.first.error).to be_nil + end + + it "does not attach Sentry cron metadata to serialized jobs" do + run_entry(:daily_report, class: "ReportJob", cron: "0 9 * * *") + + expect(GoodJob::Job.first.serialized_params).not_to have_key("_sentry_good_job_cron") + end + it "excludes nothing by default" do expect(Sentry.configuration.rails.good_job_exclude_cron_jobs).to eq([]) end @@ -410,7 +458,7 @@ def check_ins sentry_events.select { |event| event.is_a?(Sentry::CheckInEvent) } end - it "sends no check-ins for an overlapping run that GoodJob's concurrency limit rejects" do + it "reports concurrency-rejected attempts as errors and monitors their subsequent retry" do overlapping_run = method(:run_entry) overlapping_at = 1.hour.from_now.change(usec: 0) job_fixture("ExclusiveReportJob") do @@ -426,7 +474,7 @@ def check_ins run_entry(:exclusive_report, class: "ExclusiveReportJob", cron: "0 * * * * UTC") expect(GoodJob::Execution.where("error LIKE ?", "%ConcurrencyExceededError%")).to exist - expect(check_ins.map(&:status)).to eq([:in_progress, :ok, :in_progress, :ok]) + expect(check_ins.map(&:status)).to eq([:in_progress, :in_progress, :error, :ok, :in_progress, :ok]) end end end diff --git a/sentry-rails/spec/active_job/good_job_cron_subscriber_spec.rb b/sentry-rails/spec/active_job/good_job_cron_subscriber_spec.rb new file mode 100644 index 000000000..99a643d78 --- /dev/null +++ b/sentry-rails/spec/active_job/good_job_cron_subscriber_spec.rb @@ -0,0 +1,86 @@ +# frozen_string_literal: true + +require "spec_helper" + +begin + require "good_job" +rescue LoadError +end + +if defined?(::GoodJob) + RSpec.describe "GoodJob cron notification subscriber", type: :job do + include_context "active_job backend harness", adapter: :test + include_context "test adapter" + + let(:configure_sentry) { proc { |config| config.enabled_patches << :good_job_cron } } + let(:record) { Struct.new(:cron_key, :job_class).new("report", "ReportJob") } + + around do |example| + configuration = GoodJob.configuration + GoodJob.configuration = GoodJob::Configuration.new({ cron: { report: { class: "ReportJob", cron: "0 9 * * *" } } }) + example.run + ensure + GoodJob.configuration = configuration + end + + before { job_fixture("ReportJob") { def perform; end } } + + def check_ins + sentry_events.grep(Sentry::CheckInEvent) + end + + def instrument(payload = {}, &block) + ActiveSupport::Notifications.instrument("perform_job.good_job", { job: record }.merge(payload), &block) + end + + it "keeps nested executions independent and removes state when they finish" do + outer_payload = inner_payload = nil + instrument do |outer| + outer_payload = outer + instrument { |inner| inner_payload = inner } + end + + expect(check_ins.map(&:status)).to eq([:in_progress, :in_progress, :ok, :ok]) + expect(check_ins[0].check_in_id).to eq(check_ins[3].check_in_id) + expect(check_ins[1].check_in_id).to eq(check_ins[2].check_in_id) + expect(check_ins[0].check_in_id).not_to eq(check_ins[1].check_in_id) + expect(outer_payload).not_to have_key(Sentry::Rails::GoodJobCron::EVENT_STATE) + expect(inner_payload).not_to have_key(Sentry::Rails::GoodJobCron::EVENT_STATE) + end + + [:handled_error, :unhandled_error].each do |error_key| + it "reports #{error_key} from GoodJob's result payload" do + instrument { |payload| payload[error_key] = RuntimeError.new("boom") } + + expect(check_ins.map(&:status)).to eq([:in_progress, :error]) + end + end + + it "reports exceptions that escape the instrumented execution without swallowing them" do + expect { instrument { raise "boom" } }.to raise_error("boom") + + expect(check_ins.map(&:status)).to eq([:in_progress, :error]) + end + + it "does not send check-ins for ordinary jobs" do + record.cron_key = nil + instrument { } + + expect(check_ins).to be_empty + end + + it "does not send check-ins when the patch is disabled in a later configuration" do + Sentry.configuration.enabled_patches.delete(:good_job_cron) + instrument { } + + expect(check_ins).to be_empty + end + + it "registers only once when initialized repeatedly" do + 2.times { Sentry::Rails::GoodJobCron.patch } + instrument { } + + expect(check_ins.map(&:status)).to eq([:in_progress, :ok]) + end + end +end diff --git a/sentry-rails/spec/isolated/good_job_cron_boot_spec.rb b/sentry-rails/spec/isolated/good_job_cron_boot_spec.rb new file mode 100644 index 000000000..88e7ceb2c --- /dev/null +++ b/sentry-rails/spec/isolated/good_job_cron_boot_spec.rb @@ -0,0 +1,24 @@ +# frozen_string_literal: true + +begin + require "good_job" +rescue LoadError +end + +if defined?(::GoodJob) + RSpec.describe "Enabling GoodJob cron monitoring during Rails boot" do + it "registers its subscriber without loading CronEntry during Sentry.init" do + expect(Sentry::Rails::GoodJobCron).to receive(:patch).and_wrap_original do |original| + expect($LOADED_FEATURES.grep(%r{/good_job/cron_entry\.rb\z})).to be_empty + original.call + expect($LOADED_FEATURES.grep(%r{/good_job/cron_entry\.rb\z})).to be_empty + end + + make_basic_app do |config| + config.enabled_patches << :good_job_cron + end + + expect(Sentry).to be_initialized + end + end +end diff --git a/sentry-rails/spec/isolated/good_job_cron_reload_spec.rb b/sentry-rails/spec/isolated/good_job_cron_reload_spec.rb new file mode 100644 index 000000000..dc6b3748a --- /dev/null +++ b/sentry-rails/spec/isolated/good_job_cron_reload_spec.rb @@ -0,0 +1,37 @@ +# frozen_string_literal: true + +begin + require "good_job" +rescue LoadError +end + +if defined?(::GoodJob) + RSpec.describe "GoodJob cron monitoring across Rails reloads" do + it "continues monitoring after Rails replaces CronEntry" do + app = Sentry::Rails::Test::Application.define do |application| + application.config.cache_classes = false + application.config.eager_load = false + application.initializer :configure_sentry do + Sentry.init do |config| + config.dsn = "http://12345:67890@sentry.localdomain:3000/sentry/42" + config.transport.transport_class = Sentry::DummyTransport + config.background_worker_threads = 0 + config.enabled_patches << :good_job_cron + end + end + end + + old_entry_class = GoodJob::CronEntry + app.reloader.reload! + expect(GoodJob::CronEntry).not_to equal(old_entry_class) + + GoodJob.configuration = GoodJob::Configuration.new({ cron: { report: { class: "ActiveJob::Base", cron: "0 9 * * *" } } }) + record = Struct.new(:cron_key, :job_class).new("report", "ActiveJob::Base") + ActiveSupport::Notifications.instrument("perform_job.good_job", job: record) { } + + check_ins = sentry_events.grep(Sentry::CheckInEvent) + expect(check_ins.map(&:status)).to eq([:in_progress, :ok]) + expect(check_ins.map(&:monitor_slug)).to eq(["report", "report"]) + end + end +end From 041b96494db920259b4510c6851936df8a9af621 Mon Sep 17 00:00:00 2001 From: Peter Solnica Date: Mon, 16 Nov 2026 12:01:02 +0000 Subject: [PATCH 15/20] test(rails): isolate GoodJob cron lifecycle checks in subprocesses --- .../spec/fixtures/good_job_cron_boot.rb | 19 ++++++++++ .../spec/fixtures/good_job_cron_reload.rb | 32 ++++++++++++++++ .../spec/isolated/good_job_cron_boot_spec.rb | 24 ++++-------- .../isolated/good_job_cron_reload_spec.rb | 37 ++++--------------- 4 files changed, 65 insertions(+), 47 deletions(-) create mode 100644 sentry-rails/spec/fixtures/good_job_cron_boot.rb create mode 100644 sentry-rails/spec/fixtures/good_job_cron_reload.rb diff --git a/sentry-rails/spec/fixtures/good_job_cron_boot.rb b/sentry-rails/spec/fixtures/good_job_cron_boot.rb new file mode 100644 index 000000000..dcd6c9bb8 --- /dev/null +++ b/sentry-rails/spec/fixtures/good_job_cron_boot.rb @@ -0,0 +1,19 @@ +# frozen_string_literal: true + +require "good_job" + +RSpec.describe "Enabling GoodJob cron monitoring during Rails boot" do + it "registers its subscriber without loading CronEntry during Sentry.init" do + expect(Sentry::Rails::GoodJobCron).to receive(:patch).and_wrap_original do |original| + expect($LOADED_FEATURES.grep(%r{/good_job/cron_entry\.rb\z})).to be_empty + original.call + expect($LOADED_FEATURES.grep(%r{/good_job/cron_entry\.rb\z})).to be_empty + end + + make_basic_app do |config| + config.enabled_patches << :good_job_cron + end + + expect(Sentry).to be_initialized + end +end diff --git a/sentry-rails/spec/fixtures/good_job_cron_reload.rb b/sentry-rails/spec/fixtures/good_job_cron_reload.rb new file mode 100644 index 000000000..a3b8fb90b --- /dev/null +++ b/sentry-rails/spec/fixtures/good_job_cron_reload.rb @@ -0,0 +1,32 @@ +# frozen_string_literal: true + +require "good_job" + +RSpec.describe "GoodJob cron monitoring across Rails reloads" do + it "continues monitoring after Rails replaces CronEntry" do + app = Sentry::Rails::Test::Application.define do |application| + application.config.cache_classes = false + application.config.eager_load = false + application.initializer :configure_sentry do + Sentry.init do |config| + config.dsn = "http://12345:67890@sentry.localdomain:3000/sentry/42" + config.transport.transport_class = Sentry::DummyTransport + config.background_worker_threads = 0 + config.enabled_patches << :good_job_cron + end + end + end + + old_entry_class = GoodJob::CronEntry + app.reloader.reload! + expect(GoodJob::CronEntry).not_to equal(old_entry_class) + + GoodJob.configuration = GoodJob::Configuration.new({ cron: { report: { class: "ActiveJob::Base", cron: "0 9 * * *" } } }) + record = Struct.new(:cron_key, :job_class).new("report", "ActiveJob::Base") + ActiveSupport::Notifications.instrument("perform_job.good_job", job: record) { } + + check_ins = sentry_events.grep(Sentry::CheckInEvent) + expect(check_ins.map(&:status)).to eq([:in_progress, :ok]) + expect(check_ins.map(&:monitor_slug)).to eq(["report", "report"]) + end +end diff --git a/sentry-rails/spec/isolated/good_job_cron_boot_spec.rb b/sentry-rails/spec/isolated/good_job_cron_boot_spec.rb index 88e7ceb2c..7e0c1b370 100644 --- a/sentry-rails/spec/isolated/good_job_cron_boot_spec.rb +++ b/sentry-rails/spec/isolated/good_job_cron_boot_spec.rb @@ -1,24 +1,14 @@ # frozen_string_literal: true -begin - require "good_job" -rescue LoadError -end +require "open3" -if defined?(::GoodJob) - RSpec.describe "Enabling GoodJob cron monitoring during Rails boot" do - it "registers its subscriber without loading CronEntry during Sentry.init" do - expect(Sentry::Rails::GoodJobCron).to receive(:patch).and_wrap_original do |original| - expect($LOADED_FEATURES.grep(%r{/good_job/cron_entry\.rb\z})).to be_empty - original.call - expect($LOADED_FEATURES.grep(%r{/good_job/cron_entry\.rb\z})).to be_empty - end +RSpec.describe "GoodJob cron boot in a fresh Rails process" do + it "passes the boot regression without sharing Rails or GoodJob state" do + skip "GoodJob is not bundled in this matrix cell" unless Gem.loaded_specs.key?("good_job") - make_basic_app do |config| - config.enabled_patches << :good_job_cron - end + fixture = File.expand_path("../fixtures/good_job_cron_boot.rb", __dir__) + stdout, stderr, status = Open3.capture3(RbConfig.ruby, "-S", "rspec", fixture) - expect(Sentry).to be_initialized - end + expect(status.exitstatus).to eq(0), stdout + stderr end end diff --git a/sentry-rails/spec/isolated/good_job_cron_reload_spec.rb b/sentry-rails/spec/isolated/good_job_cron_reload_spec.rb index dc6b3748a..592bd242b 100644 --- a/sentry-rails/spec/isolated/good_job_cron_reload_spec.rb +++ b/sentry-rails/spec/isolated/good_job_cron_reload_spec.rb @@ -1,37 +1,14 @@ # frozen_string_literal: true -begin - require "good_job" -rescue LoadError -end - -if defined?(::GoodJob) - RSpec.describe "GoodJob cron monitoring across Rails reloads" do - it "continues monitoring after Rails replaces CronEntry" do - app = Sentry::Rails::Test::Application.define do |application| - application.config.cache_classes = false - application.config.eager_load = false - application.initializer :configure_sentry do - Sentry.init do |config| - config.dsn = "http://12345:67890@sentry.localdomain:3000/sentry/42" - config.transport.transport_class = Sentry::DummyTransport - config.background_worker_threads = 0 - config.enabled_patches << :good_job_cron - end - end - end +require "open3" - old_entry_class = GoodJob::CronEntry - app.reloader.reload! - expect(GoodJob::CronEntry).not_to equal(old_entry_class) +RSpec.describe "GoodJob cron reload in a fresh Rails process" do + it "passes the reload regression without sharing Rails or GoodJob state" do + skip "GoodJob is not bundled in this matrix cell" unless Gem.loaded_specs.key?("good_job") - GoodJob.configuration = GoodJob::Configuration.new({ cron: { report: { class: "ActiveJob::Base", cron: "0 9 * * *" } } }) - record = Struct.new(:cron_key, :job_class).new("report", "ActiveJob::Base") - ActiveSupport::Notifications.instrument("perform_job.good_job", job: record) { } + fixture = File.expand_path("../fixtures/good_job_cron_reload.rb", __dir__) + stdout, stderr, status = Open3.capture3(RbConfig.ruby, "-S", "rspec", fixture) - check_ins = sentry_events.grep(Sentry::CheckInEvent) - expect(check_ins.map(&:status)).to eq([:in_progress, :ok]) - expect(check_ins.map(&:monitor_slug)).to eq(["report", "report"]) - end + expect(status.exitstatus).to eq(0), stdout + stderr end end From b7dff5ff3e8e150c9719f9e20329b76a70b4fa50 Mon Sep 17 00:00:00 2001 From: Peter Solnica Date: Mon, 16 Nov 2026 12:23:48 +0000 Subject: [PATCH 16/20] test(rails): bound the GoodJob cron concurrency regression --- .../spec/active_job/good_job_cron_spec.rb | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/sentry-rails/spec/active_job/good_job_cron_spec.rb b/sentry-rails/spec/active_job/good_job_cron_spec.rb index ae972eb2b..f701e5d93 100644 --- a/sentry-rails/spec/active_job/good_job_cron_spec.rb +++ b/sentry-rails/spec/active_job/good_job_cron_spec.rb @@ -459,20 +459,31 @@ def check_ins end it "reports concurrency-rejected attempts as errors and monitors their subsequent retry" do - overlapping_run = method(:run_entry) - overlapping_at = 1.hour.from_now.change(usec: 0) + overlapping_result = nil + started = false job_fixture("ExclusiveReportJob") do include GoodJob::ActiveJobExtensions::Concurrency self.good_job_labels = ["exclusive_report"] good_job_concurrency_rule(label: "exclusive_report", perform_limit: 1) + retry_on GoodJob::ActiveJobExtensions::Concurrency::ConcurrencyExceededError, wait: 0, attempts: 2 define_method(:perform) do - Thread.new { overlapping_run.call(:exclusive_report, at: overlapping_at) }.join + unless started + started = true + overlapping_result = Thread.new do + GoodJob::Job.perform_with_advisory_lock(lock_id: SecureRandom.uuid) + end.value + end end end - run_entry(:exclusive_report, class: "ExclusiveReportJob", cron: "0 * * * * UTC") + cron[:exclusive_report] = { class: "ExclusiveReportJob", cron: "0 * * * * UTC" } + entry = GoodJob::CronEntry.find(:exclusive_report) + entry.enqueue(Time.now.change(usec: 0)) + entry.enqueue(1.hour.from_now.change(usec: 0)) + drain + expect(overlapping_result.handled_error).to be_a(GoodJob::ActiveJobExtensions::Concurrency::ConcurrencyExceededError) expect(GoodJob::Execution.where("error LIKE ?", "%ConcurrencyExceededError%")).to exist expect(check_ins.map(&:status)).to eq([:in_progress, :in_progress, :error, :ok, :in_progress, :ok]) end From b0149661243e1f56f9f0aa7492a819acf90fef8c Mon Sep 17 00:00:00 2001 From: Peter Solnica Date: Mon, 16 Nov 2026 12:37:48 +0000 Subject: [PATCH 17/20] test(rails): verify GoodJob cron timezone precedence --- .../lib/sentry/rails/good_job_cron.rb | 6 ++-- .../spec/active_job/good_job_cron_spec.rb | 36 +++++++++++++++++++ 2 files changed, 39 insertions(+), 3 deletions(-) diff --git a/sentry-rails/lib/sentry/rails/good_job_cron.rb b/sentry-rails/lib/sentry/rails/good_job_cron.rb index a5505f99c..8772c6566 100644 --- a/sentry-rails/lib/sentry/rails/good_job_cron.rb +++ b/sentry-rails/lib/sentry/rails/good_job_cron.rb @@ -97,9 +97,9 @@ def monotonic_now Process.clock_gettime(Process::CLOCK_MONOTONIC) end - # Entries whose cron is a proc can change schedule between runs. GoodJob's - # scheduler threads read zoneless schedules in the app's time zone, which - # an enqueue from a request using Time.use_zone wouldn't see. + # Proc schedules can change between runs. Match the scheduler's local-zone + # resolution: EtOrbi prefers ENV['TZ'], then the Rails app's default zone. + # A request's temporary Time.use_zone must not change the monitor's zone. def schedule_for(entry) cron = entry.params[:cron] return unless cron.is_a?(String) diff --git a/sentry-rails/spec/active_job/good_job_cron_spec.rb b/sentry-rails/spec/active_job/good_job_cron_spec.rb index f701e5d93..2aeae2a7f 100644 --- a/sentry-rails/spec/active_job/good_job_cron_spec.rb +++ b/sentry-rails/spec/active_job/good_job_cron_spec.rb @@ -145,6 +145,42 @@ def perform end end + context "when the process and Rails time zones differ" do + around do |example| + previous_tz = ENV["TZ"] + previous_zone = Time.zone_default + ENV["TZ"] = "America/Los_Angeles" + Time.zone_default = Time.find_zone!("Asia/Tokyo") + example.run + ensure + ENV["TZ"] = previous_tz + Time.zone_default = previous_zone + end + + it "matches GoodJob's scheduler timezone rather than overriding ENV TZ" do + Time.use_zone("America/Chicago") do + run_entry(:daily_report, class: "ReportJob", cron: "0 9 * * *") + end + + timezone = check_ins.first.monitor_config.timezone + # Scheduler threads have the app's default zone, independent of the request's zone. + scheduled_at = Thread.new { GoodJob::CronEntry.find(:daily_report).next_at }.value + + expect(timezone).to eq("America/Los_Angeles") + expect(scheduled_at.in_time_zone(timezone).hour).to eq(9) + end + + it "keeps an explicit cron timezone ahead of both process and Rails zones" do + run_entry(:daily_report, class: "ReportJob", cron: "0 9 * * * Europe/Vienna") + + timezone = check_ins.first.monitor_config.timezone + scheduled_at = Thread.new { GoodJob::CronEntry.find(:daily_report).next_at }.value + + expect(timezone).to eq("Europe/Vienna") + expect(scheduled_at.in_time_zone(timezone).hour).to eq(9) + end + end + it "skips schedules Crons cannot express" do run_entry(:every_ten_seconds, class: "ReportJob", cron: "every 10 seconds") From 67edb42a1077b50572f578fee09130838b5815c0 Mon Sep 17 00:00:00 2001 From: Peter Solnica Date: Mon, 16 Nov 2026 14:19:28 +0000 Subject: [PATCH 18/20] fix(rails): Warn instead of patching GoodJob cron below good_job 4.0 --- .../lib/sentry/rails/good_job_cron.rb | 9 ++++++- .../fixtures/good_job_cron_unsupported.rb | 24 +++++++++++++++++++ ...good_job_cron_unsupported_good_job_spec.rb | 14 +++++++++++ 3 files changed, 46 insertions(+), 1 deletion(-) create mode 100644 sentry-rails/spec/fixtures/good_job_cron_unsupported.rb create mode 100644 sentry-rails/spec/isolated/good_job_cron_unsupported_good_job_spec.rb diff --git a/sentry-rails/lib/sentry/rails/good_job_cron.rb b/sentry-rails/lib/sentry/rails/good_job_cron.rb index 8772c6566..f49cb65b0 100644 --- a/sentry-rails/lib/sentry/rails/good_job_cron.rb +++ b/sentry-rails/lib/sentry/rails/good_job_cron.rb @@ -6,6 +6,7 @@ module Rails # Enable with `config.enabled_patches << :good_job_cron`. module GoodJobCron EVENT_STATE = :sentry_good_job_cron + MINIMUM_GOOD_JOB_VERSION = Gem::Version.new("4.0") class << self def excluded?(key) @@ -138,7 +139,13 @@ def monitored?(entry) Sentry.register_patch(:good_job_cron) do |config| if defined?(::GoodJob) && defined?(::Rails.application) && ::Rails.application - Sentry::Rails::GoodJobCron.patch + if Gem::Version.new(::GoodJob::VERSION) < Sentry::Rails::GoodJobCron::MINIMUM_GOOD_JOB_VERSION + config.sdk_logger.warn(Sentry::LOGGER_PROGNAME) do + "The GoodJob cron integration requires good_job #{Sentry::Rails::GoodJobCron::MINIMUM_GOOD_JOB_VERSION} or later, but #{::GoodJob::VERSION} is installed." + end + else + Sentry::Rails::GoodJobCron.patch + end else config.sdk_logger.warn(Sentry::LOGGER_PROGNAME) { "You tried to enable the GoodJob cron integration but the `good_job` gem was not detected." } end diff --git a/sentry-rails/spec/fixtures/good_job_cron_unsupported.rb b/sentry-rails/spec/fixtures/good_job_cron_unsupported.rb new file mode 100644 index 000000000..57d647422 --- /dev/null +++ b/sentry-rails/spec/fixtures/good_job_cron_unsupported.rb @@ -0,0 +1,24 @@ +# frozen_string_literal: true + +require "good_job" + +RSpec.describe "Enabling the :good_job_cron patch with a GoodJob older than 4.0" do + let(:sdk_log) { StringIO.new } + + before { stub_const("GoodJob::VERSION", "3.99.0") } + + it "boots the app, logs a warning, and sends no check-ins" do + make_basic_app do |config| + config.enabled_patches << :good_job_cron + config.sdk_logger = Logger.new(sdk_log) + end + + GoodJob.configuration = GoodJob::Configuration.new({ cron: { report: { class: "ActiveJob::Base", cron: "0 9 * * *" } } }) + record = Struct.new(:cron_key, :job_class).new("report", "ActiveJob::Base") + ActiveSupport::Notifications.instrument("perform_job.good_job", job: record) { } + + expect(Sentry).to be_initialized + expect(sdk_log.string).to include("The GoodJob cron integration requires good_job 4.0 or later, but 3.99.0 is installed.") + expect(sentry_events.grep(Sentry::CheckInEvent)).to be_empty + end +end diff --git a/sentry-rails/spec/isolated/good_job_cron_unsupported_good_job_spec.rb b/sentry-rails/spec/isolated/good_job_cron_unsupported_good_job_spec.rb new file mode 100644 index 000000000..ad9c7df3d --- /dev/null +++ b/sentry-rails/spec/isolated/good_job_cron_unsupported_good_job_spec.rb @@ -0,0 +1,14 @@ +# frozen_string_literal: true + +require "open3" + +RSpec.describe "GoodJob cron with an unsupported GoodJob in a fresh Rails process" do + it "warns instead of monitoring without sharing GoodJob state" do + skip "GoodJob is not bundled in this matrix cell" unless Gem.loaded_specs.key?("good_job") + + fixture = File.expand_path("../fixtures/good_job_cron_unsupported.rb", __dir__) + stdout, stderr, status = Open3.capture3(RbConfig.ruby, "-S", "rspec", fixture) + + expect(status.exitstatus).to eq(0), stdout + stderr + end +end From 4e07d3422960ed439b49fa8a42b675dba3a2bcd6 Mon Sep 17 00:00:00 2001 From: Peter Solnica Date: Mon, 16 Nov 2026 14:19:28 +0000 Subject: [PATCH 19/20] test(rails): Skip GoodJob cron specs below Rails 7.1 with a reason --- sentry-rails/spec/active_job/good_job_cron_spec.rb | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/sentry-rails/spec/active_job/good_job_cron_spec.rb b/sentry-rails/spec/active_job/good_job_cron_spec.rb index 2aeae2a7f..ebc2e4e33 100644 --- a/sentry-rails/spec/active_job/good_job_cron_spec.rb +++ b/sentry-rails/spec/active_job/good_job_cron_spec.rb @@ -7,8 +7,12 @@ rescue LoadError end -if defined?(::GoodJob) && RAILS_VERSION >= 7.1 +if defined?(::GoodJob) RSpec.describe Sentry::Rails::GoodJobCron, type: :job do + before(:all) do + skip "GoodJob cron specs run the real GoodJob adapter, which ActiveJob::TestHelper supports from Rails 7.1" if RAILS_VERSION < 7.1 + end + include_context "active_job backend harness", adapter: :good_job include_context "good_job database" From 4e58534b15cf3319a5fe7810226ad37b0496f855 Mon Sep 17 00:00:00 2001 From: Peter Solnica Date: Mon, 16 Nov 2026 15:05:46 +0000 Subject: [PATCH 20/20] fix(rails): Monitor GoodJob cron entries with a parsed Fugit schedule --- sentry-rails/lib/sentry/rails/good_job_cron.rb | 2 +- sentry-rails/spec/active_job/good_job_cron_spec.rb | 10 ++++++++++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/sentry-rails/lib/sentry/rails/good_job_cron.rb b/sentry-rails/lib/sentry/rails/good_job_cron.rb index f49cb65b0..25f729ac5 100644 --- a/sentry-rails/lib/sentry/rails/good_job_cron.rb +++ b/sentry-rails/lib/sentry/rails/good_job_cron.rb @@ -103,7 +103,7 @@ def monotonic_now # A request's temporary Time.use_zone must not change the monitor's zone. def schedule_for(entry) cron = entry.params[:cron] - return unless cron.is_a?(String) + return if cron.respond_to?(:call) Time.use_zone(Time.zone_default) { Sentry::Cron::FugitSchedule.from_cron(::Fugit.parse(cron)) } end diff --git a/sentry-rails/spec/active_job/good_job_cron_spec.rb b/sentry-rails/spec/active_job/good_job_cron_spec.rb index ebc2e4e33..746e4729b 100644 --- a/sentry-rails/spec/active_job/good_job_cron_spec.rb +++ b/sentry-rails/spec/active_job/good_job_cron_spec.rb @@ -185,6 +185,16 @@ def perform end end + it "monitors entries whose schedule is an already parsed Fugit cron" do + run_entry(:parsed_report, class: "ReportJob", cron: Fugit.parse("0 9 * * 1-5 Europe/Vienna")) + + expect(check_ins.map(&:status)).to eq([:in_progress, :ok]) + expect(check_ins.first.monitor_config.to_h).to eq( + schedule: { type: :crontab, value: "0 9 * * 1-5" }, + timezone: "Europe/Vienna" + ) + end + it "skips schedules Crons cannot express" do run_entry(:every_ten_seconds, class: "ReportJob", cron: "every 10 seconds")