diff --git a/docs/cookbook/vary-composed-configuration-per-theory-row.md b/docs/cookbook/vary-composed-configuration-per-theory-row.md index cc956a4..2f0331c 100644 --- a/docs/cookbook/vary-composed-configuration-per-theory-row.md +++ b/docs/cookbook/vary-composed-configuration-per-theory-row.md @@ -92,6 +92,33 @@ receives, `builder.Register(() => config)`, and add a composed `TConfig` parameter after the row values. It resolves to that row's own instance. See [Reading the row's `TConfig`](../packages/compono-xunitv3.md#per-row-configuration). +**Optional: a consumer-side base profile.** If many profiles repeat that +line, you can reduce the boilerplate with your own small base type — this +is a convenience in your test project, not a Compono type or API, and +Compono won't ship it: + +```csharp +public abstract class ConfigProfile(TConfig config) : ICompositionProfile + where TConfig : class +{ + protected TConfig Config => config; + + public void Configure(CompositionBuilder builder) + { + builder.Register(() => config); + ConfigureCore(builder); + } + + protected abstract void ConfigureCore(CompositionBuilder builder); +} +``` + +`PricingProfile` could derive from `ConfigProfile` and put +only its own registrations in `ConfigureCore`. A derived profile must not +also call `Register(() => config)` for `TConfig` — that's a duplicate +registration and fails composition (a `CompositionException` wrapping a +`CompositionConfigurationException`). + **`[Shared]` still works.** Mark a parameter `[Shared]` and, when a row supplies a value at that position, that value becomes the single instance every other parameter in the row resolving that type receives; otherwise diff --git a/docs/packages/compono-logging.md b/docs/packages/compono-logging.md index b32f9e2..6f73121 100644 --- a/docs/packages/compono-logging.md +++ b/docs/packages/compono-logging.md @@ -40,6 +40,10 @@ composition to work. There is no separate MSBuild opt-in to remember, no "How this actually runs," below, for what "on by default" means mechanically and how to opt back out. +**Forgot `UseLogging()`?** A composition failure naming `ILogger` or +`ILogger` usually means it wasn't registered — see [Runtime composition +failures](../troubleshooting/common-errors.md#runtime-composition-failures). + ## What it gives you ```csharp diff --git a/docs/packages/compono-metrics.md b/docs/packages/compono-metrics.md index 6a9c274..a884fb3 100644 --- a/docs/packages/compono-metrics.md +++ b/docs/packages/compono-metrics.md @@ -36,9 +36,19 @@ not `Microsoft.Extensions.Diagnostics`, not `Microsoft.Extensions.Diagnostics.Testing`, not `Microsoft.Extensions.DependencyInjection.Abstractions`. -**No MSBuild opt-in.** Unlike `Compono.TestDoubles`, there is nothing to -enable — `Compono.Metrics` ships no generator, analyzer, or props asset. -`UseMetrics()` works as soon as the package is referenced. +**No generation opt-in.** Unlike `Compono.TestDoubles`, there is nothing to +enable: `Compono.Metrics` ships no generator or analyzer, and `UseMetrics()` +works as soon as the package is referenced. The package includes a +`build`/`buildTransitive` props asset that defaults +`ComponoMetricsOwnsMeterFactory` to `true`, so `Compono.Generators` never +emits a `Compono.TestDoubles` double for `IMeterFactory`; consumers can +override that property (set it to `false`) but don't need to configure it +themselves. See +[Registration order and misuse](#registration-order-and-misuse). + +**Forgot `UseMetrics()`?** A composition failure naming `IMeterFactory` +usually means it wasn't registered — see [Runtime composition +failures](../troubleshooting/common-errors.md#runtime-composition-failures). ## What it gives you @@ -55,7 +65,7 @@ var service = composer.Create(); // OrderService(IMeterFactory m public sealed class MetricsProfile : ICompositionProfile { public void Configure(CompositionBuilder builder) => - builder.UseMetrics().Share(); + builder.UseMetrics(); } [Theory] @@ -71,6 +81,16 @@ public void PlacingAnOrderCountsIt([Shared] IMeterFactory meters, OrderService s } ``` +**`[Shared]` and `Share()` — use one or the other.** The +parameter above is `[Shared]`, so the test and the SUT receive the same +factory with no `Share()` needed; `[Shared]` resolves first, whatever +its parameter position. Use `Share()` in the profile +instead for profile-wide intent — an undecorated `IMeterFactory` parameter, +or several consumers in one `Composer.Create` graph. Declaring both is +redundant but harmless. What matters is the sharing, not the mechanism: +each `CapturingMeterFactory` captures only the meters it created, so a +test observing a different instance sees no measurements. + ```csharp var placed = meters.GetMeasurements("Shop.Orders", "shop.orders.placed"); Assert.Equal(1, placed.Sum(m => m.Value)); // value math via LINQ diff --git a/docs/packages/compono-xunitv3-aot.md b/docs/packages/compono-xunitv3-aot.md index d4bc2ce..1b27d4a 100644 --- a/docs/packages/compono-xunitv3-aot.md +++ b/docs/packages/compono-xunitv3-aot.md @@ -245,6 +245,16 @@ unchanged on this package. See [`Compono.XunitV3`'s per-row configuration](compono-xunitv3.md#per-row-configuration) and [Use Profiles](../how-to/use-profiles.md#a-profile-whose-constructor-takes-runtime-objects). +**Failure granularity is the same whole-theory contract** (ADR-0070 item 9): +all rows are composed before any row runs, so one row's composition failure +stops the rest — including rows that would have passed — and the theory +reports a single failed result instead of one per row, so the reported test +count can drop while the failure is present. Every data attribute on the +method, including `[InlineData]` rows, is affected. Fix the failing row and +every row runs and is counted again. On AOT, an unsupported row/shape is +usually a compile-time `CMP` diagnostic instead of this runtime failure — see +[ComposeData diagnostics on Native AOT](#composedata-diagnostics-on-native-aot). + ## Not yet supported `Compono.XunitV3.Aot.ComposeAttribute`'s three forms don't support inline diff --git a/docs/packages/compono-xunitv3.md b/docs/packages/compono-xunitv3.md index b4e999f..5276aa4 100644 --- a/docs/packages/compono-xunitv3.md +++ b/docs/packages/compono-xunitv3.md @@ -373,6 +373,15 @@ This works the same on `Compono.XunitV3.Aot`. Both engines are proven by ([RESEARCH-0040](../research/0040-issue-161-1-4-dogfood-follow-up.md) finding 2). +**Optional consumer-side base profile.** If many profiles repeat +`builder.Register(() => config)`, you can write your own +`ConfigProfile` base to hold that one line — see [Vary Composed +Configuration per Theory +Row](../cookbook/vary-composed-configuration-per-theory-row.md#solution). +It's a convenience type in your test project, not a Compono API. A derived +profile must not also register `TConfig` (that's a duplicate +registration). + ### Shared dependencies and `[Shared]` A `[Shared]` parameter works the same as under `[Compose]`: it names the one @@ -455,8 +464,17 @@ Every failure — reading the member, building one row's profile, or composing a row — throws a `CompositionException` that names the member (`Type.Member`). A row failure also names the **zero-based row index** and the row's label when it has one, and (per the rule below) a seed; a member-level failure has no row -index. The whole theory fails as a unit: there are no placeholder rows -and no custom invoker to keep the other rows running. The original cause is +index. + +The whole theory fails as a unit: there are no placeholder rows and no custom +invoker to keep the other rows running. Composition happens when the theory +runs, and **all** rows are built before any row executes. A composition +failure in one row therefore stops the rest: no row of that theory executes, +including rows that would have passed. The theory then reports a **single** +failed result instead of one result per row, so the suite's reported test +count can drop while the failure is present. Every data attribute on the same +method is affected, including its `[InlineData]` rows. Once the composition +error is fixed, every row runs and is counted again. The original cause is preserved as the exception's `InnerException`, and any `Diagnostic` is carried through. diff --git a/docs/plans/0076-issue-161-preview-128-dogfood-follow-up-impl-plan.md b/docs/plans/0076-issue-161-preview-128-dogfood-follow-up-impl-plan.md new file mode 100644 index 0000000..4b2e2c5 --- /dev/null +++ b/docs/plans/0076-issue-161-preview-128-dogfood-follow-up-impl-plan.md @@ -0,0 +1,265 @@ +# [PLAN-0076] Issue #161 preview.128 Dogfood Follow-Up (Documentation) + +**Status:** Done. Beads epic: `compono-6bg`. + +**Implements:** [RESEARCH-0041](../research/0041-issue-161-preview-128-dogfood-follow-up.md) +decisions (maintainer, 2026-11-12). No ADR is created or amended. Every +change is documentation that describes existing, `Accepted` behavior +(ADR-0022, ADR-0056, ADR-0070 item 9, ADR-0072). + +## Goal + +A consumer who hits any of the four preview.128 findings can find the answer +in the docs: + +- the generic `IMeterFactory` or `ILogger` failure leads to `UseMetrics()` or + `UseLogging()`; +- reading the row's `TConfig` has a low-boilerplate recipe; +- `[Shared]` and `Share()` are presented as alternatives, not + a pair; +- a failing `ComposeData` row is explained as reducing the reported result + count. + +## Scope + +**In scope:** docs, the skill and its evals, and the compiled examples that +back new docs snippets. + +**Out of scope** (RESEARCH-0041): any core message or hint mechanism (F1 +option 2 or 3), any `TConfig` opt-in API, any change to `UseMetrics()` +sharing, and per-row failure isolation or any change to `ComposeData` +failure behavior. No production code or public API changes. ApiCompat, +pack-consume, and AOT gates are untouched, because no shipped assembly +changes. + +One PR, since the changes are small and all trace back to one dogfood +comment. + +## Tasks + +### D1: Missing provider troubleshooting (F1) (`compono-6bg.1`) + +- [x] `docs/troubleshooting/common-errors.md`, "Runtime composition + failures": add guidance for the exact message naming + `IMeterFactory` → call `UseMetrics()`, and `ILogger`/`ILogger` → + call `UseLogging()`. Word it as "if you meant Compono.Metrics or + Compono.Logging to supply it". Note that supplying the type through + `Register()`/`UseServiceProvider` is also valid. Cross-link the + existing Metrics misuse entry. +- [x] Correct the stale `CompositionException` sample in that section so + it matches the real text built at `CompositionContext.cs:681`. The + sample reads "No registration, semantic provider, …", but the real + message includes "configuration rule": "No registration, configuration + rule, semantic provider, test-double provider, built-in provider, or + generated plan could satisfy …". +- [x] `docs/packages/compono-metrics.md` and `docs/packages/compono-logging.md`: + add a one-line "forgot `UseX()`?" pointer to the troubleshooting entry. +- [x] `skills/compono/references/metrics.md` and `logging.md`: the same + mapping. + +### D2: Reading the row's `TConfig` (F2) (`compono-6bg.2`) + +- [x] Keep `builder.Register(() => config)` in the profile, plus a composed + `TConfig` parameter, as the **primary documented recommendation** in + `docs/cookbook/vary-composed-configuration-per-theory-row.md` and + `docs/packages/compono-xunitv3.md` (per-row configuration). Leave the + existing wording as the main path. +- [x] After it, add a short **optional** note: consumers who repeat the line + across many profiles can write their own base profile, for example + `ConfigProfile` from RESEARCH-0041. Make clear that this is a + consumer-side convenience for repeated patterns. It isn't a Compono + type or API, and Compono won't ship it. Note that a derived profile + that also calls `Register` for `TConfig` gets the duplicate-registration + error. +- [x] Back the optional snippet with a compiled test in + `test/Compono.XunitV3.Tests`, with the base type declared in the test + project. Add no AOT test unless the snippet appears in AOT docs. +- [x] `skills/compono/references/xunit-v3.md`: keep `Register(() => config)` + as the recommendation. Mention the base profile only as an optional + consumer pattern, if it's mentioned at all. + +### D3: `[Shared]` vs `Share()` (F3) (`compono-6bg.3`) + +- [x] `docs/packages/compono-metrics.md` lead example: remove + `.Share()` from the profile used with a + `[Shared] IMeterFactory` parameter, or keep it and explain it. Add a + short "one or the other" note: `[Shared]` for per-test intent (it's + resolved first, in any parameter position), `Share()` + for profile-wide intent, undecorated parameters, and `Composer.Create` + graphs. Explain why sharing matters: each factory captures only its + own meters. +- [x] `skills/compono/references/metrics.md` "`Share()` and `[Shared]`": + replace "Prefer `Share()`" with the same either/or + guidance. +- [x] Check `docs/migrating-from-microsoft-extensions-diagnostics-testing.md` + for the same redundant pairing. +- [x] **Don't** add a `Compono.XunitV3` reference to + `test/Compono.Metrics.Tests`. +- [x] Adapter-level sharing coverage, if warranted: first check whether + `test/Compono.XunitV3.Tests` already proves that a `[Shared]` + parameter declared after its dependent, with two nested consumers, + gets the same instance with no `Share()`. Add a test there only if + that's missing. Use a stand-in interface and provider; don't pull in + `Compono.Metrics`. +- [x] Keep metrics lifetime coverage in `test/Compono.Metrics.Tests`, which + is already in place: `EachComposedRequest_GetsItsOwnFactory_AbsentShared` + and `Share_MakesMeterFactoryGraphWide_WithinOneRoot`. Add a test there + only if a new docs claim isn't backed. One candidate: without sharing, + two nested consumers in one `Composer.Create` graph get different + factories. + +### D4: `ComposeData` failure and result counts (F4) (`compono-6bg.4`) + +Wording rule for every item below: describe **whole-theory** failure. The +theory test case fails once, with the first failing row's +`CompositionException`, and the remaining rows aren't executed. Never +suggest that each row failed independently or was reported as a separate +failure. + +- [x] `docs/packages/compono-xunitv3.md` "Failures, seeds, and row labels": + extend the existing "fails as a unit" text. + - Composition happens when the theory runs, and all rows are built + before any of them runs. A composition failure in one row therefore + stops the rest: no row of that theory executes, including rows that + would have passed. + - The theory then reports a single failed result instead of one result + per row, so the suite's reported test count can drop while the + failure is present. + - Every data attribute on the same method is affected, including + `[InlineData]` rows. + - Once the composition error is fixed, every row runs and is counted + again. +- [x] `docs/packages/compono-xunitv3-aot.md`: the same explanation. ADR-0070 + item 9 applies to both engines. +- [x] `docs/troubleshooting/common-errors.md`: a symptom entry, "A + `ComposeData` theory's test count dropped / only one result is + reported". It covers the cause, the single-result behavior, the fix, + and a link to the guide section. +- [x] `skills/compono/references/xunit-v3.md`, and the AOT reference if it's + separate: the same explanation, condensed. + +### D5: Skill evals (`compono-6bg.5`) + +- [x] `skills/compono/evals/evals.json`: add or update evals for + (a) "IMeterFactory could not be satisfied" → `UseMetrics()`; + (b) "do I need both `UseMetrics().Share()` and + `[Shared]`?" → either one; (c) "my theory count dropped when a row + failed" → expected, ADR-0070; fix the row. Update any existing eval + whose expected output prescribes both together. + +### D6: Validation (`compono-6bg.6`) + +- [x] `dotnet build` — 0 warnings, 0 errors. +- [x] Relevant existing test suites (at least `Compono.XunitV3.Tests`, + `Compono.Metrics.Tests`, and any project touched) green on every + supported TFM; full `dotnet test` green. +- [x] `mkdocs build --strict` passes. +- [x] Validate `skills/compono/evals/evals.json`: it parses as JSON, new + entries match the existing schema, and ids are unique. The repo has + no dedicated eval validator, so use `jq` or an equivalent. +- [x] Confirm `git diff` shows no `src/` changes. ApiCompat, pack-consume, + AOT, and package-validation gates don't apply unless that changes. +- [x] Regenerate `docs/reference/api` only if any public XML doc changed + (none is planned). +- [x] Update this plan's checklist and Notes in the same PR. + +## Critical Files + +- `docs/troubleshooting/common-errors.md` +- `docs/packages/compono-metrics.md`, `docs/packages/compono-logging.md` +- `docs/packages/compono-xunitv3.md`, `docs/packages/compono-xunitv3-aot.md` +- `docs/cookbook/vary-composed-configuration-per-theory-row.md` +- `docs/migrating-from-microsoft-extensions-diagnostics-testing.md` +- `skills/compono/references/{metrics,logging,xunit-v3}.md` +- `skills/compono/evals/evals.json` +- `test/Compono.XunitV3.Tests`, `test/Compono.Metrics.Tests` (example-backing tests only) + +## Test Plan + +Only tests that back new docs claims: + +- the optional base-profile snippet (D2), in `Compono.XunitV3.Tests`; +- adapter-level `[Shared]` sharing (D3), in `Compono.XunitV3.Tests`, only if + it isn't already covered; +- metrics lifetime (D3), in `Compono.Metrics.Tests`, only if a new claim is + unbacked. + +No behavior changes, so no regression tests are needed. Existing `ComposeData` failure tests +already cover the as-a-unit contract. + +## Notes + +- 2026-11-12: plan proposed from RESEARCH-0041. Each finding was reproduced + in an out-of-repo harness (xUnit 4.0.1, net11.0, JIT). The maintainer + chose documentation-only for all four. +- 2026-11-12: maintainer review of the proposal made four changes: + - D4 stays, and is worded as whole-theory failure, not per-row failure. + - D3 adds no `Compono.XunitV3` dependency to `Compono.Metrics.Tests`; + adapter coverage goes in `Compono.XunitV3.Tests`. + - D2 keeps `Register(() => config)` as the primary recommendation, with + `ConfigProfile` as an optional consumer-side convenience only. + - D1 includes the stale `CompositionException` sample correction. +- 2026-11-12: maintainer approved the plan and added D6 gates (`mkdocs build + --strict`, evals.json validation, per-TFM suites, zero warnings). + - Beads: epic `compono-6bg`; children `.1` (D1) through `.6` (D6). + - Dependencies: D1, D2, D3, and D4 can run in parallel. + - D5 is blocked by D1, D3, and D4. + - D6 is blocked by D1 through D5. +- 2026-11-12: D1-D6 implemented locally (not committed). + - D1: corrected the runtime sample to include "configuration rule"; added + the `IMeterFactory`/`ILogger` mapping in `common-errors.md`, the + `Compono.Metrics`/`Compono.Logging` guides, and the skill references; + cross-linked the Metrics misuse entry. + - D2: kept `Register(() => config)` primary; added the optional + consumer-side `ConfigProfile` note (cookbook + package guide, + brief skill note), backed by + `OptionalBaseProfile_RegistersRowConfig_ForAComposedParameter` in + `DocumentedRecipeTests`. + - D3: removed the redundant `Share()` from the lead + `[Shared]` example and added one-or-the-other guidance to the package + guide and skill. The migration guide needed no change (it already uses + `[Shared]` without `Share`). Adapter-level coverage was missing, so added + `SharedParameter_DeclaredAfterDependent_IsSharedAcrossTwoNestedConsumers`; + added `NestedConsumers_GetIndependentFactories_WithinOneRoot_AbsentShared` + to back the no-sharing claim. + - D4: documented the whole-theory failure contract in the xUnit v3 package + guide, the AOT guide, `common-errors.md`, and the skill reference. + - D5: added evals 75-77; no existing eval prescribed both sharing + mechanisms together. + - D6 validation (macOS arm64): `dotnet build` 0 warnings/0 errors; full + `dotnet test` 7,642 total, 0 failed, 501 skipped; `Compono.XunitV3.Tests` + (339 passed per TFM) and `Compono.Metrics.Tests` (105-106 passed per TFM) + green on net8.0-net11.0; `uv run mkdocs build --strict` passed; + `evals.json` parses, 77 entries, 0 duplicate ids; `git diff` shows no + `src/` changes. +- 2026-11-12: review corrections applied (no Beads reopened; epic and + children remain closed). + - F1: removed the false "or a catch-all provider resolved first" clause + from the missing-provider guidance in the skill metrics/logging + references; a catch-all that resolves prevents that failure, and + registration order is now called out as a separate concern. + - F2: strengthened the optional base-profile test — distinct config per + row, the SUT consumes the composed config (`RetentionPolicy.Window`), + and the derived profile no longer manually registers `RetentionPolicy`. + - F3: corrected the duplicate-registration wording in the cookbook to a + `CompositionException` wrapping a `CompositionConfigurationException`. + - F4: corrected the `DocumentedRecipeTests` header to separate the + RESEARCH-0040 recipes (also AOT-proven) from the RESEARCH-0041 optional + consumer-side base-profile recipe (JIT-only coverage). + - F5: corrected the `Compono.Metrics` "no props asset" claim in the + package guide and skill reference — the package ships a + `build`/`buildTransitive` props asset that defaults + `ComponoMetricsOwnsMeterFactory` to `true`; consumers can override it + but don't configure it. Eval 75 no longer asserts unrelated MSBuild + behavior, and eval 67's ownership-property wording was corrected. + - Revalidation (macOS arm64): `dotnet build` 0 warnings/0 errors; full + `dotnet test` 7,642 total, 0 failed, 501 skipped; `Compono.XunitV3.Tests` + 339 passed per TFM and `Compono.Metrics.Tests` 105-106 passed per TFM on + net8.0-net11.0; `uv run mkdocs build --strict` passed; `evals.json` + parses with 77 unique ids; `git diff -- src/` empty. +- 2026-11-12: targeted verification approved the plan for commit and PR. + Final editorial corrections: eval 75 now describes the failure across all + composition resolution stages, and the metrics docs/skill describe the + packaged props asset (consumer-overridable) rather than calling it + internal. Revalidated `evals.json` (77 unique ids) and + `uv run mkdocs build --strict`; `git diff -- src/` remains empty. diff --git a/docs/plans/README.md b/docs/plans/README.md index f7962fd..c1a9539 100644 --- a/docs/plans/README.md +++ b/docs/plans/README.md @@ -90,3 +90,4 @@ one. This file is just the mechanics: numbering, status, and the index. | [0073](0073-compono-nunit-classic-vstest-discovery-impl-plan.md) | Compono.NUnit: classic-VSTest discovery-time module initialization (Issue #171) | Done | | [0074](0074-compono-metrics-testing-support-impl-plan.md) | `Compono.Metrics`: `System.Diagnostics.Metrics` Testing Support (Issue #165) | In Progress | | [0075](0075-issue-161-1-4-dogfood-follow-up-impl-plan.md) | Issue #161 1.4 Dogfood Follow-Up (Metrics `IMeterFactory` ownership, Logging prefix filters, docs) | Done | +| [0076](0076-issue-161-preview-128-dogfood-follow-up-impl-plan.md) | Issue #161 preview.128 Dogfood Follow-Up (documentation only) | Done | diff --git a/docs/research/0041-issue-161-preview-128-dogfood-follow-up.md b/docs/research/0041-issue-161-preview-128-dogfood-follow-up.md new file mode 100644 index 0000000..d69d837 --- /dev/null +++ b/docs/research/0041-issue-161-preview-128-dogfood-follow-up.md @@ -0,0 +1,380 @@ +# RESEARCH-0041: Issue #161 preview.128 Dogfood Follow-Up — Four Findings + +**Status:** Complete. Every finding is triaged. The maintainer decided all +four on 2026-11-12: each is resolved by documentation, with no code, public +API, or ADR change. Execution is tracked by +[PLAN-0076](../plans/0076-issue-161-preview-128-dogfood-follow-up-impl-plan.md). + +**Trigger:** the consumer's follow-up comment on +[#161](https://github.com/LayeredCraft/compono/issues/161#issuecomment-6832495571). +The consumer upgraded to `1.4.0-preview.128` (xUnit v3 JIT, with Compono, +Logging, Metrics, Options, TestDoubles, and XunitV3). Every PR #181 item +behaved as documented: 231/231 tests passed, with 0 warnings and no `CMP` +diagnostics. Four follow-up observations remain. None is a regression. + +**Release state when researched:** `main` at `546af41` (PR #181 merged). +`v1.4.0` hasn't shipped stable. + +## Summary + +| # | Finding | Kind | Disposition | +|---|---|---|---| +| 1 | Missing `UseMetrics()` gives a generic error | Documentation gap (diagnostic enhancement declined) | **DOCUMENT** | +| 2 | Exposing the row's `TConfig` takes boilerplate | Convenience over a supported pattern | **DOCUMENT** (opt-in API **REJECTED** for now) | +| 3 | `UseMetrics()` plus `Share()` | Documentation defect (misleading lead example) | **DOCUMENT** | +| 4 | A failed `ComposeData` row collapses the theory count | Expected behavior (ADR-0070 item 9) | **DOCUMENT**; per-row isolation **DEFERRED** | + +No runtime defect was found. No provider precedence, sharing, or ownership +contract changes. + +## Reproduction harness + +A throwaway xUnit v3 project lives outside the repository, in the session +scratchpad. It targets `net11.0` and uses `xunit.v3.mtp-v2` 4.0.1. It takes +`ProjectReference`s to `src/Compono`, `src/Compono.Metrics`, and +`src/Compono.XunitV3`, plus `src/Compono.Generators` as an analyzer, with +`ComponoMetricsOwnsMeterFactory=true`. The harness changed no tracked file. +Results are quoted below. + +## Finding 1: missing `UseMetrics()` gives a generic error + +**Consumer report.** If `UseMetrics()` is left out, composition throws: + +``` +Compono.CompositionException : No registration, configuration rule, semantic provider, +test-double provider, built-in provider, or generated plan could satisfy 'IMeterFactory'. +``` + +The consumer asks for a hint naming `UseMetrics()`, and the same for +`ILogger` → `UseLogging()`. + +**Reproduced.** `Composer.Create(_ => { }).Create()`, where +`OrderService(IMeterFactory)`, gives exactly that message. + +**Where it comes from.** The message is built once, in +`CompositionContext.ResolveCore` (`src/Compono/CompositionContext.cs:679-681`), +after stages 3 to 8 have all returned `NotHandled`. Core knows only the +requested `Type`. It has no notion of which package owns which type, and the +modularity rule (AGENTS.md: core never references or knows about an +integration package) forbids adding one. + +**What the generator knows.** `ComponoMetricsOwnsMeterFactory` reaches the +generator as `GeneratorFeatureFlags.MetricsOwnsMeterFactory` +(`ComponoIncrementalGenerator.cs:44-48`). `TransitiveClosureWalker` uses it +only to skip generating an `IMeterFactory` double (`TransitiveClosureWalker.cs:212-217`). +`ComponoGeneratedLogging` works the same way for `ILogger`/`ILogger` +(ADR-0055 Amendment 4). The generator could therefore produce ownership +facts. Today nothing carries them to the runtime. + +**Options considered.** + +1. **Status quo plus docs.** Add a troubleshooting entry keyed on the exact + message: `IMeterFactory` → `UseMetrics()`, `ILogger`/`ILogger` → + `UseLogging()`. No code. +2. **Generator-emitted hint.** Add a generator-facing core hook (an + `EditorBrowsable(Never)` type-to-hint registry). The generator emits a + `[ModuleInitializer]` that registers "IMeterFactory is supplied by + Compono.Metrics; call `UseMetrics()`" when the flag is on and the type is + reached. Core appends the hint only on a final no-provider failure for + that exact type. Core stays package-agnostic, because the text comes from + the generator. Costs: new core surface used only for messages, a generator + emitter, an ADR amendment, and JIT and AOT tests. +3. **Generic core wording.** For an interface, abstract type, or delegate + that nothing handled, add "register it, or add the test-double provider + that supplies it". There's no coupling and it helps every interface, but + it can't name `UseMetrics()`. +4. **Compile-time diagnostic.** Rejected. Whether `UseMetrics()` was called + is a runtime builder fact. A profile can live in another assembly, and a + syntactic scan would raise false positives. + +**Avoiding misleading guidance.** Every runtime option (2 and 3) fires only +after the whole pipeline has failed. A consumer who supplies `IMeterFactory` +through `Register()`, `UseServiceProvider`, or another stage-6 provider +never reaches that point, so they never see the hint. The docs entry carries +the same "if you meant Compono.Metrics to supply it" wording. + +**Decision (maintainer, 2026-11-12): option 1, documentation only.** The +error is accurate, appears at the right moment, and names the type. A +troubleshooting entry fixes the lookup cost without new core surface. Option +2 stays recorded as the smallest code path if diagnostic evidence grows. If +it's ever built, it applies to both Logging and Metrics. + +**Incidental drift.** The sample message in +`docs/troubleshooting/common-errors.md` ("No registration, semantic +provider, …") is missing "configuration rule", which the real message +includes. The maintainer confirmed on 2026-11-12 that correcting it is part +of the finding 1 docs change (PLAN-0076 D1). + +**Public API / compatibility / AOT / performance.** None. + +## Finding 2: reading the row's `TConfig` takes boilerplate + +**Consumer report.** Each profile adds `builder.Register(() => config)`, and +the test declares an extra parameter. The consumer calls this minor. + +**How `TConfig` flows.** For `ComposeData`, row element 0 +is the `TConfig`. It's passed to the `TProfile` constructor +(`ConfigProfileBinder`, ADR-0036, ADR-0070 item 4) and isn't bound to any +test parameter. `[Compose(args)]` builds `TConfig` from +attribute constants the same way. The profile is the only code that sees +the instance. + +**Already supported.** RESEARCH-0040 finding 2 and PR #181 documented the +recipe: the profile registers `config`, and a composed `TConfig` parameter +resolves at stage 3 to that row's own instance. The consumer confirmed it +works. It's in `docs/cookbook/vary-composed-configuration-per-theory-row.md`, +`docs/packages/compono-xunitv3.md`, and `skills/compono/references/xunit-v3.md`. + +**Why automatic registration conflicts.** + +- **Duplicate registration.** `Register()` is strict, so a duplicate is a + build-time error. Auto-registering `TConfig` would break every consumer + who already wrote the documented recipe, this consumer included. +- **Graph-wide side effect.** A stage-3 registration answers every + `TConfig` request in the graph, not just a test parameter. A `TConfig` + that is also a SUT dependency (an options record, for example) would + silently change resolution. That violates "predictability over magic". +- **Surface.** An explicit opt-in (for example `ExposeConfig = true`) means + new public properties on `Compose<,>` and `ComposeData<,>`, in every + adapter that has them (XunitV3, XunitV3.Aot, TUnit, NUnit, MSTest). It + also means generator emission for AOT and parity tests. That's a lot of + surface to remove one line per profile. + +**Assessment.** This is convenience around a supported pattern, not a +missing capability. The test parameter is inherent: it's how a test reads +any composed value. + +**Decision (maintainer, 2026-11-12): no new API.** +`builder.Register(() => config)` in the profile, plus a composed `TConfig` +parameter, stays the **primary documented recommendation**. For consumers +who repeat that line across many profiles, the docs may also show an +**optional consumer-side convenience**. It's the consumer's own base +profile, not a Compono type, and Compono won't ship it as API: + +```csharp +public abstract class ConfigProfile(TConfig config) : ICompositionProfile + where TConfig : class +{ + protected TConfig Config => config; + + public void Configure(CompositionBuilder builder) + { + builder.Register(() => config); + ConfigureCore(builder); + } + + protected abstract void ConfigureCore(CompositionBuilder builder); +} +``` + +The harness ran this base profile with a 2-row +`ComposeData` theory (JIT). Each row's composed `Win` +parameter was that row's own config, and both rows passed. + +The decline of an opt-in API is recorded here. Revisit only if several +consumers show the explicit line is a real burden. + +**Public API / compatibility / AOT / performance.** None. The recipe is an +ordinary registration. It already works on JIT and AOT. + +## Finding 3: is `Share()` still needed with `UseMetrics()`? + +**Consumer report.** The consumer calls both `builder.UseMetrics()` and +`builder.Share()`, and asks whether both are needed. + +**Existing semantics.** + +- `MetricsProvider` returns a **new** `CapturingMeterFactory` per request + (`src/Compono.Metrics/MetricsProvider.cs`). ADR-0072 "Lifecycle and + ownership" makes this deliberate: composition is non-owning, and sharing + is opt-in. +- `[Shared]` parameters are composed **first**, before any other + parameter, whatever their declaration order (ADR-0022 binding step 6). + The result is stored in the row's shared scope, so every later request + for that type in the row gets the same instance. +- `Share()` (ADR-0056) makes the first request for `T` in a graph the + shared one, from any source and in any order, with no `[Shared]` needed. + It also applies to `Composer.Create()` graphs, which have no + parameters. + +**Reproduced (harness, all passing):** + +| Setup | Result | +|---|---| +| `UseMetrics()` only; `(OrderService sut, [Shared] IMeterFactory meters)` | `meters` is the SUT's factory, even when declared after the SUT | +| `UseMetrics()` only; `([Shared] IMeterFactory meters, Coordinator c)` with two nested consumers | Both consumers get `meters` | +| `UseMetrics().Share()`; undecorated `(IMeterFactory meters, Coordinator c)` | Both consumers get `meters` | +| `UseMetrics()` only; undecorated `IMeterFactory` plus SUT | Different instances | +| `Composer.Create(b => b.UseMetrics()).Create()` | The two nested consumers get different factories | + +**Multiple factories and measurement collection.** Each +`CapturingMeterFactory` captures only the meters it created. If two +components get different factories, a test that asserts against one of them +misses the other's measurements. That's why sharing matters. It doesn't +matter which mechanism provides the sharing. + +**Generated doubles and provider ordering.** These aren't involved. +`ComponoMetricsOwnsMeterFactory` already guarantees that no generated +`IMeterFactory` double exists (ADR-0072 Amendment 5). Sharing caches +whatever stage 6 produced. It doesn't change which provider wins. + +**Answer to the consumer.** Use one or the other: + +- In a `[Compose]`-family test that takes `[Shared] IMeterFactory`, the + attribute alone is enough. `Share()` is redundant but + harmless. +- Use `Share()` in a profile for profile-wide intent: tests + that take an undecorated `IMeterFactory`, or `Composer.Create` graphs with + several consumers. + +**Root cause of the confusion.** The lead example in +`docs/packages/compono-metrics.md` (lines 54-70) uses both together without +saying why. `skills/compono/references/metrics.md` ("`Share()` and +`[Shared]`") says "Prefer `Share()`", while its own examples +use `[Shared]`. Those are documentation defects. + +**Decision (maintainer, 2026-11-12): fix the docs only.** Test placement: +adapter-level `[Shared]` sharing coverage, if any is needed, goes in +`Compono.XunitV3.Tests` with a stand-in type. `Compono.Metrics.Tests` gets +no `Compono.XunitV3` dependency and keeps only metrics lifetime tests that +don't involve an adapter. `UseMetrics()` +keeps composing a new factory per request. Making it share by default would +reverse ADR-0072's non-owning lifecycle and change `Composer.Create` +behavior, so it was declined. An opt-in overload was declined because it +would duplicate `Share()`. + +**Public API / compatibility / AOT / performance.** None. + +## Finding 4: a failed `ComposeData` row collapses the theory count + +**Consumer report.** When a row fails to compose (for example because +`UseMetrics()` is missing), the theory is reported once instead of once per +row. The Application project's count fell from 49 to 42. + +**Reproduced (xUnit 4.0.1, JIT).** A 3-row +`ComposeData` theory where only row 1 omits `UseMetrics()`: + +``` +Probe.F4.ComposeDataRows [FAIL] + Compono.CompositionException : ComposeData row 1 from 'Probe.F4.Rows' for + 'Probe.F4.ComposeDataRows' failed: No registration, ... could satisfy 'IMeterFactory'. + Seed: 1556484067 +``` + +One result is reported. Rows 0 and 2, which would pass, **never run**. The +same theory with every row valid reports three results. + +**Where the failure happens.** At execution time, during row +materialization, not during discovery or the test body: + +- `ComposeDataAttribute.SupportsDiscoveryEnumeration()` returns `false` + (`src/Compono.XunitV3/ComposeDataAttribute.cs:100`). Discovery therefore + creates **one** delay-enumerated test case for the theory (RESEARCH-0038 + §2.2). +- At execution, xUnit calls `GetData`. `GetDataCore` composes every row in a + loop (`ComposeDataAttribute.cs:149-156`). The first `CompositionException` + aborts the loop, so xUnit gets no rows and reports the single test case as + failed. + +**Is xUnit in control of the count?** Yes. A delay-enumerated theory's result +count is however many rows `GetData` returns. When it throws, xUnit reports +the test case itself. That's xUnit's model, not a Compono choice. + +**Scope.** + +- Every data attribute on the method is affected. One non-discoverable + source collapses the whole method into one test case, so `[InlineData]` + rows on the same method fail with it (RESEARCH-0038 §2.2). +- `[Compose]` and `[Compose]` produce one row, so there's no + count to collapse. The failure behavior is otherwise the same. +- `Compono.XunitV3.Aot` follows the same contract (ADR-0070 item 9 applies + to both engines). + +**Status: expected behavior.** ADR-0070 item 9 ("the theory test case fails +as a unit. No placeholder rows, no custom invokers") and its Negative +Consequences ("Whole-theory failure granularity") accept this explicitly. +The maintainer rejected per-row alternatives in RESEARCH-0038 Q12. It's +already documented in `docs/packages/compono-xunitv3.md` ("Failures, seeds, +and row labels") and the skill. Neither says plainly that the **reported +count drops** or that other data attributes' rows go down too. + +**New evidence: deferred per-row failure prototype (JIT only).** Two +mechanisms were tried in the harness: + +1. **A row whose `ITheoryDataRow.GetData()` throws lazily.** This still + collapses to one failure. xUnit reads every row's data before running + any. **Not viable.** +2. **A placeholder row plus a before-test hook.** `GetData` catches the row + failure, stores the exception in a static dictionary keyed by a GUID, and + returns a placeholder row with typed default arguments and a trait + `compono.rowFailure = `. The same attribute implements + `IBeforeAfterTestAttribute`. `Before` looks up the trait and rethrows the + stored exception. Result: **3 results, 2 passed and 1 failed with the + real `CompositionException`.** The test body didn't run for the failing + row. + +**Why the prototype doesn't justify reopening ADR-0070 now.** + +- **Display identity.** The failing row shows placeholder arguments + (`DeferredRows(n: 0, s: null)`) unless a synthetic `TestDisplayName` is + set. Either way the name is invented, not the row's real identity. +- **Typed placeholders.** Every parameter needs a value its type accepts. + For a value type that means creating a default instance through + reflection on JIT and generated code on AOT. A `null` passed for a value + type fails conversion with a misleading error. +- **Out-of-band state.** A process-wide static dictionary that leaks if the + row is filtered out or never runs. A synthetic trait also becomes visible + in Test Explorer and filter output. +- **Hook ordering.** Other `BeforeAfterTest` attributes on the class or + assembly run around Compono's hook. Their side effects would run for a + row that can't execute. +- **AOT parity unknown.** It hasn't been checked whether xUnit's AOT core + honors `IBeforeAfterTestAttribute` on a data attribute through the + generated registration path. ADR-0070 item 13 requires engine parity. +- **It reverses a recorded decision (Q12)** on one report where the + consumer calls the effect "harmless but surprising". + +**Other option considered.** Composing every row and throwing one exception +that lists every failing row keeps the xUnit model, but the count still +collapses and valid rows still don't run. It wasn't chosen. + +**Decision (maintainer, 2026-11-12): document, and keep ADR-0070 +unchanged.** The user docs to update are the xUnit v3 guide, the AOT +guidance, troubleshooting, and the skill. They must state that a composition +failure stops the remaining rows from running and can lower the reported +test count. They must describe whole-theory failure: the theory fails once, +with the first failing row's exception. They must not imply that each row +failed on its own. Record the +prototype and its limits here. Per-row isolation is a **possible future +investigation**, to reopen only if more real-world evidence appears (for +example several consumers, or CI tooling that depends on stable per-row +counts). That investigation would start from mechanism 2 above, and would +first settle AOT parity, display identity, and state lifetime. + +**Public API / compatibility / AOT / performance.** None. + +## Test coverage if the deferred options are ever implemented + +- **F1 option 2:** generator tests (flag on emits the hint registration, + flag off or type not reached emits nothing); runtime tests (hint present + only on a no-provider failure for that exact type; absent when + `Register`, `UseServiceProvider`, or another provider supplies it); + Logging parity; an AOT smoke test. +- **F2 opt-in:** each adapter and engine (JIT, AOT, TUnit, NUnit, MSTest); + a duplicate-registration conflict with an explicit `Register`; a + `TConfig` that is also a SUT dependency. +- **F4 per-row isolation:** result counts with mixed good and bad rows; + display names; value-type placeholders; `[InlineData]` plus `ComposeData` + on one method; filtered and explicit rows (state cleanup); other + `BeforeAfterTest` attributes present; AOT parity. + +## Links + +- [#161 preview.128 comment](https://github.com/LayeredCraft/compono/issues/161#issuecomment-6832495571) +- [RESEARCH-0040](0040-issue-161-1-4-dogfood-follow-up.md) (findings 1-3 precedents) +- [RESEARCH-0038](0038-issue-163-composed-theory-data-rows.md) §2.2 and Q12 +- [ADR-0022](../adr/0022-compono-xunit-package-design.md) (binding step 6, `[Shared]` first) +- [ADR-0056](../adr/0056-composition-builder-share-graph-wide-sharing.md) (`Share()`) +- [ADR-0070](../adr/0070-xunitv3-composedata-composed-theory-rows.md) item 9 +- [ADR-0072](../adr/0072-compono-metrics-testing-support-package.md) "Lifecycle and ownership", Amendment 5 +- [PLAN-0076](../plans/0076-issue-161-preview-128-dogfood-follow-up-impl-plan.md) diff --git a/docs/troubleshooting/common-errors.md b/docs/troubleshooting/common-errors.md index 6047d15..528318e 100644 --- a/docs/troubleshooting/common-errors.md +++ b/docs/troubleshooting/common-errors.md @@ -47,8 +47,9 @@ CreateOrderHandler └── OrderValidator validator └── IRuleProvider rules -No registration, semantic provider, test-double provider, built-in -provider, or generated plan could satisfy IRuleProvider. +No registration, configuration rule, semantic provider, test-double +provider, built-in provider, or generated plan could satisfy +IRuleProvider. Seed: 8451203967726193045 ``` @@ -78,6 +79,15 @@ if you want an automatic substitute. `Compono.Bogus` doesn't supply interface providers — it only matches `string`-typed members by name, so it won't resolve this. +**If the name in the message is `IMeterFactory` or `ILogger`/`ILogger`** +and you meant `Compono.Metrics` or `Compono.Logging` to supply it, call +`UseMetrics()` or `UseLogging()` from the profile or `Composer.Create` +builder. Supplying the type yourself through `Register()` or +`UseServiceProvider` is equally valid — the point is that no provider was +registered for it. For the related instrument/`Verify()` symptoms, see +[Verify metrics on a non-Compono IMeterFactory +throws](#verify-metrics-on-a-non-compono-imeterfactory-throws). + **A genuine construction cycle always fails this way too, immediately** — Compono has no `OmitOnRecursionBehavior`-style opt-out; a self-referencing object graph fails fast with the same path-annotated message rather than @@ -245,6 +255,20 @@ constructor's **own** message and the original exception is kept as `AddProfile()` and applies to every framework's `[Compose]` and `[ComposeData]`, so those failures read identically. +### "A `[ComposeData]` theory's test count dropped / only one result is reported" + +A composition failure in any row stops the whole theory. `[ComposeData]` +builds all rows when the theory runs, before any row executes, so one +failing row prevents every other row — including rows that would have +passed — from running. xUnit then reports the theory as a single failed +result instead of one result per row, which is why the suite's reported +count can drop. Every data attribute on the same method is affected, +including its `[InlineData]` rows. This is the documented whole-theory +failure contract, not a lost or silently skipped test: fix the +`CompositionException` in the failing row, and every row runs and is +counted again. See [Failures, seeds, and row +labels](../packages/compono-xunitv3.md#failures-seeds-and-row-labels). + ### "A composed value doesn't look realistic" (looks like an anonymous string) `Compono.Bogus` isn't installed, or `UseBogus()` wasn't called, or the diff --git a/skills/compono/evals/evals.json b/skills/compono/evals/evals.json index d1f1338..f278ae8 100644 --- a/skills/compono/evals/evals.json +++ b/skills/compono/evals/evals.json @@ -842,12 +842,12 @@ "id": 67, "category": "behavioral-correctness", "prompt": "I registered both UseNSubstitute() and UseMetrics() but the order was builder.UseNSubstitute().UseMetrics(). When my test calls meters.Verify(\"shop.orders.placed\") on the composed IMeterFactory it throws InvalidOperationException saying the instance is not a Compono metrics factory. Also, do I need to set an MSBuild property so UseMetrics() generates something?", - "expected_output": "Explains the real cause: Compono's stage-6 test-double providers resolve first-registered-wins, and UseNSubstitute() was registered before UseMetrics(), so IMeterFactory resolved to an NSubstitute substitute instead of a CapturingMeterFactory - the fix is reordering to builder.UseMetrics().UseNSubstitute(). Explicitly answers the second question: no MSBuild property is needed or exists - unlike Compono.Logging/Compono.TestDoubles there is no generation opt-in for Compono.Metrics at all; the failure is registration order, not a missing opt-in.", + "expected_output": "Explains the real cause: Compono's stage-6 test-double providers resolve first-registered-wins, and UseNSubstitute() was registered before UseMetrics(), so IMeterFactory resolved to an NSubstitute substitute instead of a CapturingMeterFactory - the fix is reordering to builder.UseMetrics().UseNSubstitute(). Explicitly answers the second question: no MSBuild generation opt-in is needed or exists for Compono.Metrics - its packaged props asset defaults ComponoMetricsOwnsMeterFactory=true so TestDoubles won't generate an IMeterFactory double, and consumers can override it but don't set it manually; the failure is registration order.", "files": [], "expectations": [ "Correctly identifies first-registered-wins stage-6 provider precedence as the cause, not a Compono.Metrics bug", "Recommends reordering to builder.UseMetrics().UseNSubstitute() (UseMetrics first for IMeterFactory)", - "Explicitly states no MSBuild opt-in property exists or is needed for Compono.Metrics", + "States no MSBuild generation opt-in is needed; the ownership property is defaulted by the package rather than manually configured", "Does not suggest a priority/specificity mechanism that doesn't exist" ] }, @@ -941,6 +941,46 @@ "Notes earlier GetMeasurements snapshots are unaffected by clearing", "Does not invent Checkpoint(), Since(...), or BeginCapture() APIs" ] + }, + { + "id": 75, + "category": "behavioral-correctness", + "prompt": "Compono throws CompositionException: \"No registration, configuration rule, semantic provider, test-double provider, built-in provider, or generated plan could satisfy 'IMeterFactory'.\" The project references Compono, Compono.XunitV3, and Compono.Metrics. What is missing?", + "expected_output": "The message means no composition stage could satisfy IMeterFactory: no registration, configuration rule, semantic provider, test-double provider, built-in provider, or generated plan supplied it. Since Compono.Metrics is referenced, add builder.UseMetrics() (in a profile or Composer.Create); it registers the stage-6 provider that composes IMeterFactory as CapturingMeterFactory. Register()/UseServiceProvider is also valid. A registration-order conflict with a catch-all provider is a separate problem from this missing-provider failure. Do not suggest a hand-rolled factory.", + "files": [], + "expectations": [ + "Recommends UseMetrics() as the fix for the IMeterFactory composition failure", + "Explains the message means no composition stage supplied IMeterFactory", + "Mentions Register()/UseServiceProvider as a valid alternative", + "Does not recommend a hand-rolled IMeterFactory or Microsoft.Extensions.Diagnostics.Testing" + ] + }, + { + "id": 76, + "category": "behavioral-correctness", + "prompt": "Do I need both builder.UseMetrics().Share() in my profile and [Shared] IMeterFactory meters on my [Compose] method?", + "expected_output": "No - use one or the other. [Shared] is per-test intent and resolves first whatever the parameter position; Share() is for profile-wide intent, an undecorated IMeterFactory parameter, or several consumers in one Composer.Create graph. Both together is redundant but harmless. What matters is sharing: each CapturingMeterFactory captures only its own meters, so a different factory sees no measurements.", + "files": [], + "expectations": [ + "States that using both is unnecessary - one mechanism is enough", + "Explains [Shared] for per-test intent and Share() for profile-wide/undecorated/Composer.Create sharing", + "Explains why sharing matters: each factory captures only its own meters", + "Does not claim both are required together or that [Shared] only works when declared first" + ] + }, + { + "id": 77, + "category": "behavioral-correctness", + "prompt": "My [ComposeData] theory used to report several test cases, but after one row's composition started failing the suite only reports one failed result for the whole theory. Did Compono lose the other rows?", + "expected_output": "No - this is the documented whole-theory failure contract (ADR-0070 item 9). All rows are composed before any row runs, so the first failing row stops the rest (including rows that would have passed), and xUnit reports the theory as a single failed result instead of one per row; the reported count drops while the failure is present. Every data attribute on the method, including [InlineData], is affected. Fix the row's CompositionException and all rows run and are counted again.", + "files": [], + "expectations": [ + "States the other rows were not lost or silently skipped - the whole theory fails as a unit", + "Explains all rows are composed before any run, so one failing row stops the rest", + "States the theory reports one failed result instead of one per row and the count can drop", + "Notes every data attribute on the method, including [InlineData], is affected", + "Recommends fixing the failing row's CompositionException to restore all rows" + ] } ] } diff --git a/skills/compono/references/logging.md b/skills/compono/references/logging.md index 249f35b..fbcda44 100644 --- a/skills/compono/references/logging.md +++ b/skills/compono/references/logging.md @@ -31,6 +31,13 @@ public void RetriesLogAWarning(ILogger logger, OrderService servic } ``` +**Composition failed naming `ILogger`/`ILogger`?** If you meant +`Compono.Logging` to supply it, `UseLogging()` wasn't registered — see +`docs/troubleshooting/common-errors.md#runtime-composition-failures`. +`Register>()`/`UseServiceProvider` is equally valid. Provider +registration order is a separate concern (see below); a catch-all provider +that resolves the dependency prevents this missing-provider failure. + ## When to use it A composed type takes an `ILogger`/`ILogger` constructor dependency diff --git a/skills/compono/references/metrics.md b/skills/compono/references/metrics.md index 2e90491..c28ffbb 100644 --- a/skills/compono/references/metrics.md +++ b/skills/compono/references/metrics.md @@ -33,6 +33,13 @@ public void PlacingAnOrderCountsIt([Shared] IMeterFactory meters, CheckoutServic } ``` +**Composition failed naming `IMeterFactory`?** If you meant +`Compono.Metrics` to supply it, `UseMetrics()` wasn't registered — see +`docs/troubleshooting/common-errors.md#runtime-composition-failures`. +`Register()`/`UseServiceProvider` is equally valid. Provider +registration order is a separate concern (see below); a catch-all provider +that resolves the dependency prevents this missing-provider failure. + ## When to use it A composed type takes an `IMeterFactory` constructor dependency and the test @@ -52,9 +59,15 @@ an `IMeterFactory`. Unlike `Compono.Logging` (`ComponoGeneratedLogging`) and `Compono.TestDoubles` (`ComponoGeneratedTestDoubles`), `Compono.Metrics` -ships **no generator involvement and no MSBuild property at all**. It relies -only on the in-box `System.Diagnostics.Metrics` BCL types. Never suggest a -compile-time opt-in for it — there is none. +ships **no generator or analyzer**, and consumers never set an MSBuild +property to turn `UseMetrics()` on. The package ships a +`build`/`buildTransitive` props asset that defaults +`ComponoMetricsOwnsMeterFactory` to `true`, which tells +`Compono.Generators` not to emit a `Compono.TestDoubles` double for +`IMeterFactory`; consumers can override it (set it to `false`) but don't +configure it manually. It relies only on +the in-box `System.Diagnostics.Metrics` BCL types. Never suggest a +compile-time generation opt-in for it — there is none. ## Core usage vocabulary @@ -232,11 +245,14 @@ package — register them from the shared factory in a profile. ## `Share()` and `[Shared]` A composed `IMeterFactory` participates in `Share()` like any other type -— no metrics-specific mechanism. `[Shared] IMeterFactory meters` gives the -SUT and the test body the same factory, exactly like `[Shared] ILogger`; -without `[Shared]` the test's factory is a different instance from the SUT's -and can't be asserted against or disposed. Prefer `Share()` -in a profile for a reusable whole-suite intent. +— no metrics-specific mechanism. Use **one or the other**: `[Shared] +IMeterFactory meters` for per-test intent (resolved first, any parameter +position) gives the SUT and test body the same factory; `Share()` +declared in a profile for profile-wide intent, an undecorated +`IMeterFactory` parameter, or several consumers in one `Composer.Create` +graph. Both is redundant but harmless. Without either, the test's factory +is a different instance from the SUT's and can't be asserted against or +disposed — each `CapturingMeterFactory` captures only its own meters. ## Native AOT and trimming diff --git a/skills/compono/references/xunit-v3.md b/skills/compono/references/xunit-v3.md index ebc1a8b..c3941f9 100644 --- a/skills/compono/references/xunit-v3.md +++ b/skills/compono/references/xunit-v3.md @@ -206,6 +206,11 @@ public sealed class RetentionProfile(RetentionWindow window) : ICompositionProfi public void Keeps(int ageInDays, bool expected, RetentionWindow window, RetentionPolicy sut) { } ``` +If many profiles repeat `builder.Register(() => config)`, a consumer-side +`ConfigProfile` base is an optional boilerplate reduction — not a +Compono type. A derived profile must not register `TConfig` again +(duplicate-registration error). + ### Shared dependencies and `[Shared]` `[Shared]` works on a `[ComposeData]` row exactly as on `[Compose]`: put a @@ -247,7 +252,12 @@ Row metadata merges with the attribute's own by one rule: Reading the member or building row `i` throws `CompositionException` — the whole theory fails **as a unit** (there are no placeholder rows). The message names the member (`Type.Member`), the zero-based row index, and the -row label if it has one. +row label if it has one. All rows are built before any runs, so one row's +composition failure stops the rest — including rows that would have passed — +and the theory reports a single failed result instead of one per row, so +the reported test count can drop. Every data attribute on the method, +including `[InlineData]`, is affected. Fix the row and every row runs and is +counted again. Exactly **one** seed source applies per row: diff --git a/test/Compono.Metrics.Tests/CompositionTests.cs b/test/Compono.Metrics.Tests/CompositionTests.cs index 3715250..b90ba9a 100644 --- a/test/Compono.Metrics.Tests/CompositionTests.cs +++ b/test/Compono.Metrics.Tests/CompositionTests.cs @@ -35,6 +35,16 @@ public void EachComposedRequest_GetsItsOwnFactory_AbsentShared() second.Meters.Should().NotBeSameAs(first.Meters); } + [Fact] + public void NestedConsumers_GetIndependentFactories_WithinOneRoot_AbsentShared() + { + var composer = Composer.Create(builder => builder.UseMetrics()); + + var coordinator = composer.Create(); + + coordinator.Meters.Should().NotBeSameAs(coordinator.Service.Meters); + } + [Fact] public void Share_MakesMeterFactoryGraphWide_WithinOneRoot() { diff --git a/test/Compono.XunitV3.Tests/DocumentedRecipeTests.cs b/test/Compono.XunitV3.Tests/DocumentedRecipeTests.cs index c79e88a..aa942c5 100644 --- a/test/Compono.XunitV3.Tests/DocumentedRecipeTests.cs +++ b/test/Compono.XunitV3.Tests/DocumentedRecipeTests.cs @@ -3,14 +3,21 @@ namespace Compono.XunitV3.Tests; // Real-runner proof for the recipes RESEARCH-0040 (#161 1.4 dogfood follow-up) documents instead of // adding API: finding 2 (read a ComposeData row's TConfig in the test body by registering it from the // profile; row values bind to the leading parameters) and finding 6 (supply profile constructor -// arguments through a parameterless wrapper profile, or a single-row ComposeData). The same recipes -// are proven under the xUnit Native AOT runner in Compono.XunitV3.Aot.Tests/DocumentedRecipeTests.cs. +// arguments through a parameterless wrapper profile, or a single-row ComposeData). Those RESEARCH-0040 +// recipes are also proven under the xUnit Native AOT runner in +// Compono.XunitV3.Aot.Tests/DocumentedRecipeTests.cs. +// +// Also covers the optional consumer-side ConfigProfile base-type recipe from RESEARCH-0041 +// (#161 preview.128 follow-up). That base type is consumer test-project code, not a Compono type, and +// this JIT test is its only coverage - no Native AOT counterpart was added for it. public sealed record RetentionWindow(int DaysBefore, int DaysAfter); public sealed class RetentionPolicy(RetentionWindow window) { - public bool Keeps(int ageInDays) => ageInDays >= -window.DaysBefore && ageInDays <= window.DaysAfter; + public RetentionWindow Window { get; } = window; + + public bool Keeps(int ageInDays) => ageInDays >= -Window.DaysBefore && ageInDays <= Window.DaysAfter; } // Finding 2: the profile already receives the row's config - registering it makes it composable. @@ -52,6 +59,29 @@ public void Configure(CompositionBuilder builder) } } +// Optional consumer-side boilerplate reduction for finding 2 (the profile registers the row's own +// config once); not a Compono type. +public abstract class ConfigProfile(TConfig config) : ICompositionProfile + where TConfig : class +{ + protected TConfig Config => config; + + public void Configure(CompositionBuilder builder) + { + builder.Register(() => config); + ConfigureCore(builder); + } + + protected abstract void ConfigureCore(CompositionBuilder builder); +} + +public sealed class BaseRetentionProfile(RetentionWindow window) : ConfigProfile(window) +{ + // No additional registrations: the base type's Register(() => config) is what lets Compono + // compose RetentionPolicy from this row's RetentionWindow. + protected override void ConfigureCore(CompositionBuilder builder) { } +} + public sealed class DocumentedRecipeTests { public static TheoryData RetentionCases => new() @@ -120,4 +150,24 @@ public void SingleRowComposeData_SuppliesNonConstantProfileArguments(RecipeRepos log.Entries.Should().Equal("saved 7"); } + + public static TheoryData BaseProfileCases => new() + { + { new RetentionWindow(DaysBefore: 1, DaysAfter: 2), 2, 2, true }, + { new RetentionWindow(DaysBefore: 5, DaysAfter: 10), 11, 10, false }, + }; + + [Theory] + [ComposeData(nameof(BaseProfileCases))] + public void OptionalBaseProfile_RegistersRowConfig_ForAComposedParameter( + int ageInDays, + int expectedDaysAfter, + bool expected, + RetentionWindow window, + RetentionPolicy sut) + { + window.DaysAfter.Should().Be(expectedDaysAfter); + sut.Window.Should().BeSameAs(window); + sut.Keeps(ageInDays).Should().Be(expected); + } } diff --git a/test/Compono.XunitV3.Tests/SharedParameterSharingTests.cs b/test/Compono.XunitV3.Tests/SharedParameterSharingTests.cs new file mode 100644 index 0000000..94a83cc --- /dev/null +++ b/test/Compono.XunitV3.Tests/SharedParameterSharingTests.cs @@ -0,0 +1,39 @@ +namespace Compono.XunitV3.Tests; + +public interface ISharedStandIn +{ +} + +public sealed class SharedStandIn : ISharedStandIn +{ +} + +public sealed class SharedStandInConsumer(ISharedStandIn dependency) +{ + public ISharedStandIn Dependency { get; } = dependency; +} + +public sealed class SharedStandInRoot(SharedStandInConsumer first, SharedStandInConsumer second) +{ + public SharedStandInConsumer First { get; } = first; + public SharedStandInConsumer Second { get; } = second; +} + +public sealed class SharedStandInProfile : ICompositionProfile +{ + public void Configure(CompositionBuilder builder) => + builder.Register(() => new SharedStandIn()); +} + +public sealed class SharedParameterSharingTests +{ + [Theory] + [Compose] + public void SharedParameter_DeclaredAfterDependent_IsSharedAcrossTwoNestedConsumers( + SharedStandInRoot sut, + [Shared] ISharedStandIn shared) + { + ReferenceEquals(shared, sut.First.Dependency).Should().BeTrue(); + ReferenceEquals(shared, sut.Second.Dependency).Should().BeTrue(); + } +} \ No newline at end of file