Skip to content

ADR 0012 — Transactional outbox owned by the producer context ​

  • Status: Accepted design; implementation is incremental, not acceptance of the full requirement
  • Date: 2026-10-21
  • Amendment: local consumption (2a), worker/observation (2b), Auth membership pilot (3b.1a/b), explicit platform scope (OUT-09/10)
  • Baseline inspected: develop, 655ceb40d3a4a60bd4131086be4689188c4794e7
  • Related: ADR 0009, ADR 0010, ADR 0011
  • Implementation contract: Transactional outbox

Context ​

The Nexio messaging requirement (mensageria.html, v1.6, 2026-09-12, in its business definitions) requires durable reactions to confirmed business facts, retries, isolation, per-key ordering and operational recovery. Its CA-01 through CA-27 define acceptance; a reusable writer alone cannot satisfy them. Its E-01 through E-14 describe an older platform revision, not the present baseline.

GrydAuthDbContext currently saves and dispatches inside a transaction. The dispatch can change tracked state and repeat saving. AuthorizationAffectingEventHandler increments TokenVersion in this loop. Moving that handler after commit would permit old tokens after revocation, violating A1.7. Conversely, external reactions must not run inside a business transaction.

The Core already supplies OutboxMessage and PostgresOutbox. Notifications maps these into its own schema and supplies a specialized durable processor, receipts and its own payload storage. That implementation is useful evidence, but it is neither a general event transport nor a reason to route every product event through Notifications.

Options considered ​

OptionAssessment
In-memory dispatch after commitSmall, but loses work between commit and publication; cannot satisfy CA-05.
A central outbox written through a separate contextLoses atomicity without a distributed transaction; couples every product to one database. Rejected.
A new broker and messaging framework nowDoes not remove the need for transactional producer storage or consumer idempotency. Adds deployment, upgrades and another operational state before the existing primitives have been proven. Deferred.
Jobs as the event contractJobs remain useful for scheduling, but a separate enqueue is not atomic with an arbitrary producer's business write. Deferred as a delivery adapter, not used as the consistency boundary.
Producer-owned relational outbox using existing Core primitivesChosen: shares the producer transaction, adds no running service for the first stage, and can drain independently owned contexts later.

No broker, managed queue or external messaging library is introduced by this decision. A future transport adapter must preserve these semantics and justify its operational cost separately.

Decision ​

1. Separate transactional invariants from durable reactions ​

An invariant required for the validity or authorization of an act stays in its transaction. In particular, the source-of-truth increment of TokenVersion commits with the revocation and rolls back with it. Cache propagation may later become a durable reaction; the increment cannot.

An integration event describes a confirmed fact to a consumer. The producer writes its envelope with the business fact and does not invoke a consumer while writing. A processor in a separate unit of work may read it only after commit. An exception from a later consumer cannot change the already confirmed result presented to the original caller.

The first stage leaves the existing Auth dispatch loop unchanged. It does not rename the loop into a post-commit mechanism. Migrating Auth requires classifying every handler, moving transactional invariants to explicit transactional code, and retaining revocation/rollback integration tests. Only then can a gate forbid the remaining pre-commit reaction paths (CA-04).

The additive Auth membership pilot preserves those protections. Stage shares the source transaction; Audit delivery is separately opt-in. Identity is per attempt: P1/P4/CA-06/CA-22–24 remain open. Rollback neither compensates Redis nor guarantees complete in-memory event restoration.

2. Storage belongs to the context that owns the fact ​

Each participating product or module maps OutboxMessage into its own EF Core context and schema. The business rows and delivery intent are written through the same context and transaction. The writer must not resolve GrydAuthDbContext, write via a second context, publish, or commit. An explicit caller transaction still owns commit; SaveChanges is not proof of commit in that case.

Keep the existing OutboxMessage shape and table contract compatible with Notifications. Store the generic JSON body and immutable event metadata in a new, producer-mapped companion row with a one-to-one foreign key to the envelope. Both rows are added before saving. Notifications can keep its existing notification payload storage; this change does not require adding a companion table to Notifications or migrating its existing rows.

The companion model is infrastructure, not a cross-module business entity. A context opts in via explicit model configuration and creates its own migration. No library applies migrations at startup. The writer rejects a context that has not mapped both rows and rejects a known nonrelational provider: in-memory tests do not establish a transactional guarantee.

3. Producer contract and retries ​

The enqueue operation stages immutable, serialized data. It neither calls SaveChanges nor opens a transaction. The product supplies a stable message ID, explicit tenant, aggregate ID, strictly positive aggregate sequence, versioned event kind, occurrence time and availability time. Optional causation/correlation and declared-author IDs are data, never an authenticated execution identity. The generic writer defaults to Tenant scope. Platform scope is now available only through explicit envelope scope and separately composed writer/consumer capabilities; a missing or empty tenant never infers platform ownership.

The producer allocates the sequence with its aggregate's concurrency control. The existing unique index on (TenantId, AggregateId, Sequence) detects conflicts; the library does not allocate a sequence with MAX + 1, promise gap detection or infer aggregate concurrency. Within a producer outbox the aggregate ID must identify one ordering stream across event kinds.

The caller creates message IDs, metadata and payload once per logical operation and reuses them on retry. An aborted transaction is retried by reconstructing the complete business operation with a fresh context, not by reusing accepted EF tracking state. A failed or uncertain commit must be verified in a new context by stable operation/message identity before any replay. The writer is not a command idempotency store and duplicate-key failure is not an automatic declaration of success.

