debug-agent 0.5.1 → 0.7.0
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 +4 -4
- data/README.md +86 -5
- data/lib/debug_agent/inspectors/build_info.rb +87 -0
- data/lib/debug_agent/inspectors/config_inspector.rb +137 -0
- data/lib/debug_agent/inspectors/cpu_profile.rb +192 -0
- data/lib/debug_agent/inspectors/endpoint_test.rb +284 -0
- data/lib/debug_agent/inspectors/feature_flags.rb +215 -0
- data/lib/debug_agent/inspectors/leak_detector.rb +161 -0
- data/lib/debug_agent/inspectors/locks.rb +343 -0
- data/lib/debug_agent/inspectors/migration.rb +150 -0
- data/lib/debug_agent/inspectors/pool_inspector.rb +320 -0
- data/lib/debug_agent/inspectors/service_registry.rb +88 -0
- data/lib/debug_agent/inspectors/snapshot.rb +206 -0
- data/lib/debug_agent/version.rb +1 -1
- data/lib/debug_agent.rb +20 -0
- metadata +12 -1
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: fe4d325302d304db5821ef8bc5283ce3978e26d7721604efcbf00a646229346c
|
|
4
|
+
data.tar.gz: '058ae474cc6e35f83f59ee86da1ca807af84a51762c66a9452827805e28664c9'
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: f72cf134d401b2f055e5103eea6b6d35e06bbc75f7962a6f33d37f906f91e6899a5f562a5a032209448f469c5830b24d582b43b34730fbf949a1c47d4a8b25cb
|
|
7
|
+
data.tar.gz: dbb70e23e5bce9c717c8ecbdf708b2724811beeac9fa3672f496ac25dfedda108f0c051f71c7af5a1421cf181d120534aff1a94f6c511df3af04a56745a19098
|
data/README.md
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
# Ruby Debug Agent
|
|
2
2
|
|
|
3
3
|
[](https://github.com/topcheer/ruby-debug-agent)
|
|
4
|
-

|
|
5
|
+

|
|
6
6
|

|
|
7
7
|

|
|
8
8
|
|
|
9
|
-
An AI-powered runtime debugging agent that embeds directly into your Ruby application. Add one gem, configure an LLM key, and chat with your live app at `/agent` to inspect GC, ObjectSpace, threads, routes, Redis, Rails models/routes, Sidekiq queues, Puma stats, fibers/signals, process info, HTTP requests, and more — **
|
|
9
|
+
An AI-powered runtime debugging agent that embeds directly into your Ruby application. Add one gem, configure an LLM key, and chat with your live app at `/agent` to inspect GC, ObjectSpace, threads, routes, Redis, Rails models/routes, Sidekiq queues, Puma stats, fibers/signals, process info, HTTP requests, and more — **98 diagnostic tools across 36 inspectors**.
|
|
10
10
|
|
|
11
11
|
## Version Support
|
|
12
12
|
|
|
@@ -71,10 +71,10 @@ http://localhost:4567/agent
|
|
|
71
71
|
- **Context compression** — automatically summarizes old conversation when token limit is approached
|
|
72
72
|
- **Dark-themed chat UI** with full markdown rendering (tables, code blocks, lists)
|
|
73
73
|
- **Max tool rounds** (25) with forced final summary when limit is reached
|
|
74
|
-
- **
|
|
74
|
+
- **98 diagnostic tools** across **36 inspectors**
|
|
75
75
|
- Zero external dependencies (no Datadog, no Grafana, no APM)
|
|
76
76
|
|
|
77
|
-
## Inspectors & Tools (
|
|
77
|
+
## Inspectors & Tools (98)
|
|
78
78
|
|
|
79
79
|
### GC Inspector
|
|
80
80
|
| Tool | Description |
|
|
@@ -209,6 +209,81 @@ http://localhost:4567/agent
|
|
|
209
209
|
|------|-------------|
|
|
210
210
|
| `get_concurrent_state` | Ruby concurrency primitives state (Mutex, ConditionVariable, Queue) |
|
|
211
211
|
|
|
212
|
+
### Deadlock & Lock Contention Inspector (v0.6.0)
|
|
213
|
+
| Tool | Description |
|
|
214
|
+
|------|-------------|
|
|
215
|
+
| `get_lock_contention` | Mutex contention stats (wait time, hold time, acquisition count) |
|
|
216
|
+
| `detect_deadlock` | Analyze all threads for deadlock patterns (circular wait detection) |
|
|
217
|
+
| `get_mutex_stats` | Per-lock statistics: total acquisitions, contentions, average wait time |
|
|
218
|
+
|
|
219
|
+
### Database Migration Inspector (v0.6.0)
|
|
220
|
+
| Tool | Description |
|
|
221
|
+
|------|-------------|
|
|
222
|
+
| `get_migration_status` | Current schema version, applied count, last migration applied |
|
|
223
|
+
| `get_pending_migrations` | Migrations not yet applied (version, description, dependencies) |
|
|
224
|
+
| `get_migration_history` | Applied migration history (version, applied_at, duration_ms) |
|
|
225
|
+
|
|
226
|
+
### Configuration Inspector (v0.6.0)
|
|
227
|
+
| Tool | Description |
|
|
228
|
+
|------|-------------|
|
|
229
|
+
| `get_config_snapshot` | All registered config values (sensitive keys masked) |
|
|
230
|
+
| `get_env_vars_masked` | Process environment variables with secret values redacted |
|
|
231
|
+
| `get_config_sources` | Config source hierarchy (env, file, defaults) with effective values |
|
|
232
|
+
|
|
233
|
+
### Feature Flags Inspector (v0.6.0)
|
|
234
|
+
| Tool | Description |
|
|
235
|
+
|------|-------------|
|
|
236
|
+
| `get_feature_flags` | List all registered feature flags with current state |
|
|
237
|
+
| `evaluate_feature_flag` | Evaluate a specific flag for a given context/user |
|
|
238
|
+
|
|
239
|
+
### Endpoint Testing Inspector (v0.6.0)
|
|
240
|
+
| Tool | Description |
|
|
241
|
+
|------|-------------|
|
|
242
|
+
| `test_endpoint` | Make an HTTP request to own app, return full response (status, headers, body) |
|
|
243
|
+
| `batch_test_endpoints` | Test multiple endpoints in one call with aggregated results |
|
|
244
|
+
| `get_endpoint_coverage` | Compare registered routes vs tested endpoints (coverage report) |
|
|
245
|
+
|
|
246
|
+
### Connection Pool Inspector (v0.6.0)
|
|
247
|
+
| Tool | Description |
|
|
248
|
+
|------|-------------|
|
|
249
|
+
| `get_pool_details` | Detailed DB pool stats (pool size, active, idle, waiting, max) |
|
|
250
|
+
| `detect_pool_leaks` | Heuristic leak detection (growing pool, high wait ratio, saturation) |
|
|
251
|
+
| `get_pool_wait_stats` | Connection acquire wait stats (avg, P95, max wait, timeout count) |
|
|
252
|
+
|
|
253
|
+
### CPU Profiler Inspector (v0.7.0)
|
|
254
|
+
| Tool | Description |
|
|
255
|
+
|------|-------------|
|
|
256
|
+
| `start_cpu_profile` | Start a CPU profiling session (stackprof/stackprof-native) |
|
|
257
|
+
| `stop_cpu_profile` | Stop CPU profiling and return collected profile data |
|
|
258
|
+
| `get_top_functions` | Get top CPU-consuming functions from the current profile |
|
|
259
|
+
|
|
260
|
+
### Memory Leak Detector Inspector (v0.7.0)
|
|
261
|
+
| Tool | Description |
|
|
262
|
+
|------|-------------|
|
|
263
|
+
| `take_heap_snapshot` | Capture an ObjectSpace heap snapshot for leak analysis |
|
|
264
|
+
| `compare_heap_snapshots` | Compare two heap snapshots to identify object growth |
|
|
265
|
+
| `get_leak_candidates` | Identify objects likely to be memory leaks |
|
|
266
|
+
|
|
267
|
+
### Deployment/Build Info Inspector (v0.7.0)
|
|
268
|
+
| Tool | Description |
|
|
269
|
+
|------|-------------|
|
|
270
|
+
| `get_build_info` | Build version, commit hash, and gem metadata |
|
|
271
|
+
| `get_deployment_info` | Deployment environment, container, and orchestration metadata |
|
|
272
|
+
| `get_runtime_version` | Ruby interpreter version, engine, and platform details |
|
|
273
|
+
|
|
274
|
+
### Snapshot & Diff Inspector (v0.7.0)
|
|
275
|
+
| Tool | Description |
|
|
276
|
+
|------|-------------|
|
|
277
|
+
| `take_snapshot` | Capture a runtime state snapshot |
|
|
278
|
+
| `compare_snapshots` | Compare two snapshots to identify state changes |
|
|
279
|
+
| `list_snapshots` | List all saved snapshots with timestamps |
|
|
280
|
+
|
|
281
|
+
### Service Registry Inspector (v0.7.0)
|
|
282
|
+
| Tool | Description |
|
|
283
|
+
|------|-------------|
|
|
284
|
+
| `get_registered_services` | List all registered application services |
|
|
285
|
+
| `get_service_dependencies` | Map service-to-service dependency graph |
|
|
286
|
+
|
|
212
287
|
## Custom Tools
|
|
213
288
|
|
|
214
289
|
```ruby
|
|
@@ -261,6 +336,12 @@ cd demo && ruby -I../lib app.rb
|
|
|
261
336
|
|
|
262
337
|
[](https://github.com/topcheer/ruby-debug-agent)
|
|
263
338
|
|
|
339
|
+
## Built With
|
|
340
|
+
|
|
341
|
+
[](https://github.com/topcheer/ggcode)
|
|
342
|
+
|
|
343
|
+
This project was built using [ggcode](https://github.com/topcheer/ggcode) — an AI coding assistant for terminal-based development.
|
|
344
|
+
|
|
264
345
|
## License
|
|
265
346
|
|
|
266
347
|
MIT
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
require 'socket'
|
|
2
|
+
require 'etc'
|
|
3
|
+
|
|
4
|
+
module DebugAgent
|
|
5
|
+
register_tool('get_build_info',
|
|
6
|
+
'Get Ruby build info: version, engine (MRI/JRuby/TruffleRuby), ' \
|
|
7
|
+
'platform, build date, RUBY_DESCRIPTION') do
|
|
8
|
+
{
|
|
9
|
+
ruby_version: RUBY_VERSION,
|
|
10
|
+
ruby_engine: RUBY_ENGINE,
|
|
11
|
+
ruby_engine_version: defined?(RUBY_ENGINE_VERSION) ? RUBY_ENGINE_VERSION : RUBY_VERSION,
|
|
12
|
+
platform: RUBY_PLATFORM,
|
|
13
|
+
ruby_description: RUBY_DESCRIPTION,
|
|
14
|
+
ruby_patchlevel: defined?(RUBY_PATCHLEVEL) ? RUBY_PATCHLEVEL : nil,
|
|
15
|
+
ruby_revision: defined?(RUBY_REVISION) ? RUBY_REVISION.to_s : nil,
|
|
16
|
+
ruby_release_date: defined?(RUBY_RELEASE_DATE) ? RUBY_RELEASE_DATE : nil,
|
|
17
|
+
build_date: defined?(RUBY_RELEASE_DATE) ? RUBY_RELEASE_DATE : nil,
|
|
18
|
+
host_os: RbConfig::CONFIG['host_os'],
|
|
19
|
+
host_cpu: RbConfig::CONFIG['host_cpu'],
|
|
20
|
+
configure_args: RbConfig::CONFIG['configure_args']
|
|
21
|
+
}
|
|
22
|
+
rescue => e
|
|
23
|
+
{ error: e.message }
|
|
24
|
+
end
|
|
25
|
+
|
|
26
|
+
register_tool('get_deployment_info',
|
|
27
|
+
'Get deployment info: hostname, PID, uptime, container detection, ' \
|
|
28
|
+
'APP_ENV, Rails env') do
|
|
29
|
+
rss = `ps -o rss= -p #{Process.pid}`.to_i
|
|
30
|
+
uptime_seconds = Time.now - DebugAgent::PROCESS_START_TIME
|
|
31
|
+
|
|
32
|
+
container_detected = File.exist?('/.dockerenv')
|
|
33
|
+
in_cgroup = false
|
|
34
|
+
begin
|
|
35
|
+
in_cgroup = File.read('/proc/1/cgroup').include?('docker') ||
|
|
36
|
+
File.read('/proc/1/cgroup').include?('containerd')
|
|
37
|
+
rescue
|
|
38
|
+
end
|
|
39
|
+
|
|
40
|
+
{
|
|
41
|
+
hostname: Socket.gethostname,
|
|
42
|
+
pid: Process.pid,
|
|
43
|
+
ppid: Process.ppid,
|
|
44
|
+
process_name: $0,
|
|
45
|
+
uptime_seconds: uptime_seconds.round(0),
|
|
46
|
+
rss_mb: (rss / 1024.0).round(2),
|
|
47
|
+
container_detected: container_detected || in_cgroup,
|
|
48
|
+
docker_detected: File.exist?('/.dockerenv'),
|
|
49
|
+
app_env: ENV['APP_ENV'] || ENV['RAILS_ENV'] || ENV['RACK_ENV'] || 'unknown',
|
|
50
|
+
rails_env: defined?(::Rails) ? ::Rails.env.to_s : nil,
|
|
51
|
+
user: Etc.getpwuid(Process.uid)&.name,
|
|
52
|
+
uid: Process.uid,
|
|
53
|
+
gid: Process.gid,
|
|
54
|
+
cpu_count: Etc.nprocessors
|
|
55
|
+
}
|
|
56
|
+
rescue => e
|
|
57
|
+
{ error: e.message }
|
|
58
|
+
end
|
|
59
|
+
|
|
60
|
+
register_tool('get_runtime_versions',
|
|
61
|
+
'Get versions of key gems: rails, sinatra, sidekiq, redis, puma ' \
|
|
62
|
+
'if loaded') do
|
|
63
|
+
key_gems = %w[rails sinatra sidekiq redis puma rack rack-attack \
|
|
64
|
+
activerecord activesupport postgresql pg mysql2 bunny \
|
|
65
|
+
faraday httplog oj msgpack json]
|
|
66
|
+
|
|
67
|
+
versions = {}
|
|
68
|
+
key_gems.each do |gem_name|
|
|
69
|
+
spec = Gem.loaded_specs[gem_name] || Gem.loaded_specs.values.find { |s| s.name == gem_name }
|
|
70
|
+
versions[gem_name] = spec&.version&.to_s if spec
|
|
71
|
+
end
|
|
72
|
+
|
|
73
|
+
# Remove nils
|
|
74
|
+
versions.compact!
|
|
75
|
+
|
|
76
|
+
{
|
|
77
|
+
ruby_version: RUBY_VERSION,
|
|
78
|
+
ruby_engine: RUBY_ENGINE,
|
|
79
|
+
rubygems_version: Gem::VERSION,
|
|
80
|
+
bundler_version: defined?(Bundler) ? Bundler::VERSION : nil,
|
|
81
|
+
loaded_gem_count: Gem.loaded_specs.size,
|
|
82
|
+
key_gem_versions: versions
|
|
83
|
+
}
|
|
84
|
+
rescue => e
|
|
85
|
+
{ error: e.message }
|
|
86
|
+
end
|
|
87
|
+
end
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
require 'time'
|
|
2
|
+
|
|
3
|
+
module DebugAgent
|
|
4
|
+
# Register configuration hashes for inspection.
|
|
5
|
+
#
|
|
6
|
+
# DebugAgent.register_config(:app, {
|
|
7
|
+
# app_name: 'MyApp',
|
|
8
|
+
# port: 4567,
|
|
9
|
+
# api_key: 'secret123'
|
|
10
|
+
# })
|
|
11
|
+
@registered_configs = {}
|
|
12
|
+
|
|
13
|
+
SENSITIVE_KEY_PATTERN = /password|secret|token|api.?key|private.?key|credential/i
|
|
14
|
+
|
|
15
|
+
class << self
|
|
16
|
+
attr_reader :registered_configs
|
|
17
|
+
|
|
18
|
+
def register_config(name, config_hash, source: 'registered')
|
|
19
|
+
@registered_configs[name.to_s] = {
|
|
20
|
+
values: config_hash,
|
|
21
|
+
source: source,
|
|
22
|
+
registered_at: Time.now.iso8601
|
|
23
|
+
}
|
|
24
|
+
end
|
|
25
|
+
end
|
|
26
|
+
|
|
27
|
+
class << self
|
|
28
|
+
private
|
|
29
|
+
|
|
30
|
+
def mask_sensitive(key, value)
|
|
31
|
+
return value unless value.is_a?(String) || value.is_a?(Symbol)
|
|
32
|
+
return '***' if key.to_s =~ SENSITIVE_KEY_PATTERN
|
|
33
|
+
value
|
|
34
|
+
end
|
|
35
|
+
|
|
36
|
+
def mask_config_hash(hash)
|
|
37
|
+
hash.map do |k, v|
|
|
38
|
+
if v.is_a?(Hash)
|
|
39
|
+
[k, mask_config_hash(v)]
|
|
40
|
+
else
|
|
41
|
+
[k, mask_sensitive(k, v)]
|
|
42
|
+
end
|
|
43
|
+
end.to_h
|
|
44
|
+
end
|
|
45
|
+
end
|
|
46
|
+
|
|
47
|
+
register_tool('get_config_snapshot',
|
|
48
|
+
'Get all registered configuration values. Sensitive keys (password, secret, ' \
|
|
49
|
+
'token, api_key, etc.) are automatically masked') do
|
|
50
|
+
if registered_configs.empty?
|
|
51
|
+
next { error: 'No configs registered. Call DebugAgent.register_config(:name, hash).' }
|
|
52
|
+
end
|
|
53
|
+
|
|
54
|
+
configs = registered_configs.map do |name, entry|
|
|
55
|
+
{
|
|
56
|
+
name: name,
|
|
57
|
+
source: entry[:source],
|
|
58
|
+
registered_at: entry[:registered_at],
|
|
59
|
+
values: mask_config_hash(entry[:values] || {}),
|
|
60
|
+
key_count: (entry[:values] || {}).size,
|
|
61
|
+
masked_keys: (entry[:values] || {}).keys.select { |k| k.to_s =~ SENSITIVE_KEY_PATTERN }
|
|
62
|
+
}
|
|
63
|
+
end
|
|
64
|
+
|
|
65
|
+
{
|
|
66
|
+
total_configs: configs.size,
|
|
67
|
+
configs: configs
|
|
68
|
+
}
|
|
69
|
+
rescue => e
|
|
70
|
+
{ error: e.message }
|
|
71
|
+
end
|
|
72
|
+
|
|
73
|
+
register_tool('get_env_vars',
|
|
74
|
+
'Dump environment variables (ENV) with optional prefix filter. ' \
|
|
75
|
+
'Sensitive values are automatically masked',
|
|
76
|
+
prefix: { type: 'string', description: 'Only return vars starting with this prefix (e.g. APP_, RAILS_)', required: false }) do |prefix: nil|
|
|
77
|
+
vars = ENV.to_h
|
|
78
|
+
|
|
79
|
+
if prefix && !prefix.to_s.empty?
|
|
80
|
+
vars = vars.select { |k, _| k.start_with?(prefix.to_s) }
|
|
81
|
+
end
|
|
82
|
+
|
|
83
|
+
masked = {}
|
|
84
|
+
sensitive_count = 0
|
|
85
|
+
vars.each do |k, v|
|
|
86
|
+
if k =~ SENSITIVE_KEY_PATTERN
|
|
87
|
+
masked[k] = '***'
|
|
88
|
+
sensitive_count += 1
|
|
89
|
+
else
|
|
90
|
+
masked[k] = v
|
|
91
|
+
end
|
|
92
|
+
end
|
|
93
|
+
|
|
94
|
+
{
|
|
95
|
+
total_vars: masked.size,
|
|
96
|
+
sensitive_masked: sensitive_count,
|
|
97
|
+
prefix_filter: prefix,
|
|
98
|
+
env_vars: masked
|
|
99
|
+
}
|
|
100
|
+
rescue => e
|
|
101
|
+
{ error: e.message }
|
|
102
|
+
end
|
|
103
|
+
|
|
104
|
+
register_tool('get_config_sources',
|
|
105
|
+
'Configuration provenance: shows where each registered config comes from ' \
|
|
106
|
+
'(environment, file, default, or registered)') do
|
|
107
|
+
if registered_configs.empty?
|
|
108
|
+
next { error: 'No configs registered. Call DebugAgent.register_config(:name, hash).' }
|
|
109
|
+
end
|
|
110
|
+
|
|
111
|
+
sources = registered_configs.map do |name, entry|
|
|
112
|
+
{
|
|
113
|
+
name: name,
|
|
114
|
+
source: entry[:source],
|
|
115
|
+
registered_at: entry[:registered_at],
|
|
116
|
+
keys: (entry[:values] || {}).keys
|
|
117
|
+
}
|
|
118
|
+
end
|
|
119
|
+
|
|
120
|
+
# Also show ENV as a config source
|
|
121
|
+
env_config_count = ENV.size
|
|
122
|
+
|
|
123
|
+
{
|
|
124
|
+
registered_config_sources: sources,
|
|
125
|
+
total_sources: sources.size,
|
|
126
|
+
env_var_count: env_config_count,
|
|
127
|
+
summary: {
|
|
128
|
+
registered: sources.count { |s| s[:source] == 'registered' },
|
|
129
|
+
file: sources.count { |s| s[:source] == 'file' },
|
|
130
|
+
env: sources.count { |s| s[:source] == 'env' },
|
|
131
|
+
default: sources.count { |s| s[:source] == 'default' }
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
rescue => e
|
|
135
|
+
{ error: e.message }
|
|
136
|
+
end
|
|
137
|
+
end
|
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
require 'timeout'
|
|
2
|
+
|
|
3
|
+
module DebugAgent
|
|
4
|
+
# CPU profiler inspector. Uses stackprof if available, otherwise falls back
|
|
5
|
+
# to a sampling profiler that periodically captures caller stacks.
|
|
6
|
+
@cpu_profile_data = nil
|
|
7
|
+
@cpu_profile_running = false
|
|
8
|
+
@cpu_profile_lock = Mutex.new
|
|
9
|
+
|
|
10
|
+
class << self
|
|
11
|
+
attr_reader :cpu_profile_data, :cpu_profile_running
|
|
12
|
+
end
|
|
13
|
+
|
|
14
|
+
register_tool('start_cpu_profile',
|
|
15
|
+
'Start CPU profiling for a given duration. Uses stackprof if available, ' \
|
|
16
|
+
'otherwise falls back to a sampling profiler. Auto-stops after duration.',
|
|
17
|
+
duration_seconds: { type: 'integer', description: 'Profile duration in seconds', required: false }) do |duration_seconds: 10|
|
|
18
|
+
duration = duration_seconds.to_i
|
|
19
|
+
duration = 10 if duration <= 0
|
|
20
|
+
|
|
21
|
+
@cpu_profile_lock.synchronize do
|
|
22
|
+
next { error: 'CPU profile already running' } if @cpu_profile_running
|
|
23
|
+
@cpu_profile_running = true
|
|
24
|
+
@cpu_profile_data = nil
|
|
25
|
+
end
|
|
26
|
+
|
|
27
|
+
if defined?(::StackProf)
|
|
28
|
+
# StackProf path: block-based profiling
|
|
29
|
+
StackProf.run(mode: :cpu, interval: 1000) do
|
|
30
|
+
sleep(duration)
|
|
31
|
+
end
|
|
32
|
+
@cpu_profile_lock.synchronize { @cpu_profile_running = false }
|
|
33
|
+
raw = StackProf.results
|
|
34
|
+
@cpu_profile_data = parse_stackprof(raw) if raw
|
|
35
|
+
{
|
|
36
|
+
status: 'completed',
|
|
37
|
+
backend: 'stackprof',
|
|
38
|
+
duration_seconds: duration,
|
|
39
|
+
samples: raw ? raw[:samples] : 0
|
|
40
|
+
}
|
|
41
|
+
else
|
|
42
|
+
# Fallback: sampling profiler using caller stacks
|
|
43
|
+
samples = Hash.new(0)
|
|
44
|
+
total_samples = 0
|
|
45
|
+
sample_lock = Mutex.new
|
|
46
|
+
end_time = Time.now + duration
|
|
47
|
+
|
|
48
|
+
sampler = Thread.new do
|
|
49
|
+
while Time.now < end_time && @cpu_profile_running
|
|
50
|
+
stack = caller(2)&.join("\n")
|
|
51
|
+
sample_lock.synchronize do
|
|
52
|
+
samples[stack] += 1
|
|
53
|
+
total_samples += 1
|
|
54
|
+
end if stack
|
|
55
|
+
sleep(0.001)
|
|
56
|
+
end
|
|
57
|
+
end
|
|
58
|
+
|
|
59
|
+
sampler.join
|
|
60
|
+
@cpu_profile_lock.synchronize { @cpu_profile_running = false }
|
|
61
|
+
@cpu_profile_data = parse_call_samples(samples, total_samples)
|
|
62
|
+
{
|
|
63
|
+
status: 'completed',
|
|
64
|
+
backend: 'sampling',
|
|
65
|
+
duration_seconds: duration,
|
|
66
|
+
total_samples: total_samples,
|
|
67
|
+
unique_stacks: samples.size
|
|
68
|
+
}
|
|
69
|
+
end
|
|
70
|
+
rescue => e
|
|
71
|
+
@cpu_profile_running = false
|
|
72
|
+
{ error: e.message }
|
|
73
|
+
end
|
|
74
|
+
|
|
75
|
+
register_tool('stop_cpu_profile',
|
|
76
|
+
'Stop CPU profiling and return top 20 methods by self time. ' \
|
|
77
|
+
'Each entry includes method name, file, line, self_ms, total_ms, calls.') do
|
|
78
|
+
next { error: 'No profile data available. Run start_cpu_profile first.' } unless @cpu_profile_data
|
|
79
|
+
|
|
80
|
+
@cpu_profile_running = false
|
|
81
|
+
top = (@cpu_profile_data[:functions] || []).first(20)
|
|
82
|
+
|
|
83
|
+
{
|
|
84
|
+
status: 'stopped',
|
|
85
|
+
backend: @cpu_profile_data[:backend],
|
|
86
|
+
total_samples: @cpu_profile_data[:total_samples],
|
|
87
|
+
top_functions: top
|
|
88
|
+
}
|
|
89
|
+
rescue => e
|
|
90
|
+
{ error: e.message }
|
|
91
|
+
end
|
|
92
|
+
|
|
93
|
+
register_tool('get_top_functions',
|
|
94
|
+
'Return top methods from last CPU profile. Sort by self_time, total_time, or calls.',
|
|
95
|
+
limit: { type: 'integer', description: 'Number of functions to return (default 20)', required: false },
|
|
96
|
+
sort_by: { type: 'string', description: 'Sort key: self_time, total_time, or calls (default self_time)', required: false }) do |limit: 20, sort_by: 'self_time'|
|
|
97
|
+
next { error: 'No profile data available. Run start_cpu_profile first.' } unless @cpu_profile_data
|
|
98
|
+
|
|
99
|
+
funcs = (@cpu_profile_data[:functions] || []).dup
|
|
100
|
+
sort_key = %w[self_time total_time calls].include?(sort_by.to_s) ? sort_by.to_sym : :self_time
|
|
101
|
+
funcs.sort_by! { |f| -f[sort_key].to_f }
|
|
102
|
+
top = funcs.first(limit.to_i > 0 ? limit.to_i : 20)
|
|
103
|
+
|
|
104
|
+
{
|
|
105
|
+
sort_by: sort_key,
|
|
106
|
+
total_functions: @cpu_profile_data[:functions]&.size || 0,
|
|
107
|
+
top_functions: top
|
|
108
|
+
}
|
|
109
|
+
rescue => e
|
|
110
|
+
{ error: e.message }
|
|
111
|
+
end
|
|
112
|
+
|
|
113
|
+
# --- Helpers ---
|
|
114
|
+
|
|
115
|
+
class << self
|
|
116
|
+
private
|
|
117
|
+
|
|
118
|
+
def parse_stackprof(raw)
|
|
119
|
+
return nil unless raw && raw[:frames]
|
|
120
|
+
|
|
121
|
+
funcs = raw[:frames].map do |_frame_key, frame|
|
|
122
|
+
{
|
|
123
|
+
method: frame[:name] || 'unknown',
|
|
124
|
+
file: frame[:file],
|
|
125
|
+
line: frame[:line],
|
|
126
|
+
self_ms: ((frame[:samples].to_f / raw[:samples].to_f) * (raw[:gc_profile_time] || raw[:walltime] || 0) * 1000).round(2),
|
|
127
|
+
total_ms: ((frame[:total_samples].to_f / raw[:samples].to_f) * (raw[:gc_profile_time] || raw[:walltime] || 0) * 1000).round(2),
|
|
128
|
+
calls: frame[:samples].to_i
|
|
129
|
+
}
|
|
130
|
+
end.sort_by { |f| -f[:self_ms] }
|
|
131
|
+
|
|
132
|
+
{
|
|
133
|
+
backend: 'stackprof',
|
|
134
|
+
total_samples: raw[:samples],
|
|
135
|
+
functions: funcs
|
|
136
|
+
}
|
|
137
|
+
end
|
|
138
|
+
|
|
139
|
+
def parse_call_samples(samples, total_samples)
|
|
140
|
+
method_stats = Hash.new { |h, k| h[k] = { self_time: 0, total_time: 0, calls: 0 } }
|
|
141
|
+
|
|
142
|
+
samples.each do |stack_str, count|
|
|
143
|
+
lines = stack_str.split("\n")
|
|
144
|
+
next if lines.empty?
|
|
145
|
+
|
|
146
|
+
# First line of caller(2) is the most recently called method
|
|
147
|
+
top_line = lines.first
|
|
148
|
+
parsed = parse_backtrace_line(top_line)
|
|
149
|
+
|
|
150
|
+
key = "#{parsed[:file]}:#{parsed[:method]}"
|
|
151
|
+
method_stats[key][:self_time] += count
|
|
152
|
+
method_stats[key][:total_time] += count
|
|
153
|
+
method_stats[key][:calls] += 1
|
|
154
|
+
|
|
155
|
+
# All lines contribute to total_time of their respective methods
|
|
156
|
+
lines.each do |line|
|
|
157
|
+
p = parse_backtrace_line(line)
|
|
158
|
+
k = "#{p[:file]}:#{p[:method]}"
|
|
159
|
+
method_stats[k][:total_time] += count
|
|
160
|
+
method_stats[k][:calls] += count unless k == key
|
|
161
|
+
end
|
|
162
|
+
end
|
|
163
|
+
|
|
164
|
+
funcs = method_stats.map do |_k, s|
|
|
165
|
+
parsed = parse_backtrace_line(samples.keys.find { |stk| stk.include?(_k) || true }&.split("\n")&.first || '')
|
|
166
|
+
{
|
|
167
|
+
method: _k.split(':').last,
|
|
168
|
+
file: _k.split(':')[0...-1].join(':'),
|
|
169
|
+
line: parsed[:line],
|
|
170
|
+
self_ms: (s[:self_time].to_f / total_samples.to_f * 10000).round(2),
|
|
171
|
+
total_ms: (s[:total_time].to_f / total_samples.to_f * 10000).round(2),
|
|
172
|
+
calls: s[:calls]
|
|
173
|
+
}
|
|
174
|
+
end.sort_by { |f| -f[:self_ms] }
|
|
175
|
+
|
|
176
|
+
{
|
|
177
|
+
backend: 'sampling',
|
|
178
|
+
total_samples: total_samples,
|
|
179
|
+
functions: funcs
|
|
180
|
+
}
|
|
181
|
+
end
|
|
182
|
+
|
|
183
|
+
def parse_backtrace_line(line)
|
|
184
|
+
# Format: "/path/to/file.rb:42:in `method_name'"
|
|
185
|
+
if line =~ /^(.+):(\d+):in `(.+)'$/
|
|
186
|
+
{ file: $1, line: $2.to_i, method: $3 }
|
|
187
|
+
else
|
|
188
|
+
{ file: 'unknown', line: 0, method: 'unknown' }
|
|
189
|
+
end
|
|
190
|
+
end
|
|
191
|
+
end
|
|
192
|
+
end
|