Table of Contents

Class InMemoryOutboxStore

Namespace
Excalibur.Outbox.InMemory
Assembly
Excalibur.Outbox.InMemory.dll

In-memory implementation of IOutboxStore for testing and development.

public sealed class InMemoryOutboxStore : IOutboxPayloadTransformStore, IClaimScopedOutboxStore, IClaimScopedDeadLetterableOutboxStore, IFencedOutboxStore, IOutboxStore, IServiceProvider, IFencedClaimScopedOutboxStore, IFencedDeadLetterableOutboxStore, IFencedOutboxStoreDiagnostics, IOutboxStoreAdmin, IDeadLetterableOutboxStore, IBackoffSchedulableOutboxStore, ITenantPartitionedStore, IAsyncDisposable, IDisposable
Inheritance
InMemoryOutboxStore
Implements
Inherited Members

Remarks

This implementation provides thread-safe message storage using ConcurrentDictionary. Messages are keyed by their unique message ID.

This store is intended for testing scenarios only. Data is lost on application restart.

Tenant-partitioned, not tenant-scoped. The constructor takes no ITenantContext -- every message carries its own TenantId, canonicalised on StageMessageAsync and handed back unchanged on drain, exactly as the persisting providers do. ITenantPartitionedStore declares that mechanism explicitly so AddTenantAwareStore can attest it: a constructor with no ITenantContext parameter is not, by itself, evidence of row-partitioning, so the marker interface states the claim this store's own behaviour otherwise leaves silent.

Methods

CleanupAllTenantsSentMessagesAsync(DateTimeOffset, int, CancellationToken)

Removes sent messages older than the specified age across every tenant.

public ValueTask<int> CleanupAllTenantsSentMessagesAsync(DateTimeOffset olderThan, int batchSize, CancellationToken cancellationToken)

Parameters

olderThan DateTimeOffset

Remove messages sent before this timestamp.

batchSize int

Maximum number of messages to remove in one operation.

cancellationToken CancellationToken

Token to monitor for cancellation requests.

Returns

ValueTask<int>

The number of messages removed, across all tenants.

Remarks

This is an estate-wide retention sweep and is deliberately unscoped: it matches rows by age, not by tenant, so it removes the qualifying messages of every tenant in the store. The name declares that scope so it cannot be reached by a caller who meant a single tenant.

An outbox store reads no ambient tenant context, so it cannot honor a tenant it never sees. Should tenant-scoped retention ever be required, it arrives as an explicit parameter — never by inferring a scope from ambient state.

Dispose()

Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.

public void Dispose()

DisposeAsync()

Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources asynchronously.

public ValueTask DisposeAsync()

Returns

ValueTask

A task that represents the asynchronous dispose operation.

EnqueueAsync(IDispatchMessage, IMessageContext, CancellationToken)

Enqueues a message in the outbox for later delivery with context.

[RequiresUnreferencedCode("Outbox stores serialize the message payload reflectively; supply JsonSerializerOptions with a source-generated resolver for trimming and AOT.")]
[RequiresDynamicCode("Outbox stores serialize the message payload reflectively; supply JsonSerializerOptions with a source-generated resolver for trimming and AOT.")]
public ValueTask EnqueueAsync(IDispatchMessage message, IMessageContext context, CancellationToken cancellationToken)

Parameters

message IDispatchMessage

The message to enqueue.

context IMessageContext

The message context.

cancellationToken CancellationToken

Token to monitor for cancellation requests.

Returns

ValueTask

A task representing the asynchronous enqueue operation.

Remarks

Postcondition on what is staged. The staged message's headers contain exactly the values marked on context with SetPropagatedItem(IMessageContext, string, string), plus whatever envelope keys this store supplies as its own framing. No other context state reaches them — in particular not Items, which is request-local.

This is stated here, on the interface, because it is the specification and not an implementation detail: while it lived only in the implementations, one store staged the whole Items collection, two staged their envelope keys and nothing else, and six staged neither — all three behaviours legal, none a subtyping violation, and a consumer unable to predict which they would get. Staging MORE than this is now as wrong as staging less, and a conformance derivation can check both directions.

Build the staged message with FromContext(string, byte[], string, IMessageContext, IDictionary<string, object>?), which satisfies the postcondition by construction. A store that assembles an OutboundMessage by hand is responsible for satisfying it itself.

Exceptions

ArgumentNullException

Thrown when message or context is null.

GetAllTenantsFailedMessagesAsync(int, DateTimeOffset?, int, CancellationToken)

Retrieves failed messages that are eligible for retry, across every tenant.

public ValueTask<IEnumerable<OutboundMessage>> GetAllTenantsFailedMessagesAsync(int maxRetries, DateTimeOffset? olderThan, int batchSize, CancellationToken cancellationToken)

Parameters

maxRetries int

Maximum number of retry attempts to consider.

olderThan DateTimeOffset?

Only return messages that failed before this timestamp.

batchSize int

Maximum number of messages to retrieve.

cancellationToken CancellationToken

