SQL CookbookChannels & campaigns

Channels and campaigns

Two unrelated table groups answer “how did this survey reach a person”. channels is configuration: a named door in an environment, with a type and a jsonb config blob, that a survey may point at. "Campaign" and "CampaignSend" are history: one outbound batch to one segment, and one row per recipient.

They do not reference each other. "Campaign" has sixteen columns and not one of them is a channel reference — it links to a survey, a segment and an environment (packages/database/schema.prisma:1412-1436). So “which channel did this campaign go out on” is not a question the schema can answer directly; the closest you get is the campaign’s provider_type and the survey’s channel_id, and those two can disagree.

This page also carries the one column everybody reaches for when attributing a response to a delivery — "Response".survey_delivery_channel — and the reason it is usually null or, on a migrated database, holding something other than what the reading code expects.

Read Read this first before running anything here. Every recipe below carries an explicit tenant predicate for the reasons that page establishes, and uses its :'environment_id' / :'organization_id' placeholders.

The naming contrast, in one join

Channel is one of the 12 @@map’d models, so the table is channels, and its columns are snake_case throughout. Survey has no @@map, so the table is "Survey", and its environment column is camelCase. A query that touches both has to spell the same concept two different ways in adjacent lines:

SELECT c.id,
       c.name,
       c.type,
       count(s.id) AS survey_count
FROM channels c
LEFT JOIN "Survey" s
       ON s.channel_id = c.id
      AND s."environmentId" = c.environment_id
WHERE c.environment_id = :'environment_id'
GROUP BY c.id, c.name, c.type
ORDER BY survey_count DESC, c.name;

c.environment_id is bare. s."environmentId" needs the quotes. s.channel_id is snake even though it sits in a PascalCase table — "Survey" carries "environmentId" at ordinal 7 and channel_id at ordinal 8.

Four ways to get this wrong, each with the error Postgres gives you:

SELECT id FROM "Channel" LIMIT 1;
ERROR:  relation "Channel" does not exist

SELECT "environmentId" FROM channels LIMIT 1;
ERROR:  column "environmentId" does not exist

SELECT environment_id FROM "Survey" LIMIT 1;
ERROR:  column "environment_id" does not exist

SELECT "surveyId" FROM "Campaign" LIMIT 1;
ERROR:  column "surveyId" does not exist

The last one is the counterintuitive one. "Campaign" is a quoted PascalCase table whose columns are entirely snake_case — survey_id, segment_id, environment_id, novu_workflow_id, provider_type, scheduled_at, sent_at, sent_count, failed_count, total_count. There is no rule that gets you from the table’s casing to the column’s.

The AND s."environmentId" = c.environment_id term looks redundant given the WHERE. It is not, and this is worth knowing before you drop it: nothing enforces that a survey’s channel lives in the survey’s environment. createSurvey connects the channel by bare id with no environment check (apps/web/lib/survey/service.ts:730-736). updateSurvey never resolves the channel at all — channelId stays in the surveyData rest object (:403) and is written straight through as a scalar (:645-649). The only channel validation on either path is validateRestrictedChannelElements (:38-103), which loads the channel to read type and then checks element compatibility for voice and for the messaging types — never environmentId. The foreign key targets channels(id) alone, and channels has no RLS policy at all (see the config section). So the join term is the only thing keeping a cross-environment channel_id from inflating a per-environment count.

The plan on devhub_ref is index-driven on both sides. Every plan quoted on this page is trimmed to the nodes under discussion — the Sort and Bitmap Heap Scan nodes an empty table attracts are dropped, so a child shown here is not always an immediate child in the real output:

 Sort  (cost=17.75..17.76 rows=2 width=76)
   Sort Key: (count(s.id)) DESC, c.name
   ->  GroupAggregate  (cost=17.68..17.74 rows=2 width=76)
         Group Key: c.id
         ->  Merge Left Join  (cost=17.68..17.71 rows=2 width=100)
               Merge Cond: (c.id = s.channel_id)
               ->  Bitmap Index Scan on channels_environment_id_name_key
                     Index Cond: (environment_id = 'cmr0o5ivu000clc01glv55m4p'::text)
               ->  Index Scan using "Survey_environmentId_updated_at_idx" on "Survey" s
                     Index Cond: ("environmentId" = 'cmr0o5ivu000clc01glv55m4p'::text)

Note which index served the channel filter: channels_environment_id_name_key, the @@unique([environmentId, name]) constraint, not the separate @@index([environmentId]). Both exist; the planner picked the composite.

Against hivecfm, which has 66 channels in one environment, the recipe returns real rows:

            id             |         name         |   type   | survey_count
---------------------------+----------------------+----------+--------------
 cmr0ppcgt008bu8ps7fjnhuy6 | General              | web      |          146
 cmr0ppcfq007ru8psqubiwcm5 | Email001             | email    |           47
 cmr0ppciz0099u8pst3dhwn65 | MobileSDKReact       | mobile   |           34
 cmr0ppcg7007xu8ps1v7nb3tl | Contact Center Email | email    |           28
 cmr0ppcgy008du8psebzm5eyq | EMbedpopup           | web      |           19
 cmr0ppcg1007tu8ps06jv7znn | In-Chat              | link     |           17

