Coverage for packages/workshop/src/livery/workshop/_balance.py: 97%

Measured by coverage.py 7.16.2 on CPython 3.14 while the suites of tests, packages/workshop/tests/test_workshop_proved_trees.py, packages/workshop/tests/test_workshop_c7_shards.py, packages/workshop/tests/test_workshop_balance.py ran.

1"""Predict each check platform's wall at one to several shards, and propose the counts.
2
3The reader behind ``fm ci.balance``. It reads the timing rows the
4gate job writes ([livery.workshop._metrics][]) per platform: the os
5and Python of a check job's display name, ``check (macos-latest,
63.14)``; ``check (macos-latest, 3.14, 2of4)`` is one shard of that
7platform, and a GitLab job's bare name reads its platform from the
8row's own leg label. Per platform it takes the newest ten rows whose
9jobs for it all ran the full gate and succeeded, folds the shards of
10one platform into one, and takes the medians of four measures:
11
12- F, the fixed setup: every step the forge timed except the ``Check``
13 call, from the first shard, in seconds.
14- O, the summed wall of the gate's steps that are not test steps,
15 from the first shard. The gate's steps are the job's
16 ``check/<phase>.<step>`` tasks, and the test steps are the test
17 phase's, [livery.workshop._metrics.TEST_PHASE][].
18- S, the summed test time over every package and every shard.
19- p, the measured parallelism: a shard's S over its test steps' wall,
20 the median over shards.
21
22The wall at n shards is predicted as F + max(O, (S / p + O) / n). The
23first shard runs the unsplit steps, and its tests wait about their
24summed wall, so the partition starts the first shard's slice O p item
25seconds in ([livery.workshop._metrics.first_shard_head][]): the S + O p
26item seconds split evenly over the n shards, and no count brings a
27platform under F + O, the first shard with no tests left. The runner
28seconds at n are about n F + S / p + O. The slowest platform, the one
29with the largest wall at one shard, takes the largest count within
30the cap whose every added shard saved at least F, so a shard that
31costs more setup than it saves is not proposed. Every other platform
32takes the smallest count whose wall is within
33[livery.workshop._balance.TOLERANCE][] of the slowest
34platform's at its count; one that cannot get there at the cap takes
35the cap and is named. The pull request counts apply the same rule
36over a pull request's runners when they are fewer than ``[ci]
37runners`` names. A platform with fewer than
38[livery.workshop._balance.ROWS_NEEDED][] readable rows keeps its count
39and takes no part. The cap is ``[ci] shards-max``, which the verb
40reads and never writes.
41
42The verb prints the table and the TOML the contract would hold. With
43``--write`` it rewrites ``[ci] shards``, and ``[ci]
44pull-request-shards`` when the pull request runners are fewer, in the
45root ``workshop.toml``, keeping every comment and every other key:
46when a count differs from the contract's and the predicted wall at
47the proposed counts differs from the wall at the contract's by more
48than [livery.workshop._balance.HYSTERESIS][], so a count does not move
49back and forth between two readings that predict about the same
50wall. With ``--submit`` the change lands on the day's branch,
51``chore/balance-<date>``, rendered, committed and submitted unarmed
52for a person to merge; the nightly runs that once a day. The
53constants here were chosen before the rows could set them, as the
54speed marks' margins were ([livery.workshop._speed][]).
55
56Reach for `render` for what the verb prints, `read` for the same with
57the counts a write judges, `judge` for the write's decision, `write`
58and `submit` for the two acts, `readings` for the measures from rows
59already in hand, `wall` and `runner_seconds` for the prediction, and
60`propose` for the counts.
61"""
62
63from __future__ import annotations(empty)
64
65import re(empty)
66import statistics(empty)
67import tomllib(empty)
68from collections import defaultdict(empty)
69from collections.abc import Mapping, Sequence(empty)
70from dataclasses import dataclass(empty)
71from datetime import date(empty)
72from operator import itemgetter(empty)
73from pathlib import Path(empty)
74from typing import Any(empty)
75
76from livery import git(empty)
77from livery.footman import fail(empty)
78from livery.workshop._ci_context import state_store(empty)
79from livery.workshop._contract import load_contract(empty)
80from livery.workshop._metrics import SERIES, TEST_PHASE, gate_steps, tests_ms(empty)
81from livery.workshop._points import pull_request_runners, shard_counts, shards_max(empty)
82
83#: The step the forge times for the gate's own call. Every other step
84#: the forge times is the job's setup and teardown, F.
85CALL_STEP = "Check"(empty)
86
87#: The newest full green rows read per platform.
88ROWS_READ = 10(empty)
89
90#: A platform with fewer readable rows than this keeps its count: a
91#: median of two says little. Chosen before the rows could set it.
92ROWS_NEEDED = 3(empty)
93
94#: Another platform's wall within this fraction of the slowest
95#: platform's counts as level with it. Chosen before the rows could
96#: set it; a reading of a month of rows may move it.
97TOLERANCE = 0.15(empty)
98
99#: The write happens only when the predicted wall at the proposed
100#: counts differs from the wall at the contract's counts by more than
101#: this fraction of the latter, so two readings that predict about the
102#: same wall do not move a count back and forth. Chosen before the rows
103#: could set it.
104HYSTERESIS = 0.10(empty)
105
106#: The comment written above a key the balancer adds to the contract.
107COMMENTS = {(empty)
108 "shards": (
109 "# The shards each runner's check leg runs as; fm ci.balance --write sets them."
110 ),
111 "pull-request-shards": (
112 "# The shards a pull request's check legs run as; fm ci.balance --write"
113 " sets them."
114 ),
115}
116
117_DISPLAY = re.compile((empty)
118 r"^check \((?P<os>[^,()]+), (?P<version>[^,()]+)(?:, (?P<shard>\d+)of\d+)?\)$"
119)
120_LABEL = re.compile((empty)
121 r"^check-(?P<os>.+?)-(?P<version>\d+(?:\.\d+)*)(?:-(?P<shard>\d+)of\d+)?$"
122)
123
124
125@dataclass(frozen=True)(empty)
126class Reading:(empty)
127 """One platform's measures, medians over its readable rows.
128
129 Attributes:
130 os: The runner label (``macos-latest``).
131 python: The leg's Python (``3.14``).
132 seen: The full green rows the platform had among the newest
133 [livery.workshop._balance.ROWS_READ][] read.
134 rows: Those among them that carry the test steps' wall in
135 every shard; the medians are over these.
136 fixed: F, the setup and teardown the forge timed around the
137 call, in seconds.
138 other: O, the summed wall of the gate steps that are not test
139 steps, in seconds; zero when the rows name none.
140 tests: S, the summed test time over every package and shard,
141 in seconds.
142 speed: p, the measured parallelism: a shard's S over its test
143 steps' wall, the median over shards.
144 """
145
146 os: str(empty)
147 python: str(empty)
148 seen: int(empty)
149 rows: int(empty)
150 fixed: float(empty)
151 other: float(empty)
152 tests: float(empty)
153 speed: float(empty)
154
155 @property(empty)
156 def platform(self) -> str:(empty)
157 """The platform as the table names it: ``macos-latest, 3.14``."""
158 return f"{self.os}, {self.python}"
159
160 @property(empty)
161 def enough(self) -> bool:(empty)
162 """Whether the platform has the rows a proposal needs."""
163 return self.rows >= ROWS_NEEDED
164
165
166@dataclass(frozen=True)(empty)
167class Proposal:(empty)
168 """The counts a set of readings proposes.
169
170 Attributes:
171 counts: The count per runner label, one entry per runner with
172 enough rows; a runner with two Pythons takes the larger.
173 slowest: The slowest platform, as the table names it; empty
174 when no platform had enough rows.
175 wall: The slowest platform's predicted wall at its count, in
176 seconds.
177 unsharded: Its predicted wall at one shard.
178 capped: The platforms that took the cap without reaching the
179 tolerance, as the table names them.
180 """
181
182 counts: dict[str, int](empty)
183 slowest: str = ""(empty)
184 wall: float = 0.0(empty)
185 unsharded: float = 0.0(empty)
186 capped: tuple[str, ...] = ()(empty)
187
188
189def wall(reading: Reading, shards: int) -> float:(empty)
190 """The leg's predicted wall at *shards*, in seconds: F + max(O, (S / p + O) / n)."""
191 spread = (reading.tests / reading.speed + reading.other) / shards
192 return reading.fixed + max(reading.other, spread)
193
194
195def runner_seconds(reading: Reading, shards: int) -> float:(empty)
196 """About what *shards* runners spend together, in seconds: n F + S / p + O."""
197 return shards * reading.fixed + reading.tests / reading.speed + reading.other
198
199
200def _unsharded(reading: Reading) -> float:(empty)
201 return wall(reading, 1)
202
203
204def propose(readings: Sequence[Reading], *, cap: int) -> Proposal:(empty)
205 """The counts for *readings* within *cap*; a platform short of rows takes no part.
206
207 The slowest platform's count stops at the first added shard that
208 saves less than its setup. Every other platform takes the smallest
209 count within the tolerance of the slowest platform's wall, or the
210 cap, named in ``capped``.
211 """
212 cap = max(1, cap)
213 able = [reading for reading in readings if reading.enough]
214 if not able:
215 return Proposal({})
216 slowest = max(able, key=_unsharded)
217 count = 1
218 while (
219 count < cap and wall(slowest, count) - wall(slowest, count + 1) >= slowest.fixed
220 ):
221 count += 1
222 target = wall(slowest, count) * (1 + TOLERANCE)
223 counts: dict[str, int] = {}
224 capped: list[str] = []
225 for reading in able:
226 if reading is slowest:
227 chosen = count
228 else:
229 chosen = next(
230 (n for n in range(1, cap + 1) if wall(reading, n) <= target), cap
231 )
232 if wall(reading, chosen) > target:
233 capped.append(reading.platform)
234 counts[reading.os] = max(counts.get(reading.os, 0), chosen)
235 return Proposal(
236 counts, slowest.platform, wall(slowest, count), wall(slowest, 1), tuple(capped)
237 )
238
239
240def _number(value: Any) -> float | None:(empty)
241 if isinstance(value, bool) or not isinstance(value, int | float):
242 return None
243 return float(value)
244
245
246def _platform(name: str, job: Mapping[str, Any]) -> tuple[str, str, int] | None:(empty)
247 """The os, Python and shard index of a check job; None for another job.
248
249 The display name first (``check (ubuntu-latest, 3.14, 2of4)``),
250 then the leg label the job's row carries under ``scope.leg``,
251 which is how a GitLab job, displayed as the bare ``check``, names
252 its runner. An unsharded job is shard 1.
253 """
254 match = _DISPLAY.match(name)
255 if match is None:
256 scope = job.get("scope")
257 leg = str(scope.get("leg") or "") if isinstance(scope, Mapping) else ""
258 match = _LABEL.match(leg)
259 if match is None:
260 return None
261 return match["os"], match["version"], int(match["shard"] or 1)
262
263
264def _full_green(job: Mapping[str, Any]) -> bool:(empty)
265 scope = job.get("scope")
266 return (
267 job.get("conclusion") == "success"
268 and isinstance(scope, Mapping)
269 and scope.get("scope") == "full"
270 and not scope.get("narrowed")
271 )
272
273
274def _fixed_ms(job: Mapping[str, Any]) -> float:(empty)
275 """The forge's steps of *job* except the call, summed; an untimed step is 0."""
276 total = 0.0
277 for step in job.get("steps") or []:
278 if isinstance(step, Mapping) and step.get("name") != CALL_STEP:
279 total += _number(step.get("ms")) or 0.0
280 return total
281
282
283@dataclass(frozen=True)(empty)
284class _Measures:(empty)
285 fixed: float(empty)
286 other: float(empty)
287 tests: float(empty)
288 speed: float(empty)
289
290
291def _measure(shards: Sequence[Mapping[str, Any]]) -> _Measures | None:(empty)
292 """One row's measures for a platform from its shards' jobs, the first shard first.
293
294 None when a shard carries no test step's wall or no test time: p
295 cannot be read from it. A shard's test wall is its test steps'
296 summed.
297 """
298 speeds: list[float] = []
299 total = 0.0
300 for job in shards:
301 steps = gate_steps(job)
302 test_ms = sum(ms for key, ms in steps.items() if key.startswith(TEST_PHASE))
303 tests = tests_ms(job.get("packages"))
304 if test_ms <= 0 or tests <= 0:
305 return None
306 speeds.append(tests / test_ms)
307 total += tests
308 steps = gate_steps(shards[0])
309 other = sum(ms for key, ms in steps.items() if not key.startswith(TEST_PHASE))
310 return _Measures(
311 _fixed_ms(shards[0]) / 1000.0,
312 other / 1000.0,
313 total / 1000.0,
314 statistics.median(speeds),
315 )
316
317
318def _measure_folded(job: Mapping[str, Any]) -> _Measures | None:(empty)
319 """One row's measures from a folded sharded leg.
320
321 ``ci.fold`` keeps the first shard's ``task_steps`` and ``steps`` on
322 the folded entry, sums ``packages`` across every shard, and lists
323 each shard's own ``packages`` under ``shard.shards``. The total test
324 time comes from the folded ``packages``; ``p`` comes from the first
325 shard's own ``packages`` over its test step wall so the ratio stays
326 on one shard's scale.
327 """
328 shard_meta = job.get("shard")
329 if not isinstance(shard_meta, Mapping):
330 return None
331 sub_shards = shard_meta.get("shards")
332 if not isinstance(sub_shards, list | tuple) or not sub_shards:
333 return None
334 first_sub = sub_shards[0]
335 if not isinstance(first_sub, Mapping):
336 return None
337 steps = gate_steps(job)
338 test_ms = sum(ms for key, ms in steps.items() if key.startswith(TEST_PHASE))
339 total = tests_ms(job.get("packages"))
340 first_tests = tests_ms(first_sub.get("packages"))
341 if test_ms <= 0 or total <= 0 or first_tests <= 0:
342 return None
343 other = sum(ms for key, ms in steps.items() if not key.startswith(TEST_PHASE))
344 return _Measures(
345 _fixed_ms(job) / 1000.0,
346 other / 1000.0,
347 total / 1000.0,
348 first_tests / test_ms,
349 )
350
351
352def readings(rows: Sequence[Mapping[str, Any]]) -> list[Reading]:(empty)
353 """Each platform's reading from *rows*, newest first; the platforms in name order.
354
355 A row counts for a platform when every job of that platform in it
356 ran the full gate and succeeded, and the newest
357 [livery.workshop._balance.ROWS_READ][] such rows are read. Among
358 them, a row whose shard carries no test step's wall is seen and
359 not read. A job that is not a check leg is skipped.
360 """
361 seen: dict[tuple[str, str], int] = defaultdict(int)
362 measures: dict[tuple[str, str], list[_Measures]] = defaultdict(list)
363 for row in rows:
364 jobs = row.get("jobs")
365 if not isinstance(jobs, Mapping):365 ↛ 366line 365 didn't jump to line 366 because the condition on line 365 was never true
366 continue
367 by_platform: dict[tuple[str, str], list[tuple[int, Mapping[str, Any]]]] = (
368 defaultdict(list)
369 )
370 for name, job in jobs.items():
371 if not isinstance(job, Mapping):371 ↛ 372line 371 didn't jump to line 372 because the condition on line 371 was never true
372 continue
373 found = _platform(str(name), job)
374 if found is not None:
375 by_platform[found[:2]].append((found[2], job))
376 for key, shards in by_platform.items():
377 if seen[key] >= ROWS_READ:
378 continue
379 folded = [job for _, job in shards if isinstance(job.get("shard"), Mapping)]
380 if folded:
381 row_job = folded[0]
382 raw_shards = [
383 job
384 for _, job in shards
385 if not isinstance(job.get("shard"), Mapping)
386 ]
387 if not _full_green(row_job) or any(
388 job.get("conclusion") != "success" for job in raw_shards
389 ):
390 continue
391 seen[key] += 1
392 measured = _measure_folded(row_job)
393 if measured is not None:
394 measures[key].append(measured)
395 continue
396 shards.sort(key=itemgetter(0))
397 if not all(_full_green(job) for _, job in shards):
398 continue
399 seen[key] += 1
400 measured = _measure([job for _, job in shards])
401 if measured is not None:
402 measures[key].append(measured)
403 out: list[Reading] = []
404 for key in sorted(seen):
405 taken = measures.get(key, [])
406 out.append(
407 Reading(
408 key[0],
409 key[1],
410 seen[key],
411 len(taken),
412 fixed=statistics.median([m.fixed for m in taken]) if taken else 0.0,
413 other=statistics.median([m.other for m in taken]) if taken else 0.0,
414 tests=statistics.median([m.tests for m in taken]) if taken else 0.0,
415 speed=statistics.median([m.speed for m in taken]) if taken else 0.0,
416 )
417 )
418 return out
419
420
421def _platform_lines(reading: Reading, cap: int) -> list[str]:(empty)
422 """The table of one platform, or the line saying why it keeps its count."""
423 if not reading.enough:
424 if reading.rows < reading.seen:
425 return [
426 f" {reading.platform}: keeps its count: {reading.seen} full green"
427 f" row(s), {reading.rows} with the test steps' wall ({TEST_PHASE}*),"
428 f" {ROWS_NEEDED} needed"
429 ]
430 return [
431 f" {reading.platform}: keeps its count: {reading.seen} full green"
432 f" row(s), {ROWS_NEEDED} needed"
433 ]
434 lines = [
435 f" {reading.platform}: {reading.rows} row(s): F {reading.fixed:.0f} s,"
436 f" O {reading.other:.0f} s, S {reading.tests:.0f} s, p {reading.speed:.1f}",
437 f" {'shards':>6} {'wall':>8} {'runner s':>10}",
438 ]
439 lines.extend(
440 f" {n:>6} {wall(reading, n):>6.0f} s {runner_seconds(reading, n):>8.0f} s"
441 for n in range(1, cap + 1)
442 )
443 return lines
444
445
446def _toml_line((empty)
447 key: str,
448 proposal: Proposal,
449 runners: Sequence[str],
450 current: Mapping[str, int] | None = None,
451) -> str:
452 """The TOML the contract would hold for *key*, or why there is none."""
453 if not proposal.counts:
454 return (
455 f" nothing proposed: no platform has {ROWS_NEEDED} full green rows"
456 " with the test steps' wall"
457 )
458 merged = (
459 {
460 runner: proposal.counts.get(runner, current.get(runner, 1))
461 for runner in runners
462 }
463 if current is not None
464 else proposal.counts
465 )
466 sharded = _ordered(merged, runners)
467 if not sharded:
468 return f" [ci] {key}: none, every platform runs as one shard"
469 return f" [ci] {key} = {spell(sharded)}"
470
471
472def _ordered(counts: Mapping[str, int], runners: Sequence[str]) -> dict[str, int]:(empty)
473 """The counts above one, in the order of *runners*, as the contract holds them."""
474 return {runner: counts[runner] for runner in runners if counts.get(runner, 1) > 1}
475
476
477def spell(table: Mapping[str, int]) -> str:(empty)
478 """*table* as the contract spells an inline table; ``none`` when empty."""
479 if not table:
480 return "none"
481 return "{ " + ", ".join(f'"{runner}" = {n}' for runner, n in table.items()) + " }"
482
483
484def _wall_line(what: str, proposal: Proposal) -> list[str]:(empty)
485 if not proposal.counts:
486 return []
487 return [
488 f" predicted {what} wall: {proposal.wall:.0f} s for the slowest leg,"
489 f" from {proposal.unsharded:.0f} s"
490 ]
491
492
493def report((empty)
494 readings: Sequence[Reading],
495 *,
496 cap: int,
497 runners: Sequence[str],
498 pull_request_runners: Sequence[str] | None = None,
499 current: Mapping[str, int] | None = None,
500 pull_request_current: Mapping[str, int] | None = None,
501) -> list[str]:
502 """The lines the verb prints below the window line: the tables, then the proposal.
503
504 Every reading gets its table or its reason; a runner in *runners*
505 without a reading keeps its count and says so. The proposal is
506 over the readings of *runners*; the pull request proposal over
507 *pull_request_runners* when that list is shorter, else the counts
508 are the same and say so. When *current* (or *pull_request_current*)
509 is given, runners that kept their count retain their contract count
510 in the printed TOML line.
511 """
512 cap = max(1, cap)
513 lines: list[str] = []
514 for reading in readings:
515 lines.extend(_platform_lines(reading, cap))
516 present = {reading.os for reading in readings}
517 lines.extend(
518 f" {runner}: keeps its count: 0 full green row(s), {ROWS_NEEDED} needed"
519 for runner in runners
520 if runner not in present
521 )
522 full = propose([r for r in readings if r.os in runners], cap=cap)
523 lines.extend(_named_capped(readings, full, cap))
524 lines.append(_toml_line("shards", full, runners, current))
525 narrower = pull_request_runners is not None and len(pull_request_runners) < len(
526 runners
527 )
528 pulls = (
529 propose([r for r in readings if r.os in (pull_request_runners or ())], cap=cap)
530 if narrower
531 else None
532 )
533 if pulls is not None:
534 lines.extend(_named_capped(readings, pulls, cap))
535 lines.append(
536 _toml_line(
537 "pull-request-shards",
538 pulls,
539 pull_request_runners or (),
540 pull_request_current,
541 )
542 )
543 elif full.counts:
544 lines.append(" [ci] pull-request-shards: the same")
545 lines.extend(_wall_line("run", full))
546 if pulls is not None:
547 lines.extend(_wall_line("pull request", pulls))
548 return lines
549
550
551def _named_capped((empty)
552 readings: Sequence[Reading], proposal: Proposal, cap: int
553) -> list[str]:
554 """One line per platform that took the cap without reaching the tolerance."""
555 by_platform = {reading.platform: reading for reading in readings}
556 percent = round(TOLERANCE * 100)
557 return [
558 f" {platform} takes the cap, {cap}: {wall(by_platform[platform], cap):.0f} s"
559 f" is not within {percent}% of {proposal.wall:.0f} s"
560 for platform in proposal.capped
561 ]
562
563
564def _day(entry: Mapping[str, Any]) -> str:(empty)
565 """The day a row's run was created, else the day the store stamped it."""
566 stamp = str(entry.get("created_at") or entry.get("when") or "")
567 return stamp[:10] or "an unknown day"
568
569
570@dataclass(frozen=True)(empty)
571class Counts:(empty)
572 """One key's count per runner: the contract's, the proposal's, and both walls.
573
574 Attributes:
575 key: ``shards`` or ``pull-request-shards``.
576 runners: The runners the key covers, in the contract's order.
577 current: The count per runner the contract gives, one where it
578 is silent.
579 proposed: The count per runner the proposal gives; a runner
580 whose platform keeps its count has its current one.
581 before: The predicted wall of the slowest leg at the current
582 counts, in seconds, over the platforms with enough rows.
583 after: The same at the proposed counts.
584 """
585
586 key: str(empty)
587 runners: tuple[str, ...](empty)
588 current: dict[str, int](empty)
589 proposed: dict[str, int](empty)
590 before: float(empty)
591 after: float(empty)
592
593 @property(empty)
594 def changed(self) -> bool:(empty)
595 """Whether a count differs between the proposal and the contract."""
596 return self.proposed != self.current
597
598 @property(empty)
599 def moved(self) -> bool:(empty)
600 """Whether the wall moves by more than the hysteresis between the two."""
601 return abs(self.after - self.before) > HYSTERESIS * self.before
602
603 @property(empty)
604 def table(self) -> dict[str, int]:(empty)
605 """The proposed counts as the contract holds them: those above one, in order."""
606 return _ordered(self.proposed, self.runners)
607
608 @property(empty)
609 def held(self) -> dict[str, int]:(empty)
610 """The current counts as the contract holds them."""
611 return _ordered(self.current, self.runners)
612
613
614@dataclass(frozen=True)(empty)
615class Balance:(empty)
616 """One reading of the record: the verb's lines and the counts a write judges.
617
618 Attributes:
619 lines: The window line, the tables and the proposal, as `render`
620 prints them.
621 shards: The counts of ``[ci] shards`` over ``[ci] runners``;
622 None when the record proposed nothing, and ``reason`` says
623 why.
624 pull_request: The counts of ``[ci] pull-request-shards`` over
625 ``[ci] pull-request-runners`` when that list is shorter than
626 ``[ci] runners``; None otherwise, and a write leaves the key
627 as it is.
628 reason: Why the record proposed nothing; empty when it did.
629 """
630
631 lines: list[str](empty)
632 shards: Counts | None = None(empty)
633 pull_request: Counts | None = None(empty)
634 reason: str = ""(empty)
635
636
637@dataclass(frozen=True)(empty)
638class Verdict:(empty)
639 """A write's decision on a `Balance`: the tables for the contract, or why none.
640
641 Attributes:
642 tables: The table per key the write puts in the contract, an
643 empty one removing the key; None when nothing is written.
644 why: Why nothing is written; empty when something is.
645 what: The wall the decision read, ``run`` or ``pull request``.
646 before: That wall at the contract's counts, in seconds.
647 after: That wall at the proposed counts.
648 """
649
650 tables: dict[str, dict[str, int]] | None(empty)
651 why: str = ""(empty)
652 what: str = ""(empty)
653 before: float = 0.0(empty)
654 after: float = 0.0(empty)
655
656
657def counts((empty)
658 readings: Sequence[Reading],
659 *,
660 key: str,
661 runners: Sequence[str],
662 current: Mapping[str, int],
663 cap: int,
664) -> Counts:
665 """One key's counts over *runners*: *current*, the proposal, and both walls.
666
667 A runner whose platform has too few rows keeps its current count.
668 The walls are the slowest leg's among the platforms with enough
669 rows, at the current counts and at the proposed ones.
670 """
671 proposal = propose([r for r in readings if r.os in runners], cap=cap)
672 proposed = {
673 runner: proposal.counts.get(runner, current[runner]) for runner in runners
674 }
675 able = [r for r in readings if r.os in runners and r.enough]
676 return Counts(
677 key,
678 tuple(runners),
679 dict(current),
680 proposed,
681 max((wall(r, current[r.os]) for r in able), default=0.0),
682 max((wall(r, proposed[r.os]) for r in able), default=0.0),
683 )
684
685
686def _cap(ci: dict[str, Any], cap: int) -> int:(empty)
687 """The cap the proposal stays within: ``[ci] shards-max``, or *cap* when under it.
688
689 Zero reads the contract's. A *cap* above the contract's refuses by
690 name: a count above ``[ci] shards-max`` is one the contract refuses
691 at its next load.
692 """
693 most = shards_max(ci)
694 if cap <= 0:
695 return most
696 if cap > most:
697 fail(
698 f"--max={cap} is above [ci] shards-max, {most}: raise the cap in the"
699 " contract, or lower --max"
700 )
701 return cap
702
703
704def read(root: Path, *, cap: int = 0) -> Balance:(empty)
705 """Read the record and the contract: what ``fm ci.balance`` prints, and the counts.
706
707 Reads the metrics series and the root contract's ``[ci] runners``,
708 ``[ci] pull-request-runners``, ``[ci] shards``, ``[ci]
709 pull-request-shards`` and ``[ci] shards-max``. *cap* is ``--max``,
710 zero for the contract's cap. An unreadable series prints its reason
711 and proposes nothing; an empty one says so.
712 """
713 found = SERIES.rows(state_store(root))
714 if found.failed:
715 return Balance(
716 [f" {found.reason}", " nothing proposed: the record could not be read"],
717 reason="the record could not be read",
718 )
719 entries = [row.data for row in found.rows]
720 if not entries:
721 return Balance(
722 [
723 " no timing rows yet: the gate job writes one per run",
724 " nothing proposed: the record holds no row",
725 ],
726 reason="the record holds no row",
727 )
728 lines = [f" {line}" for line in found.skipped]
729 lines.append(
730 f" {len(entries)} run(s) in the window, {_day(entries[-1])} to"
731 f" {_day(entries[0])}; the newest {ROWS_READ} full green row(s) per platform"
732 " are read"
733 )
734 ci = load_contract(root / "workshop.toml").get("ci") or {}
735 runners = [str(runner) for runner in ci.get("runners") or ["ubuntu-latest"]]
736 pulls = pull_request_runners(ci)
737 cap = _cap(ci, cap)
738 measured = readings(entries)
739 if not any(r.enough and r.os in runners for r in measured):
740 lines.extend(
741 report(measured, cap=cap, runners=runners, pull_request_runners=pulls)
742 )
743 return Balance(
744 lines,
745 reason=(
746 f"no platform has {ROWS_NEEDED} full green rows with the test"
747 " steps' wall"
748 ),
749 )
750 current = shard_counts(ci, key="shards", runners=runners, listed="[ci] runners")
751 shards = counts(measured, key="shards", runners=runners, current=current, cap=cap)
752 pull_request = None
753 held: dict[str, int] | None = None
754 if len(pulls) < len(runners):
755 if ci.get("pull-request-shards") is None:
756 held = {runner: current[runner] for runner in pulls}
757 else:
758 held = shard_counts(
759 ci,
760 key="pull-request-shards",
761 runners=pulls,
762 listed="[ci] pull-request-runners",
763 )
764 pull_request = counts(
765 measured, key="pull-request-shards", runners=pulls, current=held, cap=cap
766 )
767 lines.extend(
768 report(
769 measured,
770 cap=cap,
771 runners=runners,
772 pull_request_runners=pulls,
773 current=current,
774 pull_request_current=held,
775 )
776 )
777 return Balance(lines, shards, pull_request)
778
779
780def render(root: Path, *, cap: int = 0) -> list[str]:(empty)
781 """What ``fm ci.balance`` prints: the window, the tables, the proposal.
782
783 `read` with the counts left out; *cap* means what it means there.
784 """
785 return read(root, cap=cap).lines
786
787
788def judge(balance: Balance) -> Verdict:(empty)
789 """Decide what a write puts in the contract for *balance*, or why nothing.
790
791 Nothing is written when the record proposed nothing, when every
792 count is the contract's, and when the predicted wall at the
793 proposed counts is within the hysteresis of the wall at the
794 contract's counts. The run wall decides, over ``[ci] runners``;
795 when the run's counts are the contract's and only the pull
796 request's differ, the pull request wall decides. Otherwise the
797 tables are ``[ci] shards`` and, when the pull request runners are
798 fewer, ``[ci] pull-request-shards``, both at the proposal.
799 """
800 shards = balance.shards
801 if shards is None:
802 return Verdict(None, f"nothing written: {balance.reason}")
803 pulls = balance.pull_request
804 if shards.changed:
805 judged, what = shards, "run"
806 elif pulls is not None and pulls.changed:
807 judged, what = pulls, "pull request"
808 else:
809 return Verdict(None, "nothing written: every count is the contract's")
810 if not judged.moved:
811 return Verdict(
812 None,
813 f"nothing written: the predicted {what} wall moves from"
814 f" {judged.before:.0f} s to {judged.after:.0f} s, within"
815 f" {round(HYSTERESIS * 100)}%",
816 )
817 tables = {"shards": shards.table}
818 if pulls is not None:
819 tables["pull-request-shards"] = pulls.table
820 return Verdict(tables, "", what, judged.before, judged.after)
821
822
823#: The ``[ci]`` header, on a line of its own, a comment after it allowed.
824_CI_HEADER = re.compile(r"^[ \t]*\[[ \t]*ci[ \t]*\][ \t]*(?:#.*)?$")(empty)
825
826#: Any table header: the line's first character after its indent is ``[``.
827_HEADER = re.compile(r"^[ \t]*\[")(empty)
828
829#: A key's line, bare or quoted, up to its ``=``.
830_KEY_LINE = re.compile(r'^([ \t]*)(?:([A-Za-z0-9_-]+)|"([^"]*)")[ \t]*=')(empty)
831
832
833def _value_end((empty)
834 lines: Sequence[str], first: int, end: int, column: int
835) -> tuple[int, str]:
836 """Where the value at *column* of line *first* ends, and its trailing comment.
837
838 The value ends on the first line that closes every bracket it
839 opened, brackets inside strings and comments not counted; the
840 comment is the one after the value on that line, empty without
841 one.
842 """
843 depth = 0
844 quote = ""
845 line = first
846 at = column
847 while line < end:847 ↛ 877line 847 didn't jump to line 877 because the condition on line 847 was always true
848 text = lines[line]
849 comment = ""
850 while at < len(text):
851 char = text[at]
852 if quote:
853 if char == "\\" and quote.startswith('"'):853 ↛ 854line 853 didn't jump to line 854 because the condition on line 853 was never true
854 at += 2
855 elif text.startswith(quote, at):
856 at += len(quote)
857 quote = ""
858 else:
859 at += 1
860 continue
861 if char == "#":
862 comment = text[at:].rstrip()
863 break
864 if char in "\"'":
865 quote = char * 3 if text.startswith(char * 3, at) else char
866 at += len(quote)
867 continue
868 if char in "[{":
869 depth += 1
870 elif char in "]}":
871 depth -= 1
872 at += 1
873 if depth <= 0 and not quote:
874 return line, comment
875 line += 1
876 at = 0
877 return end - 1, ""
878
879
880@dataclass(frozen=True)(empty)
881class _Key:(empty)
882 """One key of the ``[ci]`` table as written.
883
884 Attributes:
885 name: The key, unquoted.
886 first: The line its name stands on.
887 last: The line its value ends on, the same for a one-line value.
888 comment: The comment after the value on its last line; empty
889 without one.
890 indent: What stands before the name on its line.
891 """
892
893 name: str(empty)
894 first: int(empty)
895 last: int(empty)
896 comment: str(empty)
897 indent: str(empty)
898
899
900def _keys(lines: Sequence[str], start: int, end: int) -> list[_Key]:(empty)
901 """The keys of the lines *start* to *end*, in order."""
902 found: list[_Key] = []
903 line = start
904 while line < end:
905 match = _KEY_LINE.match(lines[line])
906 if match is None:
907 line += 1
908 continue
909 last, comment = _value_end(lines, line, end, match.end())
910 found.append(
911 _Key(match.group(2) or match.group(3), line, last, comment, match.group(1))
912 )
913 line = last + 1
914 return found
915
916
917def _ci_table(lines: Sequence[str]) -> tuple[int, int] | None:(empty)
918 """The ``[ci]`` header's line and the line after its last; None without one."""
919 header = next((i for i, line in enumerate(lines) if _CI_HEADER.match(line)), None)
920 if header is None:
921 return None
922 end = next(
923 (i for i in range(header + 1, len(lines)) if _HEADER.match(lines[i])),
924 len(lines),
925 )
926 return header, end
927
928
929def holds_key(text: str, key: str) -> bool:(empty)
930 """Whether *text*'s ``[ci]`` table spells *key* as one of its own keys."""
931 lines = text.split("\n")
932 table = _ci_table(lines)
933 if table is None:933 ↛ 934line 933 didn't jump to line 934 because the condition on line 933 was never true
934 return False
935 header, end = table
936 return any(found.name == key for found in _keys(lines, header + 1, end))
937
938
939def rewrite(text: str, key: str, table: Mapping[str, int]) -> str:(empty)
940 """*text* with ``[ci] <key>`` at *table*, every other line kept as written.
941
942 A key the table holds is rewritten in place as one inline table,
943 its trailing comment kept, however many lines it spanned; an
944 empty *table* removes the key with the comment lines directly
945 above it, since a comment on a key that is gone misleads. A key
946 the table lacks is added after its last key, under its own comment
947 ([livery.workshop._balance.COMMENTS][]), or under the header when
948 the table has none; a contract without a ``[ci]`` table gains one
949 at its end. An absent key with an empty *table* changes nothing.
950 """
951 lines = text.split("\n")
952 spelled = f"{key} = {spell(table)}"
953 found = _ci_table(lines)
954 if found is None:
955 if not table:
956 return text
957 base = text.rstrip("\n")
958 return (base + "\n\n" if base else "") + f"[ci]\n{COMMENTS[key]}\n{spelled}\n"
959 header, end = found
960 keys = _keys(lines, header + 1, end)
961 for held in keys:
962 if held.name != key:
963 continue
964 if table:
965 after = f" {held.comment}" if held.comment else ""
966 lines[held.first : held.last + 1] = [held.indent + spelled + after]
967 else:
968 above = held.first
969 while above > header + 1 and lines[above - 1].strip().startswith("#"):
970 above -= 1
971 del lines[above : held.last + 1]
972 return "\n".join(lines)
973 if not table:
974 return text
975 if keys:
976 indent, at = keys[-1].indent, keys[-1].last + 1
977 else:
978 indent, at = "", header + 1
979 lines[at:at] = [indent + COMMENTS[key], indent + spelled]
980 return "\n".join(lines)
981
982
983def write(root: Path, balance: Balance) -> dict[str, dict[str, int]] | None:(empty)
984 """Rewrite the contract's counts when `judge` says to; the tables written, or None.
985
986 Prints what each key becomes and the wall the decision read, or
987 why nothing is written. Refuses by name when a key the contract
988 holds is not spelled as a key of the ``[ci]`` table, as a
989 ``[ci.shards]`` table or a dotted key: the rewrite keeps the
990 contract's text and cannot reach it there.
991 """
992 verdict = judge(balance)
993 if verdict.tables is None:
994 print(f" {verdict.why}")
995 return None
996 path = root / "workshop.toml"
997 text = path.read_text(encoding="utf-8")
998 ci = load_contract(path).get("ci") or {}
999 for key, table in verdict.tables.items():
1000 if ci.get(key) is not None and not holds_key(text, key):
1001 fail(
1002 f"[ci] {key} is not a key of the [ci] table in {path.name} (a"
1003 f" [ci.{key}] table, or a dotted key): spell it `{key} = {{ ... }}`"
1004 " under [ci] for the balancer to rewrite it"
1005 )
1006 text = rewrite(text, key, table)
1007 path.write_text(text, encoding="utf-8")
1008 for found in (balance.shards, balance.pull_request):
1009 if found is not None and found.key in verdict.tables:
1010 print(
1011 f" [ci] {found.key}: {spell(found.held)} becomes"
1012 f" {spell(verdict.tables[found.key])}"
1013 )
1014 print(
1015 f" the predicted {verdict.what} wall moves from {verdict.before:.0f} s to"
1016 f" {verdict.after:.0f} s"
1017 )
1018 return verdict.tables
1019
1020
1021def on_default_branch(root: Path) -> bool:(empty)
1022 """Whether HEAD is on the history of origin's default branch.
1023
1024 Origin's default branch is fetched as ``HEAD``, so no branch name
1025 is needed and a checkout a merge moved on since still answers; a
1026 detached HEAD at a commit of that history answers True.
1027
1028 Raises:
1029 Failed: when origin cannot be fetched, in git's words.
1030 """
1031 try:
1032 git.fetch(root, "HEAD")
1033 except git.GitError as error:
1034 fail(f"origin could not be fetched: {error}")
1035 answer = git.call(root, "merge-base", "--is-ancestor", "HEAD", "FETCH_HEAD")
1036 if answer.code not in (0, 1):1036 ↛ 1037line 1036 didn't jump to line 1037 because the condition on line 1036 was never true
1037 said = (answer.stderr or answer.stdout).strip()
1038 fail(f"git merge-base exited {answer.code}: {said}")
1039 return answer.code == 0
1040
1041
1042def auto_balance(root: Path) -> bool:(empty)
1043 """Whether ``[ci] auto-balance`` arms auto-merge on balancer pull requests."""
1044 from livery.workshop._contract import load_contract
1045
1046 ci = load_contract(root / "workshop.toml").get("ci") or {}
1047 return bool(ci.get("auto-balance", False))
1048
1049
1050def submit(root: Path, *, cap: int = 0, on: date | None = None) -> None:(empty)
1051 """Land a due change on the day's branch and open its pull request.
1052
1053 Armed when ``[ci] auto-balance = true`` in the root contract, unarmed
1054 otherwise.
1055
1056 The act, each step printed: off origin's default branch nothing is
1057 read or written, the line names the branch, and the verb exits
1058 green, so a nightly dispatched on another branch skips it. On it,
1059 the record is read and judged as `write` judges it; nothing due
1060 means no branch and no pull request. Otherwise origin is asked for
1061 the day's branch, ``chore/balance-<date>``, before anything in the
1062 checkout changes: one holding these counts, from an earlier run of
1063 the day, means the day's balance is already submitted, and one
1064 holding other counts refuses by name, for a person to merge or
1065 close its pull request first. Then, from a clean tree, the branch
1066 is started in this checkout from a fetched ``origin/main``
1067 ([livery.workshop._issue_tasks.start_here][]), the contract is
1068 rewritten, the sync renders the workflows at the counts
1069 ([livery.workshop._sync.sync_checkout][]), the change is committed
1070 as ``chore(ci): the check legs run as <counts>``
1071 ([livery.workshop._commit.commit_flow][]) and submitted unarmed
1072 ([livery.workshop._submit.submit_flow][]), its gate run there and
1073 not twice, and the checkout returns to where it was. *on* is the
1074 day, today when None; *cap* is ``--max``.
1075
1076 Raises:
1077 Failed: naming what stopped it, with nothing written when it
1078 stops before the write.
1079 """
1080 from livery.git import remote_snapshot
1081
1082 if not on_default_branch(root):
1083 where = git.current_branch(root) or "(detached)"
1084 print(
1085 f" not on origin's default branch (on {where}): nothing is written or"
1086 " submitted; the balancer submits from the default branch alone"
1087 )
1088 return
1089 with remote_snapshot(state_store(root), fetch=("metrics",)):
1090 balance = read(root, cap=cap)
1091 for line in balance.lines:
1092 print(line)
1093 verdict = judge(balance)
1094 if verdict.tables is None:
1095 print(f" {verdict.why}")
1096 print(" no branch, no pull request")
1097 return
1098 day = on or date.today()
1099 branch = f"chore/balance-{day:%Y%m%d}"
1100 if _origin_holds(root, branch):
1101 held = _held(root, branch, verdict.tables)
1102 if held == verdict.tables:
1103 print(
1104 f" the day's balance is already submitted: {branch} on origin holds"
1105 " these counts; nothing is written"
1106 )
1107 return
1108 fail(
1109 f"{branch} on origin holds other counts ({_spell_tables(held)}) than"
1110 f" this reading proposes ({_spell_tables(verdict.tables)}): merge or"
1111 " close its pull request, then run the balancer again; nothing is"
1112 " written"
1113 )
1114 if not git.is_clean(root):
1115 fail(
1116 "the working tree has uncommitted changes: commit or stash them, then"
1117 " run the balancer again; nothing is written"
1118 )
1119 from livery.workshop._commit import commit_flow
1120 from livery.workshop._forge_lane import this_repository
1121 from livery.workshop._issue_tasks import fetch_base, start_here
1122 from livery.workshop._submit import forge_failures_named, submit_flow
1123 from livery.workshop._sync import sync_checkout
1124
1125 came_from = git.current_branch(root) or git.head_sha(root)
1126 repo = this_repository(root)
1127 fetch_base(root)
1128 start_here(root, repo, branch)
1129 try:
1130 write(root, balance)
1131 sync_checkout(root)
1132 subject = _subject(balance, verdict.tables)
1133 # The submit's gate judges this tree next; a gate at the commit
1134 # would judge the same tree twice.
1135 commit_flow(
1136 root,
1137 "chore",
1138 subject,
1139 scope="ci",
1140 body=(
1141 f"the predicted {verdict.what} wall moves from {verdict.before:.0f} s"
1142 f" to {verdict.after:.0f} s"
1143 ),
1144 check=False,
1145 )
1146 arm = auto_balance(root)
1147 with forge_failures_named():
1148 number = submit_flow(
1149 repo,
1150 root,
1151 title=f"chore(ci): {subject}",
1152 armed=arm,
1153 armed_reason=(
1154 "[ci] auto-balance" if arm else "the balancer, which never arms"
1155 ),
1156 follow_to_verdict=False,
1157 )
1158 if arm:
1159 print(f" submitted armed: PR #{number} merges when green")
1160 else:
1161 print(f" submitted unarmed: PR #{number} waits for a person")
1162 finally:
1163 if not git.is_clean(root):1163 ↛ 1164line 1163 didn't jump to line 1164 because the condition on line 1163 was never true
1164 git.call(root, "reset", "--hard", "HEAD")
1165 if git.local_branch_exists(root, came_from):1165 ↛ 1169line 1165 didn't jump to line 1169 because the condition on line 1165 was always true
1166 git.switch(root, came_from)
1167 print(f" back on {came_from}")
1168 else:
1169 git.run(root, "checkout", "--detach", came_from)
1170 print(f" back at {came_from[:12]}, detached as before")
1171
1172
1173def _subject(balance: Balance, tables: Mapping[str, Mapping[str, int]]) -> str:(empty)
1174 """The commit subject's words: the counts, and a pull request's that differ."""
1175 shards = tables["shards"]
1176 words = f"the check legs run as {_spoken(shards)}"
1177 pulls = balance.pull_request
1178 if pulls is not None:1178 ↛ 1182line 1178 didn't jump to line 1182 because the condition on line 1178 was always true
1179 same = {r: n for r, n in shards.items() if r in pulls.runners}
1180 if tables["pull-request-shards"] != same:1180 ↛ 1181line 1180 didn't jump to line 1181 because the condition on line 1180 was never true
1181 words += f", pull requests as {_spoken(tables['pull-request-shards'])}"
1182 return words
1183
1184
1185def _spoken(table: Mapping[str, int]) -> str:(empty)
1186 return ", ".join(f"{runner} {n}" for runner, n in table.items()) or "one shard each"
1187
1188
1189def _spell_tables(tables: Mapping[str, Mapping[str, int]]) -> str:(empty)
1190 return "; ".join(f"[ci] {key} {spell(table)}" for key, table in tables.items())
1191
1192
1193def _origin_holds(root: Path, branch: str) -> bool:(empty)
1194 """Whether origin holds *branch*, asked of origin itself; a refusal names it."""
1195 try:
1196 return bool(git.ls_remote(root, f"refs/heads/{branch}"))
1197 except git.GitError as error:
1198 fail(f"could not ask origin for {branch}: {error}\n nothing is written")
1199
1200
1201def _held((empty)
1202 root: Path, branch: str, tables: Mapping[str, Mapping[str, int]]
1203) -> dict[str, dict[str, int]]:
1204 """The counts origin's *branch* holds for the keys of *tables*, as written."""
1205 git.fetch(root, f"+refs/heads/{branch}:refs/remotes/origin/{branch}")
1206 text = git.file_at(root, f"refs/remotes/origin/{branch}", "workshop.toml")
1207 loaded: dict[str, Any] = tomllib.loads(text) if text else {}
1208 ci = _table_or_empty(loaded.get("ci"))
1209 return {key: _table_of(ci.get(key)) for key in tables}
1210
1211
1212def _table_or_empty(value: Any) -> dict[str, Any]:(empty)
1213 """*value* when it is a table, else an empty one."""
1214 if isinstance(value, dict):
1215 table: dict[str, Any] = value
1216 return table
1217 return {}
1218
1219
1220def _table_of(value: Any) -> dict[str, int]:(empty)
1221 """The counts above one in *value*, a table of runner to count; none otherwise."""
1222 return {
1223 runner: n
1224 for runner, n in _table_or_empty(value).items()
1225 if isinstance(n, int) and not isinstance(n, bool) and n > 1
1226 }