Domain-event collection must not clear the only event copy before the unit of work is recoverable. The first stage is explicit enqueue; automatic aggregate collection and Auth adoption remain separate work. Their tests must include retry after event collection (CA-06).

4. Explicit local processing and inbox (stage 2a) ​

Stage 2a added explicit ProcessOneAsync(producerId, ct) and a small producer/tenant failure query. OUT-09/10 later amended that stage to support explicit platform routes and receipts (section 4c). Registration alone creates no hosted service. Section 4b adds an explicitly enabled worker. PostgreSQL is required for both producer and consumer storage. Platform messages are supported only as an explicit opt-in local route with a dedicated platform receipt and execution snapshot. External effects are not supported by this processor. HTTP, broker and ERP calls are unsupported inside a local consumer because a remote effect cannot commit atomically with its local inbox receipt. A future adapter needs destination idempotency, natural-key reconciliation and a durable external reference. Notifications remains on its specialized processor and payload/receipt contract; its scope migration backfills only documented legacy global rows. It is not routed through the generic plan/receipt path.

Registration freezes producer factories, consumer IDs and typed (producer, kind, version) routes. IDs are stable operational identities, not context type names or connection strings. One physical source outbox has one producer identity; it must not be aliased under different IDs. Two registered producers can use the same context type in different databases. Each factory receives the provider of a fresh dependency scope, creates a clean context, and transfers its lifetime to the processor. Context factories cannot supply any previously tracked entity, including an Unchanged entry, a current transaction or automatic EF execution-strategy retries: this stage does not permit implicit replay of a handler. IDs have no peripheral whitespace; kind is a literal ordinal string that is not trimmed, matching the writer. Both are nonblank and at most 100 characters. A dedicated drain context can map only the outbox tables in the same producer database/schema without retries; the writer remains in the context of the business fact. Auth's normal context currently enables retries, so simply resolving it is not a supported drain configuration or an Auth migration.

A producer explicitly maps a generic dispatch companion. Before any consumer effect, the processor persists a canonical ordered list of consumers and an immutable event fingerprint. The plan is reused after restart; adding a registration cannot change an existing plan. A missing planned consumer is a visible failure, not permission to omit its effect or rebuild the plan. Empty plans, unknown contracts and invalid payloads cannot be completed successfully. When a message has no matching registered route on its first preparation, the processor freezes an empty plan and finishes it as DeadLettered with OUTBOX_NO_CONSUMERS; FailureCount remains zero because no handler failed. Registering a consumer later does not amend that plan, including an empty one. There is no authorized plan-recovery/replay operation in this processor. A message that remains unprepared while the worker is off has no plan: after a compatible consumer is registered, first preparation can include it. The worker must remain off until route coverage is complete; pending rows still incur storage, index, backup and operational costs.

Tenant Format 1 fingerprints remain byte-for-byte frozen for persisted plans and receipts. Platform uses Format 2, which adds explicit scope. The fingerprint covers the stable producer ID, canonical scope-specific consumer plan, tenant, message/aggregate identity, sequence, kind/version, payload hash, original occurrence and declared author/correlation/causation. Delivery state, priority, attempts, lease and AvailableAt are operational data and do not change the event identity. SHA-256 of the stored JSON is checked before deserialization. The only payload type accepted is the registered one, interpreted using the same default System.Text.Json contract as the writer; no message can select a CLR type or deserializer.

Every tenant destination maps an InboxReceipt keyed by (ProducerId, MessageId, ConsumerId); an explicit platform route maps the separate PlatformInboxReceipt with its platform-execution filter. There is no cross-database foreign key. In an explicit ReadCommitted transaction, an incomplete receipt is inserted with conflict handling before invoking the consumer. Its unique constraint serializes concurrent deliveries. After a competing transaction commits, a new statement can observe that receipt. A matching completed receipt skips the handler; a committed incomplete receipt or a fingerprint/tenant mismatch stops the message visibly, without deleting evidence or replaying.

The handler receives the exact destination context used for that transaction. Its effect and the completed receipt commit together. A confirmed consumer A is skipped when B fails and delivery restarts. There is no distributed transaction or rollback across consumers. The producer is acknowledged only after all consumers in its persisted plan have confirmed receipts.

Lease, clock and failure boundaries ​

The producer PostgreSQL clock is authoritative for availability and lease validity. Fencing, acknowledgment and retry first acquire the source row lock in a short transaction, then check the current time and lease ownership. A timestamp captured before waiting for a lock is insufficient. The source transaction is never held during a handler or destination I/O.

A handler is started only while the producer lease is valid, including a fresh check after a possibly blocking inbox insert. A handler already started under a valid lease can commit late in another database; the receipt prevents another delivery from duplicating its effect. This is not atomic lease validity across databases. The old owner cannot start another handler or acknowledge, retry or otherwise change source delivery state after expiration.

Claim count is diagnostic, bounded against overflow, and is not the failure budget. The generic dispatch companion counts known failed attempts whose destination transaction rolled back. Crashes, cancellation, lost source acknowledgment and uncertain destination commit do not consume that budget. An uncertain commit is checked using a fresh destination context and stable receipt key; it cannot be assumed to mean either rollback or success. Exhaustion cannot preempt recognizing a receipt that has already committed. Failure codes are stable; payloads, exception messages and credentials are not persisted as diagnostic reasons or copied to logs.

