ci: run the tests in parallel jobs and speed up the Sphinx build

The single test job ran all tests one after the other on one runner,
including the Sphinx build and the Docker checks (11-19 min). It is now
split so that every test still runs exactly once:

- docs-test, docker-test: the Sphinx build (new marker "docs") and the
  Docker / Home Assistant add-on checks ("docker") in jobs of their own.
- test-server: the tests that start EOS or EOSdash on the fixed ports.
  The collection hook marks every test that uses the xprocess fixture
  with "eos_server" and puts them into one xdist group, so
  "pytest -n auto --dist loadgroup" also works locally. A test that
  binds the ports without a fixture carries the marker itself.
- test-shard: all other tests in four shards of about equal runtime
  (scripts/shard_test_files.py, runtimes in scripts/test_durations.json),
  each with pytest-xdist.
- test-count: fails if these parts do not add up to the tests of one
  plain run.
- test: keeps the name of the required check. It prints the combined
  coverage report and fails if any of the jobs above failed.

COVERAGE_CORE=sysmon measures line coverage through sys.monitoring:
the report is the same, the test time drops by about a third. The
combined report misses 1-3 statements more than a single run, in lines
that only run when a test finds state left by an earlier test.

The Sphinx build spent 74 % of its time in one search of
PythonDomain.find_obj (sphinx-doc/sphinx#11282). The local extension
docs/_ext/pyxrefindex.py answers it from an index of name endings with
the same matches in the same order; a build has a byte-identical
objects.inv. It copies the logic of Sphinx 9.0.4 and is only active for
that version; TestPyXrefIndex compares it with the installed Sphinx and
fails after a Sphinx update until the version is raised. The
documentation test builds with -j (up to four jobs); its pages can
differ from a serial build in the target of ambiguous cross-references.
Read the Docs builds without -j. Sphinx build on GitHub runners:
427-480 s -> 180-233 s.

make test-ci runs the commands of these jobs one after the other.

On GitHub runners the tests are done after about 2 minutes; the
required check ends with docs-test after about 4-5 minutes.

Additional changes
Add pytest-xdist to the development dependencies
List the 25 slowest tests in each test job (--durations=25)
Test version() directly; it was covered only through the Sphinx test
Add a "Keep Tests Fast" tip, the server marker rule, the extension and
test-ci to the development guide and the testing skill

Refs #1553

Co-authored-by: SchaafAlexander <86607129+SchaafAlexander@users.noreply.github.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Signed-off-by: SchaafAlexander <86607129+SchaafAlexander@users.noreply.github.com>
Assisted-by: Claude Code (claude-opus-5-5)
Assisted-by: Claude Code (claude-fable-5-2)
This commit is contained in:
Christin
2026-11-20 07:15:33 +01:00
committed by Bobby Noelte
co-authored by SchaafAlexander Claude Opus 5.5
parent e2726354c2
commit 57905b2024
16 changed files with 1284 additions and 8 deletions
+176
View File
@@ -0,0 +1,176 @@
"""Speed up Python cross-reference resolution with a suffix index.
Sphinx resolves most Python cross-references in "fuzzy" search mode (every
reference created from a type annotation carries ``refspecific``). For a name
that is not found exactly, ``PythonDomain.find_obj`` then scans *all* known
objects for names ending in ``.<name>`` (sphinx/domains/python/__init__.py,
fuzzy branch of ``find_obj``). With the EOS API reference (about 22,000 objects
and 150,000 references) this linear scan takes about three quarters of the whole
documentation build, see https://github.com/sphinx-doc/sphinx/issues/11282.
This extension replaces the Python domain with a subclass that answers the
fuzzy search from an index instead of a scan. ``oname.endswith("." + name)``
holds exactly when ``name`` follows one of the dots in ``oname``, so the index
maps every such suffix to the object names, in the iteration order of the
domain's objects. The search therefore returns the same matches in the same
order as Sphinx, including the first match that Sphinx picks for an ambiguous
name. The rendered documentation does not change.
The subclass copies the logic of ``find_obj`` from the Sphinx version in
``VERIFIED_SPHINX_VERSION``. For any other Sphinx version the extension does
nothing and logs a note; ``TestPyXrefIndex`` in ``tests/test_docsphinx.py``
checks the equivalence against the installed Sphinx and must pass before the
version is raised.
"""
from collections.abc import Set
from typing import Any
import sphinx
from sphinx.application import Sphinx
from sphinx.domains.python import ObjectEntry, PythonDomain
from sphinx.environment import BuildEnvironment
from sphinx.util import logging
logger = logging.getLogger(__name__)
#: Sphinx version whose ``PythonDomain.find_obj`` this extension reproduces.
VERIFIED_SPHINX_VERSION: tuple[int, int, int] = (9, 0, 4)
class IndexedPythonDomain(PythonDomain):
"""Python domain whose fuzzy object search uses a suffix index.
The index is built on the first fuzzy search and dropped whenever the
domain changes its objects (``note_object``, ``clear_doc``,
``merge_domaindata``); Sphinx changes them nowhere else. As a second line
of defence the index is rebuilt when the number of objects differs from
the indexed one. A direct change of the objects mapping that keeps their
number is not noticed.
"""
_suffix_index: tuple[int, dict[str, list[str]]] | None = None
def _drop_suffix_index(self) -> None:
"""Forget the suffix index; the next fuzzy search rebuilds it."""
self._suffix_index = None
def _suffixes(self) -> dict[str, list[str]]:
"""Return the suffix index of the current objects.
Returns:
Mapping of every text that follows a dot in an object name to the
object names with that ending, in the order of ``self.objects``.
"""
objects = self.objects
if self._suffix_index is not None and self._suffix_index[0] == len(objects):
return self._suffix_index[1]
index: dict[str, list[str]] = {}
for oname in objects:
pos = oname.find(".")
while pos != -1:
index.setdefault(oname[pos + 1 :], []).append(oname)
pos = oname.find(".", pos + 1)
self._suffix_index = (len(objects), index)
return index
def note_object(
self,
name: str,
objtype: str,
node_id: str,
aliased: bool = False,
location: Any = None,
) -> None:
"""Note a Python object for cross-reference and drop the index."""
self._drop_suffix_index()
super().note_object(name, objtype, node_id, aliased=aliased, location=location)
def clear_doc(self, docname: str) -> None:
"""Remove the objects of ``docname`` and drop the index."""
self._drop_suffix_index()
super().clear_doc(docname)
def merge_domaindata(self, docnames: Set[str], otherdata: dict[str, Any]) -> None:
"""Merge objects from a parallel read process and drop the index."""
self._drop_suffix_index()
super().merge_domaindata(docnames, otherdata)
def find_obj(
self,
env: BuildEnvironment,
modname: str,
classname: str,
name: str,
type: str | None,
searchmode: int = 0,
) -> list[tuple[str, ObjectEntry]]:
"""Find a Python object like ``PythonDomain.find_obj``.
Only the fuzzy branch of search mode 1 differs: it looks the name up in
the suffix index instead of scanning all objects.
Args:
env: The build environment.
modname: Module of the reference, if any.
classname: Class of the reference, if any.
name: Target name of the reference.
type: Role of the reference, or ``None`` for any object type.
searchmode: 1 for references marked ``refspecific``, else 0.
Returns:
Matching ``(name, object entry)`` pairs, in Sphinx's order.
"""
if searchmode != 1:
return super().find_obj(env, modname, classname, name, type, searchmode)
name = name.removesuffix("()")
if not name:
return []
if type is None:
objtypes: list[str] | None = list(self.object_types)
else:
objtypes = self.objtypes_for_role(type)
if objtypes is None:
return []
objects = self.objects
if modname and classname:
fullname = f"{modname}.{classname}.{name}"
if fullname in objects and objects[fullname].objtype in objtypes:
return [(fullname, objects[fullname])]
if (
modname
and f"{modname}.{name}" in objects
and objects[f"{modname}.{name}"].objtype in objtypes
):
return [(f"{modname}.{name}", objects[f"{modname}.{name}"])]
if name in objects and objects[name].objtype in objtypes:
return [(name, objects[name])]
return [
(oname, objects[oname])
for oname in self._suffixes().get(name, ())
if objects[oname].objtype in objtypes
]
def setup(app: Sphinx) -> dict[str, Any]:
"""Install the indexed Python domain if the Sphinx version is verified.
Args:
app: The Sphinx application.
Returns:
Extension metadata; the extension is safe for parallel builds.
"""
if tuple(sphinx.version_info[:3]) == VERIFIED_SPHINX_VERSION:
app.add_domain(IndexedPythonDomain, override=True)
else:
logger.info(
"pyxrefindex: Sphinx %s is not the verified version %s; "
"using the unindexed Python cross-reference search.",
sphinx.__display_version__,
".".join(map(str, VERIFIED_SPHINX_VERSION)),
)
return {"parallel_read_safe": True, "parallel_write_safe": True}
+3
View File
@@ -11,6 +11,8 @@ from pathlib import Path
PROJECT_ROOT = Path(__file__).parent.parent
SRC_DIR = PROJECT_ROOT / "src"
sys.path.insert(0, str(SRC_DIR))
# Local Sphinx extensions
sys.path.insert(0, str(Path(__file__).parent / "_ext"))
# Tell akkudoktoreos that it is imported for the documentation build
# (see ConfigEOS.documentation_mode()).
@@ -38,6 +40,7 @@ extensions = [
"myst_parser",
"sphinx_tabs.tabs",
"sphinxcontrib.mermaid",
"pyxrefindex", # faster Python cross-reference search, see docs/_ext/pyxrefindex.py
]
templates_path = ["_templates"]
+64
View File
@@ -600,6 +600,70 @@ Ensure your changes do not break existing functionality:
make test
```
### Keep Tests Fast
Keep each test case well under a second:
- Do not wait in real time (no `sleep` or wait loops); use synthetic timestamps instead.
- Do not `parametrize` the full cartesian product of independent axes.
- Extend an existing parametrized test before writing a new one.
The CI logs of the `test-shard` and `test-server` jobs list their 25 slowest tests
(`--durations=25`). The Sphinx documentation build and the Docker checks run in their own CI
jobs. Run them locally with `uv run pytest --finalize -m docs` and
`uv run pytest --finalize -m docker` (the Docker checks need a running Docker engine).
The Sphinx build resolves Python cross-references through the local extension
`docs/_ext/pyxrefindex.py`. It answers a search that Sphinx runs over all documented objects from
an index; the generated pages stay the same (see
[sphinx-doc/sphinx#11282](https://github.com/sphinx-doc/sphinx/issues/11282)). The extension is
only active for the Sphinx version it was verified with. After a Sphinx update, `TestPyXrefIndex`
in `tests/test_docsphinx.py` fails until the version in the extension is raised.
The documentation test builds with up to four parallel jobs (`sphinx-build -j`), and so do
`make docs` and `make read-docs`, which run this test. A parallel build can link a cross-reference
with an ambiguous name to another object of the same name than a build with one process.
CI runs every test exactly once, spread over several jobs:
- `test-shard`: the tests that do not start a server, in four shards of about equal runtime, each
with pytest-xdist on all cores of its runner.
- `test-server`: the tests with the `eos_server` marker, one after the other.
- `test-count`: fails if these parts do not add up to the tests of one plain run, or if the
marker of the server tests is no longer derived from the fixture.
- `test`: prints the coverage report of all parts. It is the required check and fails if one of
these jobs, `docs-test` or `docker-test` failed.
`make test-ci` runs the tests of the jobs `test-server`, `test-shard`, `docs-test` and
`docker-test` locally, with the markers and options of these jobs and one part after the other:
the server tests, the other tests with pytest-xdist on all cores (not split into shards), the
Sphinx build and the Docker checks. It prints the coverage report of the first two parts and stops
at the first part that fails. The browser tests of the `browser-test` job have their own target,
`make test-browser`.
The coverage report of the `test` job is combined from the parts. It differs from the report of
one plain run in a few lines, and not in exactly the same ones in every run: lines that are only
executed when a test finds state left by an earlier test of the same process. With pytest-xdist
the order of the tests in a worker changes from run to run. When the layout was introduced, three
runs missed 4523 to 4525 statements out of 26154, one plain run 4522.
`scripts/shard_test_files.py` distributes the test modules to the shards by the runtimes in
`scripts/test_durations.json`. Outdated runtimes only cost balance; a module without an entry
counts one second. To rebalance, download the `junit-shard-*` artifacts of a CI run and call
`uv run python scripts/shard_test_files.py --update junit-shard-*.xml`.
CI measures coverage with the `sys.monitoring` core of coverage.py (`COVERAGE_CORE=sysmon`).
The report is the same as with the default tracer, but a coverage run takes about a third less
time. Set the variable for local coverage runs as well. On Python 3.13 this core does not measure
branch coverage: with `--cov-branch`, coverage.py falls back to the default tracer.
Run the tests in parallel with `uv run pytest -n auto --dist loadgroup` (pytest-xdist). The tests
that start a real EOS or EOSdash server listen on fixed ports and must not run next to each
other. They carry the `eos_server` marker, set automatically for every test that uses the
`xprocess` fixture, and share one xdist group, which `--dist loadgroup` keeps on one worker.
Without `--dist loadgroup` these tests collide. Give a test that binds the ports without the
fixture the marker itself (`@pytest.mark.eos_server`).
### Follow Coding Standards
Keep your code consistent with existing style and conventions.