diff --git a/devel-common/pyproject.toml b/devel-common/pyproject.toml index 6dc6c92a9af3..a959fa4144ad 100644 --- a/devel-common/pyproject.toml +++ b/devel-common/pyproject.toml @@ -88,6 +88,7 @@ dependencies = [ "sphinx-copybutton>=0.5.2", "sphinx-design>=0.5.0", "sphinx-jinja>=2.0.2", + "sphinx-llm>=1.1.0,<1.2", # airflow_llms_txt subclasses its Markdown translator "sphinx-rtd-theme>=2.0.0", "sphinx>=7", "sphinxcontrib-applehelp>=1.0.4", diff --git a/devel-common/src/docs/provider_conf.py b/devel-common/src/docs/provider_conf.py index 4df107b7d412..22f8159263ec 100644 --- a/devel-common/src/docs/provider_conf.py +++ b/devel-common/src/docs/provider_conf.py @@ -64,6 +64,7 @@ get_intersphinx_mapping, get_rst_epilogue, ) +from docs.utils.example_source import example_source_ref from sphinx_exts.provider_yaml_utils import load_package_data PACKAGE_NAME = os.environ.get("AIRFLOW_PACKAGE_NAME", "") @@ -147,6 +148,36 @@ ] ) +# Providers that publish a Markdown copy of every page plus llms.txt for LLMs and coding agents. +PROVIDER_PACKAGES_WITH_LLMS_TXT = [ + "apache-airflow-providers-common-ai", +] + + +if PACKAGE_NAME in PROVIDER_PACKAGES_WITH_LLMS_TXT: + extensions.append("airflow_llms_txt") + llms_txt_site_url = f"https://airflow.apache.org/docs/{PACKAGE_NAME}/{PACKAGE_VERSION}/" + _release_tag = f"providers-{PACKAGE_ID.replace('.', '-')}/{PACKAGE_VERSION}" + llms_txt_source_url = f"https://github.com/apache/airflow/blob/{example_source_ref(_release_tag)}/" + llms_txt_release_source_url = f"https://github.com/apache/airflow/blob/{_release_tag}/" + llms_txt_repo_root = AIRFLOW_REPO_ROOT_PATH.as_posix() + llms_txt_intro = ( + f"Install with `pip install {PACKAGE_NAME}`. This index covers version {PACKAGE_VERSION}. " + "Each link is a Markdown copy of a docs page; drop the trailing `.md` for the HTML page. " + "Code samples are excerpts of example Dags, and each one links to the full file." + ) + llms_txt_root_description = "Package overview, its requirements and what each optional extra installs." + # Long or generic pages an agent rarely needs first. + llms_txt_optional_docs = ["_api/**", "changelog", "security", "installing-providers-from-sources"] + # Not useful to an agent at all; their Markdown copies are still published. + llms_txt_skip_docs = ["_api/tests/**", "commits"] + llms_txt_nested_enabled = False + # One Markdown copy per page, ``page.html.md``: what llms.txt and ``rel=alternate`` link to. + llms_txt_suffix_mode = "append" + # Run the Markdown build after the HTML build, not alongside it: both run autoapi, which + # rewrites the ``_api`` sources in place while the other build may be reading them. + llms_txt_build_parallel = False + # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. empty_subpackages = ["apache", "atlassian", "common", "cncf", "dbt", "ibm", "microsoft"] diff --git a/devel-common/src/docs/utils/conf_constants.py b/devel-common/src/docs/utils/conf_constants.py index fd2116bbab65..d961402673c3 100644 --- a/devel-common/src/docs/utils/conf_constants.py +++ b/devel-common/src/docs/utils/conf_constants.py @@ -74,7 +74,9 @@ def get_rst_epilogue(package_version: str, airflow_core: bool) -> str: ) -SMARTQUOTES_EXCLUDES = {"builders": ["man", "text", "spelling"]} +# ``llms-markdown`` is sphinx-llm's Markdown build: its files are served without a charset, so +# curly quotes in them turn into mojibake for clients that default ``text/*`` to Latin-1. +SMARTQUOTES_EXCLUDES = {"builders": ["man", "text", "spelling", "llms-markdown"]} BASIC_SPHINX_EXTENSIONS = [ "sphinx.ext.autodoc", diff --git a/devel-common/src/docs/utils/example_source.py b/devel-common/src/docs/utils/example_source.py new file mode 100644 index 000000000000..552286969393 --- /dev/null +++ b/devel-common/src/docs/utils/example_source.py @@ -0,0 +1,46 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +from __future__ import annotations + +import subprocess + +from docs.utils.conf_constants import AIRFLOW_REPO_ROOT_PATH + + +def example_source_ref(tag: str) -> str: + """Return HEAD if a remote-tracking ref or tag contains it; otherwise return the release tag.""" + + def git(*args: str) -> str: + try: + result = subprocess.run( + ["git", *args], cwd=AIRFLOW_REPO_ROOT_PATH, capture_output=True, text=True, check=False + ) + except OSError: # Git may be unavailable when building from an sdist. + return "" + return result.stdout.strip() + + head = git("rev-parse", "--verify", "--quiet", "HEAD^{commit}") + if not head or head == git("rev-parse", "--verify", "--quiet", f"{tag}^{{commit}}"): + return tag + + # Main docs may reference examples missing from the latest release tag. + # The docs publishing workflow can cherry-pick fixes onto a release tag, + # creating a local-only HEAD that is unavailable on GitHub. Prefer HEAD + # when a remote-tracking ref or tag contains it; otherwise use the release tag. + pushed = git("for-each-ref", "--contains", head, "--count=1", "refs/remotes", "refs/tags") + return head if pushed else tag diff --git a/devel-common/src/sphinx_exts/airflow_llms_txt.py b/devel-common/src/sphinx_exts/airflow_llms_txt.py new file mode 100644 index 000000000000..1d486de77775 --- /dev/null +++ b/devel-common/src/sphinx_exts/airflow_llms_txt.py @@ -0,0 +1,564 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +""" +Publish Markdown copies of each page and an ``llms.txt`` index for LLMs and coding agents. + +`sphinx-llm `__ does the heavy lifting: it runs a second +Sphinx build with a Markdown builder, writes ``page.html.md`` next to every ``page.html`` and +adds ```` to each HTML page. This extension adds what +Airflow docs need on top of it: + +* Markdown handlers for nodes the stock translator drops or misrenders: ``mermaid`` diagrams, + code-block captions, keyword-only ``*`` markers in API signatures and toctree captions. +* License-header comments are removed, so they do not open every page. +* ``exampleinclude`` headers link to the full example file on GitHub at the release tag, since + the excerpts leave out imports. +* ``llms.txt`` is rewritten: sections follow the root toctree captions, every link is absolute, + and descriptions come from each page's first paragraph rather than its first line of text. +* ``llms-full.txt`` holds the same pages in the same order, each headed by its URL, with links + made absolute so they still work once the pages share one file. +""" + +from __future__ import annotations + +import posixpath +import re +from collections.abc import Iterator +from pathlib import Path +from typing import TYPE_CHECKING, Any, cast +from urllib.parse import urljoin, urlsplit, urlunsplit + +from docutils import nodes +from sphinx import addnodes +from sphinx.errors import ExtensionError +from sphinx.util import logging +from sphinx.util.matching import Matcher +from sphinx_llm.markdown_builder import SphinxLlmMarkdownBuilder, SphinxLlmMarkdownTranslator +from sphinx_markdown_builder.contexts import IndentContext, SubContext, SubContextParams, TableContext + +from sphinx_exts.redirects import iter_redirects + +if TYPE_CHECKING: + from sphinx.application import Sphinx + from sphinx.domains.std import StandardDomain + from sphinx.environment import BuildEnvironment + +logger = logging.getLogger(__name__) + +MARKDOWN_BUILDER = SphinxLlmMarkdownBuilder.name +# Pages whose first paragraph is shorter than this get no description rather than a fragment. +MIN_DESCRIPTION_LENGTH = 20 +MAX_DESCRIPTION_LENGTH = 240 +_SENTENCE_END = re.compile(r"(?<=[.!?])\s+(?=[A-Z`])") +# Paragraphs under these are not the page's own opening prose. +_NOT_PROSE = ( + nodes.Admonition, + nodes.comment, + nodes.compound, + nodes.list_item, + nodes.system_message, + nodes.table, + nodes.topic, + addnodes.desc, +) +# llms.txt is built from the HTML build's doctrees, where Sphinx has already curled the quotes. +# The files are served without a charset, so keep them ASCII (see SMARTQUOTES_EXCLUDES). +_TYPOGRAPHY = str.maketrans( + { + "\u2018": "'", + "\u2019": "'", + "\u201c": '"', + "\u201d": '"', + "\u2013": "-", + "\u2014": "-", + "\u2026": "...", + "\u00a0": " ", + } +) +_INLINE_CODE = re.compile(r"(`[^`]*`)") +_MARKDOWN_LINK = re.compile(r"(\]\()([^)\s]+)(\))") + + +class CompactTableContext(TableContext): + """ + A pipe table without the column padding. + + ``tabulate`` pads every cell to the widest one in its column, which is pure whitespace to a + model reading the file: about a tenth of ``llms-full.txt`` before this. + """ + + def make(self) -> str: + ctx = SubContext() + prefix = self.internal_context.make() + if prefix: + ctx.add(prefix) + rows = [self.make_row(row) for row in [*self.headers, *self.body]] + if rows: + width = max(len(row) for row in rows) + lines = [ + "| " + + " | ".join(cell.replace("|", r"\|") for cell in [*row, *[""] * (width - len(row))]) + + " |" + for row in rows + ] + lines.insert(1, "|" + "---|" * width) + ctx.add("\n".join(lines), prefix_eol=2) + return ctx.make() + + +class AirflowMarkdownTranslator(SphinxLlmMarkdownTranslator): + """Render the Sphinx nodes Airflow docs use that sphinx-markdown-builder skips or misrenders.""" + + def _push_box(self, title: str) -> None: + # Admonitions become a quoted block that starts with their label, rather than an + # ``#### NOTE`` heading that breaks the heading order and never says where the note ends. + self._push_context(IndentContext("> ", empty=True, params=SubContextParams(2, 2))) + self.add(f"**{title.capitalize()}:**", suffix_eol=2) + + def _fetch_ref_uri(self, node: nodes.reference) -> str: + # A link to a section on the same page (```Confidence`_``) has a refid but no refuri and + # no ``internal`` flag, so the base translators leave its target empty. + if node.get("refid") and not node.get("refuri"): + return self.builder.link_token(self.builder.current_doc_name, node["refid"]) + return super()._fetch_ref_uri(node) + + def visit_meta(self, node: nodes.Element) -> None: + raise nodes.SkipNode + + def visit_toctree(self, node: addnodes.toctree) -> None: + # Hidden toctrees can reach the writer unresolved; like HTML, show nothing for them. + # Visible ones are resolved into link lists before this, so any left are unexpected. + if not node.get("hidden"): + super().unknown_visit(node) + raise nodes.SkipNode + + def visit_table(self, node: nodes.Element) -> None: + self._push_context(CompactTableContext(params=SubContextParams(2, 1))) + + def depart_table(self, node: nodes.Element) -> None: + self._pop_context(node) + + def visit_mermaid(self, node: nodes.Element) -> None: + self.add(f"```mermaid\n{node['code'].strip()}\n```", prefix_eol=2, suffix_eol=2) + raise nodes.SkipNode + + def visit_caption(self, node: nodes.Element) -> None: + self.add(f"**{node.astext()}**", prefix_eol=2, suffix_eol=1) + raise nodes.SkipNode + + # ``abbreviation`` wraps the bare ``*`` that marks keyword-only parameters in signatures. + def visit_abbreviation(self, node: nodes.Element) -> None: + pass + + def depart_abbreviation(self, node: nodes.Element) -> None: + pass + + def visit_title(self, node: nodes.Element) -> None: + # Render navigation captions in bold rather than as section headings. + parent = node.parent + if (isinstance(parent, addnodes.compact_paragraph) and parent.get("toctree")) or ( + isinstance(parent, nodes.compound) and "toctree-wrapper" in parent.get("classes", []) + ): + self.add(f"**{node.astext()}**", prefix_eol=2, suffix_eol=1) + raise nodes.SkipNode + + super().visit_title(node) + + def depart_title(self, node: nodes.Element) -> None: + self._pop_context(node) + + +def _escape_link_text(text: str) -> str: + return text.replace("[", r"\[").replace("]", r"\]") + + +def _inline_markdown(node: nodes.Node, env: BuildEnvironment) -> str: + """Flatten a title or paragraph to one line of Markdown, keeping inline code as code.""" + parts: list[str] = [] + for child in node.children: + if isinstance(child, addnodes.pending_xref) and not child.get("refexplicit"): + parts.append(_xref_title(child, env) or _inline_markdown(child, env)) + elif isinstance(child, nodes.literal): + parts.append(f"`{child.astext()}`") + elif isinstance(child, nodes.Text): + parts.append(child.astext()) + elif isinstance(child, nodes.Element): + parts.append(_inline_markdown(child, env)) + return re.sub(r"\s+", " ", "".join(parts)).strip().translate(_TYPOGRAPHY) + + +def _xref_title(xref: addnodes.pending_xref, env: BuildEnvironment) -> str | None: + """ + Return the title a ``:doc:`` or ``:ref:`` without explicit text resolves to. + + Doctrees read back from the environment are unresolved, so such a reference still holds its + raw target (``operators/llm``) rather than the page or section title the HTML shows. + """ + target = xref.get("reftarget", "") + if xref.get("reftype") == "doc": + refdoc = xref.get("refdoc", "") + docname = ( + target.lstrip("/") + if target.startswith("/") + else posixpath.join(posixpath.dirname(refdoc), target) + ) + title = env.titles.get(posixpath.normpath(docname)) + return _inline_markdown(title, env) if title else None + if xref.get("reftype") == "ref": + domain = cast("StandardDomain", env.get_domain("std")) + label = domain.labels.get(target.lower()) + return label[2] if label else None + return None + + +def _is_markdown_build(app: Sphinx) -> bool: + return app.builder is not None and app.builder.name == MARKDOWN_BUILDER + + +def _remember_example_sources(app: Sphinx, doctree: nodes.document) -> None: + """Preserve example filenames before exampleinclude replaces its headers.""" + # Import by the bare name used by conf.py to preserve ExampleHeader's class identity. + from exampleinclude import ExampleHeader + + for header in doctree.findall(ExampleHeader): + header.parent["example_source_filename"] = header["filename"] + + +def _link_example_sources(app: Sphinx, doctree: nodes.document, docname: str) -> None: + """Replace rendered example headers with full-source links for Markdown.""" + if not _is_markdown_build(app): + return + + repo_root = Path(app.config.llms_txt_repo_root).resolve() + source_url = app.config.llms_txt_source_url.rstrip("/") + + for header in list(doctree.findall(nodes.paragraph)): + if ( + "example-header" not in header.get("classes", []) + or "example_source_filename" not in header.parent + ): + continue + + path = Path(header.parent["example_source_filename"]).resolve() + if not source_url or not path.is_relative_to(repo_root): + header.parent.remove(header) + continue + + repo_path = path.relative_to(repo_root).as_posix() + paragraph = nodes.paragraph() + paragraph += nodes.Text("Excerpt from ") + link = nodes.reference("", "", refuri=f"{source_url}/{repo_path}", internal=False) + link += nodes.literal(repo_path, repo_path) + paragraph += link + paragraph += nodes.Text(":") + header.replace_self(paragraph) + + +def _clean_markdown_doctree(app: Sphinx, doctree: nodes.document, docname: str) -> None: + """Remove RST comments and normalize version, GitHub source and site-root links for Markdown.""" + + if not _is_markdown_build(app): + return + + # Shared HTML doctrees already contain smart quotes; normalize prose at output time. + for text in list(doctree.findall(nodes.Text)): + if any( + isinstance(ancestor, (nodes.literal, nodes.math, nodes.FixedTextElement)) + for ancestor in _ancestors(text) + ): + continue + + normalized = text.astext().translate(_TYPOGRAPHY) + if normalized != text.astext(): + text.parent.replace(text, nodes.Text(normalized)) + + site_root = urljoin(app.config.llms_txt_site_url, "/") + release_url = app.config.llms_txt_release_source_url + source_url = app.config.llms_txt_source_url + for reference in doctree.findall(nodes.reference): + refuri = reference.get("refuri", "") + + # |version| in a URL is not an RST substitution. + # extra_provider_files_with_substitutions rewrites only the built HTML, + # so Markdown needs the equivalent replacement on the doctree. + if "|version|" in refuri: + refuri = reference["refuri"] = refuri.replace("|version|", app.config.version) + + # Give handwritten GitHub release links the same source ref as + # exampleinclude links, so both point to examples matching these docs. + if release_url and source_url and release_url != source_url: + for kind in ("blob", "tree"): + prefix = release_url.replace("/blob/", f"/{kind}/") + if refuri.startswith(prefix): + refuri = reference["refuri"] = ( + source_url.replace("/blob/", f"/{kind}/") + refuri[len(prefix) :] + ) + # Links into other packages' docs are site-root relative, which means nothing to a model + # that got the page without its URL. + if refuri.startswith("/") and not refuri.startswith("//"): + reference["refuri"] = urljoin(site_root, refuri) + for comment in list(doctree.findall(nodes.comment)): + comment.parent.remove(comment) + for quote in list(doctree.findall(nodes.block_quote)): + if not quote.children: + quote.parent.remove(quote) + + +def _page_description(env: BuildEnvironment, docname: str) -> str: + """Return the page's meta description or the opening sentences of its first paragraph.""" + doctree = env.get_doctree(docname) + for meta in doctree.findall(nodes.meta): + if meta.get("name") == "description" and meta.get("content"): + return meta["content"] + for paragraph in doctree.findall(nodes.paragraph): + # ``example-header`` is the file path ``exampleinclude`` puts above a code excerpt. + if "example-header" in paragraph["classes"] or any( + isinstance(ancestor, _NOT_PROSE) for ancestor in _ancestors(paragraph) + ): + continue + text = _inline_markdown(paragraph, env) + if len(text) >= MIN_DESCRIPTION_LENGTH: + return _summarize(text) + return "" + + +def _summarize(text: str) -> str: + """Return whole sentences of ``text`` up to the length cap, cutting the first one if it is longer.""" + description = "" + for sentence in _SENTENCE_END.split(text): + if description and len(description) + len(sentence) + 1 > MAX_DESCRIPTION_LENGTH: + break + description = f"{description} {sentence}".strip() + if len(description) > MAX_DESCRIPTION_LENGTH: + description = description[:MAX_DESCRIPTION_LENGTH].rsplit(" ", 1)[0] + " ..." + # A paragraph that introduces a list or code block ends on a colon. + return re.sub(r":$", ".", description) + + +def _ancestors(node: nodes.Node) -> Iterator[nodes.Element]: + parent = node.parent + while parent is not None: + yield parent + parent = parent.parent + + +def _page_title(env: BuildEnvironment, docname: str, explicit_title: str | None) -> str: + if explicit_title: + return explicit_title + title_node = env.titles.get(docname) + return _inline_markdown(title_node, env) if title_node else docname + + +def _toctree_docs(env: BuildEnvironment, docname: str, seen: set[str]) -> list[tuple[str, str | None]]: + """Return ``docname`` and everything below it in toctree order, each once.""" + if docname in seen: + return [] + seen.add(docname) + docs: list[tuple[str, str | None]] = [(docname, None)] + for child in env.toctree_includes.get(docname, []): + docs.extend(_toctree_docs(env, child, seen)) + return docs + + +def _write_markdown_redirects(app: Sphinx) -> None: + """Write Markdown stubs for redirected documentation pages.""" + outdir = Path(app.outdir) + + for from_path, to_path in iter_redirects(app): + # Preserve Markdown belonging to an actual source document. + docname = from_path.removesuffix(".html") + if docname in app.env.found_docs: + continue + + target = urlsplit(to_path) + resolved_path = posixpath.normpath(posixpath.join(posixpath.dirname(from_path), target.path)) + + # Only change links within this package to Markdown. + # Other packages and external sites might only publish HTML. + if ( + not target.scheme + and not target.netloc + and not target.path.startswith("/") + and resolved_path != ".." + and not resolved_path.startswith("../") + and target.path.endswith(".html") + ): + target = target._replace(path=f"{target.path}.md") + + destination = urlunsplit(target) + output = outdir / f"{from_path}.md" + output.parent.mkdir(parents=True, exist_ok=True) + output.write_text( + f"# Page moved\n\nThis page has moved to [the new page](<{destination}>).\n", + encoding="utf-8", + ) + + +def _check_markdown_coverage(outdir: Path) -> None: + """Fail if an eligible HTML page has no Markdown copy.""" + excluded = {"genindex.html", "search.html", "py-modindex.html"} + missing = [] + + for page in sorted(outdir.rglob("*.html")): + relative = page.relative_to(outdir) + if "_modules" in relative.parts or page.name in excluded: + continue + if not page.with_name(page.name + ".md").is_file(): + missing.append(relative.as_posix()) + + if missing: + raise ExtensionError( + "HTML pages missing Markdown copies:\n" + "\n".join(f" {page}" for page in missing) + ) + + +def _write_llms_txt(app: Sphinx, exception: Exception | None) -> None: + """ + Replace sphinx-llm's flat ``llms.txt`` with one grouped by the root toctree captions. + + Runs after sphinx-llm has copied the Markdown pages into the HTML output (priority 101). + """ + if exception is not None or app.builder.name != "html" or not app.config.llms_txt_enabled: + return + env = app.env + outdir = Path(app.outdir) + root_doc = app.config.root_doc + + # Report a missing root page before the coverage check lists every HTML page. + # sphinx-llm logs subprocess failures above without copying the Markdown output. + if not (outdir / f"{root_doc}.html.md").is_file(): + raise ExtensionError( + f"The Markdown build did not generate {root_doc}.html.md; " + "check the sphinx-llm build output above for errors." + ) + + _write_markdown_redirects(app) + _check_markdown_coverage(outdir) + + site_url = app.config.llms_txt_site_url.rstrip("/") + optional = Matcher(app.config.llms_txt_optional_docs) + skipped = Matcher(app.config.llms_txt_skip_docs) + + def md_url(docname: str) -> str: + return f"{site_url}/{docname}.html.md" + + def entry(docname: str, title: str | None = None, *, describe: bool = True) -> str: + line = f"- [{_escape_link_text(_page_title(env, docname, title))}]({md_url(docname)})" + description = _page_description(env, docname) if describe else "" + return f"{line}: {description}" if description else line + + root = env.get_doctree(root_doc) + # A caption's own pages come first; each page with pages under it gets a section of its own. + # Each section is its caption and its (docname, llms.txt line) pairs. + sections: list[tuple[str, list[tuple[str, str]]]] = [] + optional_entries: list[str] = [] + seen: set[str] = {root_doc} + for toctree in root.findall(addnodes.toctree): + leaves: list[tuple[str, str]] = [] + sections.append((toctree.get("caption") or "Pages", leaves)) + for title, ref in toctree["entries"]: + if ref == "self": + line = f"- [{_escape_link_text(title or 'Home')}]({md_url(root_doc)})" + if app.config.llms_txt_root_description: + line += f": {app.config.llms_txt_root_description}" + leaves.append((root_doc, line)) + continue + if "://" in ref: + continue + docs = [ + doc + for doc, _ in _toctree_docs(env, ref, seen) + if not skipped(doc) and (outdir / f"{doc}.html.md").is_file() + ] + if optional(ref): + if ref in docs: + optional_entries.append(entry(ref, title, describe=False)) + continue + lines = [(doc, entry(doc, title if doc == ref else None)) for doc in docs if not optional(doc)] + if len(lines) > 1: + sections.append((_page_title(env, ref, title), lines)) + else: + leaves.extend(lines) + sections = [(caption, lines) for caption, lines in sections if lines] + ordered_docs = [doc for _, lines in sections for doc, _ in lines] + if root_doc not in ordered_docs: + ordered_docs.insert(0, root_doc) + + title = f"{app.config.project} {app.config.release}" + summary = app.config.llms_txt_description or _page_description(env, app.config.root_doc) + pages = [ + f"---\n\nSource: {md_url(doc)}\n\n" + + _absolute_links((outdir / f"{doc}.html.md").read_text(encoding="utf-8").strip(), md_url(doc)) + for doc in ordered_docs + ] + (outdir / "llms-full.txt").write_text( + "\n\n".join([f"# {title}", f"> {summary}", *pages]) + "\n", encoding="utf-8" + ) + optional_entries.append( + f"- [llms-full.txt]({site_url}/llms-full.txt): The pages in the sections above, " + "in the same order, in one file." + ) + + out = [f"# {title}", "", f"> {summary}", ""] + if app.config.llms_txt_intro: + out += [app.config.llms_txt_intro.strip(), ""] + for caption, lines in sections: + out += [f"## {caption}", "", *(line for _, line in lines), ""] + if optional_entries: + out += ["## Optional", "", *optional_entries, ""] + (outdir / "llms.txt").write_text("\n".join(out), encoding="utf-8") + logger.info("Wrote grouped llms.txt with %d sections", len(sections)) + + +def _absolute_links(markdown: str, page_url: str) -> str: + """Resolve the page's relative Markdown links against its URL, leaving code blocks alone.""" + lines = [] + in_code = False + for line in markdown.splitlines(): + fence = line.lstrip().startswith("```") + in_code ^= fence + if in_code or fence: + lines.append(line) + continue + # Odd-numbered parts are inline code spans, which stay as written. + parts = _INLINE_CODE.split(line) + for i in range(0, len(parts), 2): + parts[i] = _MARKDOWN_LINK.sub(lambda m: f"{m[1]}{urljoin(page_url, m[2])}{m[3]}", parts[i]) + lines.append("".join(parts)) + return "\n".join(lines) + + +def setup(app: Sphinx) -> dict[str, Any]: + app.setup_extension("sphinx_llm.txt") + app.set_translator(MARKDOWN_BUILDER, AirflowMarkdownTranslator, override=True) + app.add_config_value("llms_txt_site_url", "", "env") + app.add_config_value("llms_txt_source_url", "", "env") + app.add_config_value("llms_txt_release_source_url", "", "env") + app.add_config_value("llms_txt_repo_root", "", "env") + app.add_config_value("llms_txt_intro", "", "env") + app.add_config_value("llms_txt_root_description", "", "env") + app.add_config_value("llms_txt_optional_docs", [], "env") + app.add_config_value("llms_txt_skip_docs", [], "env") + app.connect("doctree-read", _remember_example_sources, priority=400) + app.connect("doctree-resolved", _link_example_sources) + app.connect("doctree-resolved", _clean_markdown_doctree) + app.connect("build-finished", _write_llms_txt, priority=102) + return { + "env_version": 1, + "parallel_read_safe": True, + "parallel_write_safe": True, + } diff --git a/devel-common/src/sphinx_exts/airflow_spelling.py b/devel-common/src/sphinx_exts/airflow_spelling.py index 4a8360649045..aceafc097d54 100644 --- a/devel-common/src/sphinx_exts/airflow_spelling.py +++ b/devel-common/src/sphinx_exts/airflow_spelling.py @@ -175,7 +175,7 @@ def _describe(node: nodes.Text, text: str, word: str, offset: int) -> dict[str, def _start(app: Sphinx) -> None: - if app.config.airflow_spelling_output: + if app.builder.name == "html" and app.config.airflow_spelling_output: setattr(app, _RUN_ATTRIBUTE, _SpellingRun(app)) diff --git a/devel-common/src/sphinx_exts/redirects.py b/devel-common/src/sphinx_exts/redirects.py index 351c8bb2029f..709946802a88 100644 --- a/devel-common/src/sphinx_exts/redirects.py +++ b/devel-common/src/sphinx_exts/redirects.py @@ -43,67 +43,63 @@ def build_redirect_page(to_path: str) -> str: return TEMPLATE.format(target=json.dumps(to_path), url=to_path) -def generate_redirects(app): - """Generate redirects files.""" +def iter_redirects(app): + """Yield source and resolved destination paths for redirects.""" redirect_file_path = os.path.join(app.srcdir, app.config.redirects_file) if not os.path.exists(redirect_file_path): - log.info("Could not found the redirect file: %s", redirect_file_path) + log.info("Could not find the redirect file: %s", redirect_file_path) return in_suffix = next(iter(app.config.source_suffix.keys())) - if not isinstance(app.builder, builders.StandaloneHTMLBuilder): - return - with open(redirect_file_path) as redirects: for line in redirects: - # Skip empty line - if not line.strip(): - continue - - # Skip comments - if line.startswith("#"): + if not line.strip() or line.startswith("#"): continue - # Split line into the original path `from_path` and where the URL should redirect to `to_path` from_path, _, to_path = line.rstrip().partition(" ") log.debug("Redirecting '%s' to '%s'", from_path, to_path) - # in_suffix is often ".rst" from_path = from_path.replace(in_suffix, ".html") to_path = to_path.replace(in_suffix, ".html") - to_path_prefix = f"..{os.path.sep}" * (len(from_path.split(os.path.sep)) - 1) - # The redirect path needs to move back to the root of the apache-airflow docs directory - # or the root of the docs directory altogether for provider distributions. + # Redirects climb back to the package docs root, or to the shared docs + # root for provider destinations, which requires one extra parent level. + # Core API-to-provider redirects use the package-root depth instead. + depth = len(from_path.split(os.path.sep)) - 1 if ( from_path.startswith("_api/airflow/") and "_api/airflow/providers" not in from_path and "providers" in to_path ): - to_path_prefix = f"..{os.path.sep}" * (len(from_path.split(os.path.sep)) - 1) - elif "../" and "providers" in to_path: - to_path_prefix = f"..{os.path.sep}" * (len(from_path.split(os.path.sep))) + to_path_prefix = f"..{os.path.sep}" * depth + elif "providers" in to_path: + to_path_prefix = f"..{os.path.sep}" * (depth + 1) else: - to_path_prefix = f"..{os.path.sep}" * (len(from_path.split(os.path.sep)) - 1) + to_path_prefix = f"..{os.path.sep}" * depth to_path = to_path_prefix + to_path log.debug("Resolved redirect '%s' to '%s'", from_path, to_path) + yield from_path, to_path + - # This will be used to save an HTML file with `TEMPLATE` formatted - redirected_filename = os.path.join(app.builder.outdir, from_path) - redirected_directory = os.path.dirname(redirected_filename) +def generate_redirects(app): + """Generate HTML redirect files.""" + if not isinstance(app.builder, builders.StandaloneHTMLBuilder): + return - os.makedirs(redirected_directory, exist_ok=True) + for from_path, to_path in iter_redirects(app): + redirected_filename = os.path.join(app.builder.outdir, from_path) + os.makedirs(os.path.dirname(redirected_filename), exist_ok=True) - with open(redirected_filename, "w") as f: - f.write(build_redirect_page(to_path)) + with open(redirected_filename, "w", encoding="utf-8") as f: + f.write(build_redirect_page(to_path)) def setup(app): - """Setup plugin""" + """Setup plugin.""" app.add_config_value("redirects_file", "redirects", "env") app.connect("builder-inited", generate_redirects) return {"version": "builtin", "parallel_read_safe": True, "parallel_write_safe": True} diff --git a/devel-common/tests/unit/docs/utils/test_example_source.py b/devel-common/tests/unit/docs/utils/test_example_source.py new file mode 100644 index 000000000000..d6b3cd27f936 --- /dev/null +++ b/devel-common/tests/unit/docs/utils/test_example_source.py @@ -0,0 +1,71 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +from __future__ import annotations + +import subprocess +from unittest import mock + +import pytest + +from docs.utils.example_source import example_source_ref + + +@pytest.mark.parametrize( + ("outputs", "expected"), + [ + pytest.param([""], "release-tag", id="head-unavailable"), + pytest.param( + ["head-sha", "head-sha"], + "release-tag", + id="head-matches-release-tag", + ), + pytest.param( + ["head-sha", "tag-sha", "refs/remotes/upstream/main\n"], + "head-sha", + id="head-in-remote-branch", + ), + pytest.param( + ["head-sha", "", "refs/tags/another-tag\n"], + "head-sha", + id="head-in-tag", + ), + pytest.param( + ["head-sha", "tag-sha", ""], + "release-tag", + id="head-only-local", + ), + ], +) +def test_example_source_ref(outputs, expected): + results = [subprocess.CompletedProcess(args=["git"], returncode=0, stdout=output) for output in outputs] + + with mock.patch( + "docs.utils.example_source.subprocess.run", + autospec=True, + side_effect=results, + ): + assert example_source_ref("release-tag") == expected + + +def test_example_source_ref_without_git(): + with mock.patch( + "docs.utils.example_source.subprocess.run", + autospec=True, + side_effect=OSError("Git is unavailable"), + ): + assert example_source_ref("release-tag") == "release-tag" diff --git a/devel-common/tests/unit/sphinx_exts/test_airflow_llms_txt.py b/devel-common/tests/unit/sphinx_exts/test_airflow_llms_txt.py new file mode 100644 index 000000000000..bbe6bd12abe8 --- /dev/null +++ b/devel-common/tests/unit/sphinx_exts/test_airflow_llms_txt.py @@ -0,0 +1,727 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +from __future__ import annotations + +import io +from pathlib import Path +from types import SimpleNamespace + +import pytest +from docutils import nodes +from sphinx import addnodes +from sphinx.application import Sphinx +from sphinx.errors import ExtensionError + +from sphinx_exts import airflow_llms_txt + + +def make_app(tmp_path, *, found_docs=()): + source = tmp_path / "source" + output = tmp_path / "output" + source.mkdir() + output.mkdir() + (source / "redirects.txt").write_text("", encoding="utf-8") + + return SimpleNamespace( + srcdir=source, + outdir=output, + builder=SimpleNamespace(name="html"), + env=SimpleNamespace(found_docs=set(found_docs)), + config=SimpleNamespace( + redirects_file="redirects.txt", + source_suffix={".rst": "restructuredtext"}, + llms_txt_enabled=True, + root_doc="index", + ), + ) + + +@pytest.mark.parametrize( + ("source", "target", "expected"), + [ + pytest.param( + "old.rst", + "new.rst", + "new.html.md", + id="normal", + ), + pytest.param( + "hooks/index.rst", + "concepts.rst", + "../concepts.html.md", + id="nested", + ), + pytest.param( + "old.rst", + "new.rst#section", + "new.html.md#section", + id="anchor", + ), + pytest.param( + "old.rst", + "new.rst?view=full#section", + "new.html.md?view=full#section", + id="query-and-anchor", + ), + pytest.param( + "old.rst", + "../other/new.rst", + "../other/new.html", + id="outside-package", + ), + pytest.param( + "old.rst", + "https://example.org/new.html", + "https://example.org/new.html", + id="external", + ), + ], +) +def test_write_markdown_redirects(tmp_path, source, target, expected): + app = make_app(tmp_path) + (app.srcdir / "redirects.txt").write_text(f"{source} {target}\n", encoding="utf-8") + + airflow_llms_txt._write_markdown_redirects(app) + + output = app.outdir / source.replace(".rst", ".html.md") + assert output.read_text(encoding="utf-8") == ( + f"# Page moved\n\nThis page has moved to [the new page](<{expected}>).\n" + ) + + +def test_redirect_preserves_actual_document(tmp_path): + app = make_app(tmp_path, found_docs={"old"}) + (app.srcdir / "redirects.txt").write_text("old.rst new.rst\n", encoding="utf-8") + output = app.outdir / "old.html.md" + output.write_text("# Actual documentation\n", encoding="utf-8") + + airflow_llms_txt._write_markdown_redirects(app) + + assert output.read_text(encoding="utf-8") == "# Actual documentation\n" + + +def test_redirect_updates_existing_stub(tmp_path): + app = make_app(tmp_path) + (app.srcdir / "redirects.txt").write_text("old.rst new.rst\n", encoding="utf-8") + output = app.outdir / "old.html.md" + output.write_text("Old redirect destination", encoding="utf-8") + + airflow_llms_txt._write_markdown_redirects(app) + + assert "()" in output.read_text(encoding="utf-8") + assert "Old redirect destination" not in output.read_text(encoding="utf-8") + + +def test_complete_markdown_coverage(tmp_path): + for name in ("index.html", "operators/llm.html"): + page = tmp_path / name + page.parent.mkdir(parents=True, exist_ok=True) + page.write_text("HTML", encoding="utf-8") + page.with_name(page.name + ".md").write_text("# Documentation", encoding="utf-8") + + airflow_llms_txt._check_markdown_coverage(tmp_path) + + +def test_missing_markdown_lists_all_missing_pages(tmp_path): + for name in ("index.html", "operators/llm.html"): + page = tmp_path / name + page.parent.mkdir(parents=True, exist_ok=True) + page.write_text("HTML", encoding="utf-8") + + with pytest.raises(ExtensionError) as exc: + airflow_llms_txt._check_markdown_coverage(tmp_path) + + assert str(exc.value) == ("HTML pages missing Markdown copies:\n index.html\n operators/llm.html") + + +@pytest.mark.parametrize( + "name", + [ + "genindex.html", + "search.html", + "py-modindex.html", + "_modules/index.html", + "_modules/airflow/providers/example.html", + ], +) +def test_coverage_excludes_special_pages(tmp_path, name): + page = tmp_path / name + page.parent.mkdir(parents=True, exist_ok=True) + page.write_text("HTML", encoding="utf-8") + + airflow_llms_txt._check_markdown_coverage(tmp_path) + + +@pytest.mark.parametrize("root_doc", ["index", "guide/start"]) +def test_missing_root_markdown_fails_build(tmp_path, root_doc): + app = make_app(tmp_path, found_docs={root_doc, "other"}) + app.config.root_doc = root_doc + + for name in (root_doc, "other"): + page = app.outdir / f"{name}.html" + page.parent.mkdir(parents=True, exist_ok=True) + page.write_text("HTML", encoding="utf-8") + + with pytest.raises(ExtensionError) as exc: + airflow_llms_txt._write_llms_txt(app, None) + + assert str(exc.value) == ( + f"The Markdown build did not generate {root_doc}.html.md; " + "check the sphinx-llm build output above for errors." + ) + + +@pytest.mark.parametrize( + ("builder", "enabled", "exception"), + [ + pytest.param("html", True, RuntimeError("Build failed"), id="failed-build"), + pytest.param("html", False, None, id="disabled"), + pytest.param( + airflow_llms_txt.MARKDOWN_BUILDER, + True, + None, + id="markdown-build", + ), + ], +) +def test_index_generation_skipped(tmp_path, builder, enabled, exception): + app = make_app(tmp_path) + app.builder.name = builder + app.config.llms_txt_enabled = enabled + (app.outdir / "index.html").write_text("HTML", encoding="utf-8") + + airflow_llms_txt._write_llms_txt(app, exception) + + assert not (app.outdir / "llms.txt").exists() + assert not (app.outdir / "llms-full.txt").exists() + + +def test_index_generation_reports_partial_markdown_coverage(tmp_path): + app = make_app( + tmp_path, + found_docs={"index", "guide", "operators/llm"}, + ) + + for name in ("index", "guide", "operators/llm"): + page = app.outdir / f"{name}.html" + page.parent.mkdir(parents=True, exist_ok=True) + page.write_text("HTML", encoding="utf-8") + + (app.outdir / "index.html.md").write_text("# Documentation\n", encoding="utf-8") + + with pytest.raises(ExtensionError) as exc: + airflow_llms_txt._write_llms_txt(app, None) + + assert str(exc.value) == ("HTML pages missing Markdown copies:\n guide.html\n operators/llm.html") + + +def test_indexes_follow_navigation_and_use_versioned_urls(tmp_path): + names = {"index", "guide", "second", "changelog", "commits"} + app = make_app(tmp_path, found_docs=names) + site_url = "https://airflow.apache.org/docs/apache-airflow-providers-common-ai/0.10.0" + + root = nodes.document("", "") + navigation = addnodes.toctree() + navigation["caption"] = "Guides" + navigation["entries"] = [ + ("Getting started", "guide"), + (None, "second"), + (None, "changelog"), + (None, "commits"), + ] + root += navigation + + doctrees = {"index": root} + for name in names - {"index"}: + tree = nodes.document("", "") + tree += nodes.paragraph("", f"This is the documentation description for {name}.") + doctrees[name] = tree + + app.env.titles = {name: nodes.title("", name.capitalize()) for name in names} + app.env.toctree_includes = {} + app.env.get_doctree = doctrees.__getitem__ + + app.config.llms_txt_site_url = site_url + "/" + app.config.llms_txt_optional_docs = ["changelog"] + app.config.llms_txt_skip_docs = ["commits"] + app.config.project = "Common AI" + app.config.release = "0.10.0" + app.config.llms_txt_description = "Common AI documentation." + app.config.llms_txt_intro = "Install the Common AI provider." + app.config.llms_txt_root_description = "" + + for name in names: + (app.outdir / f"{name}.html").write_text("HTML", encoding="utf-8") + content = f"# {name.capitalize()}\n" + if name == "guide": + content += "[Next](second.html.md)\n" + (app.outdir / f"{name}.html.md").write_text(content, encoding="utf-8") + + airflow_llms_txt._write_llms_txt(app, None) + + index = (app.outdir / "llms.txt").read_text(encoding="utf-8") + full = (app.outdir / "llms-full.txt").read_text(encoding="utf-8") + + assert index.startswith("# Common AI 0.10.0\n") + assert "Install the Common AI provider." in index + assert "## Guides" in index + assert ( + f"- [Getting started]({site_url}/guide.html.md): This is the documentation description for guide." + ) in index + assert index.index("/guide.html.md") < index.index("/second.html.md") + + optional = index.split("## Optional\n", 1)[1] + assert f"- [Changelog]({site_url}/changelog.html.md)" in optional + assert f"[llms-full.txt]({site_url}/llms-full.txt)" in optional + assert "/commits.html.md" not in index + + assert full.index("Source: " + site_url + "/index.html.md") < full.index( + "Source: " + site_url + "/guide.html.md" + ) + assert full.index("Source: " + site_url + "/guide.html.md") < full.index( + "Source: " + site_url + "/second.html.md" + ) + assert f"[Next]({site_url}/second.html.md)" in full + assert "Source: " + site_url + "/changelog.html.md" not in full + assert "Source: " + site_url + "/commits.html.md" not in full + + +@pytest.mark.parametrize( + ("inside_repo", "source_url", "builder"), + [ + pytest.param( + True, "https://github.com/apache/airflow/blob/abc", airflow_llms_txt.MARKDOWN_BUILDER, id="linked" + ), + pytest.param( + False, + "https://github.com/apache/airflow/blob/abc", + airflow_llms_txt.MARKDOWN_BUILDER, + id="outside-repo", + ), + pytest.param(True, "", airflow_llms_txt.MARKDOWN_BUILDER, id="no-source-url"), + pytest.param(True, "https://github.com/apache/airflow/blob/abc", "html", id="html-unchanged"), + ], +) +def test_example_source_links(tmp_path, inside_repo, source_url, builder): + + repo = tmp_path / "repo" + example = ( + repo / "providers/common/ai/tests/system/example.py" + if inside_repo + else tmp_path / "outside/example.py" + ) + tree = nodes.document("", "") + wrapper = nodes.container() + wrapper["example_source_filename"] = str(example) + header = nodes.paragraph("", "Original example header", classes=["example-header"]) + wrapper += header + tree += wrapper + + app = SimpleNamespace( + builder=SimpleNamespace(name=builder), + config=SimpleNamespace( + llms_txt_repo_root=str(repo), + llms_txt_source_url=source_url + "/" if source_url else "", + ), + ) + + airflow_llms_txt._link_example_sources(app, tree, "index") + + if builder == "html": + assert wrapper.children == [header] + elif not inside_repo or not source_url: + assert not wrapper.children + else: + references = list(wrapper.findall(nodes.reference)) + assert len(references) == 1 + assert references[0]["refuri"] == (source_url + "/providers/common/ai/tests/system/example.py") + assert references[0].astext() == ("providers/common/ai/tests/system/example.py") + assert wrapper.astext() == ("Excerpt from providers/common/ai/tests/system/example.py:") + + +def test_example_source_links_in_built_docs(rendered_docs): + assert ( + "Excerpt from [`example.py`](https://github.com/apache/airflow/blob/test-ref/example.py):" + ) in rendered_docs.markdown + assert 'print("example survives cache reuse")' in rendered_docs.markdown + + assert 'class="example-header' in rendered_docs.html + assert "Excerpt from" not in rendered_docs.html + + +def test_remember_example_sources(tmp_path, monkeypatch): + monkeypatch.syspath_prepend(str(Path(airflow_llms_txt.__file__).parent)) + from exampleinclude import ExampleHeader + + filename = str(tmp_path / "example.py") + tree = nodes.document("", "") + wrapper = nodes.container() + header = ExampleHeader() + header["filename"] = filename + wrapper += header + tree += wrapper + + airflow_llms_txt._remember_example_sources(SimpleNamespace(builder=SimpleNamespace(name="html")), tree) + + assert wrapper["example_source_filename"] == filename + assert wrapper.children == [header] + + +@pytest.mark.parametrize( + ("url", "expected"), + [ + pytest.param( + "https://example.org/docs/|version|/guide", + "https://example.org/docs/0.10.0/guide", + id="version", + ), + pytest.param( + "https://github.com/apache/airflow/blob/release-tag/example.py", + "https://github.com/apache/airflow/blob/head-sha/example.py", + id="github-file", + ), + pytest.param( + "https://github.com/apache/airflow/tree/release-tag/examples", + "https://github.com/apache/airflow/tree/head-sha/examples", + id="github-directory", + ), + pytest.param( + "/docs/apache-airflow/stable/index.html", + "https://airflow.apache.org/docs/apache-airflow/stable/index.html", + id="site-root", + ), + pytest.param( + "//example.org/page", + "//example.org/page", + id="protocol-relative-unchanged", + ), + pytest.param( + "concepts.html.md#section", + "concepts.html.md#section", + id="relative-unchanged", + ), + pytest.param( + "https://example.org/page", + "https://example.org/page", + id="external-unchanged", + ), + ], +) +def test_clean_markdown_link_targets(url, expected): + tree = nodes.document("", "") + reference = nodes.reference("", "Link", refuri=url) + tree += reference + + app = SimpleNamespace( + builder=SimpleNamespace(name=airflow_llms_txt.MARKDOWN_BUILDER), + config=SimpleNamespace( + version="0.10.0", + llms_txt_site_url=("https://airflow.apache.org/docs/common-ai/0.10.0/"), + llms_txt_release_source_url=("https://github.com/apache/airflow/blob/release-tag/"), + llms_txt_source_url=("https://github.com/apache/airflow/blob/head-sha/"), + ), + ) + + airflow_llms_txt._clean_markdown_doctree(app, tree, "index") + + assert reference["refuri"] == expected + + +def test_clean_markdown_removes_comments_and_empty_quotes(): + tree = nodes.document("", "") + tree += nodes.comment("", "License header") + tree += nodes.block_quote() + populated_quote = nodes.block_quote() + populated_quote += nodes.paragraph("", "Keep this quotation.") + tree += populated_quote + + app = SimpleNamespace( + builder=SimpleNamespace(name=airflow_llms_txt.MARKDOWN_BUILDER), + config=SimpleNamespace( + llms_txt_site_url="https://airflow.apache.org/", + llms_txt_release_source_url="", + llms_txt_source_url="", + ), + ) + + airflow_llms_txt._clean_markdown_doctree(app, tree, "index") + + assert not list(tree.findall(nodes.comment)) + assert list(tree.findall(nodes.block_quote)) == [populated_quote] + assert tree.astext() == "Keep this quotation." + + +def test_clean_doctree_leaves_html_unchanged(): + tree = nodes.document("", "") + comment = nodes.comment("", "License header") + reference = nodes.reference("", "Link", refuri="/docs/|version|/") + tree += comment + tree += reference + app = SimpleNamespace(builder=SimpleNamespace(name="html")) + + airflow_llms_txt._clean_markdown_doctree(app, tree, "index") + + assert comment in tree.children + assert reference["refuri"] == "/docs/|version|/" + + +@pytest.mark.parametrize( + ("markdown", "expected"), + [ + pytest.param( + "[Next](other.html.md#section)", + "[Next](https://example.org/docs/other.html.md#section)", + id="relative-link", + ), + pytest.param( + "[Parent](../index.html.md)", + "[Parent](https://example.org/index.html.md)", + id="parent-link", + ), + pytest.param( + "[Section](#setup)", + "[Section](https://example.org/docs/page.html.md#setup)", + id="same-page-link", + ), + pytest.param( + "[External](https://other.example/page)", + "[External](https://other.example/page)", + id="external-link", + ), + pytest.param( + "`[Example](other.html.md)` [Next](other.html.md)", + "`[Example](other.html.md)` [Next](https://example.org/docs/other.html.md)", + id="inline-code", + ), + pytest.param( + "```python\n[Example](other.html.md)\n```\n[Next](other.html.md)", + "```python\n[Example](other.html.md)\n```\n[Next](https://example.org/docs/other.html.md)", + id="fenced-code", + ), + ], +) +def test_absolute_links(markdown, expected): + assert airflow_llms_txt._absolute_links(markdown, "https://example.org/docs/page.html.md") == expected + + +def test_navigation_handles_nested_pages_duplicates_and_cycles(): + env = SimpleNamespace( + toctree_includes={ + "index": ["guide", "second", "guide"], + "guide": ["child", "second"], + "child": ["index"], + } + ) + seen = set() + + assert airflow_llms_txt._toctree_docs(env, "index", seen) == [ + ("index", None), + ("guide", None), + ("child", None), + ("second", None), + ] + assert airflow_llms_txt._toctree_docs(env, "guide", seen) == [] + + +@pytest.fixture +def rendered_docs(tmp_path): + source = tmp_path / "source" + output = tmp_path / "output" + source.mkdir() + + # The extension imports redirects and exampleinclude by bare module name. + extension_dir = Path(airflow_llms_txt.__file__).parent + source_root = extension_dir.parent + + (source / "conf.py").write_text( + "import sys\n" + f"sys.path.insert(0, {str(source_root)!r})\n" + f"sys.path.insert(0, {str(extension_dir)!r})\n" + "extensions = [\n" + ' "redirects",\n' + ' "exampleinclude",\n' + ' "sphinx_exts.airflow_llms_txt",\n' + ' "sphinxcontrib.mermaid",\n' + "]\n" + 'root_doc = "index"\n' + 'redirects_file = "redirects.txt"\n' + "llms_txt_enabled = True\n" + 'llms_txt_suffix_mode = "append"\n' + "llms_txt_build_parallel = False\n" + 'smartquotes_excludes = {"builders": ["man", "text", "spelling", "llms-markdown"]}\n' + f"exampleinclude_sourceroot = {str(source)!r}\n" + f"llms_txt_repo_root = {str(source)!r}\n" + 'llms_txt_source_url = "https://github.com/apache/airflow/blob/test-ref/"\n', + encoding="utf-8", + ) + (source / "redirects.txt").write_text("", encoding="utf-8") + (source / "index.rst").write_text( + """\ +Rendering +========= + +.. _setup-section: + +Setup +----- + +See :ref:`Setup `. + +.. note:: + + Important configuration advice. + +Following paragraph outside the note. + +.. list-table:: + :header-rows: 1 + + * - Name + - Value + * - Short + - A much longer value + +.. code-block:: python + :caption: Example code + + print("hello") + +.. mermaid:: + + graph TD + A --> B + +.. py:function:: configure(*, model_id) + + Configure a model. + +.. toctree:: + :caption: Further reading + + child + +Don't "quote" this -- dash. + +Keep ``Don\u2019t \u201cchange\u201d this`` unchanged. + +.. code-block:: text + + Don\u2019t \u201cchange\u201d this \u2013 dash. + +Example +------- + +.. exampleinclude:: example.py +""", + encoding="utf-8", + ) + (source / "child.rst").write_text( + "Child page\n==========\n\nChild documentation.\n", + encoding="utf-8", + ) + (source / "example.py").write_text( + 'print("example survives cache reuse")\n', + encoding="utf-8", + ) + + warnings = io.StringIO() + app = Sphinx( + srcdir=str(source), + confdir=str(source), + outdir=str(output), + doctreedir=str(tmp_path / "doctrees"), + buildername="html", + status=io.StringIO(), + warning=warnings, + freshenv=True, + ) + app.build(force_all=True) + + assert app.statuscode == 0, warnings.getvalue() + pages = list(output.rglob("index*.md")) + assert len(pages) == 1 + return SimpleNamespace( + markdown=pages[0].read_text(encoding="utf-8"), + html=(output / "index.html").read_text(encoding="utf-8"), + ) + + +def test_rendered_mermaid(rendered_docs): + rendered_markdown = rendered_docs.markdown + + assert "```mermaid\n" in rendered_markdown + assert "graph TD\n" in rendered_markdown + assert "A --> B" in rendered_markdown + + +def test_rendered_code_caption_and_sample(rendered_docs): + rendered_markdown = rendered_docs.markdown + + assert "**Example code**" in rendered_markdown + assert 'print("hello")' in rendered_markdown + assert rendered_markdown.index("**Example code**") < (rendered_markdown.index('print("hello")')) + + +def test_rendered_keyword_only_marker(rendered_docs): + rendered_markdown = rendered_docs.markdown + + signature = next(line for line in rendered_markdown.splitlines() if "configure(" in line) + assert "*" in signature + assert "model_id" in signature + + +def test_rendered_toctree_caption(rendered_docs): + rendered_markdown = rendered_docs.markdown + + assert "**Further reading**" in rendered_markdown + assert "[Child page]" in rendered_markdown + assert "# Further reading" not in rendered_markdown + + +def test_rendered_admonition_has_clear_boundaries(rendered_docs): + rendered_markdown = rendered_docs.markdown + + lines = rendered_markdown.splitlines() + assert any(line.startswith(">") and "**Note:**" in line for line in lines) + assert any(line.startswith(">") and "Important configuration advice." in line for line in lines) + following = next(line for line in lines if "Following paragraph outside the note." in line) + assert not following.startswith(">") + + +def test_rendered_table_is_compact(rendered_docs): + rendered_markdown = rendered_docs.markdown + + table_lines = [line.strip() for line in rendered_markdown.splitlines() if line.strip().startswith("|")] + assert "| Name | Value |" in table_lines + assert "|---|---|" in table_lines + assert "| Short | A much longer value |" in table_lines + + +def test_rendered_same_page_link(rendered_docs): + rendered_markdown = rendered_docs.markdown + + assert "[Setup](#setup-section)" in rendered_markdown + + +def test_rendered_typography(rendered_docs): + """Normalize Markdown prose while preserving literal content and HTML typography.""" + assert 'Don\'t "quote" this - dash.' in rendered_docs.markdown + assert "Don\u2019t \u201cquote\u201d this \u2013 dash." in rendered_docs.html + + assert "`Don\u2019t \u201cchange\u201d this`" in rendered_docs.markdown + assert "Don\u2019t \u201cchange\u201d this \u2013 dash." in rendered_docs.markdown diff --git a/devel-common/tests/unit/sphinx_exts/test_airflow_spelling.py b/devel-common/tests/unit/sphinx_exts/test_airflow_spelling.py index 34f6644df866..d6cdca0b16c7 100644 --- a/devel-common/tests/unit/sphinx_exts/test_airflow_spelling.py +++ b/devel-common/tests/unit/sphinx_exts/test_airflow_spelling.py @@ -132,6 +132,20 @@ def test_undoing_smartquotes_gives_back_the_text_as_typed(typed): assert smartyPants(typed, "qDe", "en").translate(airflow_spelling._UNSMARTEN) == typed +def test_start_skips_markdown_builder(tmp_path, dictionary_factory): + """Do not start spell checking during the Markdown build.""" + app = SimpleNamespace( + builder=SimpleNamespace(name="llms-markdown"), + config=_config(airflow_spelling_output=str(tmp_path / "spelling.json")), + srcdir=tmp_path, + ) + + airflow_spelling._start(app) + + assert not hasattr(app, airflow_spelling._RUN_ATTRIBUTE) + dictionary_factory.assert_not_called() + + def _env(docname_path: str = "index.rst", good_words=None): env = mock.create_autospec(BuildEnvironment, instance=True) env.doc2path.return_value = Path(docname_path) diff --git a/devel-common/tests/unit/sphinx_exts/test_redirects.py b/devel-common/tests/unit/sphinx_exts/test_redirects.py index 9f9c1dadbb5e..b26e95364288 100644 --- a/devel-common/tests/unit/sphinx_exts/test_redirects.py +++ b/devel-common/tests/unit/sphinx_exts/test_redirects.py @@ -16,17 +16,158 @@ # under the License. from __future__ import annotations -import sys -from pathlib import Path +import os +from types import SimpleNamespace +from unittest import mock import pytest +from sphinx.builders.html import StandaloneHTMLBuilder -SPHINX_EXTS_PATH = Path(__file__).parents[3] / "src" / "sphinx_exts" -if SPHINX_EXTS_PATH.as_posix() not in sys.path: - # The extensions are loaded by Sphinx from this directory and import each other by bare name. - sys.path.append(SPHINX_EXTS_PATH.as_posix()) +from sphinx_exts import redirects -from sphinx_exts.redirects import build_redirect_page # noqa: E402 + +@pytest.fixture +def app(tmp_path): + source = tmp_path / "source" + output = tmp_path / "output" + source.mkdir() + output.mkdir() + + return SimpleNamespace( + srcdir=source, + config=SimpleNamespace( + redirects_file="redirects.txt", + source_suffix={".rst": "restructuredtext"}, + ), + builder=SimpleNamespace(outdir=output), + ) + + +@pytest.mark.parametrize( + ("source", "target", "expected_source", "expected_target"), + [ + pytest.param( + "old.rst", + "new.rst", + "old.html", + "new.html", + id="root-page", + ), + pytest.param( + "hooks/index.rst", + "concepts.rst", + "hooks/index.html", + "../concepts.html", + id="nested-page", + ), + pytest.param( + "guides/nested/old.rst", + "guides/new.rst", + "guides/nested/old.html", + "../../guides/new.html", + id="deeply-nested-page", + ), + pytest.param( + "old.rst", + "new.rst#section", + "old.html", + "new.html#section", + id="anchor", + ), + pytest.param( + "_api/airflow/old.rst", + "providers/example/new.rst", + "_api/airflow/old.html", + "../../providers/example/new.html", + id="core-api-to-provider", + ), + pytest.param( + "hooks/old.rst", + "providers/example/new.rst", + "hooks/old.html", + "../../providers/example/new.html", + id="provider-destination", + ), + pytest.param( + "_api/airflow/providers/old.rst", + "providers/example/new.rst", + "_api/airflow/providers/old.html", + "../../../../providers/example/new.html", + id="provider-api-destination", + ), + ], +) +def test_iter_redirects(app, source, target, expected_source, expected_target): + # The existing resolver uses the platform separator for parent prefixes. + expected_target = expected_target.replace("../", f"..{os.path.sep}") + (app.srcdir / "redirects.txt").write_text(f"{source} {target}\n", encoding="utf-8") + + assert list(redirects.iter_redirects(app)) == [(expected_source, expected_target)] + + +def test_iter_redirects_skips_comments_and_empty_lines(app): + (app.srcdir / "redirects.txt").write_text( + "# Old documentation paths\n" + "\n" + " \n" + "first.rst new-first.rst\n" + "# Another comment\n" + "second.rst new-second.rst\n", + encoding="utf-8", + ) + + assert list(redirects.iter_redirects(app)) == [ + ("first.html", "new-first.html"), + ("second.html", "new-second.html"), + ] + + +def test_iter_redirects_without_redirect_file(app): + assert list(redirects.iter_redirects(app)) == [] + + +def test_iter_redirects_uses_configured_source_suffix(app): + app.config.source_suffix = {".md": "markdown"} + (app.srcdir / "redirects.txt").write_text("old.md new.md\n", encoding="utf-8") + + assert list(redirects.iter_redirects(app)) == [("old.html", "new.html")] + + +def test_generate_html_redirects(app): + output = app.builder.outdir + # A spec'd mock passes the existing HTML-builder isinstance check. + app.builder = mock.Mock(spec=StandaloneHTMLBuilder) + app.builder.outdir = output + (app.srcdir / "redirects.txt").write_text( + "old.rst new.rst\nhooks/index.rst concepts.rst\n", + encoding="utf-8", + ) + + redirects.generate_redirects(app) + + assert (output / "old.html").read_text(encoding="utf-8") == (redirects.build_redirect_page("new.html")) + destination = f"..{os.path.sep}concepts.html" + assert (output / "hooks/index.html").read_text(encoding="utf-8") == ( + redirects.build_redirect_page(destination) + ) + + +def test_generate_redirects_skips_non_html_builder(app): + (app.srcdir / "redirects.txt").write_text("old.rst new.rst\n", encoding="utf-8") + + redirects.generate_redirects(app) + + assert not list(app.builder.outdir.rglob("*")) + + +def test_generate_redirects_without_redirect_file(app): + output = app.builder.outdir + app.builder = mock.Mock(spec=StandaloneHTMLBuilder) + app.builder.outdir = output + + redirects.generate_redirects(app) + + assert not list(output.rglob("*")) @pytest.mark.parametrize( @@ -36,8 +177,8 @@ pytest.param("../security/index.html", id="without-anchor"), ], ) -def test_redirect_page_keeps_the_requested_anchor(to_path): - page = build_redirect_page(to_path) +def test_redirect_page_contains_anchor_preserving_script(to_path): + page = redirects.build_redirect_page(to_path) assert f'var target = "{to_path}";' in page assert 'target = target.split("#")[0] + window.location.hash;' in page diff --git a/providers/common/ai/docs/operations.rst b/providers/common/ai/docs/operations.rst index 0eae34cd5e6b..3a5052f72629 100644 --- a/providers/common/ai/docs/operations.rst +++ b/providers/common/ai/docs/operations.rst @@ -20,6 +20,9 @@ Reliability and operations ========================== +.. meta:: + :description: Keep AI tasks reliable and affordable: cheap retries with durable execution, model-driven retry policies, OpenTelemetry tracing, provider fallback, agent security and troubleshooting. + An AI task fails in more ways than a SQL task, and it costs money each time it runs. - :doc:`recovery` keeps an agent run going through a provider outage, and replays the diff --git a/providers/common/ai/docs/rag_pipelines.rst b/providers/common/ai/docs/rag_pipelines.rst index 96592e0e0486..2c9854e44141 100644 --- a/providers/common/ai/docs/rag_pipelines.rst +++ b/providers/common/ai/docs/rag_pipelines.rst @@ -20,6 +20,9 @@ Document and RAG pipelines ========================== +.. meta:: + :description: Build a retrieval pipeline from three ordinary tasks: load documents, embed them with LlamaIndex, and retrieve the closest chunks to answer a question with LLMOperator. + .. note:: Experimental: this can change or be removed in a minor release of this provider. diff --git a/providers/common/ai/docs/sandbox/configuration.rst b/providers/common/ai/docs/sandbox/configuration.rst index 34129a3d245b..db008a3589af 100644 --- a/providers/common/ai/docs/sandbox/configuration.rst +++ b/providers/common/ai/docs/sandbox/configuration.rst @@ -18,6 +18,9 @@ Configure a sandbox =================== +.. meta:: + :description: Configure what a sandbox is provisioned with (network, environment, credentials), get results out of it, share one between tasks, and how it behaves on failure, retry and cleanup. + .. note:: Experimental: this can change or be removed in a minor release of this provider. diff --git a/providers/common/ai/docs/tool_approval.rst b/providers/common/ai/docs/tool_approval.rst index 425054b19603..f1ae3d4872e9 100644 --- a/providers/common/ai/docs/tool_approval.rst +++ b/providers/common/ai/docs/tool_approval.rst @@ -20,6 +20,14 @@ Approve an agent's tool calls ============================= +.. meta:: + :description: Pause an agent before it runs a tool you marked for approval, such as one that refunds an order or writes to a table, and let a person approve or reject that call from the Required Actions page. + +.. note:: + + Experimental: this can change or be removed in a minor release of this provider. + See :ref:`howto/stability`. + .. seealso:: To approve, edit or reject an LLM operator's output instead, see :doc:`approval_gates`; to review an agent's final answer over several rounds, see :doc:`hitl_review`. diff --git a/uv.lock b/uv.lock index cedd5d8256d6..4324e7479a1b 100644 --- a/uv.lock +++ b/uv.lock @@ -2785,6 +2785,7 @@ docs = [ { name = "sphinx-copybutton" }, { name = "sphinx-design" }, { name = "sphinx-jinja" }, + { name = "sphinx-llm" }, { name = "sphinx-rtd-theme" }, { name = "sphinxcontrib-applehelp" }, { name = "sphinxcontrib-devhelp" }, @@ -2974,6 +2975,7 @@ requires-dist = [ { name = "sphinx-copybutton", marker = "extra == 'docs'", specifier = ">=0.5.2" }, { name = "sphinx-design", marker = "extra == 'docs'", specifier = ">=0.5.0" }, { name = "sphinx-jinja", marker = "extra == 'docs'", specifier = ">=2.0.2" }, + { name = "sphinx-llm", marker = "extra == 'docs'", specifier = ">=1.1.0,<1.2" }, { name = "sphinx-rtd-theme", marker = "extra == 'docs'", specifier = ">=2.0.0" }, { name = "sphinxcontrib-applehelp", marker = "extra == 'docs'", specifier = ">=1.0.4" }, { name = "sphinxcontrib-devhelp", marker = "extra == 'docs'", specifier = ">=1.0.2" }, @@ -24846,6 +24848,38 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/20/9f/81fe50b1861bda8c02b4272a166d14455411e04865ddaf3616f25d12cd50/sphinx_jinja-2.0.2-py3-none-any.whl", hash = "sha256:705ebeb9b7a6018ca3f93724315a7c1effa6ba3db44d630e7eaaa15e4ac081a8", size = 4355, upload-time = "2022-07-05T11:57:47.861Z" }, ] +[[package]] +name = "sphinx-llm" +version = "1.1.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "markdown-it-py" }, + { name = "sphinx", version = "9.0.4", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.12'" }, + { name = "sphinx", version = "9.1.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version == '3.12.*'" }, + { name = "sphinx", version = "9.2.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.13'" }, + { name = "sphinx-markdown-builder" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/9b/2b/2529cb0b1acb85489167904649387ea7b17e3172ac3286fc0c8af2887bc5/sphinx_llm-1.1.0.tar.gz", hash = "sha256:5f3b41c0d7888c75a6fe9f92b1a965c50ee233eaf38673c0ef3501072599c617", size = 408770, upload-time = "2026-09-21T10:15:26.81Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/cb/06/8db70029d13ae3b5ef4dabd7496e15941f0f700b9e2f1fb77859bef97263/sphinx_llm-1.1.0-py3-none-any.whl", hash = "sha256:40cfadbfeb4483f4fd5b6c1c0b1a48152847f30febfa94fc413bbbe09c137953", size = 85878, upload-time = "2026-09-21T10:15:25.627Z" }, +] + +[[package]] +name = "sphinx-markdown-builder" +version = "0.6.11" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "docutils" }, + { name = "sphinx", version = "9.0.4", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.12'" }, + { name = "sphinx", version = "9.1.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version == '3.12.*'" }, + { name = "sphinx", version = "9.2.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.13'" }, + { name = "tabulate" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/ad/13/102d7134743120db25e636ffb57a30818e95a416583dca83aadac9c5dd87/sphinx_markdown_builder-0.6.11.tar.gz", hash = "sha256:ba3bf33e0e42ff30ae686ac73957a95e6d045790dcfbaca012dd8ae01794e577", size = 24020, upload-time = "2026-08-16T06:51:38.158Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/c9/71/06b415631c2e494c80546073b46013d1715dceb3abe30bd63b34b4e7d9ca/sphinx_markdown_builder-0.6.11-py3-none-any.whl", hash = "sha256:acfb94d6ee66c7a47da0ca0420578fa16f115812af25b8fd21755d5909aacf51", size = 18088, upload-time = "2026-08-16T06:51:36.81Z" }, +] + [[package]] name = "sphinx-rtd-theme" version = "3.1.0"