diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index f35be4fb..0ebb99ae 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -1,24 +1,35 @@ name: docs +# Runs the examples, builds the documentation site from their output, and deploys it. +# +# examples one leg per example, a job of its own in the PR's list of checks, named +# " (README)": it executes examples//README.md with +# tools/execute_markdown.py, against this checkout of benchx, and uploads +# docs-, the page that the site shows. A failing example is a red check. +# build needs every example. Puts the pages in docs/generated/examples/, builds the site (strict). +# deploy needs build. Only for a push to main, or a run by hand on main. +# +# It runs for every pull request. A push to main deploys only when it changes one of the paths +# below: the pages show the output of benchx, so the package and what it depends on count. To add +# an example, see examples/README.md. + on: push: branches: [main] paths: - "docs/**" - - "src/benchx/schemas/**" + - "src/benchx/**" + - "pyproject.toml" + - "uv.lock" - "tools/gen_docs.py" + - "tools/execute_markdown.py" + - "examples/**" - "zensical.toml" - "README.md" - ".github/workflows/docs.yml" pull_request: branches: [main] - paths: - - "docs/**" - - "src/benchx/schemas/**" - - "tools/gen_docs.py" - - "zensical.toml" - - "README.md" - - ".github/workflows/docs.yml" + workflow_dispatch: concurrency: group: ${{ github.workflow }}-${{ github.ref }} @@ -28,15 +39,102 @@ permissions: contents: read jobs: + examples: + name: ${{ matrix.example }} (README) + runs-on: ubuntu-latest + timeout-minutes: 20 + strategy: + fail-fast: false + matrix: + example: [pyperf-suite] + env: + EXAMPLE: ${{ matrix.example }} + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3 + with: + enable-cache: true + cache-dependency-glob: uv.lock + + # The examples run plain `python` and `bx`, and the benchmark workers use the same + # `python`, so the environment goes on the PATH. benchx is installed in editable mode, which + # is where it reads its schemas from. The `test` extra brings pyperf and the runner's + # markdown-it-py; the `parquet` extra is for the stores of the examples, which are Parquet. + - name: Install benchx + run: | + uv python install 3.13 + uv sync --extra parquet --extra test --python 3.13 + echo "$PWD/.venv/bin" >> "$GITHUB_PATH" + + - name: Show what is under test + run: | + echo "python: $(python --version) ($(command -v python))" + echo "bx: $(command -v bx)" + echo "benchx: $(python -c 'import benchx; print(benchx.__file__)')" + echo "pyperf: $(python -c 'import pyperf; print(pyperf.__version__)')" + echo "commit: $(git rev-parse --short HEAD)" + + # From the root of the checkout, so that annotations carry a path relative to the + # repository and the page does not show the runner's paths. The page and the logs go + # outside the checkout. + - name: Execute examples/${{ matrix.example }}/README.md + run: | + python tools/execute_markdown.py \ + --source "examples/$EXAMPLE/README.md" \ + --output "$RUNNER_TEMP/pages/$EXAMPLE.md" \ + --logs "$RUNNER_TEMP/logs/$EXAMPLE" + + - name: Upload logs + if: always() + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: logs-${{ matrix.example }} + path: ${{ runner.temp }}/logs/${{ matrix.example }}/ + if-no-files-found: warn + retention-days: 14 + + - name: Upload the example's output + if: always() + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: results-${{ matrix.example }} + path: examples/${{ matrix.example }}/out/ + if-no-files-found: ignore + retention-days: 14 + + # The contract with `build`: docs- holds .md. + - name: Upload the page + if: success() + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: docs-${{ matrix.example }} + path: ${{ runner.temp }}/pages/${{ matrix.example }}.md + if-no-files-found: error + retention-days: 14 + build: + needs: examples runs-on: ubuntu-latest steps: - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + with: + persist-credentials: false - uses: astral-sh/setup-uv@d4b2f3b6ecc6e67c4457f6d3e41ec42d3d0fcb86 # v5.4.2 - - name: Generate derived pages (landing page, benchx page, schema reference) - run: uv run --python 3.12 --with-requirements docs/requirements.txt python tools/gen_docs.py + # generated/.md, one page for each docs- artifact of this run. + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + pattern: docs-* + path: generated + merge-multiple: true + + # --executed: every example in examples/ must have its executed page, or this stops. + - name: Generate derived pages (landing page, schema reference, example pages) + run: uv run --python 3.12 --with-requirements docs/requirements.txt python tools/gen_docs.py --executed generated - name: Build site run: uv run --python 3.12 --with-requirements docs/requirements.txt zensical build --strict --clean @@ -46,7 +144,7 @@ jobs: path: site deploy: - if: github.event_name == 'push' && github.ref == 'refs/heads/main' + if: (github.event_name == 'push' || github.event_name == 'workflow_dispatch') && github.ref == 'refs/heads/main' needs: build runs-on: ubuntu-latest permissions: diff --git a/.github/workflows/e2e.yml b/.github/workflows/e2e.yml index 9f19208a..cb293d04 100644 --- a/.github/workflows/e2e.yml +++ b/.github/workflows/e2e.yml @@ -8,8 +8,6 @@ name: e2e examples # arrow builds a small Google Benchmark suite with CMake and compares the builds: # examples/arrow/demo/run.sh # examples/arrow/archery-local/run.sh -# pyperf-suite runs a suite of Python functions with `bx bench`: -# examples/pyperf-suite/run.sh # matmul-params runs one parametrized benchmark, numpy and torch at three sizes, with # `bx bench`; the quick version from the example's README: # examples/matmul-params @@ -241,59 +239,6 @@ jobs: if-no-files-found: warn retention-days: 14 - pyperf-suite: - name: pyperf-suite (run.sh) - runs-on: ubuntu-latest - timeout-minutes: 20 - steps: - - name: Check out benchx - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 - with: - path: benchx - - - name: Clone benchx_examples - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 - with: - repository: benchx-dev/benchx_examples - ref: ${{ inputs.examples_ref || 'main' }} - path: benchx_examples - - - uses: astral-sh/setup-uv@d4b2f3b6ecc6e67c4457f6d3e41ec42d3d0fcb86 # v5.4.2 - with: - enable-cache: true - cache-dependency-glob: benchx/uv.lock - - # The script runs plain `python` and `bx`, and the workers need pyperf, which the - # `test` extra brings. benchx is installed in editable mode, which is where it reads - # its schemas from. - - name: Install benchx - working-directory: benchx - run: | - uv python install 3.13 - uv sync --extra parquet --extra test --python 3.13 - echo "$PWD/.venv/bin" >> "$GITHUB_PATH" - - - name: Show what is under test - run: | - echo "python: $(python --version) ($(command -v python))" - echo "bx: $(command -v bx)" - echo "pyperf: $(python -c 'import pyperf; print(pyperf.__version__)')" - echo "benchx: $(git -C benchx rev-parse --short HEAD)" - echo "benchx_examples: $(git -C benchx_examples rev-parse --short HEAD)" - - - name: Run the pyperf suite - working-directory: benchx_examples/examples/pyperf-suite - run: bash ./run.sh - - - name: Upload the output - if: always() - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 - with: - name: pyperf-suite-output - path: benchx_examples/examples/pyperf-suite/out - if-no-files-found: warn - retention-days: 14 - matmul-params: name: matmul-params (quick version) runs-on: ubuntu-latest diff --git a/.gitignore b/.gitignore index 0ffb9c1c..ff4d114c 100644 --- a/.gitignore +++ b/.gitignore @@ -8,9 +8,8 @@ __pycache__/ .ruff_cache/ .mypy_cache/ dist/ -# generated by tools/gen_docs.py -docs/index.md -docs/schemas/ +# generated by tools/gen_docs.py: the home page, the schema reference, the pages of the examples +docs/generated/ .coverage .coverage.* htmlcov/ diff --git a/README.md b/README.md index be0ff7d3..fb8a006c 100644 --- a/README.md +++ b/README.md @@ -112,7 +112,8 @@ uv run --with-requirements docs/requirements.txt python tools/gen_docs.py uv run --with-requirements docs/requirements.txt zensical serve ``` -`tools/gen_docs.py` generates `docs/index.md` and `docs/schemas/` (gitignored); +`tools/gen_docs.py` builds `docs/generated/` (gitignored), the folder the site is built from: the +pages of `docs/` copied, plus the home page, the schema reference and the pages of the examples; `zensical.toml` configures the site, and `.github/workflows/docs.yml` builds and deploys it. diff --git a/docs/benchx.md b/docs/benchx.md index ec7b2ba9..d64079f9 100644 --- a/docs/benchx.md +++ b/docs/benchx.md @@ -196,8 +196,7 @@ function without readable source has no version. functions: the module's git checkout is the target, its path the suite, and the functions are exact case names. `bx run` is the layer underneath: it executes a finished order, so `bx run results/KEY/orders/order.json` replays any bench run. -`examples/pyperf-suite` in [benchx_examples](https://github.com/benchx-dev/benchx_examples) -is a runnable walk-through. +[`examples/pyperf-suite`](examples/pyperf-suite.md) is a runnable walk-through. Environments that cannot share a process, such as two venvs with different numpy versions, are measured by separate `bx bench` calls that share a `--run-key`; `--label NAME=VALUE`, `--round R[/N]` diff --git a/docs/examples.md b/docs/examples.md index b9d160f0..09e4640e 100644 --- a/docs/examples.md +++ b/docs/examples.md @@ -30,14 +30,19 @@ so that core `benchx` remains cloud-free and CI-vendor-neutral: machine catalog, and thin caller workflows. Use `benchx-arrow` as a minimal template when setting up continuous benchmarking for another project. -## Local worked examples +## Worked examples of local benchmarking -Standalone, runnable local examples live in -[`benchx-dev/benchx_examples`](https://github.com/benchx-dev/benchx_examples) -and are exercised by CI: +The sources of these examples live in [`examples/`](https://github.com/benchx-dev/benchx/tree/main/examples) +in this repository. + +- [`pyperf-suite`](examples/pyperf-suite.md) -- timing a suite of Python functions with + `bx bench`, the local store, and `bx series` / `bx history`. + +## Additional, cookbook-style examples + +Standalone, runnable examples of local usage live in a separate repository, +[`benchx-dev/benchx_examples`](https://github.com/benchx-dev/benchx_examples): -- `examples/pyperf-suite` — timing a Python function suite with `pyperf` - (`bx bench` and replaying orders with `bx run`). - `examples/numpy-venvs` — cross-environment comparison across two virtual environments ([UC-04](use-cases/UC-04-cross-env.md)). - `examples/pandas-asv` -- cross-environment comparison run of a specific benchmark diff --git a/examples/README.md b/examples/README.md new file mode 100644 index 00000000..66048f48 --- /dev/null +++ b/examples/README.md @@ -0,0 +1,86 @@ +# Examples + +Each directory here is an example: a `README.md` and the files it uses. CI executes the README +(`tools/execute_markdown.py`) on every pull request, and the documentation site shows the result +(`docs/examples.md` lists the examples). + +## Writing one + +- `sh` and `bash` fences are executed with Bash (`-e -o pipefail`), a whole fence at a time, in the + example's directory. A `$ ` at the start of a line is removed before the run and kept on the + page. `python` fences are executed in one namespace shared by the whole README. + Add `noexec` after the language (```` ```sh noexec ````) to show a block without running it. + Unlabelled fences, and any other language (`json`, ...), are shown as they are. +- The first `text` or `json` fence after an executable block is its committed output snapshot. The + page leaves it out and shows the output of the run instead, in a fence of the same language (so + `cat benchx.conf.json` followed by a `json` fence shows the file once, as JSON). Prose may come in + between; a heading or another fence ends the association. The two are never compared. A `json` + fence that is not the output of the block before it (the file that a command writes, say) needs a + heading or another fence before it, or another language (`jsonc`). +- A README with no executable block is allowed: it is copied to the site as it is. +- A block that exits non-zero, or a `python` block that raises, fails the example, and with it the + pull request's check. +- `bx bench` exits 0 when a benchmark case fails, so the runner also reads the example's store before + and after each `sh` or `bash` block that ends with status 0. A block that stored a failed result + (error, censored, partial or skipped: a missing dependency is an error) fails the example, and + the message names the case. A block marked `exit=N` with N other than 0 is not checked, and an + example cannot show a failed case in its output. Only what is stored is seen: not a run with + `--no-ingest`. Any other check on the results (the number of points in a series, say) is a + command in the block that fails when it is wrong, as in section 7 of `pyperf-suite`. +- A `sh` or `bash` block that is meant to fail, to show an error, says so: ```` ```bash exit=1 ````. + It must then end with exactly that status: a 0, or any other status, fails the example just as + an unexpected failure does, so the page cannot go on showing an error the code no longer gives. + Its output goes into the page as for any block, and the run goes on. The fence is one script + run with `-e`, so the status is that of the first command that fails, and the commands after it + do not run: put the failing command last. The page has the fence without `exit=1` (the site's + fence parser does not take a `key=value` there). Python blocks have no such marker. +- On the page, ANSI escape sequences are removed from the output, and so is the path of the + repository checkout (`/home/runner/work/benchx/benchx/examples/x` shows as `examples/x`). +- Do not link to other files of the example from the README: the page is built into the site on its + own, so a link to a file of the example (`bench_suite.py`) is dead there without any warning, and a + link to a Markdown page that does not exist fails `zensical build --strict`. +- Benchmarks run in the checkout, so the example measures the benchx repository as the tree. Put the + output in an ignored directory (`out/`, as `pyperf-suite` does). + +## Adding one + +1. Create `examples//README.md` and its files. +2. Add `` to the matrix of the `examples` job in `.github/workflows/docs.yml`. Without it + `tools/gen_docs.py --executed` stops, since the site would show the example unexecuted. +3. Add a line for it under "Worked examples of local benchmarking" in `docs/examples.md`. + +An example that needs more than `benchx` and `pyperf` (a compiler, another package) gets its own job in +`docs.yml` instead of a matrix leg. The contract is the artifact: the job uploads `docs-` +containing `.md`. + +## Running one locally + +From the root of the repository, in an environment with benchx and what the example needs +(`uv sync --extra test` gives `bx`, pyperf and the runner's `markdown-it-py`): + +```sh +python tools/execute_markdown.py --source examples/pyperf-suite/README.md \ + --output /tmp/pages/pyperf-suite.md --logs /tmp/logs/pyperf-suite +``` + +The page and the per-block logs go where you point `--output` and `--logs`, not into the checkout. +The example's own output goes to its `out/`. Remove an `out/` that an earlier run left before running +again: in `pyperf-suite` the store rejects a second run under the same run key. + +To build the site with the executed pages, in one command (the pages and the logs go in a temporary +directory, and an `out/` left by an earlier run is removed first): + +```sh +uv run --python 3.13 --extra parquet --extra test --with-requirements docs/requirements.txt \ + python tools/build_site.py # into site/; add --serve to preview it +``` + +Or by hand, after running the examples as above: + +```sh +python tools/gen_docs.py --executed /tmp/pages +zensical build --strict --clean # or: zensical serve +``` + +Without `--executed`, `tools/gen_docs.py` builds the pages from the committed READMEs, under a +"not executed" notice. diff --git a/examples/pyperf-suite/.gitignore b/examples/pyperf-suite/.gitignore new file mode 100644 index 00000000..ea93687f --- /dev/null +++ b/examples/pyperf-suite/.gitignore @@ -0,0 +1,2 @@ +out/ +__pycache__/ diff --git a/examples/pyperf-suite/README.md b/examples/pyperf-suite/README.md new file mode 100644 index 00000000..487e92d3 --- /dev/null +++ b/examples/pyperf-suite/README.md @@ -0,0 +1,314 @@ +# Example: benchmarking Python functions with `bx bench` + +A runnable example of a benchmark suite. `bench_suite.py` holds five small +functions; `bx bench` runs each one under [pyperf](https://pyperf.readthedocs.io), +writes benchx result files, delivers them to a local store, and prints a table. + +## First, install benchx + +We install `benchx` with `pyperf` + +``` +$ python3 -m venv .venv && . .venv/bin/activate # Python >= 3.11, or any environment you like +$ pip install pyperf benchx[parquet] +``` + +## Benchmarks + +In the simplest case, benchmarks are plain python functions. Here is an example suite +of several small microbenchmarks (here we only show one function out of five in the suite): + +```sh +$ head -20 bench_suite.py +``` + +```text +"""Example benchmark suite: plain Python functions, one case each. + +`bx bench bench_suite.py` runs every function named bench_* or benchmark_*. +Name functions on the command line to run only those: + bx bench bench_suite.py bench_sorted bench_join + +Each function is the timed body; pyperf calls it many times. Do your setup +at module level (it runs once per worker process, outside the timing). +""" + +import os + +DATA = list(range(2000, 0, -1)) +WORDS = [f"word{i}" for i in range(500)] + + +def bench_sorted(): + sorted(DATA) +``` + +Additionally, this directory contains an optional configuration file, `benchx.conf.json`, +which collects settings for the benchmarking process. See Sec. 8 below for details. + +The benchmark functions are timed bodies: `pyperf` calls each one many times, and does +the calibration (how many calls make up one value) itself. Put setup at module level. + + +## Run the benchmarks + +The main CLI entry point for the `benchx` package is the `bx` executable, which +supports several subcommands. + +### 1. Run all benchmarks with default settings + +The first subcommand is `bx bench` which accepts the +name of the suite or a selection of benchmarks: + +```bash +$ bx bench . --run-key example-all --out out/all +``` + +Here the first argument to `bx bench` is the current directory, and it makes it search +for functions names `bench_` in all python files in the current directory. +Other arguments are optional and are only provided for convenience: +`--out` controls where the output files go (default is `$PWD/out`), and `--run-key` +sets the key for the results of this run in the local store. If not provided, it will +be synthesized. +Specific parameters for running benchmarks (the number of repetitions +and so on) will be taken from the configuration file, `benchx.conf.json`. +The output lists benchmarks and their results: + + +```text +measuring bench_suite.py on . +precision: 5 processes x 3 values (config: /home/br/temp/bex/benchx.conf.json) +case median mean ± sd min .. max n status +----------------- -------- ------------------- -------------------- -- --------------------------------------------------- +bench_dict_build 21.42 us 21.45 us ± 326.9 ns 20.95 us .. 22.09 us 15 success [dirty-subject-tree, dirty-benchmark-tree] +bench_env_var 676.5 ns 675.3 ns ± 6.897 ns 663.6 ns .. 685.6 ns 15 success [dirty-subject-tree, dirty-benchmark-tree] +bench_join 4.296 us 4.302 us ± 27.51 ns 4.268 us .. 4.35 us 15 success [dirty-subject-tree, dirty-benchmark-tree] +bench_sorted 14.35 us 14.44 us ± 188.6 ns 14.28 us .. 14.92 us 15 success [dirty-subject-tree, dirty-benchmark-tree] +bench_sum_squares 34.18 us 34.35 us ± 344.5 ns 34.11 us .. 35.29 us 15 success [dirty-subject-tree, dirty-benchmark-tree] + +10 result(s) -> out/all (order sha256:6990583c3230) +/home/br/temp/bex/out/store.parquet: ingested 10, duplicate 0 +``` + +### 2. Run a single benchmark, with an environment variable and process controls + +To run a single benchmark from the suite, use the second optional argument of `bx bench`: + +```bash +$ bx bench . bench_env_var -e EXAMPLE_N=100000 --processes 3 \ + --run-key example-env --out out/env +``` +Note how parameters that control benchmark execution (here `--processes`) can supplied +as command line arguments---if provided, they superseded the values from the configuration file. +We also set an environment variable, which the benchmark reads, via the `-e` argument. + +```text +measuring bench_suite.py on . +precision: 3 processes x 3 values (config: /home/br/temp/bex/benchx.conf.json) +case median mean ± sd min .. max n status +-------------------------------- -------- ------------------- -------------------- - --------------------------------------------------- +bench_env_var [EXAMPLE_N=100000] 456.3 ns 455.2 ns ± 6.209 ns 446.9 ns .. 466.7 ns 9 success [dirty-subject-tree, dirty-benchmark-tree] + +2 result(s) -> out/env (order sha256:097cdeee8c33) +/home/br/temp/bex/out/store.parquet: ingested 2, duplicate 0 +``` + +### 3. Repeat a run + +Here we rerun a benchmark again under a new run key, so its series gets a second point: + + +```bash +$ bx bench . bench_join --run-key example-again --out out/again +``` + +```text +measuring bench_suite.py on . +precision: 5 processes x 3 values (config: /home/br/temp/bex/benchx.conf.json) +case median mean ± sd min .. max n status +---------- -------- ------------------- -------------------- -- --------------------------------------------------- +bench_join 4.381 us 4.393 us ± 61.69 ns 4.295 us .. 4.536 us 15 success [dirty-subject-tree, dirty-benchmark-tree] + +2 result(s) -> out/again (order sha256:7b5034bcad0c) +/home/br/temp/bex/out/store.parquet: ingested 2, duplicate 0 +``` + +Note that using a different `--run-key` is essential, while setting a different `--out` directory +only is not. + +### 4. Idempotency conflicts + +Attempting to reuse the same run key for a different workload is a user error. +The system will refuse to add the new result to the _local store_ (see Section 5 below): +results of the rerun will not be byte-identical, and the store maintains a one-to-one +correspondence between the run key and the run results. The error will be reported +as _idempotency conflict_: + + +```bash exit=1 +# same run-key +$ bx bench . bench_join --run-key example-again --out out/again2 +``` + +```text +measuring bench_suite.py on . +precision: 5 processes x 3 values (config: /home/br/temp/bex/benchx.conf.json) +case median mean ± sd min .. max n status +---------- -------- ------------------ -------------------- -- --------------------------------------------------- +bench_join 4.384 us 4.39 us ± 52.28 ns 4.336 us .. 4.549 us 15 success [dirty-subject-tree, dirty-benchmark-tree] + +2 result(s) -> out/again2 (order sha256:26d4dd076e27) + rejected example-again_bench_join_wall-time.json: idempotency-conflict — same (producer, ingest_key), different payload + rejected example-again_bench_join_load-average.json: idempotency-conflict — same (producer, ingest_key), different payload +/home/br/temp/bex/out/store.parquet: ingested 0, duplicate 0, rejected 2 (idempotency-conflict) +``` + + +### 5. The local store + +Benchmark results are saved to the local store. `bx head` lists its contents: + +```bash +$ bx head -n 10 +``` + +```text +/home/br/temp/bex/out/store.parquet: 14 result(s); latest 10, newest first + 13 2026-11-25 10:10:24 example-again bench_join load-average success 0.7 1 directory- local/gonzales + 12 2026-11-25 10:10:24 example-again bench_join wall-time success [dirty-subject-tree, dirty-benchmark-tree] 4.57613e-06 s directory- local/gonzales + 11 2026-11-25 10:10:08 example-env bench_env_var load-average success 0.52 1 directory- local/gonzales + 10 2026-11-25 10:10:08 example-env bench_env_var wall-time success [dirty-subject-tree, dirty-benchmark-tree] 4.45852e-07 s directory- local/gonzales + 9 2026-11-25 10:09:53 example-all bench_sum_squares load-average success 0.67 1 directory- local/gonzales + 8 2026-11-25 10:09:53 example-all bench_sum_squares wall-time success [dirty-subject-tree, dirty-benchmark-tree] 3.42711e-05 s directory- local/gonzales + 7 2026-11-25 10:09:50 example-all bench_sorted load-average success 0.64 1 directory- local/gonzales + 6 2026-11-25 10:09:50 example-all bench_sorted wall-time success [dirty-subject-tree, dirty-benchmark-tree] 1.44032e-05 s directory- local/gonzales + 5 2026-11-25 10:09:48 example-all bench_join load-average success 0.64 1 directory- local/gonzales + 4 2026-11-25 10:09:48 example-all bench_join wall-time success [dirty-subject-tree, dirty-benchmark-tree] 4.31922e-06 s directory- local/gonzales +``` + +Note that each run has two entries, one per measured quantity (by default: wall time and load average). + + +### 6. List the series in the store + +`bx series` lists the series from the local store. We can also filter by measured quantities. + +```bash +$ bx series --quantity wall-time +``` + +Note that `bench_env_var` workload has two entries: we ran it with two values of the envirornment variable, setting `-e` changes the environment, which `benchx` tracks: + +```text +bx series --quantity wall-time +1ba1bf938012 local/gonzales bench_dict_build wall-time [s] est=benchx/median/v1 +c4525d138f93 local/gonzales bench_env_var wall-time [s] est=benchx/median/v1 +72bbf2a3e37c local/gonzales bench_join wall-time [s] est=benchx/median/v1 +49318d657b29 local/gonzales bench_sorted wall-time [s] est=benchx/median/v1 +5442871527d0 local/gonzales bench_sum_squares wall-time [s] est=benchx/median/v1 +6d346fd5a7da local/gonzales bench_env_var wall-time [s] est=benchx/median/v1 +``` + +To filter by the workload use the `--workload` argument: `bx series --quantity wall-time --workload bench_env_var`. + + +### 7. The history of one series + +`bx history` lists the points of one series, one for each run. We take the series of +`bench_join` and see the two runs of it that we made, `example-all` and `example-again`. +The last line fails the example unless there are exactly two points: + +```bash +$ SERIES=$(bx series --workload bench_join --quantity wall-time | awk 'NR == 1 {print $1}') +$ bx history "$SERIES" | tee out/history.txt +$ [ "$(grep -c example- out/history.txt)" -eq 2 ] +``` + +```text +revision order unavailable without a revision graph; listed by measurement start +5828abd0be55 2026-11-27T14:08:37.171737Z 3.97284e-06 (server) example-all:bench_join:wall-time +5828abd0be55 2026-11-27T14:08:47.457609Z 3.96866e-06 (server) example-again:bench_join:wall-time +``` + + +### 8. The config file + +An optional `benchx.conf.json` file collects various configuration settings. Calling +`bx config init` writes a file with default settings, which you can then customize. +A bad config file is reported before anything runs. +Settings provided as command line arguments take precedence over the config file. +Here is an example: + +```bash +$ cat benchx.conf.json +``` + +```json +{ + "schema_version": "benchx/config/0.1.0", + "adapter": { + "name": "pyperf", + "suite": "bench_suite.py", + "precision": { + "repetitions": { + "mode": "fixed", + "levels": [{"unit": "process", "n": 5}, {"unit": "value", "n": 3}] + }, + "calibration": {"mode": "adaptive", "minimum_sample_seconds": 0.05}, + "warmup": {"mode": "count", "n_warmup": 1} + } + }, + "paths": {"store": "out/store.parquet", "results": "out"} +} +``` + +Here the suite is being with `pyperf` via its harness adapter; Additional settings are +supplied to `pyperf` through the work-order: + +- `repetitions.levels`: `process` is the number of worker processes, `value` the values + each one records. Leave a level out and it takes pyperf's default (20 and 3). +- `calibration`: `adaptive` with `minimum_sample_seconds` lets pyperf pick how many calls + make up one value; `{"mode": "fixed", "n_iterations": N}` fixes it. +- `warmup`: `{"mode": "count", "n_warmup": N}` discards N values per process, or `{"mode": "none"}`. +- Every key is optional; pyperf's defaults (20 x 3, adaptive 0.1 s, 1 warmup) fill the rest. + +Precision is resolved as: **flags, then the config file, then pyperf's defaults** +(20 processes x 3 values, 0.1 s calibration, 1 warmup). A level you leave out of the +file takes pyperf's default. + + + +### 9. What is written + +Finally, take a peek into the output directory (typically, you never need to look there +unless debugging): + +```bash +$ ls -l out/all/ +``` + +```text +drwxrwxr-x 3 br br 4096 ноя 25 11:09 artifacts +-rw-rw-r-- 1 br br 24869 ноя 25 11:09 bx.log +-rw-rw-r-- 1 br br 2799 ноя 25 11:09 example-all_bench_dict_build_load-average.json +-rw-rw-r-- 1 br br 6413 ноя 25 11:09 example-all_bench_dict_build_wall-time.json +-rw-rw-r-- 1 br br 2793 ноя 25 11:09 example-all_bench_env_var_load-average.json +-rw-rw-r-- 1 br br 6394 ноя 25 11:09 example-all_bench_env_var_wall-time.json +-rw-rw-r-- 1 br br 2787 ноя 25 11:09 example-all_bench_join_load-average.json +-rw-rw-r-- 1 br br 6388 ноя 25 11:09 example-all_bench_join_wall-time.json +-rw-rw-r-- 1 br br 2791 ноя 25 11:09 example-all_bench_sorted_load-average.json +-rw-rw-r-- 1 br br 6406 ноя 25 11:09 example-all_bench_sorted_wall-time.json +-rw-rw-r-- 1 br br 2801 ноя 25 11:09 example-all_bench_sum_squares_load-average.json +-rw-rw-r-- 1 br br 6403 ноя 25 11:09 example-all_bench_sum_squares_wall-time.json +drwxrwxr-x 2 br br 4096 ноя 25 11:09 orders +-rw-rw-r-- 1 br br 968 ноя 25 11:09 workorder-7ff9a9ec43dc8960acf3fcaf08a3d4ab4898e204f8bc7d09a2271d276e992980.json +``` + +`benchx` stores a host of information: + +- `bx.log` file is the log file of internal `benchx` operations (the default logging level is DEBUG); +- `example-...json` files contain detailed results from individual runs, which are ingested into the parquet store; +- "work orders" are internal `benchx` way of tracking what to run and how: you can exactly replay a run +with `bx run workorder-file.json`; +- `artifacts/` directory contains full details low-level inputs and outputs of harness adapters. + diff --git a/examples/pyperf-suite/bench_suite.py b/examples/pyperf-suite/bench_suite.py new file mode 100644 index 00000000..cf6589df --- /dev/null +++ b/examples/pyperf-suite/bench_suite.py @@ -0,0 +1,39 @@ +"""Example benchmark suite: plain Python functions, one case each. + +`bx bench bench_suite.py` runs every function named bench_* or benchmark_*. +Name functions on the command line to run only those: + bx bench bench_suite.py bench_sorted bench_join + +Each function is the timed body; pyperf calls it many times. Do your setup +at module level (it runs once per worker process, outside the timing). +""" + +import os + +DATA = list(range(2000, 0, -1)) +WORDS = [f"word{i}" for i in range(500)] + + +def bench_sorted(): + sorted(DATA) + + +def bench_join(): + ",".join(WORDS) + + +def bench_dict_build(): + {w: len(w) for w in WORDS} + + +def bench_sum_squares(): + sum(i * i for i in range(1000)) + + +def bench_env_var(): + """Reads EXAMPLE_N from the environment, to show `-e NAME=VALUE` reaching the workers.""" + int(os.environ.get("EXAMPLE_N", "100")) ** 2 + + +def helper_not_a_case(): + """Not named bench_*, so only run if you name it explicitly.""" diff --git a/examples/pyperf-suite/benchx.conf.json b/examples/pyperf-suite/benchx.conf.json new file mode 100644 index 00000000..bc595448 --- /dev/null +++ b/examples/pyperf-suite/benchx.conf.json @@ -0,0 +1,13 @@ +{ + "schema_version": "benchx/config/0.1.0", + "adapter": { + "name": "pyperf", + "suite": "bench_suite.py", + "precision": { + "repetitions": { "mode": "fixed", "levels": [{ "unit": "process", "n": 5 }, { "unit": "value", "n": 3 }] }, + "calibration": { "mode": "adaptive", "minimum_sample_seconds": 0.05 }, + "warmup": { "mode": "count", "n_warmup": 1 } + } + }, + "paths": { "store": "out/store.parquet", "results": "out" } +} diff --git a/pyproject.toml b/pyproject.toml index 6a6cb411..c6ca4422 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -25,7 +25,7 @@ Repository = "https://github.com/benchx-dev/benchx" [project.optional-dependencies] parquet = ["pyarrow>=19"] -test = ["pytest", "pyperf", "asv_runner"] +test = ["pytest", "pyperf", "asv_runner", "markdown-it-py"] [project.scripts] bx = "benchx.cli:main" diff --git a/tests/test_execute_markdown.py b/tests/test_execute_markdown.py new file mode 100644 index 00000000..79ada11f --- /dev/null +++ b/tests/test_execute_markdown.py @@ -0,0 +1,338 @@ +"""The Markdown runner, tools/execute_markdown.py, which executes the examples' READMEs. + +Apart from the tests of benchx itself: the runner is a development tool that lives in tools/, and +needs markdown-it-py (the `test` extra). These tests skip where either is missing. An installed +benchx has no tools/ (`python -m pytest --pyargs benchx` runs this file from site-packages). +""" + +import importlib.util +import json +import os +import subprocess +import sys +from pathlib import Path + +import pytest + +pytest.importorskip("markdown_it") + +ROOT = Path(__file__).resolve().parents[1] +TOOL = ROOT / "tools" / "execute_markdown.py" +if not TOOL.is_file(): + pytest.skip("tools/execute_markdown.py is not part of an installed benchx", allow_module_level=True) + +_spec = importlib.util.spec_from_file_location("execute_markdown", TOOL) +runner = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(runner) + + +@pytest.fixture +def repo(tmp_path, monkeypatch): + """A repository root with examples/ex/, which is also where the runner is started from. + + The page and the logs go next to it, not into it, as they do in CI. + """ + root = tmp_path / "repo" + (root / "examples" / "ex").mkdir(parents=True) + monkeypatch.chdir(root) + return root + + +def source_of(repo, text): + source = repo / "examples" / "ex" / "README.md" + source.write_text(text) + return source + + +def page_of(repo, text): + """Execute `text` as the README of the example, and return the page.""" + source = source_of(repo, text) + output = repo.parent / "out" / "ex.md" + runner.run(source, output, repo.parent / "logs") + return output.read_text() + + +def test_fresh_output_replaces_the_committed_snapshot(repo): + page = page_of(repo, "# T\n\n```sh\necho hello\n```\n\n```text\nOLD\n```\n\nafter\n") + assert "```sh\necho hello\n```" in page # the block is kept + assert "```text\nhello\n```" in page + assert "OLD" not in page and page.rstrip().endswith("after") + + +def test_prose_may_come_between_a_block_and_its_snapshot(repo): + page = page_of(repo, "```sh\necho a\n```\n\nSome prose.\n\n```text\nOLD\n```\n") + assert "```text\na\n```" in page and "Some prose." in page and "OLD" not in page + + +@pytest.mark.parametrize("between", ["## Next\n", "```yaml\na: 1\n```\n"], ids=["heading", "fence"]) +def test_a_heading_or_another_fence_ends_the_association(repo, between): + page = page_of(repo, f"```sh\necho a\n```\n\n{between}\n```text\nKEEP\n```\n") + assert "KEEP" in page # no longer a snapshot of the block above: it is an ordinary fence + + +def test_a_json_snapshot_is_replaced_by_the_output_in_a_json_fence(repo): + page = page_of(repo, "# T\n\n```sh\necho '{\"new\": 1}'\n```\n\nSome prose.\n\n```json\n{\"old\": 0}\n```\n\nafter\n") + assert '```json\n{"new": 1}\n```' in page # the output, once, in the language of the snapshot + assert "old" not in page and "```text" not in page + assert "Some prose." in page and page.rstrip().endswith("after") + assert page.count("```json") == 1 # the snapshot is gone, not shown next to the output + + +def test_only_the_first_snapshot_is_replaced(repo): + page = page_of(repo, "```sh\necho a\n```\n\n```json\nOLD\n```\n\n```text\nKEEP\n```\n\n```json\nKEEP2\n```\n") + assert "OLD" not in page and "KEEP\n" in page and "KEEP2" in page + + +def test_a_json_fence_after_a_heading_or_of_another_language_is_not_a_snapshot(repo): + after_heading = page_of(repo, "```sh\necho a\n```\n\n## Next\n\n```json\n{\"keep\": 1}\n```\n") + assert '```json\n{"keep": 1}\n```' in after_heading and "```text\na\n```" in after_heading + other_language = page_of(repo, "```sh\necho a\n```\n\n```jsonc\n// keep\n```\n") + assert "```jsonc\n// keep\n```" in other_language and "```text\na\n```" in other_language + + +def test_noexec_unlabelled_and_other_fences_are_kept_and_not_run(repo): + text = "```sh noexec\nexit 1\n```\n\n```\n$ pip install x\n```\n\n```json\n{}\n```\n" + assert page_of(repo, text) == text # `exit 1` would have failed the run + + +def test_a_readme_with_no_executable_block_is_copied(repo, capsys): + text = "# Only prose\n\nNothing to run here.\n" + assert page_of(repo, text) == text + assert "No executable blocks" in capsys.readouterr().out + + +def test_a_dollar_prompt_is_removed_before_the_run_and_kept_on_the_page(repo): + page = page_of(repo, "```sh\n$ echo one\ntrue\n$ echo two\n```\n") + assert "```sh\n$ echo one\ntrue\n$ echo two\n```" in page + assert "```text\none\ntwo\n```" in page + + +def test_output_containing_backticks_gets_a_longer_fence(repo): + page = page_of(repo, "```sh\nprintf '%s\\n' '```'\n```\n") + assert "````text\n```\n````" in page + + +def test_python_blocks_share_one_namespace(repo): + page = page_of(repo, "```python\nx = 41\n```\n\n```python\nprint(x + 1)\n```\n") + assert "```text\n42\n```" in page + + +def test_stderr_is_part_of_the_output(repo): + assert "```text\nerr\n```" in page_of(repo, "```sh\necho err >&2\n```\n") + + +def test_ansi_escapes_and_the_checkout_path_are_left_out_of_the_page_but_not_of_the_log(repo): + page = page_of(repo, ( + "```sh\n" + "printf '\\033[36m$ bx run\\033[0m\\n'\n" + 'echo "config: $(pwd -P)/benchx.conf.json"\n' + 'echo "root: $(cd ../.. && pwd -P)"\n' + "```\n")) + assert "```text\n$ bx run\nconfig: examples/ex/benchx.conf.json\nroot: .\n```" in page + assert "\x1b" not in page and str(repo) not in page + log = (repo.parent / "logs" / "block-001.log").read_text() + assert "\x1b[36m" in log and str(repo) in log + + +def test_a_failing_block_raises_with_an_annotation_and_writes_no_page(repo, capsys): + source = source_of(repo, "# T\n\n```sh\nexit 3\n```\n\n```sh\ntouch ran\n```\n") + output = repo.parent / "out" / "ex.md" + with pytest.raises(RuntimeError, match="status 3"): + runner.run(source, output, repo.parent / "logs") + assert "::error file=examples/ex/README.md,line=3::" in capsys.readouterr().out + assert not output.exists() + assert not (repo / "examples" / "ex" / "ran").exists() # the blocks after it did not run + + +def test_a_block_marked_exit_is_expected_to_fail_and_the_run_goes_on(repo): + page = page_of(repo, ( + "# T\n\n```sh exit=1\necho before\nfalse\necho never\n```\n\n```text\nOLD\n```\n\n" + "```sh\necho next\n```\n")) + assert "```sh\necho before\nfalse\necho never\n```" in page # the block is kept, without its marker + assert "```text\nbefore\n```" in page # `false` stopped the script (-e): "never" is not in the output + assert "OLD" not in page and "```text\nnext\n```" in page # the snapshot is replaced, the next block ran + assert "exit=" not in page + + +def test_the_marker_is_left_out_of_every_fence_of_the_page_and_the_fence_is_kept_as_it_was(repo): + page = page_of(repo, "~~~sh exit=2\nexit 2\n~~~\n\n```sh noexec exit=1\nexit 1\n```\n") + assert page == "~~~sh\nexit 2\n~~~\n\n```sh noexec\nexit 1\n```\n" # a noexec block is not run, so not checked + + +@pytest.mark.parametrize(("marked", "script", "said"), [ + ("exit=1", "true", r"status 0, not the exit=1"), + ("exit=1", "exit 2", r"status 2, not the exit=1"), + ("exit=2", "exit 1", r"status 1, not the exit=2"), + ("exit=0", "exit 1", r"status 1;"), +], ids=["a-success", "another-failure", "a-lower-one", "zero-is-the-default"]) +def test_a_block_that_does_not_end_with_its_marked_status_fails_the_run(repo, capsys, marked, script, said): + source = source_of(repo, f"# T\n\n```sh {marked}\n{script}\n```\n\n```sh\ntouch ran\n```\n") + output = repo.parent / "out" / "ex.md" + with pytest.raises(RuntimeError, match=said): + runner.run(source, output, repo.parent / "logs") + assert "::error file=examples/ex/README.md,line=3::" in capsys.readouterr().out + assert not output.exists() and not (repo / "examples" / "ex" / "ran").exists() + + +@pytest.mark.parametrize("marked", ["exit=", "exit=x", "exit=-1", "exit=256", "exit=1 exit=2"], + ids=["empty", "word", "negative", "too-large", "twice"]) +def test_a_malformed_marker_fails_the_run_before_the_block_runs(repo, capsys, marked): + source = source_of(repo, f"```sh {marked}\ntouch ran\n```\n") + with pytest.raises(ValueError, match="exit="): + runner.run(source, repo.parent / "out" / "ex.md", repo.parent / "logs") + assert "::error file=examples/ex/README.md,line=1::" in capsys.readouterr().out + assert not (repo / "examples" / "ex" / "ran").exists() + + +def test_a_python_block_cannot_be_marked_exit(repo): + source = source_of(repo, "```python exit=1\nopen('ran', 'w')\n```\n") + with pytest.raises(ValueError, match="only sh and bash"): + runner.run(source, repo.parent / "out" / "ex.md", repo.parent / "logs") + assert not (repo / "examples" / "ex" / "ran").exists() + + +def test_a_failing_python_block_raises_and_its_traceback_is_in_the_log(repo): + source = source_of(repo, "```python\nraise ValueError('boom')\n```\n") + output = repo.parent / "out" / "ex.md" + with pytest.raises(ValueError, match="boom"): + runner.run(source, output, repo.parent / "logs") + assert "ValueError: boom" in (repo.parent / "logs" / "block-001.log").read_text() + assert not output.exists() + + +def test_the_source_is_not_modified_and_cannot_be_the_output(repo): + text = "```sh\necho hi\n```\n\n```text\nOLD\n```\n" + source = source_of(repo, text) + runner.run(source, repo.parent / "out" / "ex.md", repo.parent / "logs") + assert source.read_text() == text + with pytest.raises(ValueError, match="differ"): + runner.run(source, source, repo.parent / "logs") + assert source.read_text() == text + + +def test_the_command_line(repo): + source = source_of(repo, "```sh\necho cli\n```\n") + output = repo.parent / "out" / "ex.md" + args = [sys.executable, str(TOOL), "--source", str(source), "--output", str(output), + "--logs", str(repo.parent / "logs")] + done = subprocess.run(args, cwd=repo, capture_output=True, text=True, check=False) + assert done.returncode == 0, done.stderr + assert "```text\ncli\n```" in output.read_text() + source.write_text("```sh\nexit 1\n```\n") + output.unlink() + failed = subprocess.run(args, cwd=repo, capture_output=True, text=True, check=False) + assert failed.returncode != 0 and "::error" in failed.stdout and not output.exists() + + +# The failed results that `bx bench` leaves in the store while it exits 0. A `bx` of the tests +# answers `bx head --json` with the lines of $FAKE_STORE, which a block writes to. + + +@pytest.fixture +def fake_bx(tmp_path, monkeypatch): + scripts = tmp_path / "scripts" + scripts.mkdir() + (scripts / "bx").write_text( + '#!/bin/sh\n' + '[ "$1" = head ] || exit 64\n' + 'if [ -n "$FAKE_BX_ERROR" ]; then echo "$FAKE_BX_ERROR" >&2; exit 2; fi\n' + 'if [ -f "$FAKE_STORE" ]; then cat "$FAKE_STORE"; fi\n') + (scripts / "bx").chmod(0o755) + monkeypatch.setenv("PATH", f"{scripts}{os.pathsep}{os.environ['PATH']}") + monkeypatch.setenv("FAKE_STORE", str(tmp_path / "store.jsonl")) + + +def result(status, case="bench_x", quantity="wall-time", reason=None, kind=None, message=None): + """One line of `bx head --json`, with the fields that the runner reads.""" + measurement = {"status": status, "quantity": {"name": quantity}} + measurement.update({k: v for k, v in {"reason": reason, "kind": kind}.items() if v}) + return json.dumps({ + "ingest_key": f"r:{case}:{quantity}:{status}", + "provenance": {"run_key": "r", "info": {"message": message} if message else {}}, + "coordinates": {"workload": {"name": case, "parameters": {"n": "10"}}}, + "measurement": measurement}) + + +def stores(*lines): + """A block that appends to the store of the test, as `bx bench` does.""" + return "printf '%s\\n' " + " ".join(f"'{line}'" for line in lines) + ' >> "$FAKE_STORE"' + + +@pytest.mark.parametrize("status", ["error", "censored", "partial", "skipped"]) +def test_a_block_that_exits_0_but_stored_a_failed_result_fails_the_run(repo, fake_bx, status): + source = source_of(repo, f"```sh\n{stores(result(status, reason='harness.error', message='boom'))}\n```\n") + output = repo.parent / "out" / "ex.md" + with pytest.raises(RuntimeError, match=rf"status 0, but 1 result\(s\) it stored failed:\n " + rf"r: bench_x \[n=10\], wall-time: {status} \(harness.error\): boom"): + runner.run(source, output, repo.parent / "logs") + assert not output.exists() + + +def test_results_that_did_not_fail_and_the_load_average_do_not_fail_the_run(repo, fake_bx): + rows = [result("success"), + result("success", quantity="load-average", kind="condition"), + result("skipped", quantity="load-average", kind="condition", reason="probe-unavailable")] + page_of(repo, f"```sh\n{stores(*rows)}\n```\n") + + +def test_a_failure_stored_before_a_block_is_not_blamed_on_it_and_a_marked_block_is_not_checked(repo, fake_bx): + page = page_of(repo, ( + f"```sh exit=1\n{stores(result('error'))}\nfalse\n```\n\n" + f"```sh\n{stores(result('success', case='other'))}\n```\n")) + assert "exit=" not in page + + +def test_a_new_failure_is_found_though_an_earlier_block_stored_one_too(repo, fake_bx): + source = source_of(repo, ( + f"```sh exit=1\n{stores(result('error'))}\nfalse\n```\n\n" + f"```sh\n{stores(result('error', case='other'))}\n```\n")) + with pytest.raises(RuntimeError, match=r"1 result\(s\) it stored failed:\n r: other "): + runner.run(source, repo.parent / "out" / "ex.md", repo.parent / "logs") + + +def test_a_store_that_bx_cannot_read_fails_the_block(repo, fake_bx, monkeypatch): + monkeypatch.setenv("FAKE_BX_ERROR", "requires pyarrow") + source = source_of(repo, "```sh\ntrue\n```\n") + with pytest.raises(RuntimeError, match=r"bx head could not read the store \(status 2\): requires pyarrow"): + runner.run(source, repo.parent / "out" / "ex.md", repo.parent / "logs") + + +def test_nothing_is_checked_where_bx_is_not_installed(repo, monkeypatch): + monkeypatch.setattr(runner.shutil, "which", lambda name: None) + assert runner.failed_results(repo) is None + assert "```text\nhi\n```" in page_of(repo, "```sh\necho hi\n```\n") + + +# With the real `bx` and pyperf, which also keeps the runner in step with the stored documents. + + +@pytest.fixture +def bench_example(repo, monkeypatch): + pytest.importorskip("pyperf") + scripts = Path(sys.executable).parent + if not (scripts / "bx").exists(): + pytest.skip("bx is not installed next to this Python") + monkeypatch.setenv("PATH", f"{scripts}{os.pathsep}{os.environ['PATH']}") + example = repo / "examples" / "ex" + (example / "benchx.conf.json").write_text(json.dumps({ + "schema_version": "benchx/config/0.1.0", "paths": {"store": "out/store.jsonl", "results": "out"}})) + (example / "bench_x.py").write_text( + "import importlib\n\n\n" + "def bench_ok():\n sum(range(10))\n\n\n" + "def bench_needs_a_library():\n importlib.import_module('no_such_library_for_the_test')\n") + + +QUICK = "--processes 1 --values 1 --min-time 0.01" + + +def test_a_case_that_bx_bench_could_not_measure_fails_the_run(bench_example, repo): + source = source_of(repo, f"```sh\nbx bench bench_x.py {QUICK} --run-key bad\n```\n") + with pytest.raises(RuntimeError, match=r"status 0, but \d+ result\(s\) it stored failed:\n" + r" bad: bench_needs_a_library, wall-time: error \(harness.error\): " + r"ModuleNotFoundError: No module named 'no_such_library_for_the_test'"): + runner.run(source, repo.parent / "out" / "ex.md", repo.parent / "logs") + + +def test_cases_that_bx_bench_measured_pass(bench_example, repo): + page = page_of(repo, f"```sh\nbx bench bench_x.py bench_ok {QUICK} --run-key good\n```\n") + assert "bench_ok" in page and "success" in page diff --git a/tools/build_site.py b/tools/build_site.py new file mode 100644 index 00000000..a335b814 --- /dev/null +++ b/tools/build_site.py @@ -0,0 +1,105 @@ +"""Build the documentation site with the examples executed, in one command. + + python tools/build_site.py # into site/ + python tools/build_site.py --serve # and preview it, http://127.0.0.1:8000 + +This is what the docs workflow does, on this machine: it executes the README of every example +(tools/execute_markdown.py), puts the pages in docs/generated/examples/ (tools/gen_docs.py --executed), and +builds the site with Zensical in strict mode. The pages and the logs of the runner go in a +temporary directory, which is removed when the site is built; if an example fails, no site is +built and the directory is kept, so that its logs can be read. + +The Python that runs this script must have what the examples need and what the build needs: +benchx with `bx` and pyperf (the `parquet` and `test` extras), markdown-it-py (the `test` extra) +and Zensical (docs/requirements.txt). The examples run `bx` and `python` from the PATH, and this +script puts the directory of its own Python first on it. For example: + + uv run --python 3.13 --extra parquet --extra test --with-requirements docs/requirements.txt \\ + python tools/build_site.py + +The examples benchmark this checkout, so an uncommitted change to a tracked file shows in their +output as a `dirty-subject-tree` warning. Each example writes into its own `out/`, ignored by git; +one left by an earlier run is removed first, since the stores reject a run that was made before. +""" + +from __future__ import annotations + +import argparse +import os +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +TOOLS = ROOT / "tools" + +sys.path.insert(0, str(TOOLS)) +from gen_docs import example_names # the one definition of what an example is + + +def fail(message: str) -> int: + print(f"error: {message}", file=sys.stderr) + return 1 + + +def main() -> int: + parser = argparse.ArgumentParser( + description="Build the documentation site with the examples executed " + "(see the top of this file).") + parser.add_argument("--serve", action="store_true", + help="preview the site with `zensical serve` instead of building it into site/") + args = parser.parse_args() + + # The examples run `bx` and `python` from the PATH: the ones of the environment of this Python. + env = {**os.environ, + "PATH": os.pathsep.join([str(Path(sys.executable).parent), os.environ.get("PATH", "")])} + zensical = shutil.which("zensical", path=env["PATH"]) + problems = [] + if subprocess.run([sys.executable, "-c", "import markdown_it"], capture_output=True, check=False).returncode: + problems.append("markdown-it-py is not installed in this environment (the `test` extra)") + if shutil.which("bx", path=env["PATH"]) is None: + problems.append("`bx` is not on the PATH: benchx is not installed in this environment") + if zensical is None: + problems.append("Zensical is not installed in this environment (docs/requirements.txt)") + if problems: + return fail("; ".join(problems) + ". See the top of tools/build_site.py.") + + names = example_names() + tmp = Path(tempfile.mkdtemp(prefix="benchx-examples-")) + pages, logs = tmp / "pages", tmp / "logs" + for name in names: + stale = ROOT / "examples" / name / "out" + if stale.exists(): + print(f"removing {stale.relative_to(ROOT)}, left by an earlier run", flush=True) + shutil.rmtree(stale) + print(f"\n=== executing examples/{name}/README.md", flush=True) + done = subprocess.run( + [sys.executable, str(TOOLS / "execute_markdown.py"), + "--source", f"examples/{name}/README.md", + "--output", str(pages / f"{name}.md"), "--logs", str(logs / name)], + cwd=ROOT, env=env, check=False) + if done.returncode: + return fail(f"example {name} failed, so no site was built. Logs, one per block: {logs / name}") + + print("\n=== building the site", flush=True) + generate = [sys.executable, str(TOOLS / "gen_docs.py"), "--executed", str(pages)] + if subprocess.run(generate, cwd=ROOT, env=env, check=False).returncode: + return fail(f"tools/gen_docs.py failed. The pages of the examples are in {pages}") + shutil.rmtree(tmp) # the pages are in docs/generated/examples/ now + build = [zensical, "serve"] if args.serve else [zensical, "build", "--strict", "--clean"] + try: + if subprocess.run(build, cwd=ROOT, env=env, check=False).returncode: + return fail(f"`zensical {build[1]}` failed") + except KeyboardInterrupt: # the end of `--serve` + return 0 + + if not args.serve: + print("\nBuilt site/. To look at it: python -m http.server -d site" + " (or run this script with --serve; the pages link by directory, which file:// does not follow)") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/execute_markdown.py b/tools/execute_markdown.py new file mode 100644 index 00000000..c1ca40fc --- /dev/null +++ b/tools/execute_markdown.py @@ -0,0 +1,523 @@ +"""Execute the code blocks of a Markdown file and render a page with fresh output. + + python tools/execute_markdown.py --source examples/NAME/README.md \\ + --output OUT/NAME.md --logs LOGS/NAME + +Run it from the root of the repository: the path of that directory is what is left out of +the output (see below), and what GitHub annotations are relative to. It needs `markdown-it-py` +(the `test` extra of benchx). + +Conventions: +- sh/bash fences: executed with Bash (-e -o pipefail), a whole fence at a time, in the + directory of the source file. A `$ ` at the start of a line is removed before the run (the + page keeps it, as a prompt). +- python fences: executed in one namespace shared by the whole file. +- A language followed by `noexec` (```sh noexec) is not executed. +- A sh/bash fence that is meant to fail says so: ```sh exit=1. The block must end with exactly + that status (a 0 fails the run as well as any other status), its output goes into the page as + for any block, and the run goes on. The fence is one script run with -e, so the status is that + of the first command that fails and the commands after it do not run: put it last. The page + has the fence without its `exit=1`: the site's fence parser does not take a key=value there. + Python fences have no such marker: one that raises fails the run. +- A sh/bash fence that ends with status 0 must also leave no failed result in the example's + store: `bx bench` exits 0 when a case fails, but it stores the result with its status. The + runner reads the store (`bx head --json`, run in the directory of the source file) before and + after the block, and a result that is new and has the status error, censored, partial or + skipped fails the run. The load-average results are not the benchmark's own and are left out. + A block marked `exit=N` with N other than 0 is not checked: it is meant to fail. Nothing is + checked where `bx` is not on the PATH. Only what is stored is seen: a run with --no-ingest, or + a store that the fence itself relocates (with BENCHX_HOME, say), is not. +- The first `text` or `json` fence after an executable block is a committed output snapshot: + it is left out of the page, and the output of the run is put after the block instead, in a + fence of the same language (so the output of `cat config.json` is shown as JSON, once). Prose + may come between the block and its snapshot; a heading or another fence ends the association. + A `json` fence that is not the output of the block before it (the file that a command writes, + say) needs a heading or another fence in between, or another language (`jsonc`). +- Unlabelled and other fences are kept as they are. +- Output is never compared with the snapshot. +- A file with no executable block is allowed: the page is a copy of it. + +In the output that goes into the page, ANSI escape sequences are removed and the path of the +directory the runner was started in is dropped (`/home/runner/work/x/x/examples/a/b` is +printed as `examples/a/b`, the directory itself as `.`). The logs keep the output as it was. + +The source file is never modified. The page and the logs are written to other places, and +the page only after every block has run: a failing block leaves no page. +""" + +import argparse +import contextlib +import io +import json +import os +import re +import shutil +import subprocess +import sys +import traceback +from pathlib import Path + +from markdown_it import MarkdownIt + +EXECUTABLE_LANGUAGES = {"sh", "bash", "python"} + +# The languages of a committed output snapshot, which the fresh output replaces. +SNAPSHOT_LANGUAGES = {"text", "json"} + +# The statuses of a failed result. `skipped` is one too: an example runs where what it needs is +# installed, so a skipped case means that something is missing. +FAILED_STATUSES = {"error", "censored", "partial", "skipped"} + +ANSI = re.compile(r"\x1b\[[0-9;?]*[ -/]*[@-~]") + + +def clean(text: str, root: Path) -> str: + """Output as it goes into the page: no ANSI escapes, no path of the runner's checkout.""" + text = ANSI.sub("", text) + prefix = str(root) + + if len(prefix) > 1: + text = text.replace(prefix + os.sep, "").replace(prefix, ".") + + return text + + +def text_fence(text: str, language: str = "text") -> str: + """Format captured output as a Markdown fence. + + `text`, unless it replaces a committed snapshot of another language (`json`). + """ + if not text.strip(): + return "" + + # Use a fence longer than any backtick sequence in output. + runs = re.findall(r"`+", text) + marker = "`" * max(3, max(map(len, runs), default=0) + 1) + + return f"\n{marker}{language}\n{text.rstrip()}\n{marker}\n" + + +def expected_status(attributes: list[str], language: str) -> int: + """The exit status a block must end with: N for `exit=N` after the language, else 0.""" + given = [a for a in attributes if a.startswith("exit=")] + if not given: + return 0 + + if language not in {"sh", "bash"}: + raise ValueError( + f"{given[0]}: only sh and bash blocks take exit=; a {language} block fails by raising" + ) + + if len(given) > 1: + raise ValueError(f"{' '.join(given)}: a block has one exit=") + + value = given[0].removeprefix("exit=") + + if not re.fullmatch(r"[0-9]{1,3}", value) or int(value) > 255: + raise ValueError(f"{given[0]}: exit= takes a status from 0 to 255") + + return int(value) + + +def page_fence(fence_lines: list[str], token) -> list[str]: + """The lines of a fence as they go into the page: without its `exit=N`. + + The site's fence parser (pymdownx.superfences) does not accept an unquoted key=value after the + language: it shows the fence as text, with the markup that follows it. The README keeps + `exit=N`, since that is what the runner reads; the page has no use for it. + """ + parts = token.info.strip().split() + kept = [part for part in parts if not part.startswith("exit=")] + + if len(kept) == len(parts): + return fence_lines + + opening = fence_lines[0] + indent = opening[: len(opening) - len(opening.lstrip(" "))] + newline = opening[len(opening.rstrip("\r\n")):] + + return [f"{indent}{token.markup}{' '.join(kept)}{newline}", *fence_lines[1:]] + + +def without_prompts(code: str) -> str: + """The code of a Bash block with the `$ ` prompt removed from the start of its lines.""" + return re.sub(r"(?m)^\$ ", "", code) + + +def failed_results(workdir: Path) -> dict[str, str] | None: + """The failed results in the store of the example in `workdir`: what each says, by ingest key. + + None where `bx` is not installed. `bx bench` exits 0 when a case fails, but it stores the + result with its status. The load-average results (a condition measurement, skipped where the + platform has no probe) are not the benchmark's own and are left out. + """ + if shutil.which("bx") is None: + return None + + done = subprocess.run( + ["bx", "head", "-n", str(10**9), "--json"], + cwd=workdir, + capture_output=True, + text=True, + check=False, + ) + + if done.returncode: + raise RuntimeError( + f"bx head could not read the store (status {done.returncode}): " + f"{(done.stderr or done.stdout).strip()}" + ) + + failed = {} + + for line in done.stdout.splitlines(): + result = json.loads(line) + measurement = result["measurement"] + + if measurement["status"] not in FAILED_STATUSES or measurement.get("kind") == "condition": + continue + + workload = result["coordinates"]["workload"] + parameters = ", ".join(f"{k}={v}" for k, v in (workload.get("parameters") or {}).items()) + case = workload["name"] + (f" [{parameters}]" if parameters else "") + message = (result["provenance"].get("info") or {}).get("message") + said = f"{measurement['status']} ({measurement['reason']})" if "reason" in measurement else measurement["status"] + + failed[result["ingest_key"]] = ( + f"{result['provenance']['run_key']}: {case}, {measurement['quantity']['name']}: {said}" + + (f": {message}" if message else "") + ) + + return failed + + +def execute_bash( + code: str, + workdir: Path, + logfile: Path, + expected: int = 0, +) -> str: + """Execute a complete Bash block and stream output to logs. + + The block must end with the status `expected`: any other one raises. A block that ends with 0 + must not have added a failed result to the store either (see `failed_results`). + """ + chunks = [] + before = failed_results(workdir) if expected == 0 else None + + with logfile.open("w", encoding="utf-8") as log, subprocess.Popen( + ["bash", "-e", "-o", "pipefail", "-c", code], + cwd=workdir, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + text=True, + bufsize=1, + ) as process: + assert process.stdout is not None + + for line in process.stdout: + print(line, end="", flush=True) + log.write(line) + log.flush() + chunks.append(line) + + status = process.wait() + + if status != expected: + marked = f", not the exit={expected} of the block" if expected else "" + raise RuntimeError( + f"Bash exited with status {status}{marked}; see {logfile}" + ) + + if expected: + print(f"[exit status {status}, as the block says]", flush=True) + + if before is not None: + added = {key: said for key, said in failed_results(workdir).items() if key not in before} + + if added: + raise RuntimeError( + f"Bash exited with status 0, but {len(added)} result(s) it stored failed:\n " + + "\n ".join(added.values()) + ) + + return "".join(chunks) + + +def execute_python( + code: str, + namespace: dict, + logfile: Path, + filename: str, +) -> str: + """Execute Python with shared state and capture diagnostics.""" + captured = io.StringIO() + + try: + with ( + contextlib.redirect_stdout(captured), + contextlib.redirect_stderr(captured), + ): + # Running the README's code is the point of this tool. + exec(compile(code, filename, "exec"), namespace) # noqa: S102 + + except BaseException: + captured.write(traceback.format_exc()) + output = captured.getvalue() + + logfile.write_text(output, encoding="utf-8") + print(output, file=sys.stderr, flush=True) + raise + + output = captured.getvalue() + logfile.write_text(output, encoding="utf-8") + + if output: + print(output, end="", flush=True) + + return output + + +def github_annotation( + source: Path, + line: int, + message: str, +) -> None: + """Emit a GitHub Actions error annotation for a source line.""" + def escape(value: str, property: bool = False) -> str: + value = ( + str(value) + .replace("%", "%25") + .replace("\r", "%0D") + .replace("\n", "%0A") + ) + + if property: + value = ( + value.replace(":", "%3A") + .replace(",", "%2C") + ) + + return value + + print( + f"::error file={escape(source, True)}," + f"line={line}::{escape(message)}", + flush=True, + ) + + +def run( + source: Path, + output: Path, + logs: Path, +) -> int: + """Execute a Markdown file and render fresh output. + + Returns the number of executable blocks that were run. A failing block raises. + """ + repository_root = Path.cwd().resolve() + + source = source.resolve() + output = output.resolve() + logs = logs.resolve() + + if source == output: + raise ValueError("Output must differ from source") + + output.parent.mkdir(parents=True, exist_ok=True) + logs.mkdir(parents=True, exist_ok=True) + + # Execute in the original example directory. + # BenchX needs the real Git checkout to record revision and + # dirty-tree information correctly. + workdir = source.parent + + original = source.read_text(encoding="utf-8") + lines = original.splitlines(keepends=True) + + tokens = MarkdownIt("commonmark").parse(original) + + # markdown-it-py identifies fences and headings. + # Do not filter on token.level: valid fenced blocks may + # have a nonzero nesting level. + events = [ + token + for token in tokens + if token.map is not None + and token.type in {"fence", "heading_open"} + ] + + rendered = [] + cursor = 0 + awaiting_output = False + fresh_output = None # (index in `rendered`, cleaned text) of the last block's output + block_number = 0 + + # Python blocks share variables across the document. + namespace = {"__name__": "__main__"} + + previous_cwd = Path.cwd() + + try: + os.chdir(workdir) + + for token in events: + start, end = token.map + + # Preserve all ordinary Markdown between events. + rendered.extend(lines[cursor:start]) + + if token.type == "heading_open": + awaiting_output = False + rendered.extend(lines[start:end]) + + elif token.type == "fence": + parts = token.info.strip().split() + language = parts[0] if parts else "" + + executable = ( + language in EXECUTABLE_LANGUAGES + and "noexec" not in parts[1:] + ) + + if language in SNAPSHOT_LANGUAGES and awaiting_output: + # Remove the first committed text or json output + # snapshot after an executable block. + # + # Ordinary prose may intervene, but a heading + # or another fence ends the association. + # + # Fresh output has already been inserted + # immediately after the executable block, as + # text: it takes the language of the snapshot. + # + # We never compare committed and fresh output. + if language != "text": + index, shown = fresh_output + rendered[index] = text_fence(shown, language) + + awaiting_output = False + + elif executable: + block_number += 1 + line = start + 1 + logfile = logs / f"block-{block_number:03d}.log" + + # Preserve original code fence in rendered docs. + rendered.extend(page_fence(lines[start:end], token)) + + print( + f"\n[{block_number}] " + f"{source}:{line} ({' '.join(parts)})", + flush=True, + ) + + try: + # An invalid exit= is an error of the README: before anything runs. + expected = expected_status(parts[1:], language) + + if language in {"sh", "bash"}: + result = execute_bash( + without_prompts(token.content), + workdir, + logfile, + expected, + ) + else: + result = execute_python( + token.content, + namespace, + logfile, + f"{source}:{line}", + ) + + except BaseException as exc: + try: + relative_source = ( + source.relative_to(repository_root) + ) + except ValueError: + relative_source = source + + github_annotation( + relative_source, + line, + f"{language} block failed: {exc}", + ) + + print( + f"Failed block {block_number}." + + (f" Diagnostics: {logfile}" if logfile.exists() else ""), + file=sys.stderr, + ) + raise + + # Insert fresh text output after executable code. + # Empty output does not produce a text fence. + shown = clean(result, repository_root) + rendered.append(text_fence(shown)) + fresh_output = (len(rendered) - 1, shown) + + awaiting_output = True + + else: + # Preserve unlabelled, json, yaml, noexec, + # and other non-executable fences unchanged. + rendered.extend(page_fence(lines[start:end], token)) + awaiting_output = False + + cursor = end + + rendered.extend(lines[cursor:]) + + if block_number == 0: + print( + f"No executable blocks in {source}: copied as it is.", + flush=True, + ) + + # Write generated Markdown only after successful execution. + output.write_text( + "".join(rendered), + encoding="utf-8", + ) + + finally: + os.chdir(previous_cwd) + + print(f"\nGenerated documentation: {output}") + + return block_number + + +def main() -> None: + parser = argparse.ArgumentParser( + description="Execute Markdown examples and capture outputs" + ) + + parser.add_argument( + "--source", + type=Path, + required=True, + help="Source Markdown file", + ) + parser.add_argument( + "--output", + type=Path, + required=True, + help="Generated Markdown file", + ) + parser.add_argument( + "--logs", + type=Path, + required=True, + help="Directory for per-block diagnostic logs", + ) + + args = parser.parse_args() + run(args.source, args.output, args.logs) + + +if __name__ == "__main__": + main() diff --git a/tools/gen_docs.py b/tools/gen_docs.py index 416951c6..b075bc96 100644 --- a/tools/gen_docs.py +++ b/tools/gen_docs.py @@ -1,20 +1,32 @@ """Generate the documentation pages that are derived from other files. Run before `zensical build` (the docs workflow does; locally: `python tools/gen_docs.py`). -It writes, into docs/, files that are gitignored and never committed: +It builds docs/generated/, the folder the site is built from (`docs_dir` in zensical.toml), which is +gitignored and never committed. In it: +- a copy of the hand-written pages of docs/. The generated pages must sit next to them: a page's + URL is its path in the docs folder, and Zensical takes one, so the site keeps `/`, `/schemas/` + and `/examples/` and has no `/generated/`; - index.md, from the repository README (links to docs/... rewritten); - schemas/index.md, listing every schema; - schemas/.md, one reference page per schema (newest version); - schemas///schema.json and examples/*.json, so the raw - documents are downloadable from the site. + documents are downloadable from the site; +- examples/.md, the page of each example (a directory of the top-level examples/ with + a README.md). With `--executed DIR` it is DIR/.md, the README as tools/execute_markdown.py + rendered it, which the docs workflow downloads from the jobs that ran the examples (a missing + page is an error). Without the option it is the committed README, under a notice that it was + not executed, so that a local build needs no setup. A schema page shows the top-level property table, one subsection per nested object, the conditional rules (allOf/if/then) in prose, the $defs once each, and the examples as tabbed code blocks. Cross-schema $refs (urn:benchx:schema::#/...) link to the other schema's page. -Stale output is removed first, so deleting a schema deletes its page. +docs/generated/ is removed first, so deleting a schema or a page deletes it from the site. Edit the +pages in docs/, not in docs/generated/, and run this again to see the change. Earlier versions wrote +index.md, schemas/ and examples/ directly under docs/: if they are still there, the run stops (they +would be copied next to the pages generated here). """ from __future__ import annotations @@ -489,23 +501,78 @@ def rewrite_readme(text: str, strip_prefix: str) -> str: return text +# --------------------------------------------------------------------------- examples + +EXAMPLES = ROOT / "examples" + +NOT_EXECUTED = ( + '!!! warning "Not executed"\n' + " This is the committed README of the example, with the output that was committed with it.\n" + " The documentation site shows the output of a CI run instead.\n" +) + + +def example_names() -> list[str]: + """The examples: the directories of examples/ that have a README.md.""" + if not EXAMPLES.is_dir(): + return [] + return sorted(d.name for d in EXAMPLES.iterdir() if (d / "README.md").is_file()) + + +def unexecuted_page(readme: str) -> str: + """The README with a notice under its title (at the top, when the first line is not one).""" + lines = readme.splitlines(keepends=True) + at = 1 if lines and lines[0].startswith("# ") else 0 + return "".join(lines[:at]) + "\n" + NOT_EXECUTED + "\n" + "".join(lines[at:]) + + +def example_pages(executed: Path | None) -> dict[str, str]: + """The page of each example, by name (see the top of this file).""" + pages = {} + for name in example_names(): + if executed is None: + pages[name] = unexecuted_page((EXAMPLES / name / "README.md").read_text()) + continue + page = executed / f"{name}.md" + if not page.is_file(): + raise SystemExit( + f"no executed page for examples/{name}: {page} is missing. An example needs a " + "leg in the matrix of the `examples` job of .github/workflows/docs.yml, or the " + "site would show it unexecuted.") + pages[name] = page.read_text() + return pages + + # --------------------------------------------------------------------------- main -GENERATED = ["index.md", "schemas"] # paths under docs/, all gitignored +OUT = DOCS / "generated" # the folder the site is built from: gitignored, rebuilt on each run +LEGACY = ["index.md", "schemas", "examples"] # where earlier versions wrote, directly under docs/ def main() -> None: + import argparse import shutil - for rel in GENERATED: - path = DOCS / rel - if path.is_dir(): - shutil.rmtree(path) - elif path.exists(): - path.unlink() + parser = argparse.ArgumentParser(description="Generate the documentation pages derived from other files.") + parser.add_argument("--executed", type=Path, metavar="DIR", + help="a directory with .md for each example, as tools/execute_markdown.py " + "made them; without it the examples' pages are their committed READMEs") + args = parser.parse_args() + + left = [f"docs/{rel}" for rel in LEGACY if (DOCS / rel).exists()] + if left: + raise SystemExit( + f"{', '.join(left)}: left by an earlier tools/gen_docs.py, which wrote directly under " + f"docs/. They would be copied into {OUT.relative_to(ROOT)}/ next to the pages generated " + "there. They are gitignored output, not source: delete them.") + if OUT.exists(): + shutil.rmtree(OUT) + + # The hand-written pages go in too: the generated pages have to sit next to them (see the top). + shutil.copytree(DOCS, OUT, ignore=lambda folder, names: ["generated"] if Path(folder) == DOCS else []) def write(rel: str, content: str | bytes) -> None: - path = DOCS / rel + path = OUT / rel path.parent.mkdir(parents=True, exist_ok=True) if isinstance(content, bytes): path.write_bytes(content) @@ -525,7 +592,12 @@ def write(rel: str, content: str | bytes) -> None: write(f"schemas/{p.name}/{v}/schema.json", (vdir / "schema.json").read_bytes()) for ex in sorted((vdir / "examples").glob("*.json")) if (vdir / "examples").is_dir() else []: write(f"schemas/{p.name}/{v}/examples/{ex.name}", ex.read_bytes()) - print(f"generated {len(pages)} schema pages under {DOCS.relative_to(ROOT)}/") + # The pages of the examples, which docs/examples.md links to. + examples = example_pages(args.executed) + for name, page in examples.items(): + write(f"examples/{name}.md", page) + print(f"generated {len(pages)} schema pages and {len(examples)} example pages " + f"({'executed' if args.executed else 'not executed'}) under {OUT.relative_to(ROOT)}/") if __name__ == "__main__": diff --git a/uv.lock b/uv.lock index 59c3ed3c..36ee2efe 100644 --- a/uv.lock +++ b/uv.lock @@ -37,6 +37,7 @@ parquet = [ ] test = [ { name = "asv-runner" }, + { name = "markdown-it-py" }, { name = "pyperf" }, { name = "pytest" }, ] @@ -45,6 +46,7 @@ test = [ requires-dist = [ { name = "asv-runner", marker = "extra == 'test'" }, { name = "jsonschema", specifier = ">=4.18" }, + { name = "markdown-it-py", marker = "extra == 'test'" }, { name = "pyarrow", marker = "extra == 'parquet'", specifier = ">=19" }, { name = "pyperf", marker = "extra == 'test'" }, { name = "pytest", marker = "extra == 'test'" }, @@ -100,6 +102,27 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/41/45/1a4ed80516f02155c51f51e8cedb3c1902296743db0bbc66608a0db2814f/jsonschema_specifications-2025.9.1-py3-none-any.whl", hash = "sha256:98802fee3a11ee76ecaca44429fda8a41bff98b00a0f2838151b113f210cc6fe", size = 18437, upload-time = "2025-09-08T01:34:57.871Z" }, ] +[[package]] +name = "markdown-it-py" +version = "4.3.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "mdurl" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/16/fc/cee2c45553c9a9bf77d8b0c391560c556d7ed756b1f0bb35eb5d48db09ea/markdown_it_py-4.3.0.tar.gz", hash = "sha256:91a58fa5b72c71a40cf7177250fd767480d7a2bb3ac426ccfb76fb90305fdaaa", size = 242701, upload-time = "2026-11-10T16:18:30.467Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/c9/31/5f0ac2f1a1c67423c995c731a11cd4ad05d081a2be969d74f868bdb9cc70/markdown_it_py-4.3.0-py3-none-any.whl", hash = "sha256:7aa1511a46c39138de78d9eba92ce47e63124d8003fc98b3a351909e04239efa", size = 96951, upload-time = "2026-11-10T16:18:28.975Z" }, +] + +[[package]] +name = "mdurl" +version = "0.1.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/d6/54/cfe61301667036ec958cb99bd3efefba235e65cdeb9c84d24a8293ba1d90/mdurl-0.1.2.tar.gz", hash = "sha256:bb413d29f5eea38f31dd4754dd7377d4465116fb207585f97bf925588687c1ba", size = 8729, upload-time = "2022-08-14T12:40:10.846Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b3/38/89ba8ad64ae25be8de66a6d463314cf1eb366222074cfda9ee839c56a4b4/mdurl-0.1.2-py3-none-any.whl", hash = "sha256:84008a41e51615a49fc9966191ff91509e3c40b939176e643fd50a5c2196b8f8", size = 9979, upload-time = "2022-08-14T12:40:09.779Z" }, +] + [[package]] name = "packaging" version = "26.3" diff --git a/zensical.toml b/zensical.toml index e0d36df5..76db01c1 100644 --- a/zensical.toml +++ b/zensical.toml @@ -1,11 +1,16 @@ # Documentation site, built with Zensical (https://zensical.org). # -# python tools/gen_docs.py # generate docs/index.md and docs/schemas/ +# python tools/gen_docs.py # build docs/generated/, which the site is built from: the +# # pages of docs/ copied, plus the home page, schemas, examples # zensical serve # preview at http://127.0.0.1:8000 # zensical build --strict --clean # what CI runs # -# The generated pages are gitignored; run the generator again after changing -# a schema or the README. +# python tools/build_site.py # all of it, with the examples executed (see the script); +# # without it, the pages of the examples are the committed +# # READMEs, under a "not executed" notice +# +# Everything under docs/generated/ is generated and gitignored. Edit the pages in docs/, never +# there, and run the generator again after changing a page, a schema, the README or an example. [project] site_name = "benchx" @@ -16,7 +21,8 @@ repo_name = "benchx-dev/benchx" edit_uri = "edit/main/docs/" copyright = "Copyright © benchx contributors" -docs_dir = "docs" +# Built by tools/gen_docs.py: the pages of docs/ copied, and the generated ones next to them. +docs_dir = "docs/generated" site_dir = "site" # Ablation studies are working notes, not part of the published design;