Skip to content

Tenant work discovery for delivery workers

Status: design only. No cross-tenant discovery or production dispatch is enabled by this document. Test handoffs remain opt-in and use the fake adapter.

Tenant-owned handoffs and their payloads remain behind forced row-level security. A separate discovery capability exposes only the minimum scheduling metadata necessary for a worker to identify tenants with potentially due work. It must not expose destination, message, recipient, provider reference, or incident data. Merely discovering a tenant is not authorization for a web request to use that tenant. The background worker is the only intended consumer.

  • Required tenant-context invariant: Establish the authorized tenant context before any tenant-owned query. Scope it to the database transaction; a pooled connection must not retain it across transactions or tenants, including after commit, rollback, exceptions, database cancellation or reuse. Missing, empty or invalid context must fail closed: no tenant-owned data may be exposed or modified. A read may return no rows rather than raise an error; tests must check isolation rather than require a particular error response. Tenant context enforces database isolation, but does not itself authorize a user or worker to act for a tenant. The caller must establish that authority separately before setting the context.
  • Maintain a durable scheduling directory in PostgreSQL, separate from the tenant-owned handoff rows, containing an opaque or internal tenant reference and next possible wake time. Treat the directory as sensitive operational metadata. Do not rely on Redis as the sole record of work.
  • Give the worker a dedicated discovery database identity, with only the exact directory read operation it needs. It must not be a superuser, have BYPASSRLS, own tenant tables, or inherit the migration or runtime role. Web and normal application connections must not acquire this capability.
  • Create or advance the directory hint in the same database transaction as the handoff or retry becoming eligible. A crash or Redis outage cannot erase committed work. Directory updates must never let a later deadline replace an earlier one; stale hints are harmless, missing hints are not.
  • The worker selects a bounded, fair batch of due hints, then uses its normal runtime connection to enter a separate TenantContext for each discovered tenant. It rechecks current handoff status and due time under row locking. A hint never grants access to the payload by itself. Concurrent workers may discover the same hint but only one may claim a handoff.
  • A hint can be cleared or rescheduled only with a protocol that cannot race a concurrent insert or retry. In particular, a read-then-delete without a lock or generation check can permanently lose work. Include old submitting entries in scheduling so uncertain outcomes can become indeterminate, never automatically pending again. Eventual recovery must not depend on a single worker receiving a one-time wakeup.
  • Separate test-mode work from real dispatch work at the database and service boundary. Existing simulations never become authorization to send.
  1. Specify the exact database role provisioning, connection secret management, migration ordering, grants and revocations, including default privileges and schema reloads. Avoid broad SECURITY DEFINER or discovery access through the application login. Provision separate isolated roles for tests.
  2. Implement the directory and its transactionally maintained hints; define fairness, retry timing and operational bounds. Verify least privilege with direct SQL as both discovery and application identities.
  3. Test concurrent create/claim/clear/retry and crash windows against PostgreSQL, restarts and Redis outage, RLS isolation, duplicate processing, indeterminate attempts and inaccessible tenant payloads. Test multiple worker processes. With the restricted runtime and discovery identities, test absent, empty and invalid contexts; reuse of the same physical pooled connection across tenants; and cleanup after commit, rollback, exceptions and database cancellation. Verify reads do not expose rows and writes cannot modify tenant-owned data without the correct context. Verify that discovery cannot read payloads or assume the application or migration role. These cases are requirements for verification, not claims that current tests already cover them.
  4. Provide separate deployment and rollback procedures, monitoring and alerting. Keep real provider transport, durable real-dispatch creation, delivery receipts, reconciliation, data retention and activation as distinct work.

The current manual allowlist and test-mode poller remain in place until the above exists and passes verification. This document is not a security review or an assertion that a production worker is ready.

The development setup can provision notifi_discovery using infra/docker/postgres/provision_discovery_role.sql as the PostgreSQL bootstrap administrator. It is an inactive, cluster-wide NOLOGIN role with no table access or memberships; it is not assigned to the application or worker. The script creates it only if absent and rejects unexpected existing capabilities, object ownership, memberships or public-table access instead of silently changing an existing role. Verify it separately in every database using infra/docker/postgres/verify_discovery_role.sql. Both scripts require an administrator, and must be reviewed before use in any other environment.

This reserves an isolated role name; it is not a worker login, connection, grant on a scheduling directory or implementation of automatic tenant discovery. The future connection identity, secrets, narrow grants and migration lifecycle are still open. An operator must not grant this role to the web/runtime identity as a shortcut. tenant_context_security_test.rb exercises the restricted runtime role against PostgreSQL, including transaction rollback, statement timeout and connection checkout reuse. It does not prove behavior under every form of network interruption, process cancellation or connection-pool failure.

notifi_migrator is subject to forced RLS on existing handoffs. A migration that runs INSERT ... SELECT without a tenant context can silently see zero rows even when pending handoffs exist. Therefore an ordinary Rails migration cannot be trusted to backfill the cross-tenant directory. Checking the current row count alone is insufficient because work can be created concurrently.

The rollout must use an administrator-controlled, bounded maintenance procedure that coordinates writers and workers, backfills existing pending, retryable and submitting test handoffs, verifies directory coverage and permissions, then activates discovery. Define and test rollback and restart handling before use. The discovery login must have only SELECT on scheduling metadata and must not inherit the runtime or migration roles. Neither the directory nor its discovery identity should expose message or destination fields. Until the migration and cutover protocol is implemented and verified, keep the current test-only allowlist and do not deploy a partial backfill.

tests/sql/test_directory_cutover.sql, test_directory_verify.sql and test_directory_rollback.sql are an administrator-run experiment restricted to *_test databases. The cutover takes a write-blocking table lock, installs an invoker-rights trigger and backfills under the same transaction. The experiment has been run against the dedicated test database, including one existing pending handoff and rollback. It is not a deployment migration. Lock contention, writer races, crash windows, independent login credentials and worker discovery still need automated coverage and implementation; production rollout remains disabled. The discovery NOLOGIN role can read only the scheduling directory in this test setup; no worker login is provisioned by these scripts.

An isolated Rails.env.test? worker can opt into directory discovery with TEST_DISCOVERY_DATABASE_URL, using a separate test login which inherits only notifi_discovery. The discovery and runtime URLs must name the same test host, port and database. Discovery reads only due tenant and handoff IDs; handling re-enters the tenant transaction and rechecks the handoff under lock. The worker uses only the fake SMS adapter. It does not activate in development or production, and cannot be combined with the existing explicit allowlist.

The tests/sql/provision_test_discovery_login.sql script creates a temporary cluster-wide login using an operator-supplied password; it fails if the name already exists. Remove the role with drop_test_discovery_login.sql after the isolated test. tests/test_directory_cutover_concurrency.sh checks a writer blocked during installation; tests/test_directory_cutover_abort.sh checks transaction rollback on backend termination. Both require psql, a dedicated *_test database and an explicitly supplied administrator URL. These tests are experiments, not deployment procedures. Before use outside an isolated test, role provisioning and secret rotation, fairness under sustained load, multiple worker processes, monitoring, recovery, authorization and production rollout still require design and verification.