From 0e2434dcd12ff3331e9cb8d08f894e53ce8e2c44 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Fri, 23 Oct 2026 15:10:29 +0300 Subject: [PATCH] Make one forwarding wrapper serve every call-boundary watcher The steps this packet landed as, in order: - Time both legs at one boundary, three attributions apart - Pair the per-call table over the cases both legs did exactly - Name the layers the venue actually has in the honest-framing line - Localise a per-call cost with --call, and find where replace_region goes Content: the tree of `development` at f0b110e225, unchanged. --- crates/metal2vulkan-conformance/Cargo.toml | 3 + crates/metal2vulkan-conformance/README.md | 115 +- .../pass-bytes-half-tanh-regimes.json | 202 +++ .../pass-bytes-srgb-decode-all-bytes.json | 202 +++ .../pass-bytes-srgb-encode-sweep.json | 202 +++ .../recordings/texture-fills-212.json | 40 + .../recordings/texture-fills-236.json | 40 + .../src/bin/conformance.rs | 168 +- .../src/cases/handler_waits.rs | 7 +- crates/metal2vulkan-conformance/src/clocks.rs | 72 + .../metal2vulkan-conformance/src/coverage.rs | 497 ++++++ crates/metal2vulkan-conformance/src/lib.rs | 5 + .../metal2vulkan-conformance/src/recording.rs | 30 + crates/metal2vulkan-conformance/src/run.rs | 258 +++ crates/metal2vulkan-conformance/src/tests.rs | 19 +- crates/metal2vulkan-conformance/src/times.rs | 1380 +++++++++++++++++ .../metal2vulkan-conformance/src/validated.rs | 449 +----- crates/metal2vulkan-conformance/src/watch.rs | 790 ++++++++++ 18 files changed, 4031 insertions(+), 448 deletions(-) create mode 100644 crates/metal2vulkan-conformance/src/clocks.rs create mode 100644 crates/metal2vulkan-conformance/src/coverage.rs create mode 100644 crates/metal2vulkan-conformance/src/times.rs create mode 100644 crates/metal2vulkan-conformance/src/watch.rs diff --git a/crates/metal2vulkan-conformance/Cargo.toml b/crates/metal2vulkan-conformance/Cargo.toml index a155fc5da..a4a2448bb 100644 --- a/crates/metal2vulkan-conformance/Cargo.toml +++ b/crates/metal2vulkan-conformance/Cargo.toml @@ -20,6 +20,9 @@ metal2vulkan-runtime = { path = "../metal2vulkan-runtime" } metal2vulkan-devtools = { path = "../metal2vulkan-devtools" } ash = { workspace = true, features = ["loaded"] } base64 = "0.22" +# The two CPU clocks the cost table reads: the calling thread's and the whole process's +# (`src/clocks.rs`). `std` exposes neither. +libc.workspace = true serde.workspace = true serde_json.workspace = true sha2.workspace = true diff --git a/crates/metal2vulkan-conformance/README.md b/crates/metal2vulkan-conformance/README.md index a237f2734..35969218e 100644 --- a/crates/metal2vulkan-conformance/README.md +++ b/crates/metal2vulkan-conformance/README.md @@ -246,9 +246,118 @@ venue the measurement was not taken on, a selection that is not the whole case s depend on what ran before it in the same process), a run that stopped part way, and a run the device degraded otherwise. -Times are **advisory** here: a wall-clock figure is printed per case so a reader can see where the -counts are large, and it is neither recorded nor gated. Per-call timing against Metal is the per-call -cost table in `metal2vulkan-runtime/examples/host_ab`, which this half does not duplicate. +`cost`'s own per-case wall-clock figure stays **advisory**: it is printed so a reader can see where +the counts are large, and it is neither recorded nor gated. Timing against Metal is the times half, +below. + +## The times half: Metal's cost beside ours + +The counters say what our side **did**. The times half says what each leg **cost**, over the same +case set, with native Metal's own cost as the thing to beat: + +```sh +conformance times --runs 8 # both legs, print the tables +conformance times --runs 8 --show # and every per-case row, not only the interesting ones +conformance times --leg metal --runs 8 # one leg in a process of its own +conformance times --runs 8 --write # keep the figures in the cases' recordings +conformance times --runs 8 --call replace_region # where one call's cost sits, case by case +conformance timing-coverage # which calls are timed, and which are not +``` + +`--call` is the triage, and it earns its place: the first whole-set run put `replace_region` at +105x over 108 calls, and the three cases that obviously make it came out at 1.2x over 3 when run +alone. The figure was real and almost none of it was there. `--call replace_region` put all of it +in one family — 16 `xr-two-plane-samples` cases, one such call each, Metal 72 us against our +19,132 us (**265x**, 92% of ours spent blocked) — while the other 86 cases that make the call sit +at 1.3x together. A per-call total says *that* a call is expensive and never *where*, and a reading +over one selection is not evidence about another. + +Both legs are measured **at one boundary**, `watch::Watching`'s span: around the Metal or Vulkan +call and the side's own handle bookkeeping, outside the transcript, the fixtures and the input +fingerprint. One wrapper, not one span in `MetalSide` and another in `RuntimeSide`, because two +spans placed separately are two spans that drift and a comparison of two legs measured in different +places is not a comparison. + +**A difference is the whole chain's, and attributes to no layer.** On this Mac our leg is +translation, then our runtime, then MoltenVK, then Metal. A ratio is the cost of all of that against +native Metal. The suite cannot say what MoltenVK's share is or what ours is, and no figure it prints +licenses a sentence of the form "MoltenVK costs X". Separating the shares needs counters inside each +layer or the same case on a non-Apple driver to difference against. + +**Three attributions, kept apart, because moving work between them is not a win.** The calling +thread's own CPU inside the call; what the caller waited for; and CPU the rest of the process burned +over the case. A call that returns at once and hands its work to a thread the caller must then wait +on has saved nothing, so the margin is judged on `wall-in-calls + elsewhere` — everything the +machine spent on the case's calls, however attributed. No split of one total changes a verdict. + +The split is the instrument's, not a preference. Measured on this M3 Max: the wall clock reads in +16 ns and answers nanoseconds, the thread CPU clock reads in 95 ns and steps in 125 ns, and the +**process** CPU clock reads in 230 ns and steps in **1000 ns**. A microsecond step is most of a +short call, so the handoff is a per-case figure and the other two are per call. The instrument's own +~0.24 us a call is measured on the host and printed beside the table; it is never subtracted, and it +is paid identically on both legs, so a ratio carries it top and bottom. + +**Two tables, and the per-call one needs the other to be honest.** Metal compiles the AIR at +`library` and we translate it at `compute_pipeline`, so the same work sits at a different call on +each leg: measured here, `library` costs Metal about 23 ms and us about 0.1 ms, while +`compute_pipeline` costs Metal 0.09 ms and us 2.1 ms. Neither row alone is a result. The per-case +total is the figure that cannot be moved. + +The per-call table is **paired over the cases both legs did exactly**, and that is not optional. Each +leg's own pool is over the cases *that leg* finished without a notice, and the two sets differ: 77 of +this suite's cases announce a notice on our leg and none do on Metal's. The first whole-set run, +before the pairing, compared `render_pipeline` over 132 Metal calls against 85 of ours and printed a +ratio of different work. Each row still prints both legs' call counts, because a case whose legs make +a call a different number of times is comparing different work and only the counts can say so. The +ratio is on the **totals**, so a call is weighted by how often it runs. + +**The degraded-set rule, which matters more here than for counts.** A leg that announced a degrade +notice did a different amount of work: the device lacked the exact form and the runtime did something +cheaper and said so. Its cost is `unmeasured`, never a fast row. Without that rule a device's honest +gap reads as a cost win, which is the most flattering lie the suite could tell. + +**Reported, never gated.** `times::MARGIN` is an order of magnitude, computed and printed as a +verdict, and it decides **no exit status**. Measured twice over the whole set on this Mac, eight +rounds each: the verdicts were identical both times (221 within, 0 over, 162 unmeasured) while +Metal's own per-call totals moved a median 1.28x and as much as 2.43x between the two runs, and the +ratios moved a median 1.25x. So a 10x margin survived both runs and a 2x margin would not have. What +the commit that turns the gate on has to show first: a bound per case rather than one margin for all, +each naming its measurement the way a cost bound does; the contrast between a case run alone and the +same case inside the set, which for counts turned five apparent regressions into four counters that +were never per-case facts; and a rule for what happens when the machine is busy, since one of these +two runs took 4m20s and the other 7m48s on the same binary over the same cases. + +**What a recording keeps, and why.** Metal's cost on a given macOS build is the one half that cannot +be re-taken: a measurement of ours is a command away on any host, but what Metal charged for a call +on 26A434 is gone the moment the machine updates. `--write` keeps both legs' figures in the case's own +recording for that reason. Nothing compares a stored figure with a live one — a comparison is only +ever between two legs measured in the same run, on one machine, from the identical transcript — so +the stored figures are history, and a case with none is a reported hole. `RECORDING_FORMAT_VERSION` +is untouched: the field is optional, the pattern the counters half established, so no committed +recording moves. + +## Timing coverage is a number + +A per-call table over an unknown fraction of the API is a table nobody can act on, so `untimed` is +tracked and driven down the way `unrecorded` is. `conformance timing-coverage` answers it in two +parts, and only the first is exact: + +- **The suite's own vocabulary.** Every call a case can make is a `Side` method, and a run says + which ones the selection made. Both the trait and the wrapper are read from their own sources, so + a call a stream adds cannot make coverage look complete by being left off a list. Today: **51 of + 51 spanned calls are timed** by the whole case set; `venue` and `announced` are forwarded without + a span on purpose and are listed as such rather than counted as holes. +- **The runtime's public frame surface**, which can only be answered approximately from here. A + `Side` call reaches the runtime through our own code, which calls further helpers, so knowing + which public method a timed call reaches needs a call graph this crate has no business building. + The census counts the public methods of the objects a frame makes its calls on and says which are + **named anywhere** in the suite's runtime-side sources — an **upper bound** on timed coverage, and + the report says so in those words. Today: **148 of 540**, so at least 392 frame-surface methods + cannot be timed by any case. Narrowing the bound to a real figure is a call graph's job. + +The frame-surface list is the one `scripts/api-cost-coverage` uses for the other harness's table, +kept the same deliberately: two censuses over two denominators would be two numbers nobody can put +beside each other. ## This crate is not the validation suite diff --git a/crates/metal2vulkan-conformance/recordings/pass-bytes-half-tanh-regimes.json b/crates/metal2vulkan-conformance/recordings/pass-bytes-half-tanh-regimes.json index af3a421f4..af30a87f2 100644 --- a/crates/metal2vulkan-conformance/recordings/pass-bytes-half-tanh-regimes.json +++ b/crates/metal2vulkan-conformance/recordings/pass-bytes-half-tanh-regimes.json @@ -309,5 +309,207 @@ "pooled_memory_blocks_made": 3 } } + ], + "times": [ + { + "leg": "metal", + "venue": "native Metal", + "chip": "apple-m3-max", + "os_build": "26A434", + "rounds": 2, + "measured": "2 round(s) of the whole selection, in the case set's own order, each round on a fresh device; a figure is the median of the rounds' own medians", + "instrument": 251, + "times": { + "case": "pass-bytes-half-tanh-regimes", + "calls": 6, + "in_calls": 33949168, + "on_cpu": 1213542, + "blocked": 32736334, + "elsewhere": 4165042, + "spend": 38114210, + "spend_least": 38114210, + "spend_most": 51677794, + "per_call": [ + { + "call": "compute_pipeline", + "least_calls": 1, + "most_calls": 1, + "wall": 104125, + "on_cpu": 104375, + "blocked": 0, + "wall_least": 104125, + "wall_most": 429084, + "wall_total": 104125, + "on_cpu_total": 104375, + "blocked_total": 0 + }, + { + "call": "dispatch", + "least_calls": 1, + "most_calls": 1, + "wall": 115459, + "on_cpu": 115666, + "blocked": 0, + "wall_least": 115459, + "wall_most": 122625, + "wall_total": 115459, + "on_cpu_total": 115666, + "blocked_total": 0 + }, + { + "call": "library", + "least_calls": 1, + "most_calls": 1, + "wall": 28984667, + "on_cpu": 915125, + "blocked": 28063917, + "wall_least": 28984667, + "wall_most": 42646792, + "wall_total": 28984667, + "on_cpu_total": 915125, + "blocked_total": 28063917 + }, + { + "call": "read_buffer", + "least_calls": 1, + "most_calls": 1, + "wall": 5250, + "on_cpu": 5375, + "blocked": 0, + "wall_least": 5250, + "wall_most": 5292, + "wall_total": 5250, + "on_cpu_total": 5375, + "blocked_total": 0 + }, + { + "call": "wait", + "least_calls": 1, + "most_calls": 1, + "wall": 4260791, + "on_cpu": 10417, + "blocked": 4250374, + "wall_least": 4260791, + "wall_most": 4682834, + "wall_total": 4260791, + "on_cpu_total": 10417, + "blocked_total": 4250374 + }, + { + "call": "zeroed_buffer", + "least_calls": 1, + "most_calls": 1, + "wall": 41459, + "on_cpu": 41666, + "blocked": 0, + "wall_least": 41459, + "wall_most": 49667, + "wall_total": 41459, + "on_cpu_total": 41666, + "blocked_total": 0 + } + ] + } + }, + { + "leg": "ours", + "venue": "Apple M3 Max", + "chip": "apple-m3-max", + "os_build": "26A434", + "rounds": 2, + "measured": "2 round(s) of the whole selection, in the case set's own order, each round on a fresh device; a figure is the median of the rounds' own medians", + "instrument": 240, + "times": { + "case": "pass-bytes-half-tanh-regimes", + "calls": 6, + "in_calls": 4615917, + "on_cpu": 2681834, + "blocked": 1934958, + "elsewhere": 1551250, + "spend": 6167167, + "spend_least": 6167167, + "spend_most": 6885418, + "per_call": [ + { + "call": "compute_pipeline", + "least_calls": 1, + "most_calls": 1, + "wall": 2627958, + "on_cpu": 2453500, + "blocked": 174458, + "wall_least": 2627958, + "wall_most": 2763209, + "wall_total": 2627958, + "on_cpu_total": 2453500, + "blocked_total": 174458 + }, + { + "call": "dispatch", + "least_calls": 1, + "most_calls": 1, + "wall": 72292, + "on_cpu": 72500, + "blocked": 0, + "wall_least": 72292, + "wall_most": 76750, + "wall_total": 72292, + "on_cpu_total": 72500, + "blocked_total": 0 + }, + { + "call": "library", + "least_calls": 1, + "most_calls": 1, + "wall": 143125, + "on_cpu": 143542, + "blocked": 0, + "wall_least": 143125, + "wall_most": 167417, + "wall_total": 143125, + "on_cpu_total": 143542, + "blocked_total": 0 + }, + { + "call": "read_buffer", + "least_calls": 1, + "most_calls": 1, + "wall": 1125, + "on_cpu": 1250, + "blocked": 0, + "wall_least": 1125, + "wall_most": 1208, + "wall_total": 1125, + "on_cpu_total": 1250, + "blocked_total": 0 + }, + { + "call": "wait", + "least_calls": 1, + "most_calls": 1, + "wall": 1765500, + "on_cpu": 5000, + "blocked": 1760500, + "wall_least": 1765500, + "wall_most": 2023000, + "wall_total": 1765500, + "on_cpu_total": 5000, + "blocked_total": 1760500 + }, + { + "call": "zeroed_buffer", + "least_calls": 1, + "most_calls": 1, + "wall": 5917, + "on_cpu": 6042, + "blocked": 0, + "wall_least": 5917, + "wall_most": 21084, + "wall_total": 5917, + "on_cpu_total": 6042, + "blocked_total": 0 + } + ] + } + } ] } diff --git a/crates/metal2vulkan-conformance/recordings/pass-bytes-srgb-decode-all-bytes.json b/crates/metal2vulkan-conformance/recordings/pass-bytes-srgb-decode-all-bytes.json index 34b682976..3988176cd 100644 --- a/crates/metal2vulkan-conformance/recordings/pass-bytes-srgb-decode-all-bytes.json +++ b/crates/metal2vulkan-conformance/recordings/pass-bytes-srgb-decode-all-bytes.json @@ -282,5 +282,207 @@ "wakes_spared": 7 } } + ], + "times": [ + { + "leg": "metal", + "venue": "native Metal", + "chip": "apple-m3-max", + "os_build": "26A434", + "rounds": 2, + "measured": "2 round(s) of the whole selection, in the case set's own order, each round on a fresh device; a figure is the median of the rounds' own medians", + "instrument": 251, + "times": { + "case": "pass-bytes-srgb-decode-all-bytes", + "calls": 6, + "in_calls": 33231875, + "on_cpu": 1182458, + "blocked": 32050126, + "elsewhere": 4147916, + "spend": 37379791, + "spend_least": 37379791, + "spend_most": 108703914, + "per_call": [ + { + "call": "compute_pipeline", + "least_calls": 1, + "most_calls": 1, + "wall": 106625, + "on_cpu": 106833, + "blocked": 0, + "wall_least": 106625, + "wall_most": 904083, + "wall_total": 106625, + "on_cpu_total": 106833, + "blocked_total": 0 + }, + { + "call": "dispatch", + "least_calls": 1, + "most_calls": 1, + "wall": 138042, + "on_cpu": 138250, + "blocked": 0, + "wall_least": 138042, + "wall_most": 698291, + "wall_total": 138042, + "on_cpu_total": 138250, + "blocked_total": 0 + }, + { + "call": "library", + "least_calls": 1, + "most_calls": 1, + "wall": 28303084, + "on_cpu": 897750, + "blocked": 27405334, + "wall_least": 28303084, + "wall_most": 98003291, + "wall_total": 28303084, + "on_cpu_total": 897750, + "blocked_total": 27405334 + }, + { + "call": "read_buffer", + "least_calls": 1, + "most_calls": 1, + "wall": 1750, + "on_cpu": 1875, + "blocked": 0, + "wall_least": 1750, + "wall_most": 5791, + "wall_total": 1750, + "on_cpu_total": 1875, + "blocked_total": 0 + }, + { + "call": "wait", + "least_calls": 1, + "most_calls": 1, + "wall": 4517833, + "on_cpu": 10291, + "blocked": 4506083, + "wall_least": 4517833, + "wall_most": 4655083, + "wall_total": 4517833, + "on_cpu_total": 10291, + "blocked_total": 4506083 + }, + { + "call": "zeroed_buffer", + "least_calls": 1, + "most_calls": 1, + "wall": 27291, + "on_cpu": 27459, + "blocked": 0, + "wall_least": 27291, + "wall_most": 48083, + "wall_total": 27291, + "on_cpu_total": 27459, + "blocked_total": 0 + } + ] + } + }, + { + "leg": "ours", + "venue": "Apple M3 Max", + "chip": "apple-m3-max", + "os_build": "26A434", + "rounds": 2, + "measured": "2 round(s) of the whole selection, in the case set's own order, each round on a fresh device; a figure is the median of the rounds' own medians", + "instrument": 240, + "times": { + "case": "pass-bytes-srgb-decode-all-bytes", + "calls": 6, + "in_calls": 8415708, + "on_cpu": 6456750, + "blocked": 1960042, + "elsewhere": 1663459, + "spend": 10079167, + "spend_least": 10079167, + "spend_most": 30241750, + "per_call": [ + { + "call": "compute_pipeline", + "least_calls": 1, + "most_calls": 1, + "wall": 6352333, + "on_cpu": 6143083, + "blocked": 209250, + "wall_least": 6352333, + "wall_most": 20518416, + "wall_total": 6352333, + "on_cpu_total": 6143083, + "blocked_total": 209250 + }, + { + "call": "dispatch", + "least_calls": 1, + "most_calls": 1, + "wall": 140125, + "on_cpu": 140292, + "blocked": 0, + "wall_least": 140125, + "wall_most": 2029875, + "wall_total": 140125, + "on_cpu_total": 140292, + "blocked_total": 0 + }, + { + "call": "library", + "least_calls": 1, + "most_calls": 1, + "wall": 152000, + "on_cpu": 152625, + "blocked": 0, + "wall_least": 152000, + "wall_most": 3361125, + "wall_total": 152000, + "on_cpu_total": 152625, + "blocked_total": 0 + }, + { + "call": "read_buffer", + "least_calls": 1, + "most_calls": 1, + "wall": 625, + "on_cpu": 750, + "blocked": 0, + "wall_least": 625, + "wall_most": 1042, + "wall_total": 625, + "on_cpu_total": 750, + "blocked_total": 0 + }, + { + "call": "wait", + "least_calls": 1, + "most_calls": 1, + "wall": 1758250, + "on_cpu": 7458, + "blocked": 1750792, + "wall_least": 1758250, + "wall_most": 1881542, + "wall_total": 1758250, + "on_cpu_total": 7458, + "blocked_total": 1750792 + }, + { + "call": "zeroed_buffer", + "least_calls": 1, + "most_calls": 1, + "wall": 11958, + "on_cpu": 12084, + "blocked": 0, + "wall_least": 11958, + "wall_most": 105750, + "wall_total": 11958, + "on_cpu_total": 12084, + "blocked_total": 0 + } + ] + } + } ] } diff --git a/crates/metal2vulkan-conformance/recordings/pass-bytes-srgb-encode-sweep.json b/crates/metal2vulkan-conformance/recordings/pass-bytes-srgb-encode-sweep.json index 833473424..02014d6b0 100644 --- a/crates/metal2vulkan-conformance/recordings/pass-bytes-srgb-encode-sweep.json +++ b/crates/metal2vulkan-conformance/recordings/pass-bytes-srgb-encode-sweep.json @@ -271,5 +271,207 @@ "wakes_spared": 6 } } + ], + "times": [ + { + "leg": "metal", + "venue": "native Metal", + "chip": "apple-m3-max", + "os_build": "26A434", + "rounds": 2, + "measured": "2 round(s) of the whole selection, in the case set's own order, each round on a fresh device; a figure is the median of the rounds' own medians", + "instrument": 251, + "times": { + "case": "pass-bytes-srgb-encode-sweep", + "calls": 6, + "in_calls": 33709000, + "on_cpu": 1249041, + "blocked": 32457668, + "elsewhere": 4191667, + "spend": 37900667, + "spend_least": 37900667, + "spend_most": 37976417, + "per_call": [ + { + "call": "compute_pipeline", + "least_calls": 1, + "most_calls": 1, + "wall": 116417, + "on_cpu": 116791, + "blocked": 0, + "wall_least": 116417, + "wall_most": 501375, + "wall_total": 116417, + "on_cpu_total": 116791, + "blocked_total": 0 + }, + { + "call": "dispatch", + "least_calls": 1, + "most_calls": 1, + "wall": 139583, + "on_cpu": 139791, + "blocked": 0, + "wall_least": 139583, + "wall_most": 151625, + "wall_total": 139583, + "on_cpu_total": 139791, + "blocked_total": 0 + }, + { + "call": "library", + "least_calls": 1, + "most_calls": 1, + "wall": 28362375, + "on_cpu": 861541, + "blocked": 27500834, + "wall_least": 28362375, + "wall_most": 28660292, + "wall_total": 28362375, + "on_cpu_total": 861541, + "blocked_total": 27500834 + }, + { + "call": "read_buffer", + "least_calls": 1, + "most_calls": 1, + "wall": 3666, + "on_cpu": 3959, + "blocked": 0, + "wall_least": 3666, + "wall_most": 3792, + "wall_total": 3666, + "on_cpu_total": 3959, + "blocked_total": 0 + }, + { + "call": "wait", + "least_calls": 1, + "most_calls": 1, + "wall": 4653667, + "on_cpu": 9083, + "blocked": 4642709, + "wall_least": 4653667, + "wall_most": 4728041, + "wall_total": 4653667, + "on_cpu_total": 9083, + "blocked_total": 4642709 + }, + { + "call": "zeroed_buffer", + "least_calls": 1, + "most_calls": 1, + "wall": 48334, + "on_cpu": 48500, + "blocked": 0, + "wall_least": 48334, + "wall_most": 54583, + "wall_total": 48334, + "on_cpu_total": 48500, + "blocked_total": 0 + } + ] + } + }, + { + "leg": "ours", + "venue": "Apple M3 Max", + "chip": "apple-m3-max", + "os_build": "26A434", + "rounds": 2, + "measured": "2 round(s) of the whole selection, in the case set's own order, each round on a fresh device; a figure is the median of the rounds' own medians", + "instrument": 240, + "times": { + "case": "pass-bytes-srgb-encode-sweep", + "calls": 6, + "in_calls": 6268375, + "on_cpu": 3628417, + "blocked": 2641208, + "elsewhere": 2392416, + "spend": 8660791, + "spend_least": 8660791, + "spend_most": 9150169, + "per_call": [ + { + "call": "compute_pipeline", + "least_calls": 1, + "most_calls": 1, + "wall": 3564541, + "on_cpu": 3368292, + "blocked": 196249, + "wall_least": 3564541, + "wall_most": 3741042, + "wall_total": 3564541, + "on_cpu_total": 3368292, + "blocked_total": 196249 + }, + { + "call": "dispatch", + "least_calls": 1, + "most_calls": 1, + "wall": 90167, + "on_cpu": 90333, + "blocked": 0, + "wall_least": 90167, + "wall_most": 90667, + "wall_total": 90167, + "on_cpu_total": 90333, + "blocked_total": 0 + }, + { + "call": "library", + "least_calls": 1, + "most_calls": 1, + "wall": 148750, + "on_cpu": 149625, + "blocked": 0, + "wall_least": 148750, + "wall_most": 149333, + "wall_total": 148750, + "on_cpu_total": 149625, + "blocked_total": 0 + }, + { + "call": "read_buffer", + "least_calls": 1, + "most_calls": 1, + "wall": 1208, + "on_cpu": 1334, + "blocked": 0, + "wall_least": 1208, + "wall_most": 1292, + "wall_total": 1208, + "on_cpu_total": 1334, + "blocked_total": 0 + }, + { + "call": "wait", + "least_calls": 1, + "most_calls": 1, + "wall": 2450417, + "on_cpu": 5458, + "blocked": 2444959, + "wall_least": 2450417, + "wall_most": 2625834, + "wall_total": 2450417, + "on_cpu_total": 5458, + "blocked_total": 2444959 + }, + { + "call": "zeroed_buffer", + "least_calls": 1, + "most_calls": 1, + "wall": 11584, + "on_cpu": 11709, + "blocked": 0, + "wall_least": 11584, + "wall_most": 12625, + "wall_total": 11584, + "on_cpu_total": 11709, + "blocked_total": 0 + } + ] + } + } ] } diff --git a/crates/metal2vulkan-conformance/recordings/texture-fills-212.json b/crates/metal2vulkan-conformance/recordings/texture-fills-212.json index d8522fcc0..b72adb8ce 100644 --- a/crates/metal2vulkan-conformance/recordings/texture-fills-212.json +++ b/crates/metal2vulkan-conformance/recordings/texture-fills-212.json @@ -182,5 +182,45 @@ "pooled_memory_blocks_made": 3 } } + ], + "times": [ + { + "leg": "ours", + "venue": "Apple M3 Max", + "chip": "apple-m3-max", + "os_build": "26A434", + "rounds": 2, + "measured": "2 round(s) of the whole selection, in the case set's own order, each round on a fresh device; a figure is the median of the rounds' own medians", + "instrument": 240, + "times": { + "case": "texture-fills-212", + "calls": 25, + "in_calls": 15892082, + "on_cpu": 1053712, + "blocked": 14838370, + "elsewhere": 5865542, + "spend": 21757624, + "spend_least": 21757624, + "spend_most": 27571336, + "degraded": [ + "metal2vulkan-degrade-unpacked-fill-color" + ], + "per_call": [ + { + "call": "work", + "least_calls": 25, + "most_calls": 25, + "wall": 622958, + "on_cpu": 26208, + "blocked": 586833, + "wall_least": 622958, + "wall_most": 732000, + "wall_total": 15892082, + "on_cpu_total": 1053712, + "blocked_total": 14838370 + } + ] + } + } ] } diff --git a/crates/metal2vulkan-conformance/recordings/texture-fills-236.json b/crates/metal2vulkan-conformance/recordings/texture-fills-236.json index 65c18f539..a7823ca80 100644 --- a/crates/metal2vulkan-conformance/recordings/texture-fills-236.json +++ b/crates/metal2vulkan-conformance/recordings/texture-fills-236.json @@ -179,5 +179,45 @@ "pooled_memory_blocks_made": 3 } } + ], + "times": [ + { + "leg": "ours", + "venue": "Apple M3 Max", + "chip": "apple-m3-max", + "os_build": "26A434", + "rounds": 2, + "measured": "2 round(s) of the whole selection, in the case set's own order, each round on a fresh device; a figure is the median of the rounds' own medians", + "instrument": 240, + "times": { + "case": "texture-fills-236", + "calls": 25, + "in_calls": 7513165, + "on_cpu": 534749, + "blocked": 6969164, + "elsewhere": 2995208, + "spend": 10546332, + "spend_least": 10546332, + "spend_most": 10829085, + "degraded": [ + "metal2vulkan-degrade-unpacked-fill-color" + ], + "per_call": [ + { + "call": "work", + "least_calls": 25, + "most_calls": 25, + "wall": 290916, + "on_cpu": 19500, + "blocked": 269083, + "wall_least": 290916, + "wall_most": 299000, + "wall_total": 7513165, + "on_cpu_total": 534749, + "blocked_total": 6969164 + } + ] + } + } ] } diff --git a/crates/metal2vulkan-conformance/src/bin/conformance.rs b/crates/metal2vulkan-conformance/src/bin/conformance.rs index 3be7ab5ca..045a3348a 100644 --- a/crates/metal2vulkan-conformance/src/bin/conformance.rs +++ b/crates/metal2vulkan-conformance/src/bin/conformance.rs @@ -5,6 +5,8 @@ //! conformance record [case ...] //! conformance replay [--cpu] [--default-policy] [case ...] //! conformance cost [--cpu] [--default-policy] [--runs N] [--write] [--show] [--alone] [case ...] +//! conformance times [--cpu] [--default-policy] [--runs N] [--leg metal|ours] [--write] [--show] +//! [--call NAME] [case ...] //! conformance cases //! ``` //! @@ -26,6 +28,16 @@ //! `Divergent`, with our answer and Metal's, and still counted, because its rows are open bugs //! rather than accepted differences. //! +//! `times` is the cost half's other face ([`metal2vulkan_conformance::times`]): it runs **both** +//! legs over the same selection on this Mac, back to back, and prints what each call cost on +//! native Metal beside what it cost on our stack. The figures are reported and gate nothing — a +//! time is not assertable on a machine running other work — and a ratio is the cost of our whole +//! chain (translation, runtime, MoltenVK, Metal) against native Metal, attributing to no layer of +//! it. `--leg` runs one leg alone, which is the only way to read the off-thread attribution with +//! nothing of the other leg's threads in it; `--write` keeps the figures in the cases' own +//! recordings, because Metal's cost on a given macOS build is the one half that cannot be re-taken +//! later. +//! //! `cost` is the other half ([`metal2vulkan_conformance::cost`]): it runs our side alone and says //! what the runtime did to answer each case, by count. `--runs N` runs the whole selection N times //! (eight by default), each round on a fresh device, so a count that is not deterministic is seen @@ -66,6 +78,8 @@ fn command() -> Result { let mut write = false; let mut show = false; let mut alone = false; + let mut legs = Legs::Both; + let mut call = None; let mut words = words.peekable(); while let Some(word) = words.next() { match word.as_str() { @@ -76,6 +90,18 @@ fn command() -> Result { "--write" => write = true, "--show" => show = true, "--alone" => alone = true, + "--call" => { + call = Some(words.next().ok_or("--call wants a Side call's name")?); + } + "--leg" => { + let value = words.next().ok_or("--leg wants metal or ours")?; + legs = match value.as_str() { + "metal" => Legs::Metal, + "ours" => Legs::Ours, + "both" => Legs::Both, + other => return Err(format!("--leg {other}: expected metal, ours or both")), + }; + } "--runs" => { let value = words.next().ok_or("--runs wants a number")?; runs = value @@ -96,6 +122,19 @@ fn command() -> Result { } "record" => record(&cases), "cost" => cost(venues, policy, &cases, runs, write, show, alone), + "times" => times( + &cases, + Asked { + venues, + policy, + runs, + legs, + write, + show, + call: call.as_deref(), + }, + ), + "timing-coverage" => timing_coverage(venues, policy, &cases), metal2vulkan_conformance::validated::LEG_VERB => validated_leg(&cases), "replay" => { let report = run::replay_on_under(venues, policy, &cases)?; @@ -143,7 +182,8 @@ fn command() -> Result { Ok(false) } other => Err(format!( - "unknown command {other}: expected record, replay, cost or cases" + "unknown command {other}: expected record, replay, cost, times, timing-coverage or \ + cases" )), } } @@ -347,3 +387,129 @@ fn validated_leg(cases: &[Box]) -> Res fn validated_leg(_cases: &[Box]) -> Result { Err("Metal's API validation layer is on macOS, where Metal is".to_owned()) } + +/// Which legs a `times` run measures. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Legs { + /// Both, in two phases, which is what a comparison needs. + Both, + /// Native Metal alone. + Metal, + /// Our stack alone. + Ours, +} + +/// What a `times` run was asked for: the flags, gathered so the run takes one argument rather +/// than eight. +struct Asked<'a> { + venues: Venues, + policy: Policy, + runs: u32, + legs: Legs, + write: bool, + show: bool, + /// The one call `--call` names, whose cost is then printed case by case. + call: Option<&'a str>, +} + +/// Measure what the selection costs in **time** on each leg and print the table. +/// +/// The two legs run as two phases of one process rather than case by case, because the off-thread +/// attribution reads the whole process's CPU and interleaving would put each leg's threads in the +/// other's readings. `--leg` runs one leg in a process of its own, which is the only way to read +/// that attribution with nothing of the other leg in it. +fn times( + cases: &[Box], + asked: Asked<'_>, +) -> Result { + let Asked { + venues, + policy, + runs, + legs, + write, + show, + call, + } = asked; + let metal = match legs { + Legs::Both | Legs::Metal => metal_times(cases, runs)?, + Legs::Ours => None, + }; + let ours = match legs { + Legs::Both | Legs::Ours => Some(run::times_on_under(venues, policy, cases, runs)?), + Legs::Metal => None, + }; + let words = format!( + "{runs} round(s) of the whole selection, in the case set's own order, each round on a \ + fresh device; a figure is the median of the rounds' own medians" + ); + match (&metal, &ours) { + (metal, Some(ours)) => print!( + "{}", + metal2vulkan_conformance::times::render(metal.as_ref(), ours, show) + ), + // The Metal leg alone: there is nothing to compare it with, so it prints as its own + // measurement rather than as half a table. + (Some(metal), None) => print!( + "{}", + metal2vulkan_conformance::times::render(None, metal, show) + ), + (None, None) => return Err("--leg selected neither leg".to_owned()), + } + // The triage for a row of the per-call table: a total over a case set says that a call is + // expensive, never where. + if let (Some(call), Some(metal), Some(ours)) = (call, &metal, &ours) { + print!( + "{}", + metal2vulkan_conformance::times::render_one_call(metal, ours, call) + ); + } + if !write { + println!("nothing written; pass --write to keep these figures in the recordings"); + return Ok(true); + } + let mut all = true; + for (case, written) in run::record_times(metal.as_ref(), ours.as_ref(), &words) { + match written { + Ok(path) => println!("{case}: {}", path.display()), + Err(why) => { + all = false; + println!("{case}: not recorded: {why}"); + } + } + } + Ok(all) +} + +/// The Metal leg's figures, where this host has Metal. +#[cfg(target_os = "macos")] +fn metal_times( + cases: &[Box], + runs: u32, +) -> Result, String> { + run::metal_times(cases, runs).map(Some) +} + +/// There is no Metal to time off macOS, so the run reports our leg alone rather than refusing. +#[cfg(not(target_os = "macos"))] +fn metal_times( + _cases: &[Box], + _runs: u32, +) -> Result, String> { + Ok(None) +} + +/// Print the timing-coverage census: which calls the selection times and which it does not. +fn timing_coverage( + venues: Venues, + policy: Policy, + cases: &[Box], +) -> Result { + // One round is enough: the census asks which calls a case makes, not what they cost. A call a + // case makes only sometimes is the one thing a single round can miss, so the census says how + // many rounds it took. + let measured = run::times_on_under(venues, policy, cases, 1)?; + let census = metal2vulkan_conformance::coverage::Census::of(&measured)?; + print!("{}", census.render()); + Ok(true) +} diff --git a/crates/metal2vulkan-conformance/src/cases/handler_waits.rs b/crates/metal2vulkan-conformance/src/cases/handler_waits.rs index 9eb4d8e48..a06c1b082 100644 --- a/crates/metal2vulkan-conformance/src/cases/handler_waits.rs +++ b/crates/metal2vulkan-conformance/src/cases/handler_waits.rs @@ -194,10 +194,11 @@ mod tests { Recording::new(case.name(), Vec::new(), vec![case.stated_answer().unwrap()]); let committed = recording::read(case.name()).unwrap_or_else(|why| panic!("{}: {why}", case.name())); - // Metal's answer alone: the cost half of the file is our own measurement on a venue, - // taken by another leg, and a case states nothing about it. + // Metal's answer alone: the cost and times halves of the file are our own + // measurements on a venue, taken by other legs, and a case states nothing about + // either. assert_eq!( - committed.without_costs(), + committed.without_costs().without_times(), stated, "{}: its committed recording is not the answer the case states", case.name() diff --git a/crates/metal2vulkan-conformance/src/clocks.rs b/crates/metal2vulkan-conformance/src/clocks.rs new file mode 100644 index 000000000..781d83913 --- /dev/null +++ b/crates/metal2vulkan-conformance/src/clocks.rs @@ -0,0 +1,72 @@ +//! The three clocks the per-call cost table reads, and what each one is good for. +//! +//! The suite times both legs at the same boundary ([`crate::watch`]), so the clocks must be cheap +//! enough that reading them does not dominate a 2 us call, and fine enough that a 2 us call is not +//! quantised away. Those two demands are what decided the attribution split, so the measurements +//! are written down here rather than left as a feeling. Taken on this Apple M3 Max, macOS 27.0.1 +//! (26A434), with an optimised C loop of 200,000 reads each: +//! +//! | clock | read | smallest step it reports | +//! |---|---:|---:| +//! | `CLOCK_MONOTONIC` (through [`std::time::Instant`]) | 16 ns | nanoseconds | +//! | `CLOCK_THREAD_CPUTIME_ID` | 95 ns | 125 ns | +//! | `CLOCK_PROCESS_CPUTIME_ID` | 230 ns | **1000 ns** | +//! +//! So the first two are read **per call** and the third is read **per case**. A microsecond step is +//! most of a short call: reading the process clock around a 2 us `setBytes:` would answer 0 or +//! 1 us, and a median of those is a number about the clock rather than about the call. Over a whole +//! case — thousands of calls — the same clock is accurate to a part in a thousand. +//! +//! That is why "our own threads' time" is a per-case attribution and the other two are per-call. +//! It is a property of the instrument, not a choice about what matters. +//! +//! # The instrument's own cost is reported, never subtracted +//! +//! Two reads at each end of a call come to about 220 ns, which is real against a Metal call of a +//! couple of microseconds. It is paid **identically on both legs**, because one wrapper times both, +//! so a ratio carries it in numerator and denominator alike. The `times` command measures the span +//! machinery's cost on the host it runs on and prints it beside the table +//! ([`crate::times::instrument_nanos`]). It is never subtracted from a figure: a measured overhead +//! a reader can see is honest, and an estimate quietly removed from every row is not. + +/// The calling thread's CPU time, user and system, in nanoseconds, or `None` where the host does +/// not answer the clock. +/// +/// This is the thread the case runs on, so a call's reading is what **the caller** burned. The +/// difference between a call's elapsed time and this is the time the caller was not computing: it +/// was waiting. +pub fn thread_cpu_nanos() -> Option { + read(libc::CLOCK_THREAD_CPUTIME_ID) +} + +/// The whole process's CPU time, every thread of it, in nanoseconds, or `None` where the host does +/// not answer the clock. +/// +/// Read once at each end of a case, never per call: its step is a microsecond +/// ([module docs](self)). Minus the calling thread's own, it is the CPU the implementation spent +/// **off** the calling thread — the handoff the plan says must not read as a win. +/// +/// It is the whole process, so on our leg it covers our runtime's threads *and* the driver's, and +/// on the Metal leg it covers Metal's own. That is the honest denominator: the suite compares two +/// whole stacks and has no way to cut one into layers ([`crate::times`]). +pub fn process_cpu_nanos() -> Option { + read(libc::CLOCK_PROCESS_CPUTIME_ID) +} + +/// One POSIX clock, in nanoseconds. `None` where the call failed, which is how a host that does +/// not answer a clock reaches the report as a missing attribution rather than as a zero. +fn read(clock: libc::clockid_t) -> Option { + let mut when = libc::timespec { + tv_sec: 0, + tv_nsec: 0, + }; + // SAFETY: `clock_gettime` writes one `timespec`, which is what it is given, and reads nothing + // else. A clock the host does not know answers -1 and leaves the value alone. + let answered = unsafe { libc::clock_gettime(clock, &mut when) }; + if answered != 0 { + return None; + } + let seconds = u64::try_from(when.tv_sec).ok()?; + let nanos = u64::try_from(when.tv_nsec).ok()?; + seconds.checked_mul(1_000_000_000)?.checked_add(nanos) +} diff --git a/crates/metal2vulkan-conformance/src/coverage.rs b/crates/metal2vulkan-conformance/src/coverage.rs new file mode 100644 index 000000000..f288c9e76 --- /dev/null +++ b/crates/metal2vulkan-conformance/src/coverage.rs @@ -0,0 +1,497 @@ +//! The timing-coverage census: which calls have a cost case, and which are untimed. +//! +//! A per-call cost table over an unknown fraction of the API is a table nobody can act on, so +//! "untimed" is a number tracked and driven down the way "unrecorded" is. The plan's words: *a +//! census over the public API — which calls have a cost case and which do not. Today the honest +//! answer is "most of it".* This module is what makes that answer a figure instead of a feeling. +//! +//! # Two censuses, because they answer different questions, and one is exact +//! +//! **The suite's own vocabulary** ([`Census::side`]) is exact and needs no guessing. Every call a +//! case can make is a method of [`crate::case::Side`], and a `times` run says which of them the +//! selection actually made. A `Side` call no case makes is a hole in the suite's coverage of its +//! own vocabulary, and the list of them is work to do. +//! +//! **The runtime's public surface** ([`Census::runtime`]) is the question a consumer cares about, +//! and it can only be answered approximately from here. A `Side` call reaches the runtime through +//! our own code, which calls further helpers, so knowing which public method a timed call reaches +//! needs a call graph this crate has no business building. What the census does instead is honest +//! and still useful: it counts the public methods of the runtime's **frame surface** — the objects +//! a frame makes its calls on — and says which are **named anywhere** in the suite's own +//! runtime-side sources. +//! +//! That count is an **upper bound** on timed coverage, and the report says so in those words. A +//! method named in our sources is at most reachable by a timed call; a method named nowhere in +//! them cannot possibly be timed. The gap between the two numbers is the actionable figure, and +//! narrowing the upper bound to a real one is a call graph's job, named as the next step rather +//! than quietly assumed away. +//! +//! The frame-surface list is the one `scripts/api-cost-coverage` already uses for the other +//! harness's table, kept the same here deliberately: two censuses over two different denominators +//! would be two numbers nobody can put beside each other. + +use std::collections::BTreeSet; + +/// The objects a frame makes its calls on: the device and its queue, the command buffer, its +/// encoders, the resources they bind and the objects they wait on. +/// +/// The rest of the runtime's surface is descriptors, queries, formats, errors and small value +/// types, whose cost a frame does not pay call by call. The same list as +/// `scripts/api-cost-coverage`'s, so the two censuses share a denominator. +const FRAME: &[&str] = &[ + "Device", + "CommandQueue", + "CommandBuffer", + "RenderCommandEncoder", + "ComputeCommandEncoder", + "BlitCommandEncoder", + "ResourceStateCommandEncoder", + "Buffer", + "Texture", + "Heap", + "SharedEvent", + "Event", + "Fence", + "IndirectCommandBuffer", + "IndirectRenderCommand", + "IndirectComputeCommand", + "ArgumentEncoder", +]; + +/// The suite's own sources that drive the runtime: where a public runtime method is named if the +/// suite reaches it at all. +const DRIVING: &[&str] = &[ + "runtime_side.rs", + "runtime_work.rs", + "render.rs", + "work.rs", + "texture.rs", + "texture_query.rs", + "queue_slots.rs", + "event_orders.rs", + "handler_waits.rs", + "scheduled_handlers.rs", + "shared_events.rs", + "device.rs", + "replay.rs", +]; + +/// How much of the call surface the selection times. +#[derive(Clone, Debug)] +pub struct Census { + /// The rounds the measurement behind it took. + pub rounds: u32, + /// The venue it was measured on. + pub venue: String, + /// The suite's own vocabulary: every [`crate::case::Side`] call the timing wrapper opens a + /// span for, and how many times the selection made it. + pub side: Vec<(String, u64)>, + /// The `Side` calls the timing wrapper forwards **without** a span, so no selection can time + /// them. They are listed rather than counted as holes: a census that reports a gap which is a + /// decision is a census nobody can act on. Read from the wrapper's own source, so a call a + /// stream forwards without a span appears here instead of vanishing. + pub unspanned: Vec, + /// The `Side` calls the timing wrapper does not forward at all. **A defect, never a gap**: a + /// `Side` method has a default answering `Failure::unavailable`, so an unforwarded one answers + /// "no such call" where the side answers fine — and in a cost table it reads as a free call. + /// `tests::the_announcing_side_forwards_every_call` fails on a non-empty list: one guard + /// over the one forwarding impl, rather than a second copy of it here. + pub unforwarded: Vec, + /// The runtime's frame surface: every public method, and whether the suite's own sources name + /// it at all. + pub runtime: Vec<(String, bool)>, +} + +impl Census { + /// Take the census over `measured`. + pub fn of(measured: &crate::times::Measurement) -> Result { + let timed = timed_calls(measured); + let forwarded = forwarded_calls()?; + let mut side = Vec::new(); + let mut unspanned = Vec::new(); + let mut unforwarded = Vec::new(); + for call in side_calls()? { + match forwarded.iter().find(|(name, _)| *name == call) { + Some((_, true)) => { + let calls = timed.get(&call).copied().unwrap_or(0); + side.push((call, calls)); + } + Some((_, false)) => unspanned.push(call), + None => unforwarded.push(call), + } + } + let named = named_in_the_suite()?; + let runtime = frame_surface()? + .into_iter() + .map(|method| { + let reached = named.contains(method.split("::").nth(1).unwrap_or(&method)); + (method, reached) + }) + .collect(); + Ok(Self { + rounds: measured.rounds, + venue: measured.venue.clone(), + side, + unspanned, + unforwarded, + runtime, + }) + } + + /// The `Side` calls the selection never made. + pub fn untimed_side(&self) -> Vec<&str> { + self.side + .iter() + .filter(|(_, calls)| *calls == 0) + .map(|(call, _)| call.as_str()) + .collect() + } + + /// The runtime's frame-surface methods the suite's own sources never name, so no case can be + /// timing them. + pub fn untouched_runtime(&self) -> Vec<&str> { + self.runtime + .iter() + .filter(|(_, reached)| !reached) + .map(|(method, _)| method.as_str()) + .collect() + } + + /// The census, as the command prints it. + pub fn render(&self) -> String { + let mut out = String::new(); + let timed = self.side.len() - self.untimed_side().len(); + let reached = self.runtime.len() - self.untouched_runtime().len(); + out.push_str(&format!( + "timing coverage, over {} round(s) of the selection on {}\n\n", + self.rounds, self.venue + )); + out.push_str(&format!( + "the suite's own vocabulary: {timed} of the {} Side call(s) the timing wrapper spans \ + are timed by this selection\n", + self.side.len() + )); + if !self.unspanned.is_empty() { + out.push_str(&format!( + " {} more are forwarded without a span on purpose, so they are not holes: {}\n", + self.unspanned.len(), + self.unspanned.join(", ") + )); + } + if !self.unforwarded.is_empty() { + out.push_str(&format!( + " {} Side call(s) the wrapper does not forward at all, which is a DEFECT: {}\n", + self.unforwarded.len(), + self.unforwarded.join(", ") + )); + } + out.push_str(&format!( + "the runtime's frame surface: {reached} of {} public method(s) are named anywhere in \ + the suite's runtime-side sources\n", + self.runtime.len() + )); + out.push_str( + " that second figure is an UPPER BOUND on timed coverage, not a measurement of it: a \ + method our sources\n name is at most reachable by a timed call, while one they never \ + name cannot be timed at all. Narrowing it\n to a real figure needs a call graph; the \ + gap is the work.\n", + ); + let untimed = self.untimed_side(); + if untimed.is_empty() { + out.push_str("\nevery Side call is timed by this selection\n"); + } else { + out.push_str(&format!( + "\n{} Side call(s) no case in this selection makes, so nothing times them:\n", + untimed.len() + )); + for call in untimed { + out.push_str(&format!(" {call}\n")); + } + } + let untouched = self.untouched_runtime(); + if untouched.is_empty() { + out.push_str("\nthe suite's sources name every frame-surface method\n"); + } else { + out.push_str(&format!( + "\n{} frame-surface method(s) the suite's sources never name, so no case can time \ + them:\n", + untouched.len() + )); + for method in untouched { + out.push_str(&format!(" {method}\n")); + } + } + out + } +} + +/// How many times the measurement saw each call, by name. +fn timed_calls(measured: &crate::times::Measurement) -> std::collections::BTreeMap { + let mut seen = std::collections::BTreeMap::new(); + for case in &measured.cases { + for call in &case.per_call { + let held = seen.entry(call.call.clone()).or_insert(0); + *held += call.most_calls; + } + } + seen +} + +/// Every `Side` method the timing wrapper forwards, and whether it opens a span, read from +/// `watch.rs`'s own source. +/// +/// Read rather than listed for the same reason [`side_calls`] is: a list would rot, and it would +/// rot the flattering way, by making a forgotten method look like a decision. +fn forwarded_calls() -> Result, String> { + let source = read_source("watch.rs")?; + let start = source + .find("impl Side for Watching {") + .ok_or("watch.rs holds no `impl Side for Watching {`")?; + let body = &source[start..]; + let end = body + .find("\n}\n") + .ok_or("watch.rs's forwarding impl has no close at the left margin")?; + let body = &body[..end]; + let mut found = Vec::new(); + let mut name = String::new(); + for line in body.lines() { + if let Some(rest) = line.strip_prefix(" fn ") { + if !name.is_empty() { + found.push((std::mem::take(&mut name), false)); + } + name = rest + .chars() + .take_while(|letter| letter.is_ascii_alphanumeric() || *letter == '_') + .collect(); + continue; + } + // A span whose name is not the method's would attribute one call's cost to another, so + // the name is matched and not merely the call to `watch`. + if !name.is_empty() && line.contains(&format!("self.watch(\"{name}\")")) { + found.push((std::mem::take(&mut name), true)); + } + } + if !name.is_empty() { + found.push((name, false)); + } + Ok(found) +} + +/// Every method of [`crate::case::Side`], read from its own source. +/// +/// Read rather than listed, because a list here would be a second copy of the trait and would rot +/// the first time a stream added a call — and it would rot the **safe** way, by making coverage +/// look complete. +fn side_calls() -> Result, String> { + let source = read_source("case.rs")?; + let start = source + .find("pub trait Side {") + .ok_or("case.rs holds no `pub trait Side {`")?; + let body = &source[start..]; + let end = body + .find("\n}\n") + .ok_or("case.rs's `pub trait Side` has no close at the left margin")?; + Ok(methods_at_indent(&body[..end], " fn ")) +} + +/// Every public method of the runtime's frame surface, as `Type::method`. +fn frame_surface() -> Result, String> { + let root = runtime_src()?; + let mut found = Vec::new(); + for file in rust_files(&root)? { + let source = std::fs::read_to_string(&file) + .map_err(|error| format!("{}: {error}", file.display()))?; + for (kind, body) in inherent_impls(&source) { + if !FRAME.contains(&kind.as_str()) { + continue; + } + for method in methods_at_indent(&body, " pub fn ") { + found.push(format!("{kind}::{method}")); + } + for method in methods_at_indent(&body, " pub unsafe fn ") { + found.push(format!("{kind}::{method}")); + } + } + } + found.sort(); + found.dedup(); + Ok(found) +} + +/// Every identifier the suite's own runtime-side sources call as a method (`.name(`). +/// +/// A textual reach, deliberately: it answers "could the suite possibly be timing this" and never +/// "is it", which is what [`Census::runtime`] is documented to mean. +fn named_in_the_suite() -> Result, String> { + let mut named = BTreeSet::new(); + for file in DRIVING { + let source = read_source(file)?; + let mut rest = source.as_str(); + while let Some(at) = rest.find('.') { + rest = &rest[at + 1..]; + let name: String = rest + .chars() + .take_while(|letter| letter.is_ascii_alphanumeric() || *letter == '_') + .collect(); + if !name.is_empty() && rest[name.len()..].starts_with('(') { + named.insert(name); + } + } + } + Ok(named) +} + +/// The names of the methods `body` declares with the prefix `head` at one indent. +fn methods_at_indent(body: &str, head: &str) -> Vec { + body.lines() + .filter_map(|line| { + let rest = line.strip_prefix(head)?; + let name: String = rest + .chars() + .take_while(|letter| letter.is_ascii_alphanumeric() || *letter == '_') + .collect(); + (!name.is_empty()).then_some(name) + }) + .collect() +} + +/// Each inherent `impl Type {` block of `source`, as its type's name and its body. +/// +/// A trait impl (`impl Trait for Type`) is not part of the named surface, and neither is anything +/// indented, which in this tree is inside a function or a module. +fn inherent_impls(source: &str) -> Vec<(String, String)> { + let mut found = Vec::new(); + for (index, line) in source.lines().enumerate() { + let Some(rest) = line.strip_prefix("impl") else { + continue; + }; + if !line.ends_with('{') { + continue; + } + // `impl<'a> Type<'a> {`: step over the generics, then take the type's name. + let rest = rest.trim_start(); + let rest = match rest.strip_prefix('<') { + Some(after) => match after.find('>') { + Some(close) => after[close + 1..].trim_start(), + None => continue, + }, + None => rest, + }; + let kind: String = rest + .chars() + .take_while(|letter| letter.is_ascii_alphanumeric() || *letter == '_') + .collect(); + if kind.is_empty() || rest[kind.len()..].trim_start().starts_with("for ") { + continue; + } + // The block runs to the next `}` at the left margin. + let body: String = source + .lines() + .skip(index + 1) + .take_while(|line| *line != "}") + .collect::>() + .join("\n"); + found.push((kind, body)); + } + found +} + +/// Every `.rs` file under `root`, recursively. +fn rust_files(root: &std::path::Path) -> Result, String> { + let mut found = Vec::new(); + let mut to_read = vec![root.to_path_buf()]; + while let Some(directory) = to_read.pop() { + let entries = std::fs::read_dir(&directory) + .map_err(|error| format!("{}: {error}", directory.display()))?; + for entry in entries { + let entry = entry.map_err(|error| format!("{}: {error}", directory.display()))?; + let path = entry.path(); + if path.is_dir() { + to_read.push(path); + } else if path.extension().is_some_and(|kind| kind == "rs") { + found.push(path); + } + } + } + found.sort(); + Ok(found) +} + +/// One of the suite's own sources, read from the tree this crate was built in. +/// +/// The census reads sources, so it needs the tree. This crate is never published +/// (`publish = false`), so its manifest directory is always a checkout. +fn read_source(file: &str) -> Result { + let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("src") + .join(file); + std::fs::read_to_string(&path).map_err(|error| format!("{}: {error}", path.display())) +} + +/// The runtime crate's sources, beside this crate's in the workspace. +fn runtime_src() -> Result { + let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../metal2vulkan-runtime/src"); + path.canonicalize() + .map_err(|error| format!("{}: {error}", path.display())) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A span's name is the method's name, in every forwarded method that opens one. + /// + /// A span named for another call would attribute one call's cost to a different row, which is + /// a wrong table rather than a missing one. [`forwarded_calls`] matches the name, so a + /// mismatch reaches this test as a call with no span. + #[test] + fn the_only_calls_without_a_span_are_the_two_that_are_not_the_implementations() { + let unspanned: Vec = forwarded_calls() + .unwrap() + .into_iter() + .filter(|(_, spanned)| !*spanned) + .map(|(name, _)| name) + .collect(); + assert_eq!( + unspanned, + ["venue", "announced"], + "the set of Side calls the timing wrapper does not measure has changed; either a span \ + was dropped or its name no longer matches its method" + ); + } + + /// The runtime's frame surface is read from the runtime's own sources, so the census's + /// denominator cannot be a stale list. + #[test] + fn the_frame_surface_is_read_from_the_runtime() { + let surface = frame_surface().unwrap(); + assert!( + surface.len() > 100, + "the frame surface came out at {} methods, so the parse found almost nothing", + surface.len() + ); + for expected in ["Texture::width", "Buffer::length", "Device::name"] { + assert!( + surface.iter().any(|method| method == expected), + "{expected} is not in the frame surface the census read" + ); + } + // Every entry is `Type::method` of a frame type, never a free function or a trait impl's. + for method in &surface { + let (kind, _) = method + .split_once("::") + .unwrap_or_else(|| panic!("{method}")); + assert!(FRAME.contains(&kind), "{method} is not a frame type's"); + } + } + + /// The suite's own driving sources are all read: a file named here that no longer exists would + /// silently shrink the census's numerator and make coverage look worse than it is. + #[test] + fn every_driving_source_the_census_names_exists() { + for file in DRIVING { + read_source(file).unwrap_or_else(|why| panic!("{file}: {why}")); + } + assert!(!named_in_the_suite().unwrap().is_empty()); + } +} diff --git a/crates/metal2vulkan-conformance/src/lib.rs b/crates/metal2vulkan-conformance/src/lib.rs index ad79dcd6f..d7b87ba98 100644 --- a/crates/metal2vulkan-conformance/src/lib.rs +++ b/crates/metal2vulkan-conformance/src/lib.rs @@ -42,8 +42,10 @@ pub mod allowance; pub mod buffer_texture; pub mod case; pub mod cases; +pub mod clocks; pub mod compare; pub mod cost; +pub mod coverage; pub mod device; pub mod diff; pub mod event_orders; @@ -66,9 +68,11 @@ pub mod sparse_query; pub mod surface; pub mod texture; pub mod texture_query; +pub mod times; pub mod transcript; pub mod validated; pub mod verdict; +pub mod watch; pub mod work; #[cfg(target_os = "macos")] @@ -89,6 +93,7 @@ pub use cost::{CostBound, CostRecord, CostVerdict, Counts, Region}; pub use recording::{Recording, SUITE_VERSION}; pub use replay::{replay, replay_against, Replayed}; pub use report::Report; +pub use times::{CallTimes, CaseTimes, Leg, TimeRecord, TimeVerdict}; pub use transcript::{Node, Observed, Sites, Transcript, Value}; pub use verdict::Verdict; diff --git a/crates/metal2vulkan-conformance/src/recording.rs b/crates/metal2vulkan-conformance/src/recording.rs index c1352a88d..e92088d40 100644 --- a/crates/metal2vulkan-conformance/src/recording.rs +++ b/crates/metal2vulkan-conformance/src/recording.rs @@ -298,6 +298,22 @@ pub struct Recording { /// none, and reads as `Unmeasured`. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub costs: Vec, + /// What **each leg** cost in time over the case, per leg and venue ([`crate::times`]): the + /// per-call and per-case figures a `times` run measured. + /// + /// It is here for one reason the counts half does not have: **Metal's own cost on a given + /// macOS build cannot be re-taken later.** A measurement of ours is one command away on any + /// host; what Metal charged for a call on 26A434 is gone the moment the machine updates. This + /// is the plan's standing property — that a year of Metal measurements stops evaporating — + /// applied to cost. + /// + /// Nothing compares a stored figure with a live one. A time comparison is only ever made + /// between two legs measured in the same run, on one machine, from the identical transcript + /// ([`crate::times::judge`]); off this Mac the stored Metal figures are another machine's, and + /// even here they are another moment's. A recording taken before the times half existed holds + /// none, which is a reported hole and never a failure. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub times: Vec, } impl Recording { @@ -310,6 +326,7 @@ impl Recording { shaders, answers, costs: Vec::new(), + times: Vec::new(), } } @@ -333,6 +350,19 @@ impl Recording { self } + /// The same recording with the times half dropped, for the same reason + /// [`Recording::without_costs`] exists and never folded into it, because the two names would + /// then each describe half of what the one call does. + /// + /// A time is our own measurement of a run on a venue, written by the `times` command. A case + /// states nothing about it, so a test that ties a committed recording to the answer its case + /// states drops this half as well. + #[must_use] + pub fn without_times(mut self) -> Self { + self.times = Vec::new(); + self + } + /// The answer for the venue's declared Metal `level`, or why there is none. /// /// The two outcomes are kept apart because they mean different things. A recording of another diff --git a/crates/metal2vulkan-conformance/src/run.rs b/crates/metal2vulkan-conformance/src/run.rs index dde8755e7..f07daf7fa 100644 --- a/crates/metal2vulkan-conformance/src/run.rs +++ b/crates/metal2vulkan-conformance/src/run.rs @@ -469,3 +469,261 @@ pub fn validated_leg(case: &dyn Case) -> Result<(), String> { let _ = case.run(&mut side, &mut sites); Ok(()) } + +/// Measure what `cases` cost **on our stack** on the venue `venues` names, over `rounds` rounds. +/// +/// The measurement's shape is the cost half's, for the same reasons measured there: the whole +/// selection in its own order, because the runtime pools command pools, memory blocks and +/// descriptor sets across cases, and **a fresh device each round**, because a warm recycler is not +/// what a first run meets. +/// +/// This leg and [`metal_times`] are run as two phases rather than case by case, and the reason is +/// a measurement hazard rather than tidiness: the `elsewhere` attribution reads the **whole +/// process's** CPU, so interleaving the legs would put Metal's own threads inside our cases' +/// readings and ours inside Metal's. Phases confine that to the first case or two of a phase. The +/// per-call elapsed and calling-thread figures — the table a reader acts on — are of the calling +/// thread alone and are not affected either way. `--leg` runs one leg in a process of its own, +/// which is the only way to read `elsewhere` with nothing of the other leg in it. +pub fn times_on_under( + venues: Venues, + policy: Policy, + cases: &[Box], + rounds: u32, +) -> Result { + let instrument = crate::times::instrument_nanos(); + let mut venue = String::new(); + let mut taken: Vec> = Vec::new(); + for _ in 0..rounds.max(1) { + let notices = Notices::default(); + let cache = ScratchCache::new().map_err(|error| error.to_string())?; + let device = device::open_under(venues, policy, ¬ices, &cache)?; + // The notices the device announced as it was made are the venue's, not any case's. + notices.take(); + venue = device.name().to_owned(); + let mut round = Vec::with_capacity(cases.len()); + for case in cases { + let taker = notices.clone(); + let side = RuntimeSide::new(&device, move || taker.take()); + round.push(timed(case.as_ref(), side)?); + } + taken.push(round); + } + Ok(crate::times::fold( + crate::times::Leg::Ours, + venue, + rounds.max(1), + instrument, + cases, + &taken, + )) +} + +/// Measure what `cases` cost **on native Metal** on this Mac, over `rounds` rounds. +/// +/// A case record mode must not run on Metal is not run here either, and for the same reason: the +/// safety rule is about what the suite asks Metal to do, not about which command asks it. A case +/// whose Metal leg would end the process or fault the device is left with no Metal figures, which +/// reads as an unmeasured row rather than as a fast one. +#[cfg(target_os = "macos")] +pub fn metal_times( + cases: &[Box], + rounds: u32, +) -> Result { + let instrument = crate::times::instrument_nanos(); + let mut venue = String::new(); + let mut taken: Vec> = Vec::new(); + for _ in 0..rounds.max(1) { + let mut round = Vec::with_capacity(cases.len()); + for case in cases { + if let Some(why) = metal_leg_refused(case.as_ref()) { + round.push(crate::times::CaseRound { + stopped: Some(why), + ..Default::default() + }); + continue; + } + // Every Metal call that answers an object answers an **autoreleased** one, and this + // process drains no pool of its own, so a case's objects would live to the end of the + // command and a few hundred cases of them would hold every queue slot Metal has. The + // pool is drained after the case's window is read, so its own cost is outside the + // measurement. + let (side, measured) = objc2::rc::autoreleasepool(|_| { + let side = crate::metal_side::MetalSide::new(); + match side { + Ok(side) => { + let taken = timed(case.as_ref(), side); + (Ok(()), taken) + } + Err(why) => (Err(why), Ok(crate::times::CaseRound::default())), + } + }); + match side { + Ok(()) => round.push(measured?), + Err(why) => { + return Err(format!("{}: no Metal side: {why}", case.name())); + } + } + } + venue = "native Metal".to_owned(); + taken.push(round); + } + Ok(crate::times::fold( + crate::times::Leg::Metal, + venue, + rounds.max(1), + instrument, + cases, + &taken, + )) +} + +/// Why the Metal leg must not run `case`, where it must not. +/// +/// The two sources the suite already holds for this: a row Metal never returned from, and a +/// carried answer whose case says re-recording it on Metal is not safe. +#[cfg(target_os = "macos")] +fn metal_leg_refused(case: &dyn Case) -> Option { + match case.metal_source() { + crate::case::MetalSource::Run => None, + crate::case::MetalSource::Carried { re_record, .. } => match re_record { + crate::case::ReRecord::Allowed => None, + crate::case::ReRecord::Forbidden { reason } => Some(format!( + "the case forbids running its Metal leg here: {reason}" + )), + }, + crate::case::MetalSource::DidNotReturn { call, says, .. } => { + Some(format!("Metal does not return from {call}: {says}")) + } + } +} + +/// Run one case on `side`, measuring every call it makes. +/// +/// The span is the [`crate::watch`] wrapper's, so both legs are measured at one boundary: around +/// the Metal or Vulkan call and the side's own handle bookkeeping, and outside the transcript, the +/// fixtures and the input fingerprint. A cost comparison of two legs measured in different places +/// would not be a comparison, and one wrapper is how that cannot happen. +/// +/// The case's window is closed **before** the side is dropped, so tearing a device down is not +/// charged to the case's calls on either leg. +fn timed(case: &dyn Case, side: S) -> Result { + use crate::times::Timer; + let timer = Timer::new(); + let mut side = crate::watch::Watching::with(side, timer.clone()); + let mut sites = crate::transcript::Sites::new(); + let inputs = case + .inputs() + .map_err(|why| format!("{}: {why}", case.name()))?; + sites.push(crate::case::inputs_node(&inputs)); + let process_cpu_before = crate::clocks::process_cpu_nanos(); + let on_cpu_before = crate::clocks::thread_cpu_nanos(); + let started = std::time::Instant::now(); + let abort = case.run(&mut side, &mut sites).err(); + let window_wall = u64::try_from(started.elapsed().as_nanos()).unwrap_or(u64::MAX); + let on_cpu_after = crate::clocks::thread_cpu_nanos(); + let process_cpu_after = crate::clocks::process_cpu_nanos(); + let observed = timer.take(); + let mut degraded = side.announced(); + degraded.extend(sites.finish().announced_notices().into_keys()); + degraded.sort(); + degraded.dedup(); + let stopped = abort.map(|abort| { + let what = abort + .failure + .lacks + .as_deref() + .unwrap_or("a call did not answer"); + format!("{what}, at {}", abort.at) + }); + Ok(crate::times::CaseRound { + observed, + window_wall, + window_on_cpu: span(on_cpu_before, on_cpu_after), + window_process_cpu: span(process_cpu_before, process_cpu_after), + stopped, + degraded, + }) +} + +/// The nanoseconds between two readings of one clock, or zero where the host answered neither. +fn span(before: Option, after: Option) -> u64 { + match (before, after) { + (Some(before), Some(after)) => after.saturating_sub(before), + _ => 0, + } +} + +/// Write what `metal` and `ours` measured into the cases' own recordings, answering where each +/// went or why it could not be written. +/// +/// A leg whose round **stopped** before the case finished is not written: its calls are a part of +/// the case. A leg that announced a degrade notice **is** written, with the codes beside the +/// figures, because the figures are a true measurement of what that device did — it is the +/// *comparison* that the notices rule out, and [`crate::times::judge`] is where that happens. +pub fn record_times( + metal: Option<&crate::times::Measurement>, + ours: Option<&crate::times::Measurement>, + words: &str, +) -> Vec<(String, Result)> { + let mut names: Vec<&str> = Vec::new(); + for measured in [metal, ours].into_iter().flatten() { + for case in &measured.cases { + if !names.contains(&case.case.as_str()) { + names.push(&case.case); + } + } + } + names + .into_iter() + .map(|name| (name.to_owned(), record_one_time(name, metal, ours, words))) + .collect() +} + +/// Put one case's time records in its recording, replacing this machine's records for the legs +/// measured and keeping every other machine's. +fn record_one_time( + case: &str, + metal: Option<&crate::times::Measurement>, + ours: Option<&crate::times::Measurement>, + words: &str, +) -> Result { + use crate::times::TimeRecord; + let mut recording = crate::recording::read(case)?; + let mut written = 0; + for measured in [metal, ours].into_iter().flatten() { + let Some(times) = measured.case(case) else { + continue; + }; + // A leg that did not finish the case keeps nothing, and that is not an error for the + // case: the other leg may still have figures worth keeping, and a case whose Metal leg + // the safety rule refuses is exactly that shape. + if times.stopped.is_some() { + continue; + } + let record = TimeRecord { + leg: measured.leg, + venue: measured.venue.clone(), + chip: crate::recording::ORACLE_CHIP.to_owned(), + os_build: crate::recording::ORACLE_OS_BUILD.to_owned(), + rounds: measured.rounds, + measured: words.to_owned(), + instrument: measured.instrument, + times: times.clone(), + }; + recording.times.retain(|held| { + held.leg != record.leg + || held.venue != record.venue + || held.chip != record.chip + || held.os_build != record.os_build + }); + recording.times.push(record); + written += 1; + } + if written == 0 { + return Err("neither leg finished the case, so there is nothing to keep".to_owned()); + } + recording + .times + .sort_by(|one, two| (one.leg, &one.venue).cmp(&(two.leg, &two.venue))); + crate::recording::write(&recording) +} diff --git a/crates/metal2vulkan-conformance/src/tests.rs b/crates/metal2vulkan-conformance/src/tests.rs index 02fe45ad0..c7e0af269 100644 --- a/crates/metal2vulkan-conformance/src/tests.rs +++ b/crates/metal2vulkan-conformance/src/tests.rs @@ -1475,10 +1475,11 @@ fn the_rate_map_cases_name_what_justifies_them() { } } -/// The announcing side forwards **every** `Side` call, and this is what keeps it from rotting. +/// The one forwarding wrapper forwards **every** `Side` call, and this is what keeps it from +/// rotting. /// /// `Side` gives most of its calls a default that answers `Failure::unavailable`, so a method the -/// announcing wrapper forgets to forward makes `Announcing` answer "no such call" where +/// wrapper forgets to forward makes `Announcing` answer "no such call" where /// `MetalSide` answers perfectly well — and the compiler says nothing, because the default is /// there to be inherited. The trait grows with every ported batch, so the guard must be mechanical /// rather than a list somebody remembers to extend. @@ -1510,21 +1511,25 @@ fn the_announcing_side_forwards_every_call() { .collect() } let declared = methods(include_str!("case.rs"), "\npub trait Side {"); + // One forwarding impl serves every call-boundary watcher — the announcing one and the timing + // one — so this guard covers both. Two hand-written wrappers would have been two places to + // forget a method, and in the cost table a forgotten method reads as a *free* call. let forwarded = methods( - include_str!("validated.rs"), - "\nimpl Side for Announcing {", + include_str!("watch.rs"), + "\nimpl Side for Watching {", ); assert!(declared.len() > 10, "the trait was not found: {declared:?}"); let missing: Vec<&String> = declared.difference(&forwarded).collect(); assert!( missing.is_empty(), - "validated::Announcing does not forward {missing:?}, so it answers Unavailable where the \ - side it wraps answers. Forward each of them." + "watch::Watching does not forward {missing:?}, so it answers Unavailable where the \ + side it wraps answers, and a cost table would read each as a free call. Forward each of \ + them." ); let extra: Vec<&String> = forwarded.difference(&declared).collect(); assert!( extra.is_empty(), - "Announcing forwards {extra:?}, which Side no longer declares" + "watch::Watching forwards {extra:?}, which Side no longer declares" ); } diff --git a/crates/metal2vulkan-conformance/src/times.rs b/crates/metal2vulkan-conformance/src/times.rs new file mode 100644 index 000000000..5281fc327 --- /dev/null +++ b/crates/metal2vulkan-conformance/src/times.rs @@ -0,0 +1,1380 @@ +//! The times half: what a call costs on native Metal, beside what the same call costs on our +//! stack, over the same case. +//! +//! The suite is the right place for this because **a case is one write and both legs run it from +//! the identical transcript**: [`crate::metal_side::MetalSide`] drives native Metal and +//! [`crate::runtime_side::RuntimeSide`] drives ours, from the same [`crate::case::Case`], on one +//! machine, back to back. Nothing else in the project compares the two over the same work. +//! +//! # What a difference here is, and what it is not +//! +//! **Read this before quoting a number.** On this Mac our leg is translation, then our runtime, +//! then MoltenVK, then Metal underneath; the Metal leg is Metal. A row's difference is therefore +//! the cost of **that whole chain against native Metal**, and it does **not** attribute to a layer +//! of it. The suite cannot say what MoltenVK's share is, and no figure here licenses a sentence of +//! the form "MoltenVK costs X" or "our runtime costs Y". Separating the shares needs either +//! counters inside each layer or the same case on a non-Apple driver to difference against, and +//! this round is one machine. The ratio is honest and the attribution to a layer would not be. +//! +//! What a row **does** license: this case's calls cost N times what Metal's do, here, today, over +//! this many rounds. That is the number the project has never had. +//! +//! # Three attributions, kept apart, because moving work between them is not a win +//! +//! A call that returns at once and hands its work to a thread the caller must then wait on has +//! saved nothing. So each measurement is three numbers, never one: +//! +//! - **on cpu** — the calling thread's own CPU time inside the call. What the caller burned. +//! - **blocked** — the call's elapsed time less that. What the caller waited for. +//! - **elsewhere** — CPU the rest of the process burned over the case. What was handed off. +//! +//! The first two are per call; the third is per case, because the process clock's step is a +//! microsecond and a per-call reading of it would be a number about the clock +//! ([`crate::clocks`]). `on cpu + blocked` is exactly what the caller paid at the call boundary; +//! `elsewhere` is work the machine did that the caller may pay for in a later call. +//! +//! The quantity a margin is judged on is **`wall + elsewhere` summed over the case**: everything +//! the machine spent on the case's calls, however attributed. Nothing can lower it by moving work +//! from one attribution to another, which is the whole point of keeping the three apart. +//! +//! # Reported, not gated +//! +//! A time is not assertable: this machine runs other work, and the counters half exists precisely +//! because counts are the things a gate can hold ([`crate::cost`]). So every figure here is +//! reported. [`MARGIN`] is the one judgement the plan allows — an order of magnitude, which is +//! this project's actual failure mode — and it is computed and printed as a verdict +//! ([`TimeVerdict`]) while deliberately **not** deciding any exit status yet: the measurement +//! discipline a gate needs (a quiet machine, the contrast between a case alone and in company, +//! enough rounds for a rare arm) has not been paid for times the way it was for counts. Turning it +//! on is a later, separate commit, and `README.md` says what that commit has to show first. +//! +//! # The degraded-set rule, which matters more here than for counts +//! +//! A case whose run announced a degrade notice did a **different amount of work** from Metal's +//! leg: the device lacked the exact form and the runtime did something cheaper and said so. Its +//! cost is therefore not comparable with Metal's, and the row is +//! [`TimeVerdict::Unmeasured`] rather than a fast row. Without that rule a device's honest gap +//! reads as a cost win, which is the most flattering lie the suite could tell. + +use crate::watch::Watcher; +use serde::{Deserialize, Serialize}; +use std::cell::RefCell; +use std::collections::BTreeMap; +use std::rc::Rc; +use std::time::Instant; + +/// The margin a row is judged against: our leg may cost an order of magnitude more than Metal's +/// before the row reads [`TimeVerdict::Over`]. +/// +/// Ten, and not a tighter number, for two reasons the project has evidence for. A tighter margin +/// is not measurable on a machine running other work. And an order of magnitude is the size of +/// every per-call cost bug this project has actually had: 77.3 us a draw against 2.39, and 57.8 +/// against 4.11. A margin that fires on 40% would fire on load; this one fires on the shape of bug +/// we keep finding. +pub const MARGIN: u64 = 10; + +/// Which leg a measurement is of. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Leg { + /// Native Metal, through `objc2-metal`. + Metal, + /// Our stack: the translator, the runtime, and whatever Vulkan implementation the venue is. + Ours, +} + +impl Leg { + /// The word the report and the record use. + pub fn label(self) -> &'static str { + match self { + Leg::Metal => "metal", + Leg::Ours => "ours", + } + } +} + +impl std::fmt::Display for Leg { + fn fmt(&self, out: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + out.write_str(self.label()) + } +} + +/// One call, measured. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Observation { + /// The [`crate::case::Side`] call's name, as [`crate::watch`] names it. + pub call: &'static str, + /// Elapsed nanoseconds inside the call. + pub wall: u64, + /// The calling thread's own CPU nanoseconds inside the call. Zero where the host answers no + /// thread clock, which [`Measurement::cpu_clock`] says rather than implying. + pub on_cpu: u64, +} + +impl Observation { + /// The nanoseconds the caller waited rather than computed: elapsed less its own CPU time. + /// + /// Floored at zero. The two clocks are not read at the same instant and the thread clock's + /// step is 125 ns, so a call that computes throughout can read a hair over its own elapsed + /// time; that is instrument noise and never negative waiting. + pub fn blocked(&self) -> u64 { + self.wall.saturating_sub(self.on_cpu) + } +} + +/// What a leg cost over one case in one round. +#[derive(Clone, Debug, Default)] +pub struct CaseRound { + /// Every call the case made, in order. + pub observed: Vec, + /// Elapsed nanoseconds over the whole case, calls and the harness's work between them. + pub window_wall: u64, + /// The calling thread's CPU nanoseconds over the whole case. + pub window_on_cpu: u64, + /// The whole process's CPU nanoseconds over the whole case, every thread of it. + pub window_process_cpu: u64, + /// Why the run stopped before the case finished, where it did. + pub stopped: Option, + /// The degrade-notice codes the run announced, sorted. + pub degraded: Vec, +} + +impl CaseRound { + /// CPU the process burned **off** the calling thread over the case: the handoff. + /// + /// Floored at zero, because the two clocks are read a few hundred nanoseconds apart. + pub fn elsewhere(&self) -> u64 { + self.window_process_cpu.saturating_sub(self.window_on_cpu) + } + + /// The nanoseconds spent inside the case's calls, summed. + pub fn in_calls(&self) -> u64 { + self.observed.iter().map(|one| one.wall).sum() + } + + /// What a margin is judged on: everything the machine spent on the case's calls, however + /// attributed. See the [module docs](self). + pub fn spend(&self) -> u64 { + self.in_calls().saturating_add(self.elsewhere()) + } +} + +/// The log a [`Timer`] writes into, shared with every span it has handed out. +#[derive(Clone, Debug, Default)] +pub struct Log { + observed: Vec, +} + +/// A [`Watcher`] that measures each call. +/// +/// It holds its log through an [`Rc`] rather than owning it, because a span must not borrow the +/// watcher: the wrapper holds the span across the forwarded call, and that call needs the wrapped +/// side mutably. +#[derive(Clone, Debug, Default)] +pub struct Timer { + log: Rc>, +} + +impl Timer { + /// A timer and the log it writes into. + pub fn new() -> Self { + Self::default() + } + + /// Everything measured so far, and the log emptied. + pub fn take(&self) -> Vec { + std::mem::take(&mut self.log.borrow_mut().observed) + } + + /// How many calls have been measured. + pub fn len(&self) -> usize { + self.log.borrow().observed.len() + } + + /// Whether nothing has been measured. + pub fn is_empty(&self) -> bool { + self.len() == 0 + } +} + +impl Watcher for Timer { + type Span = Span; + + fn enter(&self, call: &'static str) -> Span { + // Read the CPU clock first and the wall clock last, so the wall span is the inner of the + // two and the CPU clock's own cost falls outside it rather than inside the call's elapsed + // time. The reverse at the other end, for the same reason. + Span { + log: Rc::clone(&self.log), + call, + on_cpu: crate::clocks::thread_cpu_nanos(), + started: Instant::now(), + } + } +} + +/// One call's measurement, open until the call returns. +pub struct Span { + log: Rc>, + call: &'static str, + on_cpu: Option, + started: Instant, +} + +impl Drop for Span { + fn drop(&mut self) { + let wall = u64::try_from(self.started.elapsed().as_nanos()).unwrap_or(u64::MAX); + let on_cpu = match (self.on_cpu, crate::clocks::thread_cpu_nanos()) { + (Some(before), Some(after)) => after.saturating_sub(before), + _ => 0, + }; + self.log.borrow_mut().observed.push(Observation { + call: self.call, + wall, + on_cpu, + }); + } +} + +/// What the instrument itself costs on this host, in nanoseconds a call, measured now. +/// +/// It is the whole span machinery — both clock reads at each end and the push into the log — so it +/// is the number to subtract mentally from a very short call. It is **not** subtracted from any +/// figure ([`crate::clocks`]), and it is paid identically on both legs, so a ratio carries it top +/// and bottom. +pub fn instrument_nanos() -> u64 { + const ROUNDS: usize = 20_000; + let timer = Timer::new(); + let started = Instant::now(); + for _ in 0..ROUNDS { + drop(timer.enter("calibration")); + } + let took = u64::try_from(started.elapsed().as_nanos()).unwrap_or(u64::MAX); + timer.take(); + took / ROUNDS as u64 +} + +/// The middle value of `values`, which is sorted in place. Zero for nothing. +/// +/// The lower middle for an even count, so a median is always one of the readings taken rather than +/// a mean of two. +fn median(values: &mut [u64]) -> u64 { + if values.is_empty() { + return 0; + } + values.sort_unstable(); + values[(values.len() - 1) / 2] +} + +/// One call's cost, over every round and every case of the selection that made it. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct CallTimes { + /// The [`crate::case::Side`] call. + pub call: String, + /// Calls measured in a round: the least and the most any round saw. The two differ where a + /// case's work is not ordered, which is itself a fact about the measurement. + pub least_calls: u64, + pub most_calls: u64, + /// The median of the rounds' own medians, in nanoseconds: elapsed, the caller's own CPU, and + /// what it waited for. A median of medians, so one noisy round moves nothing. + pub wall: u64, + pub on_cpu: u64, + pub blocked: u64, + /// The least and the most a round's median elapsed time reached: the spread behind `wall`. + pub wall_least: u64, + pub wall_most: u64, + /// The median round's **sum** over this call: every call of this name added up, in + /// nanoseconds. + /// + /// A median says what one call costs and a sum says what the call costs the case, and a report + /// that carries only the first cannot tell a 30x on a call made once from a 30x on a call made + /// a thousand times. The paired table ratios on the sums for exactly that reason. + pub wall_total: u64, + pub on_cpu_total: u64, + pub blocked_total: u64, +} + +/// What a leg cost over one case, over every round. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct CaseTimes { + pub case: String, + /// Calls the case made in a round, the median across rounds. + pub calls: u64, + /// The median round's nanoseconds inside the case's calls. + pub in_calls: u64, + /// The median round's three attributions, in nanoseconds. The first two are summed over the + /// case's calls; `elsewhere` is over the whole case window ([module docs](self)). + pub on_cpu: u64, + pub blocked: u64, + pub elsewhere: u64, + /// The median round's [`CaseRound::spend`]: what a margin is judged on. + pub spend: u64, + /// The least and most any round's spend reached. + pub spend_least: u64, + pub spend_most: u64, + /// Why a round stopped before the case finished, where one did. Its calls are a part of the + /// case, so nothing is compared from them. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub stopped: Option, + /// The degrade-notice codes the rounds announced, sorted: how much of the case this leg did + /// exactly, and so whether its cost is comparable at all. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub degraded: Vec, + /// This case's own per-call figures. + pub per_call: Vec, +} + +impl CaseTimes { + /// Fold one case's rounds into its figures. + pub fn of(case: &str, rounds: &[&CaseRound]) -> Self { + let mut calls: Vec = Vec::new(); + let mut in_calls: Vec = Vec::new(); + let mut on_cpu: Vec = Vec::new(); + let mut blocked: Vec = Vec::new(); + let mut elsewhere: Vec = Vec::new(); + let mut spend: Vec = Vec::new(); + let mut stopped = None; + let mut degraded: Vec = Vec::new(); + for round in rounds { + calls.push(round.observed.len() as u64); + in_calls.push(round.in_calls()); + on_cpu.push(round.observed.iter().map(|one| one.on_cpu).sum()); + blocked.push(round.observed.iter().map(|one| one.blocked()).sum()); + elsewhere.push(round.elsewhere()); + spend.push(round.spend()); + // A round that stopped where another did not is a fact about the measurement, so the + // first reason any round gave is kept rather than the last round's silence. + if stopped.is_none() { + stopped = round.stopped.clone(); + } + for code in &round.degraded { + if !degraded.contains(code) { + degraded.push(code.clone()); + } + } + } + degraded.sort(); + let spend_least = spend.iter().copied().min().unwrap_or(0); + let spend_most = spend.iter().copied().max().unwrap_or(0); + Self { + case: case.to_owned(), + calls: median(&mut calls), + in_calls: median(&mut in_calls), + on_cpu: median(&mut on_cpu), + blocked: median(&mut blocked), + elsewhere: median(&mut elsewhere), + spend: median(&mut spend), + spend_least, + spend_most, + stopped, + degraded, + per_call: per_call(rounds), + } + } +} + +/// The per-call figures over a set of rounds: each round's own median for a call, then the median +/// of those. +/// +/// Pooling the rounds' observations into one list instead would let a round that made ten times as +/// many calls decide the figure, which is the shape of noise a median of medians exists to refuse. +pub fn per_call(rounds: &[&CaseRound]) -> Vec { + /// Every reading of one call within one round. + #[derive(Default)] + struct Readings { + wall: Vec, + on_cpu: Vec, + blocked: Vec, + } + + /// What one round says about one call: the calls it made, the middle of each reading, and + /// what the call cost the round in total. + struct Round { + calls: u64, + wall: u64, + on_cpu: u64, + blocked: u64, + wall_total: u64, + on_cpu_total: u64, + blocked_total: u64, + } + + let mut rounds_by_call: BTreeMap<&str, Vec> = BTreeMap::new(); + for round in rounds { + let mut seen: BTreeMap<&str, Readings> = BTreeMap::new(); + for one in &round.observed { + let held = seen.entry(one.call).or_default(); + held.wall.push(one.wall); + held.on_cpu.push(one.on_cpu); + held.blocked.push(one.blocked()); + } + for (call, mut readings) in seen { + rounds_by_call.entry(call).or_default().push(Round { + calls: readings.wall.len() as u64, + wall_total: readings.wall.iter().sum(), + on_cpu_total: readings.on_cpu.iter().sum(), + blocked_total: readings.blocked.iter().sum(), + wall: median(&mut readings.wall), + on_cpu: median(&mut readings.on_cpu), + blocked: median(&mut readings.blocked), + }); + } + } + rounds_by_call + .into_iter() + .map(|(call, readings)| { + let counts: Vec = readings.iter().map(|one| one.calls).collect(); + let mut wall: Vec = readings.iter().map(|one| one.wall).collect(); + let mut on_cpu: Vec = readings.iter().map(|one| one.on_cpu).collect(); + let mut blocked: Vec = readings.iter().map(|one| one.blocked).collect(); + let mut wall_total: Vec = readings.iter().map(|one| one.wall_total).collect(); + let mut on_cpu_total: Vec = readings.iter().map(|one| one.on_cpu_total).collect(); + let mut blocked_total: Vec = + readings.iter().map(|one| one.blocked_total).collect(); + let wall_least = wall.iter().copied().min().unwrap_or(0); + let wall_most = wall.iter().copied().max().unwrap_or(0); + CallTimes { + wall_total: median(&mut wall_total), + on_cpu_total: median(&mut on_cpu_total), + blocked_total: median(&mut blocked_total), + call: call.to_owned(), + least_calls: counts.iter().copied().min().unwrap_or(0), + most_calls: counts.iter().copied().max().unwrap_or(0), + wall: median(&mut wall), + on_cpu: median(&mut on_cpu), + blocked: median(&mut blocked), + wall_least, + wall_most, + } + }) + .collect() +} + +/// A whole leg's measurement over a selection. +#[derive(Clone, Debug)] +pub struct Measurement { + pub leg: Leg, + /// The venue the leg ran on ([`crate::case::Venue::label`]). + pub venue: String, + /// The rounds taken. + pub rounds: u32, + /// What the instrument itself cost on this host, in nanoseconds a call. + pub instrument: u64, + /// Whether the host answered the thread CPU clock. Where it did not, `on_cpu` reads zero + /// everywhere and `blocked` equals elapsed, and the report says so rather than letting a + /// reader take the zeros for a fact. + pub cpu_clock: bool, + /// Per case, in the selection's order. + pub cases: Vec, + /// Per call, pooled over the whole selection: the table a reader acts on. + pub calls: Vec, +} + +impl Measurement { + /// One case's figures, where the selection held it. + pub fn case(&self, name: &str) -> Option<&CaseTimes> { + self.cases.iter().find(|one| one.case == name) + } + + /// One call's pooled figures, where the selection made it. + pub fn call(&self, name: &str) -> Option<&CallTimes> { + self.calls.iter().find(|one| one.call == name) + } +} + +/// How one case's cost stands against Metal's over the same case. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum TimeVerdict { + /// Our leg's spend is within [`MARGIN`] times Metal's. + Within { ours: u64, metal: u64 }, + /// Our leg's spend is over [`MARGIN`] times Metal's: an order of magnitude, the shape of every + /// per-call cost bug this project has had. + Over { ours: u64, metal: u64 }, + /// The two legs cannot be compared, and why. + Unmeasured { why: String }, +} + +impl TimeVerdict { + /// The word the report prints. + pub fn word(&self) -> &'static str { + match self { + TimeVerdict::Within { .. } => "within", + TimeVerdict::Over { .. } => "over", + TimeVerdict::Unmeasured { .. } => "unmeasured", + } + } + + /// How many times our leg's spend is Metal's, where both were measured. + pub fn ratio(&self) -> Option { + match self { + TimeVerdict::Within { ours, metal } | TimeVerdict::Over { ours, metal } => { + (*metal > 0).then(|| *ours as f64 / *metal as f64) + } + TimeVerdict::Unmeasured { .. } => None, + } + } +} + +/// Judge one case's two legs against each other. +/// +/// Every reason a row cannot be compared is checked before the margin, and each is its own +/// sentence in the report: +/// +/// - either leg's run **stopped** before the case finished, so its calls are a part of the case; +/// - our leg **announced a degrade notice**, so it did a different amount of work from Metal's and +/// a lower cost is the device's gap rather than our saving ([module docs](self)); +/// - the Metal leg announced one, which cannot happen today and would mean the same thing; +/// - Metal's spend reads **zero**, which is a measurement that did not happen rather than a free +/// case. +pub fn judge(metal: &CaseTimes, ours: &CaseTimes) -> TimeVerdict { + if let Some(why) = &metal.stopped { + return TimeVerdict::Unmeasured { + why: format!("the Metal leg stopped before the case finished: {why}"), + }; + } + if let Some(why) = &ours.stopped { + return TimeVerdict::Unmeasured { + why: format!("our leg stopped before the case finished: {why}"), + }; + } + if !ours.degraded.is_empty() { + return TimeVerdict::Unmeasured { + why: format!( + "our leg announced {}, so it did a different amount of work from Metal's and its \ + cost is not Metal's to compare with", + ours.degraded.join(", ") + ), + }; + } + if !metal.degraded.is_empty() { + return TimeVerdict::Unmeasured { + why: format!( + "the Metal leg announced {}, so the two legs did different work", + metal.degraded.join(", ") + ), + }; + } + if metal.spend == 0 { + return TimeVerdict::Unmeasured { + why: "the Metal leg's spend reads zero, which is a measurement that did not happen \ + rather than a case Metal answers for nothing" + .to_owned(), + }; + } + let (ours, metal) = (ours.spend, metal.spend); + if ours > metal.saturating_mul(MARGIN) { + TimeVerdict::Over { ours, metal } + } else { + TimeVerdict::Within { ours, metal } + } +} + +/// One leg's cost for a case, as its recording keeps it. +/// +/// **Why a recording holds this at all**: Metal's own cost on a given macOS build is the one half +/// that cannot be re-taken later. A measurement of ours is a command away on any host; what Metal +/// charged for a `setBytes:` on 26A434 is gone the moment the machine updates. That is the plan's +/// standing property — a year of Metal measurements should stop evaporating — applied to cost. +/// +/// It is **not** a Metal fact anything compares against: a stored figure and a live one come from +/// different moments and, off this Mac, different hardware. A comparison is only ever made between +/// two legs measured in the same run ([`judge`]), and the stored record is history. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct TimeRecord { + /// Which leg ([`Leg`]). + pub leg: Leg, + /// The venue the leg ran on. + pub venue: String, + /// The chip, as the suite names it ([`crate::recording::ORACLE_CHIP`]). + pub chip: String, + /// The macOS build. Two records are of one machine only where these two fields agree. + pub os_build: String, + /// The rounds behind the figures. + pub rounds: u32, + /// The measurement that justified the figures, in words: what was run, where, and how the + /// figures were taken from it. Every bound in this suite names its measurement, and a time is + /// held to that rule too. + pub measured: String, + /// What the instrument cost on the host that took the measurement, in nanoseconds a call. + pub instrument: u64, + /// The case's figures. + pub times: CaseTimes, +} + +/// Fold a leg's rounds into its measurement. +/// +/// `taken` is one entry per round, each holding one [`CaseRound`] per case of the selection, in the +/// selection's order. A case's figures are the median across rounds of its own per-round figures. +/// +/// The pooled per-call table ([`Measurement::calls`]) is taken over the cases this leg did +/// **exactly, start to finish**: a round that stopped part way did a part of the case, and a round +/// that announced a notice did something cheaper than the exact form, so neither belongs in a +/// figure a reader will read as the cost of a call. Each row of the report's paired table prints +/// both legs' call counts, so a row whose two legs pooled different work is visible rather than +/// implied. +pub fn fold( + leg: Leg, + venue: String, + rounds: u32, + instrument: u64, + cases: &[Box], + taken: &[Vec], +) -> Measurement { + let mut folded = Vec::with_capacity(cases.len()); + for (index, case) in cases.iter().enumerate() { + let of_case: Vec<&CaseRound> = taken.iter().filter_map(|round| round.get(index)).collect(); + folded.push(CaseTimes::of(case.name(), &of_case)); + } + let pooled: Vec = taken + .iter() + .map(|round| CaseRound { + observed: round + .iter() + .filter(|one| one.stopped.is_none() && one.degraded.is_empty()) + .flat_map(|one| one.observed.iter().copied()) + .collect(), + ..Default::default() + }) + .collect(); + Measurement { + leg, + venue, + rounds, + instrument, + cpu_clock: crate::clocks::thread_cpu_nanos().is_some(), + cases: folded, + calls: per_call(&pooled.iter().collect::>()), + } +} + +/// One call's cost on one leg, added up over a set of cases. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct CallTotal { + /// The calls of this name those cases made, in the median round. + pub calls: u64, + /// What they cost in total, in nanoseconds, and how that splits. + pub wall: u64, + pub on_cpu: u64, + pub blocked: u64, + /// The middle case's own median for this call: what one such call costs, as against what they + /// cost together. + pub typical: u64, +} + +/// One call, on both legs, over the cases **both legs did exactly**. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Paired { + pub call: String, + pub metal: CallTotal, + pub ours: CallTotal, +} + +impl Paired { + /// How many times our leg's total is Metal's, where Metal's is not zero. + pub fn ratio(&self) -> Option { + (self.metal.wall > 0).then(|| self.ours.wall as f64 / self.metal.wall as f64) + } +} + +/// How many cases both legs did exactly, so the paired table's denominator is printed rather +/// than implied. +pub fn comparable(metal: &Measurement, ours: &Measurement) -> usize { + ours.cases + .iter() + .filter(|one| { + metal + .case(&one.case) + .is_some_and(|theirs| !matches!(judge(theirs, one), TimeVerdict::Unmeasured { .. })) + }) + .count() +} + +/// The per-call table, paired over the cases both legs did exactly. +/// +/// **Why the pairing is not optional.** Each leg's own pooled table is over the cases *that leg* +/// finished without a notice, and the two sets are not the same: 107 of this suite's 383 cases +/// announce a notice on our leg and none do on Metal's. A table built from the two pools compares +/// `render_pipeline` over 132 Metal calls against 85 of ours — a ratio of different work, printed +/// with the authority of a measurement. Measured on this Mac, not supposed: that is what the first +/// whole-set run produced, and it is why this function exists. +/// +/// So a call's row is summed over the cases where [`judge`] returns a verdict at all. Both legs +/// then cover one case set, and the row's two call counts are printed anyway, because a case whose +/// two legs make a call a different number of times is still comparing different work and only the +/// counts can say so. +/// +/// The ratio is on the **totals**, so a call is weighted by how often it runs: a 30x on a call +/// made once is not the same finding as a 30x on a call made a thousand times. +pub fn paired(metal: &Measurement, ours: &Measurement) -> Vec { + let mut by_call: BTreeMap, Vec<&CallTimes>)> = BTreeMap::new(); + for one in &ours.cases { + let Some(theirs) = metal.case(&one.case) else { + continue; + }; + if matches!(judge(theirs, one), TimeVerdict::Unmeasured { .. }) { + continue; + } + for call in &one.per_call { + by_call.entry(call.call.clone()).or_default().1.push(call); + } + for call in &theirs.per_call { + by_call.entry(call.call.clone()).or_default().0.push(call); + } + } + let total = |of: &[&CallTimes]| { + let mut typical: Vec = of.iter().map(|one| one.wall).collect(); + CallTotal { + calls: of.iter().map(|one| one.most_calls).sum(), + wall: of.iter().map(|one| one.wall_total).sum(), + on_cpu: of.iter().map(|one| one.on_cpu_total).sum(), + blocked: of.iter().map(|one| one.blocked_total).sum(), + typical: median(&mut typical), + } + }; + by_call + .into_iter() + .map(|(call, (theirs, ours))| Paired { + call, + metal: total(&theirs), + ours: total(&ours), + }) + .collect() +} + +/// The layers under our runtime on this host, named so the honest-framing line is true wherever +/// the suite runs. +/// +/// It was not, once: the line read "MoltenVK and Metal underneath" on every venue, and the first +/// run in the Linux container printed it over llvmpipe, where neither is present. A caution that +/// overstates the stack is the same defect as a figure that overstates a result. +fn chain(venue: &str) -> String { + if cfg!(target_os = "macos") { + format!("MoltenVK over Metal on {venue}") + } else { + format!("the venue's own Vulkan implementation, {venue}") + } +} + +/// Microseconds, three places, from nanoseconds: the unit a per-call figure reads in. +fn us(nanos: u64) -> String { + format!("{:.3}", nanos as f64 / 1_000.0) +} + +/// Milliseconds, three places, from nanoseconds: the unit a per-case figure reads in. +fn ms(nanos: u64) -> String { + format!("{:.3}", nanos as f64 / 1_000_000.0) +} + +/// Where one call's cost sits, case by case, worst first: the triage for a row of the per-call +/// table. +/// +/// **Why this exists.** The first whole-set run put `replace_region` at 105x over 108 calls, and +/// running the three cases that obviously make it gave 1.2x over 3 — so the figure was real and +/// almost none of it was there. A per-call total over a case set says *that* a call is expensive +/// and never *where*, and the counters half's hardest lesson is that a reading over one selection +/// is not evidence about another. Without this a reader has only the bisection by hand that the +/// plan's UX bar exists to abolish. +/// +/// Only the cases both legs did exactly are listed, for the same reason the paired table lists +/// only those. +pub fn render_one_call(metal: &Measurement, ours: &Measurement, call: &str) -> String { + let mut out = String::new(); + out.push_str(&format!( + "\nWHERE `{call}` COSTS, case by case over the cases both legs did exactly, worst ratio \ + of totals first (us)\n" + )); + out.push_str(&format!( + "{:<44} {:>7} {:>11} {:>11} {:>8} {:>11} {:>11}\n", + "case", "calls", "metal tot", "ours tot", "ratio", "ours cpu", "ours blkd" + )); + let mut rows: Vec<(&str, u64, &CallTimes, Option<&CallTimes>)> = Vec::new(); + for one in &ours.cases { + let Some(theirs) = metal.case(&one.case) else { + continue; + }; + if matches!(judge(theirs, one), TimeVerdict::Unmeasured { .. }) { + continue; + } + let Some(mine) = one.per_call.iter().find(|held| held.call == call) else { + continue; + }; + rows.push(( + &one.case, + mine.most_calls, + mine, + theirs.per_call.iter().find(|held| held.call == call), + )); + } + rows.sort_by_key(|(_, _, mine, theirs)| { + let metal = theirs.map(|theirs| theirs.wall_total).unwrap_or(0).max(1); + std::cmp::Reverse(mine.wall_total.saturating_mul(1_000) / metal) + }); + for (case, calls, mine, theirs) in &rows { + let (their_total, ratio) = match theirs { + Some(theirs) if theirs.wall_total > 0 => ( + us(theirs.wall_total), + format!("{:.1}x", mine.wall_total as f64 / theirs.wall_total as f64), + ), + Some(theirs) => (us(theirs.wall_total), "-".to_owned()), + None => ("-".to_owned(), "-".to_owned()), + }; + out.push_str(&format!( + "{:<44} {:>7} {:>11} {:>11} {:>8} {:>11} {:>11}\n", + case, + calls, + their_total, + us(mine.wall_total), + ratio, + us(mine.on_cpu_total), + us(mine.blocked_total) + )); + } + if rows.is_empty() { + out.push_str(" no case both legs did exactly makes that call\n"); + } + out +} + +/// The table a `times` run prints: native Metal beside our stack, per call and per case. +/// +/// `metal` is absent off macOS, where there is no Metal leg to compare with; the table then +/// reports our own figures alone and says so, which is the honest shape for a venue the suite can +/// measure but has no oracle on. +pub fn render(metal: Option<&Measurement>, ours: &Measurement, show: bool) -> String { + let mut out = String::new(); + out.push_str(&format!( + "times: our stack on {} against native Metal, over {} round(s)\n", + ours.venue, ours.rounds + )); + out.push_str(&format!( + "the instrument costs {} us a call on this host, paid identically on both legs and never \ + subtracted from a figure\n", + us(ours.instrument) + )); + if !ours.cpu_clock { + out.push_str( + "this host answers no thread CPU clock, so the `on cpu` column reads zero everywhere \ + and `blocked` is the whole elapsed time: an attribution that was not measured, not \ + one that is zero\n", + ); + } + out.push_str(&format!( + "\nWHAT A DIFFERENCE HERE IS: our leg is translation, then our runtime, then {}.\nA ratio \ + is the cost of that whole chain against native Metal and attributes to no layer of \ + it.\nNothing here licenses a sentence about what any one of those layers costs on its \ + own.\n", + chain(&ours.venue) + )); + + let Some(metal) = metal else { + out.push_str("\nno Metal leg on this host, so every row below is ours alone\n\n"); + out.push_str(&format!( + "{:<38} {:>7} {:>11} {:>11} {:>11}\n", + "call", "calls", "wall us", "on cpu us", "blocked us" + )); + for one in &ours.calls { + out.push_str(&format!( + "{:<38} {:>7} {:>11} {:>11} {:>11}\n", + one.call, + one.most_calls, + us(one.wall), + us(one.on_cpu), + us(one.blocked) + )); + } + return out; + }; + + // Per call, paired over the cases both legs did exactly, worst ratio first. The question a + // reader brings is how much more a call costs us; the counts are printed for both legs + // because a row whose legs make a call a different number of times is comparing different + // work and nothing but the counts can say so. + // + // Measured, not supposed: on this Mac `library` costs Metal about 23 ms and us about 0.1 ms, + // while `compute_pipeline` costs Metal 0.09 ms and us 2.1 ms. Neither row is a result. Metal + // compiles the AIR when the library is made and we translate it when the pipeline is made, so + // the *same work* sits at a different call on each leg, and the two rows are only honest read + // together. That is the per-call table's standing trap and it belongs in its heading. + let rows = { + let mut rows = paired(metal, ours); + rows.sort_by(|one, two| { + let ratio = |row: &Paired| row.ratio().unwrap_or(f64::INFINITY); + ratio(two) + .partial_cmp(&ratio(one)) + .unwrap_or(std::cmp::Ordering::Equal) + }); + rows + }; + out.push_str(&format!( + "\nPER CALL, over the {} case(s) BOTH legs did exactly, worst ratio of totals first\n", + comparable(metal, ours) + )); + out.push_str( + " a per-call ratio is only honest read beside the per-case total: the two legs put the \ + same work at different\n calls, and the measured example is right here -- Metal \ + compiles at `library`, we translate at `compute_pipeline`\n", + ); + out.push_str(&format!( + "{:<34} {:>7} {:>10} {:>10} {:>7} {:>10} {:>10} {:>7} {:>9} {:>9}\n", + "call", + "metal n", + "metal tot", + "metal one", + "ours n", + "ours tot", + "ours one", + "ratio", + "ours cpu", + "ours blkd" + )); + for row in &rows { + let ratio = row + .ratio() + .map(|ratio| format!("{ratio:.1}x")) + .unwrap_or_else(|| "-".to_owned()); + out.push_str(&format!( + "{:<34} {:>7} {:>10} {:>10} {:>7} {:>10} {:>10} {:>7} {:>9} {:>9}\n", + row.call, + row.metal.calls, + us(row.metal.wall), + us(row.metal.typical), + row.ours.calls, + us(row.ours.wall), + us(row.ours.typical), + ratio, + us(row.ours.on_cpu), + us(row.ours.blocked) + )); + } + + // Per case, the three attributions kept apart. A case is judged on `spend`, which is + // everything the machine spent on its calls however attributed, so nothing here can be + // improved by moving work from one column to another. + out.push_str( + "\nPER CASE, the three attributions apart, in ms; `spend` is wall-in-calls + elsewhere \ + and is what the margin judges\n", + ); + out.push_str(&format!( + "{:<42} {:>8} {:>8} {:>8} {:>8} {:>8} {:>8} {:>8} {:>8} {:>7}\n", + "case", + "m spend", + "m cpu", + "m blkd", + "m elsew", + "o spend", + "o cpu", + "o blkd", + "o elsew", + "ratio" + )); + let mut within = 0; + let mut over = 0; + let mut unmeasured = 0; + let mut notes: Vec = Vec::new(); + for one in &ours.cases { + let verdict = match metal.case(&one.case) { + Some(theirs) => judge(theirs, one), + None => TimeVerdict::Unmeasured { + why: "the Metal leg holds no figures for the case".to_owned(), + }, + }; + match &verdict { + TimeVerdict::Within { .. } => within += 1, + TimeVerdict::Over { .. } => over += 1, + TimeVerdict::Unmeasured { why } => { + unmeasured += 1; + notes.push(format!("{}: unmeasured, {why}", one.case)); + } + } + let interesting = !matches!(verdict, TimeVerdict::Within { .. }); + if !show && !interesting { + continue; + } + let theirs = metal.case(&one.case); + let column = |of: Option| of.map(ms).unwrap_or_else(|| "-".to_owned()); + let ratio = verdict + .ratio() + .map(|ratio| format!("{ratio:.1}x")) + .unwrap_or_else(|| verdict.word().to_owned()); + out.push_str(&format!( + "{:<42} {:>8} {:>8} {:>8} {:>8} {:>8} {:>8} {:>8} {:>8} {:>7}\n", + one.case, + column(theirs.map(|theirs| theirs.spend)), + column(theirs.map(|theirs| theirs.on_cpu)), + column(theirs.map(|theirs| theirs.blocked)), + column(theirs.map(|theirs| theirs.elsewhere)), + ms(one.spend), + ms(one.on_cpu), + ms(one.blocked), + ms(one.elsewhere), + ratio + )); + } + if !show && (within > 0) { + out.push_str(&format!( + "({within} case(s) within the margin are not listed; pass --show for every row)\n" + )); + } + for note in ¬es { + out.push_str(&format!(" {note}\n")); + } + out.push_str(&format!( + "\n{within} within {MARGIN}x, {over} over it, {unmeasured} unmeasured, over {} round(s)\n", + ours.rounds + )); + out.push_str( + "no exit status turns on any of this: a time is reported, never gated. README.md says what \ + the commit that gates it has to show first.\n", + ); + out +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A case's figures with its three attributions split however the test wants, folded through + /// the real aggregation. + /// + /// **It goes through [`CaseRound`] and [`CaseTimes::of`] on purpose.** Setting the fields of a + /// `CaseTimes` by hand would make every test below a test of nothing but `judge` reading one + /// field: the first version of this helper computed `spend` itself, and the guard that the + /// margin cannot be dodged by moving work then **passed with a `spend` that ignored the + /// handoff entirely**. Caught by breaking it, which is the only way such a test is ever + /// caught. + fn case_of(case: &str, on_cpu: u64, blocked: u64, elsewhere: u64) -> CaseTimes { + let round = CaseRound { + // One call that burned `on_cpu` and waited `blocked`. + observed: vec![seen("the_call", on_cpu + blocked, on_cpu)], + window_wall: on_cpu + blocked, + window_on_cpu: on_cpu, + // The process burned the calling thread's own CPU plus `elsewhere` on other threads. + window_process_cpu: on_cpu + elsewhere, + stopped: None, + degraded: Vec::new(), + }; + CaseTimes::of(case, &[&round]) + } + + /// One call, measured, for the aggregation tests. + fn seen(call: &'static str, wall: u64, on_cpu: u64) -> Observation { + Observation { call, wall, on_cpu } + } + + /// A median is one of the readings taken, and the lower of the two middles for an even count, + /// so no figure in a report is a number nobody measured. + #[test] + fn a_median_is_a_reading_and_never_a_mean() { + assert_eq!(median(&mut []), 0); + assert_eq!(median(&mut [5]), 5); + assert_eq!(median(&mut [9, 1]), 1); + assert_eq!(median(&mut [9, 1, 5]), 5); + assert_eq!(median(&mut [1, 2, 3, 4]), 2); + } + + /// **The property the whole three-way split exists for**: the margin is judged on the case's + /// whole spend, so moving work from the caller's thread to our own threads, or from computing + /// to waiting, changes no verdict. + /// + /// Without this a call that returns at once and queues 50 us of scheduler work would score as + /// a win, which is the known handoff problem the plan names. + #[test] + fn moving_work_between_the_attributions_changes_no_verdict() { + let metal = case_of("m", 100, 0, 0); + assert_eq!(metal.spend, 100, "the fold did not take Metal's own spend"); + let splits = [ + case_of("o", 900, 0, 0), + case_of("o", 0, 900, 0), + case_of("o", 0, 0, 900), + case_of("o", 300, 300, 300), + case_of("o", 450, 0, 450), + ]; + for ours in &splits { + assert_eq!( + ours.spend, 900, + "a split of {}/{}/{} did not fold to the same spend, so the verdict below would \ + be comparing different totals", + ours.on_cpu, ours.blocked, ours.elsewhere + ); + assert_eq!( + judge(&metal, ours), + TimeVerdict::Within { + ours: 900, + metal: 100 + }, + "a split of {}/{}/{} changed the verdict", + ours.on_cpu, + ours.blocked, + ours.elsewhere + ); + } + } + + /// The margin is an order of magnitude, and the boundary is inclusive: ten times Metal is + /// within, one nanosecond more is over. + #[test] + fn the_margin_is_an_order_of_magnitude() { + let metal = case_of("m", 100, 0, 0); + assert_eq!( + judge(&metal, &case_of("o", 1_000, 0, 0)), + TimeVerdict::Within { + ours: 1_000, + metal: 100 + } + ); + assert_eq!( + judge(&metal, &case_of("o", 1_001, 0, 0)), + TimeVerdict::Over { + ours: 1_001, + metal: 100 + } + ); + assert_eq!(MARGIN, 10); + } + + /// A leg that announced a degrade notice did a **different amount of work**, so its cost is + /// not Metal's to compare with. This is the rule that stops a device's honest gap reading as a + /// cost win, and it fires before the margin. + #[test] + fn a_degraded_leg_is_unmeasured_rather_than_fast() { + let metal = case_of("m", 1_000_000, 0, 0); + let mut ours = case_of("o", 1, 0, 0); + ours.degraded = vec!["some-notice".to_owned()]; + let verdict = judge(&metal, &ours); + match &verdict { + TimeVerdict::Unmeasured { why } => { + assert!(why.contains("some-notice"), "{why}"); + assert!(why.contains("different amount of work"), "{why}"); + } + other => panic!("a degraded leg a millionth of Metal's cost read {other:?}"), + } + assert_eq!(verdict.ratio(), None); + } + + /// A run that stopped part way did a part of the case, on either leg, so nothing is compared + /// from it — and the leg that stopped is named, because the two mean different things to fix. + #[test] + fn a_stopped_leg_is_unmeasured_and_says_which_one() { + let good = case_of("m", 100, 0, 0); + let mut stopped = case_of("o", 1, 0, 0); + stopped.stopped = Some("the venue lacks it".to_owned()); + let ours = judge(&good, &stopped); + assert!( + matches!(&ours, TimeVerdict::Unmeasured { why } if why.starts_with("our leg stopped")), + "{ours:?}" + ); + let metal = judge(&stopped, &good); + assert!( + matches!(&metal, TimeVerdict::Unmeasured { why } if why.starts_with("the Metal leg stopped")), + "{metal:?}" + ); + } + + /// Metal costing nothing is a measurement that did not happen, never a free case, so it is + /// never the denominator of a ratio. + #[test] + fn a_metal_leg_of_zero_is_unmeasured_rather_than_infinitely_worse() { + let verdict = judge(&case_of("m", 0, 0, 0), &case_of("o", 500, 0, 0)); + assert!( + matches!(&verdict, TimeVerdict::Unmeasured { why } if why.contains("reads zero")), + "{verdict:?}" + ); + } + + /// CPU read off the calling thread floors at zero: the process and thread clocks are read a + /// few hundred nanoseconds apart, and a negative handoff is instrument noise rather than a + /// fact. + #[test] + fn a_negative_handoff_reads_as_none_rather_than_wrapping() { + let round = CaseRound { + window_on_cpu: 500, + window_process_cpu: 100, + ..Default::default() + }; + assert_eq!(round.elsewhere(), 0); + let one = seen("library", 10, 400); + assert_eq!(one.blocked(), 0); + } + + /// The per-call figure is a median of the **rounds'** medians, so one wild round moves it by + /// nothing. Pooling every observation into one list instead would let the round that made the + /// most calls decide the figure. + #[test] + fn a_wild_round_does_not_move_a_per_call_figure() { + let quiet = |wall| CaseRound { + observed: vec![seen("dispatch", wall, wall)], + ..Default::default() + }; + // Four honest rounds at 100 ns and one round of a thousand calls at 100 us. + let wild = CaseRound { + observed: (0..1_000).map(|_| seen("dispatch", 100_000, 0)).collect(), + ..Default::default() + }; + let rounds = [quiet(100), quiet(100), quiet(100), quiet(100), wild]; + let folded = per_call(&rounds.iter().collect::>()); + let [one] = folded.as_slice() else { + panic!("one call: {folded:?}"); + }; + assert_eq!(one.wall, 100, "the wild round decided the figure"); + // The spread is still reported, so the wild round is visible rather than discarded. + assert_eq!((one.wall_least, one.wall_most), (100, 100_000)); + assert_eq!((one.least_calls, one.most_calls), (1, 1_000)); + } + + /// A case's figure is the **median** round and its spread is the least and most any round + /// reached, so a reader can see how settled the measurement is. + /// + /// The spread is the times half's version of the counters half's hardest lesson: a reading + /// that moves between two runs of an unchanged tree is not a fact, and the only way a report + /// can say so is by carrying both ends. + #[test] + fn a_cases_figure_is_the_median_round_and_carries_its_spread() { + let round = |on_cpu: u64| CaseRound { + observed: vec![seen("the_call", on_cpu, on_cpu)], + window_wall: on_cpu, + window_on_cpu: on_cpu, + window_process_cpu: on_cpu, + stopped: None, + degraded: Vec::new(), + }; + let rounds = [round(10), round(900), round(20), round(30), round(40)]; + let folded = CaseTimes::of("o", &rounds.iter().collect::>()); + assert_eq!(folded.spend, 30, "the figure is not the median round"); + assert_eq!( + (folded.spend_least, folded.spend_most), + (10, 900), + "the spread does not carry the rounds the measurement actually saw" + ); + assert_eq!(folded.calls, 1); + } + + /// A round that stopped, and the notices any round announced, both survive the fold: a + /// measurement whose rounds did different amounts of work must not read as one clean figure. + #[test] + fn a_fold_keeps_the_reasons_a_round_was_not_comparable() { + let clean = CaseRound { + observed: vec![seen("the_call", 10, 10)], + ..Default::default() + }; + let stopped = CaseRound { + observed: vec![seen("the_call", 10, 10)], + stopped: Some("the venue lacks it".to_owned()), + degraded: vec!["second-code".to_owned()], + ..Default::default() + }; + let noticed = CaseRound { + observed: vec![seen("the_call", 10, 10)], + degraded: vec!["first-code".to_owned()], + ..Default::default() + }; + let folded = CaseTimes::of("o", &[&clean, &stopped, ¬iced]); + assert_eq!(folded.stopped.as_deref(), Some("the venue lacks it")); + assert_eq!(folded.degraded, ["first-code", "second-code"]); + } + + /// A measurement of one leg over the cases given, for the pairing test. + fn measurement(leg: Leg, cases: Vec) -> Measurement { + Measurement { + leg, + venue: "test".to_owned(), + rounds: 1, + instrument: 1, + cpu_clock: true, + cases, + calls: Vec::new(), + } + } + + /// A case's figures from a given number of calls of one name, each costing `each`. + fn calling(case: &str, call: &'static str, times: usize, each: u64) -> CaseTimes { + let round = CaseRound { + observed: (0..times).map(|_| seen(call, each, each)).collect(), + window_wall: each * times as u64, + window_on_cpu: each * times as u64, + window_process_cpu: each * times as u64, + stopped: None, + degraded: Vec::new(), + }; + CaseTimes::of(case, &[&round]) + } + + /// **The per-call table is paired over the cases both legs did exactly.** + /// + /// This is the guard for a flaw the first whole-set run actually had: each leg's own pool was + /// over the cases *that leg* finished cleanly, and because 107 of this suite's cases announce + /// a notice on our leg and none do on Metal's, the table compared `render_pipeline` over 132 + /// Metal calls against 85 of ours and printed a ratio of different work. + #[test] + fn a_case_only_one_leg_did_exactly_is_left_out_of_the_per_call_table() { + let clean_metal = calling("clean", "render_pipeline", 1, 100); + let clean_ours = calling("clean", "render_pipeline", 1, 200); + let noisy_metal = calling("noisy", "render_pipeline", 1_000, 100); + let mut noisy_ours = calling("noisy", "render_pipeline", 1_000, 100); + noisy_ours.degraded = vec!["a-notice".to_owned()]; + let metal = measurement(Leg::Metal, vec![clean_metal, noisy_metal]); + let ours = measurement(Leg::Ours, vec![clean_ours, noisy_ours]); + assert_eq!( + comparable(&metal, &ours), + 1, + "the degraded case was compared" + ); + let rows = paired(&metal, &ours); + let [row] = rows.as_slice() else { + panic!("one call: {rows:?}"); + }; + assert_eq!(row.call, "render_pipeline"); + assert_eq!( + (row.metal.calls, row.ours.calls), + (1, 1), + "the 1,000 calls of a case only one leg did exactly reached the paired table" + ); + assert_eq!((row.metal.wall, row.ours.wall), (100, 200)); + assert_eq!(row.ratio(), Some(2.0)); + } + + /// The ratio is on the totals, so a call is weighted by how often it runs. A 30x on a call + /// made once must not read the same as a 30x on a call made a thousand times. + #[test] + fn the_per_call_ratio_weights_a_call_by_how_often_it_runs() { + // A case of its own for each call, and the names must differ: a case is keyed by name + // throughout the suite (its recording is a file of that name) and the pairing looks one up + // by it, so two cases sharing a name pair the same Metal figures twice. Caught by writing + // this test with both named `c` and watching the hot row come out at double. + let metal = measurement( + Leg::Metal, + vec![ + calling("hot-case", "hot", 1_000, 10), + calling("cold-case", "cold", 1, 10), + ], + ); + let ours = measurement( + Leg::Ours, + vec![ + calling("hot-case", "hot", 1_000, 100), + calling("cold-case", "cold", 1, 100), + ], + ); + let rows = paired(&metal, &ours); + let hot = rows.iter().find(|row| row.call == "hot").unwrap(); + assert_eq!((hot.metal.wall, hot.ours.wall), (10_000, 100_000)); + assert_eq!(hot.metal.typical, 10, "the typical call lost its median"); + assert_eq!(hot.ratio(), Some(10.0)); + } + + /// A span measures what it was asked to and nothing else: the call's name reaches the + /// observation, and the instrument's own cost is a positive number this host can state. + #[test] + fn the_instrument_states_its_own_cost() { + let cost = instrument_nanos(); + assert!(cost > 0, "the instrument measured itself at zero"); + // Generous: the point is that the figure is real, not that this machine is fast. A reading + // this far out would mean the calibration loop measured something other than the span. + assert!( + cost < 100_000, + "the instrument measured itself at {cost} ns a call" + ); + } +} diff --git a/crates/metal2vulkan-conformance/src/validated.rs b/crates/metal2vulkan-conformance/src/validated.rs index d7f132796..b7988e6ce 100644 --- a/crates/metal2vulkan-conformance/src/validated.rs +++ b/crates/metal2vulkan-conformance/src/validated.rs @@ -58,7 +58,7 @@ //! //! # How a complaint is attributed to a call //! -//! The child announces each [`Side`] call it is about to make on its standard +//! The child announces each [`Side`](crate::case::Side) call it is about to make on its standard //! error ([`MARKER`]), so Metal's own output and our markers interleave in one stream in the order //! they happened. Everything between two markers is the complaint of the call the first marker //! names. Nothing is matched against Apple's wording, so a new check in a release the suite has @@ -67,16 +67,7 @@ //! The message a recording keeps is stripped of `NSLog`'s timestamp and process prefix, because a //! recording holds nothing host-specific: the prefix carries this run's process id. -use crate::case::{ - Answer, ArgumentSlot, Bindings, Fill, FragmentFill, FragmentFilled, Handle, IndirectReadBack, - MeshCommand, MeshFunctions, MeshStep, PassOutcome, PlaneTexture, RateMapFacts, RateMapRequest, - SamplerSpec, ShaderSource, Side, StageInRegion, StageInput, TextureSpec, TileFacts, - TilePipelineSpec, TileStep, Venue, -}; use crate::recording::Validated; -use crate::transcript::Value; -use metal2vulkan::metal::state::DepthStencilDescriptor; -use metal2vulkan::metal::{BindingAccess, PixelFormat, RenderStages}; /// `MTL_DEBUG_LAYER`: Metal's API validation layer. pub const DEBUG_LAYER: (&str, &str) = ("MTL_DEBUG_LAYER", "1"); @@ -201,432 +192,22 @@ fn strip_prefix(line: &str) -> &str { /// A side that announces each call it is about to make, so the parent can attribute Metal's own /// output to the call that provoked it. It observes nothing and changes nothing else. -pub struct Announcing { - inner: S, -} +/// +/// It is [`crate::watch::Watching`] with this watcher: the forwarding lives there, in one impl, +/// shared with the timing wrapper, because two hand-written copies of it would be two places to +/// forget a method that `Side` gives a default to. +pub type Announcing = crate::watch::Watching; -impl Announcing { - /// `inner`, announcing its calls. - pub fn new(inner: S) -> Self { - Self { inner } - } +/// Announce each call on standard error, and nothing else. +#[derive(Clone, Copy, Debug, Default)] +pub struct Announce; - /// Announce `call` and go on. - fn at(&self, call: &str) { +impl crate::watch::Watcher for Announce { + /// Nothing to do when the call returns: the marker is the whole mechanism, and a marker on + /// the way out would double every line the parent has to read. + type Span = (); + + fn enter(&self, call: &'static str) { eprintln!("{MARKER}{call}"); } } - -/// Every call is forwarded, and every call is announced. -/// -/// **A forwarded method that is left out is a defect, not a gap**: `Side` gives most of its calls a -/// default that answers [`Failure::unavailable`](crate::case::Failure::unavailable), so an -/// unforwarded method would make `Announcing` answer "no such call" where `MetalSide` -/// answers perfectly well, and the compiler would say nothing. `the_announcing_side_forwards_every_call` -/// catches that by running the whole case set through both and comparing the transcripts, so the -/// trait can keep growing without this wrapper rotting. -impl Side for Announcing { - fn venue(&self) -> Venue { - self.inner.venue() - } - - fn library(&mut self, source: &ShaderSource<'_>) -> Answer { - self.at("library"); - self.inner.library(source) - } - - fn compute_pipeline(&mut self, library: Handle, entry: &str) -> Answer { - self.at("compute_pipeline"); - self.inner.compute_pipeline(library, entry) - } - - fn static_threadgroup_memory_length(&mut self, pipeline: Handle) -> Answer { - self.at("static_threadgroup_memory_length"); - self.inner.static_threadgroup_memory_length(pipeline) - } - - fn compute_pipeline_with_stage_input( - &mut self, - library: Handle, - entry: &str, - stage_input: &StageInput, - ) -> Answer { - self.at("compute_pipeline_with_stage_input"); - self.inner - .compute_pipeline_with_stage_input(library, entry, stage_input) - } - - fn buffer(&mut self, bytes: &[u8]) -> Answer { - self.at("buffer"); - self.inner.buffer(bytes) - } - - fn zeroed_buffer(&mut self, length: usize) -> Answer { - self.at("zeroed_buffer"); - self.inner.zeroed_buffer(length) - } - - fn texture_2d( - &mut self, - format: PixelFormat, - size: [u32; 2], - row_pitch: u32, - bytes: &[u8], - ) -> Answer { - self.at("texture_2d"); - self.inner.texture_2d(format, size, row_pitch, bytes) - } - - fn read_texture(&mut self, texture: Handle, size: [u32; 2], row_pitch: u32) -> Answer> { - self.at("read_texture"); - self.inner.read_texture(texture, size, row_pitch) - } - - fn texture_2d_in_role(&mut self, spec: &TextureSpec, bytes: &[u8]) -> Answer { - self.at("texture_2d_in_role"); - self.inner.texture_2d_in_role(spec, bytes) - } - - fn replace_region( - &mut self, - texture: Handle, - size: [u32; 2], - row_pitch: u32, - bytes: &[u8], - ) -> Answer<()> { - self.at("replace_region"); - self.inner.replace_region(texture, size, row_pitch, bytes) - } - - fn texture(&mut self, request: &crate::texture::TextureRequest<'_>) -> Answer { - self.at("texture"); - self.inner.texture(request) - } - - fn sampler(&mut self, spec: &SamplerSpec) -> Answer { - self.at("sampler"); - self.inner.sampler(spec) - } - - fn argument_buffer(&mut self, slots: &[ArgumentSlot]) -> Answer { - self.at("argument_buffer"); - self.inner.argument_buffer(slots) - } - - fn dispatch( - &mut self, - pipeline: Handle, - bindings: &Bindings<'_>, - threadgroups: [u32; 3], - threads: [u32; 3], - ) -> Answer { - self.at("dispatch"); - self.inner - .dispatch(pipeline, bindings, threadgroups, threads) - } - - fn dispatch_threads( - &mut self, - pipeline: Handle, - bindings: &Bindings<'_>, - stage_in: &[StageInRegion], - grid: [u32; 3], - threads: [u32; 3], - ) -> Answer { - self.at("dispatch_threads"); - self.inner - .dispatch_threads(pipeline, bindings, stage_in, grid, threads) - } - - fn wait(&mut self, command_buffer: Handle) -> Answer { - self.at("wait"); - self.inner.wait(command_buffer) - } - - fn read_buffer(&mut self, buffer: Handle, offset: u64, length: usize) -> Answer> { - self.at("read_buffer"); - self.inner.read_buffer(buffer, offset, length) - } - - fn announced(&mut self) -> Vec { - self.inner.announced() - } - - fn indirect_draw_read_back( - &mut self, - primitive_type: u64, - indexed: bool, - ) -> Answer { - self.at("indirect_draw_read_back"); - self.inner.indirect_draw_read_back(primitive_type, indexed) - } - - fn work(&mut self, work: &crate::work::Work) -> Answer { - self.at("work"); - self.inner.work(work) - } - - fn fragment_fill(&mut self, fill: &FragmentFill<'_>) -> Answer { - self.at("fragment_fill"); - self.inner.fragment_fill(fill) - } - - fn mesh_pipeline(&mut self, library: Handle, functions: &MeshFunctions<'_>) -> Answer { - self.at("mesh_pipeline"); - self.inner.mesh_pipeline(library, functions) - } - - fn mesh_pipeline_for_commands( - &mut self, - library: Handle, - functions: &MeshFunctions<'_>, - ) -> Answer { - self.at("mesh_pipeline_for_commands"); - self.inner.mesh_pipeline_for_commands(library, functions) - } - - fn render_target(&mut self, width: u32, height: u32) -> Answer { - self.at("render_target"); - self.inner.render_target(width, height) - } - - fn mesh_pass(&mut self, targets: &[Handle], steps: &[MeshStep]) -> Answer { - self.at("mesh_pass"); - self.inner.mesh_pass(targets, steps) - } - - fn mesh_command_buffer(&mut self, commands: &[MeshCommand]) -> Answer { - self.at("mesh_command_buffer"); - self.inner.mesh_command_buffer(commands) - } - - fn execute_mesh_commands( - &mut self, - targets: &[Handle], - commands: Handle, - used: &[Handle], - ) -> Answer { - self.at("execute_mesh_commands"); - self.inner.execute_mesh_commands(targets, commands, used) - } - - fn plane_texture(&mut self, buffer: Handle, over: &PlaneTexture) -> Answer { - self.at("plane_texture"); - self.inner.plane_texture(buffer, over) - } - - fn fill_texture(&mut self, texture: Handle, fill: &Fill) -> Answer { - self.at("fill_texture"); - self.inner.fill_texture(texture, fill) - } - - fn rate_map(&mut self, request: &RateMapRequest<'_>) -> Answer { - self.at("rate_map"); - self.inner.rate_map(request) - } - - fn rate_map_facts(&mut self, map: Handle, layers: &[u64]) -> Answer { - self.at("rate_map_facts"); - self.inner.rate_map_facts(map, layers) - } - - fn copy_rate_map_parameters(&mut self, map: Handle, into: Handle, offset: u64) -> Answer<()> { - self.at("copy_rate_map_parameters"); - self.inner.copy_rate_map_parameters(map, into, offset) - } - - fn tile_pipeline(&mut self, library: Handle, spec: &TilePipelineSpec<'_>) -> Answer { - self.at("tile_pipeline"); - self.inner.tile_pipeline(library, spec) - } - - fn tile_facts(&mut self, state: Handle) -> Answer { - self.at("tile_facts"); - self.inner.tile_facts(state) - } - - fn tile_pass( - &mut self, - targets: &[Handle], - tile: [u32; 2], - steps: &[TileStep], - ) -> Answer { - self.at("tile_pass"); - self.inner.tile_pass(targets, tile, steps) - } - - fn heap_texture_size_and_align( - &mut self, - query: &crate::texture_query::HeapTextureQuery, - ) -> Answer { - self.at("heap_texture_size_and_align"); - self.inner.heap_texture_size_and_align(query) - } - - fn makes_texture(&mut self, query: &crate::texture_query::HeapTextureQuery) -> Answer { - self.at("makes_texture"); - self.inner.makes_texture(query) - } - - fn buffer_texture( - &mut self, - request: &crate::buffer_texture::BufferTextureRequest, - ) -> Answer { - self.at("buffer_texture"); - self.inner.buffer_texture(request) - } - - fn sparse_tile_size( - &mut self, - query: &crate::sparse_query::SparseTileQuery, - ) -> Answer { - self.at("sparse_tile_size"); - self.inner.sparse_tile_size(query) - } - - fn sparse_tile_size_in_bytes(&mut self, page: crate::sparse_query::QueryPage) -> Answer { - self.at("sparse_tile_size_in_bytes"); - self.inner.sparse_tile_size_in_bytes(page) - } - - fn sparse_heap(&mut self, spec: &crate::sparse_query::SparseHeapSpec) -> Answer { - self.at("sparse_heap"); - self.inner.sparse_heap(spec) - } - - fn heap_facts(&mut self, heap: Handle) -> Answer { - self.at("heap_facts"); - self.inner.heap_facts(heap) - } - - fn heap_texture( - &mut self, - heap: Handle, - spec: &crate::sparse_query::SparseTextureSpec, - ) -> Answer { - self.at("heap_texture"); - self.inner.heap_texture(heap, spec) - } - - fn sparse_texture_facts( - &mut self, - texture: Handle, - ) -> Answer { - self.at("sparse_texture_facts"); - self.inner.sparse_texture_facts(texture) - } - - fn queue_slots( - &mut self, - max: Option, - cap: u32, - ) -> Answer { - self.at("queue_slots"); - self.inner.queue_slots(max, cap) - } - - fn read_texture_over( - &mut self, - texture: Handle, - size: [u32; 2], - row_pitch: u32, - before: &[u8], - ) -> Answer> { - self.at("read_texture_over"); - self.inner - .read_texture_over(texture, size, row_pitch, before) - } - - fn render_pipeline_with_reflection( - &mut self, - library: Handle, - vertex: &str, - fragment: &str, - attachment: PixelFormat, - ) -> Answer { - self.at("render_pipeline_with_reflection"); - self.inner - .render_pipeline_with_reflection(library, vertex, fragment, attachment) - } - - fn texture_accesses( - &mut self, - pipeline: Handle, - stage: RenderStages, - indices: &[u64], - ) -> Answer>> { - self.at("texture_accesses"); - self.inner.texture_accesses(pipeline, stage, indices) - } - - fn target(&mut self, spec: &crate::render::TargetSpec) -> Answer { - self.at("target"); - self.inner.target(spec) - } - - fn render_pipeline( - &mut self, - library: Handle, - spec: &crate::render::RenderPipelineSpec<'_>, - ) -> Answer { - self.at("render_pipeline"); - self.inner.render_pipeline(library, spec) - } - - fn depth_stencil_state(&mut self, spec: &DepthStencilDescriptor) -> Answer { - self.at("depth_stencil_state"); - self.inner.depth_stencil_state(spec) - } - - fn write_plane(&mut self, target: Handle, bytes: &[u8]) -> Answer<()> { - self.at("write_plane"); - self.inner.write_plane(target, bytes) - } - - fn read_plane(&mut self, target: Handle) -> Answer> { - self.at("read_plane"); - self.inner.read_plane(target) - } - - fn render(&mut self, work: &[crate::render::RenderWork]) -> Answer { - self.at("render"); - self.inner.render(work) - } - - fn handler_wait(&mut self, wait: crate::handler_waits::OwnWait) -> Answer { - self.at("handler_wait"); - self.inner.handler_wait(wait) - } - - fn shared_event_rises(&mut self, label: &str) -> Answer { - self.at("shared_event_rises"); - self.inner.shared_event_rises(label) - } - - fn event_cross_queue_wait(&mut self) -> Answer { - self.at("event_cross_queue_wait"); - self.inner.event_cross_queue_wait() - } - - fn event_highest_signal(&mut self, values: [u64; 2]) -> Answer { - self.at("event_highest_signal"); - self.inner.event_highest_signal(values) - } - - fn held_command_buffer(&mut self) -> Answer { - self.at("held_command_buffer"); - self.inner.held_command_buffer() - } - - fn signal_before_a_wait(&mut self) -> Answer { - self.at("signal_before_a_wait"); - self.inner.signal_before_a_wait() - } - - fn scheduled_handler_order( - &mut self, - ) -> Answer { - self.at("scheduled_handler_order"); - self.inner.scheduled_handler_order() - } -} diff --git a/crates/metal2vulkan-conformance/src/watch.rs b/crates/metal2vulkan-conformance/src/watch.rs new file mode 100644 index 000000000..ebfd993ea --- /dev/null +++ b/crates/metal2vulkan-conformance/src/watch.rs @@ -0,0 +1,790 @@ +//! One wrapper that forwards every [`Side`] call and lets something watch the boundary. +//! +//! Two parts of the suite need to do something **at each call** without changing what the call +//! does: [`crate::validated`] announces the call's name so the parent process can attribute +//! Metal's own output to it, and [`crate::times`] measures what the call cost. Both want the same +//! narrow span — around the Metal or Vulkan call and nothing else — and neither wants to reach +//! inside [`crate::metal_side::MetalSide`] or [`crate::runtime_side::RuntimeSide`], because a span +//! placed separately in each of them is two spans that can drift apart, and a cost comparison of +//! two legs measured in different places is not a comparison. +//! +//! So there is **one** forwarding impl, here, parameterised by what happens at the boundary. That +//! is not tidiness: `Side`'s methods mostly carry a default that answers +//! [`Failure::unavailable`](crate::case::Failure::unavailable), so a wrapper that forgets to +//! forward one answers "no such call" where the wrapped side answers fine, **and the compiler says +//! nothing**. A second hand-written wrapper would be a second copy of that hazard, in a trait +//! several streams are extending. One impl means one place to forget, and +//! `the_announcing_side_forwards_every_call` already watches that place. +//! +//! # What the span covers, and what it deliberately does not +//! +//! The span opens on entry to the `Side` method and closes when it returns, so it holds the Metal +//! or Vulkan call plus the side's own handle bookkeeping, and **excludes** building the transcript, +//! reading a fixture, hashing an input and everything else the harness does between calls. That is +//! the narrowest boundary both legs share. +//! +//! Two methods are forwarded without a span, because neither is a call to the implementation under +//! test: [`Side::venue`] answers a label, and [`Side::announced`] drains the notices our own side +//! collected, which Metal has no counterpart for at all. Timing them would put the harness's own +//! bookkeeping in the table. + +use crate::case::{ + Answer, ArgumentSlot, Bindings, Fill, FragmentFill, FragmentFilled, Handle, IndirectReadBack, + MeshCommand, MeshFunctions, MeshStep, PassOutcome, PlaneTexture, RateMapFacts, RateMapRequest, + SamplerSpec, ShaderSource, Side, StageInRegion, StageInput, TextureSpec, TileFacts, + TilePipelineSpec, TileStep, Venue, +}; +use crate::transcript::Value; +use metal2vulkan::metal::state::DepthStencilDescriptor; +use metal2vulkan::metal::{BindingAccess, PixelFormat, RenderStages}; + +/// What happens at a [`Side`] call's boundary. +/// +/// `enter` is handed the call's name and answers a span. The span is dropped when the call +/// returns, so a watcher that wants the call's *end* does its work in the span's `Drop`. A span +/// must not borrow the watcher, because the wrapper holds the span across the forwarded call and +/// that call needs the side mutably; a watcher with state shares it through a handle of its own +/// instead. +pub trait Watcher { + /// What `enter` answers, dropped when the call returns. + type Span; + + /// `call` is about to be made. + fn enter(&self, call: &'static str) -> Self::Span; +} + +/// `inner`, with `watcher` watching every call it is asked to make. It observes nothing of the +/// answers and changes none of them. +pub struct Watching { + inner: S, + watcher: W, +} + +impl Watching { + /// `inner`, watched by a watcher that needs no setting up. + pub fn new(inner: S) -> Self { + Self { + inner, + watcher: W::default(), + } + } +} + +impl Watching { + /// `inner`, watched by `watcher`. + pub fn with(inner: S, watcher: W) -> Self { + Self { inner, watcher } + } + + /// The watched side back. + pub fn into_inner(self) -> S { + self.inner + } + + /// Open `call`'s span. + /// + /// It takes `&self` and answers a span that borrows nothing of `self`, which is what lets the + /// caller hold the span across a forwarded call that needs `self.inner` mutably. + fn watch(&self, call: &'static str) -> W::Span { + self.watcher.enter(call) + } +} + +/// Every call is forwarded, and every call opens a span. +/// +/// **A forwarded method that is left out is a defect, not a gap**: `Side` gives most of its calls a +/// default that answers [`Failure::unavailable`](crate::case::Failure::unavailable), so an +/// unforwarded method would make a wrapped side answer "no such call" where the side itself +/// answers perfectly well, and the compiler would say nothing. `the_announcing_side_forwards_every_call` +/// catches that by running the whole case set through both and comparing the transcripts, so the +/// trait can keep growing without this wrapper rotting. +/// +/// The same test covers the timing side too, because there is one impl rather than one per +/// watcher. A call left out would also read as a *free* call in the cost table -- the worst +/// shape of the same defect, since a missing measurement there looks like good news. +impl Side for Watching { + fn venue(&self) -> Venue { + self.inner.venue() + } + + fn library(&mut self, source: &ShaderSource<'_>) -> Answer { + let _span = self.watch("library"); + self.inner.library(source) + } + + fn compute_pipeline(&mut self, library: Handle, entry: &str) -> Answer { + let _span = self.watch("compute_pipeline"); + self.inner.compute_pipeline(library, entry) + } + + fn static_threadgroup_memory_length(&mut self, pipeline: Handle) -> Answer { + let _span = self.watch("static_threadgroup_memory_length"); + self.inner.static_threadgroup_memory_length(pipeline) + } + + fn compute_pipeline_with_stage_input( + &mut self, + library: Handle, + entry: &str, + stage_input: &StageInput, + ) -> Answer { + let _span = self.watch("compute_pipeline_with_stage_input"); + self.inner + .compute_pipeline_with_stage_input(library, entry, stage_input) + } + + fn buffer(&mut self, bytes: &[u8]) -> Answer { + let _span = self.watch("buffer"); + self.inner.buffer(bytes) + } + + fn zeroed_buffer(&mut self, length: usize) -> Answer { + let _span = self.watch("zeroed_buffer"); + self.inner.zeroed_buffer(length) + } + + fn texture_2d( + &mut self, + format: PixelFormat, + size: [u32; 2], + row_pitch: u32, + bytes: &[u8], + ) -> Answer { + let _span = self.watch("texture_2d"); + self.inner.texture_2d(format, size, row_pitch, bytes) + } + + fn read_texture(&mut self, texture: Handle, size: [u32; 2], row_pitch: u32) -> Answer> { + let _span = self.watch("read_texture"); + self.inner.read_texture(texture, size, row_pitch) + } + + fn texture_2d_in_role(&mut self, spec: &TextureSpec, bytes: &[u8]) -> Answer { + let _span = self.watch("texture_2d_in_role"); + self.inner.texture_2d_in_role(spec, bytes) + } + + fn replace_region( + &mut self, + texture: Handle, + size: [u32; 2], + row_pitch: u32, + bytes: &[u8], + ) -> Answer<()> { + let _span = self.watch("replace_region"); + self.inner.replace_region(texture, size, row_pitch, bytes) + } + + fn texture(&mut self, request: &crate::texture::TextureRequest<'_>) -> Answer { + let _span = self.watch("texture"); + self.inner.texture(request) + } + + fn sampler(&mut self, spec: &SamplerSpec) -> Answer { + let _span = self.watch("sampler"); + self.inner.sampler(spec) + } + + fn argument_buffer(&mut self, slots: &[ArgumentSlot]) -> Answer { + let _span = self.watch("argument_buffer"); + self.inner.argument_buffer(slots) + } + + fn dispatch( + &mut self, + pipeline: Handle, + bindings: &Bindings<'_>, + threadgroups: [u32; 3], + threads: [u32; 3], + ) -> Answer { + let _span = self.watch("dispatch"); + self.inner + .dispatch(pipeline, bindings, threadgroups, threads) + } + + fn dispatch_threads( + &mut self, + pipeline: Handle, + bindings: &Bindings<'_>, + stage_in: &[StageInRegion], + grid: [u32; 3], + threads: [u32; 3], + ) -> Answer { + let _span = self.watch("dispatch_threads"); + self.inner + .dispatch_threads(pipeline, bindings, stage_in, grid, threads) + } + + fn wait(&mut self, command_buffer: Handle) -> Answer { + let _span = self.watch("wait"); + self.inner.wait(command_buffer) + } + + fn read_buffer(&mut self, buffer: Handle, offset: u64, length: usize) -> Answer> { + let _span = self.watch("read_buffer"); + self.inner.read_buffer(buffer, offset, length) + } + + fn buffer_texture( + &mut self, + request: &crate::buffer_texture::BufferTextureRequest, + ) -> Answer { + let _span = self.watch("buffer_texture"); + self.inner.buffer_texture(request) + } + + fn write_plane(&mut self, target: Handle, bytes: &[u8]) -> Answer<()> { + let _span = self.watch("write_plane"); + self.inner.write_plane(target, bytes) + } + + fn read_plane(&mut self, target: Handle) -> Answer> { + let _span = self.watch("read_plane"); + self.inner.read_plane(target) + } + + fn announced(&mut self) -> Vec { + self.inner.announced() + } + + fn indirect_draw_read_back( + &mut self, + primitive_type: u64, + indexed: bool, + ) -> Answer { + let _span = self.watch("indirect_draw_read_back"); + self.inner.indirect_draw_read_back(primitive_type, indexed) + } + + fn work(&mut self, work: &crate::work::Work) -> Answer { + let _span = self.watch("work"); + self.inner.work(work) + } + + fn fragment_fill(&mut self, fill: &FragmentFill<'_>) -> Answer { + let _span = self.watch("fragment_fill"); + self.inner.fragment_fill(fill) + } + + fn mesh_pipeline(&mut self, library: Handle, functions: &MeshFunctions<'_>) -> Answer { + let _span = self.watch("mesh_pipeline"); + self.inner.mesh_pipeline(library, functions) + } + + fn mesh_pipeline_for_commands( + &mut self, + library: Handle, + functions: &MeshFunctions<'_>, + ) -> Answer { + let _span = self.watch("mesh_pipeline_for_commands"); + self.inner.mesh_pipeline_for_commands(library, functions) + } + + fn render_target(&mut self, width: u32, height: u32) -> Answer { + let _span = self.watch("render_target"); + self.inner.render_target(width, height) + } + + fn mesh_pass(&mut self, targets: &[Handle], steps: &[MeshStep]) -> Answer { + let _span = self.watch("mesh_pass"); + self.inner.mesh_pass(targets, steps) + } + + fn mesh_command_buffer(&mut self, commands: &[MeshCommand]) -> Answer { + let _span = self.watch("mesh_command_buffer"); + self.inner.mesh_command_buffer(commands) + } + + fn execute_mesh_commands( + &mut self, + targets: &[Handle], + commands: Handle, + used: &[Handle], + ) -> Answer { + let _span = self.watch("execute_mesh_commands"); + self.inner.execute_mesh_commands(targets, commands, used) + } + + fn plane_texture(&mut self, buffer: Handle, over: &PlaneTexture) -> Answer { + let _span = self.watch("plane_texture"); + self.inner.plane_texture(buffer, over) + } + + fn fill_texture(&mut self, texture: Handle, fill: &Fill) -> Answer { + let _span = self.watch("fill_texture"); + self.inner.fill_texture(texture, fill) + } + + fn rate_map(&mut self, request: &RateMapRequest<'_>) -> Answer { + let _span = self.watch("rate_map"); + self.inner.rate_map(request) + } + + fn rate_map_facts(&mut self, map: Handle, layers: &[u64]) -> Answer { + let _span = self.watch("rate_map_facts"); + self.inner.rate_map_facts(map, layers) + } + + fn copy_rate_map_parameters(&mut self, map: Handle, into: Handle, offset: u64) -> Answer<()> { + let _span = self.watch("copy_rate_map_parameters"); + self.inner.copy_rate_map_parameters(map, into, offset) + } + + fn tile_pipeline(&mut self, library: Handle, spec: &TilePipelineSpec<'_>) -> Answer { + let _span = self.watch("tile_pipeline"); + self.inner.tile_pipeline(library, spec) + } + + fn tile_facts(&mut self, state: Handle) -> Answer { + let _span = self.watch("tile_facts"); + self.inner.tile_facts(state) + } + + fn tile_pass( + &mut self, + targets: &[Handle], + tile: [u32; 2], + steps: &[TileStep], + ) -> Answer { + let _span = self.watch("tile_pass"); + self.inner.tile_pass(targets, tile, steps) + } + + fn heap_texture_size_and_align( + &mut self, + query: &crate::texture_query::HeapTextureQuery, + ) -> Answer { + let _span = self.watch("heap_texture_size_and_align"); + self.inner.heap_texture_size_and_align(query) + } + + fn makes_texture(&mut self, query: &crate::texture_query::HeapTextureQuery) -> Answer { + let _span = self.watch("makes_texture"); + self.inner.makes_texture(query) + } + + fn sparse_tile_size( + &mut self, + query: &crate::sparse_query::SparseTileQuery, + ) -> Answer { + let _span = self.watch("sparse_tile_size"); + self.inner.sparse_tile_size(query) + } + + fn sparse_tile_size_in_bytes(&mut self, page: crate::sparse_query::QueryPage) -> Answer { + let _span = self.watch("sparse_tile_size_in_bytes"); + self.inner.sparse_tile_size_in_bytes(page) + } + + fn sparse_heap(&mut self, spec: &crate::sparse_query::SparseHeapSpec) -> Answer { + let _span = self.watch("sparse_heap"); + self.inner.sparse_heap(spec) + } + + fn heap_facts(&mut self, heap: Handle) -> Answer { + let _span = self.watch("heap_facts"); + self.inner.heap_facts(heap) + } + + fn heap_texture( + &mut self, + heap: Handle, + spec: &crate::sparse_query::SparseTextureSpec, + ) -> Answer { + let _span = self.watch("heap_texture"); + self.inner.heap_texture(heap, spec) + } + + fn sparse_texture_facts( + &mut self, + texture: Handle, + ) -> Answer { + let _span = self.watch("sparse_texture_facts"); + self.inner.sparse_texture_facts(texture) + } + + fn queue_slots( + &mut self, + max: Option, + cap: u32, + ) -> Answer { + let _span = self.watch("queue_slots"); + self.inner.queue_slots(max, cap) + } + + fn read_texture_over( + &mut self, + texture: Handle, + size: [u32; 2], + row_pitch: u32, + before: &[u8], + ) -> Answer> { + let _span = self.watch("read_texture_over"); + self.inner + .read_texture_over(texture, size, row_pitch, before) + } + + fn render_pipeline_with_reflection( + &mut self, + library: Handle, + vertex: &str, + fragment: &str, + attachment: PixelFormat, + ) -> Answer { + let _span = self.watch("render_pipeline_with_reflection"); + self.inner + .render_pipeline_with_reflection(library, vertex, fragment, attachment) + } + + fn texture_accesses( + &mut self, + pipeline: Handle, + stage: RenderStages, + indices: &[u64], + ) -> Answer>> { + let _span = self.watch("texture_accesses"); + self.inner.texture_accesses(pipeline, stage, indices) + } + + fn target(&mut self, spec: &crate::render::TargetSpec) -> Answer { + let _span = self.watch("target"); + self.inner.target(spec) + } + + fn render_pipeline( + &mut self, + library: Handle, + spec: &crate::render::RenderPipelineSpec<'_>, + ) -> Answer { + let _span = self.watch("render_pipeline"); + self.inner.render_pipeline(library, spec) + } + + fn depth_stencil_state(&mut self, spec: &DepthStencilDescriptor) -> Answer { + let _span = self.watch("depth_stencil_state"); + self.inner.depth_stencil_state(spec) + } + + fn render(&mut self, work: &[crate::render::RenderWork]) -> Answer { + let _span = self.watch("render"); + self.inner.render(work) + } + + fn handler_wait(&mut self, wait: crate::handler_waits::OwnWait) -> Answer { + let _span = self.watch("handler_wait"); + self.inner.handler_wait(wait) + } + + fn shared_event_rises(&mut self, label: &str) -> Answer { + let _span = self.watch("shared_event_rises"); + self.inner.shared_event_rises(label) + } + + fn event_cross_queue_wait(&mut self) -> Answer { + let _span = self.watch("event_cross_queue_wait"); + self.inner.event_cross_queue_wait() + } + + fn event_highest_signal(&mut self, values: [u64; 2]) -> Answer { + let _span = self.watch("event_highest_signal"); + self.inner.event_highest_signal(values) + } + + fn held_command_buffer(&mut self) -> Answer { + let _span = self.watch("held_command_buffer"); + self.inner.held_command_buffer() + } + + fn signal_before_a_wait(&mut self) -> Answer { + let _span = self.watch("signal_before_a_wait"); + self.inner.signal_before_a_wait() + } + + fn scheduled_handler_order( + &mut self, + ) -> Answer { + let _span = self.watch("scheduled_handler_order"); + self.inner.scheduled_handler_order() + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::case::Failure; + + /// A shader source no side reads: the stub answers without looking at it. + fn stub_source() -> ShaderSource<'static> { + ShaderSource { + bitcode: &[], + air_text: "", + entry: "main", + } + } + + /// A side that answers nothing and records which calls it was asked for: enough to prove the + /// wrapper forwards a call, opens exactly one span for it, and changes neither the answer nor + /// the order. + #[derive(Default)] + struct Stub { + asked: Vec<&'static str>, + } + + impl Side for Stub { + fn venue(&self) -> Venue { + Venue { + device: "stub".to_owned(), + driver: "stub".to_owned(), + api: "stub".to_owned(), + metal_level: "stub".to_owned(), + } + } + + fn library(&mut self, _source: &ShaderSource<'_>) -> Answer { + self.asked.push("library"); + Ok(Handle(7)) + } + + fn compute_pipeline(&mut self, _library: Handle, _entry: &str) -> Answer { + self.asked.push("compute_pipeline"); + Err(Failure::named("Stub", "nothing here".to_owned())) + } + + fn compute_pipeline_with_stage_input( + &mut self, + _library: Handle, + _entry: &str, + _stage_input: &StageInput, + ) -> Answer { + self.asked.push("compute_pipeline_with_stage_input"); + Ok(Handle(0)) + } + + fn buffer(&mut self, _bytes: &[u8]) -> Answer { + self.asked.push("buffer"); + Ok(Handle(1)) + } + + fn zeroed_buffer(&mut self, _length: usize) -> Answer { + self.asked.push("zeroed_buffer"); + Ok(Handle(2)) + } + + fn texture_2d( + &mut self, + _format: PixelFormat, + _size: [u32; 2], + _row_pitch: u32, + _bytes: &[u8], + ) -> Answer { + self.asked.push("texture_2d"); + Ok(Handle(3)) + } + + fn read_texture( + &mut self, + _texture: Handle, + _size: [u32; 2], + _row_pitch: u32, + ) -> Answer> { + self.asked.push("read_texture"); + Ok(Vec::new()) + } + + fn dispatch( + &mut self, + _pipeline: Handle, + _bindings: &Bindings<'_>, + _threadgroups: [u32; 3], + _threads: [u32; 3], + ) -> Answer { + self.asked.push("dispatch"); + Ok(Handle(4)) + } + + fn dispatch_threads( + &mut self, + _pipeline: Handle, + _bindings: &Bindings<'_>, + _stage_in: &[StageInRegion], + _grid: [u32; 3], + _threads: [u32; 3], + ) -> Answer { + self.asked.push("dispatch_threads"); + Ok(Handle(5)) + } + + fn wait(&mut self, _command_buffer: Handle) -> Answer { + self.asked.push("wait"); + Ok(Value::Uint(0)) + } + + fn read_buffer( + &mut self, + _buffer: Handle, + _offset: u64, + _length: usize, + ) -> Answer> { + self.asked.push("read_buffer"); + Ok(Vec::new()) + } + + fn announced(&mut self) -> Vec { + self.asked.push("announced"); + Vec::new() + } + } + + /// One span per call, named for the call, in the order the calls were made — and the answers + /// are the wrapped side's own, including a typed error. + /// + /// The last part is what makes the wrapper safe to put under a measurement: a wrapper that + /// swallowed an error would turn a refusal into a cheap call and the cost table would read it + /// as good news. + #[test] + fn a_span_is_opened_for_each_call_and_the_answer_is_the_sides_own() { + let timer = crate::times::Timer::new(); + let mut side = Watching::with(Stub::default(), timer.clone()); + assert_eq!(side.library(&stub_source()), Ok(Handle(7))); + assert!(side.compute_pipeline(Handle(7), "main").is_err()); + assert_eq!(side.buffer(&[1, 2, 3]), Ok(Handle(1))); + assert_eq!(side.wait(Handle(0)), Ok(Value::Uint(0))); + let observed = timer.take(); + let names: Vec<&str> = observed.iter().map(|one| one.call).collect(); + assert_eq!(names, ["library", "compute_pipeline", "buffer", "wait"]); + // The refused call is measured like any other: a refusal has a cost and hiding it would + // make a gap look free. + assert_eq!(observed.len(), 4); + } + + /// `venue` and `announced` are forwarded with **no** span, because neither is a call to the + /// implementation under test. Timing them would put the harness's own bookkeeping in the + /// table, and `announced` has no Metal counterpart at all. + #[test] + fn the_two_calls_that_are_not_the_implementations_open_no_span() { + let timer = crate::times::Timer::new(); + let mut side = Watching::with(Stub::default(), timer.clone()); + let _ = side.venue(); + let _ = side.announced(); + assert!( + timer.is_empty(), + "venue or announced opened a span: {:?}", + timer.take() + ); + } + + /// The span closes when the call returns, not before: a call that takes a known time is + /// measured as at least that long. + /// + /// Without this the wrapper could record a zero for every call and every table would read as + /// free — the one failure of a timing layer that looks like success. + #[test] + fn a_span_covers_the_call_rather_than_closing_early() { + /// A side whose one call sleeps, so the span has something to measure. + struct Slow(std::time::Duration); + impl Side for Slow { + fn venue(&self) -> Venue { + Venue { + device: "slow".to_owned(), + driver: "slow".to_owned(), + api: "slow".to_owned(), + metal_level: "slow".to_owned(), + } + } + fn library(&mut self, _source: &ShaderSource<'_>) -> Answer { + std::thread::sleep(self.0); + Ok(Handle(0)) + } + fn compute_pipeline(&mut self, _library: Handle, _entry: &str) -> Answer { + Err(Failure::unavailable("compute_pipeline")) + } + fn compute_pipeline_with_stage_input( + &mut self, + _library: Handle, + _entry: &str, + _stage_input: &StageInput, + ) -> Answer { + Err(Failure::unavailable("compute_pipeline_with_stage_input")) + } + fn buffer(&mut self, _bytes: &[u8]) -> Answer { + Err(Failure::unavailable("buffer")) + } + fn zeroed_buffer(&mut self, _length: usize) -> Answer { + Err(Failure::unavailable("zeroed_buffer")) + } + fn texture_2d( + &mut self, + _format: PixelFormat, + _size: [u32; 2], + _row_pitch: u32, + _bytes: &[u8], + ) -> Answer { + Err(Failure::unavailable("texture_2d")) + } + fn read_texture( + &mut self, + _texture: Handle, + _size: [u32; 2], + _row_pitch: u32, + ) -> Answer> { + Err(Failure::unavailable("read_texture")) + } + fn dispatch( + &mut self, + _pipeline: Handle, + _bindings: &Bindings<'_>, + _threadgroups: [u32; 3], + _threads: [u32; 3], + ) -> Answer { + Err(Failure::unavailable("dispatch")) + } + fn dispatch_threads( + &mut self, + _pipeline: Handle, + _bindings: &Bindings<'_>, + _stage_in: &[StageInRegion], + _grid: [u32; 3], + _threads: [u32; 3], + ) -> Answer { + Err(Failure::unavailable("dispatch_threads")) + } + fn wait(&mut self, _command_buffer: Handle) -> Answer { + Err(Failure::unavailable("wait")) + } + fn read_buffer( + &mut self, + _buffer: Handle, + _offset: u64, + _length: usize, + ) -> Answer> { + Err(Failure::unavailable("read_buffer")) + } + fn announced(&mut self) -> Vec { + Vec::new() + } + } + let slept = std::time::Duration::from_millis(20); + let timer = crate::times::Timer::new(); + let mut side = Watching::with(Slow(slept), timer.clone()); + let _ = side.library(&stub_source()); + let observed = timer.take(); + let [one] = observed.as_slice() else { + panic!("one call, one observation: {observed:?}"); + }; + let slept = u64::try_from(slept.as_nanos()).unwrap(); + assert!( + one.wall >= slept, + "the span read {} ns for a call that slept {slept} ns, so it closed before the call \ + returned", + one.wall + ); + // Asleep is not on the CPU, so nearly all of it must land in `blocked` rather than in the + // caller's own CPU time. That is the attribution the whole design turns on. + assert!( + one.blocked() > one.on_cpu, + "a sleeping call read {} ns on cpu and {} ns blocked", + one.on_cpu, + one.blocked() + ); + } +}