Skip to content

Dispatch integrity enforcement: candidate design

Status: proposal for discussion; not implemented or verified. This is not a migration, permission to send, or proof that the described constraints work. It refines dispatch storage; production dispatch is separate from the existing DeliveryTesting tables.

The application is trusted to authenticate the actor, authorize the product operation and selection, establish the authorized tenant context, and invoke the correct channel-owned destination assessment. Core orchestrates the snapshot through an internal contract; it does not implement email or telephone validation itself. The channel implementation is selected through trusted application configuration or code, never as an arbitrary class or executable supplied by request data. Define versioning and failure behavior before the production creation path is built.

The database enforces tenant-scoped relationships, transaction isolation, grouping consistency and the frozen-record write boundary as designed and tested. Forced RLS and transaction-local context help prevent accidental missing tenant filters and context leakage. A caller that can execute arbitrary SQL as the application role can set the custom tenant setting itself: the current mechanism does not independently authorize that caller for a tenant or protect against a compromised application role. RLS does not establish that a channel assessment supplied by the application is true. Stronger isolation against arbitrary SQL execution is a separate threat-model and architecture decision, not a property claimed for the current design.

The worker receives only the tenant-scoped read access and operational writes it needs; it cannot change the frozen graph. Its specific grants and tenant discovery mechanism remain to be designed and tested. No database function or adapter may treat a user-provided tenant ID, assessment or channel implementation as independently authorized merely because it was submitted.

Use database constraints for local and relational invariants, plus a controlled creation boundary for whole-dispatch validation and sealing. Separate the worker’s operational tables and write privileges. Prefer this over relying only on Ruby conventions; do not introduce general-purpose triggers for every rule. A small deferred constraint trigger is a candidate for enforcing sealing at commit if no simpler mechanism proves adequate. Test the complete construction with the actual PostgreSQL runtime and roles before choosing it.

Approach Benefit Limitation
Ruby validation only Simple to start. Other writers, races or bugs can bypass the invariants. Not sufficient for this contract.
Constraints only Strong database enforcement of keys, relationships and local checks. Whole-set completeness and closing a graph after creation require more than ordinary row checks and foreign keys.
Controlled database creation boundary plus constraints Limits who can write, validates the completed graph and can close it atomically. Privileged code is security-sensitive; implementation, RLS and commit behavior must be proven.
Broad triggers on all tables Can enforce rules regardless of writer. Harder to reason about and operate; deferred trigger execution and deletion need careful design. Use only where a specific invariant requires it.

The product continues to own authentication, product authorization, selection and the outer REPEATABLE READ tenant transaction. The database boundary must not commit, set a different tenant, accept untrusted tenant identity as proof of authorization, call Visitor or perform network operations.

  1. Within that transaction, the caller resolves and validates the product’s selection. It invokes a narrow creation entry point with the command and resolved values. Exact argument shape and batch-size limits remain open.
  2. The entry point checks the already established tenant context, validates all IDs and writes the dispatch graph and durable handoff. A private, database-internal building/sealed marker is a candidate; it is not a product draft status. It validates the complete graph, then seals it before returning. The result remains provisional until the outer commit succeeds.
  3. Unsealed graphs must never commit: candidate options are a deferred constraint trigger checking final state at commit, or an alternative construction that demonstrably cannot commit a partial graph. Merely having a marker or validating in Ruby is insufficient. Exceptions, savepoints, retries and transaction rollback need explicit tests.
  4. Runtime and worker roles have no direct INSERT, UPDATE or DELETE on frozen tables. The narrow entry point must not expose an operation to add to, unseal, modify or delete an existing dispatch; it creates and seals only a new graph. The worker can update only designated operational records. Any exceptional retention/redaction operation uses a separately controlled, auditable capability with deliberately designed effects on idempotency.

