how-to administrator

Notification Subsystem Architecture Map

How templates, triggers, providers, dispatch, delivery, and inbox fit together.


1. Pipeline Overview

Event (gate transition, conversation action)
    │
    ▼
resolve_triggers_for_event(...)
    │
    ▼
NotificationTrigger matching (event_type, role_code, is_active)
    │
    ▼
NotificationTemplate fetch + render (subject, body_html, body_text)
    │
    ▼
resolve_recipients(...) → ResolvedRecipient[]
    │
    ▼
FOR EACH recipient:
    create_delivery_row(...) → NotificationDelivery (status='queued')
    │
    ▼
check_dispatch_eligibility(...) ← [queue-time gate]
    │
    ├─ blocked → status='suppressed', suppression_reason='queue_<gate>'
    │
    └─ passed → stays 'queued'
         │
         ▼
    dispatch_pending_notifications(...) [leased-batch worker, every 60s]
         │
         ▼
    SELECT … FOR UPDATE SKIP LOCKED (status IN ('queued','failed_transient'))
         │
         ▼
    FOR EACH delivery:
         rate_limit_acquire(...)
         │
         ▼
         NotificationDispatchable.recheck_eligibility() ← [execute-time gate]
         │
         ▼
         NotificationDispatchable.execute(...) → provider adapter.send(EmailPayload)
         │
         ▼
         classify_error(result)
         │
         ├─ delivered
         ├─ failed_transient
         ├─ failed_permanent → on_permanent_failure (flags contact_invalid_flags)
         └─ rate_limited
         │
         ▼
    UPDATE NotificationDelivery.status
         │
         ▼
    Postgres trigger → upserts eapproval_notification_threads
         │
         ▼
    InboxService.list_threads / thread_detail / mark_read / mark_unread

2. Data Model

2.1 Core pipeline tables

TablePurposeKey columns
notification_templatesAgency-authored message templatescode, channel, recipient_kind, recipient_config (JSONB), reentrant, requires_acknowledgement
email_template_bodiesLocalised subject + body per templatetemplate_id (1:1), content (JSONB: locale → {subject, body_html, body_text})
notification_triggersEvent→template binding per procedure versionevent_type, target_role_code, template_id, is_active
notification_providersPer-deployment provider registrydeployment_id, channel, connector_code, operation_code, is_active
notification_deliveriesDispatch state + inbox source of truthapplication_id, trigger_id, template_id, channel, recipient_address, status, classified_error, read_at, is_test
notification_fire_ledgerDeduplication for non-reentrant templates(application_id, template_id)

2.2 Ops / governance tables

TablePurpose
platform_notification_kill_switchAppend-only audit trail of channel on/off flips
deployment_notification_policyGDPR legal basis (contractual or consent) per deployment
deployment_feature_flagsnotifications_enabled toggle per deployment
notification_rate_limitsPostgres-backed counter per (deployment, channel, window)
notification_consent_eventsGDPR Art. 7 demonstrable consent audit
notification_test_logPII-redacted audit of admin test sends
notifications_health_snapshotsTask 10 projection (deployment or procedure scope)
eapproval_notification_threadsGmail-style inbox projection (read-optimised)

2.3 Foreign key graph

notification_templates.procedure_id → smartrules_procedures.id
notification_templates.archived_from_version_id → published_versions.id (archived rows only — M100)
email_template_bodies.template_id → notification_templates.id
notification_triggers.procedure_version_id → published_versions.id
notification_triggers.template_id → notification_templates.id
notification_providers.deployment_id → deployments.id
notification_providers.connector_code → smartlink_connectors.code
notification_deliveries.application_id → eapproval_applications.id
notification_deliveries.trigger_id → notification_triggers.id (SET NULL)
notification_deliveries.template_id → notification_templates.id
notification_fire_ledger.application_id → eapproval_applications.id
notification_fire_ledger.template_id → notification_templates.id
notification_consent_events.application_id → eapproval_applications.id

3. Trigger Evaluation

3.1 Event types

'gate_passed'
'gate_failed'
'convergence_passed'
'all_gates_passed'
'comment_posted'
'clarification_opened'
'clarification_resolved'
'clarification_expired'
'clarification_stale'

3.2 Role consistency rule