An earlier non-completed message blocks later messages in its scope/tenant/aggregate stream, including one waiting for retry or stopped on failure. Tenant and Platform are distinct stream namespaces; Platform requires an empty stored TenantId. Other streams can progress. The stream key is (Scope, TenantId, AggregateId) within one producer outbox, shared across event kinds; the producer chooses the aggregate identity and protects its sequence. This is not global order, and still assumes the producer's sequence matches actual commit order. Stage 2c below adds declared waiting. Alerts, authorized plan recovery/replay/discard and retention remain later operational work.

Userless execution and trusted handlers ​

The public processing entry point starts a task with ExecutionContext flow suppressed, restoring flow before awaiting that task. Scope creation, context factories and handler activation happen inside the isolated task. This removes inherited HTTP identity, ambient transactions and tenancy without adding an ASP.NET dependency or clearing the caller's HttpContextAccessor holder.

A tenant consumer runs in ITenantAmbient for the message tenant, with filters enabled, no group/bypass and strict CurrentTenantOnly optional visibility. A platform consumer runs in ForPlatformExecution() with filters enabled and optional GlobalOnly visibility. Each consumer gets a new scope/context and the snapshot is disposed afterward. CausedBy is declared attribution, never an authenticated principal or permission grant. Tests must prove the permission guard actually ran.

Handlers are trusted application code, not sandboxed plug-ins. They may call SaveChanges but must not begin, commit, roll back, replace or dispose the executor's transaction. They must not perform external I/O or write effects through another context. Transaction ownership is checked afterward; if a handler committed early, the library cannot undo it. An incomplete durable receipt records that contract violation and stops blind replay; it is not an exactly-once guarantee for a hostile handler. Consumer effects outside the supplied transaction remain unsupported.

4b. Opt-in worker and operational query (stage 2b) ​

AddOutboxMessaging remains producer/processor/query composition only. AddOutboxWorker explicitly adds one hosted service, with one independent asynchronous pump per stable ProducerId. Register messaging first; duplicate activation, no producers or invalid settings fail composition. The worker has a single disposable DI owner. Handler scopes use DI-managed asynchronous cleanup.

Each pump calls only ProcessOneAsync, preserving its claim, plan, inbox, tenant and fencing contract. A source with backlog, a blocked consumer or an unavailable database cannot monopolize another source's pump, even when both factories create the same CLR context type. Producer IDs are the scheduling identity. This is fairness between registered producers, not a new fairness promise between priorities within one outbox or discovery of arbitrary tenant databases.

PollInterval defaults to one second and is bounded from one millisecond to one minute; ErrorBackoff defaults to five seconds and is bounded from one millisecond to five minutes. Options are copied at registration. NoMessage waits for polling; an unexpected source exception backs off only that producer. A message result permits another search so a stopped stream does not stop unrelated streams. Source errors and message failures remain distinct diagnostics.

The hosted service retains all pump tasks and awaits Task.WhenAll. Normal shutdown requests cancellation, stops admitting attempts, and observes all cooperative attempts/delays and resource cleanup. No timeout races abandon a live processor task. Handlers/factories must cooperate: .NET cannot forcibly interrupt arbitrary code ignoring cancellation. A canceled host deadline is not proof that work stopped; an orchestrator may terminate the process, and lease/receipt recovery remains the durable mechanism. The worker uses Hosting.Abstractions, without adding ASP.NET to Core.

IOutboxWorkerDiagnostics.GetSnapshot reports local enabled/started/stopping and per-producer state, active attempt, timestamps, last result and stable failure/type metadata. It returns copied, read-only collections. A producer-only host reports Enabled=false; an unobserved pump is not healthy by assumption. This data proves neither remote worker liveness nor database readiness. Backlog remains in producer-owned tables, never in an in-memory delivery ledger.

OutboxOperationsQuery.QueryAsync requires a nonempty tenant, accepts an optional literal ordinal kind and 1–200 message details, and starts no delivery. ConfigureOutboxOperations copies a source timeout, default five seconds, positive and at most one minute. Each producer is observed independently under an isolated ExecutionContext and strict tenant scope. Database operations receive a linked timeout/caller token; all tasks and cleanup are observed. Caller cancellation propagates. Factories must create contexts promptly, without blocking I/O; cancellation is cooperative and cannot impose a hard wall-clock bound on arbitrary factory/disposal code.

Each source uses a PostgreSQL RepeatableRead, READ ONLY transaction for its clock, counts and details. The merged result is best-effort across those source snapshots, not a distributed atomic snapshot. Unavailable/configuration/timeout sources have stable codes, unknown counts and unknown database observation time. Partial=true retains healthy-source observations; unknown is never zero.

The exclusive non-completed buckets have this precedence:

  1. A state other than Pending/Claimed/Sending is Stopped, including dead-letter, reconciliation or an unrecognized state. Completed is excluded before classification.
  2. Claimed/Sending with lease later than source observation time is Running.
  3. Pending with a recorded failure is Failed.
  4. Other Pending/Claimed/Sending rows are Waiting.

