diff --git a/.github/actions/run-gates/action.yml b/.github/actions/run-gates/action.yml index 6b4e63c8..b790bdce 100644 --- a/.github/actions/run-gates/action.yml +++ b/.github/actions/run-gates/action.yml @@ -190,6 +190,12 @@ runs: - name: Unit-test the source tree's inventory (test/discover.test.mjs) shell: bash run: node --test test/discover.test.mjs + # Unit tests for the modules of scripts/build_speed.mjs that read the build's + # Gantt chart and a CPU profile: a chart drawn with the build's writer is + # read back to the same times. No build, no lanes. + - name: Unit-test the build-speed tool's readers (test/build-speed.test.mjs) + shell: bash + run: node --test test/build-speed.test.mjs # A regex that backtracks exponentially does not fail a build, it stops # one: the corpus passes until a page happens to contain the trigger, and # then a render worker sits inside String.replace forever. Nothing else diff --git a/.gitignore b/.gitignore index 2bffd5fe..c8e4af60 100644 --- a/.gitignore +++ b/.gitignore @@ -54,3 +54,7 @@ indexer/.packages/ # scripts/shot_review.mjs: the screenshot review's session and its runs' stages # (scripts/lib/shot-session.mjs), which hold the Windows user name. /.shot-review/ + +# scripts/build_speed.mjs: each measured build's log and Gantt chart, and the +# tree its serve builds write (removed after each run). +/.build-speed/ diff --git a/WIP.Build.md b/WIP.Build.md index ae1ff7b2..5b3f009d 100644 --- a/WIP.Build.md +++ b/WIP.Build.md @@ -65,6 +65,7 @@ The roster, by wrapper ([Tools and Scripts](docs/Documentation/Tools.md) owns th | `test.bat` | `test/indexer.test.mjs` | the package indexer (`indexer/lib/`) changes a snapshot only when the API changes | | `test.bat` | `test/ide-js.test.mjs` | `scripts/ide_js.mjs` and `scripts/ide-js/lib.mjs` on a few lines of minified JavaScript, and that the tool writes only under `%TEMP%` | | `test.bat` | `test/discover.test.mjs` | the source tree's inventory (`builder/discover.mjs`, `discover-read.mjs`) is the same in any number of pieces, with a picture pair that has a `bundle_extra` file | +| `test.bat` | `test/build-speed.test.mjs` | `scripts/build_speed.mjs` reads from a Gantt chart the times `builder/gantt.mjs` drew, and totals a CPU profile by function | | `test.bat` | `check_pdf_shims_equiv` | the book's pdf-lib shims write what stock pdf-lib writes, and patch only the members `PATCHES` lists | | `test.bat` | `check_impexp_parity` | the Node and Python editions of `impexp` (and, with `IMPEXP_EXE`, the twinBASIC one) behave alike | | `test.bat` | `check_publish_policy`, `check_gate_lists`, `check_page_baseline`, `check_book_coverage`, `check_axe_patch_equiv` | the gates on the gates | @@ -176,8 +177,8 @@ What makes it worth doing, and what to keep when changing it: would take them and load the second stage, and the pieces would wait for a lane. The listing takes a few hundredths of a second, less than a lane takes to start. The pieces have the highest priority, so the first lanes that look take them. - `buildInfo` waits too, since nothing early needs it: see - [dispatch does not wait for buildInfo](#dispatch-does-not-wait-for-buildinfo). + `buildInfo` is no lane task since: see + [git is started by the main thread and awaited where it is needed](#git-is-started-by-the-main-thread-and-awaited-where-it-is-needed). - **Two pieces below eight CPUs, four from eight on** (`discoverPieces`; owner, 2026-11-18). On four CPUs the other two lanes compile the stylesheets meanwhile; with four pieces there `dot` and `packTests` queued behind the reads and `dispatch`, which @@ -258,9 +259,8 @@ late. In a serve rebuild it took 0.03 to 0.3 s, with the same effect. On CI's Li was done long before. `bookPayload` waits for it now, which reads `state.site.buildInfo` and runs after the -render; the shared payload and the lanes' site object hold it no longer. `buildInfo` -also waits for `discoverList`, as the other early lane tasks do, so that it does not -take a lane the source tree's pieces want. +render; the shared payload and the lanes' site object hold it no longer. (`buildInfo` +was a lane task then; it is a main-thread task now, see the next section.) Measured on the dev box, with four pieces of the source tree as well (the two changes were measured together), the first render starting at: @@ -281,6 +281,59 @@ carries the levels, which takes 6 ms alone on its first call where it took 19 to In a build the task still reads 29 to 69 ms (28 to 64 ms before): its time there is not its own work but the main thread's share of a machine whose lanes are all booting. +### git is started by the main thread and awaited where it is needed + +On Windows a `git` process takes 0.15 to 1.0 s to start and answer, alone on a quiet +machine, and up to 2.3 s while the lanes boot. The build asks `git` two things, and both +waited for it in the wrong place: + +- **`buildInfo` was a lane task.** A lane that awaits a process does no other work, so + one lane was out of the build for 0.47 to 0.88 s on sixteen CPUs and 0.50 to 2.33 s on + four, where render starts at about 1.5 s. It was also two processes + (`rev-parse --short HEAD` and `log -1 --format=%cs`) where `log -1 --format="%h %cs"` + answers both. +- **`addinProject` listed the add-in's files at the very end of the build**, two + `git ls-files` after `helpArchive`, with nothing else left to run: 0.21 to 1.55 s in + a one-off build, 0.22 to 0.55 s in a serve rebuild. + +Both are now main-thread tasks that start one process and return: `buildInfo` keeps +the promise in `state.buildInfoPending` and `bookPayload` awaits it; `addinFiles` +keeps `state.addinListing` (`listAddinFiles`: one `git ls-files -t --cached --others`, +where `?` marks a file git does not track) and `addinProject` awaits it. By then each +has long answered. What to keep: + +- **A main-thread task must not await the process itself**: the main thread finishes a + task before it claims the next, so the await belongs in the task that needs the + answer, which runs late. +- **Both wait for `dispatch`**, only so that the processes start after the main + thread's work for the first render. Starting a process takes the main thread 3 to + 31 ms. +- **A build that writes no PDF starts no `buildInfo` process** (`--serve`, `--no-pdf`, + `--dry-run`): only the title page reads it. +- **The chart draws each process as a bar of its own**, `git log` and `git ls-files` in + the Seeds band, and the timing line has `git:log=` and `git:ls-files=` (owner, + 2026-11-18): the two tasks are over at once and say nothing of how long `git` took. + `chartProcess` (`builder/tbdocs.mjs`) adds the timing when the promise settles, from the + task's `submit`. The bar ends when the main thread hears the answer, so it is longer + than the process by whatever task the main thread was in the middle of. +- `compare_trees` replaces the title page's build line, so check the commit there by + reading `_site-pdf/book.html` after a change to `build-info.mjs`. + +Measured on the dev box, three runs of each, base against branch in the same session: + +| | before | since | +|---|---|---| +| `addinProject`, one-off, 16 CPUs | 0.48 to 0.64 s | 0.08 to 0.09 s | +| `addinProject`, one-off, 4 CPUs | 0.21 to 1.55 s | 0.09 to 0.10 s | +| `addinProject`, serve rebuild (builds 2 to 5) | 0.22 to 0.55 s | 0.01 to 0.02 s | +| first render, one-off, 16 CPUs | 0.81 to 0.95 s | 0.70 to 0.88 s | +| first render, one-off, 4 CPUs | 1.38 to 1.69 s | 1.07 to 1.34 s | +| whole build, 16 CPUs | 9.2 to 10.8 s | 8.6 to 9.4 s | +| whole build, serve rebuild (builds 2 to 5) | 3.96 to 4.66 s | 3.55 to 4.27 s | + +The whole build on four CPUs is within the runs' noise (15.2 to 18.2 s against 15.5 to +17.3 s). Not measured: CI, where `git` is quick and little should show. + ### What markdownInit is made of Every render waits for `markdownInit`. On the dev box it took 117 to 151 ms in a one-off @@ -1293,7 +1346,7 @@ and the reader builds it. `test/addin-project.test.mjs` is the gate. ### The help archive -- **The help archive is made by tasks of the build's graph, its deflating on the lanes.** `builder/help-archive-step.mjs` writes `add-in/Resources/HELP/site.zip` from `docs/_site-offline` through `lib/help-archive.mjs`, **before** the Gantt injection. `archivePlan` runs once `flushJoin`, `scss` and `writeOffline` have finished, lists the tree less `LATE_FILES` (`search-index.js`) and deals the deflating into one group of units for each lane (`archiveDeflate:i`), so the tree is deflated while the search index is built. `archiveLate` does the same for `search-index.js` once `searchIndex` has written it (`archiveLateDeflate:i`), and `helpArchive` writes the zip from every group. A unit is a whole file or one 1 MB piece of a larger one; a large file's pieces are one deflate stream, each ending with a sync flush and primed with the 32 KB before it (pigz's method), so the bytes depend only on the piece size. Measured on the 55 MB `search-index.js` at level 9: 3.2 s as one stream, 0.8 s as pieces on four threads, at the same size to within 0.02%. Each unit inflates what it deflated and compares it with the bytes it read; the zip is read back and compared with what was assembled. **The archive leaves out `HELP_ARCHIVE_SKIP`** (`builder/help-archive-step.mjs`): the Documentation Development section (`BuildInfo.html` and `assets/images/gantt.svg` with it, so the chart never reaches the zip), Videos and their poster frames, Challenges, and **every download, which stays online** (owner): a file readers download goes in a `downloads` folder beside its page, and the step fails the build when the Downloads page offers a file the archive would hold. The add-in's server redirects any file the archive lacks to the website, because pages link to all of these; a new entry needs nothing else. A mismatch fails the build (exit 1). After the Gantt injection `recheckHelpArchive` checks that the offline tree on disk lists the same files as the archive and differs from it, in size or CRC-32, only in `BuildInfo.html` and `gantt.svg`; a task that wrote into the offline tree late fails the build there. The help add-in embeds the zip as a resource and serves the pages from it with its own server; a build of the add-in without it uses the live site. The file is gitignored (about 60 MB, 10 MB of it the search index's `search-index.js`, deflated), so a build of the add-in from a clean clone is the online one until `build.bat` has run. The download carries the same zip ([The help add-in's project file](#the-help-add-ins-project-file)). **`--no-help-archive` turns the step off, and neither CI workflow may pass it** (`check_ci_workflows.mjs` refuses it, in `ALLOWED.forbiddenBuildFlags`), because CI's published download would then hold no archive. It runs only for the guarded source tree (`docs`) built into the default `docs/_site-offline` (not another `--dest`, so `compare_trees` and `check_links_diff` leave it alone), never under `--serve` or `--dry-run`, never without an offline tree, and not keyed on `$CI`. There is no command-line tool for the archive: the `help-offline` lane makes its own with `writeHelpArchive`. The zip's format is fixed by the add-in's reader, which does no inflating ([WIP.HelpAddin.md](WIP.HelpAddin.md), Stage 4, increment 5). +- **The help archive is made by tasks of the build's graph, its deflating on the lanes.** `builder/help-archive-step.mjs` writes `add-in/Resources/HELP/site.zip` from `docs/_site-offline` through `lib/help-archive.mjs`, **before** the Gantt injection. `archivePlan` runs once `flushJoin`, `scss` and `writeOffline` have finished, lists the tree less `LATE_FILES` (`search-index.js`) and deals the deflating into one group of units for each lane (`archiveDeflate:i`), so the tree is deflated while the search index is built. `archiveLate` does the same for `search-index.js` once `searchIndex` has written it (`archiveLateDeflate:i`), and `helpArchive` writes the zip from every group. A unit is a whole file or one 1 MB piece of a larger one; a large file's pieces are one deflate stream, each ending with a sync flush and primed with the 32 KB before it (pigz's method), so the bytes depend only on the piece size. Measured on the 55 MB `search-index.js` at level 9: 3.2 s as one stream, 0.8 s as pieces on four threads, at the same size to within 0.02%. **A piece is deflated at level 6, a whole file at level 9** (owner, 2026-11-18): the pieces are `search-index.js`'s, the last file the build writes, so their deflating is on the way to the build's end. Measured on the dev box, three builds each, from the end of `searchIndex` to the start of `helpArchive`: 0.60 to 0.63 s at level 9 and 0.13 to 0.16 s at level 6 on sixteen CPUs, 1.17 to 1.29 s and 0.37 to 0.41 s on four; the whole build 8.6 to 9.4 s and 7.7 to 8.3 s, 15.5 to 17.3 s and 14.5 to 15.0 s. The archive is 206 KB larger (77.66 MB, 77.87 MB). Not measured: CI. Each unit inflates what it deflated and compares it with the bytes it read; the zip is read back and compared with what was assembled. **The archive leaves out `HELP_ARCHIVE_SKIP`** (`builder/help-archive-step.mjs`): the Documentation Development section (`BuildInfo.html` and `assets/images/gantt.svg` with it, so the chart never reaches the zip), Videos and their poster frames, Challenges, and **every download, which stays online** (owner): a file readers download goes in a `downloads` folder beside its page, and the step fails the build when the Downloads page offers a file the archive would hold. The add-in's server redirects any file the archive lacks to the website, because pages link to all of these; a new entry needs nothing else. A mismatch fails the build (exit 1). After the Gantt injection `recheckHelpArchive` checks that the offline tree on disk lists the same files as the archive and differs from it, in size or CRC-32, only in `BuildInfo.html` and `gantt.svg`; a task that wrote into the offline tree late fails the build there. The help add-in embeds the zip as a resource and serves the pages from it with its own server; a build of the add-in without it uses the live site. The file is gitignored (about 60 MB, 10 MB of it the search index's `search-index.js`, deflated), so a build of the add-in from a clean clone is the online one until `build.bat` has run. The download carries the same zip ([The help add-in's project file](#the-help-add-ins-project-file)). **`--no-help-archive` turns the step off, and neither CI workflow may pass it** (`check_ci_workflows.mjs` refuses it, in `ALLOWED.forbiddenBuildFlags`), because CI's published download would then hold no archive. It runs only for the guarded source tree (`docs`) built into the default `docs/_site-offline` (not another `--dest`, so `compare_trees` and `check_links_diff` leave it alone), never under `--serve` or `--dry-run`, never without an offline tree, and not keyed on `$CI`. There is no command-line tool for the archive: the `help-offline` lane makes its own with `writeHelpArchive`. The zip's format is fixed by the add-in's reader, which does no inflating ([WIP.HelpAddin.md](WIP.HelpAddin.md), Stage 4, increment 5). ### Build-time counts as named values diff --git a/WIP.BuildSpeed.md b/WIP.BuildSpeed.md new file mode 100644 index 00000000..728ab06f --- /dev/null +++ b/WIP.BuildSpeed.md @@ -0,0 +1,184 @@ +# The build's speed --- Working Notes + +What a session needs before it makes `tbdocs` faster: the rules, how to measure, and the +work that is open. What was done, and why each piece of the pipeline is built as it is, is in +[WIP.Build.md](WIP.Build.md#the-pipeline) and [WIP.Search.md](WIP.Search.md) (*The pre-built +index*), with every measurement that still decides something. History is in git. + +The owner's standard for this work: "Our build's performance was achieved by relentlessly +slicing every 0.1s off until it was perfect. So a 0.1s win is just fine in my book." + +## Rules + +- **Measure before and after, in the same session, more than once.** The dev box is rarely + quiet: one-off builds of one commit range over a second, and a `git` process alone takes + 0.15 to 1.0 s. Compare the base checkout with the branch in alternating runs + (`bench.ps1 -Trees ,`), read each run's chart, and report ranges, never one + total. +- **Measure each kind of build**, because a change that helps one often does nothing for + another: a one-off build on every CPU, a one-off build on four (`start /affinity F`, the + nearest thing to a CI runner), and rebuilds on one pool as `--serve` runs them. Say which + were not measured; CI never is until the owner pushes. +- **Look for a gap before optimising a bar.** The gains so far came mostly from a task + waiting for something it did not need, a lane held by a wait, or the main thread claiming + a long task just before a critical one became ready. Read which task ran in a gap from the + build's timing line: the chart does not draw every main-thread task (`linkJoin`), and a + `submit`'s time is the paler stretch after its bar, not in `=`. +- **A task's time in a build is not its own work while the lanes boot.** Measure a function + alone first, then in the build, and report both. +- **The output must not change unless it is meant to.** `node scripts/compare_trees.mjs` + after every change to `builder/` or `lib/`; then `build.bat`, `check.bat`, `test.bat` and + lint. A rewrite of an inner loop is compared with the old code over every page first (import + both checkouts' modules in one script). +- **No task starts a thread**, and a new lane task or main-thread task needs its entry in + `GANTT_SECTION` (`builder/gantt.mjs`), or the build fails after writing the trees + ([WIP.Build.md](WIP.Build.md#no-task-starts-a-thread)). +- **A task that only waits does not belong on a lane**, and a main-thread task must not + await a process: start it, keep the promise, and await it in the task that needs the answer + ([WIP.Build.md](WIP.Build.md#git-is-started-by-the-main-thread-and-awaited-where-it-is-needed)). +- **Separate commits for code and for docs**, and the developer pages + (`docs/Documentation/Builder.md`, `Pipeline-Stages.md`, `Extending.md`) are updated with the + task graph. + +## How to measure + +`node scripts/build_speed.mjs` ([Tools-Build](docs/Documentation/Tools-Build.md#build-speed)) +does the measuring. It is outside every gate and CI; `test/build-speed.test.mjs` holds +its reading of the chart to the chart's writer. + +| Command | For | +|---|---| +| `bench --tree --tree ` | one-off builds of each tree in turn, on every CPU and on four, with each figure's range over the runs; each log and chart is kept in `.build-speed/` | +| `serve --tree --tree ` | rebuilds on one pool, as `--serve` does (the first build is cold) | +| `--task a,b` on either | named main-thread tasks' times as well | +| `times ...` | the same figures from charts kept earlier | +| `png ...` | a chart as a PNG, to look at with the Read tool | +| `profile --fn a,b` | the inclusive time of named functions in a `--cpu-prof` profile | +| `part ` | one part of the build alone on one thread: `markdown-init`, `nav`, `index-slices`, `index-add`, `index-terms`, `deflate`, `archive` | + +A base to compare with is the main checkout while the branch is ahead of it, or a detached +worktree of the commit with a `node_modules` junction. `part --tree ` runs that +tree's modules, so a rewrite is timed against the old code by naming each checkout in turn. + +**A new part goes into `scripts/build-speed/parts.mjs`** when a function is timed alone +for the second time; a one-off comparison of two checkouts' output over every page (the way +`maskCode` and `computeNav` were checked) is a script in the session's scratchpad. + +What goes wrong when measuring: + +- A build's timing line gives a lane task's duration as the main thread saw it; its bar in + the chart is the lane's own. +- A profile inflates code that runs once and cannot tell one caller of a shared function + from another: for a task's parts, marks printed to stderr are better. +- From Git Bash, `cmd //c "start \"\" /affinity F ..."` fails on quoting: run the four-CPU + builds from PowerShell. `& .\test.bat` from PowerShell works; `cmd /c test.bat` does not. +- Never pipe a build into `Select-Object -First N`: it ends the process. +- `bench.ps1` copies the chart even when the build failed, so check each run's exit code. +- Two CI runners differ by a quarter in speed: compare a task's time with render's own + length before believing a gain there. + +## Where the time is + +Against `952c9da1`, on the dev box (16 logical CPUs), three runs each: + +| | first render | render ends | build ends | +|---|---|---|---| +| one-off, 16 CPUs | 0.7 to 0.9 s | 4.9 to 5.6 s | 7.7 to 8.3 s | +| one-off, 4 CPUs | 1.1 to 1.3 s | 9.1 to 10.1 s | 14.5 to 15.0 s | +| serve rebuild | 0.16 to 0.25 s | 2.3 to 2.8 s | 3.5 to 4.3 s | + +After render the critical path is `indexAdd:i` -> `indexMerge` -> `indexTerms` -> +`searchIndex` -> the late deflate -> `helpArchive` -> `addinProject` -> `checkReport`, +mostly on the main thread while the lanes have little to do. + +## Open work + +None of these is started. A figure is of the runs named, so measure again before +believing an order. + +### Render takes twice the lane time on 16 lanes that it does on 4 + +Render and flush take 4.1 to 4.9 s on sixteen lanes and 8.2 to 8.4 s on four: about 70 +lane-seconds against 34. It is the largest block of the build and nobody has looked into +why. Candidates: the sixteen are hyperthreads of eight cores, the garbage collector, memory +traffic, or the file writes in `flush` (three trees, and a markdown copy of each page). The +first measurements to take: a build with eight lanes, and one whose flushes write nothing. + +### The stylesheets are compiled in every build + +`scssLight` takes 0.8 to 1.2 s and `scssDark` 0.9 to 2.4 s in a one-off build, each holding +a lane that then starts Shiki and joins the render late (about 0.7 s late on CI). In a serve +rebuild they still held two lanes until about 2 s in one run. + +- A serve rebuild in which no `.scss` file changed could keep the previous result. +- A one-off build could take it from a cache on disk keyed by the sources' hash and the + compiler's version. That is a larger decision: the build has no cache today. +- Compiling later instead (the lanes render first) moves the CPU and removes none: on four + CPUs the lanes are idle only after `archivePlan`, which needs the stylesheet written. + +### The main thread runs long tasks just before `searchIndex` + +On sixteen CPUs `archivePlan` (0.1 to 0.25 s) and `linkJoin` (0.33 to 0.40 s) are claimed +between `indexTerms` and `searchIndex`, which started 0.13 and 0.54 s late in two runs. The +main thread never interrupts a task, and it claims ready tasks in declaration order. On four +CPUs and in a serve build it does not arise: the main thread is done long before. + +- Ways: let the scheduler prefer a main-thread task on the critical path; or reorder; or + shorten the tasks. `F_RUN_WHEN_IDLE` exists for lane tasks only (`warmInit`). +- `linkJoin`: `checkChunk` over the redirect stubs and `nav.html` is about 0.2 s of + htmlparser2 on the main thread, a piece for the lanes (`fanOut`); `checkSearch` needs only + the entries' URLs, which `searchEntries` has without parsing `search-data.json`. +- `bookPayload` (0.25 to 0.44 s): `packShared` makes JSON of every page's `renderedContent`. + The render lanes hold that content and could pack it as they pack the search entries. +- `archivePlan`: `listFiles` is a `statSync` of every file of the offline tree, whose sizes + the build knows, having written them. + +### The index's main-thread end + +- `indexTerms` (`invertedIndexJson`, 0.35 to 0.65 s) while the lanes idle. The merged + postings are strings on the main thread, so a lane cannot build the JSON without a transfer + that costs what the building does. What would work: each `indexAdd:i` writes its posting + fragments (ASCII) into a SharedArrayBuffer, `indexMerge` numbers the terms only, and + term-range tasks on the lanes build the JSON as bytes. Gain at most 0.4 s. +- `searchIndex` (0.35 to 0.45 s: escaping, `JSON.stringify(docs)`, `Buffer.byteLength` for a + statistic, two 55 MB writes). The entries are packed as bytes already, so the `docs` part + could be assembled from them as `search-data.json` is, and the file written as Buffers. +- **A faster replacement for lunr's `Builder.add`**, most of the index's CPU (4.5 to 5 s on + one thread). Of 3.9 s profiled: tokenizing and stemming 0.84 s, `Builder.add`'s own + bookkeeping 1.6 s (a `Token` used as an object key becomes a string at every lookup; every + posting is an `Object.create(null)`), the postings' JSON 1.2 s, the garbage collector 0.4 s. + A builder of our own with Maps and arrays could be two or three times faster. The test + compares bytes with lunr's for any slice count, so the safety net exists. Keep lunr for the + vectors and replace only `add` and the postings' JSON first. +- `deriveSymbolIndex` (about 45 ms after render): `placeOwnPages` goes through every page of + a folder for every type and calls `cleanName` each time. The stem twins (about 20 ms) could + run on a lane while the main thread settles the entries. +- About 0.2 s of idle lanes between the last render chunk and the first `indexAdd:i` + (`symbolPlace`, `searchEntries`, `indexSlices`). + +### Smaller things + +- `markdownInit`'s two cold block parses (`deriveCounts`, `checkPlaceholders`): 50 to 70 ms + in a build, about 10 ms alone and warm + ([WIP.Build.md](WIP.Build.md#what-markdowninit-is-made-of)). +- On four CPUs `dispatch` waits a few hundredths of a second for `dot` in some runs. +- Start the late deflate from memory while `searchIndex` writes its files (about 0.2 s; it + would tie the archive to the index's task); deflate the part of `search-index.js` that is + known early during the adds (about 0.2 s, much wiring). + +## Considered and not done + +- **Adding the search entries during render** (owner asked twice). An entry has its final + form only after every page is rendered, and on four CPUs every lane is busy through render, + so the index's CPU would lengthen render by what it took off the tail. How it could be done + if ever wanted is in WIP.Search.md. +- **`prepDest`** is on no critical path; it is long in a cold serve build only because it + wipes the previous tree (owner: no action). +- **`nav`**: `computeNav` is three times faster alone than it was and unchanged in a build. + +## Owner's decisions + +- A 0.1 s gain is worth a slice. +- The source tree is read in four pieces from eight logical CPUs on, in two below. +- Orange in the Gantt chart is for write tasks; indexing has its own colour. +- A file the help archive deflates in pieces is at level 6 (2026-11-18). diff --git a/WIP.md b/WIP.md index a924ec12..633622c3 100644 --- a/WIP.md +++ b/WIP.md @@ -20,6 +20,7 @@ you are about to change. | start an IDE or a program on a private desktop, choose a port for one, or change `tbbroker` | [WIP.Broker.md](WIP.Broker.md) --- the broker that hands out desktops, slots and ports, and its protocol | | a new twinBASIC BETA has been installed | [WIP.NewBeta.md](WIP.NewBeta.md) --- the checklist, in order | | change `builder/`, `scripts/`, or any gate | [WIP.Build.md](WIP.Build.md) --- the pipeline and why each gate exists | +| make the build faster, or measure it | [WIP.BuildSpeed.md](WIP.BuildSpeed.md) --- the rules, how to measure, where the time is, and the work that is open | | touch fonts, diagrams, or the PDF's type | [WIP.Typography.md](WIP.Typography.md), then [WIP.Fonts.md](WIP.Fonts.md) for the generator | | change the accessibility scan | [WIP.A11y.md](WIP.A11y.md) --- the axe scan, the sample, the fingerprint gate | | work on the sample-compiling harness | [WIP.ExamplesBuild.md](WIP.ExamplesBuild.md) | @@ -320,6 +321,7 @@ and what actually collides inside one project. - `node scripts/vb6run.mjs` --- builds and runs VB6 code, so that what a sample prints in twinBASIC can be compared with VB6 ([WIP.ExamplesBuild.md](WIP.ExamplesBuild.md#vb6runmjs)). **Never start `VB6.EXE` from a shell**: in Git Bash `/make` is rewritten as a path and VB6 answers with a modal box on the desktop. - `node scripts/errors.mjs run|generate|write` --- the run-time errors of the documented procedures, as data under `errors/` ([WIP.Errors.md](WIP.Errors.md), [Tools-Defects](docs/Documentation/Tools-Defects.md#errorsmjs)): `run` builds and runs a probe of the cases in twinBASIC 32-bit and 64-bit (`tbrun --exe`), VB6 and 64-bit VBA (in 64-bit Access, `scripts/lib/vba.mjs`) and compares each with the data, `write` writes each page's Errors section. Its gate is `check_errors.mjs`; `run` is by hand, never CI. - `node scripts/recheck_callouts.mjs` --- after a new BETA, checks again every callout labelled with an older one by running what its marker names, relabels what holds and lists the rest; by hand, never CI ([WIP.Indexer.md, Rules](WIP.Indexer.md#rules); [Tools-Defects](docs/Documentation/Tools-Defects.md#recheck-callouts)). +- `node scripts/build_speed.mjs ` --- measures the build for work on its speed: one-off builds and serve rebuilds of one checkout or two, the times read from each Gantt chart, a CPU profile by function, and one part of the build alone ([WIP.BuildSpeed.md](WIP.BuildSpeed.md), [Tools-Build](docs/Documentation/Tools-Build.md#build-speed)). By hand, never CI. - `node scripts/ide_js.mjs ` --- reads, names and patches the IDE's minified `ide/main.js` (*Fixing the IDE itself*, under [Driving the twinBASIC compiler](#driving-the-twinbasic-compiler), and [WIP.Harness.md](WIP.Harness.md#rules)). **After a new twinBASIC BETA**, work through [WIP.NewBeta.md](WIP.NewBeta.md). diff --git a/builder/addin-project.mjs b/builder/addin-project.mjs index 8d951e27..275192c9 100644 --- a/builder/addin-project.mjs +++ b/builder/addin-project.mjs @@ -73,12 +73,30 @@ export function addinProjectOf(config) { return { src: String(e.src), dest: posix(String(e.dest)).replace(/^\/+/, "") }; } -// The files git lists under `dir`, relative to it, with forward slashes. -async function gitFiles(dir, ...args) { - const { stdout } = await exec("git", ["-C", dir, "ls-files", "-z", ...args, "--", "."], { - maxBuffer: 16 * 1024 * 1024, - }); - return stdout.split("\0").filter(Boolean).sort(byCodePoint); +/** + * The files of the add-in's folder as git sees them, relative to it, with forward + * slashes: those it tracks, and those it does not track and does not ignore. + * + * One process lists both: `-t` puts a status letter and a space before each + * path, `?` for a file git does not track. On Windows a `git` takes a few tenths + * of a second to start, so the build starts this long before it packs the + * project (the addinFiles task) and passes the promise to packAddinProject. + * + * @returns {Promise<{tracked: string[], untracked: string[]}>} + */ +export async function listAddinFiles(dir) { + const { stdout } = await exec( + "git", + ["-C", dir, "ls-files", "-z", "-t", "--cached", "--others", "--exclude-standard", "--", "."], + { maxBuffer: 16 * 1024 * 1024 }, + ); + const tracked = new Set(); + const untracked = new Set(); + for (const entry of stdout.split("\0")) { + if (!entry) continue; + (entry[0] === "?" ? untracked : tracked).add(entry.slice(2)); + } + return { tracked: [...tracked].sort(byCodePoint), untracked: [...untracked].sort(byCodePoint) }; } const isHelp = (rel) => rel.toLowerCase().startsWith(HELP_DIR); @@ -96,12 +114,14 @@ function lf(bytes) { * @param {string} [o.symbols] the symbol index to pack in place of the folder's copy * @param {Buffer} [o.archive] the offline tree's archive this build wrote, packed as * Resources/HELP/site.zip; none when absent, whatever site.zip is on the disk + * @param {Promise<{tracked: string[], untracked: string[]}>} [o.listing] what + * listAddinFiles(dir) returned, when the caller started it earlier * @returns {Promise<{bytes: Buffer, files: string[], untracked: string[]}>} the * project file, the files packed, and the files git does not track that were * left out (Resources/HELP/ aside) */ -export async function packAddinProject({ dir, symbols, archive = null }) { - const [tracked, untracked] = await Promise.all([gitFiles(dir), gitFiles(dir, "--others", "--exclude-standard")]); +export async function packAddinProject({ dir, symbols, archive = null, listing = null }) { + const { tracked, untracked } = await (listing ?? listAddinFiles(dir)); const files = []; for (const rel of tracked) { if (isHelp(rel)) continue; @@ -139,11 +159,12 @@ export async function packAddinProject({ dir, symbols, archive = null }) { * @param {Buffer} [o.archive] the offline archive this build wrote, if it wrote one * @param {string[]} o.roots the trees to write into * @param {string} o.rel the file's path in each tree + * @param {Promise} [o.listing] listAddinFiles(dir), started earlier * @returns {Promise<{rel: string, bytes: number, files: number, archived: boolean, untracked: string[], roots: number, ms: number}>} */ -export async function writeAddinProject({ dir, symbols, archive = null, roots, rel }) { +export async function writeAddinProject({ dir, symbols, archive = null, roots, rel, listing = null }) { const t0 = Date.now(); - const packed = await packAddinProject({ dir, symbols, archive }); + const packed = await packAddinProject({ dir, symbols, archive, listing }); for (const root of roots) { const out = path.join(root, ...rel.split("/")); await fs.mkdir(path.dirname(out), { recursive: true }); diff --git a/builder/build-info.mjs b/builder/build-info.mjs index ce781163..f53b7f3d 100644 --- a/builder/build-info.mjs +++ b/builder/build-info.mjs @@ -1,8 +1,12 @@ -// Phase 2 build-info capture. Two `git` shell-outs (parallel) to -// produce { commit, commitDate } for the PDF title page. Falls back to +// Phase 2 build-info capture. One `git` shell-out to produce +// { commit, commitDate } for the PDF title page. Falls back to // "unknown" placeholders when git is missing or this isn't a repo // (tarball install) so the build never aborts on it. // +// One process, not two: on Windows a `git` takes a few tenths of a second to +// start, more while the lanes boot. `%h` is the abbreviation `rev-parse +// --short HEAD` prints. +// // See builder/PLAN-2.md §5.9. Ports: _plugins/build-info.rb. import { execFile } from "node:child_process"; @@ -11,18 +15,12 @@ import { promisify } from "node:util"; const exec = promisify(execFile); export async function captureBuildInfo() { - const [commit, commitDate] = await Promise.all([ - git("rev-parse", "--short", "HEAD"), - git("log", "-1", "--format=%cs"), - ]); - return { commit, commitDate }; -} - -async function git(...args) { try { - const { stdout } = await exec("git", args); - return stdout.trim(); + const { stdout } = await exec("git", ["log", "-1", "--format=%h %cs"]); + const [commit, commitDate] = stdout.trim().split(" "); + if (commit && commitDate) return { commit, commitDate }; } catch { - return "unknown"; + // Not a repository, or no git. } + return { commit: "unknown", commitDate: "unknown" }; } diff --git a/builder/cpu-worker.mjs b/builder/cpu-worker.mjs index 30329c20..0bc8847b 100644 --- a/builder/cpu-worker.mjs +++ b/builder/cpu-worker.mjs @@ -20,7 +20,7 @@ import { unpackShared } from "./sab-broadcast.mjs"; // second boot bar. The names are module-level bindings that loadRest fills, so // that the handlers read as they would with static imports. // biome-ignore format: one module per line -let compileLightScss, compileDarkScss, regenerateDot, captureBuildInfo, deflateGroup, writePdf, unpackBookPayload, +let compileLightScss, compileDarkScss, regenerateDot, deflateGroup, writePdf, unpackBookPayload, createMarkdownIt, renderPhase, markdownCopy, markdownCopyRel, navTreeVersion, renderFullNav, templatePhase, withOnlineNav, withPartialNav, deriveSearchEntries, entryKeys, labelKey, packSearchEntries, readSearchEntries, @@ -33,7 +33,6 @@ const loadRest = () => const start = Date.now(); ({ compileLightScss, compileDarkScss } = await import("./scss.mjs")); ({ regenerateDot } = await import("./dot.mjs")); - ({ captureBuildInfo } = await import("./build-info.mjs")); ({ deflateGroup } = await import("./help-archive-step.mjs")); ({ writePdf } = await import("./pdf.mjs")); ({ unpackBookPayload } = await import("./book-payload.mjs")); @@ -250,11 +249,6 @@ const handlers = { return { dotStats }; }, - async buildInfo() { - const buildInfo = await captureBuildInfo(); - return { buildInfo }; - }, - // The contributed packages' test projects and published tools, packed in // memory (package-tests.mjs) from the package_tests entry that config // broadcast. The bytes go back to the main thread, where downloadSizes reads diff --git a/builder/gantt.mjs b/builder/gantt.mjs index 0346dd32..21d343a7 100644 --- a/builder/gantt.mjs +++ b/builder/gantt.mjs @@ -45,7 +45,7 @@ const BAR_PAD = 4; // its own `ganttSection` is charted there instead. // biome-ignore format: a table, one entry per line export const GANTT_SECTION = { - config: "Seeds", buildInfo: "Seeds", scssLight: "Seeds", scssDark: "Seeds", scss: "Write", dot: "Spine", + config: "Seeds", buildInfo: "Seeds", addinFiles: "Seeds", scssLight: "Seeds", scssDark: "Seeds", scss: "Write", dot: "Spine", highlighterInit: "Seeds", loadData: "Seeds", discoverList: "Spine", discover: "Spine", vendorAssets: "Spine", nav: "Spine", markdownInit: "Spine", buildInit: "Spine", resolveBookChapters: "Spine", diff --git a/builder/sab-scheduler.mjs b/builder/sab-scheduler.mjs index dc061e1f..e190a98b 100644 --- a/builder/sab-scheduler.mjs +++ b/builder/sab-scheduler.mjs @@ -34,7 +34,6 @@ export const HANDLERS = { scssLight: 3, scssDark: 4, dot: 5, - buildInfo: 6, render: 7, writePdf: 9, checkBook: 10, diff --git a/builder/tbdocs.mjs b/builder/tbdocs.mjs index ce03380b..fb7217e7 100644 --- a/builder/tbdocs.mjs +++ b/builder/tbdocs.mjs @@ -106,7 +106,8 @@ import { normalizeBaseurl } from "./url.mjs"; // build without --check pays nothing. import { deriveTreeRels } from "./check-tree.mjs"; import { syncAddinIndex } from "./addin-index.mjs"; -import { addinProjectOf, formatAddinProject, writeAddinProject } from "./addin-project.mjs"; +import { addinProjectOf, formatAddinProject, listAddinFiles, writeAddinProject } from "./addin-project.mjs"; +import { captureBuildInfo } from "./build-info.mjs"; import { formatPackageTests, packageTestRels, packageTestsOf, writePackageTests } from "./package-tests.mjs"; import { finishHelpArchive, @@ -243,6 +244,16 @@ function fanOutArchive(scheduler, from, prefix, root, groups, priority = 1) { const skipsOffline = (ctx, state) => ctx.opts.skipOffline ?? state.site.config.also_build_offline === false; const skipsPdf = (ctx, state) => ctx.opts.skipPdf ?? state.site.config.also_build_pdf === false; +// A process the main thread started and does not wait for (the buildInfo and +// addinFiles tasks), as a bar of its own in the chart and an entry in the timing +// line: the task that started it is over at once, and says nothing of how long +// git took. The bar ends when the main thread hears the answer, which is later +// than the answer by whatever task it was in the middle of. +function chartProcess(scheduler, id, pending, start) { + const done = () => scheduler.timings.set(id, { start, end: Date.now(), ganttSection: "Seeds" }); + pending.then(done, done); +} + const TASKS = { // ── Seeds ───────────────────────────────────────────────────────────────── @@ -271,15 +282,47 @@ const TASKS = { }, }, - // Git rev-parse / log shell-outs, for the book's title page: bookPayload - // waits for them, and nothing on the way to the first render does. Like the - // other early lane tasks it waits for discoverList, so that the first lanes - // up read the source tree. + // Starts the git process whose answer the book's title page states, and does + // not wait for it: bookPayload does, long after it has answered. On Windows + // a git takes a few tenths of a second to start, and up to two seconds while + // the lanes boot; as a lane task it held a lane for that long, for no work of + // the lane's. After dispatch, so that the process starts once the main + // thread's way to the first render is behind it. A build that writes no PDF + // (--serve, --no-pdf, --dry-run) starts none. buildInfo: { - expected: ["discoverList"], - handler: "buildInfo", - submit(out, state) { - state.site.buildInfo = out.buildInfo; + expected: ["dispatch"], + runOnMain: true, + execute(_, ctx, state) { + const started = Date.now(); + state.buildInfoPending = ctx.opts.dryRun || skipsPdf(ctx, state) ? null : captureBuildInfo(); + return state.buildInfoPending ? { started } : null; + }, + // The chart's "git log" bar. + submit(out, state, scheduler) { + if (out) chartProcess(scheduler, "git:log", state.buildInfoPending, out.started); + }, + }, + + // Starts the git process that lists the help add-in's files, and does not + // wait for it: addinProject does, at the end of the build, where the listing + // used to take a few tenths of a second on Windows with nothing else left to + // run. A rejection is addinProject's to report, so it is marked as handled + // here. + addinFiles: { + expected: ["dispatch"], + runOnMain: true, + execute(_, ctx, state) { + const addin = addinProjectOf(state.site.config); + state.addinListing = null; + if (!addin || ctx.opts.dryRun) return null; + const started = Date.now(); + state.addinListing = listAddinFiles(path.resolve(ctx.srcRoot, addin.src)); + state.addinListing.catch(() => {}); + return { started }; + }, + // The chart's "git ls-files" bar. + submit(out, state, scheduler) { + if (out) chartProcess(scheduler, "git:ls-files", state.addinListing, out.started); }, }, @@ -804,8 +847,9 @@ const TASKS = { // two parallel halves: nav (sidebar) + buildInit (config-only chrome). dispatch: { // buildInfo is not here: the book's title page alone states the commit, so - // bookPayload waits for it. Its two git processes take up to 0.6 s in a - // one-off build on Windows, and every render waited for them. + // bookPayload waits for it. Its git process takes up to 0.6 s in a + // one-off build on Windows, and every render waited for it. The buildInfo + // task waits for this one, only to start the process after it. expected: ["nav", "buildInit", "dot", "deriveRedirects", "markdownInit"], runOnMain: true, async execute( @@ -1450,7 +1494,7 @@ const TASKS = { // fixtures) packs nothing. A failure is reported and fails the build; the // trees are still written. addinProject: { - expected: ["symbolIndex", "prepDest", "helpArchive"], + expected: ["symbolIndex", "prepDest", "helpArchive", "addinFiles"], runOnMain: true, async execute({ symbolIndex, helpArchive }, ctx, state) { const addin = addinProjectOf(state.site.config); @@ -1462,6 +1506,7 @@ const TASKS = { archive: helpArchive?.zip ?? null, roots: [ctx.destRoot], rel: addin.dest, + listing: state.addinListing, }); } catch (err) { return { failed: true, rel: addin.dest, error: err.message }; @@ -1519,9 +1564,12 @@ const TASKS = { // states (state.site.buildInfo), which nothing before this reads. expected: ["flushJoin", "renderJoin", "dot", "resolveBookChapters", "buildInfo"], runOnMain: true, - execute(_, ctx, state) { + async execute(_, ctx, state) { const skip = !!ctx.opts.dryRun || skipsPdf(ctx, state); - if (!skip) prerenderPartText(state.site.bookData, state.site.markdown); + if (!skip) { + state.site.buildInfo = await state.buildInfoPending; + prerenderPartText(state.site.bookData, state.site.markdown); + } return packBookPayload({ pages: state.pages, staticFiles: state.staticFiles, diff --git a/docs/Documentation/Builder.md b/docs/Documentation/Builder.md index d17e78da..32d4ec4f 100644 --- a/docs/Documentation/Builder.md +++ b/docs/Documentation/Builder.md @@ -217,7 +217,7 @@ The full layout, the allocation helper and the `readTaskMeta` / `writeTaskMeta` The pipeline has the named static tasks below, plus dynamic ones: a `render:i` and a `flush:i` for each render chunk, and the pieces of the search index and of the help archive. The Gantt chart groups them into these sections, and so does the rest of this page: -- **Seeds**: `config`, `buildInfo`, `scssLight`, `scssDark`, `highlighterInit`, `loadData` +- **Seeds**: `config`, `buildInfo`, `addinFiles`, `scssLight`, `scssDark`, `highlighterInit`, `loadData` - **Spine**: `discoverList`, `discoverRead:i`, `discover`, `vendorAssets`, `nav`, `dot`, `buildInit`, `markdownInit`, `deriveRedirects`, `deriveSitemap`, `resolveBookChapters`, `packTests`, `downloadSizes`, `packageApi` - **Render**: `dispatch`, `prepDest`, `prepPageDirs`, `render:i`, `renderJoin` - **Write**: `scss`, `flush:i`, `flushJoin`, `writeAssets`, `searchData`, `symbolIndex`, `archivePlan`, `archiveDeflate:i`, `archiveLate`, `archiveLateDeflate:i`, `helpArchive`, `addinProject`, `packageTests`, `writeAux`, `writeOffline`, `bookPayload`, `writePdf` @@ -234,10 +234,13 @@ Every static task and dependency: ### Seeds -`config` has no predecessor and starts at once; `highlighterInit` waits for `config`, and `loadData` for `highlighterInit`. `buildInfo`, `scssLight` and `scssDark` wait for `discoverList`, the listing of the source tree, so that the first workers up are free to read it (see [Spine](#spine)). The three worker tasks run while the source tree is read and the main thread prepares the render. +`config` has no predecessor and starts at once; `highlighterInit` waits for `config`, and `loadData` for `highlighterInit`. `scssLight` and `scssDark` wait for `discoverList`, the listing of the source tree, so that the first workers up are free to read it (see [Spine](#spine)). The two run while the source tree is read and the main thread prepares the render. `buildInfo` and `addinFiles` wait for `dispatch`. - `config` (main) --- reads `_config.yml` and applies CLI overrides. -- `buildInfo` (worker) --- two `git` shell-outs. Falls back to `"unknown"` on failure. Only the book's title page states the result, so `bookPayload` waits for it and the render does not. +- `buildInfo` (main) --- starts one `git` process and does not wait for it. Only the book's title page states the result, so `bookPayload` awaits it and the render does not. Falls back to `"unknown"` on failure. A build that writes no PDF starts no process. +- `addinFiles` (main) --- starts the `git` process that lists the help add-in's files and does not wait for it; `addinProject` awaits the list at the end of the build. + +The [Gantt chart](BuildInfo) draws each of the two processes as a bar of its own in the Seeds band, `git log` and `git ls-files`, from the start of the process to the moment the main thread receives its answer. The bars of `buildInfo` and `addinFiles` themselves are a few milliseconds long. - `scssLight` (worker) --- compiles `just-the-docs-combined.scss` against the light palette. - `scssDark` (worker) --- the same against the dark palette. - `highlighterInit` (main) --- loads the `Light.theme` + `Dark.theme` palette and emits `tb-highlight.css`. Each worker initialises its own Shiki. @@ -308,7 +311,7 @@ dispatch ┬→ render:0 ┬→ flush:0 ┐ - `indexSlices`, `indexMerge`, `indexTerms`, `searchIndex` (main) and `indexAdd:i`, `indexVectors:i` (worker) --- build the lunr index of the search entries and write `search-index.json`, the entries and their index in one file, which the search box loads instead of building the index, and the offline tree's `search-index.js`. The index is built in slices on the lanes and merged into exactly the index `lunr()` makes (see [Pipeline Stages](Pipeline-Stages#searchindex-worker)). A lane reads its slice's entries from the buffers the render lanes packed, so the main thread does not send them. `indexSlices` depends on `searchEntries`; `archiveLate` and `checkReport` wait for `searchIndex`. - `symbolIndex` (main) --- writes `tB/symbols.json`, the [symbol index](Building#the-symbol-index) the IDE help add-in reads, from what `symbolPlace` placed, and returns the index's URLs for the drift guard that `runBuild` runs at the end. Depends on `symbolPlace` and `prepDest`. `checkReport` and `addinProject` wait for it. - `archivePlan`, `archiveLate`, `helpArchive` (main) and `archiveDeflate:i`, `archiveLateDeflate:i` (worker) --- write `add-in/Resources/HELP/site.zip`, the archive of the offline tree that the IDE help add-in embeds (see [Build and Generation Tools](Tools-Build#the-help-archive) and [Pipeline Stages](Pipeline-Stages#helparchive-worker)). `archivePlan` depends on `flushJoin`, `scss` and `writeOffline`, which between them write the whole offline tree but `search-index.js`, and the lanes deflate that tree while the search index is built. `archiveLate` depends on `searchIndex` and has the lanes deflate `search-index.js`, in pieces. `helpArchive` writes the zip from what the lanes deflated. The archive leaves out the sections `HELP_ARCHIVE_SKIP` lists, `BuildInfo.html` and its chart among them, and is made before the Gantt chart is injected. It is made only for a `docs` build into the default `--dest`, `docs/_site`, with an offline tree, and not under `--serve`, `--dry-run` or `--no-help-archive`. After the chart is injected, `runBuild` checks that the offline tree still lists the archive's files and differs from it in `BuildInfo.html` and `assets/images/gantt.svg` alone. -- `addinProject` (main) --- packs the help add-in's source folder, `add-in/`, into `tbDocsHelp.twinproj` and writes it into the online tree at the path `_config.yml`'s `addin_project` names (see [Build and Generation Tools](Tools-Build#the-help-add-ins-project-file)). The files are those git tracks there, the symbol index is the one `symbolIndex` wrote, and `Resources/HELP/site.zip` is the archive `helpArchive` wrote, if any. Depends on `symbolIndex`, `prepDest` and `helpArchive`; `checkReport` waits for it. Does nothing under `--dry-run` or for a config that declares no download. +- `addinProject` (main) --- packs the help add-in's source folder, `add-in/`, into `tbDocsHelp.twinproj` and writes it into the online tree at the path `_config.yml`'s `addin_project` names (see [Build and Generation Tools](Tools-Build#the-help-add-ins-project-file)). The files are those git tracks there, the symbol index is the one `symbolIndex` wrote, and `Resources/HELP/site.zip` is the archive `helpArchive` wrote, if any. Depends on `symbolIndex`, `prepDest`, `helpArchive` and `addinFiles`, whose list of files it awaits; `checkReport` waits for it. Does nothing under `--dry-run` or for a config that declares no download. - `writeAux` (main) --- writes redirect stubs, the sitemap, robots.txt, llms.txt and the online tree's `nav.html`, the whole nav tree, which `linkJoin` checks with the stubs. Depends on `writeAssets`, `searchData`, `flushJoin`, `renderJoin` (llms.txt takes each page's note from its `renderedContent`), `deriveRedirects`, `deriveSitemap`. - `writeOffline` (main) --- produces `_site-offline/`. `render:i` and `flush:i` already computed and wrote the per-page HTML, so this task does the cross-cutting work: CSS url() rewriting, the just-the-docs.js AST patch, the offline `nav.js`, theme assets and redirect stubs. The offline search index, `search-index.js`, is `searchIndex`'s. - `bookPayload` (main) --- packs what the book needs into one shared buffer and broadcasts it to every worker. It renders each part's subtitle and intro first, because markdown-it cannot cross to a worker, and replaces every page reference in `bookData` with the page's index in the page list, so the worker resolves it back to the same object. Depends on `flushJoin` (`renderedContent` is filled), `renderJoin`, `resolveBookChapters` (`bookData._chapters` is set) and `dot` (diagram SVGs are in `staticFiles`). The broadcast is posted before the task is marked done, so it is queued on every lane before any lane can claim `writePdf`. Under `--dry-run`, or when the build writes no PDF tree, it packs a marker that tells `writePdf` there is nothing to write. @@ -321,7 +324,7 @@ Every task and where it runs: | Section | Task | Locus | Notes | |---|---|---|---| | Seeds | `config` | main | Trivial read; output feeds `discover` directly. | -| Seeds | `buildInfo` | worker | Two `git` shell-outs in parallel. | +| Seeds | `buildInfo`, `addinFiles` | main | Each starts one `git` process and returns; the task that needs the answer awaits it. | | Seeds | `scssLight`, `scssDark` | workers | Light + dark palettes compile concurrently. | | Seeds | `highlighterInit` | main | Palette CSS only. | | Seeds | `loadData` | main | Reads `_book.yml`. | diff --git a/docs/Documentation/Building.md b/docs/Documentation/Building.md index a76f58ff..d2b579c0 100644 --- a/docs/Documentation/Building.md +++ b/docs/Documentation/Building.md @@ -88,6 +88,7 @@ Do not drop `--check-audit-index` when typing the underlying build command: with && node --test test/indexer.test.mjs \ && node --test test/ide-js.test.mjs \ && node --test test/discover.test.mjs \ + && node --test test/build-speed.test.mjs \ && node scripts/check_regex_safety.mjs \ && node scripts/check_code_regions.mjs \ && node scripts/check_page_baseline.mjs \ diff --git a/docs/Documentation/Extending.md b/docs/Documentation/Extending.md index ac215f01..f15bcb44 100644 --- a/docs/Documentation/Extending.md +++ b/docs/Documentation/Extending.md @@ -218,7 +218,7 @@ Worker handlers live in `cpu-worker.mjs`. Two edits: export const HANDLERS = { warmInit: 0, renderEnvInit: 1, flush: 2, scssLight: 3, scssDark: 4, dot: 5, - buildInfo: 6, render: 7, + render: 7, writePdf: 9, checkBook: 10, indexAdd: 12, indexVectors: 13, archiveDeflate: 14, myHandler: 15, // ← new diff --git a/docs/Documentation/Images/Tools-Groups.dot b/docs/Documentation/Images/Tools-Groups.dot index 8a3daa53..a5db08a8 100644 --- a/docs/Documentation/Images/Tools-Groups.dot +++ b/docs/Documentation/Images/Tools-Groups.dot @@ -81,7 +81,8 @@ digraph tools_groups { b3 [label="compare_trees"] b4 [label="survey_tooling"] b5 [label="convert_em_dash_separators"] b6 [label="build_fonts.py"] b7 [label="build_dot_metrics"] b8 [label="twin-index"] - b1 -> b3 -> b5 -> b7 + b9 [label="build_speed"] + b1 -> b3 -> b5 -> b7 -> b9 b2 -> b4 -> b6 -> b8 { rank=same; b3 b4 } { rank=same; b5 b6 } @@ -137,11 +138,11 @@ digraph tools_groups { t25 [label="indexer.test"] t26 [label="check_package_tests"] t27 [label="broker.test"] t28 [label="ide-js.test"] t29 [label="shot-review.test"] t30 [label="check_callout_evidence"] - t31 [label="discover.test"] + t31 [label="discover.test"] t32 [label="build-speed.test"] t1 -> t5 -> t9 -> t13 -> t17 -> t21 -> t25 -> t29 t2 -> t6 -> t10 -> t14 -> t18 -> t22 -> t26 -> t30 t3 -> t7 -> t11 -> t15 -> t19 -> t23 -> t27 -> t31 - t4 -> t8 -> t12 -> t16 -> t20 -> t24 -> t28 + t4 -> t8 -> t12 -> t16 -> t20 -> t24 -> t28 -> t32 { rank=same; t5 t6 t7 t8 } { rank=same; t9 t10 t11 t12 } { rank=same; t13 t14 t15 t16 } @@ -261,6 +262,8 @@ digraph tools_groups { tooltip="Renders the PDF book from the pre-built _site-pdf/book.html with puppeteer, paged.js and pdf-lib."] b3 [URL="Tools-Build#compare-trees" tooltip="Builds the site from a commit and from the working tree, and compares the online, offline and PDF trees byte for byte."] + b9 [URL="Tools-Build#build-speed" + tooltip="Measures the build: builds each checkout several times on every CPU and on four, reads the times from each Gantt chart, and times one part of the build alone."] b4 [URL="Tools-Build#survey-tooling" tooltip="Surveys the tooling for duplicated code, repeated functions, argument reading, undeclared packages and the import graph. It is not a gate."] b5 [URL="Tools-Build#convert-em-dash-separators" @@ -368,6 +371,8 @@ digraph tools_groups { tooltip="Runs unit tests for the screenshot review tool: its session, its pages, its writes under docs, and its server with a stand-in run and a commit in a scratch repository."] t31 [URL="Tools-Toolchain-Tests#discover-test" tooltip="Runs unit tests for the source tree's inventory, which the build reads in pieces on its lanes: the same in any number of pieces, on a small tree of the tests' own."] + t32 [URL="Tools-Toolchain-Tests#build-speed-test" + tooltip="Runs unit tests for the build-speed tool's readers: a Gantt chart drawn with the build's writer is read back to the same times, and a CPU profile is totalled by function."] t30 [URL="Tools-Toolchain-Tests#check-callout-evidence" tooltip="Verifies that every callout labelled with a twinBASIC build names what checks it, and that every marker names a reproducer, lane, sample, error data file or LLVM probe mode that exists."] diff --git a/docs/Documentation/Images/Tools-Groups.svg b/docs/Documentation/Images/Tools-Groups.svg index b35d963f..92737328 100644 --- a/docs/Documentation/Images/Tools-Groups.svg +++ b/docs/Documentation/Images/Tools-Groups.svg @@ -1,71 +1,71 @@ - - + + tools_groups cluster_wrappers - -Batch wrappers + +Batch wrappers cluster_build - -Build and Generation + +Build and Generation cluster_site - -Site Checks + +Site Checks cluster_compiler - -Compiler Harness + +Compiler Harness cluster_tests - -Toolchain Tests + +Toolchain Tests cluster_samples - -Code Samples and Attributes + +Code Samples and Attributes cluster_ide - -IDE Automation + +IDE Automation cluster_defects - -Defect Reproducers + +Defect Reproducers @@ -73,8 +73,8 @@ w1 - -build.bat + +build.bat @@ -82,8 +82,8 @@ w2 - -serve.bat + +serve.bat @@ -91,8 +91,8 @@ w3 - -check.bat + +check.bat @@ -100,8 +100,8 @@ w4 - -test.bat + +test.bat @@ -109,8 +109,8 @@ w5 - -book.bat + +book.bat @@ -118,8 +118,8 @@ w6 - -examples.bat + +examples.bat @@ -127,8 +127,8 @@ w7 - -addin-test.bat + +addin-test.bat @@ -136,8 +136,8 @@ w8 - -ide-test.bat + +ide-test.bat @@ -145,8 +145,8 @@ w9 - -try-help-addin.bat + +try-help-addin.bat @@ -154,8 +154,8 @@ w10 - -package-tests.bat + +package-tests.bat @@ -163,8 +163,8 @@ b1 - -tbdocs + +tbdocs @@ -172,8 +172,8 @@ b2 - -render-book + +render-book @@ -181,8 +181,8 @@ b3 - -compare_trees + +compare_trees @@ -190,8 +190,8 @@ b4 - -survey_tooling + +survey_tooling @@ -199,8 +199,8 @@ b5 - -convert_em_dash_separators + +convert_em_dash_separators @@ -208,8 +208,8 @@ b6 - -build_fonts.py + +build_fonts.py @@ -217,8 +217,8 @@ b7 - -build_dot_metrics + +build_dot_metrics @@ -226,612 +226,630 @@ b8 - -twin-index + +twin-index - + +b9 + + +build_speed + + + + + s1 - - -check_links + + +check_links - + s2 - - -crawl_check + + +crawl_check - + s3 - - -check_links_diff + + +check_links_diff - + s4 - - -check_tree_fresh + + +check_tree_fresh - + s5 - - -check_dot_fit + + +check_dot_fit - + s6 - - -check_a11y + + +check_a11y - + s7 - - -pick_a11y_sample + + +pick_a11y_sample - + s8 - - -axe-scan + + +axe-scan - + s9 - - -check_a11y_fingerprint + + +check_a11y_fingerprint - + s10 - - -sweep_a11y + + +sweep_a11y - + s11 - - -check_shot_sizes + + +check_shot_sizes - + c1 - - -tbbuild + + +tbbuild - + c2 - - -tbrun + + +tbrun - + c3 - - -impexp + + +impexp - + c4 - - -check_tb_registry + + +check_tb_registry - + c7 - - -tbbroker + + +tbbroker - + c6 - - -probe_build_twice + + +probe_build_twice - + t1 - - -check_publish_policy + + +check_publish_policy - + t2 - - -check_regex_safety + + +check_regex_safety - + t3 - - -check_code_regions + + +check_code_regions - + t4 - - -check_gate_lists + + +check_gate_lists - + t5 - - -check_ci_workflows + + +check_ci_workflows - + t6 - - -check_lint + + +check_lint - + t7 - - -search.test + + +search.test - + t8 - - -render.test + + +render.test - + t9 - - -strftime.test + + +strftime.test - + t10 - - -png.test + + +png.test - + t11 - - -compact-image.test + + +compact-image.test - + t12 - - -svgshot.test + + +svgshot.test - + t13 - - -example-batches.test + + +example-batches.test - + t14 - - -ide-folders.test + + +ide-folders.test - + t15 - - -addin-project.test + + +addin-project.test - + t16 - - -check_page_baseline + + +check_page_baseline - + t17 - - -check_book_coverage + + +check_book_coverage - + t18 - - -check_symbol_index + + +check_symbol_index - + t19 - - -check_twin_parsers + + +check_twin_parsers - + t20 - - -check_attribute_sweep + + +check_attribute_sweep - + t21 - - -check_cli + + +check_cli - + t22 - - -check_pdf_shims_equiv + + +check_pdf_shims_equiv - + t23 - - -check_impexp_parity + + +check_impexp_parity - + t24 - - -check_axe_patch_equiv + + +check_axe_patch_equiv - + t25 - - -indexer.test + + +indexer.test - + t26 - - -check_package_tests + + +check_package_tests - + t27 - - -broker.test + + +broker.test - + t28 - - -ide-js.test + + +ide-js.test - + t29 - - -shot-review.test + + +shot-review.test - + t30 - - -check_callout_evidence + + +check_callout_evidence - + t31 - - -discover.test + + +discover.test + + + + + +t32 + + +build-speed.test - + e1 - - -check_examples + + +check_examples - + e2 - - -gen_attribute_probes + + +gen_attribute_probes - + e3 - - -census_attributes + + +census_attributes - + e4 - - -sweep_attributes + + +sweep_attributes - + e5 - - -package_tests + + +package_tests - + i1 - - -addin_test + + +addin_test - + i2 - - -ide_test + + +ide_test - + i3 - - -try_help_addin + + +try_help_addin - + i4 - - -shoot_docs + + +shoot_docs - + i5 - - -imagestrip + + +imagestrip - + i8 - - -probe_theme_semicolon + + +probe_theme_semicolon - + i7 - - -svgshot/replay + + +svgshot/replay - + i10 - - -shot_review + + +shot_review - + i11 - - -svgshot/chromeshot + + +svgshot/chromeshot - + i12 - - -svgshot/chrome_try + + +svgshot/chrome_try - + d1 - - -bug_repro + + +bug_repro - + d2 - - -vb6run + + +vb6run - + d3 - - -recheck_callouts + + +recheck_callouts - + d4 - - -ide_js + + +ide_js @@ -849,6 +867,7 @@ + @@ -896,6 +915,7 @@ + diff --git a/docs/Documentation/Pipeline-Stages.md b/docs/Documentation/Pipeline-Stages.md index ab79979b..58d96b8d 100644 --- a/docs/Documentation/Pipeline-Stages.md +++ b/docs/Documentation/Pipeline-Stages.md @@ -61,7 +61,7 @@ Each task's `execute()` or `submit()` stores its output on `state.site`; downstr |---|---|---|---| | `config` | `object` | `discover` | Parsed `_config.yml`, with CLI overrides (`--baseurl`, `--url`) already applied. | | `navTree` | `object` | `nav` | Top-level nav hierarchy. | -| `buildInfo` | `object` | `buildInfo` | `{ commit: string, commitDate: string }` from git. Both fall back to `"unknown"` outside a git repository. | +| `buildInfo` | `object` | `bookPayload` | `{ commit: string, commitDate: string }` from git, in a build that writes the PDF. Both fall back to `"unknown"` outside a git repository. | | `data` | `object` | `loadData` | `_book.yml` loaded as `{ book: … }`, or `{}` when absent. | | `bookData` | `object\|null` | `loadData` | Shortcut for `data.book`. After `resolveBookChapters`, each entry holds `_chapters` (`Page[]`) plus `_landing` / `_foreword` if declared. | | `markdown` | `MarkdownIt` | `markdownInit` | Main-thread markdown-it instance. Used only for site-level SEO; render workers build their own. | @@ -125,7 +125,7 @@ Every task is an entry in the static `TASKS` object in [`tbdocs.mjs`](https://gi export const HANDLERS = { warmInit: 0, renderEnvInit: 1, flush: 2, scssLight: 3, scssDark: 4, dot: 5, - buildInfo: 6, render: 7, + render: 7, writePdf: 9, checkBook: 10, packTests: 11, indexAdd: 12, indexVectors: 13, archiveDeflate: 14, discoverRead: 15, @@ -148,7 +148,7 @@ A task therefore never starts a worker thread or a process for its work, and nev ## Section 1 --- Seed tasks -The tasks that start the build. `config` has no predecessor and is claimable as soon as the build starts; `highlighterInit` waits for `config`, and `loadData` for `highlighterInit`. `buildInfo`, `scssLight` and `scssDark` wait for [`discoverList`](#discoverlist-main), as `dot`, `packTests` and `warmInit` do. +The tasks that start the build. `config` has no predecessor and is claimable as soon as the build starts; `highlighterInit` waits for `config`, and `loadData` for `highlighterInit`. `scssLight` and `scssDark` wait for [`discoverList`](#discoverlist-main), as `dot`, `packTests` and `warmInit` do. `buildInfo` and `addinFiles` wait for [`dispatch`](#dispatch-main), and each only starts a `git` process. ### `config` (main) @@ -158,9 +158,17 @@ config.execute({}, ctx) → { config } Reads `/_config.yml`, applies the `ctx.opts.baseurl` and `ctx.opts.url` overrides, and returns the parsed object to `discover`. `submit` broadcasts the config's `package_tests` entry to the lanes as the `"packageTests"` task data, for [`packTests`](#packtests-worker). -### `buildInfo` (worker) +### `buildInfo` (main) -Handler in `cpu-worker.mjs`: calls `captureBuildInfo()` from `build-info.mjs`, which runs two parallel `git` commands (`rev-parse --short HEAD` and `log -1 --format=%cs`). Falls back to `"unknown"` on failure. The result goes to `state.site.buildInfo`, which the book's title page alone states: [`bookPayload`](#bookpayload-main) waits for this task, and `dispatch` does not, so no render waits for `git`. +Starts `captureBuildInfo()` from `build-info.mjs`, which runs one `git` command (`log -1 --format="%h %cs"`), and keeps the promise in `state.buildInfoPending` without waiting for it. [`bookPayload`](#bookpayload-main) awaits the promise and puts the result in `state.site.buildInfo`, which the book's title page alone states. Both values fall back to `"unknown"` on failure. The task waits for `dispatch`, so that the process starts after the main thread's work for the first render, and no render waits for `git`. A build that writes no PDF (`--serve`, `--no-pdf`, `--dry-run`) starts no process. + +The task is on the main thread because a lane that waits for `git` does no other work meanwhile, and on Windows a `git` process takes a few tenths of a second to start. + +### `addinFiles` (main) + +Starts `listAddinFiles()` from `addin-project.mjs` on the help add-in's folder, which runs one `git ls-files`, and keeps the promise in `state.addinListing` without waiting for it. [`addinProject`](#addinproject-main) awaits it at the end of the build. Waits for `dispatch`, as `buildInfo` does. Does nothing under `--dry-run` or for a config that declares no download. + +Neither task's own time says how long `git` took, so each task's `submit` passes its promise to `chartProcess` in `tbdocs.mjs`, which adds a timing to `scheduler.timings` when the promise settles: `git:log` for `buildInfo` and `git:ls-files` for `addinFiles`. The Gantt chart draws each as a bar in the Seeds band, and the build's timing line states each. The timing ends when the main thread receives the answer, which is later than the process's end when the main thread is in the middle of another task. ### `scssLight` (worker), `scssDark` (worker) @@ -207,7 +215,7 @@ Calls `listSources(srcRoot, config.exclude ?? [])` and then `cutPieces(listing, `submit()` calls `fanOut` with the pieces as payloads, handler `discoverRead`, join `discover` and the highest priority of any lane task. -The lane tasks that would otherwise be claimable before the pieces exist list `discoverList` in their `expected`: `buildInfo`, `scssLight`, `scssDark`, `dot`, `packTests` and `warmInit`. The first lanes to start therefore find the pieces and nothing else. +The lane tasks that would otherwise be claimable before the pieces exist list `discoverList` in their `expected`: `scssLight`, `scssDark`, `dot`, `packTests` and `warmInit`. The first lanes to start therefore find the pieces and nothing else. ### `discoverRead:i` (worker) @@ -566,11 +574,11 @@ The result fields: ### `addinProject` (main) ```js -addinProject.expected = ["symbolIndex", "prepDest"] -addinProject.execute({ symbolIndex }) → { rel, bytes, files, untracked, roots, ms } | { failed, rel, error } | null +addinProject.expected = ["symbolIndex", "prepDest", "helpArchive", "addinFiles"] +addinProject.execute({ symbolIndex, helpArchive }) → { rel, bytes, files, untracked, roots, ms } | { failed, rel, error } | null ``` -Writes the help add-in's project file, the download [Help Add-In](../../tB/IDE/AddIns/Help) offers (see [Build and Generation Tools](Tools-Build#the-help-add-ins-project-file)). Reads `addin_project` from the config with `addinProjectOf`, and returns `null` when the config declares none or under `--dry-run`. Otherwise calls `writeAddinProject` from `addin-project.mjs` with the add-in's folder (`src`, resolved against the source root), `symbolIndex.json` and the trees to write: the online tree, and the offline tree unless the build has none or `offline_exclude` leaves the file out of it. `dispatch` has already put `dest` in both trees' indexes and in `sitePaths`, so links to the file resolve. `checkReport` waits for this task. A failure (`git` missing, an unreadable file) is returned, not thrown, so the trees are still written; `runBuild` prints the result and fails the build on `failed`. Takes ~100 ms. +Writes the help add-in's project file, the download [Help Add-In](../../tB/IDE/AddIns/Help) offers (see [Build and Generation Tools](Tools-Build#the-help-add-ins-project-file)). Reads `addin_project` from the config with `addinProjectOf`, and returns `null` when the config declares none or under `--dry-run`. Otherwise calls `writeAddinProject` from `addin-project.mjs` with the add-in's folder (`src`, resolved against the source root), `symbolIndex.json` and the trees to write: the online tree, and the offline tree unless the build has none or `offline_exclude` leaves the file out of it. `dispatch` has already put `dest` in both trees' indexes and in `sitePaths`, so links to the file resolve. `checkReport` waits for this task. The list of files is the one [`addinFiles`](#addinfiles-main) asked `git` for (`state.addinListing`), so this task does not wait for `git` to start. A failure (`git` missing, an unreadable file) is returned, not thrown, so the trees are still written; `runBuild` prints the result and fails the build on `failed`. Takes ~100 ms. ### `writeAux` (main) @@ -869,7 +877,7 @@ Both HTML escapers convert a value that is not a string with `String` first. | Symbol | Signature | Description | |---|---|---| -| `captureBuildInfo` | `() → Promise<{ commit, commitDate }>` | Runs two parallel `git` commands. Returns `"unknown"` on failure. | +| `captureBuildInfo` | `() → Promise<{ commit, commitDate }>` | Runs one `git` command. Returns `"unknown"` for both on failure. | ### `data.mjs` @@ -1132,8 +1140,9 @@ The one definition of the site search's lunr index: its fields and boosts (`FIEL | Symbol | Signature | Description | |---|---|---| | `addinProjectOf` | `(config) → { src, dest } \| null` | The download `_config.yml`'s `addin_project` declares, `dest` without a leading slash; `null` unless both ends are given. | -| `packAddinProject` | `({ dir, symbols }) → Promise<{ bytes, files, untracked }>` | Packs the files `git ls-files` lists in `dir`, as the working folder holds them, less `Resources/HELP/`, with CRLF made LF outside `Resources/`, and `symbols` in place of `Resources/SYMBOLS/symbols.json` when given. Packs them in memory with `packFiles` from `scripts/impexp.mjs`, which gives the bytes `importProject` would give for the same files in a folder. `untracked` lists the files git does not track that were left out. Throws when git fails or tracks no `Settings`. | -| `writeAddinProject` | `({ dir, symbols, roots, rel }) → Promise<{ rel, bytes, files, untracked, roots, ms }>` | Packs once and writes the file at `rel` in each of `roots`. | +| `listAddinFiles` | `(dir) → Promise<{ tracked, untracked }>` | The files of `dir` that git tracks, and those it neither tracks nor ignores, from one `git ls-files`. | +| `packAddinProject` | `({ dir, symbols, listing }) → Promise<{ bytes, files, untracked }>` | Packs the files `listing` names, or those `listAddinFiles(dir)` returns when it is given none, as the working folder holds them, less `Resources/HELP/`, with CRLF made LF outside `Resources/`, and `symbols` in place of `Resources/SYMBOLS/symbols.json` when given. Packs them in memory with `packFiles` from `scripts/impexp.mjs`, which gives the bytes `importProject` would give for the same files in a folder. `untracked` lists the files git does not track that were left out. Throws when git fails or tracks no `Settings`. | +| `writeAddinProject` | `({ dir, symbols, roots, rel, listing }) → Promise<{ rel, bytes, files, untracked, roots, ms }>` | Packs once and writes the file at `rel` in each of `roots`. | | `formatAddinProject` | `(result, dirLabel, indent) → string` | The line `runBuild` prints, and a second naming any untracked file left out. | ### `page-baseline.mjs` @@ -1211,7 +1220,6 @@ The handler table is built from the imported `HANDLERS` constant: | `flush` | inline | Drains the next `_pendingFlush` batch to disk. | | `scssLight` / `scssDark` | `scss.mjs` | Light/dark palette compile. | | `dot` | `dot.mjs` | `regenerateDot` over `srcRoot`. | -| `buildInfo` | `build-info.mjs` | `captureBuildInfo`. | | `packTests` | `package-tests.mjs` | `packAllPackageTests` over the `"packageTests"` task data; imports the module when it runs. | | `render` | inline | Five-stage chunk render: `renderPhase` → `computeChunkSeo` → `templatePhase` → offline → `deriveSearchEntries`. | | `indexAdd` | `search-index.mjs` | `addSlice` over its slice's entries, which `sliceDocs` reads from the `"indexEntries"` task data as the plan in its `fanOutPayload` says; keeps the builder in `_indexSlices` for `indexVectors`. | diff --git a/docs/Documentation/Tools-Build.md b/docs/Documentation/Tools-Build.md index 9f142c93..cc7ef2b6 100644 --- a/docs/Documentation/Tools-Build.md +++ b/docs/Documentation/Tools-Build.md @@ -126,7 +126,7 @@ The reader on the twinBASIC side does no inflating of its own, so the zip format - The DOS date and time are always 1980-01-01 00:00, and the version made by and needed is 20. - No extra fields, comments or data descriptors: the CRC-32 and both sizes are in the local header and in the central directory. - No zip64, so a tree of more than 65,535 files, or an archive of 4 GB, is refused. -- Files that are compressed already (`.png`, `.jpg`, `.jpeg`, `.gif`, `.webp`, `.ico`, `.woff2`, `.woff`, `.mp4`, `.zip`, `.pdf`) are stored. Every other file is deflated at level 9, and stored instead when the deflated data is not smaller than the file. +- Files that are compressed already (`.png`, `.jpg`, `.jpeg`, `.gif`, `.webp`, `.ico`, `.woff2`, `.woff`, `.mp4`, `.zip`, `.pdf`) are stored. Every other file is deflated, and stored instead when the deflated data is not smaller than the file. The level is 9 for a file deflated whole and 6 for one deflated in pieces, which is a file larger than 1 MB: the offline search index. - A deflated file larger than 1 MB is deflated in pieces of 1 MB, which are joined into one deflate stream. Every piece but the last ends with a sync flush, and each piece is primed with the 32 KB of the file before it, so the stream is about the size of one made in a single pass. The bytes depend only on the piece size, not on how many pieces were deflated at a time. Each file, or piece, is inflated again after it is deflated and compared with the bytes read. The build then reads the zip back, compares it with what it assembled, and checks every entry's headers against the list of files; it names any that differ. The writer is `lib/help-archive.mjs`. @@ -277,6 +277,53 @@ A run takes about ten seconds. It is not a gate, and nothing runs it. A failed r Exit codes: **0** the trees match; **1** the trees differ; **2** a refused command line, a git command or a build that failed to produce its tree, or a crash. +## build_speed.mjs +{: #build-speed } + + node scripts/build_speed.mjs bench [--tree ]... [--runs ] [--cpus all,4] [--task a,b] [--out ] + node scripts/build_speed.mjs serve [--tree ]... [--builds ] [--task a,b] [--out ] + node scripts/build_speed.mjs times ... [--task a,b] + node scripts/build_speed.mjs png ... + node scripts/build_speed.mjs profile --fn [--depth ] + node scripts/build_speed.mjs part [--tree ] [--file ] + +Measures the build, for work on its speed: how long it takes, where in it the time is, and what one part of it costs alone. The times come from each build's [Gantt chart](BuildInfo), since the build writes no timings file. + +| Command | What it does | +|---|---| +| `bench` | Builds each tree as `build.bat` does, `--runs` times (default 3), on every CPU and on the first four, which is the nearest thing a development machine has to a CI runner. `--cpus` gives other counts, as `all` or a number. | +| `serve` | Builds each tree `--builds` times (default 5) on one pool of lanes, as `tbdocs --serve` rebuilds, without the offline and PDF trees. The first build is cold; the summary is of the rebuilds. | +| `times` | Prints the times in charts kept from earlier runs. | +| `png` | Renders charts to PNG files beside them, with puppeteer. | +| `profile` | Prints the inclusive time of each function `--fn` names in a V8 CPU profile, with what it calls to `--depth` levels (default 3). A function that calls itself is counted once. | +| `part` | Times one part of the build alone on one thread. | + +`bench` and `serve` print one line for each build and then the range of each figure over the runs: when the first page is rendered, when the render ends and when the build ends. `--task` names main-thread tasks whose times are reported as well. One build's total says little on a machine that is doing other work, so compare ranges, and look at the charts. Each build's chart, and each `bench` build's log, is kept under `--out` (default `.build-speed/` in the checkout, gitignored). + +A tree is a checkout: the one the tool is in, unless `--tree` names another. Repeat `--tree` to compare two, such as a branch's worktree and the main checkout. The trees are built in turn within each run, so that other work on the machine affects both. `bench` builds a tree in place, as `build.bat` does; `serve` builds into a folder of its own in the tree and removes it. + +Take a profile for `profile` with Node's own option; the main thread's file is the one whose name ends `.0.001.cpuprofile`: + + node --cpu-prof --cpu-prof-interval 100 --cpu-prof-dir builder/tbdocs.mjs --src docs + +The parts `part` knows: + +| Part | What it times | +|---|---| +| `markdown-init` | The pieces of the `markdownInit` task: the link tables, the counts, the parser and the scan for placeholders. | +| `nav` | `computeNav`, each call on a fresh copy of the pages. | +| `index-slices` | The search index's add step against the slice count: its CPU in all and its longest slice. | +| `index-add` | The add step split into making the entries, tokenizing and stemming, lunr's `Builder.add`, and the postings written as JSON. | +| `index-terms` | What follows the adds: the merge, the inverted index's JSON, the vectors, the file's assembly and the offline copy. | +| `deflate` | A file deflated as one stream and as pieces, by level, piece size and priming. `--file` names the file; the default is the offline search index. | +| `archive` | The help archive's deflating on one thread, whole files and pieces apart, and the recheck of the archive. | + +A part runs the modules of the tree it is given, so one checkout's tool measures another's code. The index parts, `deflate` without `--file`, and `archive` read files a build wrote: build the tree first. A part's time alone is not its time in a build, where it shares the machine with every lane. + +It is not a gate, and nothing runs it. Its readers of the chart and of a profile are tested by [`build-speed.test.mjs`](Tools-Toolchain-Tests#build-speed-test). + +Exit codes: **0** done; **1** a build failed; **2** a refused command line, or a crash. + ## render-book.mjs {: #bookrender-bookmjs } diff --git a/docs/Documentation/Tools-Toolchain-Tests.md b/docs/Documentation/Tools-Toolchain-Tests.md index ec724596..da3edcc3 100644 --- a/docs/Documentation/Tools-Toolchain-Tests.md +++ b/docs/Documentation/Tools-Toolchain-Tests.md @@ -403,6 +403,21 @@ No build, no lanes, well under a second. Exit codes: **0** every test passed, **1** a test failed. +## build-speed.test.mjs +{: #build-speed-test } + + node --test test/build-speed.test.mjs + +Unit tests for the modules of [`build_speed.mjs`](Tools-Build#build-speed) that read what another part of the tooling writes. The tool takes a build's times from its Gantt chart, since the build writes no timings file. A change to how `builder/gantt.mjs` draws the chart would not fail the tool: it would report other numbers. The tests draw a chart from timings of their own with the build's writer and read the same times back: + +- the first render, the end of the render and the end of the chart, in a build of seconds and in one of minutes; +- a main-thread task by its label, and nothing for a name the chart has not; +- a chart with no render, and a file that is not a chart, which is refused. + +They also test the reading of a V8 CPU profile: a function's time includes what it calls, a function that calls itself is counted once, and a name with no sample is reported. + +Exit codes: **0** every test passed, **1** a test failed. + ## check_page_baseline.mjs {: #check-page-baseline } diff --git a/docs/Documentation/Tools.md b/docs/Documentation/Tools.md index af0ebc7a..5fb022d6 100644 --- a/docs/Documentation/Tools.md +++ b/docs/Documentation/Tools.md @@ -17,7 +17,7 @@ Reference for every executable in the documentation repository. This page covers ## Tool groups -![Eight rounded boxes, one per group of tools, each holding a smaller rounded box for every tool in the group. Batch wrappers holds the nine .bat files at the repository root. Build and Generation holds tbdocs, render-book, compare_trees and the generators of committed files. Site Checks holds the link, freshness, diagram and accessibility checks. Toolchain Tests, the largest group, holds the gates test.bat runs. Compiler Harness holds tbbuild, tbrun, impexp, tbbroker and the probes of the harness itself. Code Samples and Attributes holds check_examples and the three attribute tools. IDE Automation holds the add-in and IDE test runners, try_help_addin, shoot_docs, imagestrip, probe_theme_semicolon, the SVG replay, and the Chrome extension's chromeshot and chrome_try. Defect Reproducers holds bug_repro and vb6run. Each group's name links to its page, and each tool's box to its entry.](Images/Tools-Groups.svg) +![Eight rounded boxes, one per group of tools, each holding a smaller rounded box for every tool in the group. Batch wrappers holds the nine .bat files at the repository root. Build and Generation holds tbdocs, render-book, compare_trees, build_speed and the generators of committed files. Site Checks holds the link, freshness, diagram and accessibility checks. Toolchain Tests, the largest group, holds the gates test.bat runs. Compiler Harness holds tbbuild, tbrun, impexp, tbbroker and the probes of the harness itself. Code Samples and Attributes holds check_examples and the three attribute tools. IDE Automation holds the add-in and IDE test runners, try_help_addin, shoot_docs, imagestrip, probe_theme_semicolon, the SVG replay, and the Chrome extension's chromeshot and chrome_try. Defect Reproducers holds bug_repro and vb6run. Each group's name links to its page, and each tool's box to its entry.](Images/Tools-Groups.svg) - [Build and Generation Tools](Tools-Build) -- `tbdocs`, the PDF render driver, the build comparison, and the generators of committed files. - [Site Checks](Tools-Site-Checks) -- the link, freshness, diagram and accessibility checks over a built site. @@ -115,7 +115,7 @@ A local pass of [`check_a11y.mjs`](Tools-Site-Checks#check-a11y) does not predic test.bat -The tests the toolchain has to pass. Thirty-three steps, each stopping the run if it fails: +The tests the toolchain has to pass. Thirty-four steps, each stopping the run if it fails: 1. [`scripts/check_publish_policy.mjs`](Tools-Toolchain-Tests#check-publish-policy) --- verifies the publish allowlist still refuses the types it should. Needs neither a browser nor a built tree. 2. [`scripts/check_gate_lists.mjs`](Tools-Toolchain-Tests#check-gate-lists) --- verifies the two gate lists on this page still match the wrappers that run them. @@ -136,20 +136,21 @@ The tests the toolchain has to pass. Thirty-three steps, each stopping the run i 17. [`test/indexer.test.mjs`](Tools-Toolchain-Tests#indexer-test) --- unit tests for the package indexer: the VB6 preprocessing, the files of a package, the `api.json` built from them (sorted by code unit, nested types by their path, values and fields in declaration order, the same bytes from the same files) and the differ that compares two of them. 18. [`test/ide-js.test.mjs`](Tools-Toolchain-Tests#ide-js-test) --- unit tests for [`ide_js.mjs`](Tools-Defects#ide-js), which reads, names and patches the IDE's minified `main.js`: the byte-exact round trip, how a name carries to another build, and a fix patched in as the smallest edit, on a few lines written in the test. 19. [`test/discover.test.mjs`](Tools-Toolchain-Tests#discover-test) --- unit tests for the source tree's inventory, which the build reads in pieces on its lanes: the same in any number of pieces, on a small tree of the tests' own. -20. [`scripts/check_regex_safety.mjs`](Tools-Toolchain-Tests#check-regex-safety) --- refuses a regex that can backtrack exponentially, written as a literal or built from constants. -21. [`scripts/check_code_regions.mjs`](Tools-Toolchain-Tests#check-code-regions) --- verifies no pre-render rewrite alters the contents of a code fence or code span, that the rewrites over rendered HTML leave a raw `
` or `` alone, and that `lib/markdown.mjs` and `lib/frontmatter.mjs` pass their probes.
-22. [`scripts/check_page_baseline.mjs`](Tools-Toolchain-Tests#check-page-baseline) --- verifies the page-count drift guard still refuses a fall.
-23. [`scripts/check_book_coverage.mjs`](Tools-Toolchain-Tests#check-book-coverage) --- verifies the build still warns about a page `docs/_book.yml` does not mention.
-24. [`scripts/check_package_tests.mjs`](Tools-Toolchain-Tests#check-package-tests) --- verifies every NOTE and WARNING of a contributed package's section names the test cases behind it, and that each package test project is in order.
-25. [`scripts/check_callout_evidence.mjs`](Tools-Toolchain-Tests#check-callout-evidence) --- verifies every callout labelled with a twinBASIC build names what checks it, and that every marker names a reproducer, lane, sample, error data file or LLVM probe mode that exists.
-26. [`scripts/check_errors.mjs`](Tools-Toolchain-Tests#check-errors) --- verifies every page's Common Errors section is what the run-time error data under `errors/` writes, and that the data is in order.
-27. [`scripts/check_symbol_index.mjs`](Tools-Toolchain-Tests#check-symbol-index) --- verifies the symbol index still places each kind of symbol, and its drift guard still refuses a lost URL.
-28. [`scripts/check_twin_parsers.mjs`](Tools-Toolchain-Tests#check-twin-parsers) --- verifies the scanners of twinBASIC source and of the attribute reference still read the shapes each once misread.
-29. [`scripts/check_attribute_sweep.mjs`](Tools-Toolchain-Tests#check-attribute-sweep) --- verifies the logic of the attribute sweep: its site skeletons, how it reads a probe's diagnostics, how it batches probes, and how it compares the answers with `Attributes.md`.
-30. [`scripts/check_cli.mjs`](Tools-Toolchain-Tests#check-cli) --- verifies `lib/cli.mjs`, the command-line parser, and each tool's recorded command-line errors.
-31. [`scripts/check_pdf_shims_equiv.mjs`](Tools-Toolchain-Tests#check-pdf-shims-equiv) --- verifies the book's pdf-lib shims write what stock pdf-lib writes, patch the members of pdf-lib it lists, have each of them in their shim's table of targets, and run.
-32. [`scripts/check_impexp_parity.mjs`](Tools-Toolchain-Tests#check-impexp-parity) --- verifies the editions of the impexp tool pass the same built-in tests, and exit, print and write the same for one sequence of commands. Without Python it reports itself skipped and passes, except in CI. It compares the twinBASIC edition too, when `IMPEXP_EXE` names its built exe.
-33. [`scripts/check_axe_patch_equiv.mjs`](Tools-Toolchain-Tests#check-axe-patch-equiv) --- verifies the vendored axe source patch still produces identical colour values.
+20. [`test/build-speed.test.mjs`](Tools-Toolchain-Tests#build-speed-test) --- unit tests for the modules of [`build_speed.mjs`](Tools-Build#build-speed) that read the build's Gantt chart and a CPU profile: a chart drawn with the build's writer is read back to the same times.
+21. [`scripts/check_regex_safety.mjs`](Tools-Toolchain-Tests#check-regex-safety) --- refuses a regex that can backtrack exponentially, written as a literal or built from constants.
+22. [`scripts/check_code_regions.mjs`](Tools-Toolchain-Tests#check-code-regions) --- verifies no pre-render rewrite alters the contents of a code fence or code span, that the rewrites over rendered HTML leave a raw `
` or `` alone, and that `lib/markdown.mjs` and `lib/frontmatter.mjs` pass their probes.
+23. [`scripts/check_page_baseline.mjs`](Tools-Toolchain-Tests#check-page-baseline) --- verifies the page-count drift guard still refuses a fall.
+24. [`scripts/check_book_coverage.mjs`](Tools-Toolchain-Tests#check-book-coverage) --- verifies the build still warns about a page `docs/_book.yml` does not mention.
+25. [`scripts/check_package_tests.mjs`](Tools-Toolchain-Tests#check-package-tests) --- verifies every NOTE and WARNING of a contributed package's section names the test cases behind it, and that each package test project is in order.
+26. [`scripts/check_callout_evidence.mjs`](Tools-Toolchain-Tests#check-callout-evidence) --- verifies every callout labelled with a twinBASIC build names what checks it, and that every marker names a reproducer, lane, sample, error data file or LLVM probe mode that exists.
+27. [`scripts/check_errors.mjs`](Tools-Toolchain-Tests#check-errors) --- verifies every page's Common Errors section is what the run-time error data under `errors/` writes, and that the data is in order.
+28. [`scripts/check_symbol_index.mjs`](Tools-Toolchain-Tests#check-symbol-index) --- verifies the symbol index still places each kind of symbol, and its drift guard still refuses a lost URL.
+29. [`scripts/check_twin_parsers.mjs`](Tools-Toolchain-Tests#check-twin-parsers) --- verifies the scanners of twinBASIC source and of the attribute reference still read the shapes each once misread.
+30. [`scripts/check_attribute_sweep.mjs`](Tools-Toolchain-Tests#check-attribute-sweep) --- verifies the logic of the attribute sweep: its site skeletons, how it reads a probe's diagnostics, how it batches probes, and how it compares the answers with `Attributes.md`.
+31. [`scripts/check_cli.mjs`](Tools-Toolchain-Tests#check-cli) --- verifies `lib/cli.mjs`, the command-line parser, and each tool's recorded command-line errors.
+32. [`scripts/check_pdf_shims_equiv.mjs`](Tools-Toolchain-Tests#check-pdf-shims-equiv) --- verifies the book's pdf-lib shims write what stock pdf-lib writes, patch the members of pdf-lib it lists, have each of them in their shim's table of targets, and run.
+33. [`scripts/check_impexp_parity.mjs`](Tools-Toolchain-Tests#check-impexp-parity) --- verifies the editions of the impexp tool pass the same built-in tests, and exit, print and write the same for one sequence of commands. Without Python it reports itself skipped and passes, except in CI. It compares the twinBASIC edition too, when `IMPEXP_EXE` names its built exe.
+34. [`scripts/check_axe_patch_equiv.mjs`](Tools-Toolchain-Tests#check-axe-patch-equiv) --- verifies the vendored axe source patch still produces identical colour values.
 
 POSIX:
 
@@ -172,6 +173,7 @@ POSIX:
       && node --test test/indexer.test.mjs \
       && node --test test/ide-js.test.mjs \
       && node --test test/discover.test.mjs \
+      && node --test test/build-speed.test.mjs \
       && node scripts/check_regex_safety.mjs \
       && node scripts/check_code_regions.mjs \
       && node scripts/check_page_baseline.mjs \
diff --git a/lib/help-archive.mjs b/lib/help-archive.mjs
index 205c6286..f2a90691 100644
--- a/lib/help-archive.mjs
+++ b/lib/help-archive.mjs
@@ -22,8 +22,9 @@
 //     sizes are in the local header and in the central directory;
 //   - no zip64: more than 65,535 entries, or 4 GB, is refused;
 //   - method 0 (stored) for files that are compressed already, method 8 (raw
-//     deflate, level 9) for the rest, unless the deflated data is not smaller than
-//     the file, in which case it is stored.
+//     deflate) for the rest, unless the deflated data is not smaller than the
+//     file, in which case it is stored. A file deflated whole is at level 9; one
+//     deflated in pieces (PIECE_BYTES) is at level 6.
 //
 // lib/zip.mjs deflates everything and is shared with other tools, so this
 // writes its own.
@@ -85,6 +86,13 @@ const STORED_EXTENSIONS = new Set([
 // A file deflated whole is at most this big; a larger one is deflated in pieces
 // of this size. The archive's bytes depend on it: changing it changes them.
 export const PIECE_BYTES = 1 << 20;
+// The deflate level of a file deflated whole, and of a piece. A file in pieces is
+// a large one, in practice the offline search index (55 MB), the last file the
+// build writes: its deflating is on the way to the build's end, and level 6
+// takes under a third of level 9's time for an entry 1.7% larger. The archive's
+// bytes depend on both.
+const WHOLE_LEVEL = 9;
+const PIECE_LEVEL = 6;
 // What a piece is primed with: deflate's whole window.
 const WINDOW = 32768;
 
@@ -223,7 +231,7 @@ export function deflateUnit(root, unit) {
     let method = 0;
     let body = data;
     if (!isStoredType(unit.name) && data.length > 0) {
-      const deflated = deflateRawSync(data, { level: 9 });
+      const deflated = deflateRawSync(data, { level: WHOLE_LEVEL });
       if (deflated.length < data.length) {
         if (!inflateRawSync(deflated).equals(data)) {
           throw new Error(`${unit.name}: the deflated data does not inflate to the file`);
@@ -245,7 +253,7 @@ export function deflateUnit(root, unit) {
   const last = index === count - 1;
   if (last && fstatSize(file) !== unit.size) throw new Error(`${unit.name} changed size while the archive was made`);
   const flush = last ? constants.Z_FINISH : constants.Z_SYNC_FLUSH;
-  const body = deflateRawSync(data, { level: 9, finishFlush: flush, ...(dictionary && { dictionary }) });
+  const body = deflateRawSync(data, { level: PIECE_LEVEL, finishFlush: flush, ...(dictionary && { dictionary }) });
   const back = inflateRawSync(body, {
     finishFlush: constants.Z_SYNC_FLUSH,
     ...(dictionary && { dictionary }),
diff --git a/scripts/build-speed/chart.mjs b/scripts/build-speed/chart.mjs
new file mode 100644
index 00000000..d0f92dcf
--- /dev/null
+++ b/scripts/build-speed/chart.mjs
@@ -0,0 +1,75 @@
+// Reads a build's times back from its Gantt chart (builder/gantt.mjs's SVG):
+// the build writes no timings file, and the chart holds every task's bar.
+//
+// readChart(svg) returns, in seconds from the build's start:
+//   env     the start of the first renderEnvInit bar: a lane may render from here
+//   render  { start, end }: the first render bar's start and the last one's end
+//   end     the end of the last bar of the chart
+//   task(name)  { start, end } of a labelled bar, or null. Every main-thread
+//               task has a label; a lane task has one only where its bar is
+//               wide enough, so a name here is a main-thread task's.
+//
+// The reading rests on three things the chart's writer does, which
+// test/build-speed.test.mjs holds it to: an axis tick is a 
+// whose content is its time, a bar is a  with x and width, and a labelled
+// bar's  follows its  within three lines.
+
+const TICK = /]*class="ga"[^>]*>([\d.]+)<\/text>/g;
+const BAR = / ({ x: Number(m[1]), t: Number(m[2]) }));
+  if (ticks.length < 2) throw new Error("not a build's Gantt chart: fewer than two axis ticks");
+  // Any two ticks give the scale: a long build has none at one second.
+  const first = ticks[0];
+  const last = ticks.at(-1);
+  const perSecond = (last.x - first.x) / (last.t - first.t);
+  const x0 = first.x - first.t * perSecond;
+  const seconds = (x) => (x - x0) / perSecond;
+  const span = (m) => ({ start: seconds(Number(m[1])), end: seconds(Number(m[1]) + Number(m[2])) });
+
+  const ofClass = (cls) => {
+    const re = new RegExp(`]*class="${cls}"`, "g");
+    return [...svg.matchAll(re)].map(span);
+  };
+  const starts = (list) => (list.length ? Math.min(...list.map((b) => b.start)) : null);
+  const ends = (list) => (list.length ? Math.max(...list.map((b) => b.end)) : null);
+  const render = ofClass("gb-render");
+  const lines = svg.split("\n");
+
+  return {
+    env: starts(ofClass("gb-env")),
+    render: { start: starts(render), end: ends(render) },
+    end: ends([...svg.matchAll(BARS)].map(span)),
+    task(name) {
+      const at = lines.findIndex((l) => l.includes('class="gl"') && l.includes(`>${name}`));
+      for (let i = at - 1; at >= 0 && i >= 0 && i >= at - 3; i--) {
+        const m = BAR.exec(lines[i]);
+        if (m) return span(m);
+      }
+      return null;
+    },
+  };
+}
+
+const s = (n) => (n == null ? "?" : n.toFixed(2));
+
+/** One line for a chart: the first render, render's end, the chart's end and the named tasks. */
+export function chartLine(chart, tasks = []) {
+  const out = [`first render ${s(chart.render.start)}`, `render ends ${s(chart.render.end)}`, `ends ${s(chart.end)}`];
+  for (const name of tasks) {
+    const bar = chart.task(name);
+    out.push(bar ? `${name} ${s(bar.start)} to ${s(bar.end)}` : `${name} ?`);
+  }
+  return out.join("; ");
+}
+
+/** "a to b s" over a list of numbers, or the one value when they agree to the hundredth. */
+export function range(list) {
+  const known = list.filter((n) => n != null);
+  if (known.length === 0) return "?";
+  const lo = Math.min(...known).toFixed(2);
+  const hi = Math.max(...known).toFixed(2);
+  return lo === hi ? `${lo} s` : `${lo} to ${hi} s`;
+}
diff --git a/scripts/build-speed/parts.mjs b/scripts/build-speed/parts.mjs
new file mode 100644
index 00000000..7366b689
--- /dev/null
+++ b/scripts/build-speed/parts.mjs
@@ -0,0 +1,265 @@
+// One part of the build timed alone, on one thread: what `build_speed.mjs part
+// ` runs. Each part imports the modules of the tree it is given, so the
+// code of another checkout (a branch's worktree, an older commit's) is measured
+// by the same tool. A part that reads built files reads that tree's: build it
+// first.
+//
+// A part's time alone is not its time in a build, where it shares the machine
+// with every lane: measure both, and report both.
+
+import { readFileSync } from "node:fs";
+import path from "node:path";
+import { pathToFileURL } from "node:url";
+import { promisify } from "node:util";
+import zlib from "node:zlib";
+
+const OUTPUT_TREES = ["_site*/**", "_serve/**", "_pdf/**"];
+const ms = (t) => `${t.toFixed(0)} ms`;
+
+function context(tree) {
+  const imp = (rel) => import(pathToFileURL(path.join(tree, rel)).href);
+  return {
+    tree,
+    imp,
+    srcRoot: path.join(tree, "docs"),
+    searchData: () => JSON.parse(readFileSync(path.join(tree, "docs/_site/assets/js/search-data.json"), "utf8")),
+  };
+}
+
+// discover() warns about pages it leaves out; a timing run does not repeat them.
+async function quietly(fn) {
+  const warn = console.warn;
+  console.warn = () => {};
+  try {
+    return await fn();
+  } finally {
+    console.warn = warn;
+  }
+}
+
+// The first call, which the engine has not compiled yet, and the range of the rest.
+function time(label, fn, runs = 5) {
+  const ts = [];
+  let out;
+  for (let i = 0; i < runs; i++) {
+    const t = performance.now();
+    out = fn();
+    ts.push(performance.now() - t);
+  }
+  const rest = ts.slice(1);
+  const later = `${Math.min(...rest).toFixed(1)} to ${Math.max(...rest).toFixed(1)} ms`;
+  console.log(`${label.padEnd(34)} first ${ts[0].toFixed(1)} ms, then ${later}`);
+  return out;
+}
+
+// What markdownInit is made of (builder/tbdocs.mjs): the link tables, the
+// counts, the parser, and the scan for placeholders with the scans inside it.
+async function markdownInit({ imp, srcRoot }) {
+  const { discover } = await imp("builder/discover.mjs");
+  const { deriveCounts, checkPlaceholders, deriveDownloads, findCountRefs } = await imp("builder/counts.mjs");
+  const { buildLinkTables, createMarkdownIt, serializeLinkTables } = await imp("builder/render.mjs");
+  const { blockRegions, maskCode } = await imp("lib/markdown.mjs");
+  const { pages, staticFiles } = await quietly(() => discover(srcRoot, OUTPUT_TREES));
+  const state = { pages, staticFiles };
+  console.log(`${pages.length} pages, ${staticFiles.length} static files`);
+  const linkTables = time("buildLinkTables", () => buildLinkTables(pages));
+  const counts = time("deriveCounts", () => deriveCounts(state, { redirectStubs: 0 }));
+  const md = time("createMarkdownIt", () =>
+    createMarkdownIt({
+      highlighter: null,
+      linkTables,
+      baseurl: "",
+      staticFiles: new Set(staticFiles.map((f) => f.srcRel)),
+      counts,
+    }),
+  );
+  const downloads = deriveDownloads(state, {});
+  const withRef = pages.filter((p) => p.rawContent.includes("{{tbdocs:"));
+  const chars = withRef.reduce((n, p) => n + p.rawContent.length, 0);
+  console.log(`pages with a placeholder: ${withRef.length}, ${chars} characters`);
+  time("checkPlaceholders", () => checkPlaceholders(pages, counts, downloads, md));
+  time("  maskCode of those pages", () => withRef.map((p) => maskCode(p.rawContent.replace(/\r\n?/g, "\n"), { md })));
+  time("  blockRegions of those pages", () => withRef.map((p) => blockRegions(p.rawContent, { md })));
+  time("  findCountRefs of those pages", () => withRef.map((p) => findCountRefs(p.rawContent, md)));
+  time("serializeLinkTables", () => serializeLinkTables(linkTables));
+}
+
+// computeNav, each call on a fresh copy of the pages: it writes to them.
+async function nav({ imp, srcRoot }) {
+  const { discover } = await imp("builder/discover.mjs");
+  const { computeNav } = await imp("builder/nav.mjs");
+  const { pages } = await quietly(() => discover(srcRoot, OUTPUT_TREES));
+  const count = (nodes) => nodes.reduce((n, node) => n + 1 + count(node.children), 0);
+  let tree;
+  const ts = [];
+  for (let i = 0; i < 6; i++) {
+    const copy = pages.map((p) => ({ ...p }));
+    const t = performance.now();
+    tree = computeNav(copy, {}).navTree;
+    ts.push(performance.now() - t);
+  }
+  console.log(`${pages.length} pages, ${count(tree)} nav nodes`);
+  console.log(`computeNav: ${ts.map((t) => t.toFixed(1)).join(", ")} ms`);
+}
+
+// The index's add step, one slice after another, against the slice count: its
+// CPU in all, and how long the longest slice holds a lane.
+async function indexSlices(ctx) {
+  const si = await ctx.imp("builder/search-index.mjs");
+  const docs = ctx.searchData();
+  const lunr = si.loadSearchLunr();
+  for (const k of [1, 2, 4, 8, 16, 32]) {
+    const times = [];
+    let terms = 0;
+    for (const p of si.planIndexSlices(lunr, docs, k)) {
+      const t = performance.now();
+      const { added } = si.addSlice(lunr, p.docs, p.twins);
+      times.push(performance.now() - t);
+      terms += added.terms.length;
+    }
+    const sum = times.reduce((a, b) => a + b, 0);
+    const slices = `${String(k).padStart(2)} slices`;
+    console.log(
+      `${slices}: ${ms(sum)} in all, longest ${ms(Math.max(...times))}, shortest ${ms(Math.min(...times))}, ${terms} terms held`,
+    );
+  }
+}
+
+// The add step split: making the entries, tokenizing and stemming the content,
+// lunr's Builder.add, and the postings written as JSON.
+async function indexAdd(ctx) {
+  const si = await ctx.imp("builder/search-index.mjs");
+  const docs = ctx.searchData();
+  const lunr = si.loadSearchLunr();
+  const ids = Object.keys(docs);
+  const twins = si.stemTwins(lunr, docs);
+  let t0 = performance.now();
+  const lap = (label) => {
+    const t = performance.now();
+    console.log(`${label.padEnd(44)} ${ms(t - t0).padStart(8)}`);
+    t0 = t;
+  };
+  const entries = ids.map((id) => si.entryFor(lunr, docs, id, twins));
+  lap(`entryFor (${ids.length} entries)`);
+  let tokens = 0;
+  const pipeline = si.newBuilder(lunr).pipeline;
+  for (const e of entries) tokens += pipeline.run(lunr.tokenizer(e.content, { fields: ["content"] })).length;
+  lap(`content tokenized and stemmed (${tokens} tokens)`);
+  const builder = si.newBuilder(lunr);
+  for (const e of entries) builder.add(e);
+  lap("Builder.add");
+  const fields = Object.keys(builder._fields);
+  let bytes = 0;
+  for (const term in builder.invertedIndex) {
+    const posting = builder.invertedIndex[term];
+    for (const f of fields) bytes += JSON.stringify(posting[f]).length;
+  }
+  lap(`postings as JSON (${bytes} characters)`);
+}
+
+// What follows the adds: the merge, the inverted index's JSON, the vectors of
+// every slice, the file's assembly and the offline copy's escaping.
+async function indexTerms(ctx) {
+  const si = await ctx.imp("builder/search-index.mjs");
+  const docs = ctx.searchData();
+  const lunr = si.loadSearchLunr();
+  for (const k of [2, 8, 16]) {
+    const lanes = si.planIndexSlices(lunr, docs, k).map((p) => si.addSlice(lunr, p.docs, p.twins));
+    const laps = [];
+    let t = performance.now();
+    const lap = (label) => {
+      laps.push(`${label} ${ms(performance.now() - t)}`);
+      t = performance.now();
+    };
+    const { merged, totals } = si.mergeSlices(lanes.map((l) => l.added));
+    lap("merge");
+    const json = si.invertedIndexJson(merged);
+    lap("terms");
+    const vectors = lanes.map((l, i) => si.sliceVectors(lunr, l.state, { ...totals, numbers: totals.numbers[i] }));
+    lap("vectors (every slice)");
+    const text = si.searchIndexFile(si.assembleIndexJson(lunr, vectors, json), docs);
+    lap("assembly");
+    si.offlineSearchIndexJs(text);
+    lap("offline copy");
+    console.log(`${String(k).padStart(2)} slices: ${laps.join(", ")}`);
+  }
+}
+
+// A file deflated as one stream and as pieces joined into one stream (pigz's
+// method, lib/help-archive.mjs), by level, piece size and whether a piece is
+// primed with the 32 KB before it. The pieces run on Node's thread pool here,
+// four at a time, where the build runs them on its lanes.
+async function deflate(ctx, { file }) {
+  const data = readFileSync(file ?? path.join(ctx.tree, "docs/_site-offline/assets/js/search-index.js"));
+  const deflateRaw = promisify(zlib.deflateRaw);
+  const WINDOW = 32768;
+  const pieces = async (size, primed, level) => {
+    const parts = [];
+    for (let at = 0; at < data.length; at += size) {
+      const last = at + size >= data.length;
+      const opts = { level, finishFlush: last ? zlib.constants.Z_FINISH : zlib.constants.Z_SYNC_FLUSH };
+      if (primed && at > 0) opts.dictionary = data.subarray(Math.max(0, at - WINDOW), at);
+      parts.push(deflateRaw(data.subarray(at, at + size), opts));
+    }
+    return Buffer.concat(await Promise.all(parts));
+  };
+  let t = performance.now();
+  const whole = zlib.deflateRawSync(data, { level: 9 });
+  console.log(`${data.length} bytes`);
+  console.log(`one stream, level 9          ${ms(performance.now() - t).padStart(8)}  ${whole.length}`);
+  for (const level of [9, 6]) {
+    for (const size of [256 << 10, 1 << 20, 4 << 20]) {
+      for (const primed of [false, true]) {
+        t = performance.now();
+        const z = await pieces(size, primed, level);
+        const took = ms(performance.now() - t).padStart(8);
+        const pct = `${((z.length / whole.length - 1) * 100).toFixed(2)}%`.padStart(7);
+        const ok = zlib.inflateRawSync(z).equals(data) ? "inflates" : "DOES NOT INFLATE";
+        const what = `level ${level}, ${String(size >> 10).padStart(4)} KB, ${primed ? "primed    " : "not primed"}`;
+        console.log(`${what} ${took}  ${z.length} ${pct}  ${ok}`);
+      }
+    }
+  }
+}
+
+// The help archive's deflating on one thread, whole files and pieces apart, and
+// the end-of-build recheck of the archive the tree's last build wrote.
+async function archive(ctx) {
+  const { helpArchiveSkips } = await ctx.imp("builder/help-archive-step.mjs");
+  const lib = await ctx.imp("lib/help-archive.mjs");
+  const root = path.join(ctx.tree, "docs/_site-offline");
+  const units = lib.planUnits(lib.listFiles(root, helpArchiveSkips));
+  for (const [what, list] of [
+    ["whole files", units.filter((u) => !u.piece)],
+    ["pieces of large files", units.filter((u) => u.piece)],
+  ]) {
+    const t = performance.now();
+    let bytes = 0;
+    for (const u of list) bytes += lib.deflateUnit(root, u).body.length;
+    console.log(
+      `${what}: ${list.length} units, ${ms(performance.now() - t)}, ${(bytes / 1048576).toFixed(1)} MB in the archive`,
+    );
+  }
+  const t = performance.now();
+  const problems = await lib.checkHelpArchive({
+    src: root,
+    zip: path.join(ctx.tree, "add-in/Resources/HELP/site.zip"),
+    mayDiffer: ["BuildInfo.html", "assets/images/gantt.svg"],
+    skip: helpArchiveSkips,
+  });
+  console.log(`the recheck of site.zip: ${ms(performance.now() - t)}, ${problems.length} problems`);
+}
+
+export const PARTS = {
+  "markdown-init": { run: markdownInit, about: "what markdownInit is made of, each piece five times" },
+  nav: { run: nav, about: "computeNav, six calls on fresh copies of the pages" },
+  "index-slices": { run: indexSlices, about: "the index's add step against the slice count (needs a built tree)" },
+  "index-add": { run: indexAdd, about: "the add step split into its costs (needs a built tree)" },
+  "index-terms": { run: indexTerms, about: "the merge, the terms, the vectors and the assembly (needs a built tree)" },
+  deflate: { run: deflate, about: "a file as one deflate stream and as pieces; --file, else the offline search index" },
+  archive: { run: archive, about: "the help archive's deflating on one thread, and its recheck (needs a built tree)" },
+};
+
+export async function runPart(name, tree, options = {}) {
+  await PARTS[name].run(context(tree), options);
+}
diff --git a/scripts/build-speed/profile.mjs b/scripts/build-speed/profile.mjs
new file mode 100644
index 00000000..bf0cb259
--- /dev/null
+++ b/scripts/build-speed/profile.mjs
@@ -0,0 +1,70 @@
+// The inclusive time of named functions in a V8 CPU profile (node --cpu-prof),
+// each with what it calls, as a tree.
+//
+// A profile's samples name the innermost frame; a sample counts under the
+// outermost frame on its stack that has one of the names, so a function that
+// calls itself is counted once. Times are in microseconds, as the profile's.
+
+import path from "node:path";
+
+const label = (node) => {
+  const f = node.callFrame;
+  const where = f.url ? `${path.basename(f.url)}:${f.lineNumber + 1}` : "";
+  return `${f.functionName || "(anonymous)"} ${where}`.trim();
+};
+
+/**
+ * @param {object} profile  the parsed .cpuprofile
+ * @param {string[]} names  function names to total
+ * @param {number} depth    how many levels of callees to keep under each
+ * @returns {Map} by name, in `names` order; a
+ *   name no sample is under is absent
+ */
+export function profileTrees(profile, names, depth = 3) {
+  const byId = new Map(profile.nodes.map((n) => [n.id, n]));
+  const parent = new Map();
+  for (const n of profile.nodes) for (const c of n.children ?? []) parent.set(c, n.id);
+  const self = new Map();
+  for (let i = 0; i < profile.samples.length; i++) {
+    const id = profile.samples[i];
+    self.set(id, (self.get(id) ?? 0) + (profile.timeDeltas[i] ?? 0));
+  }
+  const wanted = new Set(names);
+  const found = new Map();
+  for (const [id, t] of self) {
+    const stack = [];
+    for (let at = id; at != null; at = parent.get(at)) stack.push(byId.get(at));
+    stack.reverse();
+    const k = stack.findIndex((n) => wanted.has(n.callFrame.functionName));
+    if (k < 0) continue;
+    const name = stack[k].callFrame.functionName;
+    let node = found.get(name);
+    if (!node) found.set(name, (node = { t: 0, kids: new Map() }));
+    node.t += t;
+    for (let d = k + 1; d < stack.length && d - k <= depth; d++) {
+      const l = label(stack[d]);
+      let kid = node.kids.get(l);
+      if (!kid) node.kids.set(l, (kid = { t: 0, kids: new Map() }));
+      kid.t += t;
+      node = kid;
+    }
+  }
+  const trees = new Map();
+  for (const name of names) if (found.has(name)) trees.set(name, found.get(name));
+  return trees;
+}
+
+/** The trees as lines, callees by time; a callee under `floorMs` is left out. */
+export function formatTrees(trees, names, floorMs = 1.5) {
+  const lines = [];
+  const print = (name, node, indent) => {
+    if (indent && node.t < floorMs * 1000) return;
+    lines.push(`${"  ".repeat(indent)}${(node.t / 1000).toFixed(1).padStart(7)} ms  ${name}`);
+    for (const [l, kid] of [...node.kids].sort((a, b) => b[1].t - a[1].t)) print(l, kid, indent + 1);
+  };
+  for (const name of names) {
+    if (trees.has(name)) print(name, trees.get(name), 0);
+    else lines.push(`      ?      ${name}: no sample is under a function of this name`);
+  }
+  return lines;
+}
diff --git a/scripts/build_speed.mjs b/scripts/build_speed.mjs
new file mode 100644
index 00000000..94654ab9
--- /dev/null
+++ b/scripts/build_speed.mjs
@@ -0,0 +1,369 @@
+#!/usr/bin/env node
+// Measures the build: how long tbdocs takes, where in the build the time is,
+// and what one part of it costs alone. For work on the build's speed
+// (WIP.BuildSpeed.md); it is not a gate, and nothing runs it.
+//
+//   node scripts/build_speed.mjs bench [--tree ]... [--runs ] [--cpus all,4] [--task a,b] [--out ]
+//   node scripts/build_speed.mjs serve [--tree ]... [--builds ] [--task a,b] [--out ]
+//   node scripts/build_speed.mjs times ... [--task a,b]
+//   node scripts/build_speed.mjs png ...
+//   node scripts/build_speed.mjs profile  --fn  [--depth ]
+//   node scripts/build_speed.mjs part  [--tree ] [--file ]
+//
+// bench builds each tree as build.bat does, in turn, --runs times: on every CPU
+// and on the first four, which is the nearest thing this machine has to a CI
+// runner. serve builds each tree several times on one pool of lanes, as
+// `tbdocs --serve` rebuilds: the first build is cold, the rest are rebuilds.
+// Both keep each build's Gantt chart (and bench its log) under --out, print one
+// line for each build, and end with the range of each figure over the runs: one
+// build's total says little on a machine that is doing other things.
+//
+// A tree is a checkout: this one by default, and a second --tree is how a branch
+// is compared with its base (the main checkout while a worktree is ahead of it,
+// or a detached worktree of the commit, given a node_modules junction). The
+// trees are built in turn within each run, so that what else the machine is
+// doing falls on both. bench builds a tree in place, as build.bat would.
+//
+// The times come from the chart (scripts/build-speed/chart.mjs): the build
+// writes no timings file. `times` reads charts kept from earlier runs, and
+// `png` renders them to PNG files beside them, to look at.
+//
+// profile gives the inclusive time of named functions in a profile taken with
+//   node --cpu-prof --cpu-prof-interval 100 builder/tbdocs.mjs --src docs
+// where the main thread's file is the one whose name ends .0.001.cpuprofile. A
+// profile inflates code that runs once; for the parts of one task, marks
+// printed to stderr are the better tool.
+//
+// part times one part of the build alone on one thread, with the modules of
+// the tree it is given (scripts/build-speed/parts.mjs).
+//
+// Exit codes: 0 done; 1 a build failed; 2 a refused command line, or a crash.
+
+import { spawnSync } from "node:child_process";
+import { closeSync, copyFileSync, existsSync, mkdirSync, openSync, readFileSync, rmSync, statSync } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { fileURLToPath, pathToFileURL } from "node:url";
+import { CliError, exitOnCrash, numberOption, parseCli, printHelpAndExit, withUsageError } from "../lib/cli.mjs";
+import { chartLine, range, readChart } from "./build-speed/chart.mjs";
+import { PARTS, runPart } from "./build-speed/parts.mjs";
+import { formatTrees, profileTrees } from "./build-speed/profile.mjs";
+
+exitOnCrash();
+
+const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
+const BUILD_ARGS = ["builder/tbdocs.mjs", "--src", "docs", "--check-audit-index"];
+const CHART_REL = "assets/images/gantt.svg";
+
+const USAGE = `usage: node scripts/build_speed.mjs  [options]
+
+  bench    build each tree --runs times, on every CPU and on four; keep each log and chart
+             [--tree ]... [--runs ] [--cpus all,4] [--task a,b] [--out ]
+  serve    build each tree --builds times on one pool, as tbdocs --serve rebuilds
+             [--tree ]... [--builds ] [--task a,b] [--out ]
+  times    the times in charts kept from earlier runs
+             ... [--task a,b]
+  png      render charts to PNG files beside them
+             ...
+  profile  the inclusive time of named functions in a node --cpu-prof profile
+              --fn  [--depth ]
+  part     one part of the build alone on one thread
+              [--tree ] [--file ]
+
+  --tree    a checkout to measure (default: this one); repeat it to compare checkouts
+  --runs      builds of each tree at each CPU count (default 3)
+  --cpus   CPU counts to build on, "all" or a number (default all,4)
+  --builds    builds on the pool, the first of them cold (default 5)
+  --task   main-thread tasks whose times to report as well
+  --out     where logs and charts are kept (default .build-speed/ in this checkout)
+  --fn     function names to total in the profile
+  --depth     levels of callees under each (default 3)
+  --file   the file \`part deflate\` deflates
+  -h, --help     this text
+
+parts:
+${Object.entries(PARTS)
+  .map(([name, p]) => `  ${name.padEnd(14)} ${p.about}`)
+  .join("\n")}
+`;
+
+const usageError = (message) => {
+  throw new CliError("usage", message);
+};
+
+const { values, positionals } = withUsageError(
+  () => {
+    const cli = parseCli(process.argv.slice(2), {
+      options: {
+        tree: { type: "string", multiple: true },
+        runs: { type: "string" },
+        cpus: { type: "string" },
+        builds: { type: "string" },
+        task: { type: "string" },
+        out: { type: "string" },
+        fn: { type: "string" },
+        depth: { type: "string" },
+        file: { type: "string" },
+        help: { type: "boolean", short: "h" },
+      },
+      positionals: { min: 0, max: Infinity },
+      stopAt: ["help"],
+    });
+    if (cli.stopped === "help") printHelpAndExit(USAGE);
+    return cli;
+  },
+  { format: (err) => `build_speed: ${err.message}\n\n${USAGE}` },
+);
+
+const list = (text) => (text ? text.split(",").filter(Boolean) : []);
+const [command, ...args] = positionals;
+const tasks = list(values.task);
+
+// The trees to measure, each with a label for its files: its folder's name, and
+// the position as well when two trees have the same one.
+function trees() {
+  const dirs = (values.tree.length ? values.tree : [ROOT]).map((dir) => path.resolve(dir));
+  for (const dir of dirs) {
+    if (!existsSync(path.join(dir, "builder", "tbdocs.mjs"))) usageError(`--tree ${dir}: no builder/tbdocs.mjs there`);
+  }
+  const names = dirs.map((dir) => path.basename(dir));
+  return dirs.map((dir, i) => ({
+    dir,
+    label: names.indexOf(names[i]) === names.lastIndexOf(names[i]) ? names[i] : `${names[i]}-${i + 1}`,
+  }));
+}
+
+function outDir() {
+  const out = path.resolve(values.out ?? path.join(ROOT, ".build-speed"));
+  mkdirSync(out, { recursive: true });
+  return out;
+}
+
+// One build of a tree in a process of its own, on every CPU or on the first
+// `cpus` of them, its output in `log`. On Windows the CPUs are given with
+// `start /affinity`, which Node's availableParallelism follows; elsewhere with
+// taskset. `start` does not pass the build's exit code on, so whether the build
+// succeeded is read from the chart: a build writes it last.
+function buildOnce(tree, cpus, log) {
+  const started = Date.now();
+  let status;
+  if (cpus === "all") {
+    const fd = openSync(log, "w");
+    try {
+      status = spawnSync(process.execPath, BUILD_ARGS, { cwd: tree.dir, stdio: ["ignore", fd, fd] }).status;
+    } finally {
+      closeSync(fd);
+    }
+  } else if (process.platform === "win32") {
+    const mask = ((1n << BigInt(cpus)) - 1n).toString(16);
+    const line = `start "" /affinity ${mask} /b /wait "${process.execPath}" ${BUILD_ARGS.join(" ")} > "${log}" 2>&1`;
+    spawnSync("cmd.exe", ["/d", "/s", "/c", `"${line}"`], { cwd: tree.dir, windowsVerbatimArguments: true });
+    status = null;
+  } else {
+    const fd = openSync(log, "w");
+    try {
+      status = spawnSync("taskset", ["-c", `0-${cpus - 1}`, process.execPath, ...BUILD_ARGS], {
+        cwd: tree.dir,
+        stdio: ["ignore", fd, fd],
+      }).status;
+    } finally {
+      closeSync(fd);
+    }
+  }
+  const chart = path.join(tree.dir, "docs", "_site", CHART_REL);
+  const fresh = existsSync(chart) && statSync(chart).mtimeMs >= started - 1000;
+  const done = /Done in (\d+)ms/.exec(existsSync(log) ? readFileSync(log, "utf8") : "");
+  return { ok: fresh && (status === null || status === 0), chart, seconds: done ? Number(done[1]) / 1000 : null };
+}
+
+// The figures of one build, from its chart: null where the chart has none.
+function figures(svg) {
+  const chart = readChart(svg);
+  const row = { firstRender: chart.render.start, renderEnds: chart.render.end, ends: chart.end, tasks: {} };
+  for (const name of tasks) {
+    const bar = chart.task(name);
+    row.tasks[name] = bar ? bar.end - bar.start : null;
+  }
+  return { chart, row };
+}
+
+function summary(title, rows) {
+  const good = rows.filter((r) => r.ok);
+  const parts = [
+    `first render ${range(good.map((r) => r.firstRender))}`,
+    `render ends ${range(good.map((r) => r.renderEnds))}`,
+    `build ends ${range(good.map((r) => r.ends))}`,
+    ...tasks.map((name) => `${name} takes ${range(good.map((r) => r.tasks[name]))}`),
+  ];
+  const failed = rows.length - good.length;
+  console.log(`${title}: ${parts.join("; ")}${failed ? `; ${failed} of ${rows.length} builds FAILED` : ""}`);
+}
+
+function bench() {
+  const runs = numberOption(values.runs ?? "3", { option: "--runs", integer: true, min: 1 });
+  const counts = list(values.cpus ?? "all,4").map((c) =>
+    c === "all" ? c : numberOption(c, { option: "--cpus", integer: true, min: 1, max: os.availableParallelism() }),
+  );
+  if (counts.length === 0) usageError("--cpus names no CPU count");
+  const all = trees();
+  const out = outDir();
+  const rows = [];
+  for (let run = 1; run <= runs; run++) {
+    for (const tree of all) {
+      for (const cpus of counts) {
+        const stem = `${tree.label}-${cpus === "all" ? "all" : `${cpus}cpu`}-${run}`;
+        const built = buildOnce(tree, cpus, path.join(out, `build-${stem}.log`));
+        let row = { tree, cpus, ok: built.ok };
+        let line = "FAILED: see its log";
+        if (built.ok) {
+          copyFileSync(built.chart, path.join(out, `gantt-${stem}.svg`));
+          const read = figures(readFileSync(built.chart, "utf8"));
+          // The build's own "Done in" is the whole of it; the chart ends a little earlier.
+          row = { ...row, ...read.row, ends: built.seconds ?? read.row.ends };
+          line = `${chartLine(read.chart, tasks)}; done in ${row.ends.toFixed(2)}`;
+        }
+        rows.push(row);
+        console.log(`${stem}: ${line}`);
+      }
+    }
+  }
+  console.log("");
+  for (const tree of all) {
+    for (const cpus of counts) {
+      const title = `${tree.label}, ${cpus === "all" ? "every CPU" : `${cpus} CPUs`}`;
+      summary(
+        title,
+        rows.filter((r) => r.tree === tree && r.cpus === cpus),
+      );
+    }
+  }
+  console.log(`logs and charts: ${out}`);
+  return rows.every((r) => r.ok);
+}
+
+async function serve() {
+  const builds = numberOption(values.builds ?? "5", { option: "--builds", integer: true, min: 2 });
+  const all = trees();
+  const out = outDir();
+  let ok = true;
+  const lines = [];
+  for (const tree of all) {
+    const { runBuild, createWorkerPool } = await import(pathToFileURL(path.join(tree.dir, "builder/tbdocs.mjs")).href);
+    const scratch = path.join(tree.dir, ".build-speed", "serve");
+    const dest = path.join(scratch, "_serve");
+    const pool = createWorkerPool();
+    const log = console.log;
+    const rows = [];
+    try {
+      for (let n = 1; n <= builds; n++) {
+        process.exitCode = 0;
+        console.log = () => {};
+        const t = Date.now();
+        try {
+          await runBuild({
+            src: path.join(tree.dir, "docs"),
+            dest,
+            serve: true,
+            skipOffline: true,
+            skipPdf: true,
+            pool,
+          });
+        } finally {
+          console.log = log;
+        }
+        const seconds = (Date.now() - t) / 1000;
+        const stem = `${tree.label}-serve-${n}`;
+        const built = process.exitCode === 0 && existsSync(path.join(dest, CHART_REL));
+        let row = { ok: built };
+        let line = "FAILED";
+        if (built) {
+          copyFileSync(path.join(dest, CHART_REL), path.join(out, `gantt-${stem}.svg`));
+          const read = figures(readFileSync(path.join(dest, CHART_REL), "utf8"));
+          row = { ...row, ...read.row, ends: seconds };
+          line = `${chartLine(read.chart, tasks)}; done in ${seconds.toFixed(2)}`;
+        }
+        ok &&= built;
+        rows.push(row);
+        log(`${stem}${n === 1 ? " (cold)" : ""}: ${line}`);
+      }
+    } finally {
+      await pool.destroy();
+      rmSync(scratch, { recursive: true, force: true });
+    }
+    lines.push([`${tree.label}, rebuilds`, rows.slice(1)]);
+  }
+  console.log("");
+  for (const [title, rows] of lines) summary(title, rows);
+  console.log(`charts: ${out}`);
+  process.exitCode = 0;
+  return ok;
+}
+
+function times() {
+  if (args.length === 0) usageError("times: name at least one chart");
+  for (const file of args)
+    console.log(`${path.basename(file)}: ${chartLine(readChart(readFileSync(file, "utf8")), tasks)}`);
+  return true;
+}
+
+async function png() {
+  if (args.length === 0) usageError("png: name at least one chart");
+  const { default: puppeteer } = await import("puppeteer");
+  const browser = await puppeteer.launch();
+  try {
+    const page = await browser.newPage();
+    for (const file of args) {
+      const svg = readFileSync(file, "utf8");
+      const width = Number(/width="(\d+)"/.exec(svg)?.[1]);
+      const height = Number(/height="(\d+)"/.exec(svg)?.[1]);
+      if (!width || !height) throw new Error(`${file}: no width and height on its `);
+      await page.setViewport({ width, height, deviceScaleFactor: 1.5 });
+      await page.setContent(`${svg}`);
+      const out = file.replace(/\.svg$/i, "") + ".png";
+      await page.screenshot({ path: out });
+      console.log(out);
+    }
+  } finally {
+    await browser.close();
+  }
+  return true;
+}
+
+function profile() {
+  if (args.length !== 1) usageError("profile: name one .cpuprofile file");
+  const names = list(values.fn);
+  if (names.length === 0) usageError("profile: --fn names the functions to total");
+  const depth = numberOption(values.depth ?? "3", { option: "--depth", integer: true, min: 0 });
+  const trees = profileTrees(JSON.parse(readFileSync(args[0], "utf8")), names, depth);
+  for (const line of formatTrees(trees, names)) console.log(line);
+  return true;
+}
+
+async function part() {
+  const [name] = args;
+  if (args.length !== 1 || !Object.hasOwn(PARTS, name)) {
+    usageError(`part: name one of ${Object.keys(PARTS).join(", ")}`);
+  }
+  if (values.tree.length > 1) usageError("part: one --tree at a time");
+  await runPart(name, trees()[0].dir, { file: values.file });
+  return true;
+}
+
+const COMMANDS = { bench, serve, times, png, profile, part };
+
+// withUsageError takes a synchronous function, and some of the commands are
+// not: a CliError from any of them is printed here the same way.
+let ok;
+try {
+  if (!command) usageError("name a command");
+  if (!Object.hasOwn(COMMANDS, command)) usageError(`unknown command: ${command}`);
+  if (!["times", "png", "profile", "part"].includes(command) && args.length) {
+    usageError(`${command} takes no file: ${args[0]}`);
+  }
+  ok = await COMMANDS[command]();
+} catch (err) {
+  if (!(err instanceof CliError)) throw err;
+  process.stderr.write(`build_speed: ${err.message}\n\n${USAGE}`);
+  process.exit(2);
+}
+process.exit(ok ? 0 : 1);
diff --git a/test.bat b/test.bat
index bec639e7..7097ed17 100644
--- a/test.bat
+++ b/test.bat
@@ -152,6 +152,14 @@ node --test test/ide-js.test.mjs
 @rem lanes, well under a second.
 node --test test/discover.test.mjs
 @if errorlevel 1 goto :fail
