rails-profiler 0.44.19 → 0.44.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 6ff17f7394a92aa22478050a6e7fc0ba43176209346b78f62a76a1c408132e19
4
- data.tar.gz: fd9f845aa7eea816dcbbe2e6f5e48c3ee2747938fd652f136cc796ea2bd9a640
3
+ metadata.gz: 4e8274bd0fb2cb58fdfd37a2e93aecd9097b76700926326862373201a5ffb806
4
+ data.tar.gz: 6e639fb12156b9ae0729a64ffbb62f40611484b8e7258503f1e44a9021a7472d
5
5
  SHA512:
6
- metadata.gz: 0b52fe7bc4ab382e3795dfebd4775a919a704f95e4ed9c11d4fefcbfc1da0d8a17f6e2fc8602135739bb06b809346e3057c4d85058ae2884eae7bb89ab5a3cb8
7
- data.tar.gz: 1e11f5aa5caa3b22ad176859f4bb7880c115288d00f3cf638691a5e644da55277774e033d3e1f136b79cc1ece8cd7954688f2453b386280f415ffe70d3bc3ebe
6
+ metadata.gz: 80093b790074db0100eff63bb0b795d010dd40dc885c1ed44b3d7009b6717223faf648e5ef3903181897dbc4a15b958ff11777381faf26e601bb748d54923ebe
7
+ data.tar.gz: 8b219ed177c7427e2d0c4750652c1403f49e37205779ac486aa3c931d3e952f3501003bd0578c1c49f4111573b9491a023418776327847c7664578376677b72e
data/CHANGELOG.md CHANGED
@@ -19,6 +19,31 @@ every commit of every tag interval is accounted for one way or the other.
19
19
 
20
20
  ## [Unreleased]
21
21
 
22
+ ## [0.44.21] - 2026-10-25
23
+
24
+ <!-- stamped -->
25
+
26
+ ### Fixed
27
+
28
+ - **HTTP and Flame Graph collectors:** threads spawned during a profiled request but surviving
29
+ afterwards (a `Timeout.timeout` watcher, a Honeybadger or Bugsnag worker,
30
+ a `Concurrent::ScheduledTask`) no longer indefinitely pollute the profile with unbounded
31
+ entries and repeated re-saves. Collectors now refuse new entries after a grace period
32
+ (0.5 seconds) or when entry count exceeds 100, whichever comes first.
33
+
34
+ ## [0.44.20] - 2026-10-25
35
+
36
+ <!-- stamped -->
37
+
38
+ ### Fixed
39
+
40
+ - **MCP:** Clamp negative, zero, and oversized `limit` parameters in `query_profiles`, `query_jobs`, `query_mailers`, `query_console_profiles`, and `query_test_profiles` tools to the valid range `[1, 500]` to prevent invalid queries and unexpected behavior.
41
+ - **MCP:** Implement `'latest'` token support in `explain_query` tool, matching the behavior of `analyze_queries` and `get_profile` tools.
42
+ - **MCP:** Fix `related_jobs` section in `get_profile_detail` to read parent and child jobs from the correct storage (slave or local) instead of always reading from master storage.
43
+ - **MCP:** Return JSON-RPC error -32002 for unknown resource URIs instead of returning a success response with "Resource not found" text.
44
+ - **MCP:** Add `error: true` flag consistently to all validation error responses in `clear_profiles`, `explain_query`, and other tools for proper error handling by clients.
45
+ - **MCP:** Align `set_env_var` empty value handling with `EnvVarsController#update`: empty values now delete the environment variable and override, consistent between local and slave operations.
46
+
22
47
  ## [0.44.19] - 2026-10-25
23
48
 
24
49
  <!-- stamped -->
@@ -11,6 +11,7 @@ module Profiler
11
11
  @events = []
12
12
  @subscriptions = []
13
13
  @mutex = Mutex.new
14
+ @released_at = nil
14
15
  end
15
16
 
16
17
  def icon
@@ -152,6 +153,7 @@ module Profiler
152
153
  def unsubscribe
153
154
  unsubscribe_notifications(@subscriptions)
154
155
  restore_thread_slots
156
+ @released_at = Process.clock_gettime(Process::CLOCK_MONOTONIC)
155
157
  end