Event typetarget_role_code required?
gate_passed, gate_failed, comment_posted, clarification_opened, clarification_resolved, clarification_expired, clarification_staleYes
convergence_passed, all_gates_passedNo (must be NULL)

3.3 Call sites

resolve_triggers_for_event(session, application_id, event_type, role_code) is called from:

  • eapproval/reactions.py — gate transitions:
    • gate_passed on assert
    • gate_failed on recompute
    • convergence_passed on convergence activation
    • all_gates_passed on completion
  • eapproval/conversation/reactions.py — conversation events:
    • comment_posted
    • clarification_opened, clarification_resolved, clarification_expired, clarification_stale

3.4 Resolution query

select(NotificationTrigger).where(
    NotificationTrigger.procedure_version_id == app.procedure_version_id,
    NotificationTrigger.event_type == event_type,
    NotificationTrigger.is_active.is_(True),
    NotificationTrigger.target_role_code == role_code  # if not None
)

3.5 Non-reentrant dedup

Before fanning out, the dispatcher checks NotificationFireLedger for an existing (application_id, template_id) row. If found and template.reentrant == false, the trigger is skipped.

The ledger is written before inbox rows so a crash mid-loop doesn’t re-evaluate.


4. Provider Selection

4.1 Adapter registry

operation_code follows the convention <provider>:<verb>:

PrefixAdapter class
sendgridSendGridEmailAdapter
smtpSmtpEmailAdapter

New adapters register in platform/notifications/providers/registry.py — no schema change required.

4.2 Active provider resolution

select(NotificationProvider).where(
    NotificationProvider.deployment_id == deployment.id,
    NotificationProvider.channel == delivery.channel,
    NotificationProvider.is_active.is_(True),
)

Critical constraint: Partial unique index uq_notification_providers_deployment_channel_active enforces at most one active provider per (deployment, channel). There is no fallback chain.

4.3 Adapter lifecycle

adapter_cls = resolve_adapter(self.provider.operation_code)
adapter = adapter_cls(
    connector_code=self.provider.connector_code,
    operation_code=self.provider.operation_code,
)
payload = EmailPayload(
    to=delivery.recipient_address,
    subject=delivery.subject_rendered,
    body_html=delivery.body_html_rendered,
    body_text=delivery.body_text_rendered,
    from_email="noreply@opengov.local",
)
result = await adapter.send(payload)

5. Dispatch Loop

5.1 Entry point

dispatch_pending_notifications(session, batch_size=50) — Procrastinate periodic job, cron * * * * *.

5.2 Concurrency safety

select(NotificationDelivery)
.where(NotificationDelivery.status.in_(["queued", "failed_transient"]))
.limit(batch_size)
.with_for_update(skip_locked=True)

Multiple workers receive disjoint slices via SKIP LOCKED.

5.3 Per-row state machine

  1. Metrics — inc_attempted(channel, deployment_code)
  2. Provider lookup — missing → suppressed / execute_no_provider
  3. Rate-limit gate — rate_limit_acquire() returns False → failed_transient / rate_limited
  4. Template lookup — missing → suppressed / execute_no_template
  5. Execute-time eligibility re-check — fails → suppressed / recheck_<gate>
  6. Status → attempting — increment attempt_count, set last_attempted_at
  7. Execute — dispatchable.execute(attempt)
  8. Classify result:
    • success=True → delivered
    • classification == "permanent" → failed_permanent; run on_permanent_failure
    • classification == "rate_limited" → failed_transient / rate_limited
    • transient + attempt_count >= MAX_ATTEMPTS → failed_permanent / transient_exhausted
    • transient + attempt_count < MAX_ATTEMPTS → failed_transient / transient
  9. Metrics — inc_outcome(channel, outcome, deployment_code)

MAX_ATTEMPTS is shared with the integration-event dispatcher (value: 6).


6. Dispatch Eligibility Gates

Eligibility is checked twice: at queue-time (when the delivery row is created) and at execute-time (when the worker picks it up).

Gate #NameQueue-timeExecute-timeWhy checked twice
1Kill switchqueue_kill_switchrecheck_kill_switchAdmin may flip during backlog
2Provider activequeue_no_providerrecheck_no_providerProvider may be deactivated
3Feature flagqueue_feature_flagrecheck_feature_flagFlag may change
4Consentqueue_consentrecheck_consentApplicant may withdraw
5Contact validqueue_contact_invalidrecheck_contact_invalidBounce may flag address

