Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
81 changes: 81 additions & 0 deletions sentry-ruby/benchmarks/backtrace_parse.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
# frozen_string_literal: true

# Allocations and throughput for capturing the same exception repeatedly with a
# Rails-sized (120 frame) backtrace. Run it on two checkouts to compare them:
#
# bundle exec ruby benchmarks/backtrace_parse.rb

require "benchmark/ips"
require "memory_profiler"
require "sentry-ruby"

class NullTransport < Sentry::Transport
def send_data(*); end
end

Sentry.init do |config|
config.sdk_logger = ::Logger.new(nil)
config.dsn = "dummy://12345:67890@sentry.localdomain:3000/sentry/42"
config.transport.transport_class = NullTransport
config.background_worker_threads = 0
end

GEM_FRAMES = [
["actionpack-8.0.2/lib/action_controller/metal/basic_implicit_render.rb", 8, "send_action"],
["actionpack-8.0.2/lib/abstract_controller/base.rb", 226, "process_action"],
["actionpack-8.0.2/lib/action_controller/metal/rendering.rb", 193, "process_action"],
["actionpack-8.0.2/lib/abstract_controller/callbacks.rb", 261, "block in process_action"],
["activesupport-8.0.2/lib/active_support/callbacks.rb", 120, "block in run_callbacks"],
["actiontext-8.0.2/lib/action_text/rendering.rb", 25, "with_renderer"],
["activesupport-8.0.2/lib/active_support/callbacks.rb", 129, "run_callbacks"],
["actionpack-8.0.2/lib/action_dispatch/journey/router.rb", 53, "block in serve"],
["rack-3.1.12/lib/rack/etag.rb", 29, "call"],
["rack-3.1.12/lib/rack/conditional_get.rb", 31, "call"],
["railties-8.0.2/lib/rails/rack/logger.rb", 41, "call_app"],
["puma-6.6.0/lib/puma/request.rb", 99, "block in handle_request"],
["puma-6.6.0/lib/puma/thread_pool.rb", 173, "block in spawn_thread"]
].freeze

# Every 6th frame is app code, the rest are gems.
BACKTRACE = Array.new(120) do |i|
if i % 6 == 0
"/app/app/models/order_#{i}.rb:#{10 + i}:in `compute_#{i}'"
else
path, line, meth = GEM_FRAMES[i % GEM_FRAMES.size]
"/usr/local/bundle/gems/#{path}:#{line + i}:in `#{meth}'"
end
end.freeze

def build_exception
e = RuntimeError.new("boom")
e.set_backtrace(BACKTRACE.map(&:dup)) # fresh strings, like a real raise
e
end

in_app_pattern = Regexp.new("^(/app/)?#{Sentry::Configuration::APP_DIRS_PATTERN}")

# Warm every cache (parse cache, filename cache, line cache).
5.times { Sentry.capture_exception(build_exception) }

ITER = 100
backtraces = Array.new(ITER) { BACKTRACE.map(&:dup) }
parse_report = MemoryProfiler.report do
backtraces.each { |bt| Sentry::Backtrace.parse(bt, nil, nil, in_app_pattern: in_app_pattern) }
end

exceptions = Array.new(ITER) { build_exception }
capture_report = MemoryProfiler.report do
exceptions.each { |e| Sentry.capture_exception(e) }
end

puts "ruby #{RUBY_VERSION}, #{BACKTRACE.size}-frame backtrace, #{ITER} iterations"
puts format("Backtrace.parse: %6d objects / %8d bytes per call",
parse_report.total_allocated / ITER, parse_report.total_allocated_memsize / ITER)
puts format("capture_exception: %6d objects / %8d bytes per call",
capture_report.total_allocated / ITER, capture_report.total_allocated_memsize / ITER)

Benchmark.ips do |x|
x.config(time: 3, warmup: 1)
x.report("Backtrace.parse") { Sentry::Backtrace.parse(BACKTRACE, nil, nil, in_app_pattern: in_app_pattern) }
x.report("capture_exception") { Sentry.capture_exception(build_exception) }
end
24 changes: 23 additions & 1 deletion sentry-ruby/lib/sentry/backtrace/line.rb
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
# frozen_string_literal: true