156
158
 
157
159
  def toolbar_summary
@@ -163,6 +165,13 @@ module Profiler
163
165
 
164
166
  private
165
167
 
168
+ def add_event_allowed?
169
+ return true unless @released_at
170
+
171
+ grace_period = 0.5
172
+ (Process.clock_gettime(Process::CLOCK_MONOTONIC) - @released_at) <= grace_period && @events.size < 100
173
+ end
174
+
166
175
  def build_hierarchy(events)
167
176
  return [] if events.empty?
168
177
 
@@ -193,7 +202,9 @@ module Profiler
193
202
  end
194
203
 
195
204
  def add_event(event)
196
- @mutex.synchronize { @events << event }
205
+ @mutex.synchronize do
206
+ @events << event if add_event_allowed?
207
+ end
197
208
  end
198
209
 
199
210
  def short_identifier(identifier)
@@ -11,6 +11,7 @@ module Profiler
11
11
  @requests = []
12
12
  @mutex = Mutex.new
13
13
  @collected = false
14
+ @released_at = nil
14
15
  end
15
16
 
16
17
  def icon
@@ -48,6 +49,7 @@ module Profiler
48
49
  # records nothing when no collector holds the thread-local slot.
49
50
  def unsubscribe
50
51
  restore_thread_slots
52
+ @released_at = Process.clock_gettime(Process::CLOCK_MONOTONIC)
51
53
  end
52
54
 
53
55
  def collect
@@ -62,11 +64,23 @@ module Profiler
62
64
 
63
65
  # Called from NetHttpInstrumentation before the actual HTTP call.
64
66
  # Returns the mutable entry so the caller can update it on completion.
67
+ # Returns nil if the collector has been released and the grace period or entry cap is exceeded,
68
+ # to prevent fire-and-forget threads from indefinitely polluting the profile after the request ends.
65
69
  def register_pending(payload)
66
70
  entry = payload.merge(in_flight: true, status: 0, duration: nil,
67
71
  response_headers: {}, response_body: nil,
68
72
  response_body_encoding: "text", response_size: 0)
69
- @mutex.synchronize { @requests << entry }
73
+
74
+ @mutex.synchronize do
75
+ # Refuse new entries if released and (grace period expired OR cap exceeded). Checked
76
+ # and appended under the same lock, so concurrent fire-and-forget threads cannot all
77
+ # pass the cap together.
78
+ if @released_at
79
+ grace_period = 0.5
80
+ return nil if (Process.clock_gettime(Process::CLOCK_MONOTONIC) - @released_at) > grace_period || @requests.size >= 100
81
+ end
82
+ @requests << entry
83
+ end
70
84
  save_if_collected
71
85
  entry
72
86
  end
@@ -65,39 +65,42 @@ module Profiler
65
65
 
66
66
  response = super
67
67
 