Eligibility, expired lease and missing payload are separate flags. Eligible mirrors due/recoverable claim and absence of any earlier unfinished stream row, including predecessors outside a kind filter. Missing payloads use a left join and remain counted in their normal bucket plus an anomaly count; their version, event time and age are unknown. Counts include the full matching backlog, independently of detail limits. Known event times sort oldest first, unknown times last, then ordinal ProducerId and message ID. Each source supplies its top N before the global top N merge; Truncated exposes available results exceeding that limit. Age is nonnegative elapsed time from original OutboxPayload.OccurredAt against the producer database clock, never retry AvailableAt.

Safe logs use technical IDs, fixed codes and exception types only; never exception objects/messages, payloads or credentials. A cleanup failure after a receipt/result was established preserves that result and emits a safe warning; a failing diagnostic sink cannot decide delivery or erase an observation. The query disposes transaction/context/tenant/scope in ownership order.

The host authorizes both operational services; this stage supplies no HTTP endpoint, UI, replay or discard permission. Alerts/readiness adapters, thresholds, retention and remediations remain host operational work. The existing small GetFailuresAsync contract remains available unchanged.

Remaining integration and administration ​

External integrations still require destination idempotency, natural-key reconciliation and a stored ExternalRef; the existing legacy primitive's ReconciliationRequired state is not that adapter. An irreversible source act needs destination preconditions sharing the eventual effect's locking boundary. A read-only check on a stale snapshot is insufficient.

Administrative replay/discard needs explicit authorization and durable attribution; discard needs a reason and cannot masquerade as delivered. A terminal/discard transition must specify how it unblocks ordering. Purge is only for delivered records under a retention policy. Stage 2a's failure query is neither the complete unified operations query nor an HTTP authorization boundary.

4c. Declared consumer waiting (stage 2c) ​

A trusted local consumer may declare OutboxDeferredException(code, delay) without changing its Task handler interface. The code is an ordinal ASCII constant matching [A-Z][A-Z0-9_]{0,99}; delay is from one millisecond to 24 hours inclusive per declaration. No trimming, rounding, truncation or free-text error is accepted. The exception message is fixed and has no inner-error constructor. Syntax cannot prove that a code contains no sensitive data: the consumer must define stable application constants, not encode payloads, personal identities or exception text. The upper delay bounds technical re-evaluation, not a business deadline; the condition may be declared again if it remains unresolved. AvailableAt is earliest eligibility, not an execution SLA.

The typed signal is recognized only around HandleAsync, after deserialization and DI activation. An exception of that public type from factory/activation or the executor's own save/commit/cleanup is not a waiting request. No inner-exception unwrapping turns arbitrary infrastructure failure into a declaration. This is the boundary of the awaited handler call, not a sandbox: a typed exception propagated from a call the handler itself makes is inside that boundary. The executor cannot identify its physical origin deeper in that call stack. Trusted handlers retain the existing transaction and external-I/O restrictions.

The destination reservation and every effect staged or saved by the handler are explicitly rolled back together. Only a successful rollback permits a deferred outcome. Transaction replacement or early commit still yields TransactionChanged; declaration cannot retroactively undo an effect. Rollback or commit uncertainty uses a new context and the existing receipt protocol. A matching completed receipt wins; incomplete or conflicting receipts stop replay. An absent receipt remains CommitUncertain, not proof that every effect rolled back. Cancellation before a confirmed source transition propagates and leaves recovery to the lease, without consuming a known-failure budget.

After rollback, a dedicated source transition locks the message, checks ownership using a new PostgreSQL clock statement, writes the waiting metadata and clears the lease. The final message update repeats the time/lease fence, even after updating the companion: a lock wait there may expire ownership. If that update loses ownership, the whole source transaction rolls back, including its companion changes. No waiting reason or retry time is written by a stale owner. The source uses clock_timestamp() plus the parameterized delay; no client time authorizes it.

Three nullable companion fields hold the current declaration: LastDeferralCode (100), LastDeferredConsumerId (100) and DeferredAt. OutboxMessage.AvailableAt is the retry time; there is no duplicated stored deadline or new message state. Existing producer schemas must migrate those columns before enabling this processor/query version. Do not automatically alter schemas or migrate unadopted Auth/Files/Notifications models. An incomplete deployment is not supported by hiding missing-column errors or guessing older storage contracts.

Deferral preserves FailureCount, frozen consumers, fingerprint and original occurrence. It clears LastFailureCode, LastConsumerId and FailedAt in the same fenced source transaction: these describe the current diagnosis, not an append-only error history. Thus the failure query stops listing a currently waiting message, while its accumulated real-failure budget remains. The next real failure can exhaust that budget. Any confirmed non-deferred finalization clears the three waiting fields; claim/prepare alone does not clear them. Metadata, delay and availability never enter the immutable fingerprint or invalidate earlier consumers' receipts.

Deferred is appended to the public enum, preserving existing numeric values. The positional constructor/deconstruction of OutboxProcessResult remains unchanged; optional init properties expose DeferralCode, DeferredConsumerId, DeferredAt and DeferredUntil. Values come from the persisted source row, with null FailureCode. LeaseLost does not claim a declaration was stored. The message observation adds the same properties without changing its positional constructor. Its DeferredUntil mirrors AvailableAt only when there is a recorded declaration.

Waiting uses the existing exclusive bucket precedence: active lease is Running; stopped states are Stopped; pending recorded failure is Failed; remaining pending work is Waiting. A declaration has no current failure code. It retains its original OccurredAt/Age and the existing tenant/kind, snapshot and top-N semantics. During an active attempt, the prior declaration remains diagnostic until a confirmed result replaces it. There is no timer per message: the worker searches other eligible work and polls normally when none remains. A waiting predecessor still blocks its stream.

