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

Measured by coverage.py 7.16.2 on CPython 3.14 while the suites of tests, packages/workshop/tests/test_workshop_workflow.py, packages/workshop/tests/test_workshop_words.py, packages/workshop/tests/test_workshop_without_docs.py, packages/workshop/tests/test_workshop_walk.py, packages/workshop/tests/test_workshop_vocabulary.py, packages/workshop/tests/test_workshop_versions.py, packages/workshop/tests/test_workshop_variables.py, packages/workshop/tests/test_workshop_update.py, packages/workshop/tests/test_workshop_traces.py, packages/workshop/tests/test_workshop_test_reads.py, packages/workshop/tests/test_workshop_test_guard.py, packages/workshop/tests/test_workshop_templates.py, packages/workshop/tests/test_workshop_sync_locked.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_submit.py, packages/workshop/tests/test_workshop_store_tasks.py, packages/workshop/tests/test_workshop_steps.py, packages/workshop/tests/test_workshop_speed.py, packages/workshop/tests/test_workshop_skip_marks.py, packages/workshop/tests/test_workshop_shipped_files.py, packages/workshop/tests/test_workshop_shells.py, packages/workshop/tests/test_workshop_shard.py, packages/workshop/tests/test_workshop_security.py, packages/workshop/tests/test_workshop_schema.py, packages/workshop/tests/test_workshop_scale.py, packages/workshop/tests/test_workshop_runtime_language.py, packages/workshop/tests/test_workshop_runs.py, packages/workshop/tests/test_workshop_run.py, packages/workshop/tests/test_workshop_root_attribution.py, packages/workshop/tests/test_workshop_repair.py, packages/workshop/tests/test_workshop_render.py, packages/workshop/tests/test_workshop_release_render.py, packages/workshop/tests/test_workshop_release_point.py, packages/workshop/tests/test_workshop_release_fresh.py, packages/workshop/tests/test_workshop_release_driver.py, packages/workshop/tests/test_workshop_release.py, packages/workshop/tests/test_workshop_registries.py, packages/workshop/tests/test_workshop_regions.py, packages/workshop/tests/test_workshop_queries.py, packages/workshop/tests/test_workshop_quality.py, packages/workshop/tests/test_workshop_pythons.py, packages/workshop/tests/test_workshop_publish.py, packages/workshop/tests/test_workshop_provenance.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_proof_pins.py, packages/workshop/tests/test_workshop_points_contributed.py, packages/workshop/tests/test_workshop_points.py, packages/workshop/tests/test_workshop_plugin_tools.py, packages/workshop/tests/test_workshop_phases.py, packages/workshop/tests/test_workshop_phase_verbs.py, packages/workshop/tests/test_workshop_package_templates.py, packages/workshop/tests/test_workshop_package_level_fragments.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_lifecycle.py, packages/workshop/tests/test_workshop_layering.py, packages/workshop/tests/test_workshop_issue.py, packages/workshop/tests/test_workshop_isolated.py, packages/workshop/tests/test_workshop_invoke.py, packages/workshop/tests/test_workshop_inputs_pins.py, packages/workshop/tests/test_workshop_influence.py, packages/workshop/tests/test_workshop_identity.py, packages/workshop/tests/test_workshop_groups.py, packages/workshop/tests/test_workshop_graph.py, packages/workshop/tests/test_workshop_governance.py, packages/workshop/tests/test_workshop_fragments.py, packages/workshop/tests/test_workshop_footprint.py, packages/workshop/tests/test_workshop_fold.py, packages/workshop/tests/test_workshop_fallbacks.py, packages/workshop/tests/test_workshop_extensions.py, packages/workshop/tests/test_workshop_extension_mount.py, packages/workshop/tests/test_workshop_env.py, packages/workshop/tests/test_workshop_entry.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_doctor_unlisted.py, packages/workshop/tests/test_workshop_doctor.py, packages/workshop/tests/test_workshop_dispatch.py, packages/workshop/tests/test_workshop_dev_release.py, packages/workshop/tests/test_workshop_declaration.py, packages/workshop/tests/test_workshop_currency.py, packages/workshop/tests/test_workshop_credential_traces.py, packages/workshop/tests/test_workshop_cpp_kind.py, packages/workshop/tests/test_workshop_contributed_jobs.py, packages/workshop/tests/test_workshop_contract_file.py, packages/workshop/tests/test_workshop_contract.py, packages/workshop/tests/test_workshop_conformance.py, packages/workshop/tests/test_workshop_composition.py, packages/workshop/tests/test_workshop_commit.py, packages/workshop/tests/test_workshop_claims.py, packages/workshop/tests/test_workshop_ci_context.py, packages/workshop/tests/test_workshop_categories.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/workshop/tests/test_tools_restub.py, packages/workshop/tests/test_tools_materialise.py, packages/workshop/tests/test_kind_tools.py, packages/extensions/ty/tests/test_ty.py, packages/extensions/ruff/tests/test_ruff.py, packages/extensions/python/tests/test_speed.py, packages/extensions/python/tests/test_runner_terminal.py, packages/extensions/python/tests/test_release_driver.py, packages/extensions/python/tests/test_quality.py, packages/extensions/python/tests/test_python_phases.py, packages/extensions/python/tests/test_python_layering.py, packages/extensions/python/tests/test_private_reaches.py, packages/extensions/python/tests/test_plugin_reaches.py, packages/extensions/python/tests/test_extensions_python.py, packages/extensions/python/tests/test_examples.py, packages/extensions/python/tests/test_declared_imports.py, packages/extensions/pytest/tests/test_pytest_observer_shadow.py, packages/extensions/pytest/tests/test_pytest_observer_runner.py, packages/extensions/pytest/tests/test_pytest_observer.py, packages/extensions/pytest/tests/test_pytest_coverage.py, packages/extensions/pytest/tests/test_pytest_c6_selection.py, packages/extensions/pytest/tests/test_pytest_c5_repeats.py, packages/extensions/pytest/tests/test_pytest_c4_reads.py, packages/extensions/pytest/tests/test_pytest.py, packages/extensions/pyrefly/tests/test_pyrefly.py, packages/extensions/nanobind/tests/test_nanobind_kind.py, packages/extensions/nanobind/tests/test_kind_publish.py, packages/extensions/nanobind/tests/test_extensions_nanobind.py, packages/extensions/mypy/tests/test_mypy.py, packages/extensions/mkdocstrings/tests/test_mkdocstrings_refs.py, packages/extensions/mkdocstrings/tests/test_mkdocstrings_docstrings.py, packages/extensions/mkdocstrings/tests/test_mkdocstrings_digests.py, packages/extensions/mkdocstrings/tests/test_mkdocstrings.py, packages/extensions/lfs/tests/test_lfs.py, packages/extensions/docs/tests/test_taskref.py, packages/extensions/docs/tests/test_task_links.py, packages/extensions/docs/tests/test_llms.py, packages/extensions/docs/tests/test_influence.py, packages/extensions/docs/tests/test_groups.py, packages/extensions/docs/tests/test_extensions_docs.py, packages/extensions/docs/tests/test_docs_verbs.py, packages/extensions/docs/tests/test_docs_site.py, packages/extensions/docs/tests/test_docs_phase.py, packages/extensions/docs/tests/test_docs_contract.py, packages/extensions/docs/tests/test_docs.py, packages/extensions/docs/tests/test_doc_steps.py, packages/extensions/cpp/tests/test_extensions_cpp.py, packages/extensions/coverage/tests/test_parts.py, packages/extensions/coverage/tests/test_extensions_coverage.py, packages/extensions/coverage/tests/test_coverage_union_pins.py, packages/extensions/coverage/tests/test_coverage_store.py, packages/extensions/coverage/tests/test_coverage_proved_parts.py, packages/extensions/coverage/tests/test_coverage_pages.py, packages/extensions/coverage/tests/test_coverage_accept.py, packages/extensions/coverage/tests/test_coverage.py, packages/extensions/coverage/tests/test_affected_legs.py, packages/extensions/conan/tests/test_layering.py, packages/extensions/conan/tests/test_extensions_conan.py, packages/extensions/conan/tests/test_cross_kind.py, packages/extensions/conan/tests/test_conan_releases.py, packages/extensions/conan/tests/test_conan_publish.py, packages/extensions/conan/tests/test_conan_kind.py, packages/extensions/cmake/tests/test_measured_run.py, packages/extensions/cmake/tests/test_cpp_kind.py, packages/extensions/cmake/tests/test_coverage_parts.py, packages/extensions/cmake/tests/test_cmake.py, packages/extensions/clang-tidy/tests/test_clang_tidy.py, packages/extensions/clang-format/tests/test_clang_format.py, packages/extensions/changelog/tests/test_changelog.py, packages/extensions/basedpyright/tests/test_basedpyright.py, packages/extensions/agents/tests/test_agents.py ran.