Token to monitor for cancellation requests.

Returns

ValueTask<IEnumerable<OutboundMessage>>

Collection of failed messages eligible for retry, across all tenants.

Remarks

Observation only — the result MUST NOT be handed to a transport. This is a plain read: it matches rows without conditionally taking them, so two callers observe the same message and neither holds it. Publishing from this set is check-then-act and delivers the message twice. A drain claims through IOutboxStore.GetUnsentMessagesAsync, whose claim already admits a failed message once its next-attempt floor has elapsed; this read consults no floor, so a message deferred moments ago still appears here. Use it to report and diagnose, never to dispatch.

Scope: estate-wide. This read matches rows by status and age, not by tenant, so it observes the messages of every tenant in the store. It modifies nothing. Each returned OutboundMessage carries its own TenantId, so a caller can re-establish the owning tenant for each message it handles.

The name is the safety control. An unscoped read is reachable only by writing "AllTenants" at the call site — never by omitting a scope, and never by passing a value that happens to mean "everything". This discloses full message bodies, so a reviewer reading the call site sees the disclosure without tracing where a scope came from.

The outbox drain is cross-tenant by design: one dispatcher serves every tenant, so scoping this read to an ambient tenant would stall delivery for all the others. An outbox store reads no ambient tenant context; should a tenant-scoped read ever be required, it arrives as an explicit parameter on a distinct operation — never by inferring a scope from ambient state.

GetAllTenantsScheduledMessagesAsync(DateTimeOffset, int, CancellationToken)

Retrieves messages scheduled for future delivery, across every tenant.

public ValueTask<IEnumerable<OutboundMessage>> GetAllTenantsScheduledMessagesAsync(DateTimeOffset scheduledBefore, int batchSize, CancellationToken cancellationToken)

Parameters

scheduledBefore DateTimeOffset

Only return messages scheduled before this timestamp.

batchSize int

Maximum number of messages to retrieve.

cancellationToken CancellationToken

Token to monitor for cancellation requests.

Returns

ValueTask<IEnumerable<OutboundMessage>>

Collection of scheduled messages ready for delivery, across all tenants.

Remarks

Observation only — the result MUST NOT be handed to a transport. This is a plain read: it matches rows without conditionally taking them, so two callers observe the same message and neither holds it. Publishing from this set is check-then-act and delivers the message twice — a filter on an unset dispatcher column does not make it a claim, because the value it tests is never conditionally written. A drain claims through IOutboxStore.GetUnsentMessagesAsync, whose claim already admits a scheduled message once its time has arrived. Use it to report and diagnose, never to dispatch.

Scope: estate-wide. This read matches rows by status and age, not by tenant, so it observes the messages of every tenant in the store. It modifies nothing. Each returned OutboundMessage carries its own TenantId, so a caller can re-establish the owning tenant for each message it handles.

The name is the safety control. An unscoped read is reachable only by writing "AllTenants" at the call site — never by omitting a scope, and never by passing a value that happens to mean "everything". This discloses full message bodies, so a reviewer reading the call site sees the disclosure without tracing where a scope came from.

The outbox drain is cross-tenant by design: one dispatcher serves every tenant, so scoping this read to an ambient tenant would stall delivery for all the others. An outbox store reads no ambient tenant context; should a tenant-scoped read ever be required, it arrives as an explicit parameter on a distinct operation — never by inferring a scope from ambient state.

GetAllTenantsStatisticsAsync(CancellationToken)

Gets statistics about the outbox store, across every tenant.

public ValueTask<OutboxStatistics> GetAllTenantsStatisticsAsync(CancellationToken cancellationToken)

Parameters

cancellationToken CancellationToken

Token to monitor for cancellation requests.

Returns

ValueTask<OutboxStatistics>

Statistics including message counts by status and oldest unsent message age, across all tenants.

Remarks

Scope: estate-wide. The name is the safety control: estate-wide counters are reachable only by writing "AllTenants" at the call site, never by omitting a scope. Aggregate counts disclose no message identifiers, bodies, or tenant names — only totals — so this is a weaker disclosure than GetAllTenantsFailedMessagesAsync(int, DateTimeOffset?, int, CancellationToken), which returns whole messages.

These are estate-wide counters reported to an operator, not to a tenant. The figures describe the whole table: the call takes no tenant argument, and OutboxStatistics carries no tenant field, so a confined result could not say which partition it described even if one were produced.

An outbox store reads no ambient tenant context, so it cannot honor a tenant it never sees. Should per-tenant counters ever be required, they arrive as an explicit parameter on a distinct operation — never by inferring a scope from ambient state.

GetFencingHighWaterAsync(CancellationToken)

Reads the store's currently recorded fencing high-water mark.

public Task<long?> GetFencingHighWaterAsync(CancellationToken cancellationToken)

Parameters

cancellationToken CancellationToken

Token to monitor for cancellation requests.

Returns

Task<long?>

The recorded high-water mark, or null when no fencing token has ever been presented to this store.