Outcomes established before cleanup must survive it, both in the destination and in source finalization. The source records terminal confirmation only after its commit returns, before transaction/context/scope disposal. A later cleanup or logger exception cannot turn that confirmed result into a different delivery decision. A commit that throws never creates confirmation from an assumed database outcome; durable state and lease recovery remain authoritative.

This mechanism is not banking cooling-off, previous-account selection, remote-effect reconciliation, global-owner resolution, administrative replay, a new alert/UI or full CA-18/CA-27/P1 acceptance. Each migrated application condition still needs its own authorization and real-database proof.

4d. Auth membership Audit integration (stage 3b.1b) ​

The additive pilot keeps Auth security effects and synchronous audit in place. Its explicit membership producers are defined in the Auth guide. Hosts register both the source drain and mandatory Audit route on their existing builder:

csharp
services.AddOutboxMessaging(outbox =>
    outbox.AddAuthMembershipAuditIntegration("auth-main",
        (_, source) => source.UseNpgsql(authConnection),
        (_, audit) => audit.UseNpgsql(auditConnection)));
services.AddOutboxWorker(); // Explicit opt-in on the selected drain host.

Import GrydAuth.Infrastructure.Messaging. Supply the effective host-owned PostgreSQL options; the databases may differ. The integration infers no settings or credentials from the writer. Its fresh source context maps only auth_outbox; delivery uses a fresh Audit context. Both require TrackAll, an empty tracker, no existing transaction and no automatic EF retries. External data sources remain host-owned. Writer and access/MFA reader pools are unchanged.

Apply Auth and Audit migrations before writers/workers. Keep one stable ProducerId per physical outbox and retain the fixed consumer ID audit.auth-membership-v1 across replicas/deployments. Moving destination storage requires preserving receipts. The combined registration must succeed as a whole; do not swallow composition errors and run a partially configured builder. Empty Core routes fail permanently rather than waiting for a later registration.

V1 requires all ten properties and rejects unknown JSON members. Semantic validation checks the event/message/stream identity, positive sequence, state transition, UTC occurrence and declared author. Tenant must agree across payload, envelope, session and Audit context before Add. Missing or extra fields fail deserialization; semantic handler failures use the existing retry budget.

The executor commits audit.inbox_receipt and the Audit effect in the same destination transaction. The handler only adds its effect to that context. A completed matching receipt prevents replay, including recovery after destination commit and before source acknowledgment; it does not make HTTP command reconstruction idempotent or introduce a cross-database transaction.

The effect is AuthTenantMembershipTransition, with its own random AuditLog.Id and message ID as EntityId. Activation/deactivation actions explicitly describe integration receipt. Actor is System, routine GrydAuth membership integration; original actor and source time are additional data, never an inherited principal or a personal-activity record. The metadata is closed and bounded to 8000 characters; correlation is at most 64, refused rather than truncated. Existing tenant-only Audit reads and operation-tenant writes remain in force. No metadata search is added.

This record supplements the current source trail. It cannot recover a synchronous audit entry lost under the existing fail-open policy, replace the P4 source record, or close P1/P4/P16, CA-06 integral or CA-22–24. AdminDevHost supports an explicit, default-off host setting; see its instructions.

4e. Explicit platform scope and receipts (OUT-09/10) ​

The earlier tenant-only decision is retained as the compatibility default, not as a permanent claim that platform messages are unsupported. OutboxScope is persisted explicitly; Tenant remains value 0/default, Platform is a distinct value, and Guid.Empty is valid only when Scope is Platform. There is no inference from empty identity. The tenant writer rejects Platform; the opt-in platform writer requires an explicit platform execution snapshot with filters enabled, no tenant/group/set scope, and host composition. That snapshot is execution context, not authentication. The host authorizes access and opts producers/routes in.

Platform local consumers use a separate PlatformInboxReceipt. Its context-bound query filter requires ITenantQueryContext.IsPlatformExecution; runtime validation rejects missing filters or mappings. Tenant routes continue using required-tenant InboxReceipt, and cannot query the platform receipt through EF. A shared producer may register both scope-specific routes; each persisted plan selects only its scope. Platform streams have their own ordering namespace. Tenant Format 1 fingerprints and receipts remain unchanged; Platform Format 2 includes the explicit scope. Migrations add Tenant-defaulted Scope and a pairing constraint in each producer schema. Notifications alone backfills its documented legacy empty TenantId rows as Platform; other contexts do not infer scope from existing data. Apply migrations before composing platform writers or consumers. This stage does not add a broker, external-effect handler, automatic host authorization, operations endpoint, or P1/CA acceptance.

4f. External destination idempotency (A1.6): amendment, not implemented ​

