Coverage for packages/workshop/src/livery/workshop/_speed.py: 96%

Measured by coverage.py 7.16.2 on CPython 3.14 while the suites of tests, packages/workshop/tests/test_workshop_without_docs.py, packages/workshop/tests/test_workshop_vocabulary.py, packages/workshop/tests/test_workshop_traces.py, packages/workshop/tests/test_workshop_sync_install.py, packages/workshop/tests/test_workshop_sync.py, packages/workshop/tests/test_workshop_sweep.py, packages/workshop/tests/test_workshop_store_tasks.py, packages/workshop/tests/test_workshop_speed.py, packages/workshop/tests/test_workshop_shells.py, packages/workshop/tests/test_workshop_shard.py, packages/workshop/tests/test_workshop_scale.py, packages/workshop/tests/test_workshop_runs.py, packages/workshop/tests/test_workshop_proved_trees.py, packages/workshop/tests/test_workshop_proved_shadow.py, packages/workshop/tests/test_workshop_proved_parts.py, packages/workshop/tests/test_workshop_proved_flaky.py, packages/workshop/tests/test_workshop_proved_escapes.py, packages/workshop/tests/test_workshop_proved_decide.py, packages/workshop/tests/test_workshop_proved.py, packages/workshop/tests/test_workshop_prose.py, packages/workshop/tests/test_workshop_points.py, packages/workshop/tests/test_workshop_package.py, packages/workshop/tests/test_workshop_new_project.py, packages/workshop/tests/test_workshop_metrics.py, packages/workshop/tests/test_workshop_layering.py, packages/workshop/tests/test_workshop_issue.py, packages/workshop/tests/test_workshop_footprint.py, packages/workshop/tests/test_workshop_fold.py, packages/workshop/tests/test_workshop_extension_mount.py, packages/workshop/tests/test_workshop_e2e_rows.py, packages/workshop/tests/test_workshop_e2e.py, packages/workshop/tests/test_workshop_due.py, packages/workshop/tests/test_workshop_currency.py, packages/workshop/tests/test_workshop_credential_traces.py, packages/workshop/tests/test_workshop_ci_context.py, packages/workshop/tests/test_workshop_c7_shards.py, packages/workshop/tests/test_workshop_balance.py, packages/workshop/tests/test_workshop_affected_legs.py, packages/extensions/python/tests/test_speed.py, packages/extensions/python/tests/test_extensions_python.py, packages/extensions/pytest/tests/test_pytest_observer_shadow.py, packages/extensions/pytest/tests/test_pytest_c6_selection.py, packages/extensions/pytest/tests/test_pytest_c5_repeats.py, packages/extensions/nanobind/tests/test_extensions_nanobind.py, packages/extensions/docs/tests/test_task_links.py, packages/extensions/cpp/tests/test_extensions_cpp.py, packages/extensions/coverage/tests/test_coverage_store.py, packages/extensions/coverage/tests/test_coverage_proved_parts.py, packages/extensions/coverage/tests/test_coverage_accept.py, packages/extensions/coverage/tests/test_coverage.py, packages/extensions/conan/tests/test_extensions_conan.py ran.