GetUnsentMessagesAsync(int, long, CancellationToken)

Claims a batch of unsent messages on behalf of the leadership tenure identified by fencingToken.

public ValueTask<IEnumerable<OutboundMessage>> GetUnsentMessagesAsync(int batchSize, long fencingToken, CancellationToken cancellationToken)

Parameters

batchSize int

Maximum number of messages to retrieve.

fencingToken long

The fencing token for the caller's current leadership tenure.

cancellationToken CancellationToken

Token to monitor for cancellation requests.

Returns

ValueTask<IEnumerable<OutboundMessage>>

Collection of unsent messages ready for delivery.

Remarks

The high-water mark is stored once per outbox SCOPE, not per message row. Implementations MUST claim rows only when fencingToken is greater than or equal to the scope's stored mark, and MUST advance that mark to the maximum of its current value and fencingToken within the same atomic action as the claim. A presented token below the mark identifies a superseded tenure: the claim yields zero rows and MUST NOT throw — this is a set-based operation, not an error.

The mark answers which TENURE may act on this scope. It records nothing about an individual row, and a per-row column does not implement this contract. A per-row mark cannot see a tenure that touched a different row in the same scope, so it admits a superseded leader on every row the current leader has not yet reached — which is most rows, on every handover. It would also pass a single-row test, which is why the distinction is stated here rather than left to the reader.

A token identifies a tenure and cannot discriminate two claim cycles of the same tenure, so this mark is necessary and not sufficient on its own: completing a message additionally requires the claim identity the row carries. See the claim-scoped capability for that half.

Exceptions

ArgumentOutOfRangeException

Thrown when batchSize is less than 1.

GetUnsentMessagesAsync(int, CancellationToken)

Retrieves unsent messages from the outbox for publishing.

public ValueTask<IEnumerable<OutboundMessage>> GetUnsentMessagesAsync(int batchSize, CancellationToken cancellationToken)

Parameters

batchSize int

Maximum number of messages to retrieve.

cancellationToken CancellationToken

Token to monitor for cancellation requests.

Returns

ValueTask<IEnumerable<OutboundMessage>>

Collection of unsent messages ready for delivery.

Remarks

This operation returns persisted payload bytes and closed routing/header data; it does not discover or deserialize consumer payload types. Payload decoding belongs to the configured worker codec and its explicit metadata. Provider construction may impose separate runtime requirements. This claim is unfenced. A store that can enforce leadership fencing implements IFencedOutboxStore, whose overloads take the leadership token; a store that cannot is never handed one.

Exceptions

ArgumentOutOfRangeException

Thrown when batchSize is less than 1.

MarkDeadLetteredAsync(string, string, int, OutboxWriteAuthority, CancellationToken)

Dead-letters a message only while the caller holds both accepted tenure and current claim.

public ValueTask<OutboxCompletionOutcome> MarkDeadLetteredAsync(string messageId, string reason, int attemptCount, OutboxWriteAuthority authority, CancellationToken cancellationToken)

Parameters

messageId string

The persisted message identifier captured at acquisition.

reason string

The reason for the terminal disposition.

attemptCount int

Nonnegative observed logical attempt count; applied writes retain its maximum.

authority OutboxWriteAuthority

The positive tenure and nonblank acquisition identity captured by the worker.

cancellationToken CancellationToken

Token to monitor for cancellation requests.

Returns

ValueTask<OutboxCompletionOutcome>

The outcome decided atomically with the guarded terminal mutation.

Remarks

Validate arguments before mutation. For valid authority evaluate the fence before row outcomes; absent/different/released claims return ClaimLost, retained terminal rows AlreadyTerminal and absent rows MessageNotFound. Do not reconstruct outcomes from a later unguarded read.

MarkDeadLetteredAsync(string, string, int, long, CancellationToken)

Moves a message to the dead-letter destination, applying it only if the caller's tenure is still current.

public ValueTask<OutboxCompletionOutcome> MarkDeadLetteredAsync(string messageId, string reason, int attemptCount, long fencingToken, CancellationToken cancellationToken)

Parameters

messageId string

The unique identifier of the message to dead-letter.

reason string

The reason recorded against the dead-lettered message.

attemptCount int

Observed logical delivery attempts. Nonnegative; an applied transition atomically records the maximum of this value and the stored count. Missing, terminal, and refused transitions do not change the count.

fencingToken long

The monotonic token identifying the caller's leadership tenure.

cancellationToken CancellationToken

Token to monitor for cancellation requests.

Returns

ValueTask<OutboxCompletionOutcome>

What the store did, decided by the same atomic action that performed the transition.

Remarks

Implementations MUST evaluate the fence and the transition in ONE atomic action. On a store whose terminal idiom destroys the row, the transition is irreversible: there is no later read that can establish whether the caller was entitled to make it, because the evidence is what was deleted. A fence judged in a separate round trip leaves a window in which a successor advances the mark between the check and the delete.