Every channel recipe on this page was run against hivecfm. That database carries channels with 66 rows, its eight columns are name-for-name and type-for-type identical to origin/development, and 547 of its 1191 surveys hold a non-null channel_id. The half of this page that has no real rows to run against is campaigns — see below.

One table in hivecfm that does not ship

hivecfm also contains a "SurveyChannel" table — id, name, survey_id, environment_id, legacy_id, legacy_guid, legacy_extras, created_at, 0 rows. It is a migration-era artifact and there is no SurveyChannel model at origin/development (git grep -c 'model SurveyChannel' origin/development -- packages/database/schema.prisma matches nothing). Do not build on it. The shipping relationship is one-way and lives on the survey: "Survey".channel_id → channels.id. (Its legacy_id/legacy_guid/legacy_extras columns are migration-owned: works only while a migration program is open; after retirement these columns are gone — use the migrate export-provenance artifact.)

Scoping by organization instead of environment

When you hold an organizationId rather than an environmentId, channels needs the two-hop join. It cannot inherit tenancy from RLS, because it has none:

SELECT c.id, c.name, c.type, c.environment_id,
       e.type AS env_type, p.name AS project
FROM channels c
JOIN "Environment" e ON e.id = c.environment_id
JOIN "Project"     p ON p.id = e."projectId"
WHERE p."organizationId" = :'organization_id'
ORDER BY p.name, e.type, c.name;
 Incremental Sort  (cost=21.64..21.69 rows=2 width=136)
   Sort Key: p.name, e.type, c.name
   ->  Nested Loop  (cost=4.47..21.63 rows=2 width=136)
         ->  Index Scan using "Project_organizationId_name_key" on "Project" p
               Index Cond: ("organizationId" = 'org_cuid_here'::text)
         ->  Bitmap Index Scan on "Environment_projectId_idx"
               Index Cond: ("projectId" = p.id)
         ->  Index Scan using channels_environment_id_name_key on channels c
               Index Cond: (environment_id = e.id)

Substituting the real organizationId from hivecfm returns all 66 channels across one project and one production environment.

Asserting that no survey points across environments

Because neither the application nor the database enforces it, this is worth running as an assertion. It should return no rows:

SELECT s.id              AS survey_id,
       s.name            AS survey_name,
       s."environmentId" AS survey_env,
       c.id              AS channel_id,
       c.name            AS channel_name,
       c.environment_id  AS channel_env
FROM "Survey" s
JOIN channels c ON c.id = s.channel_id
WHERE s."environmentId" = :'environment_id'
  AND c.environment_id <> s."environmentId";
 Nested Loop  (cost=0.29..16.34 rows=1 width=192)
   ->  Index Scan using "Survey_environmentId_updated_at_idx" on "Survey" s
         Index Cond: ("environmentId" = 'cmr0o5ivu000clc01glv55m4p'::text)
   ->  Index Scan using channels_pkey on channels c
         Index Cond: (id = s.channel_id)
         Filter: (environment_id <> s."environmentId")

It returns 0 rows on hivecfm, across all 547 surveys there that carry a channel. Note what a clean result does and does not prove. That database has two environments, but only one of them is populated: all 66 channels and all 1191 surveys sit in the production environment cmr0o5ivu000clc01glv55m4p, and the development environment cmr0o5ivf0006lc01atf3swul holds neither a channel nor a survey. There is no second populated environment for a cross-environment assignment to show up in, so the clean result is consistent with the check working and with there being nothing to catch. The assertion only carries weight on a deployment where both environments hold rows.

Seven channel types, three survey types, and no bot

The two enums do not line up, and the gap is load-bearing.

EnumMembers
ChannelTypeweb, mobile, link, voice, whatsapp, sms, email
SurveyTypelink, app, voice

Both verified from pg_enum on devhub_ref; the source is schema.prisma:393-407.

There is no bot survey type and no chat channel type. A chat or bot survey is an ordinary survey — usually app or link — that a connector drives from the outside. That is why the Genesys Bot Connector takes the survey as a request parameter rather than looking one up by kind: turn/route.ts:402 reads body.parameters?.surveyId, and :405-410 rejects the turn with the reply text Survey ID not provided. Pass surveyId in inputParameters. when it is absent. The bot is not a survey type; it is a caller.

Two consequences for queries:

  • count(*) ... GROUP BY s.type will never show you a bot or chat population. Group by c.type through channel_id if you want the configured door, and read the section on survey_delivery_channel below for what actually happened at delivery time.
  • voice is the only member the two enums share, and it means the IVR path. See Genesys and IVR and IVR Webhook Flow.

Surveys with no channel

channel_id is nullable — String? at schema.prisma:460, is_nullable = YES in the catalog — and unassigned is the common case, not an anomaly:

SELECT s.type,
       s.status,
       count(*) AS surveys
FROM "Survey" s
WHERE s."environmentId" = :'environment_id'
  AND s.channel_id IS NULL
GROUP BY s.type, s.status
ORDER BY surveys DESC;
 Index Scan using "Survey_environmentId_updated_at_idx" on "Survey" s
   Index Cond: ("environmentId" = 'cmr0o5ivu000clc01glv55m4p'::text)
   Filter: (channel_id IS NULL)

On hivecfm, 644 of 1191 surveys have no channel, and every one of them is type app:

 type |   status   | surveys
------+------------+---------
 app  | inProgress |     388
 app  | draft      |     198
 app  | completed  |      58

