Coverage for collectra/commons/results.py: 100.00%
75 statements
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-13 04:26 +0000
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-13 04:26 +0000
1"""The header of a results file, and how it is found, read and written.
3A results file begins with an entry that describes the file itself, declared
4like any other entry by its ``type``::
6 results:
7 type: collectra.Results
8 partition: validation
9 timestamp: '2026-02-13T17:36:26.080812'
11``Results`` can be subclassed to carry more, and a file's header is read back as
12the class its ``type`` names. The older ``collectra_results_metadata:`` mapping
13is still read, with a warning, and is replaced by the new entry the next time
14Collectra saves the file.
15"""
17from __future__ import annotations
19import warnings
20from datetime import datetime
21from pathlib import Path
22from typing import Any
24import pydantic
26from ..utils import load_class_from_string
28LEGACY_KEY = "collectra_results_metadata"
29HEADER_KEY = "results"
30HEADER_TYPE = "collectra.Results"
31# Where the header goes in a file that already has a node called ``results``.
32FALLBACK_KEY = "collectra_results"
34_warned = False
37class Results(pydantic.BaseModel):
38 """What a results file records about itself.
40 Subclass it to add fields; any other key in the entry is kept as well.
41 """
43 # Some results files have an unquoted version (e.g. `version: 1.0`), which
44 # YAML reads as a float rather than text.
45 model_config = pydantic.ConfigDict(coerce_numbers_to_str=True, extra="allow")
47 workflow: str | None = None
48 version: str | None = None
49 partition: str | None = None
50 timestamp: str | None = None
52 def model_dump(self, *args, **kwargs) -> dict:
53 """The attributes as written to a file: stamped now, without unset ones."""
54 data = super().model_dump(*args, **kwargs)
55 data["timestamp"] = datetime.now().isoformat()
56 for name in ("partition", "workflow", "version"):
57 if data[name] is None:
58 data.pop(name)
59 return data
61 def entry(self) -> dict:
62 """This header as the entry written at the top of a results file."""
63 cls = type(self)
64 path = HEADER_TYPE if cls is Results else f"{cls.__module__}.{cls.__qualname__}"
65 return {"type": path, **self.model_dump()}
68def is_header(value: Any) -> bool:
69 """Whether a results entry is the file's header rather than an artefact."""
70 if not isinstance(value, dict) or not isinstance(value.get("type"), str):
71 return False
72 declared = value["type"]
73 if declared == HEADER_TYPE:
74 return True
75 if declared.startswith("collectra."):
76 return False # one of the built-in artefacts: no need to load it
77 try:
78 cls = load_class_from_string(declared)
79 except (ImportError, AttributeError, ValueError):
80 return False
81 return isinstance(cls, type) and issubclass(cls, Results)
84def _find(data: dict) -> str | None:
85 """The key of the header: the old mapping, else the first header entry."""
86 if LEGACY_KEY in data:
87 return LEGACY_KEY
88 return next((key for key, value in data.items() if is_header(value)), None)
91def _warn_legacy(source: str | Path | None) -> None:
92 """Say once, not for every file, that the old header is deprecated."""
93 global _warned
94 if _warned:
95 return
96 _warned = True
97 where = f" (first seen in {source})" if source else ""
98 warnings.warn(
99 f"Results files with a {LEGACY_KEY!r} header are deprecated{where}. The "
100 f"header is now an entry such as '{HEADER_KEY}: {{type: {HEADER_TYPE}, "
101 "partition: ...}'. Files are updated when Collectra next saves them. "
102 "This warning is shown once.",
103 FutureWarning,
104 stacklevel=3,
105 )
108def pop_header(data: dict, source: str | Path | None = None) -> Results:
109 """Remove the header from ``data`` and return it (empty if there is none)."""
110 key = _find(data)
111 if key is None:
112 return Results()
113 entry = data.pop(key)
114 if key == LEGACY_KEY:
115 _warn_legacy(source)
116 return Results(**(entry or {}))
117 entry = dict(entry)
118 declared = entry.pop("type")
119 cls = Results if declared == HEADER_TYPE else load_class_from_string(declared)
120 return cls(**entry)
123def peek_header(data: dict, source: str | Path | None = None) -> Results:
124 """The header of ``data``, leaving ``data`` as it is."""
125 return pop_header(dict(data), source)
128def put_header(header: Results, data: dict) -> dict:
129 """``data`` with ``header`` as its first entry, in the current form."""
130 key = FALLBACK_KEY if HEADER_KEY in data else HEADER_KEY
131 return {key: header.entry(), **data}
134def upgrade_header(data: dict) -> dict | None:
135 """``data`` with an old-style header turned into the current entry.
137 The header's values, timestamp included, are kept as they are. Returns None
138 when there is no old-style header, so there is nothing to change.
139 """
140 if LEGACY_KEY not in data:
141 return None
142 rest = {key: value for key, value in data.items() if key != LEGACY_KEY}
143 key = FALLBACK_KEY if HEADER_KEY in rest else HEADER_KEY
144 return {key: {"type": HEADER_TYPE, **(data[LEGACY_KEY] or {})}, **rest}