auto-optimize 1.0.0__py3-none-any.whl

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.
Files changed (67) hide show
  1. auto_optimize/__init__.py +3 -0
  2. auto_optimize/__main__.py +5 -0
  3. auto_optimize/cli.py +651 -0
  4. auto_optimize/skills/auto-optimize-code/LICENSE +21 -0
  5. auto_optimize/skills/auto-optimize-code/SKILL.md +251 -0
  6. auto_optimize/skills/auto-optimize-code/VERSION +1 -0
  7. auto_optimize/skills/auto-optimize-code/references/algorithm.md +182 -0
  8. auto_optimize/skills/auto-optimize-code/references/changes.md +146 -0
  9. auto_optimize/skills/auto-optimize-code/references/cli.md +206 -0
  10. auto_optimize/skills/auto-optimize-code/references/dashboard.md +203 -0
  11. auto_optimize/skills/auto-optimize-code/references/documents.md +55 -0
  12. auto_optimize/skills/auto-optimize-code/references/extending.md +87 -0
  13. auto_optimize/skills/auto-optimize-code/references/external-validation.md +98 -0
  14. auto_optimize/skills/auto-optimize-code/references/glossary.md +134 -0
  15. auto_optimize/skills/auto-optimize-code/references/idea-miner.md +108 -0
  16. auto_optimize/skills/auto-optimize-code/references/issue-bugs.md +182 -0
  17. auto_optimize/skills/auto-optimize-code/references/layout.md +300 -0
  18. auto_optimize/skills/auto-optimize-code/references/main-session.md +45 -0
  19. auto_optimize/skills/auto-optimize-code/references/measuring.md +208 -0
  20. auto_optimize/skills/auto-optimize-code/references/pr-optimization.md +127 -0
  21. auto_optimize/skills/auto-optimize-code/references/pr-tests.md +254 -0
  22. auto_optimize/skills/auto-optimize-code/references/promotion.md +133 -0
  23. auto_optimize/skills/auto-optimize-code/references/reading-a-search.md +65 -0
  24. auto_optimize/skills/auto-optimize-code/references/repo-mode.md +224 -0
  25. auto_optimize/skills/auto-optimize-code/references/resume.md +81 -0
  26. auto_optimize/skills/auto-optimize-code/references/shared-knowledge.md +114 -0
  27. auto_optimize/skills/auto-optimize-code/references/step0-interview.md +298 -0
  28. auto_optimize/skills/auto-optimize-code/references/step1-unit-tests.md +136 -0
  29. auto_optimize/skills/auto-optimize-code/references/step2-baseline.md +708 -0
  30. auto_optimize/skills/auto-optimize-code/references/step3-rounds.md +350 -0
  31. auto_optimize/skills/auto-optimize-code/references/step4-final.md +121 -0
  32. auto_optimize/skills/auto-optimize-code/references/step5-ship.md +220 -0
  33. auto_optimize/skills/auto-optimize-code/references/step6-finish.md +67 -0
  34. auto_optimize/skills/auto-optimize-code/references/subagent.md +467 -0
  35. auto_optimize/skills/auto-optimize-code/references/symptoms.md +67 -0
  36. auto_optimize/skills/auto-optimize-code/references/writing-briefs.md +117 -0
  37. auto_optimize/skills/auto-optimize-code/scripts/attribution.py +156 -0
  38. auto_optimize/skills/auto-optimize-code/scripts/autoopt.py +12863 -0
  39. auto_optimize/skills/auto-optimize-code/scripts/check_seeding.py +334 -0
  40. auto_optimize/skills/auto-optimize-code/scripts/cold.py +90 -0
  41. auto_optimize/skills/auto-optimize-code/scripts/dashboard/README.md +165 -0
  42. auto_optimize/skills/auto-optimize-code/scripts/dashboard/autoopt_monitor.py +850 -0
  43. auto_optimize/skills/auto-optimize-code/scripts/dashboard/gpu_scan.py +954 -0
  44. auto_optimize/skills/auto-optimize-code/scripts/dashboard/monitor_writer.py +684 -0
  45. auto_optimize/skills/auto-optimize-code/scripts/dashboard/scan.py +1030 -0
  46. auto_optimize/skills/auto-optimize-code/scripts/dashboard/static/dashboard.css +775 -0
  47. auto_optimize/skills/auto-optimize-code/scripts/dashboard/static/dashboard.js +3652 -0
  48. auto_optimize/skills/auto-optimize-code/scripts/dashboard/static/index.html +191 -0
  49. auto_optimize/skills/auto-optimize-code/scripts/issue_body.py +2118 -0
  50. auto_optimize/skills/auto-optimize-code/scripts/lint_text.py +448 -0
  51. auto_optimize/skills/auto-optimize-code/scripts/opt_pr_body.py +894 -0
  52. auto_optimize/skills/auto-optimize-code/scripts/opt_pr_tables.py +367 -0
  53. auto_optimize/skills/auto-optimize-code/scripts/paired.py +188 -0
  54. auto_optimize/skills/auto-optimize-code/scripts/preflight.py +280 -0
  55. auto_optimize/skills/auto-optimize-code/scripts/probe_run.py +72 -0
  56. auto_optimize/skills/auto-optimize-code/scripts/publish.py +385 -0
  57. auto_optimize/skills/auto-optimize-code/scripts/run_iteration.py +1382 -0
  58. auto_optimize/skills/auto-optimize-code/scripts/ship.py +1193 -0
  59. auto_optimize/skills/auto-optimize-code/scripts/stages.py +651 -0
  60. auto_optimize/skills/auto-optimize-code/scripts/tests_pr_body.py +1267 -0
  61. auto_optimize/skills/auto-optimize-code/scripts/tests_pr_push.py +426 -0
  62. auto_optimize/skills/auto-optimize-code/scripts/tests_pr_tables.py +779 -0
  63. auto_optimize-1.0.0.dist-info/METADATA +610 -0
  64. auto_optimize-1.0.0.dist-info/RECORD +67 -0
  65. auto_optimize-1.0.0.dist-info/WHEEL +4 -0
  66. auto_optimize-1.0.0.dist-info/entry_points.txt +2 -0
  67. auto_optimize-1.0.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,894 @@
