Module: HeapScope

Defined in:
lib/heapscope.rb,
lib/heapscope/cli.rb,
lib/heapscope/diff.rb,
lib/heapscope/pack.rb,
lib/heapscope/aging.rb,
lib/heapscope/graph.rb,
lib/heapscope/noise.rb,
lib/heapscope/paths.rb,
lib/heapscope/rails.rb,
lib/heapscope/rspec.rb,
lib/heapscope/budget.rb,
lib/heapscope/config.rb,
lib/heapscope/errors.rb,
lib/heapscope/growth.rb,
lib/heapscope/report.rb,
lib/heapscope/schema.rb,
lib/heapscope/tables.rb,
lib/heapscope/catalog.rb,
lib/heapscope/globals.rb,
lib/heapscope/monitor.rb,
lib/heapscope/runtime.rb,
lib/heapscope/session.rb,
lib/heapscope/suggest.rb,
lib/heapscope/version.rb,
lib/heapscope/analyzer.rb,
lib/heapscope/baseline.rb,
lib/heapscope/branding.rb,
lib/heapscope/cli/help.rb,
lib/heapscope/closures.rb,
lib/heapscope/findings.rb,
lib/heapscope/minitest.rb,
lib/heapscope/snapshot.rb,
lib/heapscope/cli/color.rb,
lib/heapscope/collector.rb,
lib/heapscope/detectors.rb,
lib/heapscope/retention.rb,
lib/heapscope/scorecard.rb,
lib/heapscope/dominators.rb,
lib/heapscope/middleware.rb,
lib/heapscope/cli/support.rb,
lib/heapscope/report/html.rb,
lib/heapscope/report/text.rb,
lib/heapscope/runtime/mri.rb,
lib/heapscope/trend_store.rb,
lib/heapscope/capabilities.rb,
lib/heapscope/runtime/base.rb,
lib/heapscope/extrapolation.rb,
lib/heapscope/notifications.rb,
lib/heapscope/runtime/jruby.rb,
lib/heapscope/cli/completion.rb,
lib/heapscope/report/markdown.rb,
lib/heapscope/cli/commands/meta.rb,
lib/heapscope/sidekiq_middleware.rb,
lib/heapscope/runtime/truffleruby.rb,
lib/heapscope/runtime/windows_rss.rb,
lib/heapscope/cli/commands/capture.rb,
lib/heapscope/cli/commands/diffing.rb,
lib/heapscope/cli/commands/reporting.rb

Overview

Optional Minitest helpers: require "heapscope/minitest"

Defined Under Namespace

Modules: Baseline, Branding, Catalog, Classification, Closures, ConfigLoader, Detectors, Diagnostics, Extrapolation, Fibers, Findings, Fragmentation, Globals, Growth, Minitest, Noise, Notifications, Overhead, Pack, Paths, RSpecMatchers, Rails, Reproduction, Runtime, Schema, Suggest, Tables Classes: Aging, AllocationTracer, AnalysisLimitError, Analyzer, Budget, BudgetExceededError, CLI, Capabilities, CapabilityError, Collector, Config, ConfigurationError, Diff, Dominators, Error, Finding, GCTracker, Graph, InvalidReportError, Middleware, Monitor, Probe, Report, RetentionSession, Scorecard, Session, SidekiqMiddleware, Snapshot, SnapshotError, TrendStore, UnsupportedRuntimeError

Constant Summary collapse

VERSION =
"0.6.0"
SCHEMA_VERSION =
1

Class Method Summary collapse

Class Method Details

.aboutObject



257
258
259
# File 'lib/heapscope.rb', line 257

def about
  Branding.about_text
end

.after_warmupObject



187
188
189
190
# File 'lib/heapscope/config.rb', line 187

def after_warmup
  yield if block_given?
  config.warmup_done = true
end

.brandingObject



261
262
263
# File 'lib/heapscope.rb', line 261

def branding
  Branding.to_h
end

.budget_preset(name) ⇒ Object



273
274
275
# File 'lib/heapscope.rb', line 273

def budget_preset(name)
  Budget.preset(name)
end

.capabilitiesObject



215
216
217
# File 'lib/heapscope.rb', line 215

def capabilities
  Capabilities.new(Runtime.current)
end

.check(budget:, **opts, &block) ⇒ Object

Like check_budget, but raises BudgetExceededError on failure.



208
209
210
211
212
213
# File 'lib/heapscope.rb', line 208

def check(budget:, **opts, &block)
  report = check_budget(budget: budget, **opts, &block)
  return report if report.passed_budget?

  raise BudgetExceededError, report.budget_result[:violations].join("; ")
end

.check_budget(budget:, force_gc: true, mode: :standard, metadata: {}, &block) ⇒ Object

Soft check — always returns a report with budget_result.

Raises:

  • (ArgumentError)


182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
# File 'lib/heapscope.rb', line 182

