Skip to content
Draft
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
2 changes: 2 additions & 0 deletions sentry-agents/lib/sentry-agents.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
require "sentry/agents/version"
require "sentry/span/data_conventions"
require "sentry/agents/ruby_llm/instrumenter"
require "sentry/agents/ruby_llm/tool_concurrency"

module Sentry
module Agents
Expand All @@ -15,6 +16,7 @@ module Agents

module RubyLLM
def self.install(ruby_llm_config = ::RubyLLM.config)
ToolConcurrency.install
Instrumenter.install(ruby_llm_config)
end
end
Expand Down
97 changes: 73 additions & 24 deletions sentry-agents/lib/sentry/agents/ruby_llm/instrumenter.rb
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,10 @@ module Agents
module RubyLLM
class Instrumenter
CHAT_EVENT = "chat.ruby_llm"
TOOL_EVENT = "tool_call.ruby_llm"
USAGE_EVENT = "usage.ruby_llm"
OPERATION = "gen_ai.chat"
TOOL_OPERATION = "gen_ai.execute_tool"
ORIGIN = "auto.ai.ruby_llm"

def self.install(config)
Expand All @@ -20,6 +22,8 @@ def instrument(name, payload)
case name.to_s
when CHAT_EVENT
with_chat_span(payload) { yield } if block_given?
when TOOL_EVENT
with_tool_span(payload) { yield } if block_given?
when USAGE_EVENT
update_usage(payload)
yield if block_given?
Expand All @@ -31,50 +35,61 @@ def instrument(name, payload)
private

def with_chat_span(payload)
with_operation_span(payload, OPERATION, span_description(payload)) { yield }
end

def with_tool_span(payload)
with_operation_span(payload, TOOL_OPERATION, tool_description(payload)) { yield }
end

def with_operation_span(payload, operation, description)
return yield unless Sentry.initialized?

if Sentry.get_current_scope.get_span
with_child_span(payload) { yield }
with_child_span(payload, operation, description) { yield }
else
with_root_transaction(payload) { yield }
with_root_transaction(payload, operation, description) { yield }
end
end

def with_child_span(payload)
Sentry.with_child_span(
op: OPERATION,
description: span_description(payload),
origin: ORIGIN
) do |span|
execute_span(span, payload) { yield }
def with_child_span(payload, operation, description)
Sentry.with_child_span(op: operation, description: description, origin: ORIGIN) do |span|
execute_span(span, payload, operation) { yield }
end
end

def with_root_transaction(payload)
transaction = Sentry.start_transaction(
name: span_description(payload),
op: OPERATION,
origin: ORIGIN
)
def with_root_transaction(payload, operation, description)
transaction = Sentry.start_transaction(name: description, op: operation, origin: ORIGIN)

begin
Sentry.with_scope do |scope|
scope.set_span(transaction)
execute_span(transaction, payload) { yield }
execute_span(transaction, payload, operation) { yield }
end
ensure
transaction.finish
end
end

def execute_span(span, payload)
set_request_data(span, payload)
def execute_span(span, payload, operation)
set_request_data(span, payload, operation)
yield
ensure
set_response_data(span, payload)
set_response_data(span, payload, operation)
end

def set_request_data(span, payload)
def set_request_data(span, payload, operation)
case operation
when OPERATION
set_chat_request_data(span, payload)
when TOOL_OPERATION
set_tool_request_data(span, payload)
end
rescue => e
Sentry.sdk_logger.debug(Sentry::LOGGER_PROGNAME) { "Failed to set RubyLLM request data: #{e}" }
end

def set_chat_request_data(span, payload)
span.set_data(Sentry::Span::DataConventions::GEN_AI_OPERATION_NAME, "chat")

if provider = provider_name(payload[:provider])
Expand Down Expand Up @@ -115,11 +130,34 @@ def set_request_data(span, payload)
if definitions.any?
span.set_data(Sentry::Span::DataConventions::GEN_AI_TOOL_DEFINITIONS, JSON.generate(definitions))
end
end

def set_tool_request_data(span, payload)
span.set_data(Sentry::Span::DataConventions::GEN_AI_OPERATION_NAME, "execute_tool")

if tool_name = payload[:tool_name] || payload[:tool]&.name
span.set_data(Sentry::Span::DataConventions::GEN_AI_TOOL_NAME, tool_name.to_s)
end

return unless collect_inputs?

