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(data-warehouse): persist only changed fields in bulk schema edits (#66083)

Daniel RC3cdf8c0d00a7
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index 4996419d44b5..d946bd4f851e 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -5872,18 +5872,9 @@ const api = {
},
async bulkUpdateSchemas(
sourceId: ExternalDataSource['id'],
- schemas: Pick<
- ExternalDataSourceSchema,
- | 'id'
- | 'should_sync'
- | 'sync_type'
- | 'incremental_field'
- | 'incremental_field_type'
- | 'sync_frequency'
- | 'sync_time_of_day'
- | 'cdc_table_mode'
- | 'enabled_columns'
- >[]
+ // Callers send a minimal diff — only `id` is required; the backend writes just the fields
+ // present and leaves the rest untouched. (Matches `externalDataSchemas.update`'s shape.)
+ schemas: (Partial<ExternalDataSourceSchema> & Pick<ExternalDataSourceSchema, 'id'>)[]
): Promise<ExternalDataSourceSchema[]> {
return await new ApiRequest().externalDataSource(sourceId).withAction('bulk_update_schemas').update({
data: { schemas },
diff --git a/products/data_warehouse/frontend/scenes/SourceScene/tabs/dataWarehouseSourceSettingsLogic.test.ts b/products/data_warehouse/frontend/scenes/SourceScene/tabs/dataWarehouseSourceSettingsLogic.test.ts
index 5759ff60577b..df160c880ed0 100644
--- a/products/data_warehouse/frontend/scenes/SourceScene/tabs/dataWarehouseSourceSettingsLogic.test.ts
+++ b/products/data_warehouse/frontend/scenes/SourceScene/tabs/dataWarehouseSourceSettingsLogic.test.ts
@@ -58,7 +58,8 @@ describe('sourceSettingsLogic', () => {
it('debounces schema saves and only sends the latest queued change', async () => {
const bulkUpdateSchemasSpy = jest
.spyOn(api.externalDataSources, 'bulkUpdateSchemas')
- .mockImplementation(async (_id, schemas) => schemas as ExternalDataSourceSchema[])
+ // Mirror the backend: merge the partial payload onto the stored row, return full schemas.
+ .mockImplementation(async (_id, schemas) => schemas.map((partial) => ({ ...makeSchema(), ...partial })))
logic = sourceSettingsLogic({ id: 'source-1' })
logic.mount()
@@ -90,7 +91,7 @@ describe('sourceSettingsLogic', () => {
return
}
- resolve(schemas as ExternalDataSourceSchema[])
+ resolve(schemas.map((partial) => ({ ...makeSchema(), ...partial })))
})
)
@@ -128,6 +129,100 @@ describe('sourceSettingsLogic', () => {
expect(logic.values.source?.schemas[0].should_sync).toBe(false)
})
+ it('bulk frequency edit sends only the changed field and preserves untouched ones', async () => {
+ // Sending enabled_columns (even unchanged) would make the backend wipe the selection, so the
+ // PATCH must carry only { id, sync_frequency }.
+ jest.spyOn(api.externalDataSources, 'get').mockResolvedValue(
+ makeSource([makeSchema({ sync_type: 'full_refresh', enabled_columns: ['id', 'name'] })])
+ )
+ const bulkUpdateSchemasSpy = jest
+ .spyOn(api.externalDataSources, 'bulkUpdateSchemas')
+ // Mirror the real backend: merge the partial payload onto the stored schema, return full rows.
+ .mockImplementation(async (_id, schemas) =>
+ schemas.map((partial) => ({ ...makeSchema({ enabled_columns: ['id', 'name'] }), ...partial }))
+ )
+
+ logic = sourceSettingsLogic({ id: 'source-1' })
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ jest.useFakeTimers()
+
+ logic.actions.bulkSetFrequency(logic.values.source!.schemas, '24hour')
+ await jest.advanceTimersByTimeAsync(500)
+
+ expect(bulkUpdateSchemasSpy).toHaveBeenCalledTimes(1)
+ expect(bulkUpdateSchemasSpy).toHaveBeenLastCalledWith('source-1', [
+ { id: 'schema-1', sync_frequency: '24hour' },
+ ])
+ expect(logic.values.source?.schemas[0].sync_frequency).toBe('24hour')
+ expect(logic.values.source?.schemas[0].enabled_columns).toEqual(['id', 'name'])
+ })
+
+ it('sends a changed writable field discovered by diff, not a fixed allowlist', async () => {
+ // row_filters isn't in any hardcoded list — guards against regressing to an allowlist that drops it.
+ jest.spyOn(api.externalDataSources, 'get').mockResolvedValue(
+ makeSource([makeSchema({ sync_type: 'incremental', incremental_field: 'updated_at' })])
+ )
+ const bulkUpdateSchemasSpy = jest
+ .spyOn(api.externalDataSources, 'bulkUpdateSchemas')
+ .mockImplementation(async (_id, schemas) => schemas.map((partial) => ({ ...makeSchema(), ...partial })))
+
+ logic = sourceSettingsLogic({ id: 'source-1' })
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ jest.useFakeTimers()
+
+ const schema = logic.values.source!.schemas[0]
+ const row_filters = [{ column: 'amount', operator: '>' as const, value: 100 }]
+ logic.actions.updateSchema({ ...schema, row_filters })
+ await jest.advanceTimersByTimeAsync(500)
+
+ expect(bulkUpdateSchemasSpy).toHaveBeenLastCalledWith('source-1', [{ id: 'schema-1', row_filters }])
+ })
+
+ it('re-sends a failed in-flight edit fields when a newer edit for the same schema is queued', async () => {
+ // A failed flush must not lose its fields: the retry re-sends them alongside the newer edit's.
+ let rejectFirst: (() => void) | null = null
+ let callCount = 0
+ const bulkUpdateSchemasSpy = jest
+ .spyOn(api.externalDataSources, 'bulkUpdateSchemas')
+ .mockImplementation((_id, schemas) => {
+ callCount++
+ if (callCount === 1) {
+ return new Promise<ExternalDataSourceSchema[]>((_resolve, reject) => {
+ rejectFirst = () => reject(new Error('boom'))
+ })
+ }
+ return Promise.resolve(schemas.map((partial) => ({ ...makeSchema(), ...partial })))
+ })
+
+ logic = sourceSettingsLogic({ id: 'source-1' })
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ jest.useFakeTimers()
+
+ // Edit 1 (should_sync) flushes and goes in-flight.
+ logic.actions.updateSchema(makeSchema({ should_sync: true }))
+ await jest.advanceTimersByTimeAsync(500)
+ expect(bulkUpdateSchemasSpy).toHaveBeenCalledTimes(1)
+
+ // Edit 2 (a different field) is queued while edit 1 is still in-flight.
+ logic.actions.updateSchema(makeSchema({ should_sync: true, sync_frequency: '24hour' }))
+
+ // Edit 1 fails — the retry must carry both should_sync and sync_frequency.
+ const rejectFirstFn = rejectFirst as unknown as (() => void) | null
+ if (!rejectFirstFn) {
+ throw new Error('Expected first request to be pending')
+ }
+ rejectFirstFn()
+ await jest.advanceTimersByTimeAsync(500)
+
+ expect(bulkUpdateSchemasSpy).toHaveBeenCalledTimes(2)
+ expect(bulkUpdateSchemasSpy).toHaveBeenLastCalledWith('source-1', [
+ { id: 'schema-1', should_sync: true, sync_frequency: '24hour' },
+ ])
+ })
+
it('keys the logic by source id', () => {
expect(sourceSettingsLogic({ id: 'source-1' }).key).toEqual('source-1')
})
diff --git a/products/data_warehouse/frontend/scenes/SourceScene/tabs/sourceSettingsLogic.ts b/products/data_warehouse/frontend/scenes/SourceScene/tabs/sourceSettingsLogic.ts
index 821493e3c023..ab25e94740b6 100644
--- a/products/data_warehouse/frontend/scenes/SourceScene/tabs/sourceSettingsLogic.ts
+++ b/products/data_warehouse/frontend/scenes/SourceScene/tabs/sourceSettingsLogic.ts
@@ -67,9 +67,30 @@ function nextJobsPollDelay(softFailureCount: number): number {
return exponential * (0.5 + Math.random() * 0.5)
}
+// Read-only/derived fields to keep out of bulk-update payloads. A denylist (not an allowlist of
+// writable fields) so new editable fields are sent automatically — a stale allowlist silently
+// dropped edits like sync_frequency.
+const NON_WRITABLE_SCHEMA_FIELDS = new Set<keyof ExternalDataSourceSchema>([
+ 'id',
+ 'name',
+ 'label',
+ 'table',
+ 'last_synced_at',
+ 'latest_error',
+ 'status',
+ 'description',
+ 'available_columns',
+ 'incremental',
+ 'should_sync_default',
+])
+
+type SchemaPayloadField = keyof ExternalDataSourceSchema
+
interface PendingSchemaUpdate {
revision: number
schema: ExternalDataSourceSchema
+ // Fields changed vs. server state, accumulated across coalesced edits before a flush.
+ changedFields: Set<SchemaPayloadField>
}
interface SchemaUpdateCache {
@@ -123,32 +144,59 @@ function applySchemasToSource(
)
}
+// PATCH body of only the changed fields (+ id). The backend writes every field it receives, so
+// sending an untouched field would clobber it. Nullish → null so a clear is sent (JSON drops undefined).
function buildSchemaUpdatePayload(
- schema: ExternalDataSourceSchema
-): Pick<
- ExternalDataSourceSchema,
- | 'id'
- | 'should_sync'
- | 'sync_type'
- | 'incremental_field'
- | 'incremental_field_type'
- | 'incremental_field_lookback_seconds'
- | 'sync_frequency'
- | 'sync_time_of_day'
- | 'cdc_table_mode'
- | 'enabled_columns'
-> {
+ schema: ExternalDataSourceSchema,
+ changedFields: Set<SchemaPayloadField>
+): Partial<ExternalDataSourceSchema> & Pick<ExternalDataSourceSchema, 'id'> {
+ const payload: Partial<ExternalDataSourceSchema> & Pick<ExternalDataSourceSchema, 'id'> = { id: schema.id }
+ const assign = payload as Record<string, unknown>
+
+ for (const field of changedFields) {
+ assign[field] = schema[field] ?? null
+ }
+
+ return payload
+}
+
+// Writable fields whose value changed vs. the current schema. No baseline (source not loaded) =>
+// treat all as changed so the edit still persists.
+function diffSchemaPayloadFields(
+ nextSchema: ExternalDataSourceSchema,
+ baselineSchema: ExternalDataSourceSchema | undefined
+): Set<SchemaPayloadField> {
+ const changed = new Set<SchemaPayloadField>()
+ const fields = new Set<SchemaPayloadField>([
+ ...(Object.keys(nextSchema) as SchemaPayloadField[]),
+ ...((baselineSchema ? Object.keys(baselineSchema) : []) as SchemaPayloadField[]),
+ ])
+
+ for (const field of fields) {
+ if (NON_WRITABLE_SCHEMA_FIELDS.has(field)) {
+ continue
+ }
+ if (!baselineSchema || !objectsEqual(nextSchema[field], baselineSchema[field])) {
+ changed.add(field)
+ }
+ }
+
+ return changed
+}
+
+// A failed flush merges its fields into the newer queued edit so the retry re-sends both; the newer
+// edit wins on overlap. Otherwise the retry would drop the failed edit's fields.
+function foldFailedUpdateIntoPending(failed: PendingSchemaUpdate, pending: PendingSchemaUpdate): PendingSchemaUpdate {
+ const mergedSchema = { ...failed.schema }
+ const assign = mergedSchema as Record<string, unknown>
+ for (const field of pending.changedFields) {
+ assign[field] = pending.schema[field]
+ }
+
return {
- id: schema.id,
- should_sync: schema.should_sync,
- sync_type: schema.sync_type,
- incremental_field: schema.incremental_field,
- incremental_field_type: schema.incremental_field_type,
- incremental_field_lookback_seconds: schema.incremental_field_lookback_seconds ?? null,
- sync_frequency: schema.sync_frequency,
- sync_time_of_day: schema.sync_time_of_day,
- cdc_table_mode: schema.cdc_table_mode,
- enabled_columns: schema.enabled_columns ?? null,
+ schema: mergedSchema,
+ revision: pending.revision,
+ changedFields: new Set([...failed.changedFields, ...pending.changedFields]),
}
}
@@ -703,7 +751,9 @@ export const sourceSettingsLogic = kea<sourceSettingsLogicType>([
try {
const updatedSchemas = await api.externalDataSources.bulkUpdateSchemas(
values.sourceId,
- batchSchemaUpdates.map(({ schema }) => buildSchemaUpdatePayload(schema))
+ batchSchemaUpdates.map(({ schema, changedFields }) =>
+ buildSchemaUpdatePayload(schema, changedFields)
+ )
)
for (const pendingUpdate of batchSchemaUpdates) {
@@ -734,8 +784,16 @@ export const sourceSettingsLogic = kea<sourceSettingsLogicType>([
scheduleSchemaUpdateFlush()
}
} catch (error: any) {
- for (const pendingUpdate of batchSchemaUpdates) {
- delete schemaUpdateCache.inFlightSchemaUpdates[pendingUpdate.schema.id]
+ for (const failedUpdate of batchSchemaUpdates) {
+ delete schemaUpdateCache.inFlightSchemaUpdates[failedUpdate.schema.id]
+
+ // If a newer edit for this schema is queued, fold the failed fields into it
+ // so the retry doesn't silently drop what this request was carrying.
+ const pending = schemaUpdateCache.pendingSchemaUpdates[failedUpdate.schema.id]
+ if (pending) {
+ schemaUpdateCache.pendingSchemaUpdates[failedUpdate.schema.id] =
+ foldFailedUpdateIntoPending(failedUpdate, pending)
+ }
}
if (Object.keys(schemaUpdateCache.pendingSchemaUpdates).length > 0) {
@@ -756,7 +814,16 @@ export const sourceSettingsLogic = kea<sourceSettingsLogicType>([
const nextRevision = (schemaUpdateCache.schemaUpdateRevisions[schema.id] ?? 0) + 1
schemaUpdateCache.schemaUpdateRevisions[schema.id] = nextRevision
- schemaUpdateCache.pendingSchemaUpdates[schema.id] = { schema, revision: nextRevision }
+
+ // Union this edit's changed fields with any not-yet-flushed pending edit's, so
+ // coalesced edits send everything that changed — not just the latest field.
+ const baselineSchema = values.source?.schemas.find((item) => item.id === schema.id)
+ const changedFields = diffSchemaPayloadFields(schema, baselineSchema)
+ for (const field of schemaUpdateCache.pendingSchemaUpdates[schema.id]?.changedFields ?? []) {
+ changedFields.add(field)
+ }
+
+ schemaUpdateCache.pendingSchemaUpdates[schema.id] = { schema, revision: nextRevision, changedFields }
const optimisticSource = applyPendingSchemaUpdatesToSource(
values.source,