@cratis/pi 7.102.0 → 7.103.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (140) hide show
  1. package/package/corpus/harnesses/copilot/instructions/profiles.instructions.md +10 -1
  2. package/package/corpus/harnesses/copilot/instructions/pull-requests.instructions.md +2 -0
  3. package/package/corpus/harnesses/copilot/instructions/secrets.instructions.md +4 -0
  4. package/package/corpus/hooks/README.md +11 -1
  5. package/package/corpus/hooks/scripts/cratis-check-pr.mjs +12 -1
  6. package/package/corpus/hooks/scripts/cratis-guard-secrets.sh +79 -23
  7. package/package/corpus/hooks/scripts/cratis-guard-writes.sh +145 -40
  8. package/package/corpus/rules/profiles.md +10 -1
  9. package/package/corpus/rules/pull-requests.md +2 -0
  10. package/package/corpus/rules/secrets.md +4 -0
  11. package/package/corpus/skills/analyzing-dotnet-performance/LICENSE +23 -0
  12. package/package/corpus/skills/analyzing-dotnet-performance/NOTICE +36 -0
  13. package/package/corpus/skills/analyzing-dotnet-performance/SKILL.md +214 -0
  14. package/package/corpus/skills/analyzing-dotnet-performance/references/async-patterns.md +122 -0
  15. package/package/corpus/skills/analyzing-dotnet-performance/references/collections-and-linq.md +220 -0
  16. package/package/corpus/skills/analyzing-dotnet-performance/references/critical-patterns.md +291 -0
  17. package/package/corpus/skills/analyzing-dotnet-performance/references/io-and-serialization.md +135 -0
  18. package/package/corpus/skills/analyzing-dotnet-performance/references/memory-and-strings.md +219 -0
  19. package/package/corpus/skills/analyzing-dotnet-performance/references/regex-patterns.md +95 -0
  20. package/package/corpus/skills/analyzing-dotnet-performance/references/structural-patterns.md +38 -0
  21. package/package/corpus/skills/binlog-generation/LICENSE +23 -0
  22. package/package/corpus/skills/binlog-generation/NOTICE +22 -0
  23. package/package/corpus/skills/binlog-generation/SKILL.md +129 -0
  24. package/package/corpus/skills/check-bin-obj-clash/LICENSE +23 -0
  25. package/package/corpus/skills/check-bin-obj-clash/NOTICE +27 -0
  26. package/package/corpus/skills/check-bin-obj-clash/SKILL.md +127 -0
  27. package/package/corpus/skills/check-bin-obj-clash/references/common-causes-and-fixes.md +206 -0
  28. package/package/corpus/skills/coverage-analysis/LICENSE +23 -0
  29. package/package/corpus/skills/coverage-analysis/NOTICE +32 -0
  30. package/package/corpus/skills/coverage-analysis/SKILL.md +198 -0
  31. package/package/corpus/skills/coverage-analysis/references/guidelines.md +68 -0
  32. package/package/corpus/skills/coverage-analysis/references/output-format.md +91 -0
  33. package/package/corpus/skills/coverage-analysis/references/report-generation.md +58 -0
  34. package/package/corpus/skills/coverage-analysis/references/setup-discovery.md +307 -0
  35. package/package/corpus/skills/coverage-analysis/scripts/Compute-CrapScores.ps1 +80 -0
  36. package/package/corpus/skills/coverage-analysis/scripts/CoverageData.ps1 +272 -0
  37. package/package/corpus/skills/coverage-analysis/scripts/Extract-MethodCoverage.ps1 +65 -0
  38. package/package/corpus/skills/csharp-refactoring/LICENSE +23 -0
  39. package/package/corpus/skills/csharp-refactoring/NOTICE +22 -0
  40. package/package/corpus/skills/csharp-refactoring/SKILL.md +175 -0
  41. package/package/corpus/skills/csharp-refactoring/references/operation-catalog.md +37 -0
  42. package/package/corpus/skills/directory-build-organization/LICENSE +23 -0
  43. package/package/corpus/skills/directory-build-organization/NOTICE +21 -0
  44. package/package/corpus/skills/directory-build-organization/SKILL.md +205 -0
  45. package/package/corpus/skills/directory-build-organization/references/common-patterns.md +56 -0
  46. package/package/corpus/skills/directory-build-organization/references/multi-level-examples.md +167 -0
  47. package/package/corpus/skills/directory-build-organization/references/targetframework-props-pitfall.md +54 -0
  48. package/package/corpus/skills/dotnet-aot-compat/LICENSE +23 -0
  49. package/package/corpus/skills/dotnet-aot-compat/NOTICE +18 -0
  50. package/package/corpus/skills/dotnet-aot-compat/SKILL.md +265 -0
  51. package/package/corpus/skills/dotnet-aot-compat/references/polyfills.md +43 -0
  52. package/package/corpus/skills/dotnet-trace-collect/LICENSE +23 -0
  53. package/package/corpus/skills/dotnet-trace-collect/NOTICE +65 -0
  54. package/package/corpus/skills/dotnet-trace-collect/SKILL.md +116 -0
  55. package/package/corpus/skills/dotnet-trace-collect/references/dotnet-monitor.md +97 -0
  56. package/package/corpus/skills/dotnet-trace-collect/references/dotnet-trace-collect-linux.md +84 -0
  57. package/package/corpus/skills/dotnet-trace-collect/references/dotnet-trace-collect.md +91 -0
  58. package/package/corpus/skills/dotnet-trace-collect/references/perfcollect.md +200 -0
  59. package/package/corpus/skills/dotnet-trace-collect/references/perfview.md +141 -0
  60. package/package/corpus/skills/dotnet-trace-collect/references/tool-selection.md +160 -0
  61. package/package/corpus/skills/dump-collect/LICENSE +23 -0
  62. package/package/corpus/skills/dump-collect/NOTICE +40 -0
  63. package/package/corpus/skills/dump-collect/SKILL.md +97 -0
  64. package/package/corpus/skills/dump-collect/references/container-dumps.md +412 -0
  65. package/package/corpus/skills/dump-collect/references/coreclr-dumps.md +108 -0
  66. package/package/corpus/skills/dump-collect/references/nativeaot-dumps.md +280 -0
  67. package/package/corpus/skills/eliminate-redundant-restores/LICENSE +23 -0
  68. package/package/corpus/skills/eliminate-redundant-restores/NOTICE +19 -0
  69. package/package/corpus/skills/eliminate-redundant-restores/SKILL.md +112 -0
  70. package/package/corpus/skills/extension-points/LICENSE +23 -0
  71. package/package/corpus/skills/extension-points/NOTICE +18 -0
  72. package/package/corpus/skills/extension-points/SKILL.md +248 -0
  73. package/package/corpus/skills/filter-syntax/LICENSE +23 -0
  74. package/package/corpus/skills/filter-syntax/NOTICE +17 -0
  75. package/package/corpus/skills/filter-syntax/SKILL.md +179 -0
  76. package/package/corpus/skills/including-generated-files/LICENSE +23 -0
  77. package/package/corpus/skills/including-generated-files/NOTICE +17 -0
  78. package/package/corpus/skills/including-generated-files/SKILL.md +139 -0
  79. package/package/corpus/skills/microbenchmarking/LICENSE +23 -0
  80. package/package/corpus/skills/microbenchmarking/NOTICE +36 -0
  81. package/package/corpus/skills/microbenchmarking/SKILL.md +131 -0
  82. package/package/corpus/skills/microbenchmarking/references/bdn-internals-and-tuning.md +143 -0
  83. package/package/corpus/skills/microbenchmarking/references/comparison-strategies.md +200 -0
  84. package/package/corpus/skills/microbenchmarking/references/diagnosers-and-exporters.md +150 -0
  85. package/package/corpus/skills/microbenchmarking/references/project-setup-and-running.md +189 -0
  86. package/package/corpus/skills/microbenchmarking/references/writing-benchmarks.md +310 -0
  87. package/package/corpus/skills/msbuild/LICENSE +23 -0
  88. package/package/corpus/skills/msbuild/NOTICE +55 -0
  89. package/package/corpus/skills/msbuild/SKILL.md +117 -0
  90. package/package/corpus/skills/msbuild/references/antipatterns/additional-antipatterns.md +291 -0
  91. package/package/corpus/skills/msbuild/references/antipatterns/incremental-build-inputs-outputs.md +57 -0
  92. package/package/corpus/skills/msbuild/references/antipatterns/private-assets.md +29 -0
  93. package/package/corpus/skills/msbuild/references/binlog-failure-analysis.md +85 -0
  94. package/package/corpus/skills/msbuild/references/binlog-generation.md +69 -0
  95. package/package/corpus/skills/msbuild/references/build-perf-baseline.md +493 -0
  96. package/package/corpus/skills/msbuild/references/build-perf-diagnostics.md +268 -0
  97. package/package/corpus/skills/msbuild/references/copy-to-output-directory.md +183 -0
  98. package/package/corpus/skills/msbuild/references/eval-performance.md +190 -0
  99. package/package/corpus/skills/msbuild/references/extension-points.md +281 -0
  100. package/package/corpus/skills/msbuild/references/incremental-build.md +365 -0
  101. package/package/corpus/skills/msbuild/references/msbuild-antipatterns.md +401 -0
  102. package/package/corpus/skills/orleans/LICENSE +21 -0
  103. package/package/corpus/skills/orleans/NOTICE +64 -0
  104. package/package/corpus/skills/orleans/SKILL.md +140 -0
  105. package/package/corpus/skills/orleans/references/anti-patterns.md +660 -0
  106. package/package/corpus/skills/orleans/references/configuration-api.md +933 -0
  107. package/package/corpus/skills/orleans/references/examples.md +66 -0
  108. package/package/corpus/skills/orleans/references/grain-api.md +784 -0
  109. package/package/corpus/skills/orleans/references/grains.md +75 -0
  110. package/package/corpus/skills/orleans/references/hosting.md +71 -0
  111. package/package/corpus/skills/orleans/references/implementation.md +591 -0
  112. package/package/corpus/skills/orleans/references/official-docs-index.md +250 -0
  113. package/package/corpus/skills/orleans/references/patterns.md +811 -0
  114. package/package/corpus/skills/orleans/references/persistence-api.md +495 -0
  115. package/package/corpus/skills/orleans/references/primitive-selection.md +35 -0
  116. package/package/corpus/skills/orleans/references/scheduling-and-services.md +295 -0
  117. package/package/corpus/skills/orleans/references/serialization-api.md +299 -0
  118. package/package/corpus/skills/orleans/references/streaming-api.md +396 -0
  119. package/package/corpus/skills/orleans/references/testing-patterns.md +210 -0
  120. package/package/corpus/skills/platform-detection/LICENSE +23 -0
  121. package/package/corpus/skills/platform-detection/NOTICE +17 -0
  122. package/package/corpus/skills/platform-detection/SKILL.md +230 -0
  123. package/package/corpus/skills/platform-detection/references/command-mode.md +27 -0
  124. package/package/corpus/skills/profiling/LICENSE +21 -0
  125. package/package/corpus/skills/profiling/NOTICE +50 -0
  126. package/package/corpus/skills/profiling/SKILL.md +144 -0
  127. package/package/corpus/skills/profiling/references/commands.md +439 -0
  128. package/package/corpus/skills/profiling/references/patterns.md +586 -0
  129. package/package/corpus/skills/profiling/references/profiling.md +190 -0
  130. package/package/corpus/skills/run-tests/LICENSE +23 -0
  131. package/package/corpus/skills/run-tests/NOTICE +19 -0
  132. package/package/corpus/skills/run-tests/SKILL.md +305 -0
  133. package/package/corpus/skills/target-authoring/LICENSE +23 -0
  134. package/package/corpus/skills/target-authoring/NOTICE +17 -0
  135. package/package/corpus/skills/target-authoring/SKILL.md +165 -0
  136. package/package/corpus/skills/vectorization/LICENSE +23 -0
  137. package/package/corpus/skills/vectorization/NOTICE +17 -0
  138. package/package/corpus/skills/vectorization/SKILL.md +189 -0
  139. package/package/profile-catalog.json +85 -1
  140. package/package.json +1 -1