This amendment fixes the contract of a future delivery to a system outside the producer's control. Nothing is implemented now. Trigger: the first real external integration; until then, no adapter, port or column ships.

  • Separate port (ISP). An external delivery does not extend ILocalOutboxConsumer. A local consumer commits its effect and its receipt in one transaction; an external destination cannot share that transaction, so the two contracts promise different things and stay apart.
  • Stable key. Each attempt carries ProducerId + MessageId + ConsumerId, unchanged across retries and restarts, as the destination's idempotency key where it offers one.
  • Query before resend. Before any resend, the adapter queries the destination by natural key. A found document ends the delivery without creating another.
  • Durable ExternalRef. The destination's reference is persisted with the receipt, in the local transaction that follows acceptance.
  • Uncertain state. A timeout or a death after sending is Uncertain, not failed. It never retries blindly: it waits for the natural-key query to resolve it, or for an authorized operator's decision.
  • Future proof. A fictitious destination that dies after accepting must prove one remote document and one stored ExternalRef (CA-20), and resumption by reconciliation without a duplicate (CA-21). Both stay open.

5. Database topology and operations ​

There is no central connection requirement in the writer: two product contexts can stage records in separate databases. Every registered producer database must eventually have a drain and expose its health; successful writing in a second database is not CA-25 delivery proof.

ADR 0011 D24 removed speculative database-per-tenant/module routing. This ADR does not restore it, remove Nexio's scale step 4, or claim it has been validated. Before full messaging adoption, the product architecture must reconcile that requirement with ADR 0011 and prove two independently owned producer databases are drained (CA-25), or explicitly revise the product requirement.

The operational contract is one logical query for waiting, failed and stopped work, filtered by tenant and kind, with oldest age. It must aggregate registered producers without inventing a second source of delivery truth. Stage 2b provides that read-only fan-out query. Alert thresholds and authorized remediation remain pending.

6. Delivery stages and cost ​

StageScopeExit evidence
Foundation (OUT-01/OUT-03)ADR, explicit producer contract, companion persistence and atomic staging in a product context independent of AuthReal PostgreSQL tests for atomic save, rollback, explicit transaction ownership, failed-write retry and validation; no consumer-dispatch claim
Explicit processor and inbox (2a, OUT-04/OUT-05)Manual local PostgreSQL delivery, tenant isolation, per-consumer receipts, frozen plans, retry/order and minimum failure queryReal-database tests establish these mechanisms; no claim of default-host coverage, continuous drain or full operational acceptance
Platform scope (OUT-09/10)Explicit Tenant/Platform discriminator, opt-in writer/routes, isolated platform receipts and scope-partitioned streamsPostgreSQL tests cover platform delivery, tenant receipt isolation, route plans, replay and legacy tenant fingerprint compatibility; host authorization and production adoption remain separate
Worker and draining (2b)Explicitly enabled continuous worker, independent producer progress and recovery, healthAutomatic recovery/drain and fairness evidence; two producer databases deliver under the running worker
Declared waiting (2c)Typed local condition, confirmed rollback, fenced source reason/due time and queryRepeated waiting above MaxFailures; rollback, uncertainty, order and recovery; real errors retain accumulated budget
Adoption (OUT-02/OUT-06)Classify existing handlers; preserve transactional invariants; migrate actual producers onto the proven processorCA-01/02/04/06 and CA-22/23/24 for migrated paths; architecture guard that really covers those paths
Product integrations and operational acceptanceWaiting domain conditions, destination idempotency/reconciliation, topology decision and runbookCA-17/18/20/21 and CA-27, plus complete CA-01–26 evidence

Handler classification can start during foundation planning; runtime migration follows the processor and receipt stages, so an adopted producer is never presented as deliverable without a drain.

With the worker disabled, the foundation adds zero running components and reuses the existing PostgreSQL operation. Retained pending rows still consume storage, indexes, backups and query capacity. Budget one engineer-hour per month for checking retained-row growth, pending age and maintenance logs once a producer is enabled. This is an engineering estimate, not measured production evidence. Before delivery is enabled, budget two engineer-hours per month for worker/dead-letter review, reconciliation and retention checks; record actual measurements after the first month. These estimates exclude incident response and product-specific external reconciliation. No additional broker operation is budgeted. Revisit them if a transport or database topology adds services.

CA-27 is not closed by these estimates: it also requires the complete real-database acceptance report. A partial green suite must not be described as acceptance of messaging as a whole.

Baseline evidence reconciliation ​

The following rechecks refer to the baseline commit above. Historical evidence remains historical; these updates do not edit the original Nexio requirement or mark its criteria passed.

OriginalBaseline recheck
E-01Still applies: Auth saves, dispatches, saves again and only then commits in Data/GrydAuthDbContext.cs.
E-02Changed: Auth now poisons the context once work starts and fails; caller must reconstruct work in a new context. See AuthSaveChangesRetrySafetyTests; do not copy the historical retry recipe.
E-03Superseded: ADR 0011 D19 made reads fail closed and removed RequireTenantOnRead. Module FailClosedTenantFilterTests cover the behavior.
E-04Superseded in the shared job adapter: JobExecutionService begins TenantAmbientScope from the scheduling envelope's tenant. This does not prove every job body is scoped correctly.
E-05Still partial: Notifications has opt-in DurableDelivery, with RunBackgroundServices controlling its worker. Not generic event delivery.
E-06Notifications scheduling and GrydJobs still exist; their presence alone is not atomic enqueue in another context.
E-07The Notifications processor now uses ITenantAmbient with a strict DurableTenantSnapshot. A generic consumer entry point and executed-guard tests are still required.
E-08Core claim still blocks behind any earlier non-completed row. Generic multi-worker acceptance is not supplied by a writer.
E-09Bank-account waiting semantics belong to the Nexio integration; no generic Core implementation satisfies them.
E-10Core still moves uncertain external Sending rows to ReconciliationRequired; product natural-key reconciliation/ExternalRef remains separate.
E-11Still critical: AuthorizationAffectingEventHandler changes the user's token version within Auth's transaction loop. Preserve it until an atomic replacement exists.
E-12Historical hybrid routing was removed by ADR 0011 D24. Multiple independently owned contexts are possible, but routing and universal draining have not been proved.
E-13No general operational query or full operational acceptance exists. This decision avoids adding a broker/framework before delivery requirements are proven.
E-14The flow-dependent switch and old filter accessor were removed. FileScanJob still opens a system scope for the entire scan and uses IgnoreQueryFilters; per-file tenant execution remains pending.

