Skip to content

Dispatch storage and transaction design

Status: proposal for review; not implemented. Names are conceptual, not a migration or public API. The existing core_dispatch_snapshots, handoffs and related tables support DeliveryTesting; their names do not make them the production dispatch model. Do not reuse or migrate those tables implicitly. See dispatch contract and worker discovery design.

Each tenant-owned record includes tenant_id and an opaque primary key. The following describes relationships and intended data, not final column types.

Record Purpose and proposed contents
Dispatch Actor reference, product/source type and version, channel, frozen versioned content, selection metadata, chosen policies and versions, creation time. One dispatch has one channel. A recorded time is not necessarily the database snapshot’s exact time or proof of delivery.
Creation key Operation, idempotency key, fingerprint and fingerprint version, plus the resulting dispatch reference. Unique (tenant_id, operation, key). Persisted atomically with the dispatch; never a separately committed “in progress” reservation in this proposal.
Selected recipient One row per distinct selected recipient in the dispatch, with the original recipient reference and only frozen display data justified by the product. Unique (tenant_id, dispatch_id, recipient_id) while the reference is retained.
Selection reason A selected-recipient reference and typed, versioned source reference explaining inclusion. A resource reason identifies both resource and link; an explicit selection need not have either. Multiple distinct links are retained. Empty resources may be represented in dispatch selection metadata; they must not invent recipients.
Assessed destination A selected-recipient reference, original destination reference where applicable, frozen channel values and assessment/version or an explicit missing/invalid exclusion reason. Multiple destinations per recipient are allowed; a missing destination is retained without inventing a value.
Logical delivery A dispatch reference, explicit grouping key and frozen channel delivery destination, created only for included eligible assessments under the chosen grouping policy. It represents intended work, not an attempt or confirmed delivery.
Delivery contribution Links one delivery to an assessed destination; reasons are traceable via that destination’s selected recipient and its selection reasons. Every contributing association remains visible, including multiple people sharing a destination.
Handoff Durable tenant-scoped work reference for the dispatch or its deliveries, committed with the dispatch. Granularity, eligibility and worker state are open; do not assume one handoff means one network request.

A recipient with two selection reasons and two valid addresses therefore has one selected-recipient row, two reason rows and two assessed destination rows. Each delivery points to the applicable assessment; tracing through the recipient preserves both reasons. A shared normalized address can have assessments for multiple recipients and one delivery under per_destination. Missing or invalid assessments never have a delivery contribution. The design must not silently collapse distinct destination records or selection reasons before recording them.

Every included assessment eligible under the dispatch’s policies contributes to exactly one logical delivery. An excluded, invalid, missing, inactive or explicitly unselected assessment contributes to none. Every logical delivery has at least one contribution. A contribution must match both its delivery’s grouping key and the dispatch’s selected policy and version. Being in the same tenant and dispatch is necessary but insufficient: an assessment for Erik’s address must not contribute to Anna’s different address, and an invalid address must never contribute to a delivery. Exact classification of unselected values and duplicate destination records remains to be specified.

Each delivery has a deterministic grouping key, conceptually:

  • per_destination: the channel-assessed normalized destination value.
  • per_recipient_destination: selected recipient identity and that value.

Channel and policy are fixed by the dispatch. Enforce one delivery per (tenant, dispatch, grouping key) for the supported policy; this conceptual key is not a finished SQL type or index. Encoding, equality, collisions and protection of destination data require design: an unkeyed hash of a phone number or email is not automatically confidential. A unique grouping key alone does not prove that contributions match it. Composite foreign keys, uniqueness, controlled writes and possibly deferred constraint triggers must be assessed against all invariants, including completeness at commit. PostgreSQL row-level CHECK constraints alone cannot enforce arbitrary cross-row relationships. Do not assume any particular mechanism is sufficient until tested.

Dispatch content, selected recipients, selection reasons, assessments, logical deliveries and contributions describe the committed selection and intended deliveries. Once committed, they are closed to unauthorized additions, modifications and removals, including inserting new child records. Explicitly authorized retention, redaction and deletion procedures are separate.

Delivery state, handoff state, worker leases, transport attempts, retry schedules and cancellation or suppression are operational records, separate from frozen delivery facts. Their lifecycle, concurrency, audit and role permissions need their own design. This separation should allow a worker to update only the operational records it needs, not rewrite the selection. Stopping pending work must not be reported as proof that a message was stopped if provider submission is already in progress or its outcome is uncertain.