68
- duration = ((Process.clock_gettime(Process::CLOCK_MONOTONIC) - t0) * 1000).round(2)
69
- # read_body with a block hands each chunk to the block and keeps none: the response then
70
- # holds a Net::ReadAdapter, whose to_s is an inspect and whose bytes are gone.
71
- streamed = NetHttpInstrumentation.streamed_body?(response)
72
- resp_body_raw = streamed ? "" : response.body.to_s
73
- resp_content_encoding = response["content-encoding"].to_s.strip.downcase
74
- resp_body = NetHttpInstrumentation.decompress_body(resp_body_raw, resp_content_encoding, limit)
75
- resp_truncated = limit ? resp_body.bytesize > limit : false
76
- resp_body = Redaction.cut_bytes(resp_body, limit) if resp_truncated
77
- resp_content_type = response["content-type"].to_s
78
- processed_resp = NetHttpInstrumentation.process_body(resp_body, resp_content_type)
79
-
80
- t1 = Process.clock_gettime(Process::CLOCK_MONOTONIC)
81
-
82
- collector.complete_request(
83
- entry,
84
- status: response.code.to_i,
85
- duration: duration,
86
- response_headers: Redaction.filter_headers(response.to_hash.transform_values { |v| v.join(", ") }),
87
- response_body: processed_resp[:body],
88
- response_body_encoding: processed_resp[:encoding],
89
- response_size: streamed ? (declared_length(response) || 0) : resp_body_raw.bytesize,
90
- response_body_truncated: resp_truncated,
91
- response_body_not_captured: streamed
92
- )
93
-
94
- fg = Thread.current[:profiler_flamegraph_collector]
95
- fg&.record_http_event(started_at: t0, finished_at: t1, url: url, method: req.method, status: response.code.to_i)
68
+ # Only record response details if the collector accepted the request
69
+ if entry
70
+ duration = ((Process.clock_gettime(Process::CLOCK_MONOTONIC) - t0) * 1000).round(2)
71
+ # read_body with a block hands each chunk to the block and keeps none: the response then
72
+ # holds a Net::ReadAdapter, whose to_s is an inspect and whose bytes are gone.
73
+ streamed = NetHttpInstrumentation.streamed_body?(response)
74
+ resp_body_raw = streamed ? "" : response.body.to_s
75
+ resp_content_encoding = response["content-encoding"].to_s.strip.downcase
76
+ resp_body = NetHttpInstrumentation.decompress_body(resp_body_raw, resp_content_encoding, limit)
77
+ resp_truncated = limit ? resp_body.bytesize > limit : false
78
+ resp_body = Redaction.cut_bytes(resp_body, limit) if resp_truncated
79
+ resp_content_type = response["content-type"].to_s
80
+ processed_resp = NetHttpInstrumentation.process_body(resp_body, resp_content_type)
81
+
82
+ t1 = Process.clock_gettime(Process::CLOCK_MONOTONIC)
83
+
84
+ collector.complete_request(
85
+ entry,
86
+ status: response.code.to_i,
87
+ duration: duration,
88
+ response_headers: Redaction.filter_headers(response.to_hash.transform_values { |v| v.join(", ") }),
89
+ response_body: processed_resp[:body],
90
+ response_body_encoding: processed_resp[:encoding],
91
+ response_size: streamed ? (declared_length(response) || 0) : resp_body_raw.bytesize,
92
+ response_body_truncated: resp_truncated,
93
+ response_body_not_captured: streamed
94
+ )
95
+
96
+ fg = Thread.current[:profiler_flamegraph_collector]
97
+ fg&.record_http_event(started_at: t0, finished_at: t1, url: url, method: req.method, status: response.code.to_i)
98
+ end
96
99
 
97
100
  response
98
101
  rescue => e
99
102
  duration = defined?(t0) && t0 ? ((Process.clock_gettime(Process::CLOCK_MONOTONIC) - t0) * 1000).round(2) : 0.0
100
- if defined?(entry) && entry
103
+ if defined?(entry) && entry && defined?(collector) && collector
101
104
  collector.fail_request(entry, error: e.message, duration: duration)
102
105
  end
103
106
  raise
@@ -54,7 +54,7 @@ module Profiler
54
54
  @server.resources_read_handler do |params|
55
55
  uri = params[:uri]
56
56
  handler = @resource_handlers[uri]
57
- next [{ uri: uri, mimeType: "application/json", text: "Resource not found: #{uri}" }] unless handler
57
+ next nil unless handler
58
58
 
59
59
  begin
60
60
  result = handler.call
@@ -10,7 +10,10 @@ module Profiler
10
10
  type = params["type"]
11
11
 
12
12
  if type && !%w[http job test console].include?(type)
13
- return [{ type: "text", text: "Error: type must be 'http', 'job', 'test', or 'console'" }]
13
+ return ::MCP::Tool::Response.new(
14
+ [{ type: "text", text: "Error: type must be 'http', 'job', 'test', or 'console'" }],
15
+ error: true
16
+ )
14
17
  end
15
18
 
16
19
  if (proxy = MCP::SlaveSupport.with_slave_proxy(params))
@@ -13,24 +13,46 @@ module Profiler
13
13
  query_index = params["query_index"]
14
14
 
15
15
  unless token
16
- return [{ type: "text", text: "Error: token parameter is required" }]
16
+ return ::MCP::Tool::Response.new(
17
+ [{ type: "text", text: "Error: token parameter is required" }],
18
+ error: true
19
+ )
17
20
  end
