Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(signals): match repo-qualified schema names in inbox source setup (#79507)

Andrew Maguire424e56014cf2
diff --git a/products/data_warehouse/frontend/scenes/NewSourceScene/sourceWizardLogic.tsx b/products/data_warehouse/frontend/scenes/NewSourceScene/sourceWizardLogic.tsx
index 44c9a97d0e2f..8c286b7db24a 100644
--- a/products/data_warehouse/frontend/scenes/NewSourceScene/sourceWizardLogic.tsx
+++ b/products/data_warehouse/frontend/scenes/NewSourceScene/sourceWizardLogic.tsx
@@ -3291,6 +3291,45 @@ export const sourceWizardLogic = kea<sourceWizardLogicType>([
return
}
+ // Webhook-sync tables produce no rows until the webhook is registered with the
+ // provider, and the required-tables flow never shows the webhook step (step 4) —
+ // register the webhook after creation and only report completion once it succeeds.
+ const registerRequiredWebhookAndComplete = async (sourceId: string): Promise<void> => {
+ let webhookResult: WebhookCreateResult
+ try {
+ webhookResult = await api.externalDataSources.createWebhook(sourceId)
+ } catch (e: any) {
+ posthog.captureException(e)
+ webhookResult = {
+ success: false,
+ webhook_url: '',
+ error: e.data?.message ?? e.message,
+ }
+ }
+ actions.setWebhookResult(webhookResult)
+ if (!webhookResultHasNoPendingInputs(webhookResult)) {
+ lemonToast.error(
+ `We created the source but couldn't set up its webhook${
+ webhookResult.error ? `: ${webhookResult.error}` : ''
+ }. Connect again to retry, or finish webhook setup in the source settings.`
+ )
+ return
+ }
+ props.onComplete!()
+ }
+
+ // A required-tables run whose webhook registration failed left the source created —
+ // retry the webhook instead of creating a duplicate source.
+ if (values.requiredTables && props.onComplete && values.sourceId) {
+ if (values.hasWebhookSchemas) {
+ await registerRequiredWebhookAndComplete(values.sourceId)
+ } else {
+ props.onComplete()
+ }
+ actions.setIsLoading(false)
+ return
+ }
+
try {
const { id } = await api.externalDataSources.create({
...values.source,
@@ -3318,7 +3357,11 @@ export const sourceWizardLogic = kea<sourceWizardLogicType>([
// When requiredTables is set (e.g. signals setup), skip step 4 and complete directly
if (values.requiredTables && props.onComplete) {
- props.onComplete()
+ if (values.hasWebhookSchemas) {
+ await registerRequiredWebhookAndComplete(id)
+ } else {
+ props.onComplete()
+ }
} else if (values.hasWebhookSchemas) {
// Go to webhook setup step (4)
actions.onNext()
@@ -3471,15 +3514,41 @@ export const sourceWizardLogic = kea<sourceWizardLogicType>([
// If required tables are specified (e.g. signals setup), skip the schema selection step
// entirely and create the source with only those tables, using their default sync settings
if (values.requiredTables) {
- const requiredSchemas = schemas.filter((schema) => values.requiredTables!.includes(schema.table))
- if (requiredSchemas.length !== values.requiredTables.length) {
- const missingTables = values.requiredTables.filter(
- (table: string) => !requiredSchemas.some((schema) => schema.table === table)
+ // Multi-repo sources qualify their schema names (`owner/repo.endpoint`), so a
+ // required table matches by suffix as well as exactly, and can resolve to one
+ // row per repo. Mirrors ensureRequiredTableSyncing in signalSourcesLogic.
+ const matchesRequiredTable = (tableName: string, requiredTable: string): boolean =>
+ tableName === requiredTable || tableName.endsWith(`.${requiredTable}`)
+ // The payload below forces should_sync on, so a permission-errored row would
+ // queue a guaranteed-403 sync. Treat it as unavailable instead.
+ const requiredSchemas = schemas.filter(
+ (schema) =>
+ !schema.permission_error &&
+ values.requiredTables!.some((table: string) => matchesRequiredTable(schema.table, table))
+ )
+ const missingTables = values.requiredTables.filter(
+ (table: string) => !requiredSchemas.some((schema) => matchesRequiredTable(schema.table, table))
+ )
+ if (missingTables.length > 0) {
+ const permissionError = schemas.find(
+ (schema) =>
+ schema.permission_error &&
+ missingTables.some((table: string) => matchesRequiredTable(schema.table, table))
+ )?.permission_error
+ lemonToast.error(
+ permissionError
+ ? `Source credentials cannot read the tables this needs (${missingTables.join(', ')}): ${permissionError}. Grant the missing scope in your source provider and reconnect.`
+ : `Required tables not found in source: ${missingTables.join(', ')}`
)
- lemonToast.error(`Required tables not found in source: ${missingTables.join(', ')}`)
actions.setIsLoading(false)
return
}
+ for (const schema of requiredSchemas) {
+ schema.should_sync = true
+ }
+ // createSource reads hasWebhookSchemas off databaseSchema to decide whether the
+ // new source still needs its webhook registered.
+ actions.setDatabaseSchemas(requiredSchemas)
actions.updateSource({
payload: {
diff --git a/products/data_warehouse/frontend/scenes/NewSourceScene/tests/sourceWizardLogic.test.ts b/products/data_warehouse/frontend/scenes/NewSourceScene/tests/sourceWizardLogic.test.ts
index 6a810296275f..7c367017544b 100644
--- a/products/data_warehouse/frontend/scenes/NewSourceScene/tests/sourceWizardLogic.test.ts
+++ b/products/data_warehouse/frontend/scenes/NewSourceScene/tests/sourceWizardLogic.test.ts
@@ -946,4 +946,179 @@ describe('sourceWizardLogic', () => {
}
})
})
+
+ // Signals setup passes requiredTables to skip the schema step and sync just those tables.
+ describe('requiredTables', () => {
+ const githubSource = {
+ name: 'Github',
+ iconPath: '',
+ caption: null,
+ fields: [],
+ } as SourceConfig
+
+ const apiSchema = (
+ table: string,
+ overrides: Partial<ExternalDataSourceSyncSchema> = {}
+ ): ExternalDataSourceSyncSchema =>
+ ({
+ table,
+ label: null,
+ rows: null,
+ should_sync: false,
+ sync_time_of_day: null,
+ incremental_field: null,
+ incremental_field_type: null,
+ sync_type: null,
+ incremental_fields: [],
+ incremental_available: false,
+ append_available: false,
+ supports_webhooks: false,
+ description: null,
+ should_sync_default: true,
+ primary_key_columns: null,
+ available_columns: [],
+ detected_primary_keys: null,
+ permission_error: null,
+ cdc_available: false,
+ ...overrides,
+ }) as ExternalDataSourceSyncSchema
+
+ const mountRequiredTablesWizard = (
+ requiredTables: string[]
+ ): { logic: ReturnType<typeof sourceWizardLogic>; onComplete: jest.Mock; unmount: () => void } => {
+ const onComplete = jest.fn()
+ const logic = sourceWizardLogic({
+ availableSources: { Github: githubSource },
+ requiredTables,
+ onComplete,
+ })
+ const unmount = logic.mount()
+ logic.actions.selectConnector(githubSource)
+ return { logic, onComplete, unmount }
+ }
+
+ afterEach(() => {
+ jest.restoreAllMocks()
+ })
+
+ it('syncs every repo-qualified row the credentials can read', async () => {
+ // Multi-repo sources name their rows `owner/repo.endpoint`, so an exact-match lookup
+ // for `issues` finds nothing and the wizard bails before creating the source. The
+ // payload forces should_sync on, so an unreadable row must not reach it.
+ jest.spyOn(api.externalDataSources, 'database_schema').mockResolvedValue([
+ apiSchema('posthog/posthog.issues'),
+ apiSchema('posthog/posthog-js.issues'),
+ apiSchema('posthog/posthog.commits'),
+ apiSchema('posthog/private.issues', { permission_error: 'Requires the "Issues" permission' }),
+ ] as ExternalDataSourceSyncSchema[])
+ const create = jest
+ .spyOn(api.externalDataSources, 'create')
+ .mockResolvedValue({ id: 'source-1' } as Awaited<ReturnType<typeof api.externalDataSources.create>>)
+ const createWebhook = jest.spyOn(api.externalDataSources, 'createWebhook')
+
+ const { logic, onComplete, unmount } = mountRequiredTablesWizard(['issues'])
+
+ try {
+ await expectLogic(logic, () => logic.actions.getDatabaseSchemas()).toFinishAllListeners()
+
+ expect(create).toHaveBeenCalledTimes(1)
+ expect(create.mock.calls[0][0].payload?.schemas).toEqual([
+ expect.objectContaining({ name: 'posthog/posthog.issues', should_sync: true }),
+ expect.objectContaining({ name: 'posthog/posthog-js.issues', should_sync: true }),
+ ])
+ // Poll-synced tables need no webhook, so completion must not wait on one.
+ expect(createWebhook).not.toHaveBeenCalled()
+ expect(onComplete).toHaveBeenCalled()
+ } finally {
+ unmount()
+ }
+ })
+
+ // Both leave the required table unsatisfied, so neither may create a source that reports
+ // setup as complete: the first would sync nothing, the second would queue a 403 sync.
+ it.each([
+ ['the required table is absent', [apiSchema('posthog/posthog.commits')]],
+ [
+ 'every matching row is unreadable',
+ [apiSchema('posthog/posthog.issues', { permission_error: 'Requires the "Issues" permission' })],
+ ],
+ ])('does not create the source when %s', async (_, discoveredSchemas) => {
+ jest.spyOn(api.externalDataSources, 'database_schema').mockResolvedValue(
+ discoveredSchemas as ExternalDataSourceSyncSchema[]
+ )
+ const create = jest.spyOn(api.externalDataSources, 'create')
+
+ const { logic, unmount } = mountRequiredTablesWizard(['issues'])
+
+ try {
+ await expectLogic(logic, () => logic.actions.getDatabaseSchemas()).toFinishAllListeners()
+
+ expect(create).not.toHaveBeenCalled()
+ expect(logic.values.isLoading).toBe(false)
+ } finally {
+ unmount()
+ }
+ })
+
+ it('registers the webhook before completing when a required table is webhook-synced', async () => {
+ // GitHub's workflow_runs/workflow_jobs are webhook-only: without registration the
+ // tables stay empty forever, while the signal reports itself as set up.
+ jest.spyOn(api.externalDataSources, 'database_schema').mockResolvedValue([
+ apiSchema('posthog/posthog.workflow_runs', { supports_webhooks: true }),
+ ] as ExternalDataSourceSyncSchema[])
+ jest.spyOn(api.externalDataSources, 'create').mockResolvedValue({ id: 'source-1' } as Awaited<
+ ReturnType<typeof api.externalDataSources.create>
+ >)
+ const createWebhook = jest
+ .spyOn(api.externalDataSources, 'createWebhook')
+ .mockResolvedValue({ success: true, webhook_url: 'https://example.com/webhook' })
+
+ const { logic, onComplete, unmount } = mountRequiredTablesWizard(['workflow_runs'])
+
+ try {
+ await expectLogic(logic, () => logic.actions.getDatabaseSchemas()).toFinishAllListeners()
+
+ expect(createWebhook).toHaveBeenCalledWith('source-1')
+ expect(onComplete).toHaveBeenCalled()
+ } finally {
+ unmount()
+ }
+ })
+
+ it('does not complete on webhook failure, and a resubmit retries the webhook without a duplicate source', async () => {
+ jest.spyOn(api.externalDataSources, 'database_schema').mockResolvedValue([
+ apiSchema('posthog/posthog.workflow_runs', { supports_webhooks: true }),
+ ] as ExternalDataSourceSyncSchema[])
+ const create = jest.spyOn(api.externalDataSources, 'create').mockResolvedValue({
+ id: 'source-1',
+ } as Awaited<ReturnType<typeof api.externalDataSources.create>>)
+ const createWebhook = jest
+ .spyOn(api.externalDataSources, 'createWebhook')
+ .mockResolvedValueOnce({
+ success: false,
+ webhook_url: '',
+ error: 'Token is missing webhook permissions',
+ })
+ .mockResolvedValueOnce({ success: true, webhook_url: 'https://example.com/webhook' })
+
+ const { logic, onComplete, unmount } = mountRequiredTablesWizard(['workflow_runs'])
+
+ try {
+ await expectLogic(logic, () => logic.actions.getDatabaseSchemas()).toFinishAllListeners()
+
+ expect(onComplete).not.toHaveBeenCalled()
+ expect(logic.values.isLoading).toBe(false)
+
+ // The source exists now, so a second submit must retry the webhook, not create again.
+ await expectLogic(logic, () => logic.actions.createSource()).toFinishAllListeners()
+
+ expect(create).toHaveBeenCalledTimes(1)
+ expect(createWebhook).toHaveBeenCalledTimes(2)
+ expect(createWebhook).toHaveBeenLastCalledWith('source-1')
+ expect(onComplete).toHaveBeenCalled()
+ } finally {
+ unmount()
+ }
+ })
+ })
})