+@rem Unit tests for the modules of scripts/build_speed.mjs that read the
+@rem build's Gantt chart and a CPU profile. The tool takes a build's times
+@rem from its chart, so a change to how the chart is drawn would make it
+@rem report other numbers without failing: these draw a chart with the
+@rem build's writer and read the same times back. No build, no lanes, well
+@rem under a second.
+node --test test/build-speed.test.mjs
+@if errorlevel 1 goto :fail
 @rem A regex that backtracks exponentially is a hang waiting for the
 @rem right input, and nothing that reads the site can see it: the corpus
 @rem passes until some page happens to contain the trigger, and then the
diff --git a/test/addin-project.test.mjs b/test/addin-project.test.mjs
index e11141de..0d9fff1b 100644
--- a/test/addin-project.test.mjs
+++ b/test/addin-project.test.mjs
@@ -26,7 +26,13 @@ import { tmpdir } from "node:os";
 import path from "node:path";
 import { after, describe, test } from "node:test";
 import { crc32, inflateRawSync } from "node:zlib";
-import { addinProjectOf, formatAddinProject, packAddinProject, writeAddinProject } from "../builder/addin-project.mjs";
+import {
+  addinProjectOf,
+  formatAddinProject,
+  listAddinFiles,
+  packAddinProject,
+  writeAddinProject,
+} from "../builder/addin-project.mjs";
 import { downloadsKept, helpArchiveSkips } from "../builder/help-archive-step.mjs";
 import {
   checkHelpArchive,
@@ -129,6 +135,16 @@ describe("the help add-in's project file", () => {
     assert.deepEqual(untracked, ["Sources/Scratch.twin"]);
   });
 
+  test("packs from a listing made earlier as it does from its own", async () => {
+    const dir = fixture("listed", TRACKED, { "Sources/Scratch.twin": "Module Scratch\nEnd Module\n" });
+    const listing = listAddinFiles(dir);
+    assert.deepEqual(await listing, { tracked: Object.keys(TRACKED).sort(), untracked: ["Sources/Scratch.twin"] });
+    const own = await packAddinProject({ dir });
+    const given = await packAddinProject({ dir, listing });
+    assert.ok(given.bytes.equals(own.bytes), "the two packs differ");
+    assert.deepEqual(given.untracked, own.untracked);
+  });
+
   test("packs the index it is given in place of the folder's copy, and the copy without one", async () => {
     const dir = fixture("symbols", TRACKED);
     const given = filesIn((await packAddinProject({ dir, symbols: '{"built":true}\n' })).bytes);
diff --git a/test/build-speed.test.mjs b/test/build-speed.test.mjs
new file mode 100644
index 00000000..66e2db50
--- /dev/null
+++ b/test/build-speed.test.mjs
@@ -0,0 +1,141 @@
+// Unit tests for the modules of scripts/build_speed.mjs that read what another
+// part of the tooling writes: the build's Gantt chart (builder/gantt.mjs) and a
+// V8 CPU profile.
+//
+// build_speed.mjs takes a build's times from its chart, since the build writes
+// no timings file. A change to how the chart is drawn would not fail the tool:
+// it would report other numbers, and a measurement that is wrong reads like one
+// that is right. These draw a chart from timings of their own with the build's
+// writer and read the same times back.
+//
+// Runs with a bare `node --test test/build-speed.test.mjs`: no build, no lanes.
+
+import assert from "node:assert/strict";
+import { describe, test } from "node:test";
+import { groupGanttTimings, renderGantt } from "../builder/gantt.mjs";
+import { chartLine, range, readChart } from "../scripts/build-speed/chart.mjs";
+import { formatTrees, profileTrees } from "../scripts/build-speed/profile.mjs";
+
+// The scheduler's timings are in milliseconds since the epoch; the chart's are
+// seconds from the first start. A chart is 900 units wide, so a time read back
+// from it is within a few hundredths of a second of the one drawn.
+const T0 = 1_000_000;
+const main = (start, end) => ({ start: T0 + start, end: T0 + end });
+const lane = (n, start, end, ganttSection) => ({
+  ...main(start, end),
+  workerStart: T0 + start,
+  workerEnd: T0 + end,
+  lane: n,
+  ganttSection,
+});
+const near = (actual, expected, what) =>
+  assert.ok(Math.abs(actual - expected) <= 0.03, `${what}: ${actual} is not within 0.03 s of ${expected}`);
+
+function chartOf(timings) {
+  return renderGantt(groupGanttTimings(new Map(Object.entries(timings))));
+}
+
+const BUILD = {
+  config: main(0, 10),
+  markdownInit: main(100, 200),
+  "renderEnvInit:0": lane(0, 400, 500, "Boot"),
+  "renderEnvInit:1": lane(1, 450, 600, "Boot"),
+  "render:0": lane(0, 500, 4000, "Render"),
+  "render:1": lane(1, 600, 5000, "Render"),
+  searchIndex: main(6000, 6500),
+  addinProject: main(7000, 7100),
+};
+
+describe("readChart", () => {
+  const chart = readChart(chartOf(BUILD));
+
+  test("reads the first render, render's end and the chart's end", () => {
+    near(chart.env, 0.4, "env");
+    near(chart.render.start, 0.5, "the first render");
+    near(chart.render.end, 5.0, "render's end");
+    near(chart.end, 7.1, "the chart's end");
+  });
+
+  test("reads a main-thread task by its label, and gives null for a name the chart has not", () => {
+    const bar = chart.task("searchIndex");
+    near(bar.start, 6.0, "searchIndex starts");
+    near(bar.end, 6.5, "searchIndex ends");
+    near(chart.task("markdownInit").end, 0.2, "markdownInit ends");
+    assert.equal(chart.task("linkJoin"), null);
+  });
+
+  test("reads a chart whose build took minutes", () => {
+    const long = readChart(chartOf({ config: main(0, 10), "render:0": lane(0, 30_000, 240_000, "Render") }));
+    assert.ok(Math.abs(long.render.start - 30) <= 0.5, `the first render: ${long.render.start}`);
+    assert.ok(Math.abs(long.render.end - 240) <= 0.5, `render's end: ${long.render.end}`);
+  });
+
+  test("gives null for what a chart has no bar of, and refuses what is not a chart", () => {
+    const bare = readChart(chartOf({ config: main(0, 10), searchIndex: main(1000, 2000) }));
+    assert.equal(bare.env, null);
+    assert.equal(bare.render.start, null);
+    assert.throws(() => readChart(""), /not a build's Gantt chart/);
+  });
+
+  test("chartLine names each figure, and a task the chart has not as unknown", () => {
+    const line = chartLine(chart, ["searchIndex", "linkJoin"]);
+    assert.match(
+      line,
+      /^first render 0\.5\d; render ends \d\.\d\d; ends 7\.\d\d; searchIndex [\d.]+ to [\d.]+; linkJoin \?$/,
+    );
+  });
+});
+
+describe("range", () => {
+  test("is the lowest and the highest, one value when they agree, and unknown for none", () => {
+    assert.equal(range([0.84, 0.7, 0.91]), "0.70 to 0.91 s");
+    assert.equal(range([0.701, 0.704]), "0.70 s");
+    assert.equal(range([null, 1.5]), "1.50 s");
+    assert.equal(range([null]), "?");
+  });
+});
+
+describe("profileTrees", () => {
+  const frame = (functionName, lineNumber) => ({ functionName, url: "file:///x/work.mjs", lineNumber });
+  // (root) -> outer -> inner -> outer, and (root) -> other.
+  const profile = {
+    nodes: [
+      { id: 1, callFrame: { functionName: "(root)", url: "", lineNumber: -1 }, children: [2, 5] },
+      { id: 2, callFrame: frame("outer", 9), children: [3] },
+      { id: 3, callFrame: frame("inner", 19), children: [4] },
+      { id: 4, callFrame: frame("outer", 9) },
+      { id: 5, callFrame: frame("other", 29) },
+    ],
+    samples: [2, 3, 4, 4, 5],
+    timeDeltas: [500, 1000, 2000, 2000, 8000],
+  };
+
+  test("totals a function with what it calls, and counts one that calls itself once", () => {
+    const trees = profileTrees(profile, ["outer"], 3);
+    const outer = trees.get("outer");
+    assert.equal(outer.t, 5500);
+    const inner = outer.kids.get("inner work.mjs:20");
+    assert.equal(inner.t, 5000);
+    assert.equal(inner.kids.get("outer work.mjs:10").t, 4000);
+  });
+
+  test("keeps only as many levels of callees as it is asked for", () => {
+    const outer = profileTrees(profile, ["outer"], 1).get("outer");
+    assert.equal(outer.t, 5500);
+    assert.equal(outer.kids.get("inner work.mjs:20").kids.size, 0);
+  });
+
+  test("prints callees by time, leaves out the small ones, and says which name had no sample", () => {
+    const names = ["other", "outer", "absent"];
+    const lines = formatTrees(profileTrees(profile, names, 3), names, 4.5);
+    assert.deepEqual(
+      lines.map((l) => l.trim()),
+      [
+        "8.0 ms  other",
+        "5.5 ms  outer",
+        "5.0 ms  inner work.mjs:20",
+        "?      absent: no sample is under a function of this name",
+      ],
+    );
+  });
+});