1"""A check leg's shard: its spelling, its share of the items, and the durations.
2
3A platform's check leg may run as several shards, each on a runner of
4its own, each running a share of the items a test step partitions;
5pytest's items are test files. A shard is spelled ``<i>of<n>`` at the
6end of the leg's label, ``check-<os>-<python>-2of4``;
7the label without it is the platform leg, the key every record below
8the gate job's fold is kept by. [livery.workshop.Shard][] parses and
9spells one, [livery.workshop.platform_leg][] and
10[livery.workshop.shard_of][] split a label.
11
12The share is a function of its inputs: [livery.workshop.partition][]
13packs the items longest first into the shard with the least summed
14seconds, the first shard's sum starting at the head, so every shard of
15a run computes the same partition from the same set, the same
16durations and the same head, and every item lands in exactly one
17shard. The durations and the head are the medians
18[livery.workshop.read_durations][] takes over the newest rows of the
19platform leg's series in the [livery.workshop.DURATIONS][] family,
20bounded by the checkout's committer time
21([livery.workshop.checkout_time][]) so a row written while the run is
22in flight reaches no shard. A shard leaves what it partitioned in
23`SHARD_FILE`, under the checkout's ``.workshop/`` directory
24([livery.workshop.leave_shard][]), and the gate job reads it back
25([livery.workshop.read_shard][]) to prove the shards of a platform
26partitioned one set from one row.
27"""
28
29from __future__ import annotations
30
31import hashlib
32import json
33import re
34import statistics
35from collections import defaultdict
36from collections.abc import Iterable, Mapping
37from dataclasses import dataclass
38from datetime import UTC, datetime, timedelta
39from pathlib import Path
40from typing import Any
41
42from livery import git
43from livery.workshop._ci_context import state_store
44
45#: The durations rows' schema. A reader skips a row of another version
46#: and names it; a new field is the same version, a changed meaning is
47#: the next.
48SCHEMA = 1
49
50#: How many rows a platform leg's durations series keeps. Kept well above
51#: `LOOKBACK` so concurrent runs writing new rows never evict a row that
52#: an in-flight run's shards are reading under their checkout bound.
53WINDOW = 30
54
55#: How many newest rows before the checkout bound `read_durations` scans
56#: when collecting up to `NEWEST` observations per item. Staying well below
57#: `WINDOW` guarantees every shard and top-up step in a run reads the exact
58#: same rows list even when other runs append to the series mid-flight.
59LOOKBACK = 15
60
61#: How many of the newest rows before the bound a read takes the
62#: median over.
63NEWEST = 5
64
65#: The file a shard leaves under the checkout's ``.workshop/``
66#: directory, which git ignores, naming the shard it ran, the digest of
67#: the set it partitioned, its own items, the rows it read and the
68#: bound it read them under.
69SHARD_FILE = ".workshop/fm-shard.json"
70
71_SPELLING = re.compile(r"^(\d+)of(\d+)$")
72_TAIL = re.compile(r"^(?P<leg>.+)-(?P<shard>\d+of\d+)$")
73
74
75@dataclass(frozen=True)
76class Shard:
77 """One shard of a leg: which of how many, spelled ``<i>of<n>``.
78
79 Attributes:
80 index: The shard's number, from 1.
81 count: How many shards the leg runs as.
82
83 Raises:
84 ValueError: When the count is below 1, the index below 1, or
85 the index above the count.
86 """
87
88 index: int
89 count: int
90
91 def __post_init__(self) -> None:
92 why = _unsound(self.index, self.count)
93 if why:
94 raise ValueError(f"shard {self.index} of {self.count}: {why}")
95
96 @classmethod
97 def parse(cls, text: str) -> Shard:
98 """The shard *text* spells, ``2of4``.
99
100 Raises:
101 ValueError: When *text* is not of the form, naming it.
102 """
103 matched = _SPELLING.match(text)
104 if matched is None:
105 raise ValueError(
106 f"{text!r} is not a shard; a shard is spelled <i>of<n>, such as 2of4"
107 )
108 index, count = int(matched.group(1)), int(matched.group(2))
109 why = _unsound(index, count)
110 if why:
111 raise ValueError(f"{text!r} is not a shard: {why}")
112 return cls(index, count)
113
114 @property
115 def first(self) -> bool:
116 """Whether this is the first shard, the one that runs what is not split."""
117 return self.index == 1
118
119 def __str__(self) -> str:
120 return f"{self.index}of{self.count}"
121
122
123def _unsound(index: int, count: int) -> str:
124 if count < 1:
125 return "the count is at least 1"
126 if index < 1:
127 return "the index counts from 1"
128 if index > count:
129 return "the index is at most the count"
130 return ""
131
132
133#: The one shard of a leg that is not split.
134ONE = Shard(1, 1)
135
136
137def platform_leg(label: str) -> str:
138 """The leg *label* without its shard; a label without one is returned as it is.
139
140 ``check-windows-latest-3.14-2of4`` gives ``check-windows-latest-3.14``.
141 """
142 matched = _TAIL.match(label)
143 return matched.group("leg") if matched else label
144
145
146def shard_of(label: str) -> Shard:
147 """The shard the leg *label* ends in; `ONE` when it ends in none.
148
149 Raises:
150 ValueError: When the label ends in a shard spelling outside the
151 form, such as ``0of2``, naming it.
152 """
153 matched = _TAIL.match(label)
154 return Shard.parse(matched.group("shard")) if matched else ONE
155
156
157def partition(
158 items: Iterable[str],
159 durations: Mapping[str, float],
160 count: int,
161 *,
162 head: float = 0.0,
163) -> tuple[tuple[str, ...], ...]:
164 """Pack *items* into *count* shards by their *durations*, every item in exactly one.
165
166 The items go longest first, ties by name, each into the shard with
167 the least summed seconds so far, ties to the lowest shard. The
168 first shard's sum starts at *head* seconds, the time of the steps
169 it runs that the other shards leave to it, so its share of the
170 items is lighter by about that much; a head above every other
171 shard's final sum leaves the first shard no item. An item
172 *durations* does not name weighs the median of the named
173 durations, or one second when none are named. The result is a
174 function of the set, the durations and the head alone: the same
175 whatever order *items* comes in, and an item given twice is one
176 item. With more shards than items the surplus shards are empty.
177
178 Returns:
179 One tuple of items per shard, in the order the items were
180 packed.
181
182 Raises:
183 ValueError: When *count* is below 1, or *head* is below 0.
184 """
185 if count < 1:
186 raise ValueError(f"count is {count}; a partition has at least one shard")
187 if head < 0:
188 raise ValueError(f"head is {head}; a head is at least 0 seconds")
189 named = [float(seconds) for seconds in durations.values()]
190 fill = statistics.median(named) if named else 1.0
191
192 def weight(name: str) -> float:
193 seconds = durations.get(name)
194 return float(seconds) if seconds is not None else fill
195
196 ordered = sorted(set(items), key=lambda name: (-weight(name), name))
197 shards: list[list[str]] = [[] for _ in range(count)]
198 sums = [0.0] * count
199 sums[0] = float(head)
200 for name in ordered:
201 at = min(range(count), key=lambda index: (sums[index], index))
202 shards[at].append(name)
203 sums[at] += weight(name)
204 return tuple(tuple(shard) for shard in shards)
205
206
207def files_digest(files: Iterable[str]) -> str:
208 """A hex digest of the sorted names in *files*.
209
210 Two shards that partitioned one set have one digest, so the gate
211 job can prove they did.
212 """
213 text = "\n".join(sorted(set(files)))
214 return hashlib.sha256(text.encode("utf-8")).hexdigest()
215
216
217def _current_legs(root: Path) -> set[tuple[str, ...]] | None:
218 """The keys the matrix produces, one per check leg; ``None`` when unknown.
219
220 The contract or the matrix cannot be read, and then the janitor
221 drops nothing.
222 """
223 from livery.workshop import check_legs
224
225 try:
226 legs = check_legs(root)
227 except (Exception, SystemExit):
228 return None
229 return {(git.slug(leg),) for leg in legs}
230
231
232#: The family: one series per run, ``plan/<run>``, holding the planned
233#: shard count per platform leg written by ``fm ci.legs`` so the gate
234#: job's fold validates the exact shards started for the run. Swept
235#: after six hours alongside ``run/*``.
236PLANS: git.Keyed = git.Keyed(
237 "plan", ("run",), schema=SCHEMA, stale_after=timedelta(hours=6)
238)
239
240#: The file `PLANS` writes per run, holding ``{"schema": 1, "shards": {...}}``.
241PLAN_FILE = "plan.json"
242
243#: Fallback minimum summed test seconds worth splitting across more than
244#: one shard when no balance timing reading is available.
245MIN_SHARD_SECONDS = 60.0
246
247#: The family: one series per platform leg, ``durations/<leg>``, one row
248#: per run, ``{"run": "<id>", "items": {"<item>": <seconds>}, "head":
249#: <seconds>}``, written by the run's gate job from its shards' rows.
250#: ``head`` is the item seconds the first shard's unsplit steps stand
251#: for on the run ([livery.workshop._metrics.first_shard_head][]); a row
252#: without it reads as 0. A series of a leg the matrix no longer
253#: produces is the janitor's to drop.
254DURATIONS: git.Keyed = git.Keyed(
255 "durations", ("leg",), window=WINDOW, schema=SCHEMA, current=_current_legs
256)
257
258
259def _moment(stamp: str) -> datetime | None:
260 """The time *stamp* names, timezone-aware; ``None`` when it names none."""
261 if not stamp:
262 return None
263 try:
264 moment = datetime.fromisoformat(stamp)
265 except ValueError:
266 return None
267 return moment if moment.tzinfo is not None else moment.replace(tzinfo=UTC)
268
269
270def read_durations(
271 root: Path, leg: str, *, before: datetime
272) -> tuple[dict[str, float], float, tuple[str, ...], str]:
273 """The median seconds per item, and the head, of *leg*'s rows before *before*.
274
275 Scans *leg*'s ``durations/<platform leg>`` rows stamped before *before*
276 newest first across the retained window, keeping up to the newest `NEWEST`
277 observations for each item so narrowed or partial recent runs do not drop
278 durations for items that ran on earlier rows. The median of an item is over
279 the observations collected for it (at most `NEWEST`). The head is the median
280 over the newest `NEWEST` eligible rows' ``head``, a row without a number
281 there counting as 0, and is what [livery.workshop.partition][] starts the
282 first shard's sum at. The returned row names list every eligible row that
283 contributed at least one item observation or head reading, newest first. A
284 naive *before* is read as UTC.
285
286 Returns:
287 The seconds per item, the head in seconds, the names of the
288 rows read, newest first, and why the series could not be read.
289 A series that cannot be read is ``({}, 0.0, (), reason)``,
290 never a raise: the caller runs as one shard of one and says
291 so. An absent series is ``({}, 0.0, (), "")``.
292 """
293 bound = before if before.tzinfo is not None else before.replace(tzinfo=UTC)
294 series = DURATIONS.series(platform_leg(leg))
295 found = series.rows(state_store(root))
296 if found.failed:
297 return {}, 0.0, (), found.reason
298 eligible: list[git.Row] = []
299 for row in found.rows:
300 when = _moment(row.when)
301 if when is None or when >= bound:
302 continue
303 eligible.append(row)
304 if len(eligible) >= LOOKBACK:
305 break
306 seen: dict[str, list[float]] = defaultdict(list)
307 used: list[str] = []
308 head_rows = eligible[:NEWEST]
309 for index, row in enumerate(eligible):
310 contributed = index < NEWEST
311 held: Any = row.data.get("items")
312 if isinstance(held, dict):
313 for name, seconds in held.items():
314 if isinstance(seconds, int | float) and not isinstance(seconds, bool):
315 key = str(name)
316 values = seen[key]
317 if len(values) < NEWEST:
318 values.append(float(seconds))
319 contributed = True
320 if contributed:
321 used.append(row.name)
322 medians = {
323 name: round(statistics.median(values), 1)
324 for name, values in sorted(seen.items())
325 }
326 heads = [_seconds(row.data.get("head")) for row in head_rows]
327 head = round(statistics.median(heads), 1) if heads else 0.0
328 return medians, head, tuple(used), ""
329
330
331def _seconds(value: Any) -> float:
332 """*value* as seconds when it is a number of at least 0; else 0."""
333 if isinstance(value, bool) or not isinstance(value, int | float):
334 return 0.0
335 return max(0.0, float(value))
336
337
338def checkout_time(root: Path) -> datetime:
339 """The committer time of HEAD's commit in the checkout at *root*, timezone-aware.
340
341 Every shard of a run checks out the same commit, so this bounds
342 the durations rows every shard reads without a call to the forge.
343
344 Raises:
345 GitError: When HEAD names no commit.
346 """
347 spelled = git.run(root, "log", "-1", "--format=%cI", "HEAD").strip()
348 return datetime.fromisoformat(spelled)
349
350
351@dataclass(frozen=True)
352class ShardMarker:
353 """What a shard left in `SHARD_FILE`: what it ran and what it partitioned from.
354
355 Attributes:
356 shard: The shard the leg ran as.
357 digest: The digest of the set it partitioned,
358 [livery.workshop.files_digest][] of every item of every
359 shard.
360 items: The items this shard ran, in packing order; pytest's
361 are test files.
362 rows: The durations rows it read, newest first.
363 before: The bound it read them under, the checkout's committer
364 time.
365 suites: The units whose items were in the set, by path. A
366 unit the record does not name ran whole on the first shard,
367 with every step that does not read the shard, so the first
368 shard leaves its parts. A record written without the key
369 names none.
370 attempt: The attempt of the run the shard ran in, as the runner
371 counts them ([livery.workshop.RunContext][]'s ``attempt``);
372 empty when the runner did not say, and for a record written
373 without the key. Two shards of one platform from two
374 attempts partitioned from the record as it was each time,
375 which the fold names when their partitions differ.
376 """
377
378 shard: Shard
379 digest: str
380 items: tuple[str, ...]
381 rows: tuple[str, ...]
382 before: datetime
383 suites: tuple[str, ...] = ()
384 attempt: str = ""
385
386
387def marker_fields(marker: ShardMarker) -> dict[str, Any]:
388 """*marker* as `SHARD_FILE` holds it, and a leg's row under ``shard``."""
389 return {
390 "shard": str(marker.shard),
391 "digest": marker.digest,
392 "items": list(marker.items),
393 "rows": list(marker.rows),
394 "before": marker.before.isoformat(),
395 "suites": list(marker.suites),
396 "attempt": marker.attempt,
397 }
398
399
400def parse_marker(loaded: Any, *, source: str) -> tuple[ShardMarker | None, str]:
401 """The record *loaded* holds, as `marker_fields` wrote it; or why it is none.
402
403 *source* names where it came from, for the reason.
404
405 Returns:
406 ``(record, "")`` when it reads; ``(None, reason)`` when *loaded*
407 is not a record.
408 """
409 if not isinstance(loaded, dict):
410 return None, f"{source} is not a JSON object"
411 try:
412 shard = Shard.parse(str(loaded.get("shard", "")))
413 except ValueError as error:
414 return None, f"{source}: {error}"
415 stamp = str(loaded.get("before", "") or "")
416 before = _moment(stamp)
417 if before is None:
418 return None, f"{source}: {stamp!r} is not a time"
419 return ShardMarker(
420 shard=shard,
421 digest=str(loaded.get("digest", "") or ""),
422 items=tuple(str(name) for name in loaded.get("items", []) or []),
423 rows=tuple(str(name) for name in loaded.get("rows", []) or []),
424 before=before,
425 suites=tuple(str(name) for name in loaded.get("suites", []) or []),
426 attempt=str(loaded.get("attempt", "") or ""),
427 ), ""
428
429
430def leave_shard(
431 root: Path,
432 *,
433 shard: Shard,
434 digest: str,
435 items: Iterable[str],
436 rows: Iterable[str],
437 before: datetime,
438 suites: Iterable[str] = (),
439 attempt: str = "",
440) -> Path:
441 """Leave the shard's record in `SHARD_FILE` at *root*, for the gate job's proof.
442
443 *suites* names the units whose items are in the set; a unit
444 left out ran whole on the first shard. *attempt* is the run's
445 attempt the shard ran in, the run context's; empty when unknown.
446 The leg's one write copies the record into its timing row under
447 ``shard``, where the gate job's fold reads it.
448
449 Returns:
450 The path of the file left.
451 """
452 path = root / SHARD_FILE
453 path.parent.mkdir(parents=True, exist_ok=True)
454 marker = ShardMarker(
455 shard, digest, tuple(items), tuple(rows), before, tuple(suites), attempt
456 )
457 path.write_text(json.dumps(marker_fields(marker), sort_keys=True), encoding="utf-8")
458 return path
459
460
461def read_shard(root: Path) -> tuple[ShardMarker | None, str]:
462 """Read the record a shard left in `SHARD_FILE` at *root*.
463
464 Returns:
465 ``(record, "")`` when it reads; ``(None, "")`` when there is no
466 file; ``(None, reason)`` when the file is not a record.
467 """
468 path = root / SHARD_FILE
469 if not path.is_file():
470 return None, ""
471 try:
472 loaded: Any = json.loads(path.read_text("utf-8"))
473 except (OSError, ValueError) as error:
474 return None, f"{SHARD_FILE} does not parse ({error})"
475 return parse_marker(loaded, source=SHARD_FILE)
476
477
478def shards_for_selection(
479 selected_items: Iterable[str],
480 all_items: Iterable[str],
481 durations: Mapping[str, float],
482 *,
483 max_shards: int,
484 fixed: float = 0.0,
485 other: float = 0.0,
486 speed: float = 0.0,
487) -> int:
488 """How many shards a platform leg needs for *selected_items*, within *max_shards*.
489
490 A full un-narrowed selection (every item of *all_items* selected)
491 keeps *max_shards* (clamped to item count when fewer than
492 *max_shards* items exist). When narrowed, if balance measures
493 (*fixed* setup seconds and *speed* test parallelism) are available,
494 applies the balancer's wall model ``F + max(O, (S / p + O) / n)`` and
495 adds a shard only while it saves at least *fixed* seconds. Without a
496 balance reading, scales proportionally by summed item durations
497 (staying at 1 when summed seconds fit within `MIN_SHARD_SECONDS`), or
498 by item share when no durations exist yet.
499
500 Raises:
501 ValueError: When *max_shards* is below 1 or any timing measure is
502 negative.
503 """
504 if max_shards < 1:
505 raise ValueError(f"max_shards is {max_shards}; a leg needs at least one shard")
506 if fixed < 0 or other < 0 or speed < 0:
507 raise ValueError("fixed, other, and speed must be non-negative")
508 selected = set(selected_items)
509 total = set(all_items)
510 if max_shards == 1 or len(selected) <= 1:
511 return 1
512 cap = min(max_shards, len(selected))
513 if total and selected >= total:
514 return cap
515 named = [float(seconds) for seconds in durations.values() if seconds >= 0]
516 fill = statistics.median(named) if named else 1.0
517
518 def weight(name: str) -> float:
519 seconds = durations.get(name)
520 return float(seconds) if seconds is not None else fill
521
522 selected_seconds = sum(weight(name) for name in selected)
523 if fixed > 0.0 and speed > 0.0:
524
525 def _wall(n: int) -> float:
526 return fixed + max(other, (selected_seconds / speed + other) / n)
527
528 count = 1
529 for n in range(2, cap + 1):529 ↛ 534line 529 didn't jump to line 534 because the loop on line 529 didn't complete
530 if _wall(n - 1) - _wall(n) >= fixed:
531 count = n
532 else:
533 break
534 return count
535 if durations:
536 if selected_seconds <= MIN_SHARD_SECONDS:
537 return 1
538 total_seconds = sum(weight(name) for name in total) if total else 0.0
539 if total_seconds > 0.0:539 ↛ 542line 539 didn't jump to line 542 because the condition on line 539 was always true
540 scaled = round(max_shards * (selected_seconds / total_seconds))
541 return min(cap, max(1, scaled))
542 return min(cap, max(1, round(selected_seconds / MIN_SHARD_SECONDS)))
543 if total:543 ↛ 546line 543 didn't jump to line 546 because the condition on line 543 was always true
544 scaled = round(max_shards * (len(selected) / len(total)))
545 return min(cap, max(1, scaled))
546 return 1 if len(selected) <= 5 else cap
547
548
549@dataclass(frozen=True)
550class VerifiedPlan:
551 """Verified-tree metadata on ``plan/<run_id>`` when ``ci.legs`` skipped checks."""
552
553 tree: str
554 branch: str
555 run: str
556
557
558def write_shard_plan(
559 root: Path,
560 run_id: str,
561 counts: Mapping[str, int],
562 *,
563 store: git.StateStore | None = None,
564 verified_tree: str = "",
565 verified_branch: str = "",
566 verified_run: str = "",
567) -> str:
568 """Write planned shard counts per platform leg onto ``plan/<run_id>``."""
569 target_store = state_store(root) if store is None else store
570 payload: dict[str, Any] = {
571 "schema": SCHEMA,
572 "shards": dict(sorted(counts.items())),
573 }
574 if verified_tree:
575 payload["verified_tree"] = verified_tree
576 payload["verified_branch"] = verified_branch
577 payload["verified_run"] = verified_run
578 return PLANS.series(run_id).put(
579 target_store,
580 {PLAN_FILE: payload},
581 message=f"plan: run {run_id}, {len(counts)} leg(s)",
582 )
583
584
585def read_verified_plan(
586 root: Path,
587 run_id: str,
588 *,
589 store: git.StateStore | None = None,
590) -> tuple[VerifiedPlan | None, str]:
591 """Read verified-tree metadata from ``plan/<run_id>``; ``(None, "")`` if absent."""
592 if not run_id:592 ↛ 593line 592 didn't jump to line 593 because the condition on line 592 was never true
593 return None, ""
594 target_store = state_store(root) if store is None else store
595 found, why = PLANS.series(run_id).row(target_store, PLAN_FILE)
596 if why:
597 return None, why
598 if found is None:
599 return None, ""
600 tree = str(found.data.get("verified_tree", "") or "")
601 if not tree:
602 return None, ""
603 return (
604 VerifiedPlan(
605 tree=tree,
606 branch=str(found.data.get("verified_branch", "") or ""),
607 run=str(found.data.get("verified_run", "") or ""),
608 ),
609 "",
610 )
611
612
613def read_shard_plan(
614 root: Path,
615 run_id: str,
616 *,
617 store: git.StateStore | None = None,
618) -> tuple[dict[str, int] | None, str]:
619 """Read planned shard counts per platform leg for *run_id*; empty when absent."""
620 target_store = state_store(root) if store is None else store
621 found, why = PLANS.series(run_id).row(target_store, PLAN_FILE)
622 if why:622 ↛ 623line 622 didn't jump to line 623 because the condition on line 622 was never true
623 return None, why
624 if found is None:
625 return None, ""
626 raw = found.data.get("shards")
627 if not isinstance(raw, Mapping):
628 return None, f"plan/{run_id}: {PLAN_FILE} carries no shards map"
629 counts: dict[str, int] = {}
630 for leg, value in raw.items():
631 if isinstance(value, bool) or not isinstance(value, int) or value < 1:
632 return None, f"plan/{run_id}: invalid shard count {value!r} for {leg}"
633 counts[str(leg)] = value
634 return counts, ""