What a null means depends on the survey type, and there are two ways to arrive at one.

For app and link surveys a null is simply unset metadata. Nothing at origin/development requires a channel to deliver or record a response; the 644 rows above are proof that the application is happy without one.

For a voice survey a null costs the survey its channel-level IVR prompts. linearizeSurveyForIvr reads the config off the channel — .../ivr/[surveyId]/lib/ivr.ts:348:

const channelConfig = survey.channelId ? (survey as any).channel?.config : null;

Be precise about what is lost, because it is less than the type suggests. :349-359 substitutes a hard-coded object when channelConfig is null or is not a voice config, and the function reads only five fields off the result (:441, :452-455). So inputTimeout, maxRetries and bargeinEnabled fall back to 5, 3 and true — the same values ZVoiceChannelConfig defaults to anyway (packages/types/channel.ts:45-47) — thankYouMessage falls back to the survey’s own first ending and errorMessage to the literal Invalid input, please try again. What a null actually removes is the pair of channel-authored prompts. The remaining ZVoiceChannelConfig fields — ttsEngine, defaultVoice, defaultLanguage, audioBaseUrl — are not read by the IVR runtime at all whether the channel is present or not; the only code that touches them is the channel editor (apps/web/modules/channels/components/channel-form-dialog.tsx, channel-list.tsx:70).

That still makes a voice survey with channel_id IS NULL worth flagging — it is running on defaults nobody chose:

SELECT s.id, s.name, s.status
FROM "Survey" s
WHERE s."environmentId" = :'environment_id'
  AND s.type = 'voice'
  AND s.channel_id IS NULL;

Assigning a channel also constrains what the survey may contain, which is the other reason the field is not merely decorative: validateRestrictedChannelElements rejects any element outside VOICE_COMPATIBLE_ELEMENT_TYPES on a voice channel, caps multipleChoiceSingle at 9 choices for DTMF keys 1-9, and applies a separate compatibility list plus a WhatsApp-specific 10-button NPS rule to the messaging types (apps/web/lib/survey/service.ts:51-102). A survey with no channel is exempt from all of it — :42 returns early on a null channelId.

⚠️

A null can also mean the channel was deleted, and the application guard does not cover SQL. deleteChannel refuses when surveys still point at the channel — apps/web/lib/channel/service.ts:157-165 counts them and throws Cannot delete channel: N survey(s) are still assigned to it. Reassign or delete them first. The database constraint disagrees:

"Survey_channel_id_fkey" FOREIGN KEY (channel_id) REFERENCES channels(id)
    ON UPDATE CASCADE ON DELETE SET NULL

A direct DELETE FROM channels WHERE id = '...' bypasses the service-layer check entirely and silently nulls channel_id on every survey that used it. There is no audit trail on the survey row. If a set of surveys lost their channel and nobody knows when, that is the mechanism.

Inspecting channels.config

config is jsonb NOT NULL DEFAULT '{}'. The typed shape is a discriminated union on type (packages/types/channel.ts:84-92) — per-type settings such as widgetPlacement for web, sdkPlatform for mobile, customSlug for link, the TTS block for voice, provider / phoneNumberId / businessAccountId / templateName for whatsapp, provider / senderId / maxMessageLength for sms, and fromName / replyTo for email.

Inspect the keys, not the values:

SELECT c.type,
       k.key,
       count(*) AS channels_with_key
FROM channels c
CROSS JOIN LATERAL jsonb_object_keys(c.config) AS k(key)
WHERE c.environment_id = :'environment_id'
GROUP BY c.type, k.key
ORDER BY c.type, k.key;
 GroupAggregate  (cost=21.15..25.15 rows=200 width=44)
   Group Key: c.type, k.key
   ->  Nested Loop  (cost=4.17..13.51 rows=200 width=36)
         ->  Bitmap Index Scan on channels_environment_id_name_key
               Index Cond: (environment_id = 'cmr0o5ivu000clc01glv55m4p'::text)
         ->  Function Scan on jsonb_object_keys k

On hivecfm it returns zero rows, and that is a fact about the data rather than a broken recipe: all 66 channels there still carry the column default, verified by SELECT config::text, count(*) FROM channels GROUP BY 1 returning exactly one group — {}, 66 rows. The recipe is EXPLAIN-verified and shape-correct; there is no configured channel in either local database to demonstrate it against.

⚠️

Treat config as sensitive, and do not rely on the database to protect it.

Two independent reasons. First, the column is unconstrained jsonb. updateChannel does run the zod union — validateInputs([channelInput, ZChannelUpdateInput]) at channel/service.ts:109 — but it discards the parsed result and writes the caller’s original object (:129-131), so the strip that z.object would have performed never reaches the database, and nothing at the database level rejects extra keys either. getChannel then returns the column verbatim through selectChannel (channel/service.ts:18-27) to GET /api/v1/management/channels/[channelId]. A provider token written into it by any client persists and is served back. The typed union itself defines no credential field, so this is about what the column can hold, not what it is declared to hold.

Second, channels has no row-level security at all — RLS neither enabled nor policied, because both scripts/rls/enable-rls.sql and scripts/rls/create-policies.sql address the table by its Prisma model name "Channel" and fail. Full derivation, including why renaming the target is not enough to fix it, is in Read this first, section 5. The consequence here: the tenant predicate in every recipe on this page is the only isolation on this table, and a SELECT config FROM channels with no predicate reads every tenant’s connector settings.