7. Inbox / Thread Projection

7.1 Source of truth

notification_deliveries is authoritative. eapproval_notification_threads is a read-optimised projection maintained by Postgres triggers (M18).

7.2 Postgres triggers

trg_thread_upsert_on_delivery — AFTER INSERT ON notification_deliveries

  • WHEN (NEW.is_test = FALSE)
  • Upserts thread row for application_id
  • Sets last_delivery_at = GREATEST(existing, NEW.created_at)
  • Clears archived_at (un-archive on new delivery)
  • Increments unread_count when NEW.read_at IS NULL

trg_thread_read_transition — AFTER UPDATE OF read_at ON notification_deliveries

  • WHEN (OLD.is_test = FALSE AND NEW.is_test = FALSE AND OLD.read_at IS DISTINCT FROM NEW.read_at)
  • Decrements unread_count on mark-read; increments on mark-unread
  • GREATEST(unread_count - 1, 0) prevents negatives

repair_notification_threads() — stored procedure for disaster recovery

7.3 InboxService

All methods scoped to recipient_sub (Zitadel sub, String 255):

  • list_threads(recipient_sub, show, date_within, channel) — Gmail-style listing. Joins threads with latest delivery snippet and frozen procedure name from published_versions.spec. Filters: active / unread / archived, 7d / 30d.
  • thread_detail(recipient_sub, application_id) — per-application delivery list, newest first.
  • mark_read(recipient_sub, delivery_id) — dwell-read transition. Refuses if template has requires_acknowledgement=TRUE (M20).
  • mark_unread(recipient_sub, delivery_id) — reversal.
  • archive_thread / unarchive_thread — idempotent.

deployment_notification_policy declares the basis per deployment:

  • consent (default if no row) — requires positive NotificationConsentEvent per (application, channel).
  • contractual — bypasses consent checks. CHECK enforces dpo_signed_off_at IS NOT NULL.

notification_consent_events is append-only:

FieldDescription
ui_surfacesubmission_form, portal_toggle, sms_stop, admin_override, migration_backfill
grantedbool
ipClient IP (INET)
user_agentString
policy_versionPolicy version at time of consent
actor_user_idWho acted

CHECK prevents granted=FALSE with ui_surface='submission_form'.

At eligibility check #4:

if recipient.kind == "applicant_field":
    policy = await session.get(DeploymentNotificationPolicy, recipient.deployment_id)
    legal_basis = policy.legal_basis if policy else "consent"
    if legal_basis == "consent":
        # Query latest NotificationConsentEvent for (application_id, channel)
        # Missing or granted=False → block with gate="consent"

8.4 Preflight check

run_preflight() warns authors if the procedure form lacks a consent_<channel> requirement (field_name LIKE 'consent_%'). This is a design-time warning, not a runtime block.


9. Kill Switch

9.1 Model

platform_notification_kill_switch is append-only. Every flip writes a new row. Latest enabled_at wins.

9.2 Queue-time check

latest_ks = select(NotificationKillSwitch)
    .where(deployment_id=recipient.deployment_id, channel=channel)
    .order_by(enabled_at.desc())
    .limit(1)

if latest_ks and latest_ks.enabled:
    return EligibilityResult(ok=False, gate="kill_switch", reason=latest_ks.reason)

9.3 Runbook behaviour

  • Flip ON → all new events on that (deployment, channel) are suppressed.
  • In-flight rows (queued / attempting / failed_transient) have their next retry blocked; already-in-flight provider calls may still deliver.
  • Force-suppress in-flight → explicit UPDATE notification_deliveries SET status='suppressed', suppression_reason='kill_switch'.
  • Flip OFF → insert new row with enabled=FALSE.

10. Health Metrics

10.1 Architecture

  • Writer: refresh_notification_health_snap(deployment_id) — Task 10 periodic job
  • Reader: NotificationHealthService — Task 9 thin read-side
  • Projection: notifications_health_snapshots

10.2 Refresh cadence

  • Procrastinate periodic: * * * * *
  • Internal gating:
    • 300 s when all providers are healthy
    • 60 s when any provider is degraded or down
  • Lag sweeper: separate gauge notifications_health_refresh_lag_seconds ages from MAX(refreshed_at)