The refusal is REPORTED, never thrown. The drains reach this member from inside their own exception handlers, where a sibling handler on the same block cannot run, so an exception raised here escapes the cycle and abandons every message the caller still holds. ClaimLost is not reachable from this member — it carries no claim term — and an implementation returning it would be reporting a decision it did not make.

Exceptions

ArgumentException

Thrown when messageId is null or empty.

ArgumentOutOfRangeException

Thrown before mutation when attemptCount is negative.

MarkDeadLetteredAsync(string, string, int, string, CancellationToken)

Dead-letters a message only while the caller holds its current acquisition.

public ValueTask<OutboxCompletionOutcome> MarkDeadLetteredAsync(string messageId, string reason, int attemptCount, string claimIdentity, CancellationToken cancellationToken)

Parameters

messageId string

The persisted identifier captured at acquisition.

reason string

The reason for the terminal disposition.

attemptCount int

Nonnegative logical attempt count; applied transitions retain its maximum.

claimIdentity string

The nonblank identity captured from the acquisition, never a process ID.

cancellationToken CancellationToken

Token to monitor for cancellation requests.

Returns

ValueTask<OutboxCompletionOutcome>

The outcome decided atomically with the guarded transition.

Remarks

Validate arguments before mutation. Missing/released/different leases return ClaimLost, retained terminal rows AlreadyTerminal and absent rows MessageNotFound. Refusals are returned, not thrown. No completion may classify its outcome by rereading after a separate mutation.

MarkDeadLetteredAsync(string, string, int, CancellationToken)

Durably transitions the specified message to the terminal DeadLettered status after its retry policy is exhausted.

public ValueTask<OutboxCompletionOutcome> MarkDeadLetteredAsync(string messageId, string reason, int attemptCount, CancellationToken cancellationToken)

Parameters

messageId string

The unique identifier of the message to dead-letter.

reason string

A human-readable reason describing why the message was dead-lettered.

attemptCount int

Observed logical delivery attempts. Nonnegative; an applied transition atomically records the maximum of this value and the stored count.

cancellationToken CancellationToken

Token to monitor for cancellation requests.

Returns

ValueTask<OutboxCompletionOutcome>

The outcome of the transition. Only Applied means the row was mutated.

Remarks

The count describes logical attempts already observed by the caller, not physical transport requests. Only an applied transition may change it: the same atomic operation records max(stored, supplied). Missing and already-terminal messages retain their count; zero is valid for a pre-dispatch poison message.

After this transition the message MUST NOT be returned by any claim predicate (GetUnsentMessagesAsync(int, CancellationToken) or IOutboxStoreAdmin.GetAllTenantsFailedMessagesAsync), preventing re-delivery.

Whether the row is also REMOVED depends on the store's idiom, and the difference is visible to an operator. A store that treats the terminal transition as a move copies the message to a dedicated dead-letter table and deletes the outbox row, so the outbox does not grow. A store that records the terminal state in a status column leaves the row in place; re-delivery is still prevented, but the row remains and this interface offers nothing that enumerates or removes it. Plan retention for that case rather than assuming the transition bounds the table.

This member marks the row. It does NOT put the message anywhere a consumer can read it back. The readable dead-letter surface is a separate contract with its own enumerate, count and replay members, and the framework's own drain writes to BOTH: it enqueues the message there and then calls this member. A caller invoking this member directly gets only the second half, so the message is buried and unreadable even on a store whose idiom moves the row. The same gap opens when the composition resolves a no-op dead-letter queue, which discards the message and logs, while this member still records the terminal state.

So: if the message must remain recoverable, write it to the dead-letter queue before calling this, exactly as the drain does. Nothing here does it for you, and nothing reports that it was not done.

A TERMINAL message is never reopened by this member either, whoever reports it. The same obligation the base completion carries applies here and has to be restated, because this interface is composition rather than inheritance: nothing an implementor reads on IOutboxStore reaches this member. A store MUST NOT dead-letter a message that is already sent or already dead-lettered, and that binds a report from the CURRENT claim holder exactly as it binds a stale one. Dead-lettering a delivered message records a delivery failure that did not happen; repeating it writes a second dead-letter row for one message, and either redrive then produces a duplicate.

Clearing the delivery lease is not hygiene — it is load-bearing and it cuts both ways. It stops a stale sweep resurrecting the message, and it also removes the only evidence a LATER completion could be judged against, so an ownership guard alone cannot protect this row afterwards. The terminal-status obligation above is what remains, which is why it is stated and not implied.

THE REFUSAL IS REPORTED, NEVER THROWN, AND THE CALLER MUST TEST FOR Applied BY NAME. Every guard an implementation runs here — the row is gone, the row is already terminal, the lease belongs to someone else — ends in a write that did not happen, and the caller has already written the dead-letter entry by the time it asks. A refusal it cannot see leaves the message simultaneously delivered by the live claimant and sitting unreplayed in the dead-letter queue, where a redrive re-executes a message that already succeeded. Deciding success by excluding the refusals instead makes every member added later a success, which is the direction this contract must never fail.