The data representation for missing versus invalid, per-destination subsets, channel content and assessment versions remains open. Stable source IDs and frozen values serve different purposes: historical rendering must not depend on mutable source records. Whether source references survive deletion, become null or are replaced by protected tombstones needs an explicit deletion design.

  • Use forced tenant RLS with read and write policies, transaction-local context and a runtime role without table-owner bypass or BYPASSRLS. Validate missing, invalid and leaked context, including pooled connection reuse and rollback. RLS does not authorize an actor or a product operation.
  • Add database-enforced composite foreign keys containing tenant_id, and where required dispatch_id, so children, assessed destinations, deliveries and contributions cannot point across tenants or across dispatches. Parent composite keys must be uniquely constrained. A contribution must link an assessment and delivery belonging to the same dispatch. Application checks supplement these constraints; they do not replace them.
  • Validate Core-owned resource links against the tenant, resource and recipient; the product checks source legitimacy and actor permissions. Define how source references remain valid when source records are later deleted; do not assume an ordinary foreign key automatically provides a retention policy.
  • Enforce key uniqueness in the database, and define scoped uniqueness and non-null/check constraints for each row type and policy. The grouping key’s uniqueness must match the chosen policy and its version; do not use a global unique index on a normalized address. Its concrete representation and protection against concurrent writers need review.
  • Frozen content, reasons, destination values and delivery relationships must be closed to unauthorized inserts as well as updates and deletes after commit. Enforce the eventual write boundary using suitable database privileges or constraints as well as application behavior; status/attempt data and authorized deletion require separate rules. Avoid logging message contents and contact values.
  1. The product authenticates, obtains or reuses its durably stored operation key, then starts the tenant-scoped REPEATABLE READ transaction before any query and establishes transaction-local context. Tenant establishment must precede tenant-owned queries, while existing-context safety checks remain compatible with the selected isolation level.
  2. Recheck authorization and find an existing key. For an existing committed result, compare the versioned canonical command and authorize access; return it without re-resolving recipients. A changed command conflicts. Existing result visibility is still provisional until the read transaction completes.
  3. For a new key, resolve product selection, validate all tenant-owned references, read and assess destinations in the same snapshot, and apply the explicit policies. Keep every selection reason and excluded assessment. The behavior for no eligible deliveries remains a product decision.
  4. Insert dispatch, creation key, recipients, reasons, assessments, logical deliveries, contributions and the durable handoff in this transaction. No network call occurs within it. Any validation or write error rolls all of these records back.
  5. Report creation only after a confirmed commit. An uncertain commit outcome remains uncertain; recover with the same key and command. A concurrent key conflict or serialization failure requires rollback and a fresh transaction to see the winning result, with bounded retries as described in the contract.

A separately designed durable discovery mechanism is required before a worker can reliably find work across tenants. The handoff alone is not evidence that a worker ran or that a provider accepted or delivered anything. Provider retries, uncertain provider outcomes and attempts require their own ledger and policy.

All frozen data, including message contents, identity, destinations and reason references, needs an explicit access and retention policy. Immutable history while retained does not mean indefinite storage. Deleting source data must not silently change historical records; a legally or operationally authorized redaction/deletion procedure must address every copy and contribution.

Key retention must prevent an old retry from becoming a new dispatch. If the dispatch is deleted while its key is retained, a minimal tombstone could reject reuse or return an authorized non-sensitive deleted-result status; the exact behavior, fingerprint protection and retention period remain decisions. No automatic expiry or promise of indefinite personal-data retention is implied.

Decide the physical schema and names, source and deletion semantics, exact constraints and canonical fingerprints; role permissions and revocation, retention, no-eligible behavior, batch sizing and handoff/discovery. Test with actual PostgreSQL and the runtime role: forced RLS and tenant reuse; composite foreign keys including cross-dispatch contribution attempts; repeated and concurrent keys, conflicts and lost commit responses; snapshot consistency while check-in/out and destination edits commit; rollback after each insertion stage; grouping mismatches, excluded assessments, missing contributions and post-commit child inserts; worker permission boundaries; and retention/deletion. Verify no partial dispatch or handoff becomes visible. No production transport is authorized by this design.