@@ -0,0 +1,23 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) .NET Foundation and Contributors
4
+
5
+ All rights reserved.
6
+
7
+ Permission is hereby granted, free of charge, to any person obtaining a copy
8
+ of this software and associated documentation files (the "Software"), to deal
9
+ in the Software without restriction, including without limitation the rights
10
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
+ copies of the Software, and to permit persons to whom the Software is
12
+ furnished to do so, subject to the following conditions:
13
+
14
+ The above copyright notice and this permission notice shall be included in all
15
+ copies or substantial portions of the Software.
16
+
17
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23
+ SOFTWARE.
@@ -0,0 +1,36 @@
1
+ Benchmark Authoring Guidelines
2
+ Copyright (c) .NET Foundation and Contributors
3
+ Licensed under the MIT License. See LICENSE.
4
+
5
+ Upstream source: https://github.com/dotnet/skills/blob/a6bf43ab61967c30919334986515163ab24d7635/plugins/dotnet-diag/skills/microbenchmarking/SKILL.md
6
+
7
+ Changes made by Cratis:
8
+
9
+ LICENSE:
10
+ - Copy upstream MIT license and copyright verbatim.
11
+
12
+ SKILL.md:
13
+ - Package guidance defers to Central Package Management pins when `Directory.Packages.props` exists.
14
+ - Reword the historical-measurements axis in neutral present-tense wording.
15
+ - Normalize frontmatter serialization, add MIT license where absent; preserve name and description.
16
+ - Add marked modification/source comment and applicability/Cratis precedence line.
17
+ - Rewrite the description to the Cratis shape (what it does, Use when, Not for) and drop references to skills that are not part of this corpus.
18
+
19
+ references/writing-benchmarks.md:
20
+ - Repair references/-relative sibling link.
21
+ - Add or normalize the top Contents list from existing headings; preserve section content.
22
+
23
+ references/bdn-internals-and-tuning.md:
24
+ - Reduce release-specific version mentions to the single behavior boundary.
25
+ - Add or normalize the top Contents list from existing headings; preserve section content.
26
+
27
+ references/comparison-strategies.md:
28
+ - Add or normalize the top Contents list from existing headings; preserve section content.
29
+
30
+ references/diagnosers-and-exporters.md:
31
+ - Add or normalize the top Contents list from existing headings; preserve section content.
32
+
33
+ references/project-setup-and-running.md:
34
+ - Add or normalize the top Contents list from existing headings; preserve section content.
35
+
36
+ NOTICE: Add this attribution, change list, and any download/execution disclosure.
@@ -0,0 +1,131 @@
1
+ ---
2
+ name: microbenchmarking
3
+ description: 'Designs, configures, runs, and reviews BenchmarkDotNet (BDN) benchmarks, including project setup, efficient runs, and side-by-side performance comparisons. Use when BenchmarkDotNet is involved, or a .NET performance question needs measurement and BenchmarkDotNet is the likely tool. Not for profiling or tracing (use profiling or dotnet-trace-collect), production telemetry, or load and stress testing.'
4
+ license: MIT
5
+ ---
6
+
7
+ <!-- Modified by Cratis from dotnet's original (MIT): frontmatter, applicability, navigation and the changes listed in NOTICE. Upstream: https://github.com/dotnet/skills (plugins/dotnet-diag/skills/microbenchmarking/SKILL.md; see NOTICE) -->
8
+
9
+ # Benchmark Authoring Guidelines
10
+
11
+ Cratis rules in `.cratis/ai/rules/` (including `csharp.md`, `specs.csharp.md`, and `orleans.md`) and the `cratis-*` skills win where they differ.
12
+
13
+ BenchmarkDotNet (BDN) is a .NET library for writing and running microbenchmarks. Throughout this skill, "BDN" refers to BenchmarkDotNet.
14
+
15
+ > **Note:** Evaluations of LLMs writing BenchmarkDotNet benchmarks have revealed common failure patterns caused by outdated assumptions about BDN's behavior — particularly around runtime comparison, job configuration, and execution defaults that have changed in recent versions. The reference files in this skill contain verified, current information. **You MUST read the reference files relevant to the task before writing any code** — your training data likely contains outdated or incorrect BDN patterns.
16
+
17
+ ## Key concepts
18
+
19
+ - **Job** — describes how to run a benchmark: runtime, iteration counts, launch count, run strategy, and environment settings. Multiple jobs can be configured to run the same benchmarks under different conditions.
20
+ - **Benchmark case** — one method × one parameter combination × one job. The atomic unit BDN measures.
21
+ - **Operation** — the logical unit of work being measured. All BDN output columns (Mean, Error, etc.) report time per operation.
22
+ - **Invocation** — a single call to the benchmark method. By default, 1 invocation = 1 operation. With `OperationsPerInvoke=N`, each invocation counts as N operations.
23
+ - **Iteration** — a timed batch of invocations. BDN measures the total time for all invocations in an iteration, then divides by the total operation count to get per-operation time.
24
+
25
+ ## Benchmarks are comparative instruments
26
+
27
+ A single benchmark number has limited value — it can confirm the order of magnitude of a measurement, but the exact value changes across machines, operating systems, and runtime configurations. Benchmarks produce the most useful information when compared against something. Before writing benchmarks, identify the **comparison axis** for the current task:
28
+
29
+ - **Approaches (A vs B)**: comparing alternative implementations side-by-side in the same run.
30
+ - **Runtimes**: comparing the same code across .NET versions (e.g., net8.0 vs net9.0).
31
+ - **Package versions**: comparing different versions of a NuGet dependency.
32
+ - **Builds (before/after)**: comparing a saved DLL of the old code against the current source.
33
+ - **Runtime configuration (GC mode, JIT settings)**: understanding how runtime settings affect performance — compared via multiple jobs in a single run.
34
+ - **Scale (N=100 vs N=1000)**: understanding how performance changes as input size grows.
35
+ - **Hardware/OS**: comparing across different machines or operating systems — requires separate runs on each environment.
36
+ - **Earlier measurements**: comparing against measurements recorded previously.
37
+
38
+ BDN can compare the first six axes side-by-side in a single run, but each requires specific CLI flags or configuration that differ from what you might expect — read [references/comparison-strategies.md](references/comparison-strategies.md) for the correct approach for each strategy before configuring a comparison.
39
+
40
+ ## Use cases and benchmark lifecycle
41
+
42
+ There are four distinct reasons a developer writes a benchmark, and each one changes how the benchmark should be designed and where it should live:
43
+
44
+ 1. **Coverage suite**: Write benchmarks to maximize coverage of real-world usage patterns so that regressions affecting most users are caught. These benchmarks are permanent — they belong in the project's benchmark suite, follow its conventions (directory structure, base classes, naming), and are checked in.
45
+
46
+ 2. **Issue investigation**: Someone has reported a specific performance problem. Write benchmarks to reproduce and diagnose that specific issue. These benchmarks are task-scoped — they persist across the investigation (reproduce → isolate → verify fix) but are not part of the permanent suite.
47
+
48
+ 3. **Change validation**: A developer has a PR or change and wants to understand its performance characteristics before merging. These benchmarks are task-scoped — they persist across the review cycle but are not checked in.
49
+
50
+ 4. **Development feedback**: A developer is actively working on a task and wants to use benchmarks to evaluate approaches and get information early. These benchmarks are task-scoped and throwaway — they persist across the development session but are deleted when the decision is made.
51
+
52
+ For use case 1, add to the existing benchmark project following its conventions. For use cases 2–4, create a standalone project in a working directory that persists for the task but is clearly not part of the permanent codebase.
53
+
54
+ For **coverage suite** benchmarks, design from the perspective of real callers — what code patterns use this API, what inputs they pass, and what performance characteristics matter to them. Each permanent benchmark should justify its maintenance cost through real-world relevance. For **temporary benchmarks**, keep the case count intentional — each additional test case costs wall-clock time (read [Cost awareness](#cost-awareness)).
55
+
56
+ ## Cost awareness
57
+
58
+ Each benchmark case (one method × one parameter combination × one job) takes **15–25 seconds** with default settings. `[Params]` creates a Cartesian product: two `[Params]` with 3 and 4 values across 5 methods = 60 cases ≈ 20 minutes. Multiple jobs multiply this further. Before running, estimate the total case count and match the job preset to the situation:
59
+
60
+ | Preset | Per-case time | When to use |
61
+ |--------|--------------|-------------|
62
+ | `--job Dry` | <1s | Validate correctness — confirms compilation and execution without measurement |
63
+ | `--job Short` | 5–8s | Quick measurements during development or investigation |
64
+ | *(default)* | 15–25s | Final measurements for a coverage suite |
65
+ | `--job Medium` | 33–52s | Higher confidence when results matter |
66
+ | `--job Long` | 3–12 min | High statistical confidence |
67
+
68
+ If benchmark runs take longer than expected, results seem unstable, or you need to tune iteration counts or execution settings, read [references/bdn-internals-and-tuning.md](references/bdn-internals-and-tuning.md) for detailed information about BDN's execution pipeline and configuration options.
69
+
70
+ ## Entry points and configuration
71
+
72
+ BDN programs use either **`BenchmarkSwitcher`** (provides interactive benchmark selection for humans, parses CLI arguments) or **`BenchmarkRunner`** (runs specified benchmarks directly). Both support CLI flags like `--filter` and `--runtimes`, but only when `args` is passed through — without it, CLI flags are silently ignored. When using `BenchmarkSwitcher`, always pass `--filter` to avoid hanging on an interactive prompt.
73
+
74
+ BDN behavior is customized through **attributes**, **config objects**, and **CLI flags**.
75
+
76
+ Read [references/project-setup-and-running.md](references/project-setup-and-running.md) for entry point setup, config object patterns, and CLI flags. If you need to collect data beyond wall-clock time — such as memory allocations, hardware counters, or profiling traces — read [references/diagnosers-and-exporters.md](references/diagnosers-and-exporters.md).
77
+
78
+ ## Running benchmarks
79
+
80
+ BenchmarkDotNet console output is extremely verbose — hundreds of lines per case showing internal calibration, warmup, and measurement details. Redirect all output to a file to avoid consuming context on verbose iteration output:
81
+
82
+ ```
83
+ dotnet run -c Release -- --filter "*MethodName" --noOverwrite > benchmark.log 2>&1
84
+ ```
85
+
86
+ Each benchmark method can take several minutes. Rather than running all benchmarks at once, use `--filter` to run a subset at a time (e.g. one or two methods per invocation), read the results, then run the next subset. This keeps each invocation short — avoiding session or terminal timeouts — and lets you verify results incrementally. Read [references/project-setup-and-running.md](references/project-setup-and-running.md) for filter syntax, CLI flags, and project setup.
87
+
88
+ After each run, read the Markdown report (`*-report-github.md`) from the results directory for the summary table. Only read `benchmark.log` if you need to investigate errors or unexpected results.
89
+
90
+ ## Writing new benchmarks
91
+
92
+ ### Step 1: Plan the test cases
93
+
94
+ Before writing any code, determine:
95
+ - Which use case this benchmark serves (coverage, investigation, change validation, or development feedback).
96
+ - Which comparison axis applies (what will the number be compared against?).
97
+ - What real-world scenarios to benchmark, based on how callers actually use the API.
98
+
99
+ Each benchmark case should justify its cost. An uncovered scenario is usually more valuable than another parameter combination for one already covered, but when a specific parameter dimension genuinely affects performance characteristics, the depth is warranted.
100
+
101
+ Decide on the list of test cases. For each test case, think through:
102
+
103
+ - **How to express variation**: BenchmarkDotNet provides several mechanisms for parameterizing benchmarks — `[Params]` and `[ParamsSource]` for property-level parameters, `[Arguments]` and `[ArgumentsSource]` for method-level arguments, `[ParamsAllValues]` to enumerate all values of a `bool` or enum, and `[GenericTypeArguments]` for varying type parameters on generic benchmark classes. Choose the mechanism that best fits the dimension being varied. Read [references/writing-benchmarks.md](references/writing-benchmarks.md) for the full set of options and correctness patterns.
104
+ - **Where input data comes from** — consider which sources are appropriate (these can be combined):
105
+ - Hard-coded values — small, fixed values where the exact input matters (e.g., specific strings, known edge-case sizes). Store in fields or `[Params]` to avoid constant folding.
106
+ - Asset files — static data that is too large or impractical to embed in source code such as binary blobs.
107
+ - Programmatically generated via `[ParamsSource]`/`[ArgumentsSource]`/`[GlobalSetup]` — when data shape matters more than specific content, or when input must be parameterized by size.
108
+ - **Whether randomness is appropriate**: If using generated data, use seeded randomness for reproducibility. When generating random data, use a large enough sample that the generated distribution is representative (e.g., 4 random values may cluster in a narrow range, while 1000 will better exercise the full distribution).
109
+
110
+ ### Step 2: Implement the benchmarks
111
+
112
+ For **coverage suite** benchmarks, add to the existing benchmark project and follow its conventions. For **temporary benchmarks** (investigation, change validation, development feedback), create a standalone project — read [references/project-setup-and-running.md](references/project-setup-and-running.md) for project setup and entry point configuration.
113
+
114
+ **Adding the BenchmarkDotNet package**: In a repository with Central Package Management (`Directory.Packages.props`), use the version already pinned there and add a versionless `<PackageReference>`; otherwise use `dotnet add package BenchmarkDotNet` (no version) — this lets NuGet resolve the latest compatible version. Do NOT manually write a `<PackageReference>` with a version number into the `.csproj`; BDN versions in training data are outdated and may lack support for current .NET runtimes.
115
+
116
+ Write the benchmark code. Follow the patterns in [references/writing-benchmarks.md](references/writing-benchmarks.md) to avoid common measurement errors — in particular:
117
+ - **Return results** from benchmark methods to prevent dead code elimination
118
+ - **Move initialization to `[GlobalSetup]`** — setup inside the benchmark method is measured; use `[IterationSetup]` only when the benchmark mutates state that must be reset between iterations
119
+ - **Do not add manual loops** — BDN controls invocation count automatically
120
+ - **Mark a baseline** when comparing alternatives — use `[Benchmark(Baseline = true)]` for method-level comparisons or `.AsBaseline()` on a job for multi-job comparisons so results show relative ratios
121
+ - **Store inputs in fields or `[Params]`**, not as literals or `const` values — the JIT can fold constant expressions at compile time, making the benchmark measure a precomputed result instead of the actual computation
122
+
123
+ ### Step 3: Validate and run
124
+
125
+ Validate before committing to a long run:
126
+
127
+ 1. Run with `--job Dry` first to catch compilation errors and runtime exceptions without spending time on measurement.
128
+ 2. Run a single representative case with default settings to verify the output looks correct and the numbers are in the expected range.
129
+ 3. Only run the full suite after validation passes.
130
+
131
+ When iterating on benchmark design, use `--job Short` until confident, then switch to default for final numbers.
@@ -0,0 +1,143 @@
1
+ # BenchmarkDotNet Execution and Configuration
2
+
3
+ ## Contents
4
+
5
+ - Build and execution
6
+ - Execution stages per case (default job settings)
7
+ - Job preset configurations
8
+ - Run strategies
9
+ - Jobs and mutators
10
+ - Execution-related attributes
11
+ - Unroll factor
12
+ - Execution environment
13
+
14
+ ## Build and execution
15
+
16
+ BDN generates a standalone project containing the measurement harness, builds it **once per unique build configuration**, and runs each case in its **own process**. Cases are partitioned into separate builds when they differ in factors including runtime, toolchain, platform, JIT, GC settings, build configuration, or MSBuild arguments. All cases sharing the same build configuration share a single build (~5s).
17
+
18
+ BDN determines the number of invocations per iteration automatically.
19
+
20
+ `[Params]` creates a full Cartesian product: two `[Params]` properties with 3 and 4 values across 5 methods = 3 × 4 × 5 = 60 cases.
21
+
22
+ Build overhead (~5s) is paid once regardless of case count. When running cases individually (separate `dotnet run` per case), each pays the build cost, adding ~5s per case.
23
+
24
+ ## Execution stages per case (default job settings)
25
+
26
+ Each case runs through these stages sequentially. Some stage defaults have changed between BDN versions and may change in future releases — check which version of the BenchmarkDotNet NuGet package is installed when the exact behavior matters.
27
+
28
+ 1. **Process launch + JIT** — The benchmark method is invoked to trigger initial JIT compilation, ensuring the method is compiled before the pilot stage calibrates invocation count. This stage's time is not included in results.
29
+ 2. **Pilot** — Determines the invocation count per iteration. Fast methods get many invocations per iteration (targeting ~500ms per iteration). Methods slower than ~333ms/op (where two invocations would exceed the target) are fixed at one invocation per iteration.
30
+ 3. **Warmup** — Adaptive, typically 6–10 iterations for stable benchmarks (those with low variance). During warmup the runtime may further optimize the method (e.g., tiered JIT recompilation).
31
+ 4. **Actual** — Adaptive, typically 15 iterations for stable benchmarks. Stops when the confidence interval is sufficiently narrow (controlled by `MaxRelativeError`, default 2%).
32
+
33
+ **Note (BDN before 0.16.0):** an additional **Overhead** stage ran between Pilot and Warmup by default. It measured the internal invocation loop's own cost and subtracted it from results. Newer releases leave this stage off by default, and the API to re-enable it (`[EvaluateOverhead]` / `.WithEvaluateOverhead()`) is marked obsolete.
34
+
35
+ ## Job preset configurations
36
+
37
+ | Preset | Per-case time | Warmup | Target iterations | Launch count | Strategy |
38
+ |--------|--------------|--------|-------------------|-------------|----------|
39
+ | `Dry` | <1s | 0 | 1 | 1 | ColdStart |
40
+ | `Short` | 5–8s | 3 | 3 | 1 | Throughput |
41
+ | Default | 15–25s | 6–50 (adaptive) | 15–100 (adaptive) | 1 | Throughput |
42
+ | `Medium` | 33–52s | 10 | 15 | 2 | Throughput |
43
+ | `Long` | 3–12 min | 15 | 100 | 3 | Throughput |
44
+
45
+ The `Dry` preset reuses the ColdStart strategy for minimal execution; its purpose is validation (confirming the benchmark compiles and runs), not first-call measurement.
46
+
47
+ ## Run strategies
48
+
49
+ The `RunStrategy` controls how BDN calibrates and measures:
50
+
51
+ - **Throughput** (default) — measures steady-state performance. BDN auto-calibrates invocation count via the pilot stage, runs warmup, and adapts iteration count. Use for microbenchmarks.
52
+ - **ColdStart** — single invocation per iteration, skips all preliminary stages (JIT pre-trigger, pilot, warmup, overhead). The first measured invocation includes JIT compilation time. Use for startup time evaluation.
53
+ - **Monitoring** — single invocation per iteration. Skips JIT pre-trigger, pilot, and overhead stages (like ColdStart), but includes the warmup stage (default 0 iterations, configurable). Use for macrobenchmarks with high variance that don't reach a steady state.
54
+
55
+ ## Jobs and mutators
56
+
57
+ A **job** defines a complete set of run conditions — runtime, iteration counts, launch count, strategy, etc. A benchmark class can have **multiple jobs**, and BDN will run all benchmark methods under each job separately. For example, `[SimpleJob(RuntimeMoniker.Net80)]` and `[SimpleJob(RuntimeMoniker.Net90)]` on the same class runs every method twice — once per runtime.
58
+
59
+ A **mutator** is not a standalone job. It is a partial override that gets applied to every existing job. This distinction matters when a class has multiple jobs:
60
+
61
+ ```csharp
62
+ [SimpleJob(RuntimeMoniker.Net80)] // Job A
63
+ [SimpleJob(RuntimeMoniker.Net90)] // Job B
64
+ [WarmupCount(3)] // Mutator — applied to BOTH Job A and Job B
65
+ public class MyBenchmarks { ... }
66
+ ```
67
+
68
+ Without the mutator distinction, `[WarmupCount(3)]` would be a third job with just a warmup count override and default everything else — probably not what was intended.
69
+
70
+ Jobs are resolved by collecting all standard jobs (from `[SimpleJob]`, etc.; `Job.Default` if none), then applying all mutators to every job. CLI flags like `--warmupCount 3` act as mutators — they override that setting on all jobs defined in source code. `--job Short` adds a standard job.
71
+
72
+ ## Execution-related attributes
73
+
74
+ **Class or method level (mutator attributes):**
75
+ These override specific job settings. When applied to a method, they affect only that method's cases. When applied to a class, they affect all methods in the class.
76
+
77
+ | Attribute | Default | Config (on Job) | CLI flag |
78
+ |-----------|---------|----------------|----------|
79
+ | `[WarmupCount(N)]` | null (adaptive) | `.WithWarmupCount(N)` | `--warmupCount N` |
80
+ | `[IterationCount(N)]` | null (adaptive) | `.WithIterationCount(N)` | `--iterationCount N` |
81
+ | `[MinWarmupCount(N)]` | 6 | `.WithMinWarmupCount(N)` | `--minWarmupCount N` |
82
+ | `[MaxWarmupCount(N)]` | 50 | `.WithMaxWarmupCount(N)` | `--maxWarmupCount N` |
83
+ | `[MinIterationCount(N)]` | 15 | `.WithMinIterationCount(N)` | `--minIterationCount N` |
84
+ | `[MaxIterationCount(N)]` | 100 | `.WithMaxIterationCount(N)` | `--maxIterationCount N` |
85
+ | `[InvocationCount(N)]` | null (auto pilot) | `.WithInvocationCount(N)` | `--invocationCount N` |
86
+ | `[IterationTime(ms)]` | 500ms | `.WithIterationTime(TimeInterval.FromMilliseconds(ms))` | `--iterationTime ms` |
87
+ | `[ProcessCount(N)]` | 1 | `.WithLaunchCount(N)` | `--launchCount N` |
88
+ | `[MaxRelativeError(pct)]` | 0.02 (= 2%) | `.WithMaxRelativeError(pct)` | — |
89
+
90
+ Note: `[ProcessCount]` and `--launchCount` control the same setting (how many separate processes BDN launches per case). The naming differs between API surfaces.
91
+
92
+ The `[RunOncePerIteration]` attribute (also available as `.RunOncePerIteration()` or `--runOncePerIteration`) is shorthand for setting `InvocationCount=1` and `UnrollFactor=1`.
93
+
94
+ **Note (older BDN releases):** `[EvaluateOverhead(bool)]` / `.WithEvaluateOverhead(bool)` / `--noOverheadEvaluation` controlled overhead subtraction. These are obsolete because overhead evaluation is disabled by default.
95
+
96
+ **Class or assembly level:**
97
+ - Job attributes: `[SimpleJob(...)]`, `[DryJob]`, `[ShortRunJob]`, `[MediumRunJob]`, `[LongRunJob]`, `[VeryLongRunJob]`. AllowMultiple — can stack to run the same benchmarks under different job configurations.
98
+
99
+ ## Unroll factor
100
+
101
+ BDN generates a measurement method that contains the benchmark code repeated `UnrollFactor` times (default 16). This reduces measurement loop overhead relative to the actual work.
102
+
103
+ UnrollFactor is distinct from `OperationsPerInvoke`: UnrollFactor is an engine optimization, while `OperationsPerInvoke` is a user declaration that each invocation performs multiple logical operations.
104
+
105
+ When `[IterationSetup]` or `[IterationCleanup]` is used, BDN defaults to `UnrollFactor=1` and `InvocationCount=1` so that setup/cleanup runs before and after each single invocation of the benchmark method. Explicitly setting `InvocationCount` or `UnrollFactor` overrides this behavior.
106
+
107
+ | Attribute | Config API | CLI flag |
108
+ |-----------|------------|----------|
109
+ | `[UnrollFactor(N)]` | `.WithUnrollFactor(N)` | `--unrollFactor N` |
110
+
111
+ ## Execution environment
112
+
113
+ The settings below configure the runtime environment the benchmark process runs in. They are orthogonal to the execution pipeline above — they don't change how many iterations run or how the engine measures, they change *what* is being measured.
114
+
115
+ | Purpose | Attribute | Config API | CLI flag |
116
+ |---------|-----------|------------|----------|
117
+ | Target runtimes | `[SimpleJob(RuntimeMoniker.Net80)]` | `Job.Default.WithRuntime(CoreRuntime.Core80)` | `--runtimes net8.0 net9.0` (first is baseline) |
118
+ | Environment variables | — | `job.WithEnvironmentVariable("key", "value")` | `--envVars KEY:VALUE` |
119
+
120
+ Multiple runtimes multiply the total case count and each requires a separate build.
121
+
122
+ ### GC configuration
123
+
124
+ | Setting | Attribute | Config API |
125
+ |---------|-----------|------------|
126
+ | Server GC | `[GcServer(true)]` | `.WithGcServer(true)` |
127
+ | Concurrent GC | `[GcConcurrent(bool)]` | `.WithGcConcurrent(bool)` |
128
+
129
+ ### MemoryRandomization
130
+
131
+ | Surface | Usage |
132
+ |---------|-------|
133
+ | Attribute | `[MemoryRandomization]` |
134
+ | Config | `.WithMemoryRandomization(true)` |
135
+ | CLI | `--memoryRandomization` |
136
+
137
+ The `[MemoryRandomization]` attribute causes BDN to allocate random-sized memory between iterations, shifting heap object alignment. This reveals whether benchmark results depend on memory layout (cache line alignment, GC heap position) rather than algorithmic performance.
138
+
139
+ When enabled, BDN:
140
+ - Allocates random-sized Gen0 and LOH objects between iterations
141
+ - Uses `stackalloc` with random size to shift stack alignment
142
+ - Re-runs `[GlobalCleanup]` and `[GlobalSetup]` after every iteration
143
+ - Disables outlier removal (since multimodal results may be genuine)
@@ -0,0 +1,200 @@
1
+ # Comparing benchmark results
2
+
3
+ ## Contents
4
+
5
+ - Strategy 1: Side-by-side methods (preferred)
6
+ - Strategy 2: Comparing runtimes
7
+ - Strategy 3: Comparing NuGet package versions
8
+ - Strategy 4: Comparing a saved build against current source (DLL reference)
9
+ - Strategy 5: Comparing runtime configurations
10
+ - Strategy 6: Comparing across input scale
11
+ - How it works
12
+ - Apples-to-apples comparison
13
+ - Mann-Whitney equivalence test
14
+
15
+ BenchmarkDotNet can compare multiple implementations or versions in a single run, producing a side-by-side table with ratio columns and statistical analysis. This is generally preferable to separate runs because it controls for environmental variance.
16
+
17
+ ## Strategy 1: Side-by-side methods (preferred)
18
+
19
+ When both the old and new implementations can coexist in the same compilation, define separate benchmark methods:
20
+
21
+ ```csharp
22
+ public class SortBenchmark
23
+ {
24
+ private int[] _data;
25
+
26
+ [GlobalSetup]
27
+ public void Setup() => _data = Enumerable.Range(0, 1000).Reverse().ToArray();
28
+
29
+ [Benchmark(Baseline = true)]
30
+ public void BubbleSort() => Sorting.BubbleSort((int[])_data.Clone());
31
+
32
+ [Benchmark]
33
+ public void QuickSort() => Sorting.QuickSort((int[])_data.Clone());
34
+ }
35
+ ```
36
+
37
+ BDN displays a Ratio column showing each method's mean relative to the baseline. This is the simplest approach and should be preferred whenever both implementations are available at compile time.
38
+
39
+ ## Strategy 2: Comparing runtimes
40
+
41
+ To compare the same benchmark across different .NET runtime versions, use `--runtimes` on the command line or configure jobs. The `.csproj` must use `<TargetFrameworks>net8.0;net9.0</TargetFrameworks>` (plural) listing all targets:
42
+
43
+ ```
44
+ dotnet run -c Release --framework net9.0 -- --runtimes net8.0 net9.0
45
+ ```
46
+
47
+ ```csharp
48
+ var config = DefaultConfig.Instance
49
+ .AddJob(Job.Default.WithRuntime(CoreRuntime.Core80).AsBaseline())
50
+ .AddJob(Job.Default.WithRuntime(CoreRuntime.Core90));
51
+ ```
52
+
53
+ Each runtime becomes a separate job. BDN builds separate executables per runtime and shows them side-by-side with ratio columns.
54
+
55
+ ## Strategy 3: Comparing NuGet package versions
56
+
57
+ To compare different versions of a NuGet dependency, use MSBuild properties to control the package version per job. Each job gets a separate build with the specified version.
58
+
59
+ **.csproj** — use an MSBuild property for the version:
60
+ ```xml
61
+ <PropertyGroup>
62
+ <MyLibVersion Condition="'$(MyLibVersion)' == ''">2.0.0</MyLibVersion>
63
+ </PropertyGroup>
64
+ <ItemGroup>
65
+ <PackageReference Include="MyLibrary" Version="$(MyLibVersion)" />
66
+ </ItemGroup>
67
+ ```
68
+
69
+ **Config** — create a job per version:
70
+ ```csharp
71
+ var config = DefaultConfig.Instance
72
+ .AddJob(Job.Default
73
+ .WithMsBuildArguments("/p:MyLibVersion=1.0.0")
74
+ .WithId("v1.0.0")
75
+ .AsBaseline())
76
+ .AddJob(Job.Default
77
+ .WithMsBuildArguments("/p:MyLibVersion=2.0.0")
78
+ .WithId("v2.0.0"));
79
+ ```
80
+
81
+ All versions must be source-compatible with the benchmark code (same namespace, same method signatures). BDN builds a separate exe per job because `WithArguments` changes the build partition.
82
+
83
+ This works with packages from any NuGet source — public registries, private feeds, or local folders created with `dotnet pack`.
84
+
85
+ ## Strategy 4: Comparing a saved build against current source (DLL reference)
86
+
87
+ When the code is not published as a NuGet package but you want to compare before/after a code change, you can save the build output of the baseline version and reference it directly.
88
+
89
+ **Step 1** — build and save the baseline:
90
+ ```
91
+ dotnet build ../MyLib -c Release -o ./saved-baseline
92
+ ```
93
+
94
+ **Step 2** — make your changes to MyLib.
95
+
96
+ **Step 3** — set up the benchmark .csproj with conditional references:
97
+ ```xml
98
+ <ItemGroup>
99
+ <ProjectReference Condition="'$(BaselineDll)' == ''" Include="..\MyLib\MyLib.csproj" />
100
+ <Reference Condition="'$(BaselineDll)' != ''" Include="MyLib">
101
+ <HintPath>$(BaselineDll)</HintPath>
102
+ </Reference>
103
+ </ItemGroup>
104
+ ```
105
+
106
+ **Step 4** — configure two jobs:
107
+ ```csharp
108
+ var config = DefaultConfig.Instance
109
+ .AddJob(Job.Default
110
+ .WithMsBuildArguments("/p:BaselineDll=../saved-baseline/MyLib.dll")
111
+ .WithId("baseline")
112
+ .AsBaseline())
113
+ .AddJob(Job.Default
114
+ .WithId("current"));
115
+ ```
116
+
117
+ The `baseline` job builds with a direct DLL reference to the saved output. The `current` job builds with the `ProjectReference` to the current source. BDN produces a side-by-side table with ratio columns.
118
+
119
+ This approach works for any class library. The namespace and public API must be the same between the two versions.
120
+
121
+ ## Strategy 5: Comparing runtime configurations
122
+
123
+ To compare how different runtime settings (GC mode, JIT options, PGO) affect performance, define multiple jobs with different environment settings. This works with any `Job` setting — GC mode, environment variables, platform, JIT settings:
124
+
125
+ ```csharp
126
+ // GC mode comparison
127
+ var config = DefaultConfig.Instance
128
+ .AddJob(Job.Default.WithGcServer(false).WithId("Workstation GC").AsBaseline())
129
+ .AddJob(Job.Default.WithGcServer(true).WithId("Server GC"));
130
+
131
+ // JIT setting comparison
132
+ var config = DefaultConfig.Instance
133
+ .AddJob(Job.Default.WithId("Default").AsBaseline())
134
+ .AddJob(Job.Default.WithEnvironmentVariable("DOTNET_TieredCompilation", "0").WithId("No Tiered"));
135
+ ```
136
+
137
+ ## Strategy 6: Comparing across input scale
138
+
139
+ Use `[Params]` on a size property to understand how performance changes with input size. BDN runs each parameter value as a separate case. Geometrically spaced values (e.g., 10×, 100×) help reveal scaling behavior:
140
+
141
+ ```csharp
142
+ [Params(100, 1_000, 10_000)]
143
+ public int N;
144
+
145
+ private int[] _data;
146
+
147
+ [GlobalSetup]
148
+ public void Setup()
149
+ {
150
+ var rng = new Random(42);
151
+ _data = Enumerable.Range(0, N).OrderBy(_ => rng.Next()).ToArray();
152
+ }
153
+
154
+ [Benchmark]
155
+ public void Sort() => Array.Sort((int[])_data.Clone());
156
+ ```
157
+
158
+ ## How it works
159
+
160
+ All multi-version strategies rely on the same BDN mechanism:
161
+
162
+ 1. **Build partitioning** — different MSBuild arguments, runtimes, or platform → separate compiled executables. Each case runs in its own process.
163
+ 2. **Ratio calculation** — when a baseline is marked, BDN adds `Ratio` and `RatioSD` columns. `Ratio` is the mean of current/baseline per-operation time ratios. A `Ratio` of `0.85` means ~15% faster.
164
+
165
+ ### Marking a baseline
166
+
167
+ For side-by-side methods (Strategy 1), mark one method with `[Benchmark(Baseline = true)]`. This compares methods within each job.
168
+
169
+ For multi-job strategies (Strategies 2–5), mark one job with `.AsBaseline()` in the config. This compares jobs against each other. For `--runtimes`, the first runtime listed is the baseline.
170
+
171
+ These are separate mechanisms — using the wrong one produces no ratio columns.
172
+
173
+ Without a baseline, BDN shows absolute numbers only — no ratio columns.
174
+
175
+ ## Apples-to-apples comparison
176
+
177
+ When comparing across jobs (Strategies 2–5), the default behavior runs each job's pilot stage independently, which may choose different invocation counts per job for the same benchmark case. This creates asymmetric measurement conditions that can bias the comparison.
178
+
179
+ The `--apples` flag forces symmetric measurement by running in two phases:
180
+
181
+ 1. **Pilot phase** — BDN runs the baseline job once per benchmark case (method × parameter combination) to determine the invocation count for that case. Different cases get different invocation counts based on their speed. This produces a first results table in the log showing only the baseline with `Ratio = 1.00`.
182
+ 2. **Measurement phase** — for each benchmark case, ALL jobs run with that case's fixed invocation count, ensuring every job measures the same number of operations per iteration. The final comparison table includes `Ratio` and `InvocationCount` columns and is written to `BenchmarkDotNet.Artifacts/`.
183
+
184
+ Outlier removal is disabled in this mode since the controlled setup makes outliers more meaningful.
185
+
186
+ ```
187
+ dotnet run -c Release --framework net9.0 -- --runtimes net8.0 net9.0 --apples --job short
188
+ ```
189
+
190
+ Because the pilot runs only once per benchmark case instead of once per job, `--apples` is faster than the default when there are many benchmark cases. The savings grow with the number of methods and parameter combinations.
191
+
192
+ Requirements:
193
+ - At least two jobs, with exactly one marked as baseline (via `.AsBaseline()` on the job, not `[Benchmark(Baseline = true)]` on the method). When using `--runtimes`, the first runtime listed is automatically treated as the baseline.
194
+ - An explicit iteration count, such as by using `--job short` (which sets `IterationCount=3`) or `--iterationCount N`. Adaptive iteration count is disabled in this mode.
195
+
196
+ This does not apply to Strategy 1 (side-by-side methods) or Strategy 6 (input scale) because those use a single job — `--apples` requires multiple job objects.
197
+
198
+ ## Mann-Whitney equivalence test
199
+
200
+ BDN can add a `Faster` / `Same` / `Slower` column based on a Mann-Whitney equivalence test. Add it via config: `.AddColumn(StatisticalTestColumn.Create(threshold: "5%"))`. The `threshold` is the equivalence margin — results within that percentage are reported as `Same`.