if arguments = payload[:tool_arguments]
span.set_data(Sentry::Span::DataConventions::GEN_AI_TOOL_CALL_ARGUMENTS, JSON.generate(arguments))
end
end

def set_response_data(span, payload, operation)
case operation
when OPERATION
set_chat_response_data(span, payload)
when TOOL_OPERATION
set_tool_response_data(span, payload)
end
rescue => e
Sentry.sdk_logger.debug(Sentry::LOGGER_PROGNAME) { "Failed to set RubyLLM request data: #{e}" }
Sentry.sdk_logger.debug(Sentry::LOGGER_PROGNAME) { "Failed to set RubyLLM response data: #{e}" }
end

def set_response_data(span, payload)
def set_chat_response_data(span, payload)
response = payload[:response]
response_model = payload[:response_model] || response&.model
finish_reason = response&.finish_reason
Expand All @@ -138,8 +176,14 @@ def set_response_data(span, payload)
if messages.any?
span.set_data(Sentry::Span::DataConventions::GEN_AI_OUTPUT_MESSAGES, JSON.generate(messages))
end
rescue => e
Sentry.sdk_logger.debug(Sentry::LOGGER_PROGNAME) { "Failed to set RubyLLM response data: #{e}" }
end

def set_tool_response_data(span, payload)
return unless collect_outputs?
return unless payload.key?(:result) || payload.key?(:result_content)

result = payload.key?(:result) ? payload[:result] : payload[:result_content]
span.set_data(Sentry::Span::DataConventions::GEN_AI_TOOL_CALL_RESULT, JSON.generate(result))
end

def update_usage(payload)
Expand Down Expand Up @@ -177,6 +221,11 @@ def provider_name(provider)
::RubyLLM::OpenTelemetry::Attributes.provider_name(provider)
end

def tool_description(payload)
tool = payload[:tool_name] || payload[:tool]&.name
tool ? "execute_tool #{tool}" : "execute_tool"
end

def collect_inputs?
Sentry.configuration.data_collection.gen_ai.inputs
end
Expand Down
74 changes: 74 additions & 0 deletions sentry-agents/lib/sentry/agents/ruby_llm/tool_concurrency.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
# frozen_string_literal: true

require "ruby_llm/chat/tool_concurrency"

module Sentry
module Agents
module RubyLLM
class HubContext
def self.capture
return unless Sentry.initialized?

hub = Sentry.get_current_hub
new(hub, hub.current_scope&.get_span)
rescue StandardError => error
report(error)
nil
end

def initialize(hub, span)
@hub = hub
@span = span
end

def with_hub
previous_hub = Sentry.send(:get_current_hub_internal)
begin
hub = @hub.clone
hub.current_scope.set_span(@span) if @span
Sentry.send(:set_current_hub_internal, hub)
rescue StandardError => error
self.class.report(error)
return yield
end

begin
yield
ensure
Sentry.send(:set_current_hub_internal, previous_hub)
end
end

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fiber tool runs corrupt hub state

Medium Severity

with_hub save/restores the current hub via thread-local storage, and run applies that wrap in every concurrency mode. RubyLLM :fibers runs tools as cooperative fibers on the same thread, so overlapping with_hub calls overwrite each other's saved hub. After the batch finishes, the request thread can be left with a stale cloned hub instead of the original, so later spans and events lose the request scope.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 01f1aad. Configure here.


class << self
def report(error)
Sentry.configuration.sdk_logger.debug("sentry-agents instrumentation failed: #{error.class}: #{error.message}")
rescue StandardError
nil
end
end
end

module ToolConcurrency
module Patch
def run(mode, tool_calls, on_result: nil, &execute)
context = HubContext.capture
return super unless context

super(mode, tool_calls, on_result: on_result) do |tool_call|
context.with_hub { execute.call(tool_call) }
end
end
end

module_function

def install
target = ::RubyLLM::Chat::ToolConcurrency
return if target.singleton_class.ancestors.include?(Patch)