So: never SELECT c.config into a shared terminal, a ticket, or a paste buffer. Query keys, jsonb_object_keys, ? existence tests, or specific non-secret fields such as config->>'ttsEngine'.

The campaign delivery funnel

Every campaign recipe below is EXPLAIN-verified only. "Campaign" and "CampaignSend" both have 0 rows in hivecfm, so no campaign query on this page has been run against real data anywhere. The plans are from devhub_ref, which is also empty — a plan there proves the query is valid and shows which indexes are available, not which plan a populated production table would get.

Four counters live on "Campaign": total_count, sent_count, failed_count, and the status enum. All four are denormalised summaries written by apps/web/lib/campaign/send-campaign.ts, and each has a distinct way of going wrong.

The diagnostic query compares each counter against the rows it is supposed to summarise:

SELECT ca.id,
       ca.name,
       ca.status,
       ca.provider_type,
       ca.total_count,
       ca.sent_count,
       ca.failed_count,
       count(cs.id)                                  AS send_rows,
       count(*) FILTER (WHERE cs.status = 'sent')    AS rows_sent,
       count(*) FILTER (WHERE cs.status = 'failed')  AS rows_failed,
       count(*) FILTER (WHERE cs.status = 'pending') AS rows_pending,
       count(*) FILTER (WHERE cs.status = 'bounced') AS rows_bounced
FROM "Campaign" ca
LEFT JOIN "CampaignSend" cs ON cs.campaign_id = ca.id
WHERE ca.environment_id = :'environment_id'
GROUP BY ca.id, ca.name, ca.status, ca.provider_type,
         ca.total_count, ca.sent_count, ca.failed_count, ca.created_at
ORDER BY ca.created_at DESC;

count(cs.id) rather than count(*), so a campaign with no sends reports 0 instead of 1.

 GroupAggregate  (cost=17.70..17.76 rows=1 width=160)
   Group Key: ca.id
   ->  Nested Loop Left Join  (cost=4.31..17.69 rows=2 width=156)
         ->  Index Scan using "Campaign_environment_id_idx" on "Campaign" ca
               Index Cond: (environment_id = 'cmr0o5ivu000clc01glv55m4p'::text)
         ->  Bitmap Index Scan on "CampaignSend_campaign_id_idx"
               Index Cond: (campaign_id = ca.id)

The same comparison as an assertion — it should return no rows, and every row it returns is a campaign whose counters drifted:

SELECT ca.id,
       ca.status,
       ca.total_count,
       ca.sent_count,
       ca.failed_count,
       count(cs.id)                                  AS send_rows,
       count(*) FILTER (WHERE cs.status = 'sent')   AS rows_sent,
       count(*) FILTER (WHERE cs.status = 'failed') AS rows_failed
FROM "Campaign" ca
LEFT JOIN "CampaignSend" cs ON cs.campaign_id = ca.id
WHERE ca.environment_id = :'environment_id'
GROUP BY ca.id, ca.status, ca.total_count, ca.sent_count, ca.failed_count
HAVING ca.sent_count   <> count(*) FILTER (WHERE cs.status = 'sent')
    OR ca.failed_count <> count(*) FILTER (WHERE cs.status = 'failed')
    OR ca.total_count  <> count(cs.id)
ORDER BY ca.id;
 GroupAggregate  (cost=17.70..17.75 rows=1 width=72)
   Group Key: ca.id
   Filter: ((ca.sent_count <> count(*) FILTER (WHERE (cs.status = 'sent'::"CampaignSendStatus")))
         OR (ca.failed_count <> count(*) FILTER (WHERE (cs.status = 'failed'::"CampaignSendStatus")))
         OR (ca.total_count <> count(cs.id)))

A mismatch means the counters drifted. The CampaignSend rows are the record; the counters on "Campaign" are a cache. There are four specific mechanisms, all readable in send-campaign.ts:

  1. total_count is not “contacts targeted”. It is set to contactsWithEmail.length (:114) or contactsWithPhone.length (:293) — after the segment has been filtered for a usable address (:64, :278). Contacts in the segment with no email or phone are dropped at :64 / :278 and appear in no counter and no CampaignSend row. total_count is silently smaller than the segment, and the difference is invisible from these tables. This is the most misread counter of the four.
  2. sent_count and failed_count are in-memory locals written exactly once, at the very end (:210-218 for email, :365-373 for SMS). If the process dies mid-send, every CampaignSend row is already durable but neither counter is ever written and status stays sending forever.
  3. A contact can land in both counters. In the email path, sentCount++ at :186 runs before the campaignSend.updateMany at :187. If that update throws, the catch at :194 does failedCount++ for the same contact. sent_count + failed_count > total_count is reachable.
  4. status is not a per-recipient verdict. The final update sets failed only when every recipient failed — failedCount === contactsWithEmail.length (:213) — and sent otherwise. A campaign with one success and 4,999 failures reports sent.

Campaigns stuck in sending

Mechanism 2 above has no recovery path. processScheduledCampaigns selects only status: "scheduled" with scheduledAt <= now (apps/web/lib/campaign/campaign-scheduler.ts:9-15), so nothing ever retries or reconciles a campaign left in sending:

SELECT ca.id,
       ca.name,
       ca.status,
       ca.provider_type,
       ca.scheduled_at,
       ca.updated_at,
       ca.total_count,
       count(cs.id) FILTER (WHERE cs.status = 'pending') AS still_pending
FROM "Campaign" ca
LEFT JOIN "CampaignSend" cs ON cs.campaign_id = ca.id
WHERE ca.environment_id = :'environment_id'
  AND ca.status = 'sending'
  AND ca.updated_at < now() - interval '1 hour'
GROUP BY ca.id, ca.name, ca.status, ca.provider_type,
         ca.scheduled_at, ca.updated_at, ca.total_count
ORDER BY ca.updated_at;
 Index Scan using "Campaign_environment_id_idx" on "Campaign" ca
   Index Cond: (environment_id = 'cmr0o5ivu000clc01glv55m4p'::text)
   Filter: ((status = 'sending'::"CampaignStatus") AND (updated_at < (now() - '01:00:00'::interval)))

still_pending > 0 on such a row means those recipients were never handed to Novu at all. still_pending = 0 with status = 'sending' means the sends completed and only the final counter update was lost. Broader stuck-work queries live in Operational queries.

provider_type accepts more than the dispatcher does

provider_type is plain text with default 'email', not an enum. Creation is constrained — ZCampaignCreateInput.providerType is ZCampaignProviderType = email | sms (packages/types/campaign.ts:9,16) — but the read schema declares it as bare z.string() (:29) and the column has no check constraint. sendCampaign switches on it and throws Unsupported campaign provider type: <value> for anything else (send-campaign.ts:389-396). A campaign row whose provider_type is neither email nor sms will never send and will report nothing useful about why, so it is worth asserting:

SELECT ca.id, ca.name, ca.status, ca.provider_type
FROM "Campaign" ca
WHERE ca.environment_id = :'environment_id'
  AND ca.provider_type NOT IN ('email', 'sms');

Failure breakdown, and the bounce path that is not wired

CampaignSend.error is free-form text taken from the caught exception’s message, or one of two literals the send path writes itself:

SELECT cs.status,
       coalesce(cs.error, '(no error text recorded)') AS error,
       count(*)                       AS sends,
       count(DISTINCT cs.campaign_id) AS campaigns,
       max(cs.created_at)             AS last_seen
FROM "CampaignSend" cs
JOIN "Campaign" ca ON ca.id = cs.campaign_id
WHERE ca.environment_id = :'environment_id'
  AND cs.status IN ('failed', 'bounced')
GROUP BY cs.status, cs.error
ORDER BY sends DESC, error;
 GroupAggregate  (cost=17.69..17.72 rows=1 width=92)
   Group Key: cs.status, cs.error
   ->  Nested Loop  (cost=4.31..17.68 rows=1 width=76)
         ->  Index Scan using "Campaign_environment_id_idx" on "Campaign" ca
               Index Cond: (environment_id = 'cmr0o5ivu000clc01glv55m4p'::text)
         ->  Bitmap Index Scan on "CampaignSend_campaign_id_idx"
               Index Cond: (campaign_id = ca.id)
         Filter: (status = ANY ('{failed,bounced}'::"CampaignSendStatus"[]))

Grouping on the raw error string is right for triage — the strings are exception messages and cluster naturally — but two of the values are known and fixed. Failed to generate survey link is written at send-campaign.ts:143 when getContactSurveyLink returns not-ok, and it is the one failure the code records without going through the catch block. Everything else is error.message, or the literal Unknown error when the thrown value was not an Error (:201, :358).

⚠️

bounced is a dead enum member at origin/development. Nothing writes it. All eight campaignSend write sites are send-campaign.ts:137, 152, 187, 197, 305, 344, 354 and apps/web/app/api/v1/novu/sms-inbound/route.ts:296, and every one sets pending, sent, or failed. Elsewhere in code the token appears only in the enum DDL (schema.prisma:421, packages/database/migration/20260120000000_add_channels_and_review_log/migration.sql:72), in ZCampaignSendStatus (packages/types/campaign.ts:6), and in a UI ternary that groups it with failed for display (campaigns/[campaignId]/components/campaign-detail.tsx:149).

Outside the code, the token appears only in prose: docs/technical/02-database-schema.md:396 and :1309, and docs/technical/04-survey-engine.md:197 and :735, all of which describe it as a live per-recipient status. It is not.

So the rows_bounced column in the funnel query and the 'bounced' term in the filter above will be 0 and empty respectively, permanently, at this ref. They are in the recipes so that the day something starts writing bounces the query already reports them — not because bounce data exists to be found. A dashboard built on a bounce rate here reads a hard-coded zero. Novu delivery webhooks are not consumed for this purpose; the one inbound Novu route is the SMS reply handler.

Attributing a response to a delivery

"Response" carries two delivery-context columns, added together in packages/database/migration/20260114220000_add_genesys_context_fields/migration.sql:14-15:

survey_delivery_channel  text
survey_delivered_at      timestamp(3)
⚠️

