Skip to content

Dispatch persistence: first migration design

Status: concrete candidate for review; not a migration or authorization to send. This document adapts storage and enforcement proposal to the current repository and development roles. No production dispatch tables, worker handoff or adapter are implemented by this document. The PostgreSQL proof of concept in tests/dispatch_integrity_poc is narrower than this design.

Existing environment and migration constraint

Section titled “Existing environment and migration constraint”

infra/docker/postgres/provision.sql provisions notifi_migrator and notifi_app as non-superuser, non-BYPASSRLS, NOINHERIT login roles. notifi_migrator owns the database and public schema; notifi_app is the application runtime role. The development notifi_discovery role is a separate inactive NOLOGIN role, not a dispatch writer. Current web and worker services both use the app database identity; a narrower worker login is not yet available. Application authorization remains separate from RLS and tenant context can be set by the app role; arbitrary SQL under that role is not isolated by a trusted tenant credential.

A crucial conflict: provisioning grants notifi_app SELECT/INSERT/UPDATE/DELETE on all existing public tables and sets equivalent default privileges for future tables made by notifi_migrator. A one-off REVOKE in a migration is not stable: rerunning provisioning would grant writes again. Provisioning also grants sequence access. The current RLS verifier does not establish a frozen-graph write boundary. The first persistence change must address this entire privilege lifecycle, including provisioning reruns and fresh schema restoration, before a creation capability becomes usable. A migration role without CREATEROLE cannot create a new dedicated database role by itself.

Provisioning now reserves a separate notifi_dispatch schema, outside the broad public grants, with isolated tests for reruns and unsafe default or assumable-role privileges. This reserves a boundary; it does not create a frozen graph or a definer function. Before adding tables, verify Rails SQL schema dump, restoration and migration flows for the additional schema. Owner and function roles, deployment and rollback remain open.

The first usable slice stores a completed, sealed dispatch graph atomically, including creation idempotency, but no provider submission and no worker activation. Do not copy or repurpose the existing DeliveryTesting tables. Concrete table names below are proposed, subject to migration review:

Table Responsibility and candidate constraints
dispatches Tenant, actor reference, product/source version, one channel, versioned message content, policy versions, selection metadata, timestamps and an internal build/sealed marker. Unique (tenant_id,id); no public draft lifecycle implied.
dispatch_creation_keys Tenant, operation, key, fingerprint version/value and dispatch reference; unique (tenant_id,operation,key) and tenant-scoped FK to dispatch. Signed-token lifecycle and canonical encoding need implementation decisions before production use.
dispatch_recipients Dispatch-scoped recipient identity and minimal frozen facts; unique recipient per dispatch.
dispatch_selection_reasons Typed/versioned selection reason per recipient, including distinct Core resource/link references when applicable. Explicit selection must not invent a Visitor resource.
dispatch_destination_assessments Per-recipient destination source, frozen normalized value or explicit missing/excluded outcome, assessment version and reason. Missing must be representable without a fake destination.
dispatch_deliveries Immutable logical destination and policy-specific grouping identity, unique within a tenant/dispatch. No mutable worker state.
dispatch_delivery_contributions Joins each eligible assessment to its logical delivery; unique assessment per dispatch and composite FKs ensuring same tenant and dispatch.

Every tenant-owned table needs tenant_id, forced RLS and matching USING and WITH CHECK policies; composite unique keys and foreign keys must enforce same-tenant and same-dispatch relationships throughout. Add narrowly scoped indexes for tenant-scoped foreign-key lookups and intended key lookup; verify query plans later rather than assume scale. Stable source references must not accidentally turn CASCADE, SET NULL or indefinite RESTRICT into the retention decision. Snapshot facts and sensitive values are not logged.

A first migration may create inactive tables before all command behavior is implemented, but must not expose any production dispatch-creation function until the complete graph, privileges, validation and tests exist. A partially populated table or handoff must never be treated as a sendable dispatch.

