Repository navigation
v7.0.0
Major release for .NET 10, describing the change from v6.0.2. Adds a completion stage to the mediation pipeline, four named decision stages that decide whether work happens, declarative message metadata, and an audit trail and in-process idempotency built on all three. The pre stage carries most of the break: guards, validators, shortcuts, and pre-handlers are four contracts the framework distinguishes before invoking them, which fixes the order they run in. The declaration model is general rather than an auditing feature: an application declares its own metadata, reads it back through an accessor, enforces it at compile time and at composition time, and a named priority band positions its unit-of-work commit against the framework's own writers. In-process mediation is observable, a refusal can be received as a value rather than caught, and a message can be asked whether it would be permitted without being performed. The outbox schema moves to version 2 with a nullable handler column for per-handler delivery, upgraded automatically where schema initialization is enabled; the inbox and saga schemas are unchanged, and the PostgreSQL idempotency and recurring-lease tables are new. Transport metadata changes in three places, listed under Breaking: Kafka and SQS use the shared litebus-route and content-type header names, and AMQP ingress scopes its broker idempotency key to the queue. Under a contextual payload encryptor, drain the inbox and outbox before upgrading: v6 encrypted those rows without the context v7 authenticates.
Added
-
LiteBus.Outbox.Storage.Martenstages outbox rows on the current MartenIDocumentSessionwithQueueSqlCommand, so the row commits in the sameSaveChangesAsyncas the documents. Register it withUsePostgreSqlStorage(postgres => postgres.UseMartenTransactionalOutbox()). It suits an application whose session serves reads and writes, where the ambient-transaction route would open a write transaction for every read; it resolvesReturnExistingandStrictidempotency with one read before staging. -
PostgreSqlOutboxSchema.CreateInsertStatementreturns the outbox insert for one envelope at the current schema version, so a unit of work that queues SQL writes the row the PostgreSQL store writes instead of hand-written column lists. -
RetryOptions.IsPermanentFailuremarks an application exception as permanent, so the inbox and outbox processors dead-letter the message on that attempt instead of spending the retry schedule on a failure no retry can fix. A classifier that throws is treated as not permanent. -
IOutboxManager.GetFailureSummaryAsyncreports, per contract, theFailedandDeadLetteredcounts with the most recent error and time, so a health probe can tell a failing message from a slow backlog. -
LiteBusMessageDeniedException.DeniedByandLiteBusMessageInvalidException.RejectedByname the guard or validator that refused the message, and the exception message includes its type name. Both are set fromPipelineDecision.DecidedBy, which records the deciding handler for a guard denial and a validation failure as well as a shortcut answer. -
TransportOutboxDispatcherOptions.TenantRoutingStrategyandOutboxModuleBuilder.UseContractResolver(IMessageContractResolver)make the dispatcher's tenant routing and the envelope factory's contract resolver configurable. Both constructor parameters existed before, but no builder could fill them. -
TransportPublishRequest.MessageGroupIdandTransportPublishRequest.DeduplicationKey. The transport outbox dispatcher fills them from the envelope (the idempotency key, otherwise the message id; the tenant id, otherwise the contract name), and the SQS adapter sets them on queues whose URL ends in.fifo, so outbox dispatch can publish to SQS FIFO queues. -
KafkaTransportOptions.SocketTimeoutMsandKafkaTransportOptions.MessageSendMaxRetries, each positive when set and left at the librdkafka default otherwise. -
AmqpReceivedMessage.QueueName, andAmqpConsumerOptions.MaxInFlightMessagesso a typedIAmqpConsumersubscription gets the same admission control as the generic consumer path. -
DiagnosticCheckRunOptions.RunTimeout, an overall budget for one diagnostic run. Unset, it is the worst case of the probe count packed intoMaxParallelismlanes atTimeouteach; probes still running when it expires are cancelled and reported unhealthy. A negative budget is rejected when health checks or management endpoints are registered. -
AmbiguousMessageResolveException.Candidatesnames the registered types that tied, andIdempotencyConfigurationExceptionreports an idempotency declaration mistake. -
SagaPurgeFilter.Takebounds a saga purge. -
A Limits and Opt-in Boundaries page, and a documentation home that states what LiteBus costs and which page answers which question.
-
ILeaseRenewable.ReleaseLeaseAsync(LeaseReleaseRequest, CancellationToken)returns a leased message to the queue without charging the attempt its lease consumed. The pipelined processor calls it for every dispatch it cancelled during shutdown or a drain, so a host restart no longer movesattempt_count. Implemented by the in-memory, PostgreSQL and EF Core inbox and outbox stores; the default implementation releases nothing, so a custom store still compiles and falls back to lease expiry.OutboxEnvelope.AsReleasedandInboxEnvelope.AsReleasedare the matching transitions. EventIds 3011 (Debug) and 3012 (Warning, release failed) record the outcome. -
MediationExceptionFilters.IsCallerCancellationrecognizes the caller's cancellation even when a dispatcher wrapped it in its own exception type. -
RecurringCommandHostOptions.IsConcurrencyConflict, defaulting toIsConcurrencyConflictByTypeName. A send that loses an optimistic-concurrency race to another instance is logged at Information (EventId 2104) and the loop waitsIntervalrather thanErrorBackoff, because the work it wanted is already done. -
InMemoryTransportBrokerimplementsIDisposableand completes its destination channels. -
Two operator pages, Message States and Alerting and Production Runbook; a reliability page on Ordering and Concurrency Guarantees; and a roadmap note keeping the integrator field report on analyzer and API gaps.
-
A fifth pipeline stage.
IMessageCompletionHandler<TMessage>,IMessageCompletionHandler<TMessage, TMessageResult>, and the axis contractsICommandCompletionHandler,IQueryCompletionHandler, andIEventCompletionHandlerrun in afinallyon every mediation path, exactly once, and receive a read-onlyMessageCompletionContextcarrying the outcome, the result, the exception, the reason, and the elapsed duration. Post-handlers run only when the main handler succeeds and error handlers only for recoverable exceptions, so no earlier stage could observe how a message actually ended. Recording an audit entry, emitting a metric, or closing a unit of work belongs here. A mediation that throws a non-recoverable fault completes asFailedwith the exception, and cancellation during stream enumeration completes asCanceled, so the unit of work does not commit and the audit records the failure. -
The completion stage is not cancellable. Handlers receive
CancellationToken.None, because the ending has already happened and handing the stage the token that just fired would drop exactly the records a review looks for. -
Guards. A pre-stage handler that may refuse a message implements
IMessageGuard<TMessage>and returns aVerdictfromDecideAsync, with the axis contractsICommandGuard<TCommand>,IQueryGuard<TQuery>, andIEventGuard<TEvent>. A refusal always carries a reason, may carry a code, and reportsMediationOutcome.Denied, which an audit trail records as a denial. The compiler requires the decision, so nothing after it runs by accident, and an expected control-flow path stays off the exception path. -
Validators.
IMessageValidator<TMessage>returnsValidityfromValidateAsync, with the axis contractsICommandValidator<TCommand>,IQueryValidator<TQuery>, andIEventValidator<TEvent>. A validator answers whether the message is well-formed, which is a different question from whether the caller may send it, so a failure reportsMediationOutcome.Invalidrather thanDeniedand stays out of the list a security review reads. Unlike every other decision stage, this one runs every validator and collects their failures rather than stopping at the first: a caller fixing a malformed message should not discover its problems one round trip at a time.ValidationFailurecarries the message, the member it applies to, and an optional code. -
Refusal mappers.
IMessageRefusalMapper<TMessage, TMessageResult>turns a guard refusal or a validation failure into the value the caller receives, for applications that model failure as data rather than as an exception, with the axis contractsICommandRefusalMapper,IQueryRefusalMapper, andIStreamQueryRefusalMapper. One registration againstICommandcovers every command producing that result type, and a mapper registered against a concrete message wins over it. Without a mapper, a refusal reaches the caller asLiteBusMessageDeniedExceptionorLiteBusMessageInvalidException. A stream supplied by a refusal mapper is enumerated through the same runner as a handler stream, so a fault in it reaches the error stage. -
Shortcuts. A pre-stage handler that answers a message whose work is already done implements
IMessageShortcut<TMessage>orIMessageShortcut<TMessage, TMessageResult>and returns aShortcutfromTryAnswerAsync, with the axis contractsICommandShortcut<TCommand>,ICommandShortcut<TCommand, TCommandResult>,IQueryShortcut<TQuery, TQueryResult>,IStreamQueryShortcut<TQuery, TQueryResult>, andIEventShortcut<TEvent>. A cache hit or a replayed idempotent command reportsMediationOutcome.Answered, which an audit trail records as a success because nothing was denied. That separation from a denial is the distinction a security review reads. -
The framework fixes the stage order: guards, then validators, then shortcuts, then pre-handlers. Priority orders handlers inside a stage and never reorders the stages, so a globally registered cache shortcut cannot answer a caller that a message-specific authorization guard would have denied, and a malformed message cannot claim an idempotency key. The order states what each stage may assume about its input: a guard sees every message, a validator sees only messages the caller is allowed to send, a shortcut sees only well-formed ones, and a pre-handler sees only messages that are going to be handled. Under a single pre-handler stage that ordering rested on a priority number the author had to remember, and indirect handlers ran ahead of direct ones regardless. ASP.NET Core documents the same hazard for
UseOutputCacheafterUseAuthorization; because LiteBus owns its stages, it makes the mistake unrepresentable instead of documenting it.PreStagenames the four stages andIPreStageHandlerDescriptor.Stagerecords which one runs a handler. -
Shortcut<TMessageResult>types the answer over the result type of the message, so a shortcut that answers a result-returning message is required by the compiler to supply the value the caller receives. Answering always carries the result; a stream query that means no items answers withAsyncEnumerable.Empty<T>(), which states that outright rather than leaving it implied by a missing value. A denial owes the caller nothing, so one guard contract fits every message, and the value a denied caller receives comes from a refusal mapper instead. -
MessageContextExtensions.RunAsyncPreStagesgives a custom mediation strategy the same stage order the shipped strategies use, in one call rather than four, because running one stage without the others cannot honor the ordering guarantee.ResolveRefusalResult<TMessageResult>applies the registered refusal mapper, or raises when none covers the message. Both live inLiteBus.Messagingrather than in the abstractions package. -
RunAsyncErrorHandlersandRunAsyncCompletionHandlerseach take the execution context and open their own ambient scope, so a strategy no longer has to wrap them. The error runner also captures theExceptionDispatchInfoitself, which preserves the original stack when nothing recovers, and the completion runner resolves a post-handler's replacement result in preference to the handler's own. Both rules were previously a strategy's job to remember. The completion runner takes the outcome, the failure, and the reason a strategy tracked, and builds the context from them. When error handlers recover, the mediation still completes asFailedbut carries no exception, so completion tells a recovered fault from a propagated one. -
LiteBusMessageDeniedExceptionandLiteBusMessageInvalidExceptionreach the caller when no refusal mapper covers the message. Both are excluded from the recoverable-exception filter, so error handlers never see a decision as a fault, andLiteBusMessageInvalidException.Failurescarries every failure the validator stage collected. -
MediationExceptionFilters.IsRefusalandIsRetryableDispatchExceptionclassify a decision apart from a fault. The inbox and outbox processors use the second to dead-letter a refusal or a missing handler on the first attempt instead of spending the retry schedule on an answer that cannot change. -
MediationOutcomedistinguishesSucceeded,Answered,Denied,Invalid,Failed, andCanceled. Every member is reported by some path, and each names a state the message ended in rather than a mechanism the pipeline used. -
IExecutionContext.SuppressPostHandlers()skips the post-handlers that have not run yet. Use it when the work turned out to be a no-op and the reactions to it should not fire, such as an idempotent command that detects it already ran. It does not stop the calling handler and does not change the outcome. -
Declarative message metadata.
IMessageDescriptor.Metadataexposes values resolved once at registration from declaring attributes on the message type and from message definitions, so a pipeline stage reads a dictionary instead of reflecting on every dispatch. -
Message definitions. A definition class lives beside the message it describes and declares one value per concern through
IMessageDefinition<TMessage, TValue>. Declarations are keyed by value type, so one class may declare several without ambiguity, and applications may declare their own value types that LiteBus applies without interpreting. A declaration covers the message type it names and every message assignable to it, so one definition can describe a family of messages; the most derived declaration wins. -
IMessageDeclarationSourcemarks an attribute as a source of message metadata and states the value type it declares. Only attributes implementing it are collected, which keeps metadata bounded, and it puts attributes and definitions on one key so a definition genuinely overwrites an attribute rather than sitting beside it. -
An audit trail at the mediation boundary.
[Audited]and[AuditExempt], or anIAuditDefinition<TMessage>, declare the constant half of a record;IAuditScopesupplies what only the handler knows.EnableAuditing()on the command and query module builders registers the writer, which hands anAuditRecordto the application'sIAuditTrail. Because it runs at the completion stage, refusals, failures, and cancellations are recorded as first-class outcomes.[AuditExempt]records the sameDeclarationExemptionthat[DeclarationExempt(typeof(AuditDeclaration), ...)]records, so every exemption a message carries reads from one place whichever spelling wrote it, and its rationale is validated when the attribute is constructed. -
The trail itself is registered on the messaging module through
UseAuditTrail<TAuditTrail>(lifetime),Scopedby default, orUseAuditTrailInstancefor a pre-created instance, beside the outcome mapper, so the shared half of auditing is configured in one place while the per-axis switch stays where the decision belongs. The instance overload carries its own name because a pre-created instance is necessarily a singleton, which a secondUseAuditTrailoverload would hide at the call site. -
AuditDeclarationis a closed hierarchy ofAuditedDeclarationandAuditExemptDeclaration, so a declaration cannot hold a combination that means nothing, such as a category on an exemption. -
ReasonRequiredon an audited declaration is enforced. A successful action that declares it and supplies no reason raisesAuditReasonMissingExceptionrather than writing an incomplete record. -
AuditTrailDiagnosticCheckreports thelitebus.audit.trailprobe as unhealthy when auditing is enabled and noIAuditTrailis registered, so a missing sink surfaces before the first audited mediation. It resolves the trail through a dispatch scope rather than from the provider, so the default scoped registration passes a container that validates scopes, and it reportsHealthywith the writer name when an application replaced the record writer, since a writer LiteBus did not build need not use a trail at all. -
IAuditOutcomeMapperandMessageModuleBuilder.UseAuditOutcomeMapperlet an application that refuses by throwing record its own exception asAuditOutcome.Deniedrather thanAuditOutcome.Failed. Refusing through a guard needs no mapper. -
MediationExceptionData.SuppressedCompletionFaultsis the key under which a completion-handler fault is attached to the exception that was already ending the mediation, so a failed audit write is never silently discarded. -
LB1018reports command and query types that state no audit position, so an unaudited message is a recorded decision rather than an oversight. Disabled by default; enable withdotnet_diagnostic.LB1018.severity = warning. -
LB1019reports a shortcut that implements the untyped shortcut contract for a message that produces a result. BecauseICommand<TResult>derives fromICommand, that contract compiles there, and answering from it fails at runtime withLiteBusConfigurationException. The typed contract is a strict superset for such a message, so the rule names it and the declaration is where the fix goes. Open generic shortcuts are not reported, and guards and validators never are: a refusal owes the caller no result, so one contract is correct for every message on those stages. -
Registration rejects an untyped shortcut declared for a message that produces a result, so the mistake
LB1019reports cannot reach production in a project that does not reference the analyzer package. The check runs from both directions, since a handler may be registered before or after the message it handles. -
HandlerPrioritiesreserves a priority window for handlers shipped by LiteBus, so ordering against them is a documented guarantee.ReservedFlooropens it,ReservedCeilingcloses it, and application handlers own the band below the floor, where an unannotated handler already sits, and the band at or above the ceiling.UnitOfWorknames the position in that upper band where an application commits, which is what makes an audit record staged by the writer atObservabilitypart of the transaction that applies the change it describes. OnlyPersistenceandObservabilitymay be reordered between releases, and only against each other.UnitOfWorksits atReservedCeiling + 100, leaving the ceiling itself a pure boundary marker with nothing on it. -
IExecutionContext.Datais anIHandleContextData: a store keyed by the CLR type of the value rather than by a string, created once per mediation. A guard whose decision depends on loaded state hands the loaded object to the main handler instead of forcing a second round trip, which is the cost that keeps authorization inside handlers rather than in the stage that owns the decision.Itemsstays for string-keyed interop.Get<T>throwsHandleContextDataNotFoundExceptionnaming the type,TryGet<T>covers the optional case, and access is lock-guarded because parallel event handlers share one execution context. -
IMessageMetadataAccessorreads a message type's declared metadata from application code, throughForMessageandTryGet. Reading a declaration previously meant injectingIMessageRegistry, callingFind, and reaching throughIMessageDescriptor.Metadata, which made the registry's descriptor shape part of every application reading a declaration it wrote itself. An unregistered type raisesMessageMetadataNotFoundExceptionrather than answering with an empty collection, because an empty answer turns a missing registration into a permission check that silently passes. An unregistered runtime type that mediation resolves through a base descriptor reads that descriptor's metadata instead, exactly as if registered, and is audited under its declaration; only a type nothing covers raises, and an ambiguous fallback raisesAmbiguousMessageResolveException. -
MessageModuleBuilder.RequireDeclaration<TValue>()fails composition for any registered message that neither declares a value of that type nor records an exemption from it, naming every offender grouped by the declaration each one omits. It runs through the newIModuleConfiguration.RegisterCompositionValidationhook, after every module has built, because the messaging module is foundational and has no commands to inspect during its own build. -
[DeclarationExempt(typeof(TValue), rationale)]records that a message deliberately declares nothing for one metadata type. It is repeatable and every instance is aggregated into oneDeclarationExemptionsvalue, readable through the accessor like any other declaration. The rationale is what separates a decision from an omission. -
[MessageDeclaration(typeof(TValue))]states, on an attribute class, which metadata value that attribute declares.IMessageDeclarationSource.DeclarationTypeis a runtime property an analyzer cannot execute, so without a static declaration no compile-time rule can tell that[RequiresPermission]is how a message states its permission. Registration fails when the annotation and the property name different types. -
LB1020reports a command or query type that states no position on a metadata value type named inlitebus_required_declarations, andLB1021reports a configured name that does not resolve.LB1018is the preconfigured instance ofLB1020overAuditDeclaration, sharing its analysis rather than duplicating it. A written policy such as "every command states the permission it requires" becomes a build failure instead of something code review has to catch. -
ThrowingValidator<TMessage, TException>, with the axis specializationsThrowingCommandValidatorandThrowingQueryValidator, adapts a validator whose body still reports failure by throwing. It is migration scaffolding for theValiditysignature change: adapted and converted validators mix in one mediation because the stage collects across both, so a codebase converts module by module instead of in one commit touching every validator. Only the named exception type is caught, so a genuine fault inside a validator still ends the mediation as a failure. -
Open generic handlers may take two type parameters, binding the message type and the result type the message declares through the new
IProducesResult<TMessageResult>marker onICommand<T>,IQuery<T>andIStreamQuery<T>. A generic post-handler, completion handler, or error handler reaches the typed contract instead of falling back to anobject?it can do nothing with. Arity 2 is accepted only when the handler implements a contract taking both parameters in order, so a second parameter the handler invented is still rejected, and a message declaring no result is skipped the way a constraint mismatch is. -
In-process idempotency.
IIdempotencyDefinition<TMessage>declares the key a repeat is recognised by,IIdempotencyStoreremembers which keys were applied, andCommandModuleBuilder.EnableIdempotency()registers two shortcuts and a completion handler that claim the key before the handler runs and settle it after: applied on success, released on anything else, so a transient failure does not turn the retry into a false repeat. The durable inbox and outbox already dedupe envelopes; this is the same problem one layer in, answered with the shortcut stage plus the declaration and the storage contract.IdempotencyDeclaration.ReplayResultrecords the first answer so a repeated result-producing command can be answered with it; without it, a repeat raises a configuration error naming the fix rather than inventing adefault.InMemoryIdempotencyStoreships fromLiteBus.Testing.Mediation, because a store that forgets on restart and knows only its own process cannot make a claim about the system. A grant carries a claim token the completion handler settles with, so a late settle after a takeover is a no-op. The stored key defaults to the message full type name, escapes its segments, and prefixes the mediation tenant when one is set; a blank explicit scope is rejected withIdempotencyConfigurationException. -
The
litebus.idempotency.storediagnostic probe reportsUnhealthywhen idempotency is enabled and noIIdempotencyStoreis registered, and thelitebus.audit.trailprobe reportstrailIsSingleton, resolved by comparing the trail across two dispatch scopes. -
IHandlerDescriptor.ContractTyperecords the closed contract a descriptor was discovered from, andPipelineDispatchcarries the delegate bound to it at registration. -
An audit record says who acted.
AuditRecord.Actorcarries anAuditActorwith a requiredIdandKindand optionalDisplayNameandOnBehalfOf, supplied by anIAuditActorResolverthe application registers throughUseAuditActorResolver.AuditActor.User(id)andFor(kind, id)take no display name; writeAuditActor.User(id) with { DisplayName = name }, which keeps personal data out of the trail unless the application deliberately puts it there.Kindstays a string, because the set of things that can act belongs to the application. The resolver receives the completion context, so it reads the actor off the message and runs on every path, which attributes a denied command; a pre-stage handler cannot, because a guard that denies stops the pipeline before any pre-handler runs, and a denied command is the case a trail exists for. A handler that knows more than the resolver overrides it withIAuditScope.WithActor. Returning null is legitimate and means nothing established an actor, which is a different answer from a named process. The message itself is deliberately not on the record: it is handed to the resolver, so a payload cannot reach audit storage by default. Thelitebus.audit.trailprobe reports a missing resolver asDegradedand carriesactorResolverRegistered. -
MessageModuleBuilder.AddAuditingconfigures the whole audit feature in one call: the trail, the actor resolver, the outcome mapper, and which axes produce records, throughAuditingBuilder. Without it, the trail on the messaging builder and the per-axis switch on the command and query builders can be registered without each other and found out only from a diagnostic probe. Configuring a trail and selecting no axis now raisesAuditConfigurationExceptionat composition, which no probe can report at runtime because nothing is ever audited and so nothing ever fails. The per-axisEnableAuditing()calls remain and are what this composes. -
EventModuleBuilder.EnableAuditing(). A domain fact is frequently the thing a review most wants recorded, so the event axis enables auditing the same way commands and queries do. One record per publish, not per handler: the mediation is the unit being audited, and a record per subscriber would turn one fact into as many entries as there happen to be reactions. -
IMessageDefinition<TMessage>declares every value for a message from oneDescribe(IMessageDeclarations)method, withDeclare<TValue>,Audited,NotAuditedandExempt<TValue>on the collection. The keyedIMessageDefinition<TMessage, TValue>remains and is the better choice for a single declaration, because the compiler checks it; past one it stops paying, since the second and every later value has to be written as an explicit interface implementation naming the message type and the value type again, which is the type name three times to say one thing. Both shapes write into the same type-keyed bag, so a codebase uses whichever fits each message. -
Declaration requirements can be scoped.
RequireDeclaration<TValue, TScope>()covers every message assignable to a marker, andRequireDeclaration<TValue>(predicate, description)covers an arbitrary selection with the words the error uses. The unscoped form applies to commands, queries and events alike, so requiring a permission of commands also demands one from every query and produces exemptions that say nothing, which trains a team to treat a rationale as paperwork. The scope is a type rather than a namespace on purpose: a namespace is a string a refactoring tool moves without telling anyone, and for an authorization rule that failure is an unguarded command that used to be guarded. The composition error names the scope alongside every offender. -
MessageModuleBuilder.ValidateComposition(Action<IMessageCatalog>)runs an application rule over every registered message after every module has built.IMessageCatalogenumeratesMessageCatalogEntryvalues carrying the message type, its resolved metadata, and itsAuditedDeclaration, with anAudited()filter. The underlying hook takes anIModuleConfiguration, which only anIModuleimplementation receives, which is a lot of ceremony for a five-line assertion.RequireUniqueAuditActions()andRequireAuditActionFormat(pattern)ship as built-ins over it, because every audited application needs both and getting either wrong corrupts the trail rather than breaking the build. -
ICommandMediator.TrySendAsyncandIQueryMediator.TryQueryAsyncreturnMediationResultandMediationResult<TResult>instead of raising a refusal. A denial and a validation failure are routine endings that the pipeline already models as decisions internally, and converting them to exceptions at the boundary left an HTTP endpoint catching one to produce a 403. A genuine fault still throws: a database timeout is not something a boundary should branch on, and a result carrying the exception would invite one to be swallowed. Where a refusal mapper is registered, the mapped value arrives alongside the denied outcome, so an application sees both its own shape and the framework's classification. -
ICommandMediator.EvaluateAsyncandIQueryMediator.EvaluateAsyncanswer whether a message would be permitted and well-formed, without performing it, returning aMediationDecision. This is what removes the second authorization method an application otherwise writes, one to authorize while doing and one for a caller that shows or hides a control; two methods answering the same question drift, and the drift is silent and security-relevant, because a button stays visible for an action the pipeline will refuse. It runs guards and validators only, because a shortcut and a pre-handler act rather than decide: the shipped idempotency shortcut claims a key, so evaluating a page full of controls would burn keys for commands nobody submitted.MessageContextExtensions.RunAsyncDecisionStagesexposes the same prefix to a custom mediation strategy. -
In-process mediation is observable.
LiteBusMediationTelemetrydeclares theLiteBus.Mediationactivity source and meter with public instrument names:litebus.mediation.duration,litebus.mediation.count,litebus.mediation.stage.durationandlitebus.mediation.decisions. One span per mediation namedmediate {MessageType}, tagged with the message, the outcome and the decision code; the decisions counter is tagged with the stage and the deciding handler, which turns "which stage denied this" from a stack trace into a filter. Only aFailedoutcome sets the span error status, because a denial is a decision and colouring every refused request red makes a trace view useless for finding the requests that actually broke. The inbox, the outbox, the transport and each broker adapter all published instruments while the library's primary job published none.MessageModuleBuilder.UseTelemetry(MediationTelemetryOptions)decides what is recorded: spans and metrics are on, per-stage spans and per-stage metrics are opt-in because mediation volume is orders of magnitude above durable-processing volume. The newLiteBus.Messaging.Extensions.OpenTelemetrypackage registers the source and the meter withAddLiteBusMediationInstrumentation()andAddLiteBusMediationMetrics(). -
IMessageReader.Explain(Type)returns aMessagePipelinePlan: the message, the result type it declares, and every handler that will run in the order it will run, asMessagePipelineSteprecords naming the stage, the priority, the handler, the contract, and whether it arrived indirectly or from a closed open generic. With a hundred messages, open generic guards, an audit writer and a commit, answering "what runs for this command" previously meant reading the registry in a debugger. It reproduces the pipeline's own ordering rules, including that completion orders by priority alone across the direct and indirect split, and it reads from the registry rather than computing at compile time because the registry is the only thing that knows about closed open generics, base-type registrations and priority ties. -
LiteBusCompositionSummaryreports what the host actually composed: message counts per axis, every open generic handler with the number of messages it was closed over, the audit trail and its lifetime, whether an actor resolver is registered, the declaration policies enforced, and how many application composition checks run. Resolve it and logToString()once at startup. The open generic line matters most: adding one file to a scanned assembly inserts a pipeline stage into every message it fits, and nothing in the composition code shows it. -
IMessageWriter.RegisterFromScan(Type)records that a type arrived through an assembly scan rather than being named, surfaced asIMessageReader.ScannedOpenGenericHandlersandIMessageReader.OpenGenericClosures.MessageModuleBuilder.RequireExplicitOpenGenerics()then fails composition, naming each scanned open generic and the registration line that fixes it. It is opt-in rather than the default because picking up open generic handlers is what an assembly scan has meant since v4, and turning that off changes what a scan is rather than fixing a defect. -
IHandleContextDatagained keyed overloads ofSet,Get,TryGet,ContainsandRemove. One value per type cannot express a command that names two accounts, which is the identity-map case the store's own worked example implies. Keys are compared withobject.Equals, so an identifier value object is usable directly, and the unkeyed slot is a distinct slot rather than a reserved key value, so neither can clear the other.HandleContextDataNotFoundExceptionnow carries theKeyalongside theDataType. -
ShortcutandShortcut<TMessageResult>carry aCodealongside their reason, andMessageCompletionContextexposesCode.Codemeans the same thing on all three decision shapes and onVerdict: something a later stage can switch on, where the reason is prose written for a person. Without it, a completion handler counting why messages were answered had to match on English, and a metric could not tell a cache hit from an idempotent replay. -
AuditReasonMissingExceptionis raised when an audited action declaresReasonRequiredand the handler supplied no reason. It carries the action and the message type. -
Family defaults.
MessageModuleBuilder.DeclareDefault<TScope, TValue>(value)declares a value for every message assignable to a marker, andIMessageWriter.AddDeclaration(MessageDeclarationItem)records a declaration without a definition class. "Everything under organizations requires ManageOrganization unless it says otherwise" is a rule worth stating once; declaring it on each of a hundred commands states it a hundred times and gives it a hundred places to drift. Nothing new decides precedence: a declaration still resolves to the one written closest to the message, so a command carrying its own value keeps it and the family inherits the default, which is the rule a definition written for a base type has always followed. The scope is a type rather than a namespace for the reason a scoped requirement is: a namespace is a string a refactoring tool moves without telling anyone, and for an authorization default that failure is a command that used to be guarded and now is not. Two defaults for one scope and value type are a configuration error, and the writer's defaultAddDeclarationthrows rather than accepting the call and dropping it, because a silently dropped default is an unguarded command that looks configured. -
An application can own the audit record shape.
AuditingBuilder.UseRecordWriter<TWriter>(lifetime)andUseRecordWriterInstance, overMessageModuleBuilder.UseAuditRecordWriter, replace the writer that turns a completed mediation into a record.AuditRecordis a handoff toIAuditTrailrather than a persistence schema, so a different set of fields needs a differentIAuditRecordWriter, which is the entire contract between the pipeline and auditing. A replacement keeps the completion-stage placement, theObservabilitypriority and the per-axis selection, and replaces exactly the record building; everything the built-in writer uses is public, including the audit position throughIMessageRegistry,AuditReasonMissingException,IAuditScope,AmbientExecutionContext, andIAuditOutcomeMapper. Skipping a message that declares no audit position is part of the contract, because without it every message on the selected axes produces a record. There is deliberately no genericAuditRecord<T>orIAuditTrail<TRecord>: a type parameter there spreads through the writer, three axis completion handlers, the probe, the builder andAddAuditing, so every application wanting the default would pay for the few that do not, and it buys nothing a writer cannot already do. The fixed shape maps onto NIST SP 800-53 AU-3, PCI DSS Requirement 10 and the DMTF CADF event model. -
LiteBusCompositionSummary.AuditRecordWriternames a writer that replaced the built-in one, and the startup line reports it. Replacing the writer replaces the whole of record building, and nothing else in the composition would say so, which makes a misregistration look exactly like auditing working. -
The audit catalogue is derived rather than maintained.
IMessageCatalogis registered as a Singleton so it resolves at runtime and not only inside a composition check, andAuditCatalogue.ToRowsprojects every audited message into anAuditCatalogueRowcarrying the action, the message, the category, the target kind, and whether a reason is required.ToMarkdownis one formatter over those rows. Rows are the primary surface because what a compliance process consumes differs per team, and a library emitting only Markdown would serve one team and obstruct the rest. Rows are ordered by action so two runs produce the same document. The other half of an authorization matrix stays the application's: a required permission is an application value type, projected fromMessageCatalogEntry.Metadataalongside these rows, because only the application knows what its own declarations mean. -
MediationHarnessinLiteBus.Testing.Mediationruns the shipped pipeline over hand-supplied handler instances, with no host and no container, and reports which pre stages ran. Asserting that a guard denies previously meant booting the whole host, which for an application with a relational store meant a database container for a test about one authorization decision.MediationHarnessResult.StagesRunis the part no consumer can build, because only the stage runner knows it, and when the point of the library is that behavior moved into named stages that is the assertion a test of the behavior wants. It runs the real strategies through the real stage runner, so the fixed stage order, the validator stage's aggregation, and priority ordering all apply; what it leaves out is composition, so a registration a host would reject still has to be asserted against a host.MessageRegistryFactory.Create()andMessageMediatorFactory.Create(registry, dispatchScopeFactory)are the public seams it is built on, bothEditorBrowsable(Never), for a manual host composing LiteBus without a container. -
AuthorizationDeclarationlets a message state its authorization position the wayAuditDeclarationstates its audit position:[Authorized(policy)],[AuthorizationExempt(rationale)], the keyedIAuthorizationDefinition<TMessage>, and theAuthorizedandAuthorizationExempthelpers onIMessageDeclarations. LiteBus carries the position and never evaluates the policy;RequireDeclaration<AuthorizationDeclaration, ICommand>()and LB1020 enforce that every message states one, and an application guard reads it throughIMessageMetadataAccessor. -
LiteBus.Commands.Storage.PostgreSqlships a PostgreSQLIIdempotencyStore, registered withcommands.UsePostgreSqlIdempotencyStore(...), with a versioned schema, a startup initializer, and theidempotency.postgresql.schemaprobe. Claims record a request fingerprint and a claim token fencing the grant, a concurrent claim of a key still in flight answersInFlight, and an unsettled claim older thanPostgreSqlIdempotencyStoreOptions.ClaimTimeout(five minutes by default and validated positive, measured on the database clock) is taken over with a new token. -
Recurring commands can run single-flight across replicas:
RecurringCommandHostOptions.RequireLeasetakes a named lease before each pass (LeaseName, defaulting to the command type's full name) and skips the pass when another instance holds it, through the newIRecurringCommandLeasecontract.TryAcquireAsyncreturns anIRecurringCommandLeaseHandlewhoseLeaseLosttoken fires when the lease is taken or renewals fail; the loop then ends the busy period, releases the handle, and waitsErrorBackoff, cancelling the in-flight send, and logs the loss at Warning (EventId 2106).LiteBus.Commands.Recurring.Storage.PostgreSqlsupplies a renewable lease row inlitebus_recurring_leases, registered withUsePostgreSqlRecurringLease(...)and configured byPostgreSqlRecurringLeaseOptions(LeaseDuration, 30 seconds by default, andRenewInterval, a third of it by default). An explicitRenewIntervalat or aboveLeaseDurationfails validation, and a held lease is never re-taken, including by the same holder. Lease times come from the database clock, the holder renews in the background while the pass runs, a crashed holder's lease expires on its own, and no connection is held between statements, so the lease works behind a transaction-mode PgBouncer. The schema is versioned and created at host startup, with therecurring.postgresql.schemaprobe. Composition fails whenRequireLeaseis set and no lease is registered. -
OutboxEnqueueItem<TEvent>.FromAmbientandInboxAcceptItem<TMessage>.FromAmbientstamp the trace of the message being handled onto what the handler writes, throughMessageTrace.FromAmbient(). They are explicit opt-ins; nothing reads ambient trace unless they are called. -
Idempotency.FromCommandKey(suffix)keys an outbox or inbox item by the idempotency key the in-flight command was granted, so a retried command enqueues the same rows.ClaimedIdempotencyKeyis public inLiteBus.Messaging.Abstractionsso other code can read the granted key. -
LiteBus.Testing.DurableMessagingadds an in-memoryITransactionalOutbox(AddTestTransactionalOutbox) andITransactionalInbox(AddTestTransactionalInbox),ProcessorPassHelpers.DrainOutboxAsyncandDrainInboxAsync, aScriptedOutboxDispatcherthat fails chosen contracts on chosen attempts, andStoreSchemaContract.AssertCompatible, which reports every schema difference at once.TestOutboxStoreaccepts store options and aTimeProvider. -
LiteBusCompositionSummary.DuplicateStageCoveragesnames every handler type that covers one message's pre-stage, post, error, or completion entries both directly and through a base type, so a handler that will run twice shows up in the startup line. -
Command idempotency answers the cases an HTTP API needs.
IdempotencyClaimOutcomereportsInFlightandFingerprintMismatch;IdempotencyDeclaration.WithFingerprintdeclares a request fingerprint, and an applied key claimed again with a different fingerprint is refused; an unsettled claim older than the store's claim timeout is taken over, so a crashed claimant does not block its key. Both outcomes deny the command with the codes inIdempotencyRefusalCodes(idempotency.in-flight,idempotency.fingerprint-mismatch). An unrecognized claim outcome throwsPipelineContractExceptioninstead of running the handler without a recorded claim.InMemoryIdempotencyStoreimplements the same semantics with aTimeProvider. -
WithIdempotencyKey(...)inLiteBus.Extensions.AspNetCoreis an endpoint filter that keys the command an endpoint sends by theIdempotency-Keyrequest header, configured byIdempotencyKeyFilterOptions(header name, required by default, 255 characters at most, optionalTenantResolverscoping keys per tenant) and carried into the pipeline byIdempotencyKeyGuardandCommandMediationSettings.WithIdempotencyKey(HttpContext).MediationResult.ToHttpResult(...)answers an in-flight key with 409, a fingerprint mismatch with 422, other denials with 403, and invalid commands with 400. -
IUnitOfWorkandUseUnitOfWork<TUnitOfWork>()on the command and query module builders commit the application's unit of work atHandlerPriorities.UnitOfWorkonce per mediation that succeeded; a denied, invalid, shortcut-answered or faulted mediation commits nothing. The application supplies the commit; LiteBus never opens a transaction. -
LiteBus.Commands.Storage.Martenbrings the command axis to Marten:UseMartenUnitOfWork()commits the scopedIDocumentSession,UseMartenIdempotencyStore(...)keeps idempotency claims as Marten documents in their own serializable sessions, andMartenAuditTrailstages each successful audit record in the handler's session so it commits with the change, while denial and failure records are written on their own so a rolled-back session cannot lose them. -
IFaultRefusalClassifier, registered withMessageModuleBuilder.UseFaultRefusalClassifier<TClassifier>(), ends a mediation as a refusal when any stage raises a fault it recognizes, including a commit fault raised in the completion stage, soTrySendAsyncreturns it as a value and error handlers do not run.PostgreSqlConstraintRefusalClassifiermaps unique (23505) and exclusion (23P01) violations on configured constraints to denials with application codes. Cancellation is never classified, and nothing changes when no classifier is registered. -
IExecutionContext.HandledAtis the instant the mediation started, read once from the messaging module'sTimeProvider. -
Shortcut.Deny(reason, code)andShortcut<TMessageResult>.Deny(reason, code)let a shortcut deny a message when the decision can only be made at the shortcut stage, such as an idempotency claim. The mediation ends exactly as a guard denial does:TrySendAsyncreturnsDenied,SendAsyncthrowsLiteBusMessageDeniedExceptionnaming the shortcut inDeniedBy, completion handlers and the audit record observe the denial, error handlers do not run, and refusal mappers apply. -
OutboxModuleBuilder.EnablePerHandlerDelivery()writes one outbox envelope per subscribed main handler of an event, recorded on the newOutboxEnvelope.Handlercolumn, and the in-process dispatcher publishes each envelope to that handler alone, so a failing reaction retries, dead-letters and is replayed on its own while the others publish. Per-handler message ids and idempotency keys are derived deterministically so a retried enqueue resolves to the same rows. A handler added after the enqueue does not receive events already enqueued. A single enqueue persists the whole fan-out atomically in one batch call,CreateBatchAsyncfans out per handler as well, strict resubmission compares handler addressing, and the Entity Framework Core save-changes interceptor keeps staged handler addressing. Composing per-handler delivery with a transport dispatcher throws unlessAllowPerHandlerDeliveryWithTransportDispatchacknowledges the duplicate broker publication. -
OutboxModuleBuilder.StageCollectedEvents()registers a scopedIDomainEventCollectorand a completion handler atHandlerPriorities.Persistencethat enqueues the events a handler collected intoITransactionalOutboxwhen the mediation succeeded, before the unit-of-work commit. WithEnableSaveChangesInterceptor, the Entity Framework Core adapter supplies the non-genericITransactionalOutboxfrom the ambient transaction. -
OutboxModuleBuilder.UseAmbientTrace()stamps enqueued envelopes that carry no explicit trace with the trace of the message being handled. -
InboxModuleBuilder.UseAmbientTrace()stamps accepted envelopes that carry no explicit trace with the trace of the message being handled, throughMessageTrace.FromAmbient(). -
AuditedDeclaration.WithTargetFrom<TMessage>(...)andWithReasonFrom<TMessage>(...)read the audit target and reason off the message, so a definition declares them once instead of every handler supplying them; a value the handler supplies throughIAuditScopestill wins. -
DeclarationGuard<TMessage, TValue>looks a declaration up for the message's runtime type and calls oneDecideAsync(declaration, message, ...); an undeclared message is denied withdeclaration.missingunlessDecideUndeclaredAsyncis overridden, and a recorded exemption allows.AuthorizationGuard<TMessage>builds on it: an exempt message is allowed and an authorized one callsAuthorizeAsync(policy, message, ...). -
Analyzers
LB1023(a command handler sends or publishes through a mediator, nesting a second unit of work) andLB1024(a command handler injects an external side-effect type such asHttpClient, configured withlitebus.LB1024.forbidden_types) are Warnings inLiteBus.Handlers, disabled by default.LB1024inspects public constructors only. -
RetryBackoff.ScheduleandRetryOptions.Delaysstate the retry ladder directly: one delay per attempt.FixedandExponentialderive every delay fromInitialDelayunder theMaxDelaycap, which cannot express a window that starts inside a minute and still reaches days: exponential from one minute reaches roughly four hours by the ninth attempt, and stretching the tail to a week pushes the first retries hours apart, the opposite of what a receiver that blipped needs. A retry window is a customer-visible guarantee for partner-facing delivery, so it is stated rather than approximated. An attempt past the end of the ladder repeats the last entry, andMaxDelaydoes not clamp the entries, so a declared tail is never silently shortened.RetryOptions.Validate()runs when the module builds and when a processor is constructed directly, so an empty or negative ladder fails at boot rather than on the first failure. -
MessageModuleBuilder.UseSerializer<TMessageSerializer>(lifetime)andUseSerializerInstancestate the wire format of persisted messages at the composition root. The default isSystemTextJsonMessageSerializerwithJsonSerializerDefaults.Web, which is camel case, and the only other way to change it is to replace the container registration afterAddLiteBus, which no analyzer sees and no startup check reports. Forgetting it renames every property of every durable message on the wire and breaks every consumer, with nothing failing at boot. -
IdempotencyDeclaration.KeyedByContext()andSuppliedIdempotencyKeycover a key that cannot be projected from the message. A processor webhook carries a raw body and a signature and nothing else, deliberately, so that nothing unverified reaches a decision; its deduplication key is the provider's event id, knowable only after the signature is checked and the body parsed. That is a lookup, and a lookup needs services. A guard does that work and hands the key forward throughIExecutionContext.Data; the pre stage runs guards before shortcuts, and the key is read once and reused by both the shortcut that claims it and the completion handler that settles it, so verification happens once per mediation. It is deliberately not a container-resolved provider: each stage resolves the key independently, so a provider would pay the cost twice and, if not perfectly deterministic, write a different key at each stage. A message declared this way that reaches the shortcut with no key raisesIdempotencyConfigurationExceptionnaming the message type, because a generated fallback would make every delivery look distinct. -
LiteBus.Commands.Recurringsends one command on a fixed interval for the life of the host, registered throughCommandModuleBuilder.AddRecurringwith either a command factory or, for a parameterless command, timing alone. It replaces the hosted service most CQRS applications write once per background job: create a scope, resolve the mediator, send one command, sleep, back off on failure, and never let an exception escape the loop.AddRecurringregisters the command it sends, andRecurringCommandHostOptions.Validaterejects a zero or negativeIntervalorErrorBackoff, which would spin the loop without pause. The loop snapshots its validated timing values at start, so changing the options later does not affect a running loop. A result implementingIRecurringWorkReportcan report that work remains, which skips the interval and turns a large backlog into one busy period instead of one batch per interval. There is no cron expression and no missed-run catch-up, and by default the loop runs on every host instance concurrently, which suits a command that drains work by leasing rows, where the store arbitrates;RequireLeasewith a registeredIRecurringCommandLeaseruns each pass on at most one instance instead. -
LB1022warns when[HandlerPriority]falls inside the range LiteBus reserves for its own handlers. A value betweenHandlerPriorities.ReservedFloorandReservedCeilingorders the handler against the persistence and audit writers rather than against the application handlers it was meant to be ordered against, and the position can move between releases. Types implementing no handler interface are skipped. -
InProcessOutboxDispatchOptions.RequireHandler, configured throughUseInProcessDispatch(dispatch => ...), controls whether a dispatched message with no handler fails the attempt. It defaults totrue. -
CommandModuleBuilder.RegisterChildModuleis the seam feature packages compose through: a capability layered on the command axis registers insideAddCommandsrather than as a second top-level module the caller must remember to add.CommandModuleis anICompositeModule.
Changed
-
Dependencies move to their current versions, including
AWSSDK.SQS4,Microsoft.Extensions.*10.0.13 and OpenTelemetry 1.20. EF Core and Npgsql stay on 9.x becausePomelo.EntityFrameworkCore.MySqlhas no EF Core 10 provider, Roslyn stays on 4.8.0 as the compiler the shipped analyzer is built against, andSQLitePCLRawstays on 2.1.x to match the EF Core 9 SQLite provider. -
LiteBusTransportTelemetryexposes the two circuit-breaker counter names as public constants; the emitted names are unchanged. -
Transport publishers are singletons in all five adapters, so a dispatched envelope no longer opens and closes its own AMQP channel, Azure Service Bus sender link or Kafka producer flush. Consumers are transient in all five, Azure Service Bus included, because each instance holds one subscription. The Kafka producer is flushed once, when the container is disposed.
-
Saga state is compared with the JSON snapshot taken when it was loaded. Reading state and then calling
Complete()now works, a dispatch that only reads state saves nothing, and a handler that changes state in place withoutSetStateis still persisted. -
The
AfterDispatchhook runs on the persist token on both the inbox and the outbox, so a shutdown during a saga save no longer leaves an executed command or a published event to run again. With the defaultHonorShutdownTokenOnPersist = false, a hook that never returns delays shutdown instead. -
A failed persist for one lease-lost message is logged and counted as a persist failure instead of aborting the whole inbox or outbox pass and discarding the other envelopes' results.
-
Every processor and cleanup loop delay goes through the injected
TimeProvider, so tests can drive the startup delay, heartbeat interval and cleanup backoff. The first cleanup retry after a transient failure waits 5 seconds instead of a fullInterval. -
PostgreSQL inbox and outbox
AddBatchAsyncinsert in chunks of 1,000 rows inside the caller's transaction, so a batch above the 65,535 parameter limit no longer fails. Inbox and outbox requeue clearerror_type,first_failed_atanddead_lettered_at, matching the EF Core and in-memory stores. -
Event post-handlers and error handlers receive
nullas the message result instead of the task that tracked handler completion. -
Message resolution counts the interfaces of the registered type, so a message implementing several registered interfaces can resolve to a different handler than before.
-
TransportOutboxDispatcherOptions.ResolveRoutewins overOutboxEnvelope.Topic, as its documentation says, and an empty result fails the dispatch withLiteBusDispatchException. An empty tenant routing strategy result fails the same way. -
A failing diagnostics store stops the queue-depth gauge from reporting until the next successful read, instead of exporting the last good counts, and the outbox records
litebus.outbox.diagnostics.unavailablewhen no store is registered. -
PostgreSQL modules register every store and the work signal through singleton factories that resolve a container-owned
PostgreSqlDataSourceOwner<TModule>. A data source created byUseConnectionStringis now disposed with the service provider under Microsoft dependency injection, which never disposed the prebuilt instance it was registered as before; the documentation already claimed it was.UseDataSourcestill leaves ownership with the application. -
IProcessorWorkSignalextendsIAsyncDisposable, so the dedicated LISTEN connection of a PostgreSQL work signal is disposed by the container that created it.PostgreSqlWorkSignaldisposal is idempotent and no longer races a listener startup; a wait after disposal falls back to the poll interval. -
The outbox in-process dispatch failure message carries contract-registration guidance only when the cause is a missing contract or handler, instead of on every failure including concurrency conflicts and cancellations.
-
MediationExceptionFilters.IsRetryableDispatchExceptioninspects the inner exception chain, so a refusal or missing handler wrapped by a dispatcher is dead-lettered on its first attempt instead of spending the retry schedule. -
Every module builder recognizes guard, validator, shortcut, and refusal mapper contracts, completion handler contracts, and message definitions as registrable constructs, so
RegisterFromAssemblydiscovers them. -
The completion stage orders handlers by priority alone. Every other role runs handlers registered for the message type before handlers registered for a base type, but completion handlers observe an ending rather than wrapping the handler, so there is no onion for a specific handler to sit inside. The split would have put the framework's broadly registered audit writer beyond the reach of an application's priority; that order decides whether a record lands inside the transaction, which is not something registration breadth should decide.
-
The registry skips an untyped open generic shortcut for a message that declares a result. A closed registration of that pair is still a configuration error, because the author named the message; an open generic says "every message I fit" and a result-producing message is not one of them, so it is skipped the way a constraint mismatch is.
-
AsyncBroadcastMediationStrategyobserves cancellations so it can report them to the completion stage, honors a guard or shortcut decision by publishing to no handlers, and reports no result to completion handlers rather than the task that tracked its handlers. Cancellation still propagates as before. -
A decision on a stream query no longer runs post-handlers. Stopping the pipeline means the work did not happen, so the reactions to it do not fire; the caller still receives whatever stream the shortcut or the refusal mapper supplied.
-
Every dispatchable handler contract is declared in one place.
PipelineContractsholds one row per contract naming its family, its invoker, and, for a pre-stage contract, its stage and aggregation policy. Dispatch, all four descriptor builders, and the stage runner read from it, so a new pre-stage role takes one row rather than edits in nine files, and post-handlers, completion handlers, and refusal mappers are declared the same way rather than hand-wired beside the table. The run order is read from thePreStageordinals rather than from a hand-written call sequence, which makes the order the enum documents the order that executes. -
The stream mediation strategy routes every fault through one place instead of six, and enumerates the handler's stream and a post-handler's replacement through one loop instead of two. It is a third shorter. One timing changes with it: the handler's enumerator is released when its enumeration ends rather than when the whole mediation does, so it is now disposed before post-handlers run rather than after. A post-handler receives the
IAsyncEnumerableand would enumerate it afresh, so nothing observes this beyond the resource being held for less time. -
The inbox and outbox share one processor hook runner. They ran identical copies, and each built a fresh envelope adapter in all five hook phases, so a single dispatch allocated five of them per axis. The adapter is now built once per dispatch.
-
A pre stage that holds no handler is skipped without enumerating the shared descriptor collection.
IMessageDependencies.HasPreStageHandlersanswers from a mask computed once when dependencies are resolved, so a message with no guard, validator, or shortcut costs nothing for those stages. The default implementation on the interface enumerates and is correct for custom implementations, so nothing outside LiteBus has to change. -
Registering a type that carries a pipeline marker but names no message type is reported with
LiteBusConfigurationExceptioninstead of being accepted. Every marker is memberless, so such a type produced no descriptor, fell through to message-type registration, and silently never ran. -
Pre-handlers, post-handlers, and completion handlers are invoked through the closed contract recorded in their descriptor at registration, using a delegate built while the descriptor is built. The previous dispatch searched a handler's interfaces for a method by name on every invocation and called it reflectively, which is how a class implementing pipeline contracts for several message types could have the wrong method selected. Choosing the contract from registration metadata makes that class of bug structurally impossible, and building the delegate at registration keeps reflection out of the dispatch path.
-
Two definitions declaring the same value type for one message, or two declarations covering one message where neither is more derived than the other, are reported at registration instead of being resolved by assembly scanning order.
-
LiteBusConfigurationExceptiongains derived types so a composition failure can be caught by category:ModuleCompositionException,MessageDeclarationException,PipelineContractException,DurableStorageConfigurationExceptionandAuditConfigurationException. It was the one type for every composition failure, so nothing could be caught selectively. The base is no longer sealed and stays catchable as the category; every throw site in the library now uses a derived type. -
The command, query and event module builders accept a pipeline handler written against the messaging-level contract when its message type is, or is constrained to be, assignable to that axis. Without it, a cross-cutting guard would be written once per axis, so a fix to authorization would have to land in every copy. A handler constrained to neither axis is still refused, because nothing says which axis it is for and accepting it would silently close it over every message in whichever axis happened to register it. Main handler contracts are excluded: a command handler and a query handler mean different things.
-
IExecutionContextis registered as a scoped dependency, so a handler declares it as a constructor parameter and the dependency appears in the type signature. Every documented way of reading mediation state went through theAsyncLocalstatic, which hides a dependency and forces an ambient scope in a unit test.AmbientExecutionContextremains the way to reach the context from code that runs outside dependency injection. -
IAuditOutcomeMapper.MapFailureCodereturns the refusal's ownCodefor aDeniedorInvalidoutcome before falling back to the exception type name. A guard that supplied a code chose it deliberately and it survives either shape of refusal, where an exception-derived code is present when a refusal raises and absent when a mapper returns a value instead. A shortcut's code is deliberately excluded, because an answered mediation reportsSucceededand its code would otherwise land in the field a review reads as the reason something did not work. -
Outbox in-process dispatch requires a handler by default.
EventMediationSettings.ThrowIfNoHandlerFounddefaults tofalse, and the v6 dispatcher published with it as-is, so an event with no registered handler was leased, dispatched and markedPublishedwithout ever leaving the process. If the assembly holding the handlers is not scanned byAddEvents, that is total data loss with no exception, no dead letter, and a backlog reading of zero. A silent no-op is a defensible default for an immediate publish, where the caller can see there are no subscribers; a durable dispatch has no such caller, and the outbox promise is that a committed message reached somewhere. The inbox axis cannot fail this way, because command mediation requires exactly one handler. SetRequireHandler = falseto allow publishing to zero handlers where that is deliberate. -
The operational columns are written and readable.
last_attempted_at,first_failed_at,dead_lettered_at,last_lease_owneranderror_typewere created by the DDL, validated by the schema check at boot, and mapped by the EF Core model, and four of the five were written by nothing and read by nothing, so an operator dashboard querying them read nulls. They are now onInboxEnvelopeandOutboxEnvelope, written by every store adapter on every terminal transition, and returned byIInboxManager.QueryAsyncandIOutboxManager.QueryAsync, so a dead-letter listing no longer needs a second statement against the library's own table.FirstFailedAtis set once and is not moved by later failures, so it keeps answering how long a message struggled;AsRequeuedclears the failure record and resets the attempt count. -
TestQueryMediator.NextResultis consumed once per query, stream, or tried query, andStreamAsyncthrowsInvalidCastExceptionon a stub type mismatch instead of yielding an empty stream.
Fixed
-
The management message query endpoints (
GET .../inbox/messagesandGET .../outbox/messages) treatpageSizeas optional and default it to 50 (InboxMessageQueryBinding.DefaultPageSize,OutboxMessageQueryBinding.DefaultPageSize); a request without it was rejected with an empty 400 response. -
A lease renewal that throws now cancels the running dispatch and reports the lease lost, instead of surfacing only after the handler finished; the lease store receives a cancellable token linked to the heartbeat.
-
Mediation restores the caller ambient execution context before it returns a task or stream, and creates the dispatch scope only when a handler resolves a service, so a stream that is never enumerated holds no container scope.
-
A command implementing
ICommand<TCommandResult>sent through the non-genericSendAsync(ICommand)orTrySendAsync(ICommand)runs the result-bearing pipeline, so post-, error- and completion handlers receive the result instead ofnull(#128). -
SQS sends invalid UTF-8 and characters SQS rejects as base64 so the payload round-trips byte for byte, caller headers can no longer replace mapper-owned attributes, and headers past the ten-attribute limit are packed into
litebus-headersand expanded on receive. -
Parallel
ContinueAndAggregateevent handling rethrowsOperationCanceledExceptionwhen every handler was cancelled, instead of reporting a failure and running error handlers. -
NoHandlerFoundExceptionandMultipleHandlerFoundExceptionname the runtime message type when the call erased it toICommand,IQueryorIEvent. -
A completed saga dispatches a new correlated message with an inactive saga scope instead of suppressing it; only a redelivery of the last applied message is suppressed.
Complete()on a saga that was never saved creates the row already completed instead of dead-lettering a successful handler. -
A handler-internal
OperationCanceledException, such as a dependency timeout, follows the normal failure path withMaxAttemptsandIsPermanentFailure, instead of being recorded as lease loss and retried indefinitely. -
Inbox transport dispatch throws
InboxDispatchExceptionnaming the message when the route resolver returns an empty route, matching the outbox dispatcher. -
Strict replay of an identical unscoped message returns
AlreadyAcceptedorAlreadyEnqueuedon every store instead of throwingIdempotencyConflictException, because stored and requested tenants compare normalized. -
The in-memory stores reject a non-terminal envelope passed to
PersistAsync, like the relational stores. -
EF Core batch acceptance re-inserts rows still missing after a concurrent unique violation and rethrows other database errors with the original exception, instead of reporting invented
AlreadyAcceptedoutcomes. -
The EF Core save-changes interceptors fail the save when two strict-idempotency envelopes share a message id, instead of keeping one and reporting both as accepted.
-
EF Core lease SQL escapes schema and table identifiers for each provider.
-
An AMQP mandatory publication the broker returns as unroutable fails with
AmqpMessageReturnedExceptionand releases its circuit-breaker permit, so a routing mistake no longer counts as broker failure and opens the circuit. -
A cancelled AMQP connection probe releases its circuit-breaker permit instead of leaving the circuit half-open until restart.
-
Cancelled inbox ingress acceptance rethrows before settling the delivery, so stopping a Kafka host no longer commits an offset for a message that was never stored.
-
The durable test host honours its
timeProviderargument in the messaging and in-memory storage modules. -
The management drain endpoints enforce the options passed to
AddLiteBusManagementEndpoints, like the other management endpoints. -
Analyzers: LB1007 and LB1017 no longer count event or query module registration as durable contract registration and accept contract scans through
Assembly.GetExecutingAssembly()and locals; LB1003 reportsITransactionalInbox,ITransactionalOutboxandITransactionalOutbox<TContext>, ignores ordinary method parameters, and reports inherited properties like inherited fields; LB1011 recognises target-typednew() { Tags = ... }; LB1015 checks the interceptor call on the same axis; LB1013 and LB1016 require the Entity Framework CoreDbContext. -
LiteBus.Analyzersno longer scans the whole project each time an editor analyzes one file. Visual Studio and language servers analyze an open file on a fresh copy of the compilation and rerun compilation-start and compilation actions each time, so the handler, contract, tag and declaration rules walked every syntax tree per keystroke: 20 to 40 seconds per analyzer on a 3,400-file project. These rules now gather facts from symbol and syntax-node actions and report at compilation end. LB1001, LB1007 through LB1012, LB1017, LB1018, LB1020 and LB1021 report the same diagnostics on build, and no longer appear as live squiggles; see Build-Only Rules. -
The Azure Service Bus publisher no longer throws
ArgumentNullExceptionfor aTransportPublishRequestwithout aMessageId; the identifier is optional on the request and is now copied only when supplied. -
MessageRegistry.Handlersreturns a snapshot taken under the registry lock instead of a live view a concurrent registration could tear. -
Assembly scans skip types that fail to load instead of aborting the registration, in all six scans.
-
Streams honour the token passed to
WithCancellationorGetAsyncEnumerator, not only the one passed toStreamAsync. -
MessageMediator.Mediateand the public pipeline extension methods throwArgumentNullExceptionnaming the argument instead ofNullReferenceException. -
One hook's
AbandonDispatchScopefailure no longer skips the other hooks or leaks the saga correlation gate, and an empty message id no longer throws from the abandon path. -
A saga save without an applied message id keeps the existing duplicate-dispatch marker instead of erasing it.
-
The PostgreSQL
LISTENchannel name is quoted. -
A diagnostic probe whose
Namediffers from its registration reports the mismatch instead of a generic failure. -
GetHostedServiceForBackgroundService<T>()works before the host has started. -
BackgroundServiceHostWrapper.StopAsynccompletes when the loop ended through the cancellation it requested, instead of reporting a failed stop, andMicrosoftMessageDispatchScope.Disposeno longer blocks on asynchronous disposal. -
LiteBusDependencyResolutionExceptionthrowsArgumentNullExceptionfor a null argument instead ofNullReferenceException. -
A failed AMQP consumer start releases its channel and can be retried; previously the consumer stayed unusable and
WaitUntilStoppedAsyncnever completed. -
The in-memory consumer's
StopAsyncandWaitUntilStoppedAsynccomplete after the destination channel is closed instead of throwingChannelClosedException, which ended the ingress loop. -
A cancelled ingress acceptance is left unacknowledged for the broker to redeliver instead of being requeued with the cancelled token.
-
The outbox and inbox retention purge routes report a missing retention policy through the management safety response instead of an HTTP 500.
-
A dispatch cancelled by host shutdown, a drain or a lease loss was recorded as a failure:
EventOutboxDispatcherwrapped theOperationCanceledExceptioninLiteBusDispatchException, so the envelope handler charged it to the retry budget, logged it at Error, pushed the message's visibility out by the backoff, and eventually dead-lettered messages that had never failed. The dispatcher now rethrows the caller's cancellation and both envelope handlers treat it as no outcome. -
Disposing a transport consumer twice threw
ObjectDisposedException(Kafka, in-memory, SQS, Azure Service Bus, AMQP consumers andAmqpConnectionManager).AzureServiceBusPublisher.Disposeblocked without a bound and let close errors escape; it now waits at most five seconds. -
KafkaConsumer.StartAsyncstarts the consume loop on the thread pool and returns. The ConfluentConsumecall blocks, so the loop ran inline andStartAsyncdid not return until the first record arrived; the ingress host hid this by starting consumers from a background loop. Behaviour after startup is unchanged. -
BackgroundServiceHostWrapperleaked its stopping token source and abandoned a loop that ignored shutdown without a trace; it disposes the source and logs EventId 6001 naming the service. -
The inbox and outbox cleanup loops threw
OperationCanceledExceptionout ofExecuteAsyncwhen the host stopped during their error backoff. -
TransportInboxIngressConsumercould recreate its admission semaphore after disposal and release a disposed one. -
Handler discovery in the analyzers recognizes the two-parameter post-handler contracts and the stream query post-handler contract. A handler implementing only those was invisible to LB1011 and LB1012, so an unused
[HandlerTag]on one was not reported. -
LB1007andLB1017match contract registration by receiver:IContractWriter,IMessageContractRegistry,MessageContractBuilderandMessageModuleBuilder.RegisterFromAssemblycount, as doRegisterextensions on those surfaces, so aRegistercall on another builder no longer silences them.LB1004coversITransactionalInbox<TContext>and untypedInboxAcceptItemacceptance, resolving untyped items throughMessageType = typeof(X)when present and matching arguments to parameters by name;LB1011resolvesconsttag names and maps arguments to parameters;LB1003walks base classes and names every API family it flags. -
One open generic pipeline handler runs once per message whatever the registration order. A handler such as
Guard<T> where T : ICommandwas also closed overICommandonce any handler named that interface, and that closure applied to commands registered after it but not before, so the guard ran twice for some commands and once for others. When two closures of one generic handler definition reach a message through the same contract, only the direct one is kept. A different handler type over a base type still runs indirectly. A new closure links to all committed messages, so indirect coverage no longer depends on registration order. -
A main handler reached through an erased message type, such as an event published as
IEvent, receives the mediation's cancellation token rather than reading the ambient one, and is called through the contract recorded at its registration. -
Inbox and outbox payload protectors forward contextual encryption when the configured encryptor implements
IContextualPayloadEncryptor, binding message id, contract, tenant, and axis as authenticated metadata.PayloadProtectionContext.TenantIdnormalizes empty and whitespace values to null, so unscoped messages authenticate identically on encrypt and decrypt. -
Health check report data includes each probe name in the per-probe entries.
-
The
Test*mediator doubles are thread-safe and return snapshot recordings instead of the live lists. -
TestMessageTransportdelivers a scriptedNextPublishExceptionto exactly one concurrent publish. -
ManualTimeProvideris thread-safe for concurrent advance and read. -
Ingress discards malformed payloads instead of requeueing them forever: serialization failures are excluded from requeue and the inner exception chain is inspected.
-
Batch ingress reports invalid headers as
InboxIngressException, matching single accept, and the batch fallback aborts on shutdown cancellation instead of attempting cancelled deliveries. -
EnableBatchAcceptwithBatchMaxWaitof zero fails validation instead of stalling partial batches. -
A zero ingress
RetryPollIntervalwaits one second between consumer restarts instead of retrying immediately. -
Non-GUID broker delivery ids derive destination-scoped inbox identity, so the same delivery id on two destinations no longer collides.
-
Saga module build fails when a
MapContractdefinition has no registered state type, instead of failing when the contract dispatches. -
Inbox completion timestamps come from the processor clock instead of wall-clock time.
-
Accepting or enqueuing a message id that already exists for another tenant throws
IdempotencyConflictExceptioninstead of returning the foreign row, on every inbox and outbox store: PostgreSQL, Entity Framework Core and in-memory. -
Outbox enqueue with a non-JSON distributed trace context throws
ArgumentExceptionat creation on every provider, instead of failing at insert or persisting a poison row. -
POCO outbox dispatch no longer wraps failures in
TargetInvocationException, restoring registration guidance forNoHandlerFoundException. -
A
PostgreSqlOutboxStorebound withUseExistingConnectionreports the configured schema inGetSchemaInfoAsyncinstead of the defaults. -
The Entity Framework Core save-changes interceptors persist the staged envelope lease generation and error type instead of dropping them.
-
Entity Framework Core outbox lease SQL returns the
idempotency_keycolumn on PostgreSQL, SQL Server, and MySQL, so leased envelopes carry the stored key like every other store. -
Entity Framework Core inbox and outbox stores mark
lease_generationas a concurrency token, so a SQLite or in-memory tracked renew, release, or terminal persist that lost a lease race reports the loss instead of overwriting the new holder. Tracked terminal persist saves one row at a time, so one lost race skips only that row. -
Entity Framework Core inbox and outbox single-add strict checks apply to rows staged on the same context, so a differing staged duplicate throws
IdempotencyConflictExceptionlike the batch and persisted paths. -
AmqpConsumerdrives deliveries with a subscription-owned token, so cancelling or disposing theStartAsynctoken after startup no longer stalls the subscription;StopAsynccancels in-flight deliveries and ends the subscription. -
AmqpConsumersettles each delivery at most once: a repeat acknowledgement is ignored and the failure-path requeue is skipped when the handler already settled, so a settle-then-throw no longer closes the channel. -
InMemoryConsumerreturns a delivery to the destination withRedelivered = truewhen its handler returns without settling, instead of dropping it silently. -
A transient Kafka consume error backs off one second and resumes polling instead of faulting the loop; only a fatal client error stops consumption and surfaces through
WaitUntilStoppedAsync. -
A Kafka requeue seek that fails transiently retries with the seek backoff schedule until it succeeds or shutdown cancels it, instead of killing the consume loop.
-
The SQS requeue backoff treats a message without system attributes as a first delivery instead of throwing
NullReferenceExceptionand faulting the consume loop. -
IExecutionContext.Itemsand audit scope state are safe for concurrent use by parallel event handlers; parallel audit writes share one scope state and racing writes to one key leave whichever landed last. -
Disposing the PostgreSQL work signal completes even when the listener loop faulted during shutdown, instead of skipping listener-connection cleanup.
-
LB1008andLB1009scope their message candidates to the analyzed assembly: a message from a referenced assembly is never reported, while handlers from referenced assemblies still satisfy coverage.LB1007likewise reports only handlers declared in the analyzed assembly, and only registrations invoked in the analyzed compilation satisfy it andLB1017. -
LB1017andLB1011report a partial type once at its first declaration instead of once per declaration.
Breaking
-
Tenant filters and lease requests mean the same on every store:
nullapplies no tenant restriction and an empty string matches unscoped rows only. The EF Core and in-memory stores previously treated an empty string as no restriction. The PostgreSQL outbox lease, query, and purge paths treat a blank filter as unscoped, matching the inbox store. -
IOutboxDiagnosticsStoreandIOutboxManagergainGetFailureSummaryAsync; a custom outbox store implements it. -
A second
AddLiteBuson one service collection or container builder throwsModuleCompositionException; each container hosts one LiteBus composition. -
A second transport module in one composition throws
ModuleCompositionExceptionnaming both modules. Both modules register the singleITransportPublisherbinding, so two transports in one composition could not work before either. -
Registering a service type both as a single binding and as collection items throws
ModuleCompositionException; the single-binding and collection views used to disagree silently. -
RegisterStartupTaskthrowsArgumentExceptionfor a type that implementsIBackgroundService, mirroring the existing rejection inRegisterBackgroundService. -
ProcessorOptions.HookFailurePolicyisProcessorHookFailurePolicy?.null, the default, means the dispatcher's recommendation, otherwiseDeadLetter. AUseProcessorOptionscall that sets only a batch size no longer replaces the transport dispatchers'CompleteDespiteHookFailurewithDeadLetter; set the policy explicitly to keep that. -
IProcessorEnvelopeandIProcessorEnvelopeHookmoved fromLiteBus.DurableMessaging.Abstractions.ProcessingtoLiteBus.Messaging.Abstractions.Processing. -
IOutboxManager.RunRetentionPurgeAsyncthrowsOutboxManagementExceptionwhenOutboxCleanupHostOptions.Retentionis not a positive period, instead of returning 0. -
A saga purge with no predicate and no
TakethrowsArgumentException. -
The AMQP ingress broker-scoped idempotency key is scoped to the queue (
ingress:{queue}:{id}) instead of the exchange, so two queues bound to one exchange no longer share a key. Ingress reads identity and idempotency from thelitebus-message-idheader only whenTrustApplicationHeadersis set. A redelivery that arrives while an AMQP ingress host is being redeployed can be accepted twice. -
Kafka and SQS route and content-type metadata use the shared names
litebus-routeandcontent-typeinstead ofRouteandContentType. A consumer reading the old names has to read both during a rollout. -
TransportPublishRequest.Mandatorydefaults totrue, matchingAmqpPublishRequestand the outbox dispatcher; a directITransportPublishercaller relying onfalsehas to set it. -
The Kafka transport no longer registers the bare
IProducer<string, byte[]>; resolveITransportPublisher.MessageTimeoutMsno longer also sets the socket timeout and disables send retries. -
LiteBus.Messaging.Extensions.ServiceProviderExtensions.GetRequiredServiceis obsolete; use the one inLiteBus.Runtime.Abstractions.Extensions. -
IProcessorWorkSignalnow extendsIAsyncDisposable. A custom work signal must implementDisposeAsync, and should also implementIDisposablewhen the container may be disposed synchronously. -
IExecutionContext.AbortandLiteBusExecutionAbortedExceptionare removed. A pre-handler that stopped the pipeline now implements a guard contract and returns aVerdict, or a shortcut contract and returns aShortcut. The break is a compile error rather than a change in behavior, which is deliberate: a flag that leftAbort()compiling would have silently started running the statements after it. -
ICommandValidator<TCommand>andIQueryValidator<TQuery>returnTask<Validity>fromValidateAsyncinstead ofTask, and derive fromIMessageValidator<TMessage>rather than from the pre-handler contract. A validator that reported a failure by throwing now returnsValidity.Invalid(...)instead. The break is a compile error rather than a change in behavior, for the same reason theAbort()removal is: a validator left compiling would have gone on reporting malformed input as a fault. An adapter over an external validation library changes one line, returning the failures instead of raising. A codebase with too many validators to convert in one commit derives them fromThrowingCommandValidatororThrowingQueryValidatorto land the build first and convert module by module. -
IExecutionContextgainedData. It is an infrastructure contract implemented by LiteBus itself; applications that only implement handlers are unaffected, and a custom implementation or test double returnsnew HandleContextData()fromData. -
IModuleConfigurationgainedCompositionValidationsandRegisterCompositionValidation. A custom host adapter must run the collected validations after its module loop, or a rule spanning several modules never executes. -
The non-generic pre-stage marker is renamed
IMessagePreStageHandler. It is the discovery marker for the whole pre stage, which now holds four roles, so it can no longer share a name withIMessagePreHandler<TMessage>, the one role in that stage LiteBus does not name. The post and completion stages hold a single role each and keep the shared name. -
IAsyncMessageErrorHandler<TMessage>andIAsyncMessageErrorHandler<TMessage, TMessageResult>are renamedIMessageErrorHandler<TMessage>andIMessageErrorHandler<TMessage, TMessageResult>. The prefix named nothing there: no synchronous error handler exists, and the contract derives straight from theIMessageErrorHandlermarker. Every stage now follows one rule, that a marker shares its name with its role when the stage holds a single role. The main handler keepsIAsyncMessageHandler, where the prefix does name something: it is theTask-returning specialization ofIMessageHandler<TMessage, TMessageResult>, alongsideIStreamMessageHandlerfor theIAsyncEnumerableone. -
IMessageDescriptorandIMessageDependenciesgainedRefusalMappersandIndirectRefusalMappers. Custom implementations, including test doubles, must add them.IMessageDependencies.HasPreStageHandlersships with a default implementation, so it needs no change unless a custom implementation wants the faster answer. -
A refusal or a missing handler now dead-letters on its first attempt in the inbox and outbox processors instead of consuming the retry schedule. Both fail identically on every attempt, so retrying only delayed the dead-letter entry an operator was waiting to see.
-
Only a guard or a shortcut can stop the pipeline. Stopping means skipping the work, and once the main handler has run there is nothing left to skip. A handler that previously aborted from a later stage calls
SuppressPostHandlers(). -
The synchronous handler layer is removed, and the asynchronous one takes over its names. In v6.0.2
IMessagePreHandler<TMessage>declaredobject PreHandle(TMessage)andIMessagePostHandler<TMessage, TMessageResult>declaredobject PostHandle(TMessage, TMessageResult?), withIAsyncMessagePreHandler<TMessage>,IAsyncMessagePostHandler<TMessage>, andIAsyncMessagePostHandler<TMessage, TMessageResult>holding theTaskmembers beside them. Every handler is asynchronous now, so theIAsyncnames are gone and the members they declared live onIMessagePreHandler<TMessage>andIMessagePostHandler<TMessage, TMessageResult>. A handler that implemented anIAsynccontract changes the interface name only; a handler that implemented a synchronous one becomes asynchronous. The axis contracts such asICommandPreHandler<TCommand>andIQueryPostHandler<TQuery, TResult>are unchanged at the call site and now derive from those directly. -
IExecutionContextgainedPostHandlersSuppressedandSuppressPostHandlers(). Custom implementations, including test doubles, must add them. -
IMessageDescriptor,IMessageDependencies, and the handler descriptor interfaces gained members for the completion stage, message metadata, the recorded contract, and the prebuilt dispatch. Custom implementations of these interfaces must add them. They are infrastructure contracts implemented by LiteBus itself; applications that only implement handlers are unaffected. -
MessageContextExtensionsmoves out of theLiteBus.Messaging.Abstractionspackage and namespace intoLiteBus.Messaging, taking the stage runners with it. They open ambient scopes, order the stages, preserve stack traces, and decide what a denied caller receives, which is engine work rather than contract. Only a custom mediation strategy names the type, and every package implementing one already referencesLiteBus.Messaging, so the fix is a using directive. -
IPreHandlerDescriptorisIPreStageHandlerDescriptor, and thePreHandlersandIndirectPreHandlerscollections onIMessageDescriptorandIMessageDependenciesarePreStageHandlersandIndirectPreStageHandlers. One collection holds all four roles, soILazyHandlerCollection<IMessagePreStageHandler, IPreHandlerDescriptor>contradicted itself on a single line. -
IMessageHandlerhas no members.object Handle(object message)and its default implementation onIMessageHandler<TMessage, TMessageResult>are removed, which is what lets one class implement several closed handler contracts such asIEventHandler<OrderRefundSucceeded>andIEventHandler<OrderRefundSettledOutsideProcessor>; those classes failed with CS8705 before. The mediator calls each handler through the closed contract on its descriptor. Delete any hand-writtenobject IMessageHandler.Handle(object)implementation; code that calledHandle(object)calls the typed contract instead. -
IExecutionContextgainsHandledAt. Only an application that implements the interface itself is affected. -
The outbox table gains a nullable
handlercolumn for per-handler delivery. The PostgreSQL outbox schema is version 2 and an existing version 1 table is upgraded on startup when schema initialization is enabled; the Entity Framework Core outbox mapping includes the column, so an application that owns its EF Core migrations adds one. -
ParallelFaultModeis nowHandlerFaultMode,AggregateAllis nowContinueAndAggregate, andEventExecutionSettings.ParallelFaultModeis nowFaultMode. The old name described a mechanism; the setting is a policy: whether a failing handler suppresses its siblings. It now applies to sequential execution as well. Under sequential broadcast the first handler that threw stopped every handler behind it, and the only escape was turning on parallel execution, which forces thread-safety onto handlers sharing a resource such as an ORM session. Fault isolation no longer costs a move toParallel. The mode governs handlers inside one priority group and never carries across groups, because a priority difference states that the later group runs after the earlier one. -
AsFailedandAsDeadLetteredon both envelopes take aMessageFailureinstead of a string. The three parts of a failure answer three different questions: the formatted text is what a person reads, the exception type is what a dashboard groups by, and the timestamp is what fillsfirst_failed_atanddead_lettered_at. Storing only the formatted string forced every consumer to parse it back apart. UseMessageFailure.From(exception, occurredAt), orMessageFailure.FromError(text, occurredAt)for a failure with a reason but no exception. -
CommandModuleBuilderno longer takes anIMessageRegistryand anIContractWriter, and queues registrations instead of writing them straight through.CommandModuleis anICompositeModule, so its configuration action runs duringDeclareChildren, before the live registry exists. Applications are unaffected; code that constructs the builder directly is not. -
ICommandMediatorandIQueryMediatorgained members without default implementations (TrySendAsync,TryQueryAsync,EvaluateAsync), so a hand-written implementation of either, such as a test double, has to implement them. -
Payloads written by v6 under an
IContextualPayloadEncryptorwere encrypted without the context, so v7 cannot decrypt them: drain the inbox and outbox before upgrading. -
The Kafka transport registers
IConsumer<string, byte[]>as transient instead of singleton, andKafkaConsumerowns its injected client: it closes the client onStopAsyncand disposes it onDisposeAsync. Code that shares one client across consumers or disposes it externally must stop doing so. -
Kafka and SQS
StopAsynccomplete without throwing when the consume loop faulted; awaitWaitUntilStoppedAsyncto observe the terminal failure. -
The SQS consumer deletes wire poison (an undecodable body or malformed packed headers) and continues with the next delivery instead of faulting the loop on every delivery and every restart, so poison no longer reaches the queue dead-letter queue through redrive.
-
A second
AmqpConsumer.StartAsyncthrowsInvalidOperationException, matchingIMessageConsumerand the other transports; it previously threwAmqpTransportConfigurationException. -
Diagnostic probe names must be unique across probe types: registering two different probe types under one name fails composition with
ModuleCompositionException. -
Management message-query endpoints reject
messageIdsidentifier sets larger thanMaxBulkMessageIdswith HTTP 400, matching purge and requeue. -
Inbox message queries reject
PageSizeabove 1000 (InboxMessagePageRequest.MaxPageSize) withArgumentOutOfRangeException, inIInboxManagerand in every inbox store. -
Ingress ignores
litebus-visible-afterandlitebus-visible-after-delayunlessTrustApplicationHeadersis set; accepted messages are immediately visible, while correlation headers are still always honored.
Documentation
- The site renders Mermaid diagrams as SVG at build time with Ondine, publishes this changelog as a page, uses one navigation built from the page tree, and names every page the same way in the navigation, breadcrumb and tab title.
- Drain is documented as completing in-flight dispatches; only shutdown releases leases without spending an attempt.
- The metric catalog lists every public instrument, the package table follows the generated inventory and includes the four broker adapters that were missing, and
Test-DocumentationSemantics.ps1checks the catalog, the package table and both axes' management routes against the source. MaxInFlightMessagesis documented with the bound each adapter enforces: 1 for AMQP, Kafka, SQS and in-memory, the configured value for Azure Service Bus.ProcessorOptions.LeaseOwneris documented as a prefix; the processor appends a session suffix that fences instances sharing a configured owner. The inbox lease requests document that stores with a database clock use it and treatNowas the fallback.- The saga pages state that duplicate-dispatch suppression covers the most recently applied message, describe the redelivery case it does not cover, and fix an example that called
SetStateandComplete()in one dispatch. - Corrected namespace attributions for
ILiteBusBuilderand the processor hook contract, a diagnostic probe sample that threw at runtime, shipped idempotency listed as roadmap work, the Marten ambient-transaction snippet, absolute links that pointed at v6 documentation, and the analyzer range, LB1001-LB1024 with LB1002 and LB1006 reserved and never shipped. - Mediation Layer Design Rules states the rules the mediation layer follows: the stage model and the capability rule, contract and arity shapes, the vocabulary grid, what a decision type may express, where each class of configuration error is rejected, and checklists for adding a pre-stage role or an axis. Known deviations are listed rather than omitted, so they read as decisions rather than as precedents. The layer had a system; it had never been written down, which left every name looking arbitrary.
- The documentation site is rebuilt in an editor-style design: one stylesheet, dark by default with an opt-in light theme that the site remembers, C# code coloured by semantic role (interface, class, struct, method, parameter), a three-step editor on the home page, and an explorer, outline and status bar on documentation pages, with a slide-in navigation drawer on narrow screens. The site serves one documentation set, built from the branch it is deployed from, at
/docs. The version switcher, the v6 snapshot,site/versions.jsonand the/v7/docsprefix are removed, and/v7/links redirect to the same page under/docs. The release the pages describe is shown in the navigation and the status bar. - The documentation is reorganized and checked against the code. Operations material (the management endpoints, the route inventory, poison-message handling, retention and encryption rotation) moves out of the architecture overview into the operations pages, the contributor catalog sits under its own heading after the reader path, duplicate pages are merged (MediatR comparison, module registry, processor hooks, domain events), and every folder has an explicit order. Wrong defaults, signatures and samples are corrected, among them
EnsureSchemaCreationOnStartup(true), the arity-2 open generic rule, the multiple-handler behaviour of commands and queries, and validators that threw instead of returningValidity. New pages cover an end-to-end sample, a durable walkthrough and the in-memory transport; refusal as a value, retention and cleanup, processor and retry defaults, batch writers, broker options and the testing packages are documented. Moved pages redirect to their new address. - The pipeline vocabulary is one word per concept, listed in Pipeline Vocabulary and enforced across type names, XML comments, and the documentation. "Refusal" is the category holding a denial and a validation failure, "denial" is what a guard does, and "answered" is what a shortcut does.
- New pages: Authorization Declarations, PostgreSQL Idempotency Store, Paged Fan-Out, ASP.NET Core Idempotency Key, Marten Unit of Work, Idempotency, and Audit, Recurring Commands, and Outbox Marten Storage. New sections cover guard discovery and ordering, one handler for several events, enforcing audit declarations, running recurring commands on several replicas, after-commit notifications through the outbox, declaring effects with application metadata, testing the outbox without a database, the unit of work, per-handler outbox delivery, domain event staging, turning faults into refusals, guarding on a declaration, PostgreSQL schema upgrades, and fanning out from a recurring pass.
- Documented that neutral
TransportConsumerOptions.PrefetchCountdefaults to0, which maps to the unlimited native prefetch window on AMQP, with guidance to set an explicit bound for large backlogs; and correctedIMessageConsumer.StartAsyncto state that the returned task completes when the consume loop is initiated, with startup failures surfacing throughWaitUntilStoppedAsync.