Reachable outcomes. Applied when the row was mutated; MessageNotFound when no row matched; AlreadyTerminal when the row was already sent or already dead-lettered; ClaimLost when the store holds a delivery lease for a different owner. FenceRefused is NOT reachable — this member carries no fencing token, so an implementation returning it would report a judgement it was given no means to make. Unknown must never be returned by a store; it exists so that a default or unset value cannot read as success.

Exceptions

ArgumentException

Thrown when messageId is null or empty.

ArgumentOutOfRangeException

Thrown before mutation when attemptCount is negative.

MarkFailedAsync(string, string, int, DateTimeOffset?, OutboxWriteAuthority, CancellationToken)

Records a delivery failure, applying it only if the caller still holds BOTH the tenure and the claim.

public ValueTask<OutboxCompletionOutcome> MarkFailedAsync(string messageId, string errorMessage, int retryCount, DateTimeOffset? nextAttemptAt, OutboxWriteAuthority authority, CancellationToken cancellationToken)

Parameters

messageId string

The unique identifier of the message that failed.

errorMessage string

The error describing the failure.

retryCount int

The absolute attempt count for this message.

nextAttemptAt DateTimeOffset?

The time before which the message must NOT be re-claimed, or null to record the failure without a computed backoff schedule.

authority OutboxWriteAuthority

The tenure and claim the caller is acting under.

cancellationToken CancellationToken

Token to monitor for cancellation requests.

Returns

ValueTask<OutboxCompletionOutcome>

What the store did, decided by the same atomic action that performed the mutation.

Remarks

ONE member rather than two, because the backoff schedule is a VALUE the caller already has or does not. The unfenced surface splits the plain and scheduled completions across two members; here the caller has already decided which it wants and holds the computed instant, so a second member would differ only in whether one argument was supplied. The nullable schedule is not the omitted-guard shape that the authority deliberately avoids: "there is no backoff schedule" is a real state with a real meaning to the statement, whereas "there is no tenure" cannot arise on a fenced member at all.

Implementations MUST evaluate the fence, the claim and the mutation in ONE atomic action, and MUST decide the returned outcome from that same action. A store that re-reads the row afterwards to classify what happened compares a value captured outside the window it must describe, which is wrong exactly when the refusal is real.

Implementations MUST persist the high-water mark such that it never decreases across process restart, failover or replica promotion. A store whose high-water is only as durable as an asynchronously-replicated value does not satisfy this and MUST NOT implement this interface.

Atomicity is necessary and not sufficient, and the second half is why this clause exists. A fence is two properties: the comparison and the mutation are one indivisible action, AND the mark is monotone non-decreasing under every fault in the deployment's model. A store can satisfy the first perfectly and still be unsafe — if a failover, an eviction or a restore can roll the mark backwards, a superseded tenure presents a token that is no longer below it and is admitted. A monotonic counter that can decrease is not a fence, and a store providing only the atomicity half satisfies the letter of this interface while breaking the guarantee it exists to give.

The refusals are REPORTED, never thrown. The drains report a delivery failure from inside their own exception handlers, where a sibling handler on the same block cannot run, so an exception raised here escapes the whole cycle and abandons every message the caller still legitimately holds. The two refusals also differ in how much work they cost: FenceRefused means a NEWER TENURE exists and the caller must stop draining entirely, while ClaimLost concerns this one message and the caller continues with the rest.

Exceptions

ArgumentException

Thrown when messageId is null or empty.

MarkFailedAsync(string, string, int, string, CancellationToken)

Records a delivery failure reported by the claim identified by claimIdentity.

public ValueTask<OutboxCompletionOutcome> MarkFailedAsync(string messageId, string errorMessage, int retryCount, string claimIdentity, CancellationToken cancellationToken)

Parameters

messageId string

The unique identifier of the message that failed.

errorMessage string

The error describing the failure.

retryCount int

The absolute attempt count for this message.

claimIdentity string

The claim under which the caller received this message, from DispatcherId.

cancellationToken CancellationToken

Token to monitor for cancellation requests.

Returns

ValueTask<OutboxCompletionOutcome>

What the store did, decided by the same atomic action that performed the mutation.

Remarks

Implementations MUST evaluate the claim and the mutation in ONE atomic action, and MUST decide whether to refuse from that same action. A store that reconstructs the decision from a separate read compares a value captured before the window it must describe, which is false exactly when the refusal is real.

A refusal is REPORTED, not thrown, and the reason is the caller's control flow rather than style. The drain reports a delivery failure from inside its own exception handler; an exception raised there is not caught by a sibling catch on the same try, so it escapes the whole cycle and abandons every message the caller still holds. The refusal must cost one message, so it travels in the return value where the caller reads it without unwinding.

A refusal here is ROW-LEVEL, and the distinction decides how much work is abandoned. A fence refusal means a NEWER TENURE exists and the whole drain cycle must stop, whereas ClaimLost means only that this message was re-claimed — the caller stops writing for THIS message and continues with the others it still holds. A caller that aborts its cycle on a lost claim abandons messages a live tenure owns.