10.3 Provider snapshot computation

SELECT COUNT(*) AS n,
       SUM(CASE WHEN status = 'delivered' THEN 1 ELSE 0 END) AS ok
FROM (
    SELECT status
    FROM notification_deliveries
    WHERE channel = :c
      AND is_test = FALSE
      AND created_at > now() - interval '24 hours'
      AND status IN ('delivered', 'failed_transient', 'failed_permanent')
    ORDER BY created_at DESC
    LIMIT :max_sample_size
) w

Success rate = ok / n.

ConditionStatus
sample_size < 20insufficient_data
success_rate >= 0.95healthy
success_rate >= 0.70degraded
otherwisedown

10.4 Procedure snapshot

Per procedure_version_id with deliveries in last 24h:

  • consent_granted, consent_withdrawn, consent_rate_baseline
  • deliveries_attempted_24h, deliveries_delivered_24h, deliveries_failed_24h
  • failure_classify_breakdown — JSONB aggregate of classified_error → count

10.5 Reader freshness guards

NotificationHealthService._compute_status:

  1. Staleness: now - refreshed_at > interval * 2.0 → unknown
  2. Sample size: sample_size < 20 → insufficient_data
  3. Raw status: otherwise return stored provider_status

11. Rate Limiting

11.1 Postgres-backed limiter

notification_rate_limits — composite PK (deployment_id, channel, window_start).

  • Windowing: floors UTC to nearest multiple of window_seconds (default 10)
  • Mechanism: INSERT … ON CONFLICT DO UPDATE SET request_count = request_count + 1 RETURNING request_count
  • Cap: max_per_window (default 50)
  • Cleanup: cleanup_stale_windows(max_age_seconds=3600) — hourly periodic drops old rows

11.2 Usage in dispatch loop

allowed = await rate_limit_acquire(session, provider.deployment_id, delivery.channel)
if not allowed:
    delivery.status = "failed_transient"
    delivery.classified_error = "rate_limited"

This is a soft limit — the row stays failed_transient and will be retried on the next sweep.


12. Key Metrics

MetricTypePurpose
notifications_health_refresh_lag_secondsGaugeSeconds since last refresh
notifications_health_snapshot_refresh_duration_secondsHistogramWall-clock duration of refresh pass
notifications_inbox_thread_projection_repair_countCounterRepair SP invocations
notifications_inbox_deadline_auto_read_refusedCounterMark-read refused (ack-required)
notification_dispatch_attempted_totalCounterPer leased inbox row
notification_dispatch_outcome_totalCounterTerminal outcome
notification_rate_limit_rejections_totalCounterRate-limit gate blocks
notification_dlq_depthGaugefailed_permanent backlog

13. Design Invariants

InvariantRationale
Inbox row before eligibilityLegal defensibility — every triggered send either goes out or is explicitly suppressed by name
Eligibility checked twiceState can change between write and send (kill switch, consent withdrawal, contact bounce)
Non-reentrant ledger before inboxCrash safety — prevents orphan deliveries that re-fan on retry
Append-only kill switchFull audit trail; no toggle mutation
Exactly one active provider per (deployment, channel)No fallback ambiguity
Thread projection via triggersInbox stays consistent without app-level coordination
Frozen procedure name in inboxApplicant sees the name at submission time even if renamed later
requires_acknowledgement on templateLegal-deadline fidelity requires explicit acknowledgement, not dwell-read
Zitadel sub as String(255)Zitadel subs are numeric snowflakes, not UUIDs

14. Further Reading

  • docs/specs/2026-04-20-smartlink-phase2d-notifications-design.md — Phase 2D design spec
  • docs/specs/2026-04-21-smartlink-phase2e-inbox-health-design.md — Phase 2E design spec
  • src/opengov/platform/notifications/dispatch.py — Trigger resolution + queue-time logic
  • src/opengov/platform/notifications/dispatchable.py — Execute-time logic
  • src/opengov/eapproval/notification_threads/inbox_service.py — Inbox API
  • src/opengov/platform/notifications_health/refresh.py — Health refresh job
  • src/opengov/platform/notifications_health/service.py — Health read-side