Three parts of the codebase disagree about what survey_delivery_channel holds, and a migrated database contains a fourth thing. Establish which you are reading before you group by it.

  1. The writers put a lowercase token in it. Exactly two write sites exist at origin/development, both in apps/web/lib/response/service.ts: createEmailEmbedInvitation at :886 writes whatever the caller passed (surveyDeliveryChannel: channel ?? undefined), and createEmailCampaignInvitation at :944 hard-codes "email".
  2. The reader in the license-reporting path agrees, and says so: apps/web/app/api/v1/management/license-reports/lib/channel-groups.ts:47 comments that the column is a free-form string ("sms", "whatsapp", "voice", "chat", …) and maps it through the 12-entry DELIVERY_CHANNEL_ALIASES table at :49-62, falling back to the survey’s type when the value is unrecognised.
  3. The Superset view layer treats it as a channel name. scripts/superset/create-views.sql:620 and :810 both project it as AS channel_name. That layer is not even self-consistent: :234 projects the same column as AS delivery_channel, and ten further sites in the same file carry it through under its own name.
  4. In hivecfm it holds something else again. Grouping the 1498 responses there yields 68 groups: 67 distinct free-form values plus a single null row. Most of them are channel names — 59 of the 67 match a row in channels.name, including General, MobileSDKReact, Absher Channel and In-Chat. The remaining eight match no channel at all: CC Email, CC Voice, embed, EMBED_WEB, MobileChannel, Popup, QR_Code, Social_Media. Not one of the 67 is in DELIVERY_CHANNEL_ALIASES, so deliveryChannelToLabel returns null for every row and the report silently falls through to the survey’s channel or type for all 1498.

Those values were written by the migrator, which is not part of origin/development — git ls-tree -d --name-only origin/development -- packages/ lists no packages/migrator. So nothing at this ref writes them, and nothing at this ref reads them correctly either. Any cross-deployment report keyed on this column is comparing two different vocabularies.

The channel and invitation breakdown, using the response-versus-invitation rule from Responses and answers:

SELECT coalesce(r.survey_delivery_channel, '(null)')          AS delivery_channel,
       count(*)                                              AS sessions,
       count(*) FILTER (WHERE r.answered_questions_count > 0) AS responses,
       count(*) FILTER (WHERE r.answered_questions_count = 0) AS invitations,
       count(r.survey_delivered_at)                           AS with_delivered_at
FROM "Response" r
JOIN "Survey" s ON s.id = r."surveyId"
WHERE s."environmentId" = :'environment_id'
GROUP BY 1
ORDER BY sessions DESC;
 GroupAggregate  (cost=16.34..16.37 rows=1 width=64)
   Group Key: (COALESCE(r.survey_delivery_channel, '(null)'::text))
   ->  Nested Loop  (cost=0.29..16.33 rows=1 width=44)
         ->  Index Scan using "Survey_environmentId_updated_at_idx" on "Survey" s
               Index Cond: ("environmentId" = 'cmr0o5ivu000clc01glv55m4p'::text)
         ->  Index Scan using "Response_surveyId_singleUseId_key" on "Response" r
               Index Cond: ("surveyId" = s.id)

This one cannot be run in full against hivecfm: that database has no answered_questions_count column, which Read this first, section 3 documents as one of the two places the schemas diverge. Dropping the two FILTER clauses makes it runnable there, and the reduced form is what produced the 68-channel-name result quoted above — including with_delivered_at = 0 on every single row.

Which paths leave these columns null

survey_delivered_at is only ever written in the same two prisma.response.create calls as survey_delivery_channel (service.ts:887, :945), both as now. That gives exactly three callers that populate either column:

CallerSets survey_delivery_channelSets survey_delivered_at
POST /api/v1/management/survey/email-embed (route.ts:138)caller-supplied channelyes
POST /api/v1/management/survey/survey-link (route.ts:132)caller-supplied channelyes
Email campaign send (send-campaign.ts:175)"email", hard-codedyes

Every other path leaves both null:

  • The SMS campaign path. It does not call createEmailCampaignInvitation at all — it goes through createResponseWithQuotaEvaluation with meta: { source: "sms_campaign" } (send-campaign.ts:315-323) and sets neither column. An SMS campaign therefore produces responses that are indistinguishable from any other by delivery channel; meta->>'source' is the only marker.
  • IVR. .../ivr/[surveyId]/route.ts:169 only selects surveyDeliveredAt, and the response handler writes meta.source = "ivr" instead.
  • The bot connector. Same shape: turn/route.ts:534 selects the column, never assigns it.
  • Ordinary link and app responses. The browser response path writes neither.

The practical consequence: survey_delivered_at is present on email invitations and nowhere else, which is exactly the invariant getExpiryAnchor encodes — apps/web/lib/survey/session-ttl.ts:86 anchors an invitation’s expiry at surveyDeliveredAt ?? createdAt, and its own test names the fallback case “invitation without surveyDeliveredAt (bot/IVR session rows) falls back to createdAt” (session-ttl.test.ts:133). So count(survey_delivered_at) is a count of email invitations, not a count of deliveries.

The resolution the application actually uses

Do not group on survey_delivery_channel alone. The codebase has one canonical answer to “which channel did this response come through”, and it is a three-tier fallback — resolveResponseLabel at channel-groups.ts:73-79: the aliased delivery channel wins, then the survey’s channels.type, then the survey’s SurveyType. Reproducing it in SQL means carrying the alias table, because an unaliased value must resolve to null so the fallback fires; a plain coalesce on the raw column would let General win and never reach the channel:

WITH alias(raw, label) AS (
  VALUES ('web',      'Web & Mobile'), ('app',     'Web & Mobile'),
         ('mobile',   'Web & Mobile'), ('chat',    'Web & Mobile'),
         ('webchat',  'Web & Mobile'), ('voice',   'Voice'),
         ('ivr',      'Voice'),        ('call',    'Voice'),
         ('link',     'Link'),         ('whatsapp','WhatsApp'),
         ('sms',      'SMS'),          ('email',   'Email')
)
SELECT coalesce(
         a.label,
         CASE c.type
           WHEN 'web'      THEN 'Web & Mobile'
           WHEN 'mobile'   THEN 'Web & Mobile'
           WHEN 'voice'    THEN 'Voice'
           WHEN 'link'     THEN 'Link'
           WHEN 'whatsapp' THEN 'WhatsApp'
           WHEN 'sms'      THEN 'SMS'
           WHEN 'email'    THEN 'Email'
         END,
         CASE s.type
           WHEN 'app'   THEN 'Web & Mobile'
           WHEN 'voice' THEN 'Voice'
           WHEN 'link'  THEN 'Link'
         END
       )                                                            AS channel_label,
       count(*)                                                     AS sessions,
       count(*) FILTER (WHERE a.label IS NOT NULL)                  AS from_delivery_channel,
       count(*) FILTER (WHERE a.label IS NULL AND c.id IS NOT NULL) AS from_survey_channel,
       count(*) FILTER (WHERE a.label IS NULL AND c.id IS NULL)     AS from_survey_type
FROM "Response" r
JOIN "Survey" s ON s.id = r."surveyId"
LEFT JOIN channels c ON c.id = s.channel_id
LEFT JOIN alias   a ON a.raw = lower(btrim(r.survey_delivery_channel))
WHERE s."environmentId" = :'environment_id'
GROUP BY 1
ORDER BY sessions DESC;

The three FILTER columns are the point: they report which tier answered, so the output audits its own provenance. The VALUES list mirrors DELIVERY_CHANNEL_ALIASES (channel-groups.ts:49-62), the first CASE mirrors channelTypeToLabel (:18-34), and the second mirrors surveyTypeToLabel (:36-45). lower(btrim(...)) matches the raw.trim().toLowerCase() at :66.

 GroupAggregate  (cost=24.93..24.98 rows=1 width=64)
   ->  Nested Loop Left Join  (cost=0.43..24.92 rows=1 width=96)
         Join Filter: ("*VALUES*".column1 = lower(btrim(r.survey_delivery_channel)))
         ->  Nested Loop Left Join  (cost=0.43..24.54 rows=1 width=72)
               ->  Nested Loop  (cost=0.29..16.33 rows=1 width=68)
                     ->  Index Scan using "Survey_environmentId_updated_at_idx" on "Survey" s
                           Index Cond: ("environmentId" = 'cmr0o5ivu000clc01glv55m4p'::text)
                     ->  Index Scan using "Response_surveyId_singleUseId_key" on "Response" r
                           Index Cond: ("surveyId" = s.id)
               ->  Index Scan using channels_pkey on channels c
                     Index Cond: (id = s.channel_id)
         ->  Values Scan on "*VALUES*"  (cost=0.00..0.15 rows=12 width=64)

Run against hivecfm it resolves all 1498 responses, and the provenance columns settle the contradiction numerically:

 channel_label | sessions | from_delivery_channel | from_survey_channel | from_survey_type
---------------+----------+-----------------------+---------------------+------------------
 Web & Mobile  |     1215 |                     0 |                1214 |                1
 Email         |      154 |                     0 |                 154 |                0
 Link          |      100 |                     0 |                 100 |                0
 Voice         |       24 |                     0 |                  24 |                0
 WhatsApp      |        5 |                     0 |                   5 |                0

from_delivery_channel is zero on every row, even though 1497 of those 1498 responses carry a non-null survey_delivery_channel. Tier one contributes nothing; every label came from channels.type (1497) or, for the single row with a null delivery channel and no survey channel, from SurveyType (1). That is the migrated-channel-names problem measured rather than asserted — and it is also the reason this recipe is the one to use: channels.type is a real enum with seven members, and it answered every row.

Joining a campaign to its responses

There is no foreign key from "Response" to "CampaignSend" or to "Campaign". The only bridge is the contact:

SELECT ca.id   AS campaign_id,
       ca.name AS campaign_name,
       count(DISTINCT cs.contact_id) AS contacts_sent,
       count(DISTINCT r."contactId") AS contacts_that_answered
FROM "Campaign" ca
JOIN "CampaignSend" cs
       ON cs.campaign_id = ca.id
      AND cs.status = 'sent'
LEFT JOIN "Response" r
       ON r."contactId" = cs.contact_id
      AND r."surveyId"  = ca.survey_id
      AND r.answered_questions_count > 0
      AND r.created_at >= cs.created_at
WHERE ca.environment_id = :'environment_id'
GROUP BY ca.id, ca.name
ORDER BY contacts_sent DESC;
 GroupAggregate  (cost=23.87..23.89 rows=1 width=80)
   Group Key: ca.id
   ->  Nested Loop Left Join  (cost=4.45..23.86 rows=1 width=128)
         Join Filter: (r."surveyId" = ca.survey_id)
         ->  Index Scan using "Campaign_environment_id_idx" on "Campaign" ca
               Index Cond: (environment_id = 'cmr0o5ivu000clc01glv55m4p'::text)
         ->  Bitmap Index Scan on "CampaignSend_campaign_id_idx"
               Index Cond: (campaign_id = ca.id)
         ->  Index Scan using "Response_contactId_created_at_idx" on "Response" r
               Index Cond: (("contactId" = cs.contact_id) AND (created_at >= cs.created_at))
               Filter: (answered_questions_count > 0)