require "concurrent/map"

module Sentry
# @api private
class Backtrace
Expand Down Expand Up @@ -31,10 +33,26 @@ class Line

attr_reader :in_app_pattern

# Parsed [file, number, method, module_name] by raw backtrace line.
# A recurring error produces the same lines on every capture, so a hit
# skips the regex match and its substring allocations. Parsing doesn't
# depend on in_app_pattern, so the pattern isn't part of the key.
# The cache is cleared once it reaches PARSE_CACHE_LIMIT entries.
PARSE_CACHE_LIMIT = 4096
@parse_cache = Concurrent::Map.new

# Parses a single line of a given backtrace
# @param [String] unparsed_line The raw line from +caller+ or some backtrace
# @return [Line] The parsed backtrace line
def self.parse(unparsed_line, in_app_pattern = nil)
file, number, method, module_name = @parse_cache[unparsed_line] || parse_and_cache(unparsed_line)
new(file, number, method, module_name, in_app_pattern)
end

# The parsed strings are shared by every Line (and event frame) created
# from the same raw line, so they're frozen to keep one caller's in-place
# mutation from leaking into later events.
def self.parse_and_cache(unparsed_line)
ruby_match = unparsed_line.match(RUBY_INPUT_FORMAT)

if ruby_match
Expand All @@ -54,8 +72,12 @@ def self.parse(unparsed_line, in_app_pattern = nil)
number = java_match[4]
end
end
new(file, number, method, module_name, in_app_pattern)

parsed = [file&.freeze, number&.freeze, method&.freeze, module_name&.freeze].freeze
@parse_cache.clear if @parse_cache.size >= PARSE_CACHE_LIMIT
@parse_cache[unparsed_line] = parsed
end
private_class_method :parse_and_cache

# Creates a Line from a Thread::Backtrace::Location object
# This is more efficient than converting to string and parsing with regex
Expand Down
58 changes: 58 additions & 0 deletions sentry-ruby/spec/sentry/backtrace/lines_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,64 @@
expect(line.module_name).to eq(nil)
expect(line.in_app).to eq(false)
end

it "converts JRuby .class files to .rb" do
2.times do
line = described_class.parse("uri:classloader:/gems/foo/lib/foo.class:7:in `bar'")

expect(line.file).to eq("/gems/foo/lib/foo.rb")
expect(line.number).to eq(7)
expect(line.method).to eq("bar")
end
end

context "parse cache" do
let(:parse_cache) { described_class.instance_variable_get(:@parse_cache) }

before { parse_cache.clear }

it "reuses frozen parsed strings for a repeated line" do
first = described_class.parse(unparsed_gem_line.dup, in_app_pattern)
second = described_class.parse(unparsed_gem_line.dup, in_app_pattern)

expect(second.file).to equal(first.file)
expect(second.method).to equal(first.method)
expect(second.file).to be_frozen
expect(second.method).to be_frozen
expect(second).not_to equal(first)
end

it "computes in_app from the pattern of each call, not the cached one" do
other_pattern = /sinatra/

expect(described_class.parse(unparsed_gem_line, in_app_pattern).in_app).to eq(false)
expect(described_class.parse(unparsed_gem_line, other_pattern).in_app).to eq(true)
expect(described_class.parse(unparsed_gem_line).in_app).to eq(false)
end

it "caches lines that don't match any format" do
2.times do
line = described_class.parse("not a backtrace line")

expect(line.file).to be_nil
expect(line.number).to eq(0)
end
expect(parse_cache.size).to eq(1)
end

it "clears itself once it reaches PARSE_CACHE_LIMIT" do
stub_const("#{described_class}::PARSE_CACHE_LIMIT", 2)

described_class.parse("a.rb:1:in `a'")
described_class.parse("b.rb:2:in `b'")
expect(parse_cache.size).to eq(2)

line = described_class.parse("c.rb:3:in `c'")
expect(parse_cache.size).to eq(1)
expect(line.file).to eq("c.rb")
expect(line.number).to eq(3)
end
end
end

describe ".from_source_location", skip: !Thread.respond_to?(:each_caller_location) do
Expand Down
Loading