def check_budget(budget:, force_gc: true, mode: :standard, metadata: {}, &block)
  raise ArgumentError, "block required" unless block

  report = measure(force_gc: force_gc, mode: mode, metadata: , &block)
  result = budget.evaluate(report)
  Report.new(
    schema_version: report.schema_version,
    heapscope_version: report.heapscope_version,
    runtime_info: report.runtime_info,
    summary: report.summary.merge(budget_passed: result[:passed]),
    before: report.before,
    after: report.after,
    diff: report.diff,
    findings: report.findings,
    suspects: report.suspects,
    classes: report.classes,
    allocation_sites: report.allocation_sites,
    retention: report.retention,
    metadata: report.,
    limitations: report.limitations,
    budget_result: result,
    reproduction: report.reproduction
  )
end

.codesObject



253
254
255
# File 'lib/heapscope.rb', line 253

def codes
  Catalog.codes
end

.compare(before, after, metadata: {}) ⇒ Object



49
50
51
52
53
54
55
# File 'lib/heapscope.rb', line 49

def compare(before, after, metadata: {})
  before = Snapshot.load(before) if before.is_a?(String)
  after = Snapshot.load(after) if after.is_a?(String)
  diff = Diff.new(before, after)
  analysis = Analyzer.new.analyze_diff(diff, context: )
  Report.from_diff(diff, analysis: analysis, metadata: )
end

.configObject



170
171
172
# File 'lib/heapscope/config.rb', line 170

def config
  @config ||= Config.new
end

.configure {|config| ... } ⇒ Object

Yields:



174
175
176
177
# File 'lib/heapscope/config.rb', line 174

def configure
  yield config
  self
end

.doctorObject



223
224
225
226
227
228
229
230
231
232
233
234
235
# File 'lib/heapscope.rb', line 223

def doctor
  {
    version: VERSION,
    ruby: RUBY_VERSION,
    engine: RUBY_ENGINE,
    platform: RUBY_PLATFORM,
    capabilities: capabilities.to_h,
    config: {
      mode: config.mode,
      ignore_patterns: config.ignore_patterns.map(&:inspect)
    }
  }
end

.experiment(runs: 10, force_gc: true, mode: :lightweight, metadata: {}, &block) ⇒ Object

Raises:

  • (ArgumentError)


136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
# File 'lib/heapscope.rb', line 136

def experiment(runs: 10, force_gc: true, mode: :lightweight, metadata: {}, &block)
  raise ArgumentError, "block required" unless block_given?

  results = runs.times.map do |i|
    measure(force_gc: force_gc, mode: mode, metadata: .merge(run: i), &block)
  end

  retained = results.map { |r| r.diff&.surviving_estimate.to_i }
  rss = results.map { |r| r.diff&.rss_delta.to_i }
  stats = lambda do |arr|
    sorted = arr.sort
    {
      min: sorted.first,
      max: sorted.last,
      median: percentile(sorted, 50),
      p95: percentile(sorted, 95),
      mean: (arr.sum.to_f / arr.size).round(2),
      variance: Growth.sample_variance(arr.map(&:to_f)).round(2)
    }
  end

  Report.new(
    runtime_info: { ruby: RUBY_VERSION, engine: RUBY_ENGINE },
    summary: {
      healthy: results.all?(&:healthy?),
      runs: runs,
      retained_objects: stats.call(retained),
      rss_delta: stats.call(rss)
    },
    findings: results.flat_map(&:findings).uniq { |f| [f.code, f.subject] },
    suspects: results.flat_map(&:suspects).group_by { |s| s[:name] }.map do |_name, list|
      list.max_by { |s| s[:delta_count] }.merge(runs_seen: list.size)
    end,
    metadata: .merge(kind: "experiment", runs: runs),
    before: results.first&.before,
    after: results.last&.after,
    diff: results.last&.diff,
    classes: results.last&.classes || []
  )
end

.ignore_class(klass) ⇒ Object



183
184
185
# File 'lib/heapscope/config.rb', line 183

def ignore_class(klass)
  config.ignored_classes << klass
end

.load_config!(path) ⇒ Object



192
193
194
# File 'lib/heapscope/config.rb', line 192

def load_config!(path)
  ConfigLoader.load!(path)
end

.measure(force_gc: config.force_gc_default, mode: nil, recovery_wait: nil, track_allocations: config.track_allocations, metadata: {}) ⇒ Object



57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
# File 'lib/heapscope.rb', line 57

