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.
@@ -0,0 +1,347 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require_relative "profile_report"
5
+
6
+ module Lowrail
7
+ # lowrail-profile compare BASE.json HEAD.json --aa BASE2.json: warm objects
8
+ # per request (and per job, mail and Action Cable action) by line outside
9
+ # the app and by action, head minus base, as a report: it exits 0 whatever
10
+ # it lists, and 2 when the reports are not valid evidence. 0.1 has no gate
11
+ # (docs/profile-gate-design.md): captured in one process, Hackatime's
12
+ # unchanged heads still crossed the floor 12.5% of the time, from an action
13
+ # whose cost moves 0.7% with data. A change is listed as a regression
14
+ # when it is larger than the noise floor. Its noise is the larger of the
15
+ # base's spread across the A/A pair, two invocations on the base (largest
16
+ # minus smallest of all their runs, so it covers both the pair's difference
17
+ # and each one's own spread), and head's own spread: the spread inside one
18
+ # invocation misses how much invocations differ (Campfire's
19
+ # json/common.rb:364 moved 0.27-3.3 inside a capture, 107.3-111.2 across
20
+ # six). The floor is twice that noise, since one A/A pair is one sample of
21
+ # it (on the 3.3 Blog one pair failed 4.5% of unchanged heads at once the
22
+ # noise), and at least --min objects for a line; for an action also 0.1% of
23
+ # its objects and 20 times --min (from Campfire's first A/A pair, every
24
+ # action within 0.08% and 6.5 objects; in one process the plants in
25
+ # README-profile.md were measured against it). Without --aa the
26
+ # noise is each report's own spread, smaller still.
27
+ #
28
+ # Only valid evidence is compared: complete reports of this version
29
+ # (every collection present, rows with unique keys, every warm vector one
30
+ # value per run), at least two runs each, every command exiting 0, no
31
+ # dropped samples, every window finished, one known Ruby and environment;
32
+ # and, for head and the A/A report against base, the same capture identity
33
+ # (the command's arguments, or for --workloads the manifest and every run's
34
+ # measured request sequence, once the run finished at least one measured
35
+ # request in one process that opened no other request windows, not the
36
+ # output directory), seed and number of runs. A kind of window is compared
37
+ # when every run of every report has some; one some runs have and others
38
+ # lack, or no comparable kind at all, is not evidence. Otherwise #status is
39
+ # 2 (insufficient evidence), whatever the numbers say. A line a report never
40
+ # reached is a measured zero there, but an action base, head or the A/A
41
+ # report did not run, or that has no warm value there (it ran once per
42
+ # process), is not compared.
43
+ class ProfileCompare
44
+ ACTION_SHARE = 0.001
45
+ ACTION_MIN = 20
46
+ KINDS = %w[request job mail cable].freeze
47
+
48
+ Change = Struct.new(:kind, :what, :name, :base, :head, :noise, keyword_init: true) do
49
+ def delta = head - base
50
+
51
+ def threshold(min)
52
+ what == "line" ? [2 * noise, min].max : [2 * noise, ACTION_SHARE * [base, head].max, ACTION_MIN * min].max
53
+ end
54
+ end
55
+
56
+ def initialize(base, head, aa: nil, min: 1.0, top: 20)
57
+ # Not !@aa.nil?: an A/A file that holds null parses to nil and is still a pair, refused.
58
+ @aa_given = !aa.nil?
59
+ @base, @head, @aa = [base, head, aa].map { |file| file && (JSON.parse(File.read(file)) rescue false) }
60
+ @aa_is_base = aa && (File.identical?(aa, base) rescue false)
61
+ @min = min
62
+ @top = top
63
+ @not_compared = []
64
+ end
65
+
66
+ # Why the two reports are not evidence for a comparison (empty when they are).
67
+ def problems
68
+ @problems ||= begin
69
+ list = reports.flat_map { |label, report| report_problems(label, report) }
70
+ list << "the A/A report is the base report itself: profile the unchanged base a second time and pass that" if @aa_is_base
71
+ if list.empty?
72
+ reports.except("base").each do |label, other|
73
+ %w[identity seed runs ruby rails_env].each do |key|
74
+ b, o = @base["meta"][key], other["meta"][key]
75
+ list << "base and #{label} differ in #{key}: #{b.to_json} and #{o.to_json}" if b != o
76
+ end
77
+ end
78
+ partial = KINDS.select { |kind| counts(kind).uniq.size > 1 && counts(kind).include?(false) }
79
+ list << "#{partial.join(", ")} windows ran in some runs only" if partial.any?
80
+ list << "no kind of window ran in every run of every report" if partial.empty? && kinds.empty?
81
+ end
82
+ list
83
+ end
84
+ end
85
+
86
+ # One strict check of a report's shape before any arithmetic: every key
87
+ # compare reads is present with its type, rows have unique keys, and
88
+ # anything unexpected is a problem (exit 2), never a crash or a zero.
89
+ def report_problems(label, report)
90
+ meta = report.is_a?(Hash) && report["meta"]
91
+ return ["#{label} is not a report.json of this lowrail-profile (no capture metadata)"] unless meta.is_a?(Hash) && meta.key?("format")
92
+ unless meta["format"] == ProfileReport::FORMAT
93
+ return ["#{label} is a report.json of format #{meta["format"].to_json}, this lowrail-profile reads #{ProfileReport::FORMAT}: profile it again"]
94
+ end
95
+ runs = meta["runs"]
96
+ return ["#{label} has no run count"] unless runs.is_a?(Integer) && runs > 0
97
+ list = []
98
+ count = ->(v) { v.is_a?(Integer) && v >= 0 }
99
+ list << "#{label} has #{runs} run(s); a noise floor needs at least 2" if runs < 2
100
+ list.concat(identity_problems(label, meta["identity"], runs))
101
+ list << "#{label} has no seed" unless meta["seed"].is_a?(String) && !meta["seed"].empty?
102
+ ruby, env = meta["ruby"], meta["rails_env"]
103
+ unless ruby.is_a?(Array) && ruby.size == 1 && ruby[0].is_a?(String) && !ruby[0].empty? &&
104
+ env.is_a?(Array) && env.size == 1 && env[0].is_a?(String)
105
+ list << "#{label} does not record one known Ruby and environment (#{ruby.to_json}, #{env.to_json})"
106
+ end
107
+ exits = meta["exit"]
108
+ list << "#{label}'s command exited #{exits.to_json}" unless exits.is_a?(Array) && exits.size == runs && exits.all?(0)
109
+ dropped = meta["dropped"]
110
+ list << "#{label} dropped samples (#{dropped.to_json})" unless dropped.is_a?(Array) && dropped.size == runs && dropped.all?(0)
111
+ summary = report["summary"]
112
+ unless summary.is_a?(Array) && summary.size == runs && summary.all? do |run|
113
+ run.is_a?(Hash) && %w[windows completed].all? { |k| run[k].is_a?(Hash) && KINDS.all? { count.(run[k][_1]) } } &&
114
+ count.(run["processes"]) && run["objects_per_request"].is_a?(Numeric) && run["objects_per_request"].to_f.finite?
115
+ end
116
+ return list << "#{label}'s summary is not one row per run with processes, objects per request, and windows and completed windows of every kind"
117
+ end
118
+ # A workloads certificate covers its run only if its request windows are
119
+ # exactly the requests it measured (an at_exit request would add one);
120
+ # a fork is a second process, refused below.
121
+ measured = meta["identity"].is_a?(Hash) && meta["identity"]["mode"] == "workloads" && meta["identity"]["measured"]
122
+ if measured.is_a?(Array) && measured.size == runs && measured.all?(Hash)
123
+ uncovered = summary.zip(measured).reject { |run, m| run["windows"]["request"] == m["requests"] }
124
+ list << "#{label} has #{uncovered.size} run(s) whose request windows are not the one process's measured requests" if uncovered.any?
125
+ end
126
+ # Warm leaves out each process's first window of an action. Parallel test
127
+ # workers split the tests anew in every capture, so in a run of several
128
+ # processes which windows those are, and with them every warm value, is
129
+ # different between captures in a way one A/A pair does not sample.
130
+ parallel = summary.map { _1["processes"] }.max
131
+ if parallel > 1
132
+ list << "#{label} ran in #{parallel} processes: parallel test workers split the tests differently in every capture, " \
133
+ "which changes what warm leaves out; profile with PARALLEL_WORKERS=1 to compare"
134
+ end
135
+ list << "#{label} has a run without requests, jobs, mails or Cable actions" if summary.any? { |run| KINDS.sum { run["windows"][_1] } == 0 }
136
+ open = summary.reject { |run| KINDS.all? { run["windows"][_1] == run["completed"][_1] } }
137
+ list << "#{label} has #{open.size} run(s) with windows that never finished, which no line or action counts" if open.any?
138
+ outside = report["outside_requests"]
139
+ return list << "#{label} has no outside_requests" unless outside.is_a?(Hash)
140
+ KINDS.each do |kind|
141
+ source = kind == "request" ? report : outside[kind]
142
+ { "ranked" => "site", "actions" => "name" }.each do |key, id|
143
+ entries = source.is_a?(Hash) && source[key]
144
+ next list << "#{label} has no #{kind} #{key}" unless entries.is_a?(Array) && entries.all?(Hash)
145
+ actions = key == "actions"
146
+ names = entries.map { _1[id] }
147
+ unless names.all? { _1.is_a?(String) || (actions && _1.nil?) } && names.uniq.size == names.size
148
+ list << "#{label} has #{kind} #{key} without a unique #{id}"
149
+ end
150
+ bad = entries.count do |e|
151
+ warm = e["warm"]
152
+ !(warm.is_a?(Array) && warm.size == runs && warm.all? { (actions && _1.nil?) || (_1.is_a?(Numeric) && _1.to_f.finite?) })
153
+ end
154
+ list << "#{label} has #{bad} #{kind} #{key} without one finite warm value per run" if bad > 0
155
+ next unless actions
156
+ # Every completed window is some action's: actions that do not add up
157
+ # to them leave windows no row accounts for.
158
+ windows = entries.map { _1["windows"] }
159
+ next list << "#{label} has #{kind} actions without a window count per run" unless windows.all? { _1.is_a?(Array) && _1.size == runs && _1.all?(&count) }
160
+ sums = windows.empty? ? [0] * runs : windows.transpose.map(&:sum)
161
+ completed = summary.map { _1["completed"][kind] }
162
+ list << "#{label}'s #{kind} actions add up to #{sums.join(" / ")} windows, its summary to #{completed.join(" / ")} completed" if sums != completed
163
+ end
164
+ end
165
+ list
166
+ end
167
+
168
+ # A command's arguments, or a workloads capture: its manifest, host, and
169
+ # per run the requests it measured once it finished, all certified.
170
+ def identity_problems(label, identity, runs)
171
+ case identity.is_a?(Hash) && identity["mode"]
172
+ when "command"
173
+ argv = identity["argv"]
174
+ argv.is_a?(Array) && !argv.empty? && argv.all? { _1.is_a?(String) } ? [] : ["#{label}'s command identity has no arguments"]
175
+ when "workloads"
176
+ list = []
177
+ known = ->(v) { v.is_a?(String) && !v.empty? }
178
+ list << "#{label} has no workloads manifest or host" unless known.(identity["manifest"]) && known.(identity["host"])
179
+ measured = identity["measured"]
180
+ unless measured.is_a?(Array) && measured.size == runs && measured.all? do |m|
181
+ m.is_a?(Hash) && m["complete"] == true && known.(m["sha256"]) && m["requests"].is_a?(Integer) && m["requests"] >= 1
182
+ end
183
+ return list << "#{label} does not record that every run finished measuring at least one request"
184
+ end
185
+ names = measured.flat_map { Array(_1["uncertified"]) }.uniq
186
+ list << "#{label} sends env: values a digest cannot certify (#{names.join(", ")}): it is not CI evidence" if names.any?
187
+ list << "#{label}'s runs measured different requests" if measured.map { _1["sha256"] }.uniq.size > 1
188
+ list
189
+ else
190
+ ["#{label} has no known capture identity (profile it again with this lowrail-profile)"]
191
+ end
192
+ end
193
+
194
+ def reports = { "base" => @base, "head" => @head, **(aa? ? { "the A/A report" => @aa } : {}) }
195
+
196
+ def valid? = problems.empty?
197
+
198
+ # A second capture with the very same counts may be a copy of the base, which measures no spread.
199
+ def warnings = aa? && !@aa_is_base && valid? && @aa == @base ? ["the A/A report has exactly the base's counts: if it is a copy of the base, it measures no difference between captures"] : []
200
+
201
+ # Only an A/A pair measures how much invocations differ.
202
+ def aa? = @aa_given
203
+
204
+ # 0 a report (whatever it lists), 2 not valid evidence.
205
+ def status = valid? ? 0 : 2
206
+
207
+ def windows(run) = run.is_a?(Hash) && run["windows"].is_a?(Hash) ? run["windows"] : {}
208
+
209
+ # Per run of every report: whether it has windows of the kind.
210
+ def counts(kind) = reports.values.flat_map { |r| Array(r["summary"]).map { windows(_1)[kind].to_i > 0 } }
211
+
212
+ def mean(values) = values.sum / values.size
213
+
214
+ # The spread of a report's runs: largest minus smallest.
215
+ def spread(values) = values.size > 1 ? values.max - values.min : 0.0
216
+
217
+ # Kinds every run of every report has windows of.
218
+ def kinds = KINDS.select { |kind| counts(kind).all? }
219
+
220
+ def lines(report, kind)
221
+ list = kind == "request" ? report["ranked"] : report.dig("outside_requests", kind, "ranked")
222
+ Array(list).to_h { [_1["site"], _1["warm"]] }
223
+ end
224
+
225
+ def actions(report, kind)
226
+ list = kind == "request" ? report["actions"] : report.dig("outside_requests", kind, "actions")
227
+ Array(list).to_h { [_1["name"] || "(no name)", _1["warm"]] }
228
+ end
229
+
230
+ # Objects allocated inside Socket.tcp per kind, by run: the counter leaves
231
+ # them out of every action and line, since how many follows timing.
232
+ def network(report)
233
+ KINDS.to_h { |kind| [kind, Array(report["summary"]).map { _1.is_a?(Hash) && _1["network"].is_a?(Hash) ? _1["network"][kind].to_i : 0 }] }
234
+ end
235
+
236
+ # Actions left out, with why: filled as the changes are computed.
237
+ def not_compared = (changes; @not_compared)
238
+
239
+ def changes
240
+ @changes ||= valid? ? kinds.flat_map { |kind| line_changes(kind) + action_changes(kind) } : []
241
+ end
242
+
243
+ # The base's spread across all runs of the A/A pair, or head's own if larger.
244
+ def noise(b, a, h) = [spread(a ? b + a : b), spread(h)].max
245
+
246
+ def line_changes(kind)
247
+ base, head = lines(@base, kind), lines(@head, kind)
248
+ aa = lines(@aa, kind) if aa?
249
+ zero = [0.0] * @base["meta"]["runs"]
250
+ (base.keys | head.keys).map do |name|
251
+ b, h = base[name] || zero, head[name] || zero
252
+ Change.new(kind: kind, what: "line", name: name, base: mean(b), head: mean(h), noise: noise(b, aa&.[](name), h))
253
+ end
254
+ end
255
+
256
+ def action_changes(kind)
257
+ base, head = actions(@base, kind), actions(@head, kind)
258
+ aa = actions(@aa, kind) if aa?
259
+ warm = ->(w) { w && !w.empty? && !w.include?(nil) }
260
+ (base.keys | head.keys).filter_map do |name|
261
+ b, h, a = base[name], head[name], aa&.[](name)
262
+ reason = if !(b && h) then "ran in #{b ? "base" : "head"} only"
263
+ elsif !warm.(b) || !warm.(h) then "no warm value in #{[("base" unless warm.(b)), ("head" unless warm.(h))].compact.join(" and ")}"
264
+ elsif aa && !a then "not run in the A/A report"
265
+ elsif aa && !warm.(a) then "no warm value in the A/A report"
266
+ end
267
+ if reason
268
+ @not_compared << { kind: kind, name: name, reason: reason }
269
+ next
270
+ end
271
+ Change.new(kind: kind, what: "action", name: name, base: mean(b), head: mean(h), noise: noise(b, a, h))
272
+ end
273
+ end
274
+
275
+ def regressions = changes.select { _1.delta > _1.threshold(@min) }.sort_by { -_1.delta }
276
+ def improvements = changes.select { -_1.delta > _1.threshold(@min) }.sort_by { _1.delta }
277
+
278
+ def total(report) = Array(report["summary"]).map { _1["objects_per_request"] if _1.is_a?(Hash) }.compact
279
+
280
+ def markdown
281
+ out = +"# lowrail-profile compare\n\n"
282
+ out << "Base: `#{@base["command"]}`. Head: `#{@head["command"]}`.\n\n" if @base.is_a?(Hash) && @head.is_a?(Hash) && (@base["command"] || @head["command"])
283
+ unless valid?
284
+ out << "## Insufficient evidence\n\nThese reports are not a valid comparison (exit 2):\n\n"
285
+ problems.each { out << "* #{_1}\n" }
286
+ return out << "\n"
287
+ end
288
+ base_total, head_total = total(@base), total(@head)
289
+ unless base_total.empty? || head_total.empty?
290
+ out << "Objects per request (all, by run): base #{base_total.map { _1.round(1) }.join(" / ")}, " \
291
+ "head #{head_total.map { _1.round(1) }.join(" / ")}.\n\n"
292
+ end
293
+ noise = aa? ? "the base's run-to-run spread across the A/A pair, or head's own if larger," : "the larger run-to-run spread in either report"
294
+ out << "A change counts when it exceeds the noise floor: twice #{noise} and for a line at least #{@min} objects per " \
295
+ "request (warm); for an action at least #{(ACTION_SHARE * 100).round(1)}% of its objects and at least " \
296
+ "#{ACTION_MIN * @min}. Compared: #{kinds.join(", ")}.\n\n"
297
+ unless not_compared.empty?
298
+ actions = changes.count { _1.what == "action" } + not_compared.size
299
+ reasons = not_compared.group_by { _1[:reason] }.map { "#{_2.size} #{_1}" }.join(", ")
300
+ out << "**Not compared: #{not_compared.size} of #{actions} actions** (#{reasons}), so a change in them is not " \
301
+ "checked; they are listed at the end.\n\n"
302
+ end
303
+ connects = KINDS.filter_map do |kind|
304
+ b, h = network(@base)[kind], network(@head)[kind]
305
+ "#{kind}s base #{b.join(" / ")}, head #{h.join(" / ")}" if (b + h).any?(&:positive?)
306
+ end
307
+ unless connects.empty?
308
+ out << "Not compared: objects allocated inside `Socket.tcp`, which every action and line leaves out (it races its " \
309
+ "connection attempts on threads and timers, so how many follows timing); by run: #{connects.join("; ")}.\n\n"
310
+ end
311
+ warnings.each { out << "**Warning:** #{_1}.\n\n" }
312
+ out << "**A report, not a gate (exit 0).** What it lists is a place to look: a listed change can be noise, and a " \
313
+ "small one can be missing (README-profile.md, *Compare*).#{" Without an A/A pair the floor is the spread inside one " \
314
+ "capture, which misses how much invocations differ; profile the base twice and pass the second with `--aa`." unless aa?}\n\n"
315
+ { "Regressions" => regressions, "Improvements" => improvements }.each do |title, list|
316
+ out << "## #{title}: #{list.size}\n\n"
317
+ next out << "None.\n\n" if list.empty?
318
+ out << "| Kind | Line or action | Base | Head | Δ | Noise floor |\n| --- | --- | ---: | ---: | ---: | ---: |\n"
319
+ list.first(@top).each do |c|
320
+ name = c.what == "line" ? "`#{c.name}`" : c.name
321
+ out << "| #{c.kind} #{c.what} | #{name} | #{c.base.round(2)} | #{c.head.round(2)} | " \
322
+ "#{format("%+.2f", c.delta)} | #{c.threshold(@min).round(2)} |\n"
323
+ end
324
+ out << "\n#{list.size - @top} more in the JSON.\n" if list.size > @top
325
+ out << "\n"
326
+ end
327
+ unless not_compared.empty?
328
+ out << "## Not compared: #{not_compared.size} actions\n\n"
329
+ if not_compared.any? { _1[:reason].start_with?("no warm value") }
330
+ out << "Warm leaves out each process's first window of an action, so an action that ran once per process has no " \
331
+ "warm value and nothing to compare.\n\n"
332
+ end
333
+ out << "| Kind | Action | Why |\n| --- | --- | --- |\n"
334
+ not_compared.first(@top).each { out << "| #{_1[:kind]} | #{_1[:name]} | #{_1[:reason]} |\n" }
335
+ out << "\n#{not_compared.size - @top} more in the JSON.\n" if not_compared.size > @top
336
+ end
337
+ out
338
+ end
339
+
340
+ def to_h
341
+ row = ->(c) { { kind: c.kind, what: c.what, name: c.name, base: c.base, head: c.head, delta: c.delta, noise_floor: c.threshold(@min) } }
342
+ { status: status, aa: aa?, problems: problems, warnings: warnings, min: @min, compared: valid? ? kinds : [], regressions: regressions.map(&row),
343
+ improvements: improvements.map(&row), not_compared: not_compared,
344
+ network: valid? ? { base: network(@base), head: network(@head) } : nil }
345
+ end
346
+ end
347
+ end