target.singleton_class.prepend(Patch)
end
end
end
end
end
3 changes: 3 additions & 0 deletions sentry-agents/lib/sentry/span/data_conventions.rb
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@ module DataConventions
GEN_AI_INPUT_MESSAGES = "gen_ai.input.messages"
GEN_AI_SYSTEM_INSTRUCTIONS = "gen_ai.system_instructions"
GEN_AI_TOOL_DEFINITIONS = "gen_ai.tool.definitions"
GEN_AI_TOOL_NAME = "gen_ai.tool.name"
GEN_AI_TOOL_CALL_ARGUMENTS = "gen_ai.tool.call.arguments"
GEN_AI_TOOL_CALL_RESULT = "gen_ai.tool.call.result"
GEN_AI_RESPONSE_MODEL = "gen_ai.response.model"
GEN_AI_RESPONSE_FINISH_REASONS = "gen_ai.response.finish_reasons"
GEN_AI_OUTPUT_MESSAGES = "gen_ai.output.messages"
Expand Down
39 changes: 39 additions & 0 deletions sentry-agents/spec/sentry/agents/ruby_llm/instrumenter_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,38 @@
expect(data["gen_ai.usage.reasoning.output_tokens"]).to eq(1)
end

it "creates a tool span with gated arguments and results" do
payload = tool_payload
result = instrument(described_class.new, "tool_call.ruby_llm", payload) do |event|
event[:result] = { temperature: 20 }
:ok
end

expect(result).to eq(:ok)
event = transaction_event
data = model_data(event)
expect(model_op(event)).to eq("gen_ai.execute_tool")
expect(model_description(event)).to eq("execute_tool weather")
expect(data["gen_ai.operation.name"]).to eq("execute_tool")
expect(data["gen_ai.tool.name"]).to eq("weather")
expect(JSON.parse(data["gen_ai.tool.call.arguments"])).to eq("city" => "Paris")
expect(JSON.parse(data["gen_ai.tool.call.result"])).to eq("temperature" => 20)
end

it "gates tool arguments and results independently" do
Sentry.configuration.data_collection.gen_ai.inputs = false
Sentry.configuration.data_collection.gen_ai.outputs = false

instrument(described_class.new, "tool_call.ruby_llm", tool_payload) do |event|
event[:result] = { temperature: 20 }
end

data = model_data(transaction_event)
expect(data["gen_ai.tool.name"]).to eq("weather")
expect(data).not_to have_key("gen_ai.tool.call.arguments")
expect(data).not_to have_key("gen_ai.tool.call.result")
end

it "gates input and output content independently" do
Sentry.configuration.data_collection.gen_ai.inputs = false
Sentry.configuration.data_collection.gen_ai.outputs = false
Expand Down Expand Up @@ -169,6 +201,13 @@ def transaction_event
sentry_events.find { |event| event.is_a?(Sentry::TransactionEvent) }
end

def tool_payload
{
tool_name: "weather",
tool_arguments: { city: "Paris" }
}
end

def chat_payload(provider: "openai", streaming: false, thinking: nil)
{
chat: Struct.new(:tools).new({}),
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
# frozen_string_literal: true

require "spec_helper"

RSpec.describe Sentry::Agents::RubyLLM::ToolConcurrency do
before do
RubyLLM.config.instrumenter = nil
Sentry.init do |config|
config.dsn = Sentry::TestHelper::DUMMY_DSN
config.sdk_logger = Logger.new(nil)
config.background_worker_threads = 0
config.transport.transport_class = Sentry::DummyTransport
config.traces_sample_rate = 1.0
config.data_collection.gen_ai.inputs = true
config.data_collection.gen_ai.outputs = true
end
end

after do
RubyLLM.config.instrumenter = nil
end

it "propagates an isolated hub while retaining the parent span recorder" do
parent = Sentry.start_transaction(name: "parent", op: "test")
Sentry.get_current_scope.set_span(parent)
adapter = Sentry::Agents::RubyLLM::Instrumenter.new
seen_spans = Queue.new

results = RubyLLM::Chat::ToolConcurrency.run(:threads, { first: "first", second: "second" }) do |tool_call|
payload = { tool_name: tool_call, tool_arguments: {} }
RubyLLM::Support::Instrumentation.instrument("tool_call.ruby_llm", payload) do |event|
seen_spans << Sentry.get_current_scope.get_span
event[:result] = tool_call
tool_call
end
end

expect(results.map(&:last)).to contain_exactly("first", "second")
expect(seen_spans.size).to eq(2)
expect(seen_spans.size.times.map { seen_spans.pop.parent_span_id }).to all(eq(parent.span_id))
expect(Sentry.get_current_scope.get_span).to eq(parent)

parent.finish
event = sentry_events.find { |item| item.is_a?(Sentry::TransactionEvent) }
expect(event.spans.size).to eq(2)
expect(event.spans.map { |span| span[:op] }).to all(eq("gen_ai.execute_tool"))
end
end
Loading