Skip to content

Avoid generating unused viewcode module pages - #14677

Open
Darlokt wants to merge 11 commits into
sphinx-doc:masterfrom
Darlokt:fix-viewcode-unused-modules
Open

Darlokt wants to merge 11 commits into
sphinx-doc:masterfrom
Darlokt:fix-viewcode-unused-modules

Conversation

@Darlokt

@Darlokt Darlokt commented Sep 13, 2026

Copy link
Copy Markdown
Contributor

Purpose

Hej, in #14675, I reported that parallel builds can generate an unreferenced module page.

Upon little bit further investigation, I found that the extra output is not caused by parallelization as I originally thought, but caused by sphinx.ext.viewcode.collect_pages() using every successful source-analysis entry as a module-page candidate and every cache key when generating the module overview and parent breadcrumbs.

A successful analysis entry can have an empty used mapping when viewcode finds and analyzes the source module but does not find a source tag for the documented object.
These entries can survive in both serial and parallel builds.
Unavailable modules are also cached as False entries.
Empty used entries can generate unreferenced module pages, while both states can incorrectly affect the module overview and parent breadcrumbs.

The fix filters the cache entries at page-collection time and generates output only for successfully analyzed modules with at least one used source tag.
The same filtered set is used for module pages, the module overview, progress reporting, and parent breadcrumbs.
Analysis caching, incremental purging, and parallel environment merging are unchanged.

The regression tests use the viewcode-find-source event to create a stable analyzed-but-unused module instead of tying the tests to viewcode's current handling of PEP 695 type aliases.
They cover fresh serial and parallel builds.
Collector coverage also checks an unavailable-module sentinel, a used child module, the overview, progress reporting, parent breadcrumbs, and preservation of the analysis cache.

References

AI Disclosure

OpenAI Codex assisted with reproduction variants, and generation and review of portions of the implementation and regression tests. All AI-assisted changes were reviewed and understood by me.

@Darlokt

Darlokt commented Sep 13, 2026

Copy link
Copy Markdown
Contributor Author

With #14611, #14679, #14681 all the CI problems should be fixed.

@kdeldycke

Copy link
Copy Markdown
Contributor

I can reproduce the False-entry case in a serial build on 9.2.0, with no parallelism.

viewcode_follow_imported_members is on by default. It follows FORECASTS = dict to builtins. ModuleAnalyzer cannot read builtins, so viewcode ends up caching False for it:

try:
analyzer = ModuleAnalyzer.for_module(modname)
analyzer.find_tags()
except Exception:
env._viewcode_modules[modname] = False # type: ignore[attr-defined] # ty: ignore[unresolved-attribute]
return False

collect_pages then takes every cache key, the False entries included:

modnames = set(env._viewcode_modules)

The module overview links each of those names:

for modname in sorted(modnames):
if modname.startswith(stack[-1]):
stack.append(modname + '.')
html.append('<ul>')
else:
stack.pop()
while not modname.startswith(stack[-1]):
stack.pop()
html.append('</ul>')
stack.append(modname + '.')
relative_uri = urito(
posixpath.join(OUTPUT_DIRNAME, 'index'),
posixpath.join(OUTPUT_DIRNAME, modname.replace('.', '/')),
)
html.append(f'<li><a href="{relative_uri}">{modname}</a></li>\n')

The False sentinel and the index built from every cache key both date back to the original viewcode commit, first released in 1.0.

Here is how to reproduce it.

A conf.py file:

import os
import sys

sys.path.insert(0, os.path.abspath("."))
extensions = ["sphinx.ext.autodoc", "sphinx.ext.viewcode"]

And a index.rst file:

Weather
=======

.. automodule:: weather
   :members:

And weather.py:

FORECASTS = dict
"""Container the forecasts are kept in."""


def forecast(city):
    """Forecast the weather of a city."""

With 9.2.0, the overview links builtins.html, which the build does not write:

$ python -m sphinx --builder html --quiet . _build/builtin-class
$ ls _build/builtin-class/_modules
index.html
weather.html
$ grep --only-matching 'href="[a-z_]*[.]html"' _build/builtin-class/_modules/index.html
href="builtins.html"
href="weather.html"
$ ls _build/builtin-class/_modules/builtins.html
ls: cannot access '_build/builtin-class/_modules/builtins.html': No such file or directory

The same module without FORECASTS works.

#14815, which I created, also touches this area.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

sphinx.ext.viewcode generates a module page with no source links

2 participants