Consequences ​

  • A product can adopt durable intent without referencing Auth or extending Notifications' schema.
  • No consumer, external effect or worker is started by registering a writer.
  • Each producer owns migrations, retention and sequence/concurrency discipline.
  • There is temporarily an explicit distinction between the legacy transactional Auth dispatch and new durable intent. The distinction must remain visible until migration is proven.
  • Foundation stores intent; 2a supplies transactional local consumption, 2b explicit continuous delivery/observation and 2c declared waiting. Product adoption, operational screens, global messages and external adapters remain distinct work.

Acceptance ledger ​

The IDs below refer to Nexio's mensageria.html v1.6. “Required” describes exit evidence, not a claim that every criterion exists or passed. Stage 2a contributes explicit local-processing tests; continuous drain, default-host composition and product adoption require their own evidence. Existing Notifications and tenancy tests cover useful specialized behavior; they do not close a generic messaging criterion. Attach real-database run evidence to the implementing PR for each applicable stage. Permission/tenant/order tests must assert that the relevant guard or consumer actually executed, not merely that no unwanted result appeared.

CriterionRequired proof and implementation stage
CA-01Foundation: business rows and staged intent disappear on rollback. Adoption/delivery: consumer invocation count remains zero for that rollback.
CA-02Delivery: consumer reads the confirmed aggregate through a separate unit of work, never an uncommitted/old snapshot.
CA-03Delivery: consumer exception leaves original commit and caller success intact, with durable failure state and a metric.
CA-04Adoption: an architecture gate rejects pre-commit reaction publication in all migrated platform/product paths; preserve explicitly transactional invariants. Proved by OutboxMigratedPathsArchitectureTests over build/outbox-migrated-paths.json, a growing list with a floor; TokenVersion is the declared exception.
CA-05Delivery: terminate after commit and before dispatch; restart drains the same durable intent.
CA-06Foundation reconstruction is partial proof. Adoption/delivery must actually retry through an execution strategy after event collection, with fresh-context reconstruction and stable captured identity/body, then consume every fact without loss.
CA-07Delivery: same message to same consumer twice commits one effect and one durable receipt.
CA-08Notifications/delivery: two worker replicas send one scheduled notification; writer tests are insufficient.
CA-09Notifications/delivery: restart drains immediate and due notifications, never future ones early.
CA-10Delivery: no-tenant job and consumer query two populated tenants and receive no tenant rows (or fail). Proven by BackgroundTenancyPostgresTests.CA10_a_job_and_a_consumer_with_no_tenant_read_no_tenant_row.
CA-11Delivery: successive executions for A and B each see only their tenant and restore ambient state. Proven by BackgroundTenancyPostgresTests.CA11_successive_executions_see_only_their_tenant_and_restore_the_context.
CA-12Delivery: default API, Worker and Portal configuration remains fail closed in request, job and consumer execution flows. Proven by FailClosedProfilesPostgresTests.CA12_the_default_profile_is_fail_closed_in_request_job_and_consumer for the web, worker and template profiles.
CA-13Delivery: declared source-user ID cannot authorize a service act; assert the permission guard executes.
CA-14Delivery: four workers cannot overtake a retrying earlier message of the same stream.
CA-15Delivery: exhausted earlier message stops the stream and produces an alert.
CA-16Delivery: a stopped stream does not stop another stream.
CA-17Product integration: during bank-account cooling-off, an outbound package uses the previous usable account.
CA-18Product integration: no usable account leaves a visible waiting reason; becoming usable resumes automatically.
CA-19Operations: replay/discard requires permission; discard requires a reason; actor is recorded durably.
CA-20Product integration: duplicate ERP delivery creates one remote document and one stored ExternalRef.
CA-21Product integration: death after remote acceptance resumes by natural-key reconciliation, not duplicate creation.
CA-22Auth adoption: old token is rejected immediately after committed revocation.
CA-23Auth adoption: forcing every post-commit consumer to fail does not restore access.
CA-24Auth adoption: rollback leaves token version and prior token validity unchanged.
CA-25Topology/delivery: two contexts in separate databases for one tenant each deliver; a writer in two databases is only partial proof. Reconcile ADR 0011 D24 first.
CA-26Operations: one logical query returns waiting/failed/stopped work by tenant/kind and oldest age.
CA-27Operational acceptance: record components and engineer-hours/month, plus complete CA-01–26 real-database evidence. Estimates in ADR 0012 are not that report.

Foundation closes storage; 2a adds explicit local consumption and 2b adds opt-in continuous delivery/observation mechanisms; 2c adds the declared-waiting primitive. OUT-02 adoption and complete A1.1/A1.2 acceptance remain separate. Consult the implementation PR for actual run evidence; this ledger never substitutes for the full CA-01–26 report.