Three predicates carry the whole argument, and each is a deliberate narrowing: r."surveyId" = ca.survey_id keeps the response on the campaign’s own survey, answered_questions_count > 0 excludes the invitation rows the send itself created, and r.created_at >= cs.created_at excludes answers that predate the send.

⚠️

What this join can and cannot prove. It proves that a contact who was sent this campaign later answered this survey. It does not prove the campaign caused the answer, and the gap is not small:

  • A second send to the same contact is indistinguishable. Two campaigns on one survey to overlapping segments both match the same response. The response is counted for both, and count(DISTINCT r."contactId") summed across campaigns can exceed the number of contacts who actually answered.
  • A link survey answered outside any campaign still matches. If the contact reached the survey from a QR code, an embedded widget, or a link somebody forwarded, the row satisfies every predicate. There is nothing on "Response" that records which delivery it came from — survey_delivery_channel would be the field for that, and the section above shows it is null on every path except email invitations.
  • The email campaign path converts its own invitation in place. createEmailCampaignInvitation writes a zero-answer row (service.ts:912-958), and the personalized /c/ link threads it as singleUseResponseId (apps/web/modules/survey/link/contact-survey/page.tsx:115, passed on at apps/web/modules/survey/link/components/survey-renderer.tsx:176) so the recipient’s first answer updates that row rather than creating a new one. So an attributed answer often has created_at from the send, not from the answer, and a stricter time window will exclude the very conversions you are trying to count. Widening the window instead admits more unrelated traffic. There is no window that is correct.
  • It is a contact-level count, not a response-level one. A contact who answered twice counts once.

Treat the output as an upper bound on campaign-attributed responses. If you need real attribution, the answer is not a better join — it is a delivery identifier written onto the response at send time, which does not exist at this ref.

Where to look in the code

  • packages/database/schema.prisma:796-812 — the Channel model, its @@map("channels"), @@unique([environmentId, name]), and the config jsonb default.
  • packages/database/schema.prisma:1412-1452 — Campaign and CampaignSend, all-snake columns and their four indexes.
  • packages/database/schema.prisma:393-422 — SurveyType, ChannelType, CampaignStatus, CampaignSendStatus.
  • packages/database/schema.prisma:459-460 — Survey.channel/channelId, nullable, with no explicit onDelete, so Prisma’s default for an optional relation applies and the emitted DDL is ON DELETE SET NULL.
  • packages/database/schema.prisma:235-237 — the Survey Delivery Context block on Response.
  • packages/types/channel.ts — the ZChannelConfig discriminated union (:84-92), the voice config (:39-52), and VOICE_COMPATIBLE_ELEMENT_TYPES (:131-137).
  • packages/types/campaign.ts — ZCampaignProviderType at :9, and ZCampaign.providerType: z.string() at :29, which is the looser of the two.
  • apps/web/lib/campaign/send-campaign.ts — the whole funnel: email flow at :31-219, SMS flow at :223-374, dispatcher at :378-397.
  • apps/web/lib/campaign/campaign-scheduler.ts:9-15 — the cron sweep, scheduled only, no reconciliation of sending.
  • apps/web/lib/response/service.ts:834-958 — the only two writers of survey_delivery_channel / survey_delivered_at.
  • apps/web/lib/channel/service.ts — selectChannel at :18-27, the config write at :129-131, the delete guard at :157-165.
  • apps/web/app/api/v1/management/channels/route.ts and .../[channelId]/route.ts — GET/POST and GET/PUT/DELETE, the API surface that returns config.
  • apps/web/app/api/v1/management/license-reports/lib/channel-groups.ts — channelTypeToLabel (:18-34), surveyTypeToLabel (:36-45), the free-form-string comment and 12-entry DELIVERY_CHANNEL_ALIASES (:47-62), deliveryChannelToLabel (:64-67), and the three-tier resolveResponseLabel (:73-79).
  • scripts/superset/create-views.sql:620,810 — survey_delivery_channel AS channel_name, the other reading of the same column.
  • apps/web/app/api/v1/client/[environmentId]/ivr/[surveyId]/lib/ivr.ts:348 — where the voice config is read off the channel, :349-359 the hard-coded fallback when it is absent, and :441, :452-455 the only five fields either one is read for.
  • apps/web/lib/survey/service.ts:38-103 — validateRestrictedChannelElements, the only place a channel is validated on survey write, and the reason it never checks environmentId.
  • Campaign send flow — the same funnel as a sequence diagram, and why there is no bounce webhook to reconcile against.
  • Genesys Bot Connector — why a chat survey needs a surveyId parameter rather than a survey type.
  • Genesys and IVR — the genesys_* columns that the voice channel fills in.
  • Responses and answers — the invitation filter used throughout this page.
  • Contacts and segments — why a contact count is not a reachable-audience count, and why the two segment evaluators disagree about who is in a segment.
  • Integrations — Novu, the transport every campaign send goes through.

HiveCFM Developer Hub — internal team guide