Exceptions

ArgumentException

Thrown when messageId is null or empty.

MarkFailedAsync(string, string, int, CancellationToken)

Marks a message as failed during delivery.

public ValueTask MarkFailedAsync(string messageId, string errorMessage, int retryCount, CancellationToken cancellationToken)

Parameters

messageId string

The unique identifier of the message that failed.

errorMessage string

The error description or exception message.

retryCount int

The current retry attempt count.

cancellationToken CancellationToken

Token to monitor for cancellation requests.

Returns

ValueTask

A task representing the asynchronous mark-failed operation.

Remarks

A failure is a delay, not an ending. The message stays owed delivery, and three conditions hold together to keep that true without turning it into a retry loop. Each is stated because a store can satisfy the other two and still be wrong.

The message is withheld, then returned. It does not become claimable again immediately -- an immediate re-claim is a zero-backoff loop that saturates the transport against a destination that is failing anyway -- and it does become claimable once the store's failure-backoff floor has elapsed. The floor is measured from the recorded failure, not from a claim lease: a message that failed without ever being claimed has no lease, and a floor derived from one would yield nothing for it. Withholding it permanently satisfies the first half and silently drops the message, so both halves are required.

A report from a dispatcher that no longer holds the claim is a no-op rather than an error -- it is stale, not invalid. Honouring it would release a claim its successor is still delivering under, and both would then send the same message. A message that was never claimed has no owner and is reported freely. The guard must not be satisfied by refusing everybody -- the owner's own report still has to land, or the store cannot record failures at all.

HOW FINELY "no longer holds the claim" IS JUDGED VARIES BY STORE, AND THIS MEMBER DOES NOT PROMISE PER-CLAIM PRECISION. An earlier wording here said only the claim's owner may report against it, which reads as a per-claim guarantee that no shipped store keeps through this member. What the shipped stores actually compare is a per-PROCESS identity, so two successive claims by the same process are indistinguishable to it: a report from an expired claim of a still-running dispatcher is accepted, and it releases a reservation a live successor of that same process still holds.

THE FLOOR A CALLER MAY RELY ON, stated because "varies by store" is not a contract. Every shipped store that offers this member refuses a report against a message currently held by a DIFFERENT dispatcher process, and admits one against a message nobody holds. That is the floor, and it is uniform: what varies above it is only whether a store can also distinguish two claim cycles of the SAME process, and none of them can through this member. An implementor of this interface is required to meet the floor; a store that matches on the message identifier alone does not implement this member's contract, however well it records the identity elsewhere.

The floor is expressed differently by different data models -- a prefix of a stored claim token, an equality against a configured processor identity, a conditional script, an in-process comparison -- and the obligation is the property, not the mechanism. Note what the floor deliberately does NOT require: an "ownership term" a caller can satisfy by omitting the value it guards is not a guard, so a store whose only option would be such a predicate must instead offer the claim-scoped member below and refuse here, rather than carry a predicate with a hole in it.

For a completion judged against the specific claim the caller holds, use IClaimScopedOutboxStore. It takes the claim identity as an argument and returns an outcome saying whether the store applied the completion or refused it, so a caller whose claim has lapsed is told rather than silently succeeding. Discover it with GetService(Type) rather than a cast: a cast sees only the outermost type and is lossy through any decorator. Not every store implements it; a caller that needs the guarantee should check, because the fallback to this member is the weaker comparison described above.

The recorded attempt count never decreases. Implementations record the greater of the stored count and retryCount. The ceiling that eventually gives up on a message is driven by that count, so a late report carrying a lower number would push the ceiling further away each time one arrived, and the message would be retried without end.

Marking a message that does not exist is a silent no-op. A message in a terminal state is never reopened by a late failure report, and terminal means delivered or dead-lettered -- in both, the decision to stop delivering has already been taken and recorded. Guarding only the delivered state is the error this wording exists to prevent: a reopened dead-lettered message re-enters the retry population it was deliberately removed from. A message merely in flight is not terminal, and a failure report against one must land -- that is the ordinary path this method exists to serve.

The ownership condition above cannot carry this guarantee, and a store that relies on it will be wrong. Dead-lettering releases the delivery lease, so a dead-lettered message presents as never-claimed and is therefore reported freely by that rule. The terminal-state check is required in its own right and applies unconditionally.

The obligation is the property, not the mechanism. A store satisfies it however its data model allows: a status term in the mutation's own predicate, a terminal transition that removes the row so no later report can match it, a claim record stamped with an identity no caller can present, or a claimable predicate keyed on a field the failure path never writes. What is required is that a late report cannot reopen a terminal message -- not that any particular column be tested.

Exceptions

ArgumentException

Thrown when messageId is null or empty.

ArgumentNullException

Thrown when errorMessage is null.

MarkFailedWithBackoffAsync(string, string, int, DateTimeOffset, string, CancellationToken)

Records a delivery failure reported by the claim identified by claimIdentity, applying the per-message backoff schedule.

