Dispatch snapshot and deduplication contract
Status: proposal for discussion; not implemented. The structures and names
below are conceptual. They are not a Ruby API, database schema, externally
stable contract, or permission to send. Existing DeliveryTesting simulations
remain separate and do not implement this production contract.
Purpose and boundary
Section titled “Purpose and boundary”A product authorizes a request, selects the intended channel and message, and chooses explicit policies. Core creates an immutable record of the selection and logical deliveries. Channel-specific code assesses destination values; a transport adapter later submits a delivery. A second product must be able to use Core without loading Visitor.
The first proposed version handles one channel per dispatch. A recipient may have zero, one or multiple active destinations for that channel. A destination may be shared by multiple recipients; separate destination records may also have the same normalized value. A logical delivery is not a network attempt: it can have multiple attempts. No transport is performed when the snapshot is created.
Proposed command
Section titled “Proposed command”The product supplies, after authentication and authorization:
| Input | Meaning |
|---|---|
| Tenant and authorized actor | Identifies the organization and who requested the operation. Neither is trusted merely because it appears in the input. |
| Selection command | Product selection criteria or explicit recipient IDs, with a generic resolved selection passed to Core inside the transaction. The exact API remains to be designed. |
| Channel | Exactly one channel identifier in this version. |
| Content | Immutable channel-specific message input, including a versioned format. Email fields, for example subject and body, have not yet been specified. |
| Deduplication policy | Explicitly chosen grouping policy and version; no implicit global Core default. |
| Exclusion policy | Explicitly specifies behavior when recipients are missing a destination or values are invalid. Exact decisions and confirmation behavior remain open. |
| Idempotency key | Stable operation key supplied by the product, scoped to the tenant and operation. The proposed lifecycle and fingerprint are described below. |
A successful result identifies the committed dispatch and its frozen selection and delivery summary. It never means that a provider accepted or that a person received the message. An idempotent retry of the same command returns the original result, even if presence or contacts have changed since. Reusing a key for a materially different canonical command is a conflict. The canonical command excludes newly evaluated recipient results, otherwise a retry could incorrectly create a new dispatch after a contact change.
Proposed product-to-Core selection boundary
Section titled “Proposed product-to-Core selection boundary”The product orchestrates the transaction: authenticate the actor, start a
tenant-scoped REPEATABLE READ transaction, establish tenant context, check
permissions, resolve its selection, then call Core to create the dispatch. Core
does not call Visitor or execute a product-supplied query or callback. All reads
and writes in this sequence use the same transaction and connection; results are
provisional until commit.
The conceptual resolved selection consists of:
- selected recipient IDs referring to recipients in the current tenant;
- zero or more selection reasons per recipient, each a typed, versioned source reference identifying why that recipient was selected. A reason may identify a generic resource and resource link, or an explicit selection;
- selection source/policy metadata needed to explain the selection, subject to data minimization and the eventual retention rules.
These are data values, not trusted evidence of permission. The product checks authorization and owns the meaning and legitimacy of its source references; Core verifies its transaction/tenant context and the existence and tenant ownership of every recipient, failing the whole command for missing or foreign IDs. For Core-owned resource links, Core must also validate the link’s tenant, recipient and resource relationship rather than accept arbitrary associations. Validation for other source types and the precise reference schema remain to be designed. Tenant isolation is not a substitute for product authorization.
Visitor can resolve active resource links for authorized locations and pass one reason for each link. A second product can pass explicitly selected recipients without creating fictitious locations or Visitor records. For example, if Anna is linked to resources A and B, her recipient ID is resolved once for destination lookup, but both reasons remain in the snapshot and are associated with each applicable delivery. Two distinct links must not be silently collapsed into one reason. Destinations, their assessment and the grouping policy are Core/channel concerns, not a way to infer person identity.
The existing Core::RecipientSelection returns resource-link entries including
legacy phone fields; Core::DestinationSelection returns channel destinations
per unique recipient, but does not preserve those link reasons. Neither is the
proposed dispatch interface. The latter currently limits input to 1,000 IDs;
batching or a different selection mechanism and its consistent-snapshot behavior
must be designed rather than silently truncating larger selections. Empty
selections, source-reference limits and validation errors also need an explicit
contract.
External directories, imported lists and booking systems are future selection sources, not implemented integrations. The first proposed boundary refers to recipients already stored in Core. A future synchronization could materialize external data before this transaction, with freshness reported separately; a live external API read cannot share the PostgreSQL snapshot. Identity matching, sync failure and freshness semantics require their own design. Source integrations select or import recipients; transport adapters submit deliveries.
For idempotency, distinguish the stable original selection criteria supplied in the command from the resolved recipient IDs and reasons. A repeated key for an already committed command returns the original snapshot even if a fresh resolution would differ. The exact canonicalization, authorization on replay and handling of concurrent same-key requests remain open; the conceptual resolved selection above must not accidentally become the retry fingerprint.
Proposed dispatch creation idempotency
Section titled “Proposed dispatch creation idempotency”The principles below are agreed design direction, not an implemented API or delivery guarantee. It covers creation of one dispatch and its durable handoff, not provider submission or delivery. A new intentional dispatch uses a new key even when its inputs are identical. A repeated key can never be used to mean “send again”.
Key and command identity
Section titled “Key and command identity”- The product creates and durably retains a key for each intentional confirmation before asking Core to create the dispatch. It retains that key across retries, page reloads and recovery. A cryptographically random UUID is proposed; the precise product-side lifecycle still needs implementation design. Generating a new key on every HTTP request is insufficient. A key alone is not authorization.
- Scope uniqueness to
(tenant, operation, key), enforced by the database. The actor is stored for audit and authorization but is not part of the uniqueness scope, so another actor cannot accidentally create a second dispatch by replaying the same key. Returning an existing result requires current authorization to access it; the detailed role policy remains open. - Store a versioned fingerprint of the original command, including tenant and operation, channel, exact versioned content, original selection criteria, and explicit deduplication and exclusion policies and versions. Normalize only fields with explicitly defined semantics (for example sort and dedupe an unordered set of selected IDs); preserve meaningful content differences. Bind the product and selection type/version to avoid cross-product ambiguity. Actor treatment in the fingerprint, exact fields and canonical encoding need review. Do not include resolved recipients, destinations or preview counts.
- Fingerprints and keys are sensitive operational metadata. Avoid logging message content, contact information or canonical input. A plain hash of low-entropy inputs may leak information; choose storage and keying as part of the security design rather than assuming a hash makes data anonymous.
Results, concurrency and recovery
Section titled “Results, concurrency and recovery”Write the idempotency record, frozen dispatch and durable handoff in one transaction. The proposed outcomes are:
| Situation | Result |
|---|---|
| Same key and same command already committed | After authorization, return the original dispatch and its original frozen result. Do not recalculate recipients or enqueue a second handoff. |
| Same key, materially different command | Return a conflict; do not modify the existing dispatch. |
| Different key | A separate intentional command, even when the content and selection are the same. |
| Validation or transaction fails before commit | No dispatch or handoff was committed by that transaction. Retrying the same command with the same key is permitted. |
| Commit outcome is unknown | Report an uncertain outcome. Recover using the same key and command; never create a replacement key automatically. |
Concurrent same-key attempts must be serialized by a tenant-scoped unique
database constraint, not a preliminary existence check. Under REPEATABLE READ,
the losing transaction may not see the winner in its existing snapshot and may
receive a uniqueness or serialization failure. Roll it back and resolve the key
in a fresh tenant-scoped transaction, then compare the fingerprint and
authorize access. If the winner rolled back, a bounded retry can attempt the
original command again using the same key. If the outcome cannot be established,
keep it uncertain; no external provider call belongs in this flow.
Do not silently expire a key while the corresponding dispatch can still be retried or while its result must remain recoverable. The exact retention period, deletion behavior and whether a minimal tombstone can outlive dispatch content remain open privacy and product decisions. Until a safe policy is defined, automatic expiry or key reuse is not part of the initial design.
Before implementation, test sequential and simultaneous same-key requests, changed-command conflicts, independent tenants, rollback, serialization failures, a lost response after successful commit, an ambiguous commit, revoked permissions and recovery after process restart. Verify that exactly one dispatch and durable handoff are committed for a successful key. This does not prove exactly-once delivery to a provider.
Snapshot contents
Section titled “Snapshot contents”The proposed frozen record contains:
- tenant, channel, actor, creation time, content and content format/version;
- selection source and policy identifiers/versions sufficient to explain it;
- each selected recipient identity and, where applicable, each selected resource-link identity that explains why they were included;
- each applicable recipient–destination association, destination ID if it exists, original and normalized values used, normalization version and the channel assessment;
- explicit missing or excluded entries and reasons, including recipients with no active destination for the chosen channel;
- associations from each logical delivery to every contributing snapshot entry.
Exact schema, resource display-name retention, access control, data minimization, retention and deletion remain design work. Snapshot data must be protected as sensitive information. Immutability means history is not silently rewritten while retained; it does not mean indefinite retention or exemption from a separately designed deletion policy.
At confirmation, current authorized state is selected and frozen. Editing, unlinking or deactivating a destination after commit cannot rewrite the frozen address or its existing logical deliveries. A changed preview does not by itself block an incident confirmation; however, the system must report the actual committed selection and exclusions, not claim that the earlier preview was the final one.
Proposed grouping policies
Section titled “Proposed grouping policies”Grouping is over valid, active destination associations for the one selected channel, using the channel-assessed normalized value rather than destination record ID. Every contributing association remains traceable in the snapshot. Missing, inactive or invalid associations never become successful deliveries.
per_destination: one logical delivery per distinct(channel, normalized destination)in this dispatch. Different destination records with equal normalized values are grouped. A recipient with two different destinations contributes to two deliveries. All recipients and source links behind each group remain associated with it.per_recipient_destination: one logical delivery per distinct(recipient, channel, normalized destination). Multiple resource links or duplicate destination records for the same recipient and value do not create extra deliveries. Different recipients sharing the value each get a delivery. A recipient with two distinct destination values gets two.
The product can explicitly select a subset of a recipient’s destinations before
creating the dispatch. Core must not silently choose an arbitrary address. The
agreed rule is one delivery for each selected, distinct normalized destination
per recipient under per_recipient_destination; a separate exactly-one-per-
recipient policy would require an explicit destination-choice rule and is not
part of this proposal.
The product chooses policy per dispatch. per_recipient_destination can send
multiple messages to a shared mailbox; per_destination intentionally sends
one. Neither grouping policy asserts that recipients have read or understood a
message. For channels where per-recipient personalization changes content,
grouping rules must also account for message content; personalized content is
outside this first proposal and must not be silently combined.
Worked examples
Section titled “Worked examples”Two people share one mailbox
Section titled “Two people share one mailbox”Anna and Erik each have the active email [email protected]. They may link
to the same destination record or two separate records with the same
normalized value. The snapshot retains both people and both associations.
| Policy | Logical deliveries | Traceability |
|---|---|---|
per_destination |
1 | The delivery references Anna and Erik’s snapshot associations. |
per_recipient_destination |
2 | One delivery references Anna’s association; the other references Erik’s. |
One person, two email addresses and two resources
Section titled “One person, two email addresses and two resources”Anna is selected through resource A and B and has active [email protected] and
[email protected]. The snapshot retains both resource links and both destination
associations. Under either policy, there are two logical deliveries,
one per distinct address; each delivery retains the relevant source links. If
the product instead wants just one address per person, it must explicitly
choose how before dispatch creation. No automatic single-address selection is implied.
Missing, inactive and invalid addresses
Section titled “Missing, inactive and invalid addresses”Anna has a valid active email, Erik has only an inactive email, and Sam has no
email. The intended snapshot includes Anna and her destination, plus explicit
missing/excluded records for Erik and Sam. Whether the distinction between
inactive and absent is retained and how much is exposed to the operator need
an explicit product/privacy decision. Only Anna can contribute a delivery.
Current Core::DestinationSelection returns no active destination for both
Erik and Sam and cannot distinguish those reasons.
If a stored address fails the channel’s dispatch-time assessment, the snapshot must retain that issue if the chosen exclusion policy permits a dispatch. Current destination creation normally rejects invalid values, but imported, legacy or subsequently invalid data can still require a defined policy. The operator’s prior choice and handling of newly invalid destinations at final confirmation remain open. Do not equate any exclusion with delivery.
Editing after confirmation
Section titled “Editing after confirmation”After a committed dispatch, Anna changes or disables her address. The frozen dispatch and its logical delivery still describe the address selected at confirmation. A later dispatch performs a new selection and may use a different address or report it missing. The product cannot silently rewrite the earlier message or destination.
Atomicity and concurrency requirements
Section titled “Atomicity and concurrency requirements”The agreed direction is one tenant-scoped PostgreSQL REPEATABLE READ
transaction. Start it at that isolation level before any query, establish the
tenant context, check the relevant authorization, and resolve the product’s
selection and Core destinations in the same transaction. Store the snapshot,
exclusions and logical deliveries with their associations. A durable worker
handoff also needs to be recorded atomically; its design remains open.
The transaction reads from one database snapshot, not necessarily the exact
instant the operator pressed confirm. PostgreSQL establishes its snapshot at
the first non-transaction-control statement; setting tenant context with
SELECT set_config(...) can therefore establish it before selection. Data
committed after that point is not included, even if it commits before this
transaction does. The transaction sees its own writes. This is a consistent
snapshot, not a guarantee of the latest state at commit or serializable
execution. Normal check-ins, checkouts and edits must not be blocked merely to
hold the selection stable.
TenantContext.with(tenant_id, isolation: :repeatable_read) can start the
transaction at the required isolation level before its context checks and
SELECT set_config. Its initial SELECT current_setting can establish the
snapshot before the context-setting statement or any selection query. The
default call retains its existing database-default isolation. This capability
does not implement dispatch creation. A product resolves its own presence and resource rules; Core receives
the selection through a generic interface and must not depend on Visitor.
Checking authorization inside the same snapshot does not automatically detect
a concurrent revocation after the snapshot; the required revocation semantics
and any coordination mechanism remain open.
The current Core::DestinationSelection is a single-statement point-in-time
read; a product first selecting resource links in a separate statement does not
thereby get one consistent snapshot for the combined operation.
Nothing calls an external provider inside that database transaction. A success response is only allowed after commit is confirmed. An unknown commit outcome must not be described as definitely failed or successful; recovery must be idempotent. Worker/provider semantics and authorization are separate from creating a snapshot.
On a serialization failure, retry the whole transaction with the same idempotency key and a bounded retry policy; no provider call may have occurred. An unknown commit outcome requires idempotent recovery using that same key, not an assertion that the transaction failed. Concurrent identical and conflicting requests require database-enforced uniqueness and an explicitly designed conflict and recovery protocol.
Before implementation, define and verify database constraints and RLS for all new tables, concurrency with edits and check-in/out, retries of the same and conflicting idempotency keys, rollback and lost-commit-response recovery, retention/deletion, and the behavior of no eligible deliveries. The earlier design proposes rejecting a dispatch with zero valid destinations; this remains a proposed rule, not current Core behavior.
Decisions needed before implementation
Section titled “Decisions needed before implementation”- Review the proposed selection boundary, source validation, scale limits and concurrent authorization revocation semantics without coupling Core to Visitor.
- Decide exclusion policy, operator confirmation and newly invalid/missing destinations at confirmation. Presence changes alone should not require an extra review.
- Agree channel assessment/versioning, email content shape and how active stored values are reassessed at dispatch time.
- Review the proposed idempotency contract, including actor treatment, canonical encoding, authorization on replay and key retention; define schema, permissions, deletion and worker handoff.