lowrail-profile 0.1.2
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 +7 -0
- data/LICENSE +21 -0
- data/README-profile.md +307 -0
- data/data/contributions-index.json +1 -0
- data/exe/lowrail-profile +335 -0
- data/ext/lowrail_profile/extconf.rb +4 -0
- data/ext/lowrail_profile/lowrail_profile.c +670 -0
- data/lib/lowrail/load_hooks.rb +133 -0
- data/lib/lowrail/loaded_constant.rb +31 -0
- data/lib/lowrail/profile.rb +521 -0
- data/lib/lowrail/profile_compare.rb +347 -0
- data/lib/lowrail/profile_report.rb +777 -0
- data/lib/lowrail/profile_version.rb +7 -0
- data/lib/lowrail/profile_workloads.rb +157 -0
- data/lib/lowrail/workloads.rb +489 -0
- metadata +60 -0
|
@@ -0,0 +1,777 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "json"
|
|
4
|
+
require_relative "profile_version"
|
|
5
|
+
|
|
6
|
+
module Lowrail
|
|
7
|
+
# Reads lowrail-profile runs (DIR/runN/PID.tsv, written by lowrail/profile)
|
|
8
|
+
# and writes DIR/report.md and DIR/report.json: lines in Rails, Ruby and gems
|
|
9
|
+
# ranked by warm objects per request, grouped by gem, with the difference
|
|
10
|
+
# between runs as the noise floor and matching entries of Lowrail's
|
|
11
|
+
# contributions ledger; the app lines and controller actions that lead to
|
|
12
|
+
# them; and jobs, mails and Action Cable actions apart from requests. Keys follow the census (RAILS/actionpack/lib/...,
|
|
13
|
+
# GEM/name/path, RUBY/path), so a report can be set against `script/census rank`.
|
|
14
|
+
#
|
|
15
|
+
# Warm leaves out, per process, the objects a line allocated in the first
|
|
16
|
+
# request that reached it: lazy one-time work (route table, template
|
|
17
|
+
# compilation, i18n load) that the census removes with 50 warmup operations.
|
|
18
|
+
class ProfileReport
|
|
19
|
+
RAILS = %w[actioncable actionmailbox actionmailer actionpack actiontext actionview activejob activemodel
|
|
20
|
+
activerecord activestorage activesupport railties].freeze
|
|
21
|
+
RAILS_NAMES = { "actionpack" => ["Action Pack", "action_dispatch", "action_controller"],
|
|
22
|
+
"actionview" => ["Action View"], "activerecord" => ["Active Record", "Arel"],
|
|
23
|
+
"activesupport" => ["Active Support"], "activemodel" => ["Active Model"], "activejob" => ["Active Job"],
|
|
24
|
+
"actiontext" => ["Action Text"], "activestorage" => ["Active Storage"], "actioncable" => ["Action Cable"],
|
|
25
|
+
"actionmailer" => ["Action Mailer"], "railties" => ["Railties"] }.freeze
|
|
26
|
+
RAILS_PATH = %r{/(?:gems|bundler/gems)/(?:rails-[^/]+/(#{RAILS.join("|")})|(#{RAILS.join("|")})-\d[^/]*)/(.+)\z}
|
|
27
|
+
GEM_PATH = %r{/(?:gems|bundler/gems)/([^/]+?)-(\d[^/]*|\h{12})/(.+)\z}
|
|
28
|
+
# Objects ObjectSpace.each_object never yields, so the census cannot see them.
|
|
29
|
+
INTERNAL = %w[IMEMO Node ICLASS Zombie Moved NONE].freeze
|
|
30
|
+
# Test clients and runners, when a test suite is the workload.
|
|
31
|
+
HARNESS = /\A(?:rack-test|minitest|rspec-\w+|capybara|selenium-webdriver|webmock|vcr)\z/
|
|
32
|
+
NOT_RANKED = ["app", "other", "lowrail-profile", "(no Ruby frame)"].freeze
|
|
33
|
+
# Work that development and test mode do and production mostly does not:
|
|
34
|
+
# the census (production, log level fatal, warmed up) never ranks these.
|
|
35
|
+
MODE_ONLY = {
|
|
36
|
+
"debug logging" => %r{/(?:log_subscriber|colorize_logging|structured_event_subscriber|event_reporter|logger)\.rb\z|\AGEM/logger/},
|
|
37
|
+
"error page" => %r{/(?:exception_wrapper|debug_exceptions|backtrace_cleaner|show_exceptions)\.rb\z|\ARUBY/error_highlight/|\AGEM/prism/},
|
|
38
|
+
"template compile" => %r{\AGEM/(?:erubi|herb|temple|slim|haml|hamlit)/|/action_view/template(?:\.rb|/handlers/)},
|
|
39
|
+
"route build" => %r{/action_dispatch/journey/(?:gtg|nfa)/},
|
|
40
|
+
# Vite Ruby checks the build on each lookup with autoBuild (its dev and
|
|
41
|
+
# test default); Sprockets compiles live in test unless precompiled.
|
|
42
|
+
"asset lookup" => %r{\AGEM/(?:propshaft|importmap-rails|vite_ruby|vite_rails|sprockets|sprockets-rails)/},
|
|
43
|
+
"reload check" => %r{/active_support/(?:evented_)?file_update_checker\.rb\z}
|
|
44
|
+
}.freeze
|
|
45
|
+
|
|
46
|
+
KINDS = %w[request job mail cable].freeze
|
|
47
|
+
# Warm requests an action needs in every run to rank by warm.
|
|
48
|
+
MIN_WARM = 2
|
|
49
|
+
# report.json's format; compare reads only its own. 3: app and path-gem keys of 8e36ae06, timed_out.
|
|
50
|
+
# 4: objects allocated inside Socket.tcp left out of actions and lines, counted apart (network).
|
|
51
|
+
FORMAT = 4
|
|
52
|
+
KIND_TITLES = { "job" => "Jobs", "mail" => "Mails", "cable" => "Action Cable" }.freeze
|
|
53
|
+
# The name lowrail/profile gives a request ActionDispatch::Static answers before routing.
|
|
54
|
+
STATIC = "ActionDispatch::FileHandler#serve"
|
|
55
|
+
|
|
56
|
+
# App middleware that hands the request on is the nearest app frame of
|
|
57
|
+
# the whole stack below it, so it is listed apart, not ranked.
|
|
58
|
+
PASSES_ON = /(?:\A|[\s=(])@?app\.call\(/
|
|
59
|
+
|
|
60
|
+
Site = Struct.new(:key, :group, :path, :line, :all, :warm, :reached, :types, :via, :kind, keyword_init: true)
|
|
61
|
+
|
|
62
|
+
attr_reader :dir, :runs
|
|
63
|
+
|
|
64
|
+
def initialize(dir, ledger: nil, top: 30)
|
|
65
|
+
@dir = dir
|
|
66
|
+
@top = top
|
|
67
|
+
@ledger = ledger if ledger && File.exist?(ledger)
|
|
68
|
+
@paths, @path_ids, @locs, @loc_ids, @window_names, @window_ids = [], {}, [], {}, [], {}
|
|
69
|
+
@runs = self.class.run_dirs(dir).map { load_run(_1) }
|
|
70
|
+
if @runs.empty? || @runs.all? { _1[:windows].values.sum == 0 }
|
|
71
|
+
tests = @runs.empty? ? 0 : @runs[0][:controller_tests]
|
|
72
|
+
raise "no runs with requests, jobs or mails under #{dir} (a request counts when it goes through the app, as in " \
|
|
73
|
+
"integration, request and system tests; controller tests and controller specs call the controller directly " \
|
|
74
|
+
"and are not counted#{"; run 1 made #{tests} request#{"s" if tests != 1} from controller tests" if tests > 0})"
|
|
75
|
+
end
|
|
76
|
+
end
|
|
77
|
+
|
|
78
|
+
# DIR/runN, listed rather than globbed: DIR may hold [, { or *.
|
|
79
|
+
def self.run_dirs(dir)
|
|
80
|
+
Dir.children(dir).grep(/\Arun\d+\z/).select { File.directory?(File.join(dir, _1)) }
|
|
81
|
+
.sort_by { _1[/\d+/].to_i }.map { File.join(dir, _1) }
|
|
82
|
+
end
|
|
83
|
+
|
|
84
|
+
# Streams each file. Attributed rows are many (one per window name, line
|
|
85
|
+
# and app line, in every process), so they are merged into flat integer
|
|
86
|
+
# arrays in first-seen order, which keeps every later sum and tie as it
|
|
87
|
+
# was with one array per row.
|
|
88
|
+
def load_run(path)
|
|
89
|
+
run = { name: File.basename(path), requests: 0, objects: 0, dropped: 0, controller_tests: 0, processes: 0, roots: [],
|
|
90
|
+
windows: Hash.new(0), sites: Hash.new { |h, k| h[k] = [0, 0, 0, 0] },
|
|
91
|
+
actions: Hash.new { |h, k| h[k] = [0, 0, 0, 0, 0] }, net: Hash.new(0),
|
|
92
|
+
attrib: { index: {}, name: [], loc: [], caller: [], count: [], first: [] } }
|
|
93
|
+
Dir.children(path).grep(/\.tsv\z/).sort.map { File.join(path, _1) }.each do |file|
|
|
94
|
+
header = File.open(file, &:gets)&.chomp
|
|
95
|
+
raise "#{file} is from an older lowrail-profile; run it again" unless header&.start_with?("# lowrail-profile 4\t")
|
|
96
|
+
meta = header.split("\t").drop(1).to_h { _1.split("=", 2) }
|
|
97
|
+
run[:processes] += 1
|
|
98
|
+
%i[requests objects dropped].each { run[_1] += Integer(meta.fetch(_1.to_s)) }
|
|
99
|
+
KINDS.zip(meta.fetch("windows").split(",")) { |kind, n| run[:windows][kind] += Integer(n) }
|
|
100
|
+
run[:controller_tests] += Integer(meta.fetch("controller_tests", "0"))
|
|
101
|
+
# The root lines were attributed through first, so app keys are relative to it.
|
|
102
|
+
run[:roots] |= [meta["app_root"], meta["root"]].compact
|
|
103
|
+
run[:ruby] ||= meta["ruby"]
|
|
104
|
+
run[:rails_env] ||= meta["rails_env"]
|
|
105
|
+
run[:rails] ||= meta["rails"] unless meta["rails"].to_s.empty?
|
|
106
|
+
(run[:rubies] ||= []) << meta["ruby"]
|
|
107
|
+
(run[:rails_envs] ||= []) << meta["rails_env"]
|
|
108
|
+
paths = { "-" => path_id("-") }
|
|
109
|
+
attrib = run[:attrib]
|
|
110
|
+
File.foreach(file, chomp: true).with_index do |row, i|
|
|
111
|
+
next if i == 0
|
|
112
|
+
fields = row.split("\t")
|
|
113
|
+
case fields[0]
|
|
114
|
+
when "P"
|
|
115
|
+
paths[fields[1]] = path_id(fields[2])
|
|
116
|
+
when "A"
|
|
117
|
+
_, kind, name, windows, objects, first, net = fields
|
|
118
|
+
action = run[:actions][[kind, name]]
|
|
119
|
+
action[0] += Integer(windows)
|
|
120
|
+
action[1] += Integer(objects)
|
|
121
|
+
action[2] += Integer(first)
|
|
122
|
+
action[3] += 1
|
|
123
|
+
action[4] += Integer(net)
|
|
124
|
+
run[:net][kind] += Integer(net)
|
|
125
|
+
when "G"
|
|
126
|
+
_, name, gem_dir = fields
|
|
127
|
+
(run[:path_gems] ||= {})[name] = gem_dir
|
|
128
|
+
when "@"
|
|
129
|
+
_, kind, name, file_path, line, caller_path, caller_line, count, first = fields
|
|
130
|
+
window = (@window_ids[[kind, name]] ||= (@window_names << [kind, name].freeze).size - 1)
|
|
131
|
+
loc = loc_id(paths.fetch(file_path), Integer(line))
|
|
132
|
+
caller_loc = loc_id(paths.fetch(caller_path), Integer(caller_line))
|
|
133
|
+
index = (attrib[:index][window] ||= {})[loc << 31 | caller_loc] ||= begin
|
|
134
|
+
attrib[:name] << window
|
|
135
|
+
attrib[:loc] << loc
|
|
136
|
+
attrib[:caller] << caller_loc
|
|
137
|
+
attrib[:count] << 0
|
|
138
|
+
(attrib[:first] << 0).size - 1
|
|
139
|
+
end
|
|
140
|
+
attrib[:count][index] += Integer(count)
|
|
141
|
+
attrib[:first][index] += Integer(first)
|
|
142
|
+
else
|
|
143
|
+
file_path, line, type, count, reached, first, via, kind = fields
|
|
144
|
+
site = run[:sites][[@paths[paths.fetch(file_path)], Integer(line), type, via, kind]]
|
|
145
|
+
site[0] += Integer(count)
|
|
146
|
+
site[1] += Integer(reached)
|
|
147
|
+
site[2] += Integer(first)
|
|
148
|
+
site[3] += Integer(count) if via == "1"
|
|
149
|
+
end
|
|
150
|
+
end
|
|
151
|
+
end
|
|
152
|
+
run[:attributed] = !run[:attrib][:count].empty?
|
|
153
|
+
run
|
|
154
|
+
end
|
|
155
|
+
|
|
156
|
+
def path_id(path) = @path_ids[path] ||= (@paths << path.freeze).size - 1
|
|
157
|
+
|
|
158
|
+
def loc_id(path, line) = @loc_ids[path << 32 | line] ||= (@locs << [path, line].freeze).size - 1
|
|
159
|
+
|
|
160
|
+
def classify(path) = (@classify ||= {})[path] ||= classify!(path)
|
|
161
|
+
|
|
162
|
+
def classify!(path)
|
|
163
|
+
@roots ||= @runs.flat_map { _1[:roots] }.uniq.compact.map { _1.end_with?("/") ? _1 : "#{_1}/" }
|
|
164
|
+
libdir = RbConfig::CONFIG.fetch("rubylibdir") + "/"
|
|
165
|
+
if path == "-" then ["(no Ruby frame)", path]
|
|
166
|
+
elsif (m = path.match(RAILS_PATH)) then ["rails: #{m[1] || m[2]}", "RAILS/#{m[1] || m[2]}/#{m[3]}"]
|
|
167
|
+
elsif (m = path.match(GEM_PATH)) then gem_site(m[1], m[3])
|
|
168
|
+
# A path gem kept inside the app (gems/, vendor/gems/) is not one of the app's lines; app/views/gems/ is,
|
|
169
|
+
# also when the root is itself a path gem (an engine profiled in place).
|
|
170
|
+
elsif (root = @roots.find { path.start_with?(_1) }) &&
|
|
171
|
+
path_gems.none? { |_, d| path.start_with?(d) && d.start_with?(root) && d.delete_prefix(root).match?(%r{(?:\A|/)gems/}) }
|
|
172
|
+
["app", "APP/#{path.delete_prefix(root)}"]
|
|
173
|
+
elsif (name, gem_dir = path_gems.find { |_, d| path.start_with?(d) })
|
|
174
|
+
RAILS.include?(name) ? ["rails: #{name}", "RAILS/#{name}/#{path.delete_prefix(gem_dir)}"] : gem_site(name, path.delete_prefix(gem_dir))
|
|
175
|
+
elsif path.start_with?(libdir) then ["ruby stdlib", "RUBY/#{path.delete_prefix(libdir)}"]
|
|
176
|
+
elsif path.start_with?("<internal:") then ["ruby core", "RUBY/#{path}"]
|
|
177
|
+
elsif path.include?("/lowrail/profile") then ["lowrail-profile", path]
|
|
178
|
+
else ["other", path]
|
|
179
|
+
end
|
|
180
|
+
end
|
|
181
|
+
|
|
182
|
+
def gem_site(name, rest)
|
|
183
|
+
group = if %w[lowrail lowrail-profile].include?(name) then "lowrail-profile"
|
|
184
|
+
elsif default_gems.include?(name) then "ruby default gem: #{name}"
|
|
185
|
+
elsif name.match?(HARNESS) then "test harness: #{name}"
|
|
186
|
+
else "gem: #{name}"
|
|
187
|
+
end
|
|
188
|
+
[group, "GEM/#{name}/#{rest}"]
|
|
189
|
+
end
|
|
190
|
+
|
|
191
|
+
# Gems loaded from a path, longest directory first (a gem inside another's).
|
|
192
|
+
def path_gems
|
|
193
|
+
@path_gems ||= @runs.map { _1[:path_gems] || {} }.reduce({}, :merge)
|
|
194
|
+
.transform_values { _1.end_with?("/") ? _1 : "#{_1}/" }.sort_by { -_2.size }
|
|
195
|
+
end
|
|
196
|
+
|
|
197
|
+
# Objects on lines outside the app, Rails, Ruby and every gem the bundle
|
|
198
|
+
# loaded, which no table ranks: per request (all, mean of the runs) and
|
|
199
|
+
# their share of every object counted, with the files that have most.
|
|
200
|
+
def unclassified(kind = "request")
|
|
201
|
+
all = sites(kind)
|
|
202
|
+
total = all.sum { mean(_1.all) }
|
|
203
|
+
other = all.select { _1.group == "other" }
|
|
204
|
+
objects = other.sum { mean(_1.all) }
|
|
205
|
+
return nil if objects == 0
|
|
206
|
+
files = other.group_by(&:path).map { |path, list| [path, list.sum { mean(_1.all) }] }.sort_by { -_2 }.first(3)
|
|
207
|
+
{ objects_per_request: objects.round(2), share: (objects / total).round(4),
|
|
208
|
+
files: files.map { |path, n| { path: path, objects_per_request: n.round(2) } } }
|
|
209
|
+
end
|
|
210
|
+
|
|
211
|
+
# By name, as the census does: a bundle may lock a newer release of one.
|
|
212
|
+
def default_gems
|
|
213
|
+
@default_gems ||= Dir[File.join(Gem.default_specifications_dir, "*.gemspec")]
|
|
214
|
+
.map { File.basename(_1, ".gemspec")[/\A(.+)-\d[^-]*\z/, 1] } - %w[json]
|
|
215
|
+
end
|
|
216
|
+
|
|
217
|
+
# Every line of one kind of window, merged over the object types
|
|
218
|
+
# ObjectSpace can see; per run objects per window (all and warm) and
|
|
219
|
+
# windows reached.
|
|
220
|
+
def sites(kind = "request")
|
|
221
|
+
(@sites ||= {})[kind] ||= begin
|
|
222
|
+
merged = {}
|
|
223
|
+
@runs.each_with_index do |run, i|
|
|
224
|
+
windows = run[:windows][kind]
|
|
225
|
+
next if windows == 0
|
|
226
|
+
run[:sites].each do |(path, line, type, _, site_kind), (count, reached, first, via)|
|
|
227
|
+
next if site_kind != kind || INTERNAL.include?(type)
|
|
228
|
+
group, key = classify(path)
|
|
229
|
+
site = merged[[key, line]] ||= Site.new(key: key, group: group, path: path, line: line, via: 0, kind: kind,
|
|
230
|
+
all: Array.new(@runs.size, 0.0), warm: Array.new(@runs.size, 0.0), reached: Array.new(@runs.size, 0),
|
|
231
|
+
types: Hash.new(0))
|
|
232
|
+
site.all[i] += count.fdiv(windows)
|
|
233
|
+
site.warm[i] += (count - first).fdiv(windows)
|
|
234
|
+
site.reached[i] = [site.reached[i], reached].max
|
|
235
|
+
site.types[type] += count
|
|
236
|
+
site.via += via
|
|
237
|
+
end
|
|
238
|
+
end
|
|
239
|
+
merged.values
|
|
240
|
+
end
|
|
241
|
+
end
|
|
242
|
+
|
|
243
|
+
def mean(values) = values.sum / values.size
|
|
244
|
+
def noise(values) = values.size > 1 ? values.last - values.first : nil
|
|
245
|
+
def ranked(kind = "request")
|
|
246
|
+
(@ranked ||= {})[kind] ||= sites(kind).select { ranked?(_1) }.sort_by { [-mean(_1.warm), -mean(_1.all), _1.key, _1.line] }
|
|
247
|
+
end
|
|
248
|
+
def ranked?(site) = !NOT_RANKED.include?(site.group) && !site.group.start_with?("test harness")
|
|
249
|
+
|
|
250
|
+
def source(site) = source_at(site.path, site.line)
|
|
251
|
+
|
|
252
|
+
def source_at(path, line)
|
|
253
|
+
@files ||= {}
|
|
254
|
+
lines = (@files[path] ||= File.exist?(path) ? File.readlines(path, chomp: true) : [])
|
|
255
|
+
text = lines[line - 1]&.strip
|
|
256
|
+
method = lines[0, line].reverse_each.lazy.map { _1[/^\s*def\s+(?:self\.)?([^\s(;=]+=?)/, 1] }.find(&:itself)
|
|
257
|
+
[text, method]
|
|
258
|
+
end
|
|
259
|
+
|
|
260
|
+
# Upstream pull requests from Lowrail's contributions ledger that reduce
|
|
261
|
+
# allocations or time (by the ledger entry) and change this very line:
|
|
262
|
+
# same gem, file and method, and the line's code is one the pull request
|
|
263
|
+
# removes there (the app runs the code before it) or adds there (the app
|
|
264
|
+
# may run it already). The index (data/contributions-index.json) is
|
|
265
|
+
# built by script/profile-ledger. Closed, unmerged ones are left out.
|
|
266
|
+
def ledger_matches(site)
|
|
267
|
+
return [] unless (index = ledger_index)
|
|
268
|
+
text, method = source(site)
|
|
269
|
+
return [] unless method && text && text.length >= 6
|
|
270
|
+
gem_name, file = ledger_file(site) || (return [])
|
|
271
|
+
index.filter_map do |pr|
|
|
272
|
+
next if pr["state"] == "closed" || !pr["allocation_work"] || !ledger_repo?(pr["repo"], gem_name)
|
|
273
|
+
f = pr["files"].find { _1["path"] == file } or next
|
|
274
|
+
change = f["methods"][method] or next
|
|
275
|
+
removed, added = change["removed"].any? { same_code?(text, _1) }, change["added"].any? { same_code?(text, _1) }
|
|
276
|
+
ledger_label(pr, site, removed: removed) if removed || added
|
|
277
|
+
end.compact.uniq.first(3)
|
|
278
|
+
end
|
|
279
|
+
|
|
280
|
+
# The same line, or the first line of a block the other version writes on
|
|
281
|
+
# one line: Rails 8.1's `type_map.fetch(oid, fmod, sql_type) {` is main's
|
|
282
|
+
# `type_map.fetch(oid, fmod, sql_type) { register_unknown_oid_type(...) }`.
|
|
283
|
+
# Braces only: a byte prefix ending in `do` also matches `download`.
|
|
284
|
+
def same_code?(text, change)
|
|
285
|
+
text == change || (text.end_with?("{") && change.start_with?(text) && change[text.size].match?(/[\s|}]/))
|
|
286
|
+
end
|
|
287
|
+
|
|
288
|
+
def ledger_index
|
|
289
|
+
return @ledger_index if defined?(@ledger_index)
|
|
290
|
+
data = @ledger && JSON.parse(File.read(@ledger))
|
|
291
|
+
@ledger_date = data && data["generated"].to_s[0, 10]
|
|
292
|
+
@ledger_index = data && data["pulls"]
|
|
293
|
+
end
|
|
294
|
+
|
|
295
|
+
# compare refuses a capture of more than one process (ProfileCompare): said
|
|
296
|
+
# when profiling, not only when comparing.
|
|
297
|
+
def parallel_warning
|
|
298
|
+
parallel = @runs.select { _1[:processes] > 1 }
|
|
299
|
+
return if parallel.empty?
|
|
300
|
+
"Not comparable: #{parallel.map { "#{_1[:name]} ran in #{_1[:processes]} processes" }.join(", ")}. Parallel test workers split the tests differently in every " \
|
|
301
|
+
"capture, which changes what warm leaves out, so compare refuses it (exit 2); profile with PARALLEL_WORKERS=1 to compare"
|
|
302
|
+
end
|
|
303
|
+
|
|
304
|
+
# The day the ledger index was taken (nil without one).
|
|
305
|
+
def ledger_date = (ledger_index; @ledger_date)
|
|
306
|
+
|
|
307
|
+
# [gem or rails component or "ruby", path in its repository]
|
|
308
|
+
def ledger_file(site)
|
|
309
|
+
case site.key
|
|
310
|
+
when %r{\ARAILS/(\w+)/(.+)\z} then [$1, "#{$1}/#{$2}"]
|
|
311
|
+
when %r{\AGEM/([^/]+)/(.+)\z} then [$1, $2]
|
|
312
|
+
when %r{\ARUBY/(?!<)(.+)\z} then ["ruby", "lib/#{$1}"]
|
|
313
|
+
end
|
|
314
|
+
end
|
|
315
|
+
|
|
316
|
+
def ledger_repo?(repo, gem_name)
|
|
317
|
+
name = repo.split("/").last.downcase.tr("_", "-").delete_suffix("-ruby").delete_prefix("ruby-")
|
|
318
|
+
return RAILS.include?(gem_name) if repo == "rails/rails"
|
|
319
|
+
return gem_name == "ruby" || default_gems.include?(gem_name) if repo == "ruby/ruby"
|
|
320
|
+
name == gem_name.downcase.tr("_", "-")
|
|
321
|
+
end
|
|
322
|
+
|
|
323
|
+
# The version of the gem the line comes from (nil for git checkouts).
|
|
324
|
+
def site_version(site)
|
|
325
|
+
if site.key.start_with?("RUBY/")
|
|
326
|
+
ruby = @runs.first[:ruby].to_s[/\Aruby (\d+\.\d+\.\d+)/, 1]
|
|
327
|
+
return ruby && Gem::Version.new(ruby)
|
|
328
|
+
end
|
|
329
|
+
m = site.path.match(RAILS_PATH) ? site.path.match(%r{/(?:#{RAILS.join("|")})-(\d[\w.]*)/}) : site.path.match(GEM_PATH)
|
|
330
|
+
version = m && m[m.size == 2 ? 1 : 2]
|
|
331
|
+
Gem::Version.new(version) if version&.match?(/\A\d+(\.\w+)*\z/)
|
|
332
|
+
end
|
|
333
|
+
|
|
334
|
+
# nil when the line only matches code the pull request adds and the app's
|
|
335
|
+
# version cannot show it runs that code (a git checkout, or not released).
|
|
336
|
+
def ledger_label(pr, site, removed:)
|
|
337
|
+
ref = pr["ref"]
|
|
338
|
+
return removed ? "#{ref} open upstream work" : nil if pr["state"] == "open"
|
|
339
|
+
released = pr["released_in"] && Gem::Version.new(pr["released_in"])
|
|
340
|
+
version = site_version(site)
|
|
341
|
+
return (released && version && version >= released ? "#{ref} merged, in #{released}, which this app runs" : nil) unless removed
|
|
342
|
+
if released && version then version < released ? "#{ref} fixed in #{released}" : nil
|
|
343
|
+
elsif released then "#{ref} fixed in #{released}, after this app's revision"
|
|
344
|
+
else "#{ref} merged #{pr["merged_at"].to_s[0, 10]}, after this app's version, not released yet"
|
|
345
|
+
end
|
|
346
|
+
end
|
|
347
|
+
|
|
348
|
+
def summary
|
|
349
|
+
@summary ||= @runs.each_with_index.map do |run, i|
|
|
350
|
+
# fetch: the actions hash adds a key it is asked for.
|
|
351
|
+
static = run[:actions].fetch(["request", STATIC], [0])[0]
|
|
352
|
+
# On the actions' basis (objects ObjectSpace sees, Socket.tcp's left out), as the Actions table counts.
|
|
353
|
+
others = run[:actions].select { |(kind, name), _| kind == "request" && name != STATIC }.values
|
|
354
|
+
dynamic, dynamic_objects = others.sum { _1[0] }, others.sum { _1[1] }
|
|
355
|
+
{ run: run[:name], processes: run[:processes], requests: run[:requests],
|
|
356
|
+
objects_per_request: run[:requests] > 0 ? run[:objects].fdiv(run[:requests]) : 0.0, dropped: run[:dropped],
|
|
357
|
+
# Each line's first request per process left out, as the noise floor and the warm columns count.
|
|
358
|
+
warm_per_request: sites.sum { _1.warm[i] }.round(2),
|
|
359
|
+
static_requests: static,
|
|
360
|
+
objects_per_dynamic_request: dynamic > 0 ? dynamic_objects.fdiv(dynamic).round(2) : nil,
|
|
361
|
+
controller_tests: run[:controller_tests],
|
|
362
|
+
windows: KINDS.to_h { [_1, run[:windows][_1]] },
|
|
363
|
+
# Windows that finished (were merged into an action); fewer than
|
|
364
|
+
# windows means some were still open when the process wrote.
|
|
365
|
+
completed: KINDS.to_h { |kind| [kind, run[:actions].sum { |(k, _), (n, *)| k == kind ? n : 0 }] },
|
|
366
|
+
network: KINDS.to_h { [_1, run[:net][_1]] } }
|
|
367
|
+
end
|
|
368
|
+
end
|
|
369
|
+
|
|
370
|
+
# Dev/test-only work is one group of its own, as its own table lists it.
|
|
371
|
+
def groups
|
|
372
|
+
totals = Hash.new { |h, k| h[k] = { warm: 0.0, all: 0.0, sites: [] } }
|
|
373
|
+
sites.each do |site|
|
|
374
|
+
site = site.dup.tap { _1.group = "dev/test-mode work" } if mode_only(site)
|
|
375
|
+
totals[site.group][:warm] += mean(site.warm)
|
|
376
|
+
totals[site.group][:all] += mean(site.all)
|
|
377
|
+
totals[site.group][:sites] << site
|
|
378
|
+
end
|
|
379
|
+
totals.sort_by { -_2[:warm] }
|
|
380
|
+
end
|
|
381
|
+
|
|
382
|
+
# Lines without dev/test-only work first, as production would see them;
|
|
383
|
+
# the dev/test-only lines get their own table.
|
|
384
|
+
def rows(list = ranked.reject { mode_only(_1) }, limit = @top)
|
|
385
|
+
list.first(limit).each_with_index.map do |site, i|
|
|
386
|
+
text, method = source(site)
|
|
387
|
+
{ rank: i + 1, site: "#{site.key}:#{site.line}", group: site.group, method: method, text: text,
|
|
388
|
+
warm: site.warm.map { _1.round(2) }, noise: noise(site.warm)&.round(2), all: mean(site.all).round(2),
|
|
389
|
+
reach: site.reached.zip(@runs).map { |r, run| (n = run[:windows][site.kind]) > 0 ? r.fdiv(n).round(3) : 0.0 },
|
|
390
|
+
via_internal: site.via > 0, types: site.types.sort_by { -_2 }.first(2).map(&:first),
|
|
391
|
+
ledger: ledger_matches(site), callers: top_callers(site), mode: mode_only(site) }
|
|
392
|
+
end
|
|
393
|
+
end
|
|
394
|
+
|
|
395
|
+
def mode_rows = rows(ranked.select { mode_only(_1) }, [@top / 3, 10].max)
|
|
396
|
+
|
|
397
|
+
def mode_only(site) = MODE_ONLY.find { |_, pattern| site.key.match?(pattern) }&.first
|
|
398
|
+
|
|
399
|
+
# The run that recorded the nearest app frame (the repeat run).
|
|
400
|
+
def attributed_run = @runs.reverse.find { _1[:attributed] }
|
|
401
|
+
|
|
402
|
+
# Attributed allocations of one kind in first-seen order: name, site key,
|
|
403
|
+
# line, group, app key or nil, app line, path, app path, count, first.
|
|
404
|
+
def each_attribution(kind)
|
|
405
|
+
a = attributed_run&.dig(:attrib) or return
|
|
406
|
+
a[:name].each_with_index do |window, i|
|
|
407
|
+
k, name = @window_names[window]
|
|
408
|
+
next unless k == kind
|
|
409
|
+
path_id, line = @locs[a[:loc][i]]
|
|
410
|
+
caller_id, caller_line = @locs[a[:caller][i]]
|
|
411
|
+
group, key = classify(@paths[path_id])
|
|
412
|
+
app = caller_id == @path_ids["-"] ? nil : classify(@paths[caller_id])[1]
|
|
413
|
+
yield name, key, line, group, app, caller_line, @paths[path_id], @paths[caller_id], a[:count][i], a[:first][i]
|
|
414
|
+
end
|
|
415
|
+
end
|
|
416
|
+
|
|
417
|
+
# "key:line", one string per line, shared by every table that counts it.
|
|
418
|
+
def label(key, line) = ((@labels ||= {})[key] ||= {})[line] ||= "#{key}:#{line}".freeze
|
|
419
|
+
|
|
420
|
+
def ranked_group?(group) = !NOT_RANKED.include?(group) && !group.start_with?("test harness")
|
|
421
|
+
|
|
422
|
+
def mode_key?(key) = (@mode_keys ||= {}).fetch(key) { @mode_keys[key] = MODE_ONLY.any? { |_, pattern| key.match?(pattern) } }
|
|
423
|
+
|
|
424
|
+
# The app lines whose calls lead to the line's allocations (repeat run),
|
|
425
|
+
# with their share; "no app frame" when none was on the stack.
|
|
426
|
+
def top_callers(site)
|
|
427
|
+
@callers ||= {}
|
|
428
|
+
@caller_paths ||= {}
|
|
429
|
+
counts = (@callers[site.kind] ||= Hash.new { |h, k| h[k] = Hash.new(0) }.tap do |acc|
|
|
430
|
+
each_attribution(site.kind) do |_, key, line, _, app, app_line, _, caller_path, count|
|
|
431
|
+
caller = app ? label(app, app_line) : "no app frame"
|
|
432
|
+
@caller_paths[caller] ||= [caller_path, app_line] if app
|
|
433
|
+
acc[[key, line]][caller] += count
|
|
434
|
+
end
|
|
435
|
+
end)[[site.key, site.line]]
|
|
436
|
+
return [] if counts.nil? || counts.empty?
|
|
437
|
+
total = counts.values.sum.to_f
|
|
438
|
+
counts.sort_by { -_2 }.first(2).map do |caller, n|
|
|
439
|
+
path, line = @caller_paths[caller]
|
|
440
|
+
entry = { caller: caller, share: (n / total).round(2) }
|
|
441
|
+
path && source_at(path, line)[0].to_s.match?(PASSES_ON) ? entry.merge(middleware: true) : entry
|
|
442
|
+
end
|
|
443
|
+
end
|
|
444
|
+
|
|
445
|
+
# Your code: per app line, the objects that Rails, Ruby and gems allocate
|
|
446
|
+
# below it per request (warm, leaving out each action's first request per
|
|
447
|
+
# process), dev/test-only work apart, and the lines it reaches most.
|
|
448
|
+
def app_lines(kind = "request")
|
|
449
|
+
run = attributed_run or return []
|
|
450
|
+
windows = run[:windows][kind]
|
|
451
|
+
return [] if windows == 0
|
|
452
|
+
lines = Hash.new { |h, k| h[k] = { warm: 0.0, all: 0.0, mode: 0.0, own: 0.0, sites: Hash.new(0.0), names: Hash.new(0.0) } }
|
|
453
|
+
each_attribution(kind) do |name, key, line, group, app, app_line, _, caller_path, count, first|
|
|
454
|
+
next unless app
|
|
455
|
+
entry = lines[[app, app_line, caller_path]]
|
|
456
|
+
warm = (count - first).fdiv(windows)
|
|
457
|
+
if group == "app"
|
|
458
|
+
entry[:own] += warm if key == app && line == app_line
|
|
459
|
+
next
|
|
460
|
+
end
|
|
461
|
+
next unless ranked_group?(group)
|
|
462
|
+
entry[:all] += count.fdiv(windows)
|
|
463
|
+
if mode_key?(key)
|
|
464
|
+
entry[:mode] += warm
|
|
465
|
+
else
|
|
466
|
+
entry[:warm] += warm
|
|
467
|
+
entry[:sites][label(key, line)] += warm
|
|
468
|
+
entry[:names][name] += warm
|
|
469
|
+
end
|
|
470
|
+
end
|
|
471
|
+
lines = lines.reject { |_, e| e[:warm].round(2) == 0 && e[:mode].round(2) == 0 && e[:own].round(2) == 0 }
|
|
472
|
+
lines.sort_by { |(app, line, _), e| [-e[:warm], -e[:mode], app, line] }.map do |(app, line, path), e|
|
|
473
|
+
text, method = source_at(path, line)
|
|
474
|
+
total = e[:warm]
|
|
475
|
+
top = ->(hash) { hash.sort_by { -_2 }.first(3).map { |k, v| { name: k, share: total > 0 ? (v / total).round(2) : 0.0 } } }
|
|
476
|
+
{ line: "#{app}:#{line}", method: method, text: text, warm: e[:warm].round(2), mode: e[:mode].round(2),
|
|
477
|
+
all: e[:all].round(2), own: e[:own].round(2), sites: top.(e[:sites]), actions: top.(e[:names]),
|
|
478
|
+
passes_on: text.to_s.match?(PASSES_ON) }
|
|
479
|
+
end
|
|
480
|
+
end
|
|
481
|
+
|
|
482
|
+
# Objects outside the app with no app line on the stack (middleware,
|
|
483
|
+
# routing, the framework's own request handling), warm per request.
|
|
484
|
+
def unattributed(kind = "request")
|
|
485
|
+
run = attributed_run or return nil
|
|
486
|
+
windows = run[:windows][kind]
|
|
487
|
+
return nil if windows == 0
|
|
488
|
+
warm = []
|
|
489
|
+
each_attribution(kind) { |_, key, _, group, app, *, count, first| warm << (!app && ranked_group?(group) && !mode_key?(key) ? (count - first).fdiv(windows) : 0.0) }
|
|
490
|
+
warm.sum.round(2)
|
|
491
|
+
end
|
|
492
|
+
|
|
493
|
+
# Per window name (controller action, job, mailer action, channel action):
|
|
494
|
+
# objects per window by run, warm leaving out its first window in each
|
|
495
|
+
# process, and the lines outside the app and app lines it reaches most.
|
|
496
|
+
def actions(kind = "request")
|
|
497
|
+
(@actions ||= {})[kind] ||= begin
|
|
498
|
+
names = @runs.flat_map { |run| run[:actions].keys.select { _1[0] == kind }.map(&:last) }.uniq
|
|
499
|
+
attributed = Hash.new { |h, k| h[k] = { sites: Hash.new(0), apps: Hash.new(0) } }
|
|
500
|
+
each_attribution(kind) do |name, key, line, group, app, app_line, *, count, first|
|
|
501
|
+
next unless ranked_group?(group) && !mode_key?(key)
|
|
502
|
+
attributed[name][:sites][label(key, line)] += count - first
|
|
503
|
+
attributed[name][:apps][label(app, app_line)] += count - first if app
|
|
504
|
+
end
|
|
505
|
+
attributed_index = @runs.index(attributed_run)
|
|
506
|
+
names.map do |name|
|
|
507
|
+
stats = @runs.map { |run| run[:actions][[kind, name]] if run[:actions].key?([kind, name]) }
|
|
508
|
+
warm = stats.map { |windows, objects, first, processes| windows && windows > processes ? (objects - first).fdiv(windows - processes) : nil }
|
|
509
|
+
all = stats.map { |windows, objects| windows ? objects.fdiv(windows) : nil }
|
|
510
|
+
windows = stats.map { _1 ? _1[0] : 0 }
|
|
511
|
+
a = attributed[name]
|
|
512
|
+
denominator = attributed_index && (s = stats[attributed_index]) ? s[0] - s[3] : 0
|
|
513
|
+
top = ->(hash) { denominator > 0 ? hash.sort_by { -_2 }.first(3).map { |k, v| { name: k, warm: v.fdiv(denominator).round(1) } } : [] }
|
|
514
|
+
known = warm.compact
|
|
515
|
+
samples = stats.map { _1 ? _1[0] - _1[3] : 0 }
|
|
516
|
+
# One warm request in a run is a sample, not a mean: in a field test such an action led the table.
|
|
517
|
+
thin = samples.min < MIN_WARM
|
|
518
|
+
{ name: name == "-" ? nil : name, windows: windows, warm: warm.map { _1&.round(1) }, all: all.map { _1&.round(1) },
|
|
519
|
+
warm_samples: samples, noise: known.size > 1 && warm.first && warm.last ? (warm.last - warm.first).round(1) : nil,
|
|
520
|
+
thin: thin, sort: thin ? all.compact.max.to_f : mean(known), sites: top.(a[:sites]), apps: top.(a[:apps]),
|
|
521
|
+
network: stats.map { _1 ? _1[4] : 0 } }
|
|
522
|
+
end.sort_by { [_1[:thin] ? 1 : 0, -_1[:sort], _1[:name].to_s] }
|
|
523
|
+
end
|
|
524
|
+
end
|
|
525
|
+
|
|
526
|
+
def noise_floor
|
|
527
|
+
deltas = rows.filter_map { _1[:noise]&.abs }.sort
|
|
528
|
+
return nil if deltas.empty?
|
|
529
|
+
{ top_lines: deltas.size, median_abs: deltas[deltas.size / 2].round(2), max_abs: deltas.last.round(2),
|
|
530
|
+
moved_ge_1: deltas.count { _1 >= 1 } }
|
|
531
|
+
end
|
|
532
|
+
|
|
533
|
+
def cell(text) = "`#{text.to_s[0, 70].gsub("|", "\\|")}`"
|
|
534
|
+
|
|
535
|
+
# App middleware that hands the request on is the nearest app line of work done after the request's own code
|
|
536
|
+
# returned or raised (an error page, a logger): not the line that caused it.
|
|
537
|
+
def callers_cell(callers)
|
|
538
|
+
callers.map { "`#{_1[:caller].delete_prefix("APP/")}`#{" (middleware)" if _1[:middleware]} #{(_1[:share] * 100).round}%" }.join(", ")
|
|
539
|
+
end
|
|
540
|
+
|
|
541
|
+
def table(rows)
|
|
542
|
+
out = +"| # | Line | Method | Warm/req | Δ | All/req | Reach | Types | Ledger | From the app | Source |\n" \
|
|
543
|
+
"| ---: | --- | --- | ---: | ---: | ---: | ---: | --- | --- | --- | --- |\n"
|
|
544
|
+
rows.each do |r|
|
|
545
|
+
out << "| #{r[:rank]} | `#{r[:site]}`#{" †" if r[:via_internal]} | `#{r[:method]}` | #{r[:warm].join(" / ")} | " \
|
|
546
|
+
"#{r[:noise]} | #{r[:all]} | #{(r[:reach].last * 100).round}% | #{r[:types].join(", ")} | " \
|
|
547
|
+
"#{r[:ledger].join(", ")} | #{callers_cell(r[:callers])} | #{cell(r[:text])} |\n"
|
|
548
|
+
end
|
|
549
|
+
out
|
|
550
|
+
end
|
|
551
|
+
|
|
552
|
+
def app_lines_table(lines, limit)
|
|
553
|
+
out = +"| # | App line | Method | Warm/req | Dev/test/req | Own/req | Lines it reaches (share of warm) | Actions (share) | Source |\n" \
|
|
554
|
+
"| ---: | --- | --- | ---: | ---: | ---: | --- | --- | --- |\n"
|
|
555
|
+
lines.first(limit).each_with_index do |l, i|
|
|
556
|
+
sites = l[:sites].map { "`#{_1[:name]}` #{(_1[:share] * 100).round}%" }.join(", ")
|
|
557
|
+
names = l[:actions].map { "#{_1[:name] || "(no name)"} #{(_1[:share] * 100).round}%" }.join(", ")
|
|
558
|
+
out << "| #{i + 1} | `#{l[:line].delete_prefix("APP/")}` | #{"`#{l[:method]}`" if l[:method]} | #{l[:warm]} | #{l[:mode]} | #{l[:own]} | " \
|
|
559
|
+
"#{sites} | #{names} | #{cell(l[:text])} |\n"
|
|
560
|
+
end
|
|
561
|
+
out
|
|
562
|
+
end
|
|
563
|
+
|
|
564
|
+
def actions_table(list, limit, label, per = "window")
|
|
565
|
+
out = +"| # | #{label} | Count | Warm/#{per} | Δ | All/#{per} | Top lines outside the app (warm) | Top app lines (warm) |\n" \
|
|
566
|
+
"| ---: | --- | ---: | ---: | ---: | ---: | --- | --- |\n"
|
|
567
|
+
list.first(limit).each_with_index do |a, i|
|
|
568
|
+
sites = a[:sites].map { "`#{_1[:name]}` #{_1[:warm]}" }.join(", ")
|
|
569
|
+
apps = a[:apps].map { "`#{_1[:name].delete_prefix("APP/")}` #{_1[:warm]}" }.join(", ")
|
|
570
|
+
out << "| #{i + 1} | #{a[:name] || "(no #{label.downcase} name)"} | #{a[:windows].join(" / ")} | " \
|
|
571
|
+
"#{a[:warm].map { _1 || "–" }.join(" / ")} | #{a[:noise]} | #{a[:all].compact.last} | #{sites} | #{apps} |\n"
|
|
572
|
+
end
|
|
573
|
+
out
|
|
574
|
+
end
|
|
575
|
+
|
|
576
|
+
def markdown
|
|
577
|
+
command_file = File.join(dir, "command.txt")
|
|
578
|
+
command = File.exist?(command_file) ? File.read(command_file).lines.first.strip : "?"
|
|
579
|
+
first = summary.first
|
|
580
|
+
labels = { "request" => "requests", "job" => "jobs", "mail" => "mail windows", "cable" => "Cable actions" }
|
|
581
|
+
counted = labels.filter_map { |kind, label| "#{first[:windows][kind]} #{label}" if first[:windows][kind] > 0 }
|
|
582
|
+
rails = @runs.filter_map { _1[:rails] }.first
|
|
583
|
+
out = +"# lowrail-profile report\n\n"
|
|
584
|
+
if (stopped = meta[:timed_out]).any?
|
|
585
|
+
out << "**Incomplete: run #{stopped.join(", ")} timed out after #{meta[:timeout]} s (--timeout) and was stopped, so " \
|
|
586
|
+
"its numbers cover only what ran before; no later run started.**\n\n"
|
|
587
|
+
end
|
|
588
|
+
out << "Objects allocated (exact counts, not time, not retained memory) per request, job, mail and Action Cable " \
|
|
589
|
+
"action, by source line. A line with many objects is a place to look, not a measured cost in milliseconds.\n\n"
|
|
590
|
+
out << "* Command: `#{command}`\n"
|
|
591
|
+
out << "* Ruby: #{@runs.first[:ruby]}\n"
|
|
592
|
+
out << "* Rails: #{rails || "?"}, #{@runs.first[:rails_env] || "?"} environment\n"
|
|
593
|
+
out << "* Counted in run 1: #{counted.join(", ")}#{" in #{first[:processes]} processes" if first[:processes] > 1}; " \
|
|
594
|
+
"#{@runs.size} run#{"s" if @runs.size != 1}\n"
|
|
595
|
+
if first[:static_requests] > 0
|
|
596
|
+
out << "* Static files: #{first[:static_requests]} of run 1's requests were files `ActionDispatch::Static` served " \
|
|
597
|
+
"before routing (`#{STATIC}` under Actions); the other requests' objects per request, counted as the Actions table " \
|
|
598
|
+
"counts them, by run: " \
|
|
599
|
+
"#{summary.map { _1[:objects_per_dynamic_request] || "–" }.join(" / ")}\n"
|
|
600
|
+
end
|
|
601
|
+
if first[:controller_tests] > 0
|
|
602
|
+
out << "* Not counted in run 1: #{first[:controller_tests]} request#{"s" if first[:controller_tests] != 1} made by " \
|
|
603
|
+
"controller tests (`ActionController::TestCase`, rspec-rails controller specs), which call the controller directly, " \
|
|
604
|
+
"without the app's middleware and routing\n"
|
|
605
|
+
end
|
|
606
|
+
connects = KINDS.filter_map do |kind|
|
|
607
|
+
per_run = summary.map { _1[:network][kind] }
|
|
608
|
+
"#{per_run.join(" / ")} in #{labels[kind]}" if per_run.any?(&:positive?)
|
|
609
|
+
end
|
|
610
|
+
unless connects.empty?
|
|
611
|
+
out << "* Left out: objects allocated inside `Socket.tcp`, by run #{connects.join(", ")}. It races its connection " \
|
|
612
|
+
"attempts on threads and timers, so how many follows timing; in a suite usually a probe for a server that is not " \
|
|
613
|
+
"running. Every action and line leaves them out\n"
|
|
614
|
+
end
|
|
615
|
+
out << "* **#{parallel_warning}**\n" if parallel_warning
|
|
616
|
+
out << "* Ledger: #{ledger_date ? "upstream pull requests as of #{ledger_date}" : "off"}\n"
|
|
617
|
+
out << "* lowrail-profile #{Lowrail::Profile::VERSION}\n"
|
|
618
|
+
if (missing = unclassified)
|
|
619
|
+
out << "* Not attributed: #{missing[:objects_per_request]} objects per request (#{(missing[:share] * 100).round(1)}% of all) " \
|
|
620
|
+
"are on lines outside the app, Rails, Ruby and the bundle's gems, which no table below ranks; most in " <<
|
|
621
|
+
missing[:files].map { "`#{_1[:path]}`" }.join(", ") << "\n"
|
|
622
|
+
end
|
|
623
|
+
out << "\n"
|
|
624
|
+
out << "| Run | Processes | Requests | Objects per request, all | Warm | Jobs | Mails | Cable actions | Dropped |\n" \
|
|
625
|
+
"| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: |\n"
|
|
626
|
+
summary.each do |s|
|
|
627
|
+
w = s[:windows]
|
|
628
|
+
out << "| #{s[:run]} | #{s[:processes]} | #{s[:requests]} | #{s[:objects_per_request].round(1)} | " \
|
|
629
|
+
"#{s[:warm_per_request].round(1)} | #{w["job"]} | " \
|
|
630
|
+
"#{w["mail"]} | #{w["cable"]} | #{s[:dropped]} |\n"
|
|
631
|
+
end
|
|
632
|
+
out << "\nAll: every object the requests allocated, with the one-time work of each process's first requests, objects " \
|
|
633
|
+
"Ruby keeps internal and those allocated inside `Socket.tcp`. Warm: the objects the lines below count, each line's " \
|
|
634
|
+
"first request per process left out, as the noise floor counts; this is the number to compare.\n"
|
|
635
|
+
summary.each do |s|
|
|
636
|
+
open = KINDS.to_h { [_1, s[:windows][_1] - s[:completed][_1]] }.select { _2 > 0 }
|
|
637
|
+
out << "\n#{s[:run]} left windows unfinished (#{open.map { "#{_2} #{_1}" }.join(", ")}), which no line or action " \
|
|
638
|
+
"counts; compare refuses it.\n" unless open.empty?
|
|
639
|
+
end
|
|
640
|
+
if (floor = noise_floor)
|
|
641
|
+
out << "\nNoise floor (last run minus first, warm, top #{floor[:top_lines]} lines): median |Δ| #{floor[:median_abs]}, " \
|
|
642
|
+
"max |Δ| #{floor[:max_abs]} objects per request; #{floor[:moved_ge_1]} lines moved by 1 or more.\n"
|
|
643
|
+
end
|
|
644
|
+
lines = app_lines
|
|
645
|
+
unless lines.empty?
|
|
646
|
+
out << "\n## Your code\n\nThe app lines whose calls lead to the most objects allocated in Rails, Ruby and gems, per " \
|
|
647
|
+
"request (repeat run): the nearest app line on the stack of each allocation, the app's tests and vendored gems " \
|
|
648
|
+
"left out. Warm: leaving out each line's first request per process. Dev/test: debug logging, error pages, " \
|
|
649
|
+
"template compilation, route building and asset lookup below the line, which production mostly does not do. " \
|
|
650
|
+
"Own: objects the line itself allocates.\n\n"
|
|
651
|
+
through, lines = lines.partition { _1[:passes_on] }
|
|
652
|
+
out << app_lines_table(lines, @top)
|
|
653
|
+
unless through.empty?
|
|
654
|
+
out << "\nApp middleware that hands the request on (the stack below it, not its own work): " <<
|
|
655
|
+
through.map { "`#{_1[:line].delete_prefix("APP/")}` #{_1[:warm]}" }.join(", ") << " warm objects per request.\n"
|
|
656
|
+
end
|
|
657
|
+
out << "\n#{unattributed} warm objects per request outside the app have no app line on the stack " \
|
|
658
|
+
"(middleware, routing, rendering setup).\n" if unattributed
|
|
659
|
+
end
|
|
660
|
+
requests = actions
|
|
661
|
+
unless requests.empty?
|
|
662
|
+
out << "\n## Actions\n\nObjects per request by controller action and run, counting everything the request " \
|
|
663
|
+
"allocates (app, Rails, gems, dev/test work). Warm leaves out the action's first request in each process; " \
|
|
664
|
+
"– when it ran once per process. An action with fewer than #{MIN_WARM} warm requests in a run comes last, ranked by " \
|
|
665
|
+
"all objects, which include one-time work. Top lines: warm objects per request of the action outside the app (repeat " \
|
|
666
|
+
"run, dev/test work left out).\n\n"
|
|
667
|
+
out << actions_table(requests, @top, "Action", "req")
|
|
668
|
+
end
|
|
669
|
+
mode_total = ranked.select { mode_only(_1) }.sum { mean(_1.warm) }
|
|
670
|
+
total = ranked.sum { mean(_1.warm) }
|
|
671
|
+
out << "\n## Top lines outside the app\n\n" \
|
|
672
|
+
"Warm: objects per request by run, without each line's first request per process (one-time work). " \
|
|
673
|
+
"All: including it, mean of the runs. Reach: share of requests in which the line allocated (last run). " \
|
|
674
|
+
"† charged from Ruby's `<internal:…>` code to this caller. A line `:0` has no line number: allocated while Ruby " \
|
|
675
|
+
"loaded or compiled the file, or by code evaluated without one. Ledger: upstream pull requests that reduce " \
|
|
676
|
+
"allocations and change this line, and whether the app's locked version has them. From the app: the nearest app line on the stack (repeat " \
|
|
677
|
+
"run); (middleware) marks app middleware that hands the request on, the nearest app line of work done after the " \
|
|
678
|
+
"request's code returned or raised, such as an error page. Dev/test-only work is listed separately below.\n\n"
|
|
679
|
+
out << table(rows)
|
|
680
|
+
unless (extra = mode_rows).empty?
|
|
681
|
+
out << "\n## Dev/test-mode work\n\n#{mode_total.round(1)} of #{total.round(1)} warm objects per request outside " \
|
|
682
|
+
"the app are work that test and development mode do and production mostly does not: debug logging, " \
|
|
683
|
+
"error pages, template compilation, route building, asset lookup, code reload checks.\n\n"
|
|
684
|
+
out << "| # | Kind | Line | Warm/req | Reach | From the app | Source |\n| ---: | --- | --- | ---: | ---: | --- | --- |\n"
|
|
685
|
+
extra.each do |r|
|
|
686
|
+
out << "| #{r[:rank]} | #{r[:mode]} | `#{r[:site]}`#{" †" if r[:via_internal]} | #{r[:warm].last} | " \
|
|
687
|
+
"#{(r[:reach].last * 100).round}% | #{callers_cell(r[:callers])} | #{cell(r[:text])} |\n"
|
|
688
|
+
end
|
|
689
|
+
end
|
|
690
|
+
shown, one_time = groups.partition { |_, data| data[:warm].round(1) > 0 }
|
|
691
|
+
out << "\n## By gem\n\nWarm and all objects per request by group; dev/test-mode work (the table above) is its own " \
|
|
692
|
+
"group.\n\n| Group | Warm/req | All/req | Top lines (warm) |\n| --- | ---: | ---: | --- |\n"
|
|
693
|
+
shown.each do |group, data|
|
|
694
|
+
top = data[:sites].select { mean(_1.warm).round(1) > 0 }.sort_by { -mean(_1.warm) }.first(3)
|
|
695
|
+
.map { "`#{File.basename(_1.key)}:#{_1.line}` #{mean(_1.warm).round(1)}" }
|
|
696
|
+
out << "| #{group} | #{data[:warm].round(1)} | #{data[:all].round(1)} | #{top.join(", ")} |\n"
|
|
697
|
+
end
|
|
698
|
+
unless one_time.empty?
|
|
699
|
+
out << "\n#{one_time.size} group#{"s" if one_time.size != 1} with no warm objects (0.0 per request), only one-time " \
|
|
700
|
+
"work in each process's first requests: #{one_time.map { "#{_1} #{_2[:all].round(1)}" }.join(", ")} all objects per request.\n"
|
|
701
|
+
end
|
|
702
|
+
out << outside_requests
|
|
703
|
+
out
|
|
704
|
+
end
|
|
705
|
+
|
|
706
|
+
# Jobs, mails and Action Cable actions, counted like requests and kept
|
|
707
|
+
# apart from them.
|
|
708
|
+
def outside_requests
|
|
709
|
+
kinds = KIND_TITLES.keys.select { |kind| @runs.any? { _1[:windows][kind] > 0 } }
|
|
710
|
+
return "" if kinds.empty?
|
|
711
|
+
out = +"\n## Outside requests\n\nJobs (`perform_now`), mails (each build and each delivery) and Action Cable " \
|
|
712
|
+
"channel actions run outside a request, counted the same way and per window. A job, mail or broadcast inside " \
|
|
713
|
+
"a request counts as part of that request.\n"
|
|
714
|
+
kinds.each do |kind|
|
|
715
|
+
label = { "job" => "Job", "mail" => "Mailer action", "cable" => "Channel action" }.fetch(kind)
|
|
716
|
+
out << "\n### #{KIND_TITLES.fetch(kind)}\n\n"
|
|
717
|
+
out << actions_table(actions(kind), @top, label)
|
|
718
|
+
lines = rows(ranked(kind), [@top / 3, 10].max)
|
|
719
|
+
next if lines.empty?
|
|
720
|
+
out << "\n| # | Line | Warm/window | Reach | From the app | Source |\n| ---: | --- | ---: | ---: | --- | --- |\n"
|
|
721
|
+
lines.each do |r|
|
|
722
|
+
out << "| #{r[:rank]} | `#{r[:site]}`#{" †" if r[:via_internal]}#{" (#{r[:mode]})" if r[:mode]} | " \
|
|
723
|
+
"#{r[:warm].join(" / ")} | #{(r[:reach].last * 100).round}% | #{callers_cell(r[:callers])} | #{cell(r[:text])} |\n"
|
|
724
|
+
end
|
|
725
|
+
end
|
|
726
|
+
out
|
|
727
|
+
end
|
|
728
|
+
|
|
729
|
+
def write
|
|
730
|
+
File.write(File.join(dir, "report.md"), markdown)
|
|
731
|
+
File.write(File.join(dir, "report.json"), JSON.pretty_generate(to_h) + "\n")
|
|
732
|
+
end
|
|
733
|
+
|
|
734
|
+
# The capture as compare checks it (capture.json, written by lowrail-profile): its identity (the command's
|
|
735
|
+
# arguments, or for --workloads the manifest and each run's measured
|
|
736
|
+
# request sequence), seed and exit status of each run; Ruby and
|
|
737
|
+
# environment of every process; dropped samples. A report without
|
|
738
|
+
# capture.json has no identity, which compare refuses.
|
|
739
|
+
def meta
|
|
740
|
+
capture_file = File.join(dir, "capture.json")
|
|
741
|
+
capture = File.exist?(capture_file) ? JSON.parse(File.read(capture_file)) : {}
|
|
742
|
+
identity = capture["identity"]
|
|
743
|
+
if identity && identity["mode"] == "workloads"
|
|
744
|
+
require "digest"
|
|
745
|
+
receipt = File.join(dir, "workloads.json")
|
|
746
|
+
manifest = JSON.parse(File.read(receipt))["manifest"] if File.exist?(receipt)
|
|
747
|
+
measured = @runs.map do |run|
|
|
748
|
+
file = File.join(dir, run[:name], "measured.json")
|
|
749
|
+
File.exist?(file) ? JSON.parse(File.read(file)) : nil
|
|
750
|
+
end
|
|
751
|
+
identity = identity.merge("manifest" => manifest && Digest::SHA256.hexdigest(JSON.generate(manifest.except("file")))[0, 16],
|
|
752
|
+
"measured" => measured)
|
|
753
|
+
end
|
|
754
|
+
{ format: FORMAT, identity: identity, argv: capture["argv"], seed: capture["seed"], exit: capture["exit"], runs: @runs.size,
|
|
755
|
+
timed_out: capture["timed_out"] || [], timeout: capture["timeout"],
|
|
756
|
+
ruby: @runs.flat_map { _1[:rubies] || [] }.uniq, rails_env: @runs.flat_map { _1[:rails_envs] || [] }.uniq,
|
|
757
|
+
dropped: @runs.map { _1[:dropped] } }
|
|
758
|
+
end
|
|
759
|
+
|
|
760
|
+
def to_h
|
|
761
|
+
command_file = File.join(dir, "command.txt")
|
|
762
|
+
{ command: File.exist?(command_file) ? File.read(command_file).lines.first.strip : nil, meta: meta,
|
|
763
|
+
summary: summary, noise_floor: noise_floor, rows: rows, mode_rows: mode_rows,
|
|
764
|
+
ranked: ranked.map { site_json(_1) }, app_lines: app_lines, unattributed: unattributed, unclassified: unclassified,
|
|
765
|
+
actions: actions,
|
|
766
|
+
outside_requests: (KINDS - ["request"]).to_h do |kind|
|
|
767
|
+
[kind, { actions: actions(kind), ranked: ranked(kind).map { site_json(_1) } }]
|
|
768
|
+
end,
|
|
769
|
+
groups: groups.map { |g, d| { group: g, warm: d[:warm], all: d[:all] } } }
|
|
770
|
+
end
|
|
771
|
+
|
|
772
|
+
def site_json(site)
|
|
773
|
+
{ site: "#{site.key}:#{site.line}", group: site.group, mode: mode_only(site), warm: site.warm, all: site.all,
|
|
774
|
+
reached: site.reached }
|
|
775
|
+
end
|
|
776
|
+
end
|
|
777
|
+
end
|