public ValueTask<OutboxCompletionOutcome> MarkFailedWithBackoffAsync(string messageId, string errorMessage, int retryCount, DateTimeOffset nextAttemptAt, string claimIdentity, CancellationToken cancellationToken)

Parameters

messageId string

The unique identifier of the message that failed.

errorMessage string

The error describing the failure.

retryCount int

The absolute attempt count for this message.

nextAttemptAt DateTimeOffset

The time before which the message must NOT be re-claimed.

claimIdentity string

The claim under which the caller received this message, from DispatcherId.

cancellationToken CancellationToken

Token to monitor for cancellation requests.

Returns

ValueTask<OutboxCompletionOutcome>

What the store did, decided by the same atomic action that performed the mutation.

Remarks

This member exists because the backoff route is the one a genuine delivery failure takes when automatic retry is enabled. Scoping only the plain completion would leave the dominant failure path unscoped while the capability appeared to close it. The same atomicity and reported-refusal requirements as MarkFailedAsync(string, string, int, string, CancellationToken) apply here in full.

Exceptions

ArgumentException

Thrown when messageId is null or empty.

MarkFailedWithBackoffAsync(string, string, int, DateTimeOffset, CancellationToken)

Marks a message as failed and records the time before which it must NOT be re-claimed for retry, applying the per-message backoff schedule.

public ValueTask MarkFailedWithBackoffAsync(string messageId, string errorMessage, int retryCount, DateTimeOffset nextAttemptAt, CancellationToken cancellationToken)

Parameters

messageId string

The unique identifier of the message that failed.

errorMessage string

The error description or exception message.

retryCount int

The current retry attempt count.

nextAttemptAt DateTimeOffset

The caller-computed earliest next attempt, typically now + IBackoffCalculator.CalculateDelay(attempt). A LOWER bound requested by the caller, not the final schedule: the store composes it with its own floor F and persists whichever is later, so this value can defer the next attempt beyond F but can never bring it inside F.

cancellationToken CancellationToken

Token to monitor for cancellation requests.

Returns

ValueTask

A task that represents the asynchronous mark-failed-with-backoff operation.

Remarks

After this call, the message MUST NOT be returned by the claim predicate (GetUnsentMessagesAsync(int, CancellationToken)) until nextAttemptAt has elapsed, so the computed backoff delay genuinely throttles re-delivery.

Implementors: compose, do not substitute. The persisted next-attempt time MUST be the LATER of nextAttemptAt and the store's own configured failure-backoff floor F — the same floor the plain MarkFailedAsync(string, string, int, CancellationToken) path applies. Binding the caller's instant verbatim is a defect, not a permitted simplification: the default backoff calculator yields on the order of a second at the first attempt, so a store that substitutes rather than composes makes this capability WEAKEN the guarantee it exists to strengthen — the identical failure waits F without the capability and about a second with it.

Compose with a maximum rather than a conditional, so relaxing the floor below F is not something ordinary use can express. Compute the floor term on whichever clock the store's own claim predicate compares against — the database server's where the store has one, the injected TimeProvider where the store is deliberately client-clocked — so the composition introduces no clock the provider was not already trusting.

Exceptions

ArgumentException

Thrown when messageId is null or empty.

ArgumentNullException

Thrown when errorMessage is null.

MarkSentAsync(string, OutboxWriteAuthority, CancellationToken)

Marks a message sent only while the caller holds the current tenure and claim.

public ValueTask<OutboxCompletionOutcome> MarkSentAsync(string messageId, OutboxWriteAuthority authority, CancellationToken cancellationToken)

Parameters

messageId string

The persisted message identifier captured at acquisition.

authority OutboxWriteAuthority

The immutable acquisition evidence captured before delivery.

cancellationToken CancellationToken

Token to monitor for cancellation requests.

Returns

ValueTask<OutboxCompletionOutcome>

The outcome decided atomically with the guarded terminal transition.

Remarks

Missing or released leases return ClaimLost. Validate nonblank identifiers before mutation. A fenced authority additionally requires a positive tenure; evaluate its fence before row-level outcomes. Retained terminal rows return AlreadyTerminal. Never infer the outcome from a later read.

MarkSentAsync(string, long, CancellationToken)

Marks a message as successfully sent on behalf of the leadership tenure identified by fencingToken.

public ValueTask<OutboxCompletionOutcome> MarkSentAsync(string messageId, long fencingToken, CancellationToken cancellationToken)

Parameters

messageId string

The unique identifier of the message to mark as sent.

fencingToken long

The fencing token for the caller's current leadership tenure.

cancellationToken CancellationToken

Token to monitor for cancellation requests.

Returns

ValueTask<OutboxCompletionOutcome>

What the store did, decided by the same atomic action that performed the mutation.

Remarks

Implementations MUST apply the mutation as a single atomic compare-and-swap: only apply it when fencingToken is greater than or equal to the stored high-water mark, and atomically advance the stored high-water mark to the maximum of its current value and fencingToken. A presented token below the stored high-water mark identifies a superseded leader attempting to complete work it no longer owns, and the store MUST NOT apply the mutation.