1
+ #!/usr/bin/env python3
2
+ """Render the optimization PR's body from its tables and its prose.
3
+
4
+ python3 opt_pr_body.py DIR --template > DIR/prose.md
5
+ python3 opt_pr_body.py DIR --title 'Vectorize column scoring' --out DIR/body.md
6
+
7
+ DIR holds the tables `opt_pr_tables.py` wrote and one prose file,
8
+ `prose.md`, of `=== <field>` blocks. Every number in the body is computed from
9
+ the tables, so the same tables and prose give the same body, byte for byte;
10
+ prose writes `{{token}}` where it needs one: `{{target}}` (the branch, in
11
+ backticks), `{{commits}}`, `{{files}}`, `{{runs}}`, `{{first}}` and `{{kept}}`
12
+ (the objective's median on the target and on this branch), `{{speedup}}`. `--out` writes the body and,
13
+ beside it, the title as `<out stem>.title`. `--template` prints the prose
14
+ skeleton for the tables DIR holds.
15
+
16
+ Exits 1, writes nothing and lists every problem on stderr when the prose or
17
+ the tables are wrong. `references/pr-optimization.md` describes every field.
18
+
19
+ Standard library only.
20
+ """
21
+
22
+ import os
23
+ import re
24
+ import sys
25
+ import json
26
+ import math
27
+ import argparse
28
+
29
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
30
+
31
+ import attribution
32
+ import publish
33
+
34
+ # What each prose field holds, as --template explains it:
35
+ # (takes an argument, text).
36
+ FIELDS = {
37
+ 'summary': (False, 'one or two sentences: what this PR changes in the '
38
+ 'code ("Replaces the per-record loop in `score()` with array '
39
+ 'operations."). The renderer follows it with the measured change'),
40
+ 'input': (False, 'the input the main measurement ran on, as a noun phrase '
41
+ 'that follows "On" ("a 10 Mbp DNA sequence with about 1% N")'),
42
+ 'row': (True, 'after the measure\'s name (`=== row seconds`): the '
43
+ 'Measure cell of its row in the Performance table, saying what is '
44
+ 'measured on which input and, when the table cannot, in which unit '
45
+ '("Peak resident memory (MB), 10 Mbp sequence")'),
46
+ 'timed': (False, 'what one run measures: the call or command, what is '
47
+ 'warmed up or cached first, and what the time covers'),
48
+ 'machine': (False, 'the machine the numbers came from: CPU, cores, OS, '
49
+ 'Python. Used only when the tables do not record it'),
50
+ 'outliers': (False, 'each row the kept code made worse, and why. Required '
51
+ 'when a row is worse beyond the run-to-run spread'),
52
+ 'cold': (False, 'why the first call in a new process takes longer on this '
53
+ 'branch (a compile, a cache to fill). Required when it takes more '
54
+ 'than twice as long'),
55
+ 'portability': (False, 'the OS-specific calls and the constants fitted to '
56
+ 'one machine that the change adds, or that it adds none'),
57
+ 'vendored': (False, 'code copied or translated from another project: '
58
+ 'files, project, version and license; or the single word none'),
59
+ 'change': (True, 'after the entry\'s short name (`=== change Vectorize '
60
+ 'scoring`): a first line `iterations: A4, A11` naming each kept change '
61
+ 'the entry covers (never printed), then what the change does as it '
62
+ 'stands in this branch, read from the diffs; sub-bullets allowed'),
63
+ 'behaviour': (False, 'every difference a user can see, one bullet each: '
64
+ 'output, messages, threads, files written, defaults, behaviour on bad '
65
+ 'input; or one sentence saying there are none'),
66
+ 'tests': (False, 'the repository\'s test suite and how it was run, as the '
67
+ 'subject of "passed on this branch" ("The testthat suite '
68
+ '(`devtools::test()`)"); with no unit tests, optionally why'),
69
+ 'gate': (True, 'after the check\'s name (`=== gate n_mismatch`): what '
70
+ 'the check compares, as a clause ("the number of positions where the '
71
+ 'output array differs from the one `main` returns")'),
72
+ 'compare': (False, 'the further inputs the separate output comparison '
73
+ 'ran on, as a noun phrase ("57 inputs: every documented option on '
74
+ 'three sequence files")'),
75
+ }
76
+ OPTIONAL = ('machine', 'outliers', 'cold', 'tests')
77
+ TOKEN = re.compile(r'\{\{([a-z_]+)\}\}')
78
+ LIST_ITEM = re.compile(r'^\s*([-*]|\d+\.)\s')
79
+
80
+
81
+ class Problems(list):
82
+ def add(self, problem):
83
+ if problem not in self:
84
+ self.append(problem)
85
+
86
+
87
+ def read_json(directory, name, problems, required=True):
88
+ path = os.path.join(directory, name)
89
+
90
+ try:
91
+ with open(path, encoding='utf-8') as handle:
92
+ return json.load(handle)
93
+ except OSError:
94
+ if required:
95
+ problems.add('{} is missing: run opt_pr_tables.py'.format(path))
96
+ except ValueError as error:
97
+ problems.add('{}: {}'.format(path, error))
98
+
99
+ return None
100
+
101
+
102
+ def read_table(directory, name, problems):
103
+ """The rows of a tab-separated table with a header, as dicts."""
104
+
105
+ path = os.path.join(directory, name)
106
+
107
+ try:
108
+ with open(path, encoding='utf-8') as handle:
109
+ lines = [line.rstrip('\n') for line in handle if line.strip()]
110
+ except OSError:
111
+ problems.add('{} is missing: run opt_pr_tables.py'.format(path))
112
+ return []
113
+
114
+ header = lines[0].split('\t')
115
+ rows = []
116
+
117
+ for number, line in enumerate(lines[1:], 2):
118
+ cells = line.split('\t')
119
+
120
+ if len(cells) != len(header):
121
+ problems.add('{}:{}: {} cells, the header has {}'.format(path,
122
+ number, len(cells), len(header)))
123
+ continue
124
+
125
+ rows.append(dict(zip(header, cells)))
126
+
127
+ return rows
128
+
129
+
130
+ def read_prose(path, problems):
131
+ """`{(field, argument or None): text}` in file order."""
132
+
133
+ try:
134
+ with open(path, encoding='utf-8') as handle:
135
+ text = handle.read()
136
+ except OSError:
137
+ problems.add('{} is missing: `opt_pr_body.py DIR --template > {}`, '
138
+ 'then fill it'.format(path, path))
139
+ return {}
140
+
141
+ fields, current = {}, None
142
+
143
+ for number, line in enumerate(text.splitlines(), 1):
144
+ if line.startswith('=== '):
145
+ name, _, argument = line[4:].strip().partition(' ')
146
+ argument = argument.strip() or None
147
+ current = (name, argument)
148
+
149
+ if name not in FIELDS:
150
+ problems.add('prose.md:{}: unknown field "{}"'.format(number,
151
+ name))
152
+ elif FIELDS[name][0] and not argument:
153
+ problems.add('prose.md:{}: "=== {}" needs a name after it'
154
+ .format(number, name))
155
+ elif not FIELDS[name][0] and argument:
156
+ problems.add('prose.md:{}: "=== {}" takes nothing after it'
157
+ .format(number, name))
158
+
159
+ if current in fields:
160
+ problems.add('prose.md:{}: "{}" appears twice'.format(number,
161
+ line.strip()))
162
+
163
+ fields[current] = []
164
+ continue
165
+
166
+ if current is None:
167
+ if line.strip():
168
+ problems.add('prose.md:{}: text before the first field'.format(
169
+ number))
170
+ continue
171
+
172
+ fields[current].append(line)
173
+
174
+ prose = {}
175
+
176
+ for key, lines in fields.items():
177
+ value = '\n'.join(lines).strip('\n')
178
+ where = '"=== {}"'.format(' '.join(part for part in key if part))
179
+
180
+ if not value.strip():
181
+ problems.add('{} is empty'.format(where))
182
+ elif '<<FILL' in value:
183
+ problems.add('{} still holds <<FILL'.format(where))
184
+ elif any(line.lstrip().startswith('#') for line in lines):
185
+ problems.add('{} holds a heading; fields hold sentences'.format(
186
+ where))
187
+
188
+ prose[key] = value
189
+
190
+ return prose
191
+
192
+
193
+ def sig(value, digits=3):
194
+ """`value` to `digits` significant figures: commas from 1,000, no
195
+ exponent for an ordinary number."""
196
+
197
+ if value == 0:
198
+ return '0'
199
+
200
+ magnitude = int(math.floor(math.log10(abs(value))))
201
+
202
+ if magnitude >= digits - 1:
203
+ return '{:,.0f}'.format(round(value, digits - 1 - magnitude))
204
+
205
+ text = '{:.{}f}'.format(value, digits - 1 - magnitude)
206
+
207
+ return text if 'e' not in text else '{:.{}g}'.format(value, digits)
208
+
209
+
210
+ def seconds(value):
211
+ for scale, unit in ((1.0, 's'), (1e-3, 'ms'), (1e-6, 'µs')):
212
+ if abs(value) >= scale:
213
+ return '{} {}'.format(sig(value / scale), unit)
214
+
215
+ return '{} ns'.format(sig(value / 1e-9))
216
+
217
+
218
+ def is_time(name, unit):
219
+ return unit == 's' or name == 'seconds' or name.startswith('seconds_') \
220
+ or name.startswith('time')
221
+
222
+
223
+ def quantity(value, name, unit):
224
+ if is_time(name, unit):
225
+ return seconds(value)
226
+
227
+ return sig(value) + (' ' + unit if unit else '')
228
+
229
+
230
+ def change(row, direction):
231
+ """`(text, worse)`: the kept code against the first measurement, and
232
+ whether it is worse beyond the run-to-run spread (None: no direction)."""
233
+
234
+ first, kept = row['first_median'], row['kept_median']
235
+ time = is_time(row['measure'], row['unit'])
236
+
237
+ if time and first > 0 and kept > 0:
238
+ ratio = first / kept
239
+ text = '{}x faster'.format(sig(ratio)) if ratio >= 1 else \
240
+ '{}x slower'.format(sig(1 / ratio))
241
+ return text, kept > first and row['kept_min'] > row['first_max']
242
+
243
+ if first == 0:
244
+ return 'from 0', None
245
+
246
+ percent = (kept - first) / abs(first) * 100
247
+ text = '{:+.{}f}%'.format(percent, 1 if abs(percent) < 10 else 0)
248
+
249
+ if direction is None:
250
+ return text, None
251
+
252
+ worse = (kept > first) if direction == 'min' else (kept < first)
253
+ beyond = (row['kept_min'] > row['first_max']) if direction == 'min' else \
254
+ (row['kept_max'] < row['first_min'])
255
+
256
+ return text, worse and beyond
257
+
258
+
259
+ def details(summary, lines):
260
+ return ['<details>', '<summary>{}</summary>'.format(summary), ''] + lines + [
261
+ '', '</details>']
262
+
263
+
264
+ def paragraph(text):
265
+ """A prose field joined into one paragraph, unless it is a list."""
266
+
267
+ if any(LIST_ITEM.match(line) for line in text.split('\n')):
268
+ return text
269
+
270
+ return ' '.join(text.split())
271
+
272
+
273
+ class Context:
274
+ def __init__(self, directory):
275
+ self.directory = directory
276
+ self.problems = Problems()
277
+ self.used = set()
278
+ self.numbers = set()
279
+ problems = self.problems
280
+ self.branch = read_json(directory, 'branch.json', problems) or {}
281
+ self.changes = read_table(directory, 'changes.tsv', problems)
282
+ self.files = read_table(directory, 'files.tsv', problems)
283
+ self.performance = read_table(directory, 'performance.tsv', problems)
284
+ self.gates = read_table(directory, 'gates.tsv', problems)
285
+ self.checks = read_json(directory, 'checks.json', problems) or {}
286
+ self.paired = read_json(directory, 'paired.json', problems)
287
+ self.machine = read_json(directory, 'machine.json', problems)
288
+ self.tests = read_json(directory, 'tests.json', problems)
289
+ self.prose = read_prose(os.path.join(directory, 'prose.md'), problems)
290
+ # The live answer when the search is found, so a document the user
291
+ # dropped after the tables were written is not cited; the copy in
292
+ # branch.json for a folder rendered on its own.
293
+ search_config = os.path.join(os.path.dirname(os.path.dirname(
294
+ os.path.abspath(directory))), 'autooptimize', 'config.json')
295
+ self.documents = publish.chosen(directory) if os.path.exists(
296
+ search_config) else (self.branch.get('documents') or
297
+ publish.chosen(directory))
298
+
299
+ for row in self.performance:
300
+ for key in ('first_median', 'first_min', 'first_max', 'kept_median',
301
+ 'kept_min', 'kept_max'):
302
+ row[key] = float(row[key])
303
+
304
+ def field(self, name, argument=None, required=True):
305
+ key = (name, argument)
306
+
307
+ if key not in self.prose:
308
+ if required:
309
+ self.problems.add('prose.md has no "=== {}" field{}'.format(
310
+ ' '.join(part for part in key if part), '' if FIELDS[name][
311
+ 0] else ''))
312
+ return None
313
+
314
+ self.used.add(key)
315
+ return self.fill(self.prose[key], key)
316
+
317
+ def fill(self, text, key):
318
+ def one(match):
319
+ name = match.group(1)
320
+
321
+ if name not in self.tokens:
322
+ self.problems.add('"=== {}" uses {{{{{}}}}}, which no table '
323
+ 'gives ({})'.format(' '.join(part for part in key if part),
324
+ name, ', '.join(sorted(self.tokens))))
325
+ return match.group(0)
326
+
327
+ return self.tokens[name]
328
+
329
+ return TOKEN.sub(one, text)
330
+
331
+ def target(self):
332
+ return '`{}`'.format(self.branch.get('target') or 'the target branch')
333
+
334
+ def note(self, text):
335
+ """`text`, a number the tables give: prose may not type it."""
336
+
337
+ self.numbers.add(text)
338
+ return text
339
+
340
+
341
+ def objective_row(ctx):
342
+ name = (ctx.branch.get('objective') or {}).get('name')
343
+
344
+ return next((row for row in ctx.performance if row['role'] ==
345
+ 'objective' and row['measure'] == name), None)
346
+
347
+
348
+ def opening(ctx):
349
+ """The summary, the measured change on the main input, and where the
350
+ output checks are."""
351
+
352
+ objective = ctx.branch.get('objective') or {}
353
+ row = objective_row(ctx)
354
+ sentences = [paragraph(ctx.field('summary') or '')]
355
+ main_input = ctx.field('input')
356
+
357
+ if row is None:
358
+ ctx.problems.add('performance.tsv has no row for the objective {}'
359
+ .format(objective.get('name')))
360
+ return ' '.join(sentences)
361
+
362
+ text, _ = change(row, objective.get('direction'))
363
+ runs = int(row['kept_runs'])
364
+ time = is_time(row['measure'], row['unit'])
365
+ what = 'time' if time else '`{}`'.format(row['measure'])
366
+ measured = 'On {}, the median {} of {} runs goes from {} on {} to {} on ' \
367
+ 'this branch{}'.format(main_input or '', what, ctx.note(str(runs)),
368
+ ctx.note(quantity(row['first_median'], row['measure'], row['unit'])),
369
+ ctx.target(), ctx.note(quantity(row['kept_median'], row['measure'],
370
+ row['unit'])), ', ' + ctx.note(text) if time else ' ({})'.format(
371
+ ctx.note(text)))
372
+ paired = (ctx.paired or {}).get('paired') or {}
373
+
374
+ if paired.get('pairs'):
375
+ measured += '; in {} alternating runs of the two, this branch was ' \
376
+ 'faster in {} (sign test, p = {})'.format(ctx.note(str(paired[
377
+ 'pairs'])), ctx.note(str(paired['wins'])), ctx.note(sig(paired[
378
+ 'p'], 2)))
379
+
380
+ sentences.append(measured + '.')
381
+
382
+ if ctx.gates:
383
+ checked_text = 'Its output was checked against the output of {} in ' \
384
+ 'every run'.format(ctx.target())
385
+ elif ctx.checks.get('compare'):
386
+ checked_text = 'Its output was compared with the output of {} on ' \
387
+ 'further inputs'.format(ctx.target())
388
+ else:
389
+ checked_text = 'No check compared its output with the output of {}' \
390
+ .format(ctx.target())
391
+
392
+ sentences.append('{}; see [How the output was checked]{}.'.format(
393
+ checked_text, attribution.CHECKED_LINK))
394
+
395
+ return ' '.join(sentences)
396
+
397
+
398
+ def scope(ctx):
399
+ """What the PR targets and holds, and how it stands to the unit tests."""
400
+
401
+ added = sum(int(row['added']) for row in ctx.files)
402
+ deleted = sum(int(row['deleted']) for row in ctx.files)
403
+ commits = len(ctx.changes)
404
+ lines = ['It targets {}. It is {} commit{} changing {} file{}, +{:,} / '
405
+ '-{:,}.'.format(ctx.target(), ctx.note(str(commits)), attribution.plural(
406
+ commits), ctx.note(str(len(ctx.files))), attribution.plural(len(
407
+ ctx.files)), added, deleted)]
408
+
409
+ if ctx.branch.get('suite'):
410
+ if 'tests' in ctx.documents:
411
+ lines.append('It is independent of the unit tests in {}: it '
412
+ 'changes none of their files, and it was measured with them in '
413
+ 'place.'.format(attribution.PLACEHOLDERS[1]))
414
+ else:
415
+ lines.append('It was measured with a new unit-test suite in place, '
416
+ 'which is not part of this PR; it changes none of that suite\'s '
417
+ 'files.')
418
+
419
+ vendored = ctx.field('vendored')
420
+
421
+ if vendored and vendored.strip().lower().rstrip('.') == 'none':
422
+ lines.append('It adds no code from another project.')
423
+ elif vendored:
424
+ lines.append(paragraph(vendored))
425
+
426
+ return ' '.join(lines)
427
+
428
+
429
+ def performance(ctx):
430
+ direction = (ctx.branch.get('objective') or {}).get('direction')
431
+ rows, worse = [], []
432
+
433
+ for row in ctx.performance:
434
+ label = ctx.field('row', row['measure'])
435
+ text, bad = change(row, direction if row['role'] == 'objective' else
436
+ ('min' if is_time(row['measure'], row['unit']) else None))
437
+
438
+ if bad:
439
+ worse.append(label or row['measure'])
440
+
441
+ rows.append((paragraph(label or row['measure']), ctx.note(quantity(
442
+ row['first_median'], row['measure'], row['unit'])), ctx.note(
443
+ quantity(row['kept_median'], row['measure'], row['unit'])),
444
+ ctx.note(text)))
445
+
446
+ lines = ['## Performance', ''] + publish.table(('Measure', ctx.target(),
447
+ 'This branch', 'Change'), rows, ['---', '---:', '---:', '---:'])
448
+ counts = {(int(row['first_runs']), int(row['kept_runs'])) for row in
449
+ ctx.performance}
450
+
451
+ if len(counts) == 1:
452
+ first, kept = counts.pop()
453
+ lines += ['', 'Each value is the median of {} run{}{}.'.format(
454
+ ctx.note(str(kept)), attribution.plural(kept), '' if first == kept
455
+ else ' of this branch and {} of {}'.format(ctx.note(str(first)),
456
+ ctx.target()))]
457
+
458
+ outliers = ctx.field('outliers', required=bool(worse))
459
+
460
+ if worse and outliers:
461
+ lines += ['', paragraph(outliers)]
462
+ elif outliers:
463
+ lines += ['', paragraph(outliers)]
464
+
465
+ cold = ctx.checks.get('cold') or {}
466
+
467
+ if cold.get('kept') is not None:
468
+ sentence = 'The first call in a new process took {} on this branch'\
469
+ .format(ctx.note(seconds(cold['kept'])))
470
+
471
+ if cold.get('first') is not None:
472
+ sentence += ' and {} on {}'.format(ctx.note(seconds(cold['first'])),
473
+ ctx.target())
474
+
475
+ slower = cold.get('first') is not None and cold['kept'] > 2 * cold[
476
+ 'first']
477
+ why = ctx.field('cold', required=slower)
478
+ lines += ['', sentence + '.' + (' ' + paragraph(why) if why else '')]
479
+
480
+ lines += [''] + details('How it was measured', measured(ctx))
481
+
482
+ return lines
483
+
484
+
485
+ def measured(ctx):
486
+ lines = []
487
+ machine = ctx.machine
488
+
489
+ if machine:
490
+ parts = [machine.get('distribution') or ' '.join(part for part in (
491
+ machine.get('os'), machine.get('release')) if part)]
492
+ parts += [machine.get('arch'), machine.get('cpu')]
493
+ cores = machine.get('cores')
494
+ text = ', '.join(part for part in parts if part)
495
+
496
+ if cores:
497
+ text += ', {} cores'.format(cores)
498
+
499
+ if machine.get('python'):
500
+ text += '; Python {}'.format(machine['python'])
501
+
502
+ lines.append('- **Machine:** {}.'.format(text))
503
+ else:
504
+ lines.append('- **Machine:** {}'.format(paragraph(ctx.field('machine')
505
+ or '')))
506
+
507
+ lines.append('- **What a run measures:** {}'.format(paragraph(ctx.field(
508
+ 'timed') or '')))
509
+ lines.append('- **Runs:** each build ran with a different seed in each '
510
+ 'run, in its own process; the table above gives the medians, and this '
511
+ 'one the range of each:')
512
+ lines.append('')
513
+ lines += [' ' + line for line in publish.table(('Measure',
514
+ '{}, min to max'.format(ctx.target()), 'This branch, min to max'), [(
515
+ paragraph(ctx.prose.get(('row', row['measure']), row['measure'])),
516
+ '{} to {}'.format(quantity(row['first_min'], row['measure'],
517
+ row['unit']), quantity(row['first_max'], row['measure'], row['unit'])),
518
+ '{} to {}'.format(quantity(row['kept_min'], row['measure'], row[
519
+ 'unit']), quantity(row['kept_max'], row['measure'], row['unit']))) for
520
+ row in ctx.performance], ['---', '---:', '---:'])]
521
+ paired = ctx.paired or {}
522
+
523
+ for key, where in (('paired', ''), ('threads', ' at {} threads')):
524
+ entry = paired.get(key) or {}
525
+
526
+ if not entry.get('pairs'):
527
+ continue
528
+
529
+ lines.append('')
530
+ lines.append('- **Paired runs{}:** the two builds ran one after the '
531
+ 'other in {} pairs of separate processes, on the same input; this '
532
+ 'branch was faster in {} of them (sign test, p = {}).'.format(
533
+ where.format(entry.get('threads')), entry['pairs'], entry['wins'],
534
+ sig(entry['p'], 2)))
535
+
536
+ return lines
537
+
538
+
539
+ def entries(ctx):
540
+ """`[(first position, name, iterations, files, text)]` from the `change`
541
+ fields, checked against the kept changes: each in one entry, every file
542
+ the PR changes named by some entry."""
543
+
544
+ steps = [str(step) for step in ctx.branch.get('steps') or []]
545
+ labels = dict(zip(ctx.branch.get('step_labels') or [], steps))
546
+ order = {step: at for at, step in enumerate(steps)}
547
+ own = {row['id']: [path for path in row['files'].split(',') if path] for
548
+ row in ctx.changes}
549
+ final = [row['path'] for row in ctx.files]
550
+ made, covered = [], {}
551
+
552
+ for key in [key for key in ctx.prose if key[0] == 'change']:
553
+ ctx.used.add(key)
554
+ name = key[1]
555
+ head, _, rest = ctx.prose[key].partition('\n')
556
+ match = re.match(r'^iterations:\s*(.+)$', head.strip())
557
+ where = '"=== change {}"'.format(name)
558
+
559
+ if '<' in name:
560
+ ctx.problems.add('{} still holds a placeholder name'.format(where))
561
+
562
+ if not match or not rest.strip():
563
+ ctx.problems.add('{} needs a first line `iterations: A4, A11` and '
564
+ 'then what the change does'.format(where))
565
+ continue
566
+
567
+ named = [part.strip() for part in re.split(r'[,\s]+', match.group(1))
568
+ if part.strip()]
569
+ unknown = [one for one in named if one not in labels]
570
+
571
+ if unknown:
572
+ ctx.problems.add('{} names {}, which is not a kept change ({})'
573
+ .format(where, ', '.join(unknown), ', '.join(labels)))
574
+
575
+ for one in named:
576
+ if one in covered:
577
+ ctx.problems.add('{} covers {} again; {} has it already'
578
+ .format(where, one, covered[one]))
579
+
580
+ covered[one] = where
581
+
582
+ ids = [labels[one] for one in named if one in labels]
583
+ files = [path for path in final if any(path in own.get(i, []) for i in
584
+ ids)]
585
+
586
+ if ids and not files:
587
+ ctx.problems.add('{} covers no file the PR changes: a change later '
588
+ 'undone belongs in the entry that undid it'.format(where))
589
+
590
+ if ids:
591
+ made.append((min(order[i] for i in ids), name, sorted(order[i] + 1
592
+ for i in ids), files, rest.strip('\n')))
593
+
594
+ missing = [one for one in labels if one not in covered]
595
+
596
+ if missing:
597
+ ctx.problems.add('no "=== change" field covers {}; every kept change is '
598
+ 'in one entry'.format(', '.join(missing)))
599
+
600
+ unnamed = [path for path in final if not any(path in entry[3] for entry in
601
+ made)]
602
+
603
+ if unnamed and made:
604
+ ctx.problems.add('no change entry names {}: say which entry changed '
605
+ 'it'.format(', '.join(unnamed)))
606
+
607
+ return sorted(made)
608
+
609
+
610
+ def changes(ctx):
611
+ lines = ['## Changes', '', 'In the order they were made, each with its '
612
+ 'commits. Open a change for its files and what it does.', '']
613
+
614
+ for number, (_, name, commits, files, text) in enumerate(entries(ctx), 1):
615
+ first, _, rest = text.partition('\n')
616
+ where = ' (commit{} {})'.format('' if len(commits) == 1 else 's',
617
+ ', '.join('{{{{commit:{}}}}}'.format(at) for at in commits))
618
+ body = ['Files: {}.'.format(', '.join('`{}`'.format(path) for path in
619
+ files)), '', ctx.fill(first.strip(), ('change', name))]
620
+
621
+ for line in rest.split('\n'):
622
+ if line.strip():
623
+ body.append(ctx.fill(line.strip() if LIST_ITEM.match(line) and
624
+ not line.startswith(' ') else line.rstrip(), ('change',
625
+ name)))
626
+
627
+ lines.append('{}. **{}**{}'.format(number, name, where))
628
+ lines.append('')
629
+ lines += [' ' + line if line else '' for line in details('Details',
630
+ body)]
631
+ lines.append('')
632
+
633
+ return lines[:-1]
634
+
635
+
636
+ def behaviour(ctx):
637
+ return ['## Behaviour changes', '', ctx.field('behaviour') or '']
638
+
639
+
640
+ def tests(ctx):
641
+ lines = ['## Tests', '']
642
+ record = ctx.tests
643
+
644
+ if not record:
645
+ why = ctx.field('tests', required=False)
646
+ return lines + ['No unit tests ran on this branch.' + (' ' + paragraph(
647
+ why) if why else '')]
648
+
649
+ if not record.get('pass'):
650
+ ctx.problems.add('tests.json: the unit tests did not pass on the kept '
651
+ 'code')
652
+
653
+ counts = record.get('counts')
654
+ sentence = '{} passed on this branch'.format(paragraph(ctx.field('tests')
655
+ or '').rstrip('.'))
656
+
657
+ if counts:
658
+ failed = counts['failed'] + counts.get('errors', 0)
659
+ sentence += ': {} test{} passed, {} {} skipped and {} failed'.format(
660
+ ctx.note('{:,}'.format(counts['passed'])), attribution.plural(
661
+ counts['passed']), ctx.note('{:,}'.format(counts['skipped'])),
662
+ 'was' if counts['skipped'] == 1 else 'were', '{:,}'.format(failed))
663
+
664
+ sentence += '.'
665
+
666
+ if ctx.branch.get('suite'):
667
+ sentence += ' The run included the new unit tests{}.'.format(' of ' +
668
+ attribution.PLACEHOLDERS[1] if 'tests' in ctx.documents else
669
+ ', which are not part of this PR')
670
+
671
+ return lines + [sentence]
672
+
673
+
674
+ def checked(ctx):
675
+ lines = [attribution.CHECKED_HEADING, '']
676
+ items = []
677
+ runs = {int(row['runs']) for row in ctx.gates if row['runs'].isdigit()}
678
+
679
+ for row in ctx.gates:
680
+ what = ctx.field('gate', row['name'])
681
+ condition = '`{} {} {}`'.format(row['name'], row['op'],
682
+ row['threshold'])
683
+ worst = row['worst']
684
+
685
+ try:
686
+ worst = '{:.4g}'.format(float(worst))
687
+ except ValueError:
688
+ pass
689
+
690
+ items.append('- {}, {}: it held in every run; the worst value was {}.'
691
+ .format(condition, (what or '').rstrip('.'), worst))
692
+
693
+ compare = ctx.checks.get('compare') or {}
694
+
695
+ if compare:
696
+ if compare.get('verdict') != 'pass':
697
+ ctx.problems.add('checks.json: the output comparison of the kept '
698
+ 'code did not pass ({})'.format(compare.get('verdict')))
699
+
700
+ inputs = ctx.field('compare')
701
+ items.append('- A separate comparison of the two builds, on {}, '
702
+ 'reported "{}".'.format((inputs or '').rstrip('.'), compare.get(
703
+ 'summary') or 'pass'))
704
+
705
+ if ctx.tests and ctx.tests.get('pass'):
706
+ items.append('- The unit tests, under [Tests](#tests).')
707
+
708
+ if ctx.gates:
709
+ lines.append('Each of this branch\'s {} run{} compared its output with '
710
+ 'the output of {}:'.format(ctx.note(str(min(runs))) if runs else
711
+ 'measured', attribution.plural(min(runs)) if runs else 's',
712
+ ctx.target()))
713
+ elif items:
714
+ lines.append('The output was compared with the output of {}:'.format(
715
+ ctx.target()))
716
+ else:
717
+ lines.append('No check compared the output with the output of {}.'
718
+ .format(ctx.target()))
719
+
720
+ if items:
721
+ lines += [''] + items
722
+
723
+ if 'bugs' in ctx.documents:
724
+ lines += ['', 'Bugs found in {} along the way are reported in {}.'
725
+ .format(ctx.target(), attribution.PLACEHOLDERS[0])]
726
+
727
+ return lines
728
+
729
+
730
+ def typed_numbers(ctx):
731
+ """A number of three or more digits the tables give, typed in prose."""
732
+
733
+ numbers = {number for number in ctx.numbers if sum(c.isdigit() for c in
734
+ number) >= 3}
735
+
736
+ for key, text in ctx.prose.items():
737
+ if key[0] in ('change',):
738
+ text = text.partition('\n')[2]
739
+
740
+ for number in sorted(numbers):
741
+ core = re.sub(r'[^0-9.,]', '', number).strip('.,')
742
+
743
+ if core and re.search(r'(?<![0-9.,]){}(?![0-9])'.format(re.escape(
744
+ core)), text):
745
+ ctx.problems.add('"=== {}" types {}, which the tables give: '
746
+ 'write the token instead, or leave it to the table'.format(
747
+ ' '.join(part for part in key if part), core))
748
+
749
+
750
+ def render(ctx):
751
+ ctx.tokens = {'target': ctx.target(), 'commits': str(len(ctx.changes)),
752
+ 'files': str(len(ctx.files))}
753
+ row = objective_row(ctx)
754
+
755
+ if row is not None:
756
+ ctx.tokens.update(first=quantity(row['first_median'], row['measure'],
757
+ row['unit']), kept=quantity(row['kept_median'], row['measure'],
758
+ row['unit']), speedup=change(row, (ctx.branch.get('objective') or
759
+ {}).get('direction'))[0], runs=str(int(row['kept_runs'])))
760
+ parts = [opening(ctx), paragraph(ctx.field('portability') or ''),
761
+ scope(ctx), '\n'.join(performance(ctx)), '\n'.join(changes(ctx)),
762
+ '\n'.join(behaviour(ctx)), '\n'.join(tests(ctx)), '\n'.join(checked(
763
+ ctx))]
764
+ typed_numbers(ctx)
765
+ text = '\n\n'.join(part for part in parts if part) + '\n'
766
+ problems = Problems()
767
+ text = publish.fill_numbers(text, ctx.directory, problems)
768
+
769
+ for problem in problems:
770
+ ctx.problems.add(problem)
771
+
772
+ for problem in attribution.opening_problems('optimization', text):
773
+ ctx.problems.add('body: ' + problem)
774
+
775
+ if 'tests' not in ctx.documents and attribution.PLACEHOLDERS[1] in text:
776
+ ctx.problems.add('the body names the unit-test PR, which was not chosen')
777
+
778
+ if 'bugs' not in ctx.documents and attribution.PLACEHOLDERS[0] in text:
779
+ ctx.problems.add('the body names the bug report, which was not chosen')
780
+
781
+ return text
782
+
783
+
784
+ def template(ctx):
785
+ """The prose skeleton: every field the tables call for, each change
786
+ entry started from what the kept change's own notes say."""
787
+
788
+ fragments = read_json(ctx.directory, 'fragments.json', Problems(),
789
+ required=False) or {}
790
+ steps = ctx.branch.get('steps') or []
791
+ labels = ctx.branch.get('step_labels') or []
792
+ out = []
793
+
794
+ def put(key, text):
795
+ out.append('=== ' + ' '.join(part for part in key if part))
796
+ out.append(text)
797
+ out.append('')
798
+
799
+ def fill(name):
800
+ return '<<FILL: {}>>'.format(FIELDS[name][1])
801
+
802
+ for name in ('summary', 'input'):
803
+ put((name,), fill(name))
804
+
805
+ for row in ctx.performance:
806
+ put(('row', row['measure']), fill('row'))
807
+
808
+ put(('timed',), fill('timed'))
809
+
810
+ if not ctx.machine:
811
+ put(('machine',), fill('machine'))
812
+
813
+ direction = (ctx.branch.get('objective') or {}).get('direction')
814
+
815
+ if any(change(row, direction if row['role'] == 'objective' else ('min' if
816
+ is_time(row['measure'], row['unit']) else None))[1] for row in
817
+ ctx.performance):
818
+ put(('outliers',), fill('outliers'))
819
+
820
+ cold = ctx.checks.get('cold') or {}
821
+
822
+ if cold.get('kept') is not None and cold.get('first') is not None and \
823
+ cold['kept'] > 2 * cold['first']:
824
+ put(('cold',), fill('cold'))
825
+
826
+ for name in ('portability', 'vendored'):
827
+ put((name,), fill(name))
828
+
829
+ for step, label in zip(steps, labels):
830
+ fragment = fragments.get(str(step)) or {}
831
+ name = fragment.get('name') or '<short name for {}>'.format(label)
832
+ put(('change', name), 'iterations: {}\n{}'.format(label, fragment.get(
833
+ 'change') or fill('change')))
834
+
835
+ put(('behaviour',), fill('behaviour'))
836
+
837
+ if ctx.tests:
838
+ put(('tests',), fill('tests'))
839
+
840
+ for row in ctx.gates:
841
+ put(('gate', row['name']), fill('gate'))
842
+
843
+ if ctx.checks.get('compare'):
844
+ put(('compare',), fill('compare'))
845
+
846
+ return '\n'.join(out)
847
+
848
+
849
+ def main(argv=None):
850
+ parser = argparse.ArgumentParser(description=__doc__,
851
+ formatter_class=argparse.RawDescriptionHelpFormatter)
852
+ parser.add_argument('directory')
853
+ parser.add_argument('--title', help='the PR\'s title: an imperative, a '
854
+ 'capital letter, no closing period, at most 72 characters')
855
+ parser.add_argument('--out', help='write the body here and the title '
856
+ 'beside it; without it the body goes to stdout')
857
+ parser.add_argument('--template', action='store_true', help='print the '
858
+ 'prose skeleton')
859
+ args = parser.parse_args(argv)
860
+ directory = os.path.abspath(os.path.expanduser(args.directory))
861
+
862
+ if args.template:
863
+ ctx = Context.__new__(Context)
864
+ ctx.directory = directory
865
+ problems = Problems()
866
+ ctx.branch = read_json(directory, 'branch.json', problems) or {}
867
+ ctx.performance = read_table(directory, 'performance.tsv', problems)
868
+ ctx.gates = read_table(directory, 'gates.tsv', problems)
869
+ ctx.checks = read_json(directory, 'checks.json', problems) or {}
870
+ ctx.machine = read_json(directory, 'machine.json', problems)
871
+ ctx.tests = read_json(directory, 'tests.json', problems)
872
+
873
+ for row in ctx.performance:
874
+ for key in ('first_median', 'first_min', 'first_max', 'kept_median',
875
+ 'kept_min', 'kept_max'):
876
+ row[key] = float(row[key])
877
+
878
+ if problems:
879
+ return publish.refuse('opt_pr_body', problems)
880
+
881
+ sys.stdout.write(template(ctx))
882
+ return 0
883
+
884
+ ctx = Context(directory)
885
+ text = render(ctx) if not ctx.problems or ctx.branch else ''
886
+ unused = [' '.join(part for part in key if part) for key in ctx.prose if
887
+ key not in ctx.used]
888
+
889
+ return publish.emit('opt_pr_body', text, ctx.problems, args.title,
890
+ args.out, unused=unused, labels=ctx.branch.get('labels'))
891
+
892
+
893
+ if __name__ == '__main__':
894
+ sys.exit(main())