Appendix: complete producer composition ​

This complete example is linked from the producer guide.

csharp
using Gryd.Application.Abstractions.Tenancy;
using Gryd.Domain.Abstractions;
using Gryd.Infrastructure.Messaging;
using Gryd.Infrastructure.Tenancy;
using Microsoft.EntityFrameworkCore;

public sealed record RequisitionApproved(Guid RequisitionId, decimal ApprovedAmount);

public sealed class ApprovedRequisition : IRequireTenant
{
    public Guid Id { get; set; }
    public Guid TenantId { get; set; }
    public decimal ApprovedAmount { get; set; }
}

public sealed class PurchasingDbContext(
    DbContextOptions<PurchasingDbContext> options,
    ITenantSession tenantSession) : DbContext(options), ITenantQueryContext
{
    public DbSet<ApprovedRequisition> Requisitions => Set<ApprovedRequisition>();

    protected override void OnConfiguring(DbContextOptionsBuilder builder)
        => builder.AddInterceptors(new TenantSaveChangesInterceptor(tenantSession));

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<ApprovedRequisition>().HasKey(row => row.Id);
        OutboxMessage.Configure(modelBuilder.Entity<OutboxMessage>(), "purchasing");
        OutboxPayload.Configure(modelBuilder.Entity<OutboxPayload>(), "purchasing");
        OutboxDeliveryState.Configure(modelBuilder.Entity<OutboxDeliveryState>(), "purchasing");
        modelBuilder.ApplyTenantQueryFilters(this);
        modelBuilder.ProtectTenantWrites();
    }
}

public static class ApprovalProducer
{
    // The caller constructs the stable envelope once, before any retry delegate.
    public static async Task WriteAsync(
        PurchasingDbContext context,
        ITenantSession tenantSession,
        OutboxEnvelope<RequisitionApproved> envelope,
        CancellationToken cancellationToken)
    {
        await using var transaction =
            await context.Database.BeginTransactionAsync(cancellationToken);
        context.Requisitions.Add(new ApprovedRequisition
        {
            Id = envelope.AggregateId,
            TenantId = envelope.TenantId,
            ApprovedAmount = envelope.Payload.ApprovedAmount,
        });
        var outbox = new TransactionalOutbox<PurchasingDbContext>(context, tenantSession);
        outbox.Enqueue(envelope);
        await context.SaveChangesAsync(cancellationToken);
        // Another context cannot consume the intent before this commit.
        await transaction.CommitAsync(cancellationToken);
    }
}

Appendix: complete local consumer composition ​

This companion to the producer guide uses its PurchasingDbContext and RequisitionApproved types. The consumer inserts one local row in the executor's transaction; it is an infrastructure example, not a budget domain model.

csharp
using Gryd.Application.Abstractions.Tenancy;
using Gryd.Domain.Abstractions;
using Gryd.Infrastructure.Messaging;
using Gryd.Infrastructure.Tenancy;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;

public sealed class ReservedApproval : IRequireTenant
{
    public Guid Id { get; set; }
    public Guid TenantId { get; set; }
    public decimal Amount { get; set; }
}

public sealed class AccountingDbContext(
    DbContextOptions<AccountingDbContext> options,
    ITenantSession tenantSession) : DbContext(options), ITenantQueryContext
{
    protected override void OnConfiguring(DbContextOptionsBuilder builder)
        => builder.AddInterceptors(new TenantSaveChangesInterceptor(tenantSession));

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<ReservedApproval>().HasKey(row => row.Id);
        InboxReceipt.Configure(modelBuilder.Entity<InboxReceipt>(), "accounting");
        modelBuilder.ApplyTenantQueryFilters(this);
        modelBuilder.ProtectTenantWrites();
    }
}

public sealed class ReserveBudgetConsumer :
    ILocalOutboxConsumer<AccountingDbContext, RequisitionApproved>
{
    public Task HandleAsync(AccountingDbContext context, RequisitionApproved payload,
        OutboxDeliveryContext delivery, CancellationToken cancellationToken)
    {
        context.Set<ReservedApproval>().Add(new ReservedApproval
        {
            Id = delivery.MessageId,
            TenantId = delivery.TenantId,
            Amount = payload.ApprovedAmount,
        });
        return Task.CompletedTask; // The executor saves effect and receipt, then commits.
    }
}

public static class OutboxComposition
{
    public static void Register(
        IServiceCollection services,
        DbContextOptions<PurchasingDbContext> sourceOptions,
        DbContextOptions<AccountingDbContext> destinationOptions)
    {
        services.AddOutboxMessaging(builder =>
        {
            builder.LeaseDuration = TimeSpan.FromMinutes(2);
            builder.RetryDelay = TimeSpan.FromSeconds(5);
            builder.MaxFailures = 3;
            builder.AddProducer<PurchasingDbContext>("purchasing", createContext: sp =>
                new PurchasingDbContext(sourceOptions, sp.GetRequiredService<ITenantSession>()));
            builder.AddLocalConsumer<AccountingDbContext, RequisitionApproved,
                ReserveBudgetConsumer>("purchasing", "accounting.reserve-budget",
                "requisition.approved", 1, createContext: sp =>
                    new AccountingDbContext(destinationOptions,
                        sp.GetRequiredService<ITenantSession>()));
        });
    }
}

Updated at:

Released under the MIT License.