Controlled write boundary: candidate, not final SQL

Section titled “Controlled write boundary: candidate, not final SQL”

The application owns the tenant REPEATABLE READ transaction, product authorization and channel assessment. Database writes go through a narrow creation function with fixed SQL and a fixed, safe search_path, not direct app writes to frozen tables. It creates a new graph, validates it and seals it in that same caller transaction. Replays, mismatched key fingerprints and unknown commit outcomes follow the separately designed idempotency contract. A return from the function is provisional until the caller confirms outer commit. No provider call or network activity is permitted in the transaction.

Candidate enforcement consists of:

  1. Database uniqueness, checks and composite FKs for record shapes, tenant and dispatch relations, one grouping identity per policy, and at most one contribution per assessment. Key representation, channel equality and index size must be resolved; a plain digest is neither privacy nor collision proof.
  2. A constrained creation path and deferred end-of-transaction graph validation for all included eligible assessments having exactly one matching contribution, excluded assessments having none, every delivery having a matching contribution, and destination/policy equality. Ordinary row CHECK constraints alone cannot prove these cross-row invariants.
  3. Guards that close the graph to child INSERT, UPDATE and DELETE after sealing, plus a commit-time guarantee that unsealed graphs cannot be committed. Parent row locking, trigger ordering, RLS visibility, savepoints and concurrency need proof using the actual schema. No trigger should imply that a database owner or superuser cannot alter or disable it.
  4. A separate, explicitly authorized retention/redaction capability. It does not silently relax the normal frozen-data rule. Its transaction, audit and behavior with provider work are still open.

A fixed SECURITY DEFINER function owned by notifi_migrator is technically a candidate because it already owns tables and has NOBYPASSRLS; forced RLS must still be verified with the actual function owner. It is also a broad and login-capable owner, so this is not automatically acceptable. A dedicated NOLOGIN function owner with only necessary table/sequence grants offers narrower privilege, but requires administrator provisioning and a migration/ownership lifecycle the current role setup does not provide. Compare and test both before choosing. Revoke PUBLIC function execution, grant only the needed entry point, protect schemas/search paths, and verify default function privileges. Do not assume that possession of a caller-set tenant context or assessor result proves product authorization or channel validity.

The original design expects a durable handoff when a dispatch is eligible for worker processing. For this first storage-only slice, do not create an active or discoverable handoff and do not claim readiness to send. Choose and document an explicit storage-only/non-sendable state or separate persistence experiment; the exact state, later atomic activation, worker discovery, cancellation and provider uncertainty must be designed before enabling delivery. It is unsafe to ship a creation API that reports a send-ready dispatch while no durable worker handoff exists. The existing test handoffs and allowlist do not satisfy this production guarantee.

  • Decide first-use signed key lifetime, canonical fingerprint, replay conflict, timeout/commit uncertainty recovery and race handling; no silent key reuse.
  • Define the channel-specific content schema, included/excluded assessment contract, empty/zero-eligible behavior and source-reference deletion policy.
  • Decide application versus dedicated owner role, admin provisioning, grants, schema dump/restore and how a provisioning rerun preserves restrictions. Existing broad grants and default privileges are a blocker, not a TODO after frozen tables are live.
  • Define how storage-only records are explicitly kept non-sendable, and the future atomic handoff/discovery activation contract.
  • Test from a fresh isolated database and through the real migration role: RLS and tenant mismatch, direct writes and sequences, function ownership and PUBLIC grants, provisioning rerun, structure dump/restore, partial graph, post-seal inserts/updates/deletes, both grouping policies, mismatched or missing contributions, savepoints, rollback, concurrent creation/replay and uncertain commit. Test app and eventual worker roles separately.
  • Never run experimental SQL against development or production data. Development migrations, when later authorized and implemented, use ./bin/dev-migrate per AGENTS.md; test and production environments have separate procedures.