def measure(force_gc: config.force_gc_default, mode: nil, recovery_wait: nil,
            track_allocations: config.track_allocations, metadata: {})
  raise ArgumentError, "block required" unless block_given?

  tracer = AllocationTracer.new
  tracing = track_allocations && tracer.available?
  tracer.start! if tracing

  GC.start if force_gc
  before = snapshot(mode: mode || :standard, metadata: .merge(phase: "before"))

  allocated_before = Runtime.current.gc_stat[:total_allocated_objects]
  t0 = Process.clock_gettime(Process::CLOCK_MONOTONIC)
  result = yield
  elapsed = Process.clock_gettime(Process::CLOCK_MONOTONIC) - t0
  allocated_after = Runtime.current.gc_stat[:total_allocated_objects]

  immediately_after = snapshot(mode: mode || :standard, metadata: .merge(phase: "immediately_after"))

  GC.start if force_gc
  after_gc = snapshot(mode: mode || :standard, metadata: .merge(phase: "after_gc"))

  after_idle = nil
  if recovery_wait&.positive?
    sleep recovery_wait
    GC.start if force_gc
    after_idle = snapshot(mode: mode || :lightweight, metadata: .merge(phase: "after_idle"))
  end

  final = after_idle || after_gc
  diff = Diff.new(before, final)
  analysis = Analyzer.new.analyze_diff(
    diff,
    context: .merge(force_gc: force_gc)
  )

  allocated = (allocated_after || 0) - (allocated_before || 0)
  rate = elapsed.positive? ? (allocated / elapsed) : nil

  report = Report.from_diff(
    diff,
    analysis: analysis,
    metadata: .merge(
      kind: "measure",
      force_gc: force_gc,
      elapsed_seconds: elapsed.round(4),
      objects_allocated_during: allocated,
      allocation_rate_per_sec: rate&.round(1),
      phases: {
        before: before.id,
        immediately_after: immediately_after.id,
        after_gc: after_gc.id,
        after_idle: after_idle&.id
      }.compact,
      recovery: recovery_stats(before, immediately_after, after_gc, after_idle),
      block_result_class: result.class.name
    )
  )
  report
ensure
  tracer&.stop! if tracing
end

.next_steps(report, limit: 8) ⇒ Object



269
270
271
# File 'lib/heapscope.rb', line 269

def next_steps(report, limit: 8)
  Suggest.next_steps(report, limit: limit)
end

.overhead(mode: :lightweight, runs: 3) ⇒ Object



237
238
239
# File 'lib/heapscope.rb', line 237

def overhead(mode: :lightweight, runs: 3)
  Overhead.measure_snapshot(mode: mode, runs: runs)
end

.pack(report, dir, label: "heapscope-report") ⇒ Object



277
278
279
# File 'lib/heapscope.rb', line 277

def pack(report, dir, label: "heapscope-report")
  Pack.export(report, dir, label: label)
end

.probe(title: "probe", **opts, &block) ⇒ Object



241
242
243
# File 'lib/heapscope.rb', line 241

def probe(title: "probe", **opts, &block)
  Probe.run(title: title, **opts, &block)
end

.repeat(times, force_gc: true, mode: :lightweight, &block) ⇒ Object



177
178
179
# File 'lib/heapscope.rb', line 177

def repeat(times, force_gc: true, mode: :lightweight, &block)
  retention_test(cycles: times, force_gc: force_gc, mode: mode, &block)
end

.reset_config!Object



179
180
181
# File 'lib/heapscope/config.rb', line 179

def reset_config!
  @config = Config.new
end

.retention_test(cycles: 5, force_gc: true, mode: :lightweight, metadata: {}) ⇒ Object

Raises:

  • (ArgumentError)


120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
# File 'lib/heapscope.rb', line 120

def retention_test(cycles: 5, force_gc: true, mode: :lightweight, metadata: {})
  raise ArgumentError, "block required" unless block_given?

  session = RetentionSession.new(force_gc: force_gc, mode: mode, metadata: )
  session.sample(label: "baseline")
  cycles.times do |i|
    yield
    session.sample(label: "cycle_#{i + 1}")
  end
  report = session.finish
  # Enrich metadata
  report.[:kind] = "retention_test"
  report.[:cycles] = cycles
  report
end

.runtimeObject



219
220
221
# File 'lib/heapscope.rb', line 219

def runtime
  Runtime.current
end

.scorecard(report, title: "HeapScope") ⇒ Object



249
250
251
# File 'lib/heapscope.rb', line 249

def scorecard(report, title: "HeapScope")
  Scorecard.from_report(report, title: title)
end

.session(name, root: Dir.pwd) ⇒ Object



245
246
247
# File 'lib/heapscope.rb', line 245

def session(name, root: Dir.pwd)
  Session.open(name, root: root)
end

.snapshot(mode: nil, **opts) ⇒ Object



45
46
47
# File 'lib/heapscope.rb', line 45

def snapshot(mode: nil, **opts)
  Collector.new.capture(mode: mode, **opts)
end

.suggest_ignores(report) ⇒ Object



265
266
267
# File 'lib/heapscope.rb', line 265

def suggest_ignores(report)
  Suggest.ignore_patterns(report)
end

.write_config!(path = "heapscope.yml", force: false) ⇒ Object



281
282
283
# File 'lib/heapscope.rb', line 281

def write_config!(path = "heapscope.yml", force: false)
  ConfigLoader.write_starter!(path, force: force)
end