A PostgreSQL SECURITY DEFINER function owned by a dedicated non-login, non-superuser, non-BYPASSRLS role is one possible implementation, not an assumed safe default. Grant its execution only to the intended caller; revoke PUBLIC execution, fix a safe search_path, schema-qualify objects, prevent untrusted object creation in searched schemas and avoid dynamic SQL where possible. Its owner must not bypass tenant RLS; forced RLS, ownership, role membership and privileges must be verified in the deployed schema. Transaction context set by a caller is not an authorization credential: application membership/operation authorization and the consequences of a compromised app role remain a separate trust-boundary design. The function must reject missing, invalid or mismatched context and check tenant ownership of supplied references. It cannot establish channel validity merely from caller-supplied eligible or grouping claims. The trusted application creation path must call the correct channel assessor and pass its results; the database verifies the graph’s structural and grouping consistency. The assessment contract and proof that all creation paths invoke it still require design and tests. If this boundary is too broad or cannot meet the tenant threat model, do not ship it; choose a different explicitly tested capability boundary.

A function call does not itself commit and cannot know whether the outer transaction eventually commits. A sealed-but-uncommitted graph rolls back with its transaction; a confirmed success response requires confirmed outer commit. Uniqueness for (tenant, operation, key) remains database-enforced. Under REPEATABLE READ, a losing concurrent caller rolls back and resolves the winner in a fresh transaction; unknown commit recovery reuses the same key.

Use non-null/check constraints for row-local shapes; tenant- and dispatch-scoped composite foreign keys for relationships; and a database unique constraint for the per-dispatch grouping key. Where feasible, composite keys can also encode and enforce equality between contribution, assessment and delivery, but they must carry the right policy-specific values and tenant/dispatch identifiers. Uniqueness on the assessment side of contributions gives at most one, not exactly one. Foreign keys and unique keys alone do not prove every eligible assessment has a contribution or every delivery has one.

At sealing, validate the entire graph against the canonical channel assessment, selected policy and version, and reject the transaction if any of these fail:

  • each included eligible assessment has exactly one contribution, while every excluded, invalid, missing, inactive or unselected assessment has none;
  • each delivery has at least one contribution and a unique grouping key within its tenant and dispatch;
  • every contribution’s assessment and delivery match the expected deterministic key, including recipient identity for per_recipient_destination, and the frozen delivery destination matches the assessed destination;
  • all IDs and relationships belong to the same tenant and dispatch; all source references subject to Core validation are valid for their claimed recipient.

Define canonicalization and equality per channel and normalization version; email local parts, for example, must not be blindly case-folded. Exact binary encoding, collation, destination protection, collision handling and database index size limits are unresolved. If a digest is used, do not assume collision impossibility or that a plain digest hides low-entropy contact values; compare canonical values as necessary under the actual representation. Duplicate records with the same assessed value retain their separate contributions.

Build an isolated PostgreSQL proof of concept rather than alter live application or test data. Exercise the actual role grants, forced RLS and schema restoration, not a superuser-only approximation. At minimum verify:

  • direct runtime and worker inserts/updates/deletes after sealing fail, including late children and contributions; controlled creation cannot mutate an existing graph; authorized retention remains separately scoped;
  • unsealed or incomplete graphs cannot commit, including exceptions, savepoints, abandoned calls, concurrent attempts and rollback; ordinary successful creation commits atomically together with its handoff;
  • wrong-destination, wrong-recipient, invalid and cross-tenant/cross-dispatch contributions are rejected; shared destinations and duplicate records are correctly grouped for both policies; missing and excluded entries contribute nothing; empty deliveries and missing contributions cannot commit;
  • failed/reused tenant context and pooled-connection reuse fail closed; the creation function cannot choose another tenant or escape its allowed schema;
  • concurrent identical/conflicting idempotency keys, serialization failure and lost commit responses recover correctly; no external call is made;
  • permitted operations remain viable under real workloads and representative batch sizes, without claiming throughput before measurement.

The unresolved product authorization/revocation, channel assessment, retention, worker handoff/discovery and cancellation semantics remain independent decisions. When the production creation path exists, exercise it end to end to verify authorization, trusted channel selection and assessment, tenant context, graph validation and failure/rollback; isolated SQL tests cannot prove the application path uses the assessor correctly.