This is an automated email from the ASF dual-hosted git repository.
HyukjinKwon pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/spark-connect-rust.git
The following commit(s) were added to refs/heads/master by this push:
new c61bc4a7 [MINOR][BUILD] Check the rust snippets of README.md too,
report the markdown line of a failing snippet, and refuse rust fences that the
snippet check skips
c61bc4a7 is described below
commit c61bc4a72d06c7bbe22f120bc3f65acb9de31fb3
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Fri Nov 13 15:04:50 2026 +0900
[MINOR][BUILD] Check the rust snippets of README.md too, report the
markdown line of a failing snippet, and refuse rust fences that the snippet
check skips
### What changes were proposed in this pull request?
A follow-up of the post-merge review of #602. The doc snippet checker
(`scripts/check_doc_snippets.py`):
- Scans `README.md`, the GitHub and PyPI front page, as well as
`docs/**/*.md`, and compiles its Quickstart.
- Fails, instead of silently skipping, a fence whose info string starts
with `rust` (or `{.rust`) but is neither plain `rust` nor `{.rust .no-run}`.
- Skips a fence directly after a `<!-- snippet: no-run -->` line. GitHub
and PyPI don't render that comment, so the block keeps its Rust highlighting.
- Reports each failure as `<md file>:<line of the fence>: <message>`.
Before, it named only the file, and the rustc line numbers pointed at a deleted
temporary harness.
- Parses fences line by line: backtick and tilde fences at any indent, with
`\r\n` normalized. It counts every fence line and fails on one that it does not
parse as a block, such as one in a blockquote or nested in a longer fence, and
on an unclosed fence, instead of swallowing the next fence.
Two doc changes: `docs/streaming.md`'s `rust,ignore` fence becomes `{.rust
.no-run}`, and the README's `spark_wasm_udf` example gets the no-run marker
plus the imports and `fn main` wrapper of `docs/udfs.md`. That example needs
the macro's build step, so it can't compile in the harness.
### Why are the changes needed?
The review found three problems: a `rust,ignore` fence that was skipped
without a message, a README that was never checked (its UDF example lacked
imports), and failure messages without a markdown location.
### Does this PR introduce _any_ user-facing change?
No. It changes the documentation check and two examples' fences.
### How was this patch tested?
- `python3 -m unittest discover -s scripts/tests`: 50 tests pass. 14 of
them are new: the parser, the refusal, the count guard, the no-run marker,
scanning README.md, and the report format.
- `python3 scripts/check_doc_snippets.py` on a debug build: "Checked 60
rust snippet(s); 0 failed to compile or were refused.", where master checks 59.
With a bad fence and a `rust,ignore` fence added to README.md, it fails with
`README.md:131: error[E0308]: mismatched types` and `README.md:135: fence info
"rust,ignore" is neither "rust" nor "{.rust .no-run}", so it would be skipped`.
- The Rust lib tests, the `--no-run` builds, `cargo fmt`, the stub audit
and ruff pass.
### Was this patch authored or co-authored using generative AI tooling?
Generated-by: Claude Opus 5.5
This pull request and its description were written by Isaac.
Closes #617 from HyukjinKwon/MINOR-doc-snippet-coverage.
Authored-by: Hyukjin Kwon <[email protected]>
Signed-off-by: Hyukjin Kwon <[email protected]>
---
README.md | 14 ++-
docs/streaming.md | 2 +-
scripts/check_doc_snippets.py | 155 +++++++++++++++++++++++++------
scripts/tests/test_check_doc_snippets.py | 123 +++++++++++++++++++++++-
4 files changed, 260 insertions(+), 34 deletions(-)
diff --git a/README.md b/README.md
index 6b961c52..d75af986 100644
--- a/README.md
+++ b/README.md
@@ -95,13 +95,25 @@ API, running a Spark Connect server, and more.
Write UDFs as plain Rust functions and call them directly — `#[spark_wasm_udf]`
compiles them to WebAssembly and ships them to the executors:
+<!-- snippet: no-run -->
```rust
+use spark_connect::{SparkSession, col};
+use spark_connect_macros::spark_wasm_udf;
+
#[spark_wasm_udf]
mod udfs {
pub fn add_one(x: i64) -> i64 { x + 1 }
}
-spark.range(5)?.select([udf::add_one(col("id"))?]).show(20)?;
+#[cfg(not(target_arch = "wasm32"))]
+fn main() -> Result<(), Box<dyn std::error::Error>> {
+ let spark = SparkSession::builder()
+ .remote("sc://localhost:15002")
+ .get_or_create()?;
+
+ spark.range(5)?.select([udf::add_one(col("id"))?]).show(20)?;
+ Ok(())
+}
```
See the [WASM UDF guide](https://apache.github.io/spark-connect-rust/udfs/) for
diff --git a/docs/streaming.md b/docs/streaming.md
index 920e1008..d49de792 100644
--- a/docs/streaming.md
+++ b/docs/streaming.md
@@ -97,7 +97,7 @@ query.await_termination(None)?;
Gracefully stop a streaming query:
-```rust,ignore
+```{.rust .no-run}
query.stop()?;
```
diff --git a/scripts/check_doc_snippets.py b/scripts/check_doc_snippets.py
index b8fae61f..28e2a2bb 100644
--- a/scripts/check_doc_snippets.py
+++ b/scripts/check_doc_snippets.py
@@ -20,8 +20,9 @@
The published guides drifted out of sync with the API (examples that used `lit`
without importing it, or `SparkSessionBuilder` without a `use`), and nothing
in CI
caught it because the docs workflow only *deploys*. This type-checks every
-```rust``` block, including the indented ones of list items, admonitions and
content
-tabs, so a doc example can't reference a symbol the crate doesn't export.
+```rust``` block of the README and of the docs, including the indented ones of
list
+items, admonitions and content tabs, so a doc example can't reference a symbol
the
+crate doesn't export.
Each block is wrapped in a small harness that binds ``spark`` and ``df`` (so
the
common "continue from an earlier block" fragments type-check) and is run
through
@@ -35,8 +36,14 @@ a snippet that needs a feature/macro the snippet harness
doesn't build - e.g. th
`wasm-udf` `#[spark_wasm_udf]` examples) should be fenced as ```{.rust
.no-run}```.
That brace form still renders as a Rust code block in mkdocs/superfences
(unlike
```rust,ignore```, whose comma makes superfences drop the fence entirely and
print
-the backticks literally), and it is not matched by the checker below, so it is
not
-compiled.
+the backticks literally). A plain ```rust``` fence can be skipped too, by
putting the
+HTML comment `<!-- snippet: no-run -->` on the line directly before it. GitHub
and PyPI
+do not show that comment, and they keep the Rust highlighting that the brace
form loses
+there, so the README uses it. Only a marker on the line directly before a
fence counts.
+A fence whose info string starts with `rust` (or `{.rust`) and is neither
```rust```,
+nor that brace form, nor marked, is reported as a failure, not skipped. A
fence the
+checker cannot parse (never closed, or in a blockquote or nested in another
fence) is
+reported too, rather than swallowing the fences after it.
Usage:
cargo build -p apache-spark-connect
@@ -51,27 +58,107 @@ import sys
import tempfile
from collections.abc import Sequence
from pathlib import Path
+from typing import NamedTuple
REPO = Path(__file__).resolve().parent.parent
-# ```rust``` (checked) vs ```{.rust .no-run}``` (rendered but skipped). We
only check
-# plain ```rust``` fences; any info string with a comma/space/brace is left
alone. A fence
-# may be indented, as in a list item, an admonition or a content tab, and its
closing fence
-# with it.
-_BLOCK = re.compile(
- r"^(?P<indent>[ \t]*)```rust[ \t]*$\n(?P<body>.*?)^[ \t]*```[ \t]*$",
re.DOTALL | re.MULTILINE
-)
+# A fence line: any indent, optional `>` (blockquote) prefixes, then three or
more backticks
+# or tildes. Every such line is counted, so a fence that is not parsed is
noticed.
+_FENCE_LINE = re.compile(r"^[ \t>]*(?:`{3,}|~{3,})")
+# An opening fence of the top level, with its indentation and info string. A
fence may be
+# indented, as in a list item, an admonition or a content tab, and its closing
fence with it.
+_OPEN = re.compile(r"^(?P<indent>[ \t]*)(?P<marker>`{3,}|~{3,})(?P<info>.*)$")
+# A closing fence: the marker's character, at least as long as the opening
marker, and nothing
+# else on the line.
+_CLOSE = re.compile(r"^[ \t]*(?P<marker>`{3,}|~{3,})[ \t]*$")
+# The info string of a snippet that is compiled, and of one that is rendered
but not compiled.
+CHECKED_INFO = "rust"
+NO_RUN_INFO = "{.rust .no-run}"
+# A marker on the line directly before a fence, which skips the fence as
NO_RUN_INFO does.
+_NO_RUN_MARKER = re.compile(r"^[ \t]*<!--[ \t]*snippet:[ \t]*no-run[ \t]*-->[
\t]*$")
-def snippets(text: str) -> list[str]:
- """The ```rust``` snippets of the Markdown ``text``. Each line of an
indented snippet loses
- up to the indentation of its opening fence, as Markdown strips it."""
- found = []
- for m in _BLOCK.finditer(text):
- width = len(m.group("indent"))
- lines = m.group("body").splitlines()
- found.append("\n".join(ln[min(width, len(ln) - len(ln.lstrip(" \t")))
:] for ln in lines))
- return found
+
+class Fence(NamedTuple):
+ """A fenced block: the line of its opening fence, its info string, its
body, and whether
+ a no-run marker is on the line before it."""
+
+ line: int
+ info: str
+ code: str
+ no_run: bool = False
+
+
+def _closes(line: str, marker: str) -> bool:
+ m = _CLOSE.match(line)
+ return (
+ m is not None
+ and m.group("marker")[0] == marker[0]
+ and len(m.group("marker")) >= len(marker)
+ )
+
+
+def fences(text: str) -> tuple[list[Fence], list[tuple[int, str]]]:
+ """The fenced blocks of the Markdown ``text``, and the problems found in
its fences as
+ (line, message) pairs. The body of an indented block loses up to the
indentation of its
+ opening fence, as Markdown strips it."""
+ lines = text.replace("\r\n", "\n").split("\n")
+ found: list[Fence] = []
+ problems: list[tuple[int, str]] = []
+ parsed: set[int] = set() # the lines of the opening and closing fences of
the blocks
+ i = 0
+ while i < len(lines):
+ opened = _OPEN.match(lines[i])
+ if opened is None:
+ i += 1
+ continue
+ marker = opened.group("marker")
+ close = next((j for j in range(i + 1, len(lines)) if _closes(lines[j],
marker)), None)
+ if close is None:
+ problems.append((i + 1, "this fence is never closed"))
+ return found, problems
+ width = len(opened.group("indent"))
+ body = [ln[min(width, len(ln) - len(ln.lstrip(" \t"))) :] for ln in
lines[i + 1 : close]]
+ info = " ".join(opened.group("info").split())
+ marked = i > 0 and _NO_RUN_MARKER.match(lines[i - 1]) is not None
+ found.append(Fence(i + 1, info, "\n".join(body), marked))
+ parsed.update((i + 1, close + 1))
+ i = close + 1
+ # Every fence line must belong to a block: a fence in a blockquote, or
nested in another
+ # fence, is not parsed and would otherwise be skipped silently.
+ fence_lines = [n for n, ln in enumerate(lines, 1) if _FENCE_LINE.match(ln)]
+ if len(fence_lines) != len(parsed):
+ unparsed = next(n for n in fence_lines if n not in parsed)
+ problems.append(
+ (
+ unparsed,
+ f"{len(fence_lines) - len(parsed)} fence line(s) are not
parsed as blocks "
+ "(a fence in a blockquote or nested in another fence is not
checked)",
+ )
+ )
+ return found, problems
+
+
+def snippets(text: str) -> tuple[list[Fence], list[tuple[int, str]]]:
+ """The ```rust``` blocks of the Markdown ``text`` to compile, and the
problems to report:
+ the problems of ``fences``, and each fence whose info string starts with
``rust`` or
+ ``{.rust`` but is neither of the two forms that are checked or skipped."""
+ blocks, problems = fences(text)
+ checked = []
+ for block in blocks:
+ if block.no_run:
+ continue
+ if block.info == CHECKED_INFO:
+ checked.append(block)
+ elif block.info.lower().startswith(("rust", "{.rust")) and block.info
!= NO_RUN_INFO:
+ problems.append(
+ (
+ block.line,
+ f'fence info "{block.info}" is neither "{CHECKED_INFO}"
nor "{NO_RUN_INFO}", '
+ "so it would be skipped",
+ )
+ )
+ return checked, problems
# Harness: bind the identifiers the fragments assume from earlier blocks. `use`
@@ -176,34 +263,42 @@ def crate_artifacts() -> tuple[Path | None, list[Path]]:
return rlib, deps
+def markdown_files() -> list[Path]:
+ """The Markdown files to check: the README, which GitHub and PyPI show,
then the docs."""
+ docs = sorted(glob.glob(str(REPO / "docs" / "**" / "*.md"),
recursive=True))
+ return [REPO / "README.md", *(Path(md) for md in docs)]
+
+
def main() -> int:
rlib, deps = crate_artifacts()
if rlib is None or not rlib.exists():
print("!! no rlib of apache-spark-connect - run `cargo build -p
apache-spark-connect`")
return 2
- failures = []
+ # Each failure is (file, line of the fence, message).
+ failures: list[tuple[str, int, str]] = []
checked = 0
with tempfile.TemporaryDirectory() as td:
tmpdir = Path(td)
idx = 0
- for md in sorted(glob.glob(str(REPO / "docs" / "**" / "*.md"),
recursive=True)):
- text = Path(md).read_text()
- for code in snippets(text):
+ for md in markdown_files():
+ rel = str(md.relative_to(REPO))
+ blocks, problems = snippets(md.read_text())
+ failures.extend((rel, line, message) for line, message in problems)
+ for block in blocks:
idx += 1
checked += 1
- ok, err = check_block(code, tmpdir, idx, rlib, deps)
+ ok, err = check_block(block.code, tmpdir, idx, rlib, deps)
if not ok:
- rel = Path(md).relative_to(REPO)
# First rustc error line is the most informative.
first = next(
(ln for ln in err.splitlines() if
ln.startswith("error")), err[:200]
)
- failures.append((str(rel), first))
+ failures.append((rel, block.line, first))
- print(f"Checked {checked} rust snippet(s); {len(failures)} failed to
compile.")
- for rel, err in failures:
- print(f" {rel}: {err}")
+ print(f"Checked {checked} rust snippet(s); {len(failures)} failed to
compile or were refused.")
+ for rel, line, message in sorted(failures):
+ print(f" {rel}:{line}: {message}")
return 1 if failures else 0
diff --git a/scripts/tests/test_check_doc_snippets.py
b/scripts/tests/test_check_doc_snippets.py
index 34715598..6df0ab73 100644
--- a/scripts/tests/test_check_doc_snippets.py
+++ b/scripts/tests/test_check_doc_snippets.py
@@ -94,10 +94,129 @@ class SnippetsTests(unittest.TestCase):
"",
]
)
+ checked, problems = checker.snippets(text)
self.assertEqual(
- checker.snippets(text),
- ["let a = 1;", "let b = 2;\n let c = 3;", "let d = 4;"],
+ [(block.line, block.code) for block in checked],
+ [(1, "let a = 1;"), (5, "let b = 2;\n let c = 3;"), (10, "let d
= 4;")],
)
+ self.assertEqual(problems, [])
+
+ def test_refuses_a_rust_fence_that_would_be_skipped(self):
+ text = "\n".join(
+ [
+ "```rust,ignore",
+ "query.stop()?;",
+ "```",
+ "",
+ "```{.rust}",
+ "let a = 1;",
+ "```",
+ "",
+ "```rust no_run",
+ "let b = 2;",
+ "```",
+ ]
+ )
+ checked, problems = checker.snippets(text)
+ self.assertEqual(checked, [])
+ self.assertEqual([line for line, _ in problems], [1, 5, 9])
+ self.assertIn('"rust,ignore"', problems[0][1])
+
+ def test_no_run_form_is_skipped_without_a_problem(self):
+ text = '```{.rust .no-run}\nlet a: i32 = "bad";\n```\n```{.rust
.no-run}\n```\n'
+ self.assertEqual(checker.snippets(text), ([], []))
+
+ def test_no_run_marker_before_a_rust_fence_skips_it(self):
+ text = (
+ '<!-- snippet: no-run -->\n```rust\nlet a: i32 = "bad";\n```\n'
+ "```rust\nlet b = 2;\n```\n"
+ )
+ checked, problems = checker.snippets(text)
+ self.assertEqual([(block.line, block.code) for block in checked], [(5,
"let b = 2;")])
+ self.assertEqual(problems, [])
+
+ def test_no_run_marker_not_directly_before_a_fence_does_nothing(self):
+ for text in (
+ "<!-- snippet: no-run -->\n\n```rust\nlet a = 1;\n```\n",
+ "<!-- snippet: no-run -->\nSome text.\n```rust\nlet a = 1;\n```\n",
+ ):
+ with self.subTest(text=text):
+ checked, problems = checker.snippets(text)
+ self.assertEqual([block.line for block in checked], [3])
+ self.assertEqual(problems, [])
+
+ def test_plain_and_non_rust_fences_are_not_refused(self):
+ text = "```python\nprint(1)\n```\n```\nplain\n```\n```bash\nls\n```\n"
+ self.assertEqual(checker.snippets(text), ([], []))
+
+ def test_tilde_fences_are_parsed_as_blocks(self):
+ checked, problems = checker.snippets("~~~rust\nlet a = 1;\n~~~\n")
+ self.assertEqual([(block.line, block.code) for block in checked], [(1,
"let a = 1;")])
+ self.assertEqual(problems, [])
+
+ def test_crlf_line_endings_are_normalized(self):
+ checked, problems = checker.snippets("```rust\r\nlet a =
1;\r\n```\r\n")
+ self.assertEqual([block.code for block in checked], ["let a = 1;"])
+ self.assertEqual(problems, [])
+
+ def test_unclosed_fence_is_reported_at_its_line(self):
+ checked, problems = checker.snippets("text\n```rust\nlet a = 1;\n")
+ self.assertEqual(checked, [])
+ self.assertEqual(problems, [(2, "this fence is never closed")])
+
+ def test_fence_opened_inside_an_unclosed_fence_is_not_swallowed(self):
+ # The second fence has an info string, so it cannot close the first
one. It is
+ # reported as a fence line that is not parsed, rather than passed over
silently.
+ checked, problems = checker.snippets("```rust\nlet a =
1;\n```rust\nlet b = 2;\n```\n")
+ self.assertEqual([block.line for block in checked], [1])
+ self.assertEqual([line for line, _ in problems], [3])
+ self.assertIn("not parsed", problems[0][1])
+
+ def test_fence_in_a_blockquote_is_reported_not_skipped(self):
+ checked, problems = checker.snippets("> ```rust\n> let a = 1;\n>
```\n")
+ self.assertEqual(checked, [])
+ self.assertEqual([line for line, _ in problems], [1])
+ self.assertIn("2 fence line(s)", problems[0][1])
+
+ def test_nested_longer_fence_is_reported(self):
+ # The three-backtick lines are body of the four-backtick fence, not
fences of their
+ # own, and the checker says so rather than compiling them as code.
+ _, problems = checker.snippets("````rust\n```\nlet a =
1;\n```\n````\n")
+ self.assertEqual([line for line, _ in problems], [2])
+
+
+class MarkdownFilesTests(unittest.TestCase):
+ def test_the_readme_is_checked_with_the_docs(self):
+ files = checker.markdown_files()
+ self.assertEqual(files[0], checker.REPO / "README.md")
+ self.assertIn(checker.REPO / "docs" / "udfs.md", files)
+
+
+class MainReportTests(unittest.TestCase):
+ def test_failures_are_reported_at_the_line_of_the_fence(self):
+ with tempfile.TemporaryDirectory() as td:
+ root = Path(td)
+ (root / "docs").mkdir()
+ doc = root / "docs" / "a.md"
+ doc.write_text('Intro.\n\n```rust\nlet n: i64 =
"bad";\n```\n\n```rust,ignore\n```\n')
+ rlib = root / "libspark_connect.rlib"
+ rlib.write_text("")
+ rustc_error = "error[E0308]: mismatched types\n -->
snippet_1.rs:11:5\n"
+ with (
+ patch.object(checker, "REPO", root),
+ patch.object(checker, "markdown_files", return_value=[doc]),
+ patch.object(checker, "crate_artifacts", return_value=(rlib,
[])),
+ patch.object(checker, "check_block", return_value=(False,
rustc_error)),
+ patch("sys.stdout", new_callable=io.StringIO) as out,
+ ):
+ self.assertEqual(checker.main(), 1)
+ lines = out.getvalue().splitlines()
+ self.assertEqual(
+ lines[0], "Checked 1 rust snippet(s); 2 failed to compile or were
refused."
+ )
+ self.assertEqual(lines[1], " docs/a.md:3: error[E0308]: mismatched
types")
+ self.assertTrue(lines[2].startswith(' docs/a.md:7: fence info
"rust,ignore"'))
+ self.assertEqual(len(lines), 3)
class CrateArtifactsTests(unittest.TestCase):
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]