A REFUSAL IS REPORTED IN THE RETURN VALUE, NEVER SMUGGLED THROUGH A SUCCESS OR A FAILURE. This member used to return ValueTask, and a void-returning mutation can express exactly two outcomes: it threw, or it did not. This seam needs three — applied, refused, and an infrastructure fault — so refusal had to travel through an exception, and implementations reached independently for four different wrong encodings of it. One reported a refusal as already-sent; one typed it as a generic failure that a catch-all then dead-lettered; one summed rowcounts across a multi-statement batch so the caller's own refusal test could never fire. A refusal indistinguishable from a failure gets disposed of as a failure, and one indistinguishable from a success gets disposed of as a success — and the second marks a message sent that was never sent. Returning the outcome is what makes both unrepresentable rather than merely unlikely.

ROW-SCOPED AND TENURE-SCOPED REFUSALS DIFFER, and the distinction decides how much work the caller abandons. FenceRefused means a NEWER TENURE exists, so every remaining write this caller would make is unfenced and it must stop draining altogether. ClaimLost, AlreadyTerminal and MessageNotFound concern THIS MESSAGE ONLY: the caller records them and carries on with the rest of its batch. A caller that stands down on a row-scoped refusal strands messages a live tenure still owns; one that carries on after a fence refusal lets a superseded tenure keep writing.

Callers MUST test for Applied BY NAME. Deciding success by excluding the refusals known at compile time makes every value added to the enumeration later begin life as a silent success, which is the way this contract fails open.

Infrastructure faults still throw. A refusal is an expected outcome of losing leadership and is not an error; a connection that dropped is.

Exceptions

ArgumentException

Thrown when messageId is null or empty.

MarkSentAsync(string, string, CancellationToken)

Marks a message sent only while the caller holds the current claim.

public ValueTask<OutboxCompletionOutcome> MarkSentAsync(string messageId, string claimIdentity, CancellationToken cancellationToken)

Parameters

messageId string

The persisted message identifier captured at acquisition.

claimIdentity string

The immutable acquisition evidence captured before delivery.

cancellationToken CancellationToken

Token to monitor for cancellation requests.

Returns

ValueTask<OutboxCompletionOutcome>

The outcome decided atomically with the guarded terminal transition.

Remarks

Missing or released leases return ClaimLost. Validate nonblank identifiers before mutation. A fenced authority additionally requires a positive tenure; evaluate its fence before row-level outcomes. Retained terminal rows return AlreadyTerminal. Never infer the outcome from a later read.

MarkSentAsync(string, CancellationToken)

Marks a message as successfully sent.

public ValueTask MarkSentAsync(string messageId, CancellationToken cancellationToken)

Parameters

messageId string

The unique identifier of the message to mark as sent.

cancellationToken CancellationToken

Token to monitor for cancellation requests.

Returns

ValueTask

A task representing the asynchronous mark-sent operation.

Remarks

This mutation is unfenced. A store that can enforce leadership fencing implements IFencedOutboxStore.

Exceptions

ArgumentException

Thrown when messageId is null or empty.

InvalidOperationException

Thrown when the message does not exist or is already marked as sent.

ResetFencingHighWaterAsync(long, bool, CancellationToken)

Administratively sets the store's fencing high-water mark.

public Task ResetFencingHighWaterAsync(long newHighWater, bool force, CancellationToken cancellationToken)

Parameters

newHighWater long

The high-water mark to record.

force bool

When false (the default an operator should reach for), the store MUST refuse a newHighWater strictly below the currently recorded value and throw InvalidOperationException without changing anything. When true, the store MUST apply newHighWater unconditionally, including a lowering.

cancellationToken CancellationToken

Token to monitor for cancellation requests.

Returns

Task

A task representing the asynchronous reset operation.

Remarks

Lowering the high-water is unsafe by design. The high-water exists to refuse a superseded leader; lowering it re-admits one — a leader whose token is now below the (lowered) high-water reads as current again and can claim and complete messages a fresher leader already owns. This is the same split-brain the fence exists to prevent, self-inflicted through the recovery surface meant to fix a stuck fence. force exists for the one case where that risk is understood and accepted (recovering a genuinely poisoned fence, with independent confirmation no live claim conflicts with the new value) — never as a routine unstick button.

Exceptions

InvalidOperationException

newHighWater is below the recorded high-water mark and force is false.

StageMessageAsync(OutboundMessage, CancellationToken)

Stages a message in the outbox for later delivery.

public ValueTask StageMessageAsync(OutboundMessage message, CancellationToken cancellationToken)

Parameters

message OutboundMessage

The outbound message to stage.

cancellationToken CancellationToken

Token to monitor for cancellation requests.

Returns

ValueTask

A task representing the asynchronous stage operation.

Exceptions

ArgumentNullException

Thrown when message is null.

InvalidOperationException

Thrown when a message with the same ID already exists.