Guarantees and Limitations
This page records what the suite guarantees, and what it deliberately does not do. Treat it as the contract a change must not break.
Runtime guarantees
Section titled “Runtime guarantees”Result<TValue, TError>is areadonly record structwith exactly three observable states:Uninitialized(thedefaultvalue),SuccessandFailure, each observable throughIsInitialized,IsSuccessandIsFailure.Result<TError>is the value-less counterpart: areadonly record structwith the same three states and the same throw-on-misuse contract, whose success holds theSuccessmarker instead of a value.Errorthrows in the wrong state,Match,Map,Bind,MapErrorand the extension operations throw"The result is uninitialized."fordefault,Throw()returns theSuccessmarker or throwsResultException<TError>, andToString()staysSuccess/Failure(error)/Uninitialized.- The throw-on-misuse contract holds:
ValueandErrorthrowInvalidOperationExceptionin the wrong state, andMatch,Map,BindandMapErrorthrow"The result is uninitialized."fordefault. An uninitialized result is never silently coerced into a success or a failure. Throw()returns the successful value, throwsResultException<TError>carrying the error on failure, and throws"The result is uninitialized."fordefault. It is the one deliberate result-to-exception escape hatch.ToString()staysSuccess(value)/Failure(error)/Uninitialized.IResultValueaccessors never throw; the accessor that does not describe the current state returnsnull. A successful unit result’sSuccessValueis theSuccessmarker.- The implicit conversions from
TValue,TErrorandSuccess, and theResult.Success/Result.Failure,Result<TValue, TError>.Success/.FailureandResult<TError>.Success/.Failurefactories, are public contract.
Observability
Section titled “Observability”Purview.Results.AspNetCore emits metrics under the meter Purview.Results.AspNetCore
(ResultsHttpTelemetry.MeterName):
| Instrument | Meaning |
|---|---|
purview.results.failures.mapped |
failures a registered mapping or fallback answered |
purview.results.failures.unmapped |
failures with no mapping, answered with the unmapped-failure response |
purview.results.uninitialized |
endpoints that returned a default result, which is always a bug |
Each measurement carries a purview.results.error_type tag with the error’s type name (unknown for an
uninitialized result, which has no error), and the failure
paths add the same tag to Activity.Current — enriching the request span ASP.NET Core already created
rather than starting one. The type name is always present in telemetry, because metrics and traces stay
inside your own infrastructure; disclosing it in the HTTP response is separately opt-in through
IncludeErrorTypeInProblemDetails.
builder.Services.AddOpenTelemetry() .WithMetrics(metrics => metrics.AddMeter(ResultsHttpTelemetry.MeterName));Log messages carry stable event identifiers, so they can be filtered without matching message text:
1000 uninitialized result, 1001 unmapped failure, 2000 a ZodSharp rule answering a multi-error
failure. No log statement records a validation payload or any user input.
These use Meter and Activity from the base class library, available through the ASP.NET Core framework
reference, so no telemetry package dependency is added.
Thread safety
Section titled “Thread safety”-
A result is safe to pass between threads by value. It is a
readonly record structwith no mutable state, so copying it — returning it, passing it as an argument, awaiting aTask<Result<…>>— is safe. -
A result is not safe to store in a shared mutable field and write concurrently. A multi-field struct is not written atomically:
Result<TValue, TError>holds the value, the error and a state byte, so a reader can observe a torn value where the state saysSuccesswhile the value field is still the previous one.This is worse than it first looks, because of the nullability annotations.
IsSuccessis annotated[MemberNotNullWhen(true, nameof(Value))], so the compiler has been told a success implies a non-nullValue— and will elide the null check at your call site. A torn read therefore surfaces as aNullReferenceExceptionin your code, with nothing pointing back here.If you need to share a result through mutable state, synchronise it, or box it into a field of a reference type and publish that reference (a reference assignment is atomic):
// Not safe: concurrent writers can tear the struct.static Result<Tenant, TenantError> _cached;// Safe: the reference is published atomically.static Tuple<Result<Tenant, TenantError>>? _cached; -
ResultsHttpOptionsis startup configuration. Its mapping dictionary and fallback list are frozen the first time a request reads them, so a registration added after the first failure is handled is ignored rather than corrupting a collection another thread is enumerating. Configure it inAddResultsHttpand do not mutate it afterwards. -
The generated helpers and factories are static and stateless, and
DefaultResultsHttpMapperholds no per-request state, so both are safe to use concurrently.
Dependency guarantees
Section titled “Dependency guarantees”Purview.Resultsis dependency-free.- The ZodSharp and ASP.NET Core packages depend on it, never the reverse.
Purview.Results.AspNetCoredeliberately knows nothing about ZodSharp; validation handling lives inPurview.Results.ZodSharp.AspNetCore.- The runtime packages contain no reflection, no
dynamicand no runtime type discovery. Union structure is inspected only by the source generator, through Roslyn symbols.
Union support limits
Section titled “Union support limits”[GenerateResult]is supported onuniondeclarations, custom[Union]types and source-visiblePurview.Unions[GenerateUnion]targets, including class-based unions, nullable cases and generic unions. A[GenerateUnion]target’s cases are read from itstypeoflist, partial static factory signatures,IUnionMembersprovider or source-visible constructors — never from another generator’s output — and a target with no source-visible case list isRSG1001. Generic unions are supported, as areIUnionMembersmember providers that declare a public static single-parameterCreateper case. A bare union type parameter case gets the union-receiver factory only. A case that names a type parameter the union does not declare isRSG1002; an array case isRSG1009; a provider with no usableCreateisRSG1007. The[GenerateUnion]path is proved end to end against the packaged generators (Purview.Unions1.0.0-prerelease.2) inSourceGenerator.UnitTestsandExamples.Unions;Purview.Resultstakes no dependency on it.- Generated implicit conversions are not possible — see Union Errors for the five compiler
rules. The per-case
AsFailure<TValue>()andAsFailure()helpers, the union-receiverUnion.Failure(...)/Union.Success(...)factories and the IDE code fix are the ergonomics the language allows; the helper-free alternative is the(TenantError)caseValuecast. - Accessibility never widens: a union or case type that is not visible produces an
internalgenerated class (RSG1003covers the case where generated code could not reference a type at all).
HTTP mapping philosophy
Section titled “HTTP mapping philosophy”- An unmapped failure is a host mapping gap, not a domain outcome. It is answered with
UnmappedStatusCode(500) and aProblemDetailscarryingUnmappedTitle, and it is logged with its case type. The type name is written into the response’serrorTypeextension only whenIncludeErrorTypeInProblemDetailsis set (it is off by default, because it discloses internal namespaces); an uninitialized result always carrieserrorType = "results_uninitialized". ThrowOnUnmappedFailureexists for development and keeps throwingInvalidOperationException.- An uninitialized result (
default) takes the unmapped path and is logged, because an endpoint returningdefaultis a bug. IResultsFailureMapperis the way in for rules keyed by a value rather than a type, and it must not become a catch-all that answers every failure — that hides exactly the gaps the unmapped-failure response exists to expose.
ZodSharp mapping philosophy
Section titled “ZodSharp mapping philosophy”- Code rules are consulted before category rules, which are consulted before origin rules (each in registration order), then the default validation problem, so a rule can only narrow what the host already gets.
- A rule matches when any of the failure’s errors carries its code, category or origin: a rule a schema can silently never reach is the kind of gap this suite surfaces rather than hides.
- A factory returns
nullto decline, and matching continues. Factories see the failure’s whole error set.
Not in scope
Section titled “Not in scope”- No exception-to-result conversion: exceptions remain for exceptional circumstances. The reverse — turning a
result failure into an exception — is available explicitly through
Throw(). - No runtime union inspection: matching an error case is ordinary C# pattern matching.
- No replacement for
Result<TValue, TError>orResult<TError>: the generator only adds call-site ergonomics. - No
Task/ValueTask-specific async combinators beyondMapAsyncandBindAsync. The async combinators takeTask<T>only, carry noCancellationTokenoverloads, and await withConfigureAwait(false). - No serialization support. A result is a control-flow type, not a DTO, so neither
Result<TValue, TError>norResult<TError>ships aJsonConverterand neither is designed to round-trip. Reflection-basedSystem.Text.Jsonserialization throwsInvalidOperationException, because it probes whichever ofValue/Errordoes not describe the current state and those accessors throw by contract. Serialize the outcome you want instead: unwrap withMatch,TryGetValue/TryGetError, or — over HTTP — letPurview.Results.AspNetCoremap the result to a response.IResultValueis the non-throwing view available to infrastructure that has to inspect a result generically. - A Native AOT minimal API returns
result.ToHttpResult(), not the result. UnderPublishAot, ASP.NET Core’s request delegate generator resolves JSON metadata for a handler’s declared return type when it builds the endpoints, and a result has none (a union error cannot be described by System.Text.Json’s source generator either), so a handler declared to return a result fails at startup there.ToHttpResult()returns anIResult; see ASP.NET Core Integration.
Related
Section titled “Related”- Core Concepts — the state contract in detail.
- Diagnostics — the rules that enforce the union limits.
- ASP.NET Core Integration — the mapping order described above.