18
21
 
19
22
  if query_index.nil?
20
- return [{ type: "text", text: "Error: query_index parameter is required" }]
23
+ return ::MCP::Tool::Response.new(
24
+ [{ type: "text", text: "Error: query_index parameter is required" }],
25
+ error: true
26
+ )
21
27
  end
22
28
 
23
29
  if (proxy = MCP::SlaveSupport.with_slave_proxy(params))
24
30
  result = proxy.post_json("/_profiler/api/explain", { token: token, query_index: query_index.to_i })
25
- text = result["error"] ? "Error: #{result["error"]}" : result.inspect
26
- return [{ type: "text", text: text }]
31
+ if result["error"]
32
+ return ::MCP::Tool::Response.new(
33
+ [{ type: "text", text: "Error: #{result["error"]}" }],
34
+ error: true
35
+ )
36
+ end
37
+ return [{ type: "text", text: result.inspect }]
38
+ end
39
+
40
+ storage = MCP::SlaveSupport.resolve_storage(params)
41
+ resolved_token = if token == "latest"
42
+ latest = storage.list(limit: 1).first
43
+ latest ? latest.token : token
44
+ else
45
+ token
27
46
  end
28
47
 
29
48
  if (reason = Profiler::ExplainRunner.refusal)
30
- return [{ type: "text", text: "Error: #{reason}" }]
49
+ return ::MCP::Tool::Response.new(
50
+ [{ type: "text", text: "Error: #{reason}" }],
51
+ error: true
52
+ )
31
53
  end
32
54
 
33
- data = Profiler::ExplainRunner.run(token, query_index.to_i)
55
+ data = Profiler::ExplainRunner.run(resolved_token, query_index.to_i)
34
56
 
35
57
  lines = []
36
58
  lines << "# EXPLAIN ANALYZE - Query ##{query_index}"
@@ -48,10 +70,16 @@ module Profiler
48
70
 
49
71
  [{ type: "text", text: lines.join("\n") }]
50
72
  rescue Profiler::ExplainRunner::RefusedError => e
51
- [{ type: "text", text: "Error: #{e.message}" }]
73
+ ::MCP::Tool::Response.new(
74
+ [{ type: "text", text: "Error: #{e.message}" }],
75
+ error: true
76
+ )
52
77
  rescue Profiler::Error => e
53
78
  # The profiler's own refusals (unknown, offline or refused slave) carry a message made for the caller.
54
- [{ type: "text", text: "Error: #{e.message}" }]
79
+ ::MCP::Tool::Response.new(
80
+ [{ type: "text", text: "Error: #{e.message}" }],
81
+ error: true
82
+ )
55
83
  rescue StandardError => e
56
84
  # The database's message carries the SQL, and sometimes a path: the log only.
57
85
  Profiler.log_error("MCP explain_query: failed for query #{query_index.to_i} of profile #{token.to_s.inspect}", e)
@@ -79,7 +79,7 @@ module Profiler
79
79
  lines += section_logs(profile, params) if want.("logs")
80
80
  lines += section_env(profile, params) if want.("env")
81
81
  lines += section_i18n(profile) if want.("i18n")
82
- lines += section_related_jobs(profile) if want.("related_jobs")
82
+ lines += section_related_jobs(profile, params) if want.("related_jobs")
83
83
  lines.join("\n")
84
84
  end
85
85
 
@@ -622,12 +622,13 @@ module Profiler
622
622
  lines
623
623
  end
624
624
 
625
- def self.section_related_jobs(profile)
625
+ def self.section_related_jobs(profile, params = {})
626
+ storage = MCP::SlaveSupport.resolve_storage(params)
626
627
  lines = []
627
628
 
628
629
  # Parent info
629
630
  if profile.parent_token
630
- parent = Profiler.storage.load(profile.parent_token)
631
+ parent = storage.load(profile.parent_token)
631
632
  if parent
632
633
  lines << "## Triggered By"
633
634
  if parent.profile_type == "job"
@@ -649,7 +650,7 @@ module Profiler
649
650
  end
650
651
 
651
652
  # Child jobs
652
- child_jobs = Profiler.storage.find_by_parent(profile.token).select { |p| p.profile_type == "job" }
653
+ child_jobs = storage.find_by_parent(profile.token).select { |p| p.profile_type == "job" }
653
654
  return lines if child_jobs.empty?
654
655
 
655
656
  lines << "## Child Jobs (#{child_jobs.size})"
@@ -9,7 +9,7 @@ module Profiler
9
9
  ALL_FIELDS = %w[time expression return_value status duration queries token].freeze
10
10
 
11
11
  def self.call(params)
12
- limit = params["limit"]&.to_i || 20
12
+ limit = [[params["limit"]&.to_i || 20, 1].max, 500].min
13
13
  fetch_size = [limit * 5, 500].min
14
14
  storage = MCP::SlaveSupport.resolve_storage(params)
15
15
  profiles = storage.list(limit: fetch_size, type: "console")
@@ -9,7 +9,7 @@ module Profiler
9
9
  ALL_FIELDS = %w[time job_class queue status duration gem_version token parent_token].freeze
10
10
 
11
11
  def self.call(params)
12
- limit = params["limit"]&.to_i || 20
12
+ limit = [[params["limit"]&.to_i || 20, 1].max, 500].min
13
13
  fetch_size = [limit * 5, 500].min
14
14
  storage = MCP::SlaveSupport.resolve_storage(params)
15
15
  profiles = storage.list(limit: fetch_size, type: "job")
@@ -10,7 +10,7 @@ module Profiler
10
10
 
11
11
  class << self
12
12
  def call(params)
13
- limit = params["limit"]&.to_i || 20
13
+ limit = [[params["limit"]&.to_i || 20, 1].max, 500].min
14
14
  fetch_size = [limit * 10, 1000].min
15
15
  storage = MCP::SlaveSupport.resolve_storage(params)
16
16
  profiles = storage.list(limit: fetch_size)
@@ -10,7 +10,7 @@ module Profiler
10
10
 
11
11
  def self.call(params)
12
12
  storage = MCP::SlaveSupport.resolve_storage(params)
13
- limit = params["limit"]&.to_i || 20
13
+ limit = [[params["limit"]&.to_i || 20, 1].max, 500].min
14
14
  fetch_size = [limit * 5, 500].min
15
15
  profiles = storage.list(limit: fetch_size, type: params["profile_type"])
16
16
 
@@ -9,7 +9,7 @@ module Profiler
9
9
  ALL_FIELDS = %w[time test_name status duration queries n1 token].freeze
10
10
 
11
11
  def self.call(params)
12
- limit = params["limit"]&.to_i || 20
12
+ limit = [[params["limit"]&.to_i || 20, 1].max, 500].min
13
13
  fetch_size = [limit * 5, 500].min
14
14
  storage = MCP::SlaveSupport.resolve_storage(params)
15
15
  profiles = storage.list(limit: fetch_size, type: "test")
@@ -33,10 +33,15 @@ module Profiler
33
33
  return [{ type: "text", text: "Set #{key}=#{value} on slave '#{params["slave"]}'" }]
34
34
  end
35
35
 
36
- Profiler.env_override_store.set(key, value)
37
- ENV[key] = value
38
-
39
- [{ type: "text", text: "Set #{key}=#{value}" }]
36
+ if value.empty?
37
+ Profiler.env_override_store.delete(key)
38
+ ENV.delete(key)
39
+ [{ type: "text", text: "Deleted #{key}" }]
40
+ else
41
+ Profiler.env_override_store.set(key, value)
42
+ ENV[key] = value
43
+ [{ type: "text", text: "Set #{key}=#{value}" }]
44
+ end
40
45
  rescue Profiler::EnvOverrideStore::Error => e
41
46
  ::MCP::Tool::Response.new([{ type: "text", text: "Error: #{e.message}; #{key} was left unchanged." }], error: true)
42
47
  end
@@ -1,7 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Profiler
4
- VERSION = "0.44.19"
4
+ VERSION = "0.44.21"
5
5
 
6
6
  GEM_ROOT = File.expand_path("../..", __dir__)
7
7
 
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: rails-profiler
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.44.19
4
+ version: 0.44.21
5
5
  platform: ruby
6
6
  authors:
7
7
  - Sébastien Duplessy