1"""The test speed marks: a package's suite time per check leg, and how it moves.
2
3The gate job judges each check leg's summed test time per package, the
4``packages`` field of the timing rows ([livery.workshop._metrics][]),
5against a mark on the ``speed/marks`` series. The mark is the median of
6the leg's last five green runs for the package, recorded once five are
7seen; it ratchets down when that median beats it by more than five per
8cent, so a suite cannot regress slowly, and a person raises it with
9``fm speed.accept``, since a new heavy test is a cost someone chose.
10
11A run over the mark by more than fifteen per cent and twenty seconds
12warns, naming the leg's slowest tests and the ones that grew most
13against their own medians; the second such run in a row on a reference
14leg (ubuntu) is red, and the other legs warn only until their variance
15is measured. A store that cannot be read falls open with its reason and
16writes nothing. The margins are constants here, chosen before the rows
17could set them; a reading of a month of rows may move them.
18
19Reach for `judge_run` to judge the run the gate job is in, `accept` for
20the person's raise, `render_marks` for what ``fm ci.timings`` adds, and
21[livery.workshop.speed_marks][] for the current marks. A test's
22package, which the speed plugin sums by and the timing rows key by, is
23what [livery.workshop.package_of][] names.
24"""
25
26from __future__ import annotations
27
28import re
29import statistics
30from collections import defaultdict
31from collections.abc import Mapping
32from dataclasses import dataclass
33from datetime import UTC, datetime
34from pathlib import Path
35from typing import Any
36
37from livery import git
38from livery.footman import fail
39from livery.workshop._ci_context import RunContext, state_store
40from livery.workshop._pytest_common import (
41 PACKAGE_TREES as PACKAGE_TREES,
42)
43from livery.workshop._pytest_common import (
44 SPEED_FILE_VARIABLE as SPEED_FILE_VARIABLE,
45)
46from livery.workshop._pytest_common import (
47 package_of as package_of,
48)
49from livery.workshop._shard import ONE, Shard
50
51#: The marks: one row per write, the newest per package and leg the
52#: mark; anyone may write, since an accept is a person's act, and the
53#: gate job's writer guards its own rule that only a run records or
54#: ratchets.
55SERIES = git.Series("speed/marks", window=400, ci_only=False)
56
57#: The green runs behind a mark: the median of this many is the mark.
58SAMPLE = 5
59
60#: Over the mark by more than this fraction ...
61MARGIN = 0.15
62
63#: ... and by more than this many seconds is over.
64FLOOR_SECONDS = 20.0
65
66#: The sample's median under the mark by more than this fraction
67#: moves the mark down to it.
68RATCHET = 0.05
69
70#: The runner whose legs are red on the second run over; every other
71#: leg warns only.
72REFERENCE = "ubuntu"
73
74#: The contract key that turns the speed marks on.
75ENABLED_KEY = "speed-marks"
76
77
78def enabled(root: Path) -> bool:
79 """The contract's ``[ci] speed-marks``; false when undeclared.
80
81 Off by default: a hosted runner's test time varies by tens of
82 seconds between two runs of one tree, and a mark taken from such
83 runs says nothing about the suite. A workspace whose runners keep
84 a steady clock declares the key, which the contract's judge holds
85 to a boolean.
86 """
87 from livery.workshop._contract import load_contract
88
89 ci = load_contract(root / "workshop.toml").get("ci") or {}
90 return bool(ci.get(ENABLED_KEY, False))
91
92
93#: The slowest tests a leg's row names, and a warning prints.
94SLOWEST = 10
95
96#: The tests that grew most a warning prints.
97GROWN = 5
98
99_DISPLAY = re.compile(
100 r"^(?P<job>[^ (]+) \((?P<os>[^,]+), (?P<python>[^,)]+)(?:, (?P<shard>[^)]+))?\)$"
101)
102
103#: GitLab lists a job that runs as ``parallel: matrix`` by its key and
104#: the matrix value: ``check: [2of4]``.
105_GITLAB_DISPLAY = re.compile(r"^(?P<job>[^ :\[]+): \[(?P<shard>[^\]]+)\]$")
106
107
108def drop_marks(root: Path) -> list[str]:
109 """Drop the marks series while the marks are off; the lines to print.
110
111 Rows written before the switch went off would be the marks a
112 later opt-in judges from, so the gate job drops the whole series
113 when it finds any. Fails open: a store that cannot be read, or a
114 delete the remote refuses, prints its reason and drops nothing.
115 Nothing to print when the series is already gone.
116 """
117 from livery.git import drop
118
119 found = SERIES.rows(state_store(root))
120 if found.failed:
121 return [f" speed marks: not dropped: {found.reason}"]
122 if not found.rows and not found.skipped:
123 return []
124 why = drop(state_store(root), SERIES.ref)
125 if why:125 ↛ 126line 125 didn't jump to line 126 because the condition on line 125 was never true
126 return [f" speed marks: not dropped: {why}"]
127 count = len(found.rows) + len(found.skipped)
128 return [
129 f" speed marks: dropped {count} stale row(s) from {SERIES.ref};"
130 f" the marks are off ([ci] {ENABLED_KEY})"
131 ]
132
133
134def leg_label(display: str) -> str:
135 """The leg label of a matrix job's display name; a plain name stands.
136
137 ``check (ubuntu-latest, 3.14)`` is the leg ``check-ubuntu-latest-3.14``
138 and ``check (windows-latest, 3.14, 2of4)`` the shard leg
139 ``check-windows-latest-3.14-2of4``, the spelling the job runner gives
140 every entry it spawns.
141 """
142 match = _DISPLAY.match(display)
143 if match is None:
144 return display
145 parts = (match["job"], match["os"], match["python"], match["shard"])
146 return "-".join(part for part in parts if part)
147
148
149def display_shard(display: str) -> Shard:
150 """The shard a job's display name spells; `ONE` when it spells none.
151
152 ``check (windows-latest, 3.14, 2of4)`` on GitHub and Gitea,
153 ``check: [2of4]`` on GitLab. A tail that is not spelled
154 ``<i>of<n>`` names no shard, so a matrix with another third value
155 reads as one shard of one.
156 """
157 match = _DISPLAY.match(display) or _GITLAB_DISPLAY.match(display)
158 spelled = match["shard"] if match else None
159 if not spelled:
160 return ONE
161 try:
162 return Shard.parse(spelled)
163 except ValueError:
164 return ONE
165
166
167def platform_display(display: str) -> str:
168 """The display name of a shard's platform: *display* without its shard.
169
170 ``check (windows-latest, 3.14, 2of4)`` gives ``check (windows-latest,
171 3.14)`` and ``check: [2of4]`` gives ``check``; a name that spells no
172 shard stands. The gate job's fold names a platform's folded row by
173 it, and the collect joins that row with the forge's jobs.
174 """
175 if display_shard(display) == ONE:
176 return display
177 match = _DISPLAY.match(display)
178 if match is not None:
179 # The shard follows a comma and a space; what comes before is
180 # the platform's own name, closed again.
181 return f"{display[: match.start('shard') - 2]})"
182 gitlab = _GITLAB_DISPLAY.match(display)
183 return gitlab["job"] if gitlab is not None else display
184
185
186def forge_shard_row(job: str, row: Mapping[str, Any]) -> bool:
187 """Whether *job*'s *row* is the forge's own row of a shard: no scope, a shard named.
188
189 The gate job folds a platform's shards into one row under the
190 platform's display name, and the collect keeps the forge's rows of
191 the shards beside it for ``fm ci.timings``; those carry the forge's
192 times and no scope. The stamp and the speed judge skip them, since
193 the folded row carries what they read.
194 """
195 return "scope" not in row and display_shard(job) != ONE
196
197
198def leg_of(job: str, row: Mapping[str, Any]) -> str:
199 """The leg a run's job row measured: the row's own label, or the name's.
200
201 A check leg writes its label (``check-ubuntu-latest-3.14``) into
202 its row under ``scope.leg``, and that spelling holds on every
203 forge; the job's display name carries the matrix on GitHub and
204 Gitea alone, and on GitLab is the bare ``check``, which would name
205 no runner and never count as the reference.
206 """
207 scope = row.get("scope")
208 label = str(scope.get("leg") or "") if isinstance(scope, Mapping) else ""
209 return label or leg_label(job)
210
211
212def is_reference(leg: str) -> bool:
213 """Whether *leg* runs on the reference runner, the one whose red counts."""
214 return REFERENCE in leg
215
216
217@dataclass(frozen=True)
218class SpeedMark:
219 """A package's mark on one check leg and the row that set it.
220
221 The mark is the suite's summed test time the gate job judges the
222 leg's runs against; [livery.workshop.speed_marks][] reads the
223 current mark of each package on each leg.
224
225 Attributes:
226 package: The package path (``packages/forge``).
227 leg: The check leg (``check-ubuntu-latest-3.14``).
228 seconds: The mark: the suite's summed test time.
229 kind: ``first`` (a run recorded it), ``ratchet`` (a run moved
230 it down), or ``accept`` (a person raised it).
231 by: The run or the person that wrote the row.
232 reason: The reason an accept gave; empty otherwise.
233 when: When the row was written, ISO 8601.
234 """
235
236 package: str
237 leg: str
238 seconds: float
239 kind: str
240 by: str
241 reason: str
242 when: str
243
244
245@dataclass(frozen=True)
246class Sample:
247 """One package's time on one leg in this run, with the leg's history.
248
249 Attributes:
250 package: The package path.
251 leg: The check leg.
252 seconds: This run's summed test time for the package.
253 tests: How many tests ran.
254 previous: The leg's earlier green runs' times for the package,
255 newest first, at most one fewer than `SAMPLE`.
256 slowest: This run's slowest tests, name and seconds, slowest first.
257 grown: The tests that grew most against their median over the
258 earlier runs: name, the median, this run's seconds.
259 """
260
261 package: str
262 leg: str
263 seconds: float
264 tests: int
265 previous: tuple[float, ...]
266 slowest: tuple[tuple[str, float], ...] = ()
267 grown: tuple[tuple[str, float, float], ...] = ()
268
269
270@dataclass(frozen=True)
271class Verdict:
272 """One package on one leg, judged against its mark.
273
274 Attributes:
275 sample: The run's time and the leg's history.
276 mark: The current mark, or ``None`` when none is recorded.
277 """
278
279 sample: Sample
280 mark: SpeedMark | None
281
282 @property
283 def limit(self) -> float | None:
284 """The seconds above which a run is over; ``None`` without a mark."""
285 if self.mark is None:
286 return None
287 return round(
288 max(self.mark.seconds * (1 + MARGIN), self.mark.seconds + FLOOR_SECONDS), 1
289 )
290
291 @property
292 def over(self) -> bool:
293 """Whether this run is over the mark by the margin."""
294 return self.limit is not None and self.sample.seconds > self.limit
295
296 @property
297 def previous_over(self) -> bool:
298 """Whether the leg's newest earlier green run was over too."""
299 return (
300 self.limit is not None
301 and bool(self.sample.previous)
302 and self.sample.previous[0] > self.limit
303 )
304
305 @property
306 def red(self) -> bool:
307 """The second run over in a row, on a reference leg."""
308 return self.over and self.previous_over and is_reference(self.sample.leg)
309
310 @property
311 def median(self) -> float | None:
312 """The median of the sample, this run included; ``None`` short of one."""
313 values = (self.sample.seconds, *self.sample.previous)
314 if len(values) < SAMPLE:
315 return None
316 return round(statistics.median(values[:SAMPLE]), 1)
317
318 @property
319 def records(self) -> bool:
320 """Whether this run records the first mark: no mark, a full sample."""
321 return self.mark is None and self.median is not None
322
323 @property
324 def ratchets(self) -> bool:
325 """Whether the sample's median beats the mark by more than `RATCHET`."""
326 return (
327 self.mark is not None
328 and self.median is not None
329 and self.median < self.mark.seconds * (1 - RATCHET)
330 )
331
332
333def _row_name(when: datetime, package: str, leg: str) -> str:
334 return f"{when.strftime('%Y%m%dT%H%M%S.%fZ')}--{git.slug(package)}--{git.slug(leg)}"
335
336
337def speed_marks(root: Path) -> tuple[dict[tuple[str, str], SpeedMark] | None, str]:
338 """Read each package's current test-time mark on each check leg.
339
340 The marks live on the checkout's state store
341 ([livery.workshop.state_store][]). The newest row per package and
342 leg is its mark. A row that does not parse, is of another schema,
343 or lacks a mark's fields is skipped, so one bad row disables
344 nothing. A store that cannot be read falls open: the caller prints
345 the reason and judges nothing.
346
347 Args:
348 root: The checkout whose state store holds the marks.
349
350 Returns:
351 Each mark by its package's path and its leg, with an empty
352 reason; an empty store gives ``({}, "")``. When the store
353 cannot be read, None and the reason.
354 """
355 found = SERIES.rows(state_store(root))
356 if found.failed:
357 return None, found.reason
358 current: dict[tuple[str, str], SpeedMark] = {}
359 for row in found.rows:
360 mark = _mark(row.data)
361 if mark is not None:
362 current.setdefault((mark.package, mark.leg), mark)
363 return current, ""
364
365
366def _mark(data: dict[str, Any]) -> SpeedMark | None:
367 try:
368 return SpeedMark(
369 package=str(data["package"]),
370 leg=str(data["leg"]),
371 seconds=float(data["seconds"]),
372 kind=str(data.get("kind", "")),
373 by=str(data.get("by", "")),
374 reason=str(data.get("reason", "")),
375 when=str(data.get("when", "")),
376 )
377 except (KeyError, TypeError, ValueError):
378 return None
379
380
381def write_mark(
382 root: Path,
383 *,
384 package: str,
385 leg: str,
386 seconds: float,
387 kind: str,
388 by: str,
389 reason: str = "",
390) -> str:
391 """Append one row setting *package*'s mark on *leg*; ``""`` or why not."""
392 row = {
393 "package": package,
394 "leg": leg,
395 "seconds": round(seconds, 1),
396 "kind": kind,
397 "by": by,
398 "reason": reason,
399 }
400 return SERIES.put(
401 state_store(root),
402 {_row_name(datetime.now(UTC), package, leg): row},
403 message=f"speed mark: {package} on {leg} {kind} {seconds:.1f}s by {by}",
404 )
405
406
407def _package_times(row: dict[str, Any]) -> dict[str, tuple[float, int]]:
408 """Each package's summed seconds and test count in a leg's row; ran ones only."""
409 out: dict[str, tuple[float, int]] = {}
410 packages = row.get("packages")
411 if not isinstance(packages, dict):411 ↛ 412line 411 didn't jump to line 412 because the condition on line 411 was never true
412 return out
413 for name, data in packages.items():
414 if not isinstance(data, dict):414 ↛ 415line 414 didn't jump to line 415 because the condition on line 414 was never true
415 continue
416 tests = data.get("tests", 0)
417 ms = data.get("tests_ms", 0.0)
418 if isinstance(tests, int) and tests > 0 and isinstance(ms, int | float):
419 out[f"packages/{name}"] = (round(float(ms) / 1000.0, 1), tests)
420 return out
421
422
423def _slowest(row: dict[str, Any]) -> dict[str, float]:
424 """The slowest tests a leg's row names, seconds by node id."""
425 out: dict[str, float] = {}
426 for item in row.get("slowest", []) or []:
427 if isinstance(item, dict) and isinstance(item.get("s"), int | float):427 ↛ 426line 427 didn't jump to line 426 because the condition on line 427 was always true
428 out[str(item.get("test", ""))] = float(item["s"])
429 return out
430
431
432def _grown(
433 now: dict[str, float], earlier: list[dict[str, float]], package: str
434) -> tuple[tuple[str, float, float], ...]:
435 """The tests of *package* that grew most against their median in *earlier*."""
436 history: dict[str, list[float]] = defaultdict(list)
437 for row in earlier:
438 for test, seconds in row.items():
439 history[test].append(seconds)
440 grown: list[tuple[float, str, float, float]] = []
441 for test, seconds in now.items():
442 if package_of(test) != package or test not in history:
443 continue
444 before = statistics.median(history[test])
445 if seconds > before * (1 + MARGIN) and seconds > before + 1.0:
446 grown.append((seconds - before, test, round(before, 2), seconds))
447 grown.sort(reverse=True)
448 return tuple((test, before, now_s) for _, test, before, now_s in grown[:GROWN])
449
450
451def samples(entries: list[dict[str, Any]], run_id: str) -> list[Sample]:
452 """This run's package times per check leg, with each leg's green history.
453
454 *entries* are the timing rows newest first. The run's own entry
455 is the one whose ``run`` is *run_id*; a check leg of it yields one
456 sample per package whose tests ran, and the forge's own row of a
457 shard (`forge_shard_row`) yields none. The history is the same leg's
458 earlier entries that concluded green and ran the package's tests,
459 newest first, up to one fewer than `SAMPLE`. Empty when the run
460 has no entry.
461 """
462 current = next((e for e in entries if str(e.get("run", "")) == run_id), None)
463 if current is None:
464 return []
465 earlier = [
466 e for e in entries if e is not current and str(e.get("run", "")) != run_id
467 ]
468 out: list[Sample] = []
469 for job, row in sorted((current.get("jobs") or {}).items()):
470 if not job.startswith("check") or not isinstance(row, dict):
471 continue
472 if forge_shard_row(job, row):
473 continue
474 leg = leg_of(job, row)
475 now_slowest = _slowest(row)
476 for package, (seconds, tests) in sorted(_package_times(row).items()):
477 previous: list[float] = []
478 slow_rows: list[dict[str, float]] = []
479 for entry in earlier:
480 past = (entry.get("jobs") or {}).get(job)
481 if not isinstance(past, dict) or past.get("conclusion") != "success":
482 continue
483 times = _package_times(past)
484 if package not in times:
485 continue
486 previous.append(times[package][0])
487 slow_rows.append(_slowest(past))
488 if len(previous) >= SAMPLE - 1:
489 break
490 slowest = tuple(
491 sorted(
492 (
493 (t, s)
494 for t, s in now_slowest.items()
495 if package_of(t) == package
496 ),
497 key=lambda item: -item[1],
498 )[:SLOWEST]
499 )
500 out.append(
501 Sample(
502 package=package,
503 leg=leg,
504 seconds=seconds,
505 tests=tests,
506 previous=tuple(previous),
507 slowest=slowest,
508 grown=_grown(now_slowest, slow_rows, package),
509 )
510 )
511 return out
512
513
514def judge(
515 found: list[Sample], current: dict[tuple[str, str], SpeedMark]
516) -> list[Verdict]:
517 """Each sample against its mark; one verdict each."""
518 return [
519 Verdict(sample=sample, mark=current.get((sample.package, sample.leg)))
520 for sample in found
521 ]
522
523
524def render(verdict: Verdict) -> list[str]:
525 """The lines for *verdict*: the time, the mark, the state, the culprits."""
526 sample, mark = verdict.sample, verdict.mark
527 head = f" speed {sample.package} on {sample.leg}: {sample.seconds:.1f}s"
528 if mark is None:
529 seen = len(sample.previous) + 1
530 if verdict.records:
531 return [f"{head}, no mark yet; this run records {verdict.median:.1f}s"]
532 return [f"{head}, no mark yet ({seen}/{SAMPLE} green runs)"]
533 limit = verdict.limit
534 assert limit is not None
535 state = ""
536 if verdict.red:
537 state = " OVER for the second run in a row: red"
538 elif verdict.over and not is_reference(sample.leg):
539 state = " OVER (this leg warns only)"
540 elif verdict.over:
541 state = " OVER (a second run over in a row is red)"
542 lines = [
543 f"{head} (mark {mark.seconds:.1f}s {mark.kind} by {mark.by},"
544 f" limit {limit:.1f}s){state}"
545 ]
546 if mark.reason:546 ↛ 547line 546 didn't jump to line 547 because the condition on line 546 was never true
547 lines.append(f" accepted: {mark.reason}")
548 if verdict.over:
549 if sample.slowest:
550 named = ", ".join(f"{test} {s:.1f}s" for test, s in sample.slowest)
551 lines.append(f" slowest: {named}")
552 if sample.grown:
553 named = ", ".join(
554 f"{test} {before:.1f}s -> {now:.1f}s"
555 for test, before, now in sample.grown
556 )
557 lines.append(f" grew: {named}")
558 if verdict.ratchets:
559 lines.append(
560 f" new mark: {verdict.median:.1f}s (the median of {SAMPLE} beats"
561 f" {mark.seconds:.1f}s by more than {RATCHET:.0%})"
562 )
563 return lines
564
565
566def judge_run(root: Path, run: RunContext) -> tuple[list[Verdict], list[str]]:
567 """Judge the run's check legs; the verdicts and the lines for what could not be.
568
569 Reads the timing rows and the marks; either unreadable falls open
570 with its reason and no verdict, so a store fault never reddens a
571 run and never writes.
572 """
573 from livery.workshop._metrics import SERIES as METRICS
574
575 rows = METRICS.rows(state_store(root))
576 if rows.failed:
577 return [], [f" speed: not judged ({rows.reason})"]
578 current, why = speed_marks(root)
579 if current is None:579 ↛ 580line 579 didn't jump to line 580 because the condition on line 579 was never true
580 return [], [f" speed: not judged ({why})"]
581 found = samples([row.data for row in rows.rows], run.run_id)
582 if not found:
583 return [], [
584 f" speed: run {run.run_id} left no check leg with tests; nothing to judge"
585 ]
586 return judge(found, current), []
587
588
589def apply(root: Path, verdicts: list[Verdict], *, by: str) -> list[str]:
590 """Write the first marks and the ratchets among *verdicts*; the lines."""
591 lines: list[str] = []
592 for verdict in verdicts:
593 if not (verdict.records or verdict.ratchets):
594 continue
595 median = verdict.median
596 assert median is not None
597 kind = "first" if verdict.records else "ratchet"
598 why = write_mark(
599 root,
600 package=verdict.sample.package,
601 leg=verdict.sample.leg,
602 seconds=median,
603 kind=kind,
604 by=by,
605 )
606 lines.append(
607 f" {'recorded' if not why else 'not recorded: ' + why}"
608 f" ({verdict.sample.package} on {verdict.sample.leg}, {kind} {median:.1f}s)"
609 )
610 return lines
611
612
613def accept(
614 root: Path,
615 *,
616 package: str,
617 leg: str,
618 seconds: float,
619 reason: str,
620 by: str,
621 packages: tuple[str, ...],
622) -> list[str]:
623 """Raise *package*'s mark on *leg* to *seconds* deliberately; the lines.
624
625 Refuses without a reason, for a path not among *packages*, a time
626 that is not positive, an unreadable store, and a value at or below
627 the current mark: lowering is the ratchet's own move.
628 """
629 if not reason.strip():
630 fail(
631 "a reason is required: --reason=<why the suite may take longer> goes"
632 " on the record beside the new mark"
633 )
634 if package not in packages:
635 fail(f"no package at {package!r}; the packages are {', '.join(packages)}")
636 if seconds <= 0:
637 fail(f"the mark is a time in seconds; {seconds!r} is not")
638 current, why = speed_marks(root)
639 if current is None:
640 fail(f"refusing: {why}; a write from an unread store would erase its rows")
641 mark = current.get((package, leg))
642 if mark is not None and seconds <= mark.seconds:
643 fail(
644 f"{package}'s mark on {leg} is {mark.seconds:.1f}s; {seconds:.1f}s does"
645 " not raise it. Lowering is the ratchet's own move, when the runs beat"
646 " the mark."
647 )
648 written = write_mark(
649 root,
650 package=package,
651 leg=leg,
652 seconds=seconds,
653 kind="accept",
654 by=by,
655 reason=reason.strip(),
656 )
657 if written:657 ↛ 658line 657 didn't jump to line 658 because the condition on line 657 was never true
658 fail(f"the mark was not written: {written}")
659 was = f"{mark.seconds:.1f}s" if mark is not None else "none"
660 return [
661 f" speed {package} on {leg}: mark {was} -> {seconds:.1f}s accepted by {by}",
662 f" reason: {reason.strip()}",
663 ]
664
665
666def render_marks(root: Path) -> list[str]:
667 """The marks beside the newest run's times, for ``fm ci.timings``."""
668 from livery.workshop._metrics import SERIES as METRICS
669
670 current, why = speed_marks(root)
671 if current is None:
672 return [f" speed marks: not read ({why})"]
673 if not current:
674 return [" speed marks: none yet; the gate job records one per package and leg"]
675 latest: dict[tuple[str, str], float] = {}
676 rows = METRICS.rows(state_store(root))
677 if not rows.failed and rows.rows:677 ↛ 683line 677 didn't jump to line 683 because the condition on line 677 was always true
678 newest = rows.rows[0].data
679 for job, row in (newest.get("jobs") or {}).items():
680 if isinstance(row, dict):680 ↛ 679line 680 didn't jump to line 679 because the condition on line 680 was always true
681 for package, (seconds, _tests) in _package_times(row).items():
682 latest[(package, leg_of(job, row))] = seconds
683 lines = [" speed marks", f" {'package on leg':<52} {'mark':>8} {'latest':>8}"]
684 for (package, leg), mark in sorted(current.items()):
685 now = latest.get((package, leg))
686 shown = f"{now:.1f}s" if now is not None else "-"
687 lines.append(
688 f" {f'{package} on {leg}'[:52]:<52} {mark.seconds:7.1f}s {shown:>8}"
689 f" {mark.kind} by {mark.by}"
690 )
691 return lines