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.

feat(data-warehouse): roll up imported sources to a summary card (#70867)

Eric Duong94ea35068ff5
diff --git a/frontend/src/scenes/data-warehouse/scene/OverviewTab.tsx b/frontend/src/scenes/data-warehouse/scene/OverviewTab.tsx
index a08da3a2ee9e..9cf037712ad7 100644
--- a/frontend/src/scenes/data-warehouse/scene/OverviewTab.tsx
+++ b/frontend/src/scenes/data-warehouse/scene/OverviewTab.tsx
@@ -7,41 +7,20 @@ import { LemonButton } from 'lib/lemon-ui/LemonButton'
import { LemonCard } from 'lib/lemon-ui/LemonCard'
import { LemonProgress } from 'lib/lemon-ui/LemonProgress'
import { LemonTable, LemonTableColumns } from 'lib/lemon-ui/LemonTable'
-import { LemonTag, LemonTagType } from 'lib/lemon-ui/LemonTag'
+import { Link } from 'lib/lemon-ui/Link'
import { Spinner } from 'lib/lemon-ui/Spinner'
import { humanFriendlyDetailedTime } from 'lib/utils/datetime'
+import { urls } from 'scenes/urls'
import type {
ManagedWarehouseDatasetStatusApi,
- ManagedWarehouseReadinessStateEnumApi,
- ManagedWarehouseSourceTableStatusApi,
+ ManagedWarehouseSourceSummaryApi,
} from 'products/data_warehouse/frontend/generated/api.schemas'
import { managedWarehouseDataStatusLogic } from './managedWarehouseDataStatusLogic'
-
-const STATUS_LABELS: Record<ManagedWarehouseReadinessStateEnumApi, string> = {
- not_configured: 'Not configured',
- waiting: 'Waiting',
- backfilling: 'Backfilling',
- catching_up: 'Catching up',
- up_to_date: 'Up to date',
- needs_attention: 'Needs attention',
- unknown: 'Status unavailable',
-}
-
-const STATUS_TAG_TYPES: Record<ManagedWarehouseReadinessStateEnumApi, LemonTagType> = {
- not_configured: 'muted',
- waiting: 'warning',
- backfilling: 'primary',
- catching_up: 'primary',
- up_to_date: 'success',
- needs_attention: 'danger',
- unknown: 'muted',
-}
-
-function StatusTag({ readinessState }: { readinessState: ManagedWarehouseReadinessStateEnumApi }): JSX.Element {
- return <LemonTag type={STATUS_TAG_TYPES[readinessState]}>{STATUS_LABELS[readinessState]}</LemonTag>
-}
+import { SourceSchemasModal } from './SourceSchemasModal'
+import { sourceSchemasModalLogic } from './sourceSchemasModalLogic'
+import { STATUS_SEVERITY, StatusTag } from './warehouseStatusDisplay'
function DatasetCard({
title,
@@ -97,72 +76,55 @@ function DatasetCard({
)
}
-// Most severe first, matching the order the API returns tables in.
-const STATUS_SEVERITY: Record<ManagedWarehouseReadinessStateEnumApi, number> = {
- needs_attention: 0,
- backfilling: 1,
- catching_up: 2,
- waiting: 3,
- unknown: 4,
- up_to_date: 5,
- not_configured: 6,
-}
-
-const sourceColumns: LemonTableColumns<ManagedWarehouseSourceTableStatusApi> = [
- {
- title: 'Source',
- key: 'source',
- render: (_, table) => (
- <div>
- <div className="font-medium">{table.source_name}</div>
- <div className="text-xs text-muted">{table.source_type}</div>
- </div>
- ),
- sorter: (a, b) => a.source_name.localeCompare(b.source_name) || a.table_name.localeCompare(b.table_name),
- },
- {
- title: 'Table',
- dataIndex: 'table_name',
- render: (tableName) => <code>{tableName}</code>,
- sorter: (a, b) => a.table_name.localeCompare(b.table_name),
- },
- {
- title: 'Warehouse status',
- key: 'readiness_state',
- render: (_, table) => (
- <div className="space-y-1 max-w-96">
- <StatusTag readinessState={table.readiness_state} />
- <div className="text-xs text-muted">{table.detail}</div>
- </div>
- ),
- sorter: (a, b) => STATUS_SEVERITY[a.readiness_state] - STATUS_SEVERITY[b.readiness_state],
- },
- {
- title: 'Backfill',
- key: 'backfill',
- render: (_, table) =>
- table.total_chunks ? `${table.completed_chunks} / ${table.total_chunks} chunks` : 'No active backfill',
- },
- {
- title: 'Pending imports',
- dataIndex: 'pending_batches',
- render: (pendingBatches) =>
- typeof pendingBatches === 'number' ? pendingBatches.toLocaleString() : 'Unavailable',
- // Unavailable counts sort last rather than as zero, which would read as "nothing pending".
- sorter: (a, b) => (a.pending_batches ?? -1) - (b.pending_batches ?? -1),
- },
- {
- title: 'Last source import',
- dataIndex: 'last_synced_at',
- render: (lastSyncedAt) =>
- typeof lastSyncedAt === 'string' ? humanFriendlyDetailedTime(lastSyncedAt) : 'Not synced yet',
- sorter: (a, b) => new Date(a.last_synced_at ?? 0).getTime() - new Date(b.last_synced_at ?? 0).getTime(),
- },
-]
-
export function OverviewTab(): JSX.Element {
const { managedWarehouseDataStatus, managedWarehouseDataStatusLoading } = useValues(managedWarehouseDataStatusLogic)
const { loadManagedWarehouseDataStatus } = useActions(managedWarehouseDataStatusLogic)
+ const { loadSourceSchemas } = useActions(sourceSchemasModalLogic)
+
+ const sourceSummaryColumns: LemonTableColumns<ManagedWarehouseSourceSummaryApi> = [
+ {
+ title: 'Source',
+ key: 'source',
+ render: (_, source) => (
+ <div>
+ <div className="font-medium">{source.source_name}</div>
+ <div className="text-xs text-muted">{source.source_type}</div>
+ </div>
+ ),
+ sorter: (a, b) => a.source_name.localeCompare(b.source_name),
+ },
+ {
+ title: 'Warehouse status',
+ key: 'readiness_state',
+ render: (_, source) => (
+ <div className="space-y-1 max-w-96">
+ <StatusTag readinessState={source.readiness_state} />
+ <div className="text-xs text-muted">{source.detail}</div>
+ </div>
+ ),
+ sorter: (a, b) => STATUS_SEVERITY[a.readiness_state] - STATUS_SEVERITY[b.readiness_state],
+ },
+ {
+ title: 'Schemas backfilled',
+ key: 'backfilled_schemas',
+ render: (_, source) => `${source.backfilled_schemas} / ${source.total_schemas}`,
+ sorter: (a, b) => a.backfilled_schemas / a.total_schemas - b.backfilled_schemas / b.total_schemas,
+ },
+ {
+ title: 'Pending imports',
+ dataIndex: 'pending_batches',
+ render: (pendingBatches) =>
+ typeof pendingBatches === 'number' ? pendingBatches.toLocaleString() : 'Unavailable',
+ sorter: (a, b) => (a.pending_batches ?? -1) - (b.pending_batches ?? -1),
+ },
+ {
+ title: 'Last source import',
+ dataIndex: 'last_synced_at',
+ render: (lastSyncedAt) =>
+ typeof lastSyncedAt === 'string' ? humanFriendlyDetailedTime(lastSyncedAt) : 'Not synced yet',
+ sorter: (a, b) => new Date(a.last_synced_at ?? 0).getTime() - new Date(b.last_synced_at ?? 0).getTime(),
+ },
+ ]
if (managedWarehouseDataStatusLoading && !managedWarehouseDataStatus) {
return (
@@ -244,22 +206,32 @@ export function OverviewTab(): JSX.Element {
<div className="p-4 flex items-start justify-between gap-3 border-b">
<div>
<h3 className="mb-1">Imported source tables</h3>
- <p className="text-muted mb-0">{managedWarehouseDataStatus.sources.detail}</p>
+ <p className="text-xs text-muted mb-0">
+ Reflects the warehouse source imports currently enabled to sync.{' '}
+ <Link to={urls.sources()}>Manage sources</Link>
+ </p>
</div>
<StatusTag readinessState={managedWarehouseDataStatus.sources.readiness_state} />
</div>
- {managedWarehouseDataStatus.sources.tables.length ? (
+ {managedWarehouseDataStatus.sources.sources.length ? (
<LemonTable
embedded
- columns={sourceColumns}
- dataSource={managedWarehouseDataStatus.sources.tables}
- rowKey="schema_id"
+ columns={sourceSummaryColumns}
+ dataSource={managedWarehouseDataStatus.sources.sources}
+ rowKey="source_id"
pagination={{ pageSize: 20 }}
+ onRow={(source) => ({
+ onClick: () =>
+ loadSourceSchemas({ sourceId: source.source_id, sourceName: source.source_name }),
+ className: 'cursor-pointer',
+ })}
/>
) : (
<div className="p-6 text-muted">No imported source tables are configured for this warehouse.</div>
)}
</LemonCard>
+
+ <SourceSchemasModal />
</div>
)
}
diff --git a/frontend/src/scenes/data-warehouse/scene/SourceSchemasModal.tsx b/frontend/src/scenes/data-warehouse/scene/SourceSchemasModal.tsx
new file mode 100644
index 000000000000..be7737ccab1a
--- /dev/null
+++ b/frontend/src/scenes/data-warehouse/scene/SourceSchemasModal.tsx
@@ -0,0 +1,51 @@
+import { useActions, useValues } from 'kea'
+
+import { IconRefresh } from '@posthog/icons'
+
+import { LemonBanner } from 'lib/lemon-ui/LemonBanner'
+import { LemonButton } from 'lib/lemon-ui/LemonButton'
+import { LemonModal } from 'lib/lemon-ui/LemonModal'
+import { LemonTable } from 'lib/lemon-ui/LemonTable'
+
+import { sourceSchemasModalLogic } from './sourceSchemasModalLogic'
+import { sourceSchemaColumns } from './warehouseStatusDisplay'
+
+export function SourceSchemasModal(): JSX.Element {
+ const { activeSource, sourceSchemas, sourceSchemasLoading, sourceSchemasError } = useValues(sourceSchemasModalLogic)
+ const { closeSourceSchemasModal, loadSourceSchemas } = useActions(sourceSchemasModalLogic)
+
+ return (
+ <LemonModal
+ isOpen={!!activeSource}
+ onClose={closeSourceSchemasModal}
+ title={activeSource ? `${activeSource.sourceName} schemas` : 'Schemas'}
+ width={960}
+ >
+ {sourceSchemasError ? (
+ <LemonBanner type="error">
+ <div className="flex items-center justify-between gap-3">
+ <span>Schemas could not be loaded.</span>
+ <LemonButton
+ type="secondary"
+ size="small"
+ icon={<IconRefresh />}
+ onClick={() => activeSource && loadSourceSchemas(activeSource)}
+ loading={sourceSchemasLoading}
+ >
+ Try again
+ </LemonButton>
+ </div>
+ </LemonBanner>
+ ) : (
+ <LemonTable
+ dataSource={sourceSchemas}
+ columns={sourceSchemaColumns}
+ loading={sourceSchemasLoading}
+ rowKey="schema_id"
+ pagination={{ pageSize: 20 }}
+ emptyState="No schemas are configured for this source."
+ />
+ )}
+ </LemonModal>
+ )
+}
diff --git a/frontend/src/scenes/data-warehouse/scene/sourceSchemasModalLogic.test.ts b/frontend/src/scenes/data-warehouse/scene/sourceSchemasModalLogic.test.ts
new file mode 100644
index 000000000000..5c6beab1b5c7
--- /dev/null
+++ b/frontend/src/scenes/data-warehouse/scene/sourceSchemasModalLogic.test.ts
@@ -0,0 +1,151 @@
+import { expectLogic } from 'kea-test-utils'
+
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+
+import { sourceSchemasModalLogic } from './sourceSchemasModalLogic'
+
+// Dispatching loadSourceSchemas doesn't reach the MSW resolver synchronously - the API client and
+// fetch layers each add a microtask hop. Poll for the resolver having registered itself rather than
+// waiting a fixed duration, so this stays deterministic regardless of how many hops there are.
+async function waitUntilPending(pending: Record<string, unknown>, sourceId: string): Promise<void> {
+ for (let i = 0; i < 20 && !pending[sourceId]; i++) {
+ await Promise.resolve()
+ }
+}
+
+describe('sourceSchemasModalLogic', () => {
+ let logic: ReturnType<typeof sourceSchemasModalLogic.build>
+
+ beforeEach(() => {
+ useMocks({
+ get: {
+ '/api/projects/:team_id/data_warehouse/managed-warehouse-source-schemas/': ({ request }) => {
+ const sourceId = new URL(request.url).searchParams.get('source_id')
+ return [200, { schemas: [{ schema_id: 'schema-1', source_id: sourceId }] }]
+ },
+ },
+ })
+ initKeaTests()
+ logic = sourceSchemasModalLogic()
+ logic.mount()
+ })
+
+ afterEach(() => {
+ logic.unmount()
+ })
+
+ // activeSource doubles as the modal's isOpen flag, so a wiring slip here leaves the modal
+ // stuck open (or shows the wrong source's schemas) rather than just a failed network call.
+ it('opens for the clicked source and fetches its schemas', async () => {
+ await expectLogic(logic, () => {
+ logic.actions.loadSourceSchemas({ sourceId: 'stripe-1', sourceName: 'Stripe' })
+ }).toDispatchActions(['loadSourceSchemas', 'loadSourceSchemasSuccess'])
+
+ expect(logic.values.activeSource).toEqual({ sourceId: 'stripe-1', sourceName: 'Stripe' })
+ expect(logic.values.sourceSchemas).toEqual([{ schema_id: 'schema-1', source_id: 'stripe-1' }])
+ })
+
+ it('closes back to no active source', async () => {
+ await expectLogic(logic, () => {
+ logic.actions.loadSourceSchemas({ sourceId: 'stripe-1', sourceName: 'Stripe' })
+ }).toDispatchActions(['loadSourceSchemasSuccess'])
+
+ logic.actions.closeSourceSchemasModal()
+
+ expect(logic.values.activeSource).toBeNull()
+ })
+
+ it('switches to a different source without leaking the previous one', async () => {
+ await expectLogic(logic, () => {
+ logic.actions.loadSourceSchemas({ sourceId: 'stripe-1', sourceName: 'Stripe' })
+ }).toDispatchActions(['loadSourceSchemasSuccess'])
+
+ await expectLogic(logic, () => {
+ logic.actions.loadSourceSchemas({ sourceId: 'postgres-1', sourceName: 'Postgres' })
+ }).toDispatchActions(['loadSourceSchemasSuccess'])
+
+ expect(logic.values.activeSource).toEqual({ sourceId: 'postgres-1', sourceName: 'Postgres' })
+ expect(logic.values.sourceSchemas).toEqual([{ schema_id: 'schema-1', source_id: 'postgres-1' }])
+ })
+
+ // A slower first request can resolve after a faster later one. If the response isn't checked
+ // against whichever source is active by the time it lands, the modal ends up showing stale
+ // schemas under the new source's title.
+ it('does not let an earlier click overwrite a later one that resolved first', async () => {
+ const pending: Record<string, { resolve: (body: unknown) => void }> = {}
+ useMocks({
+ get: {
+ '/api/projects/:team_id/data_warehouse/managed-warehouse-source-schemas/': ({ request }) => {
+ const sourceId = new URL(request.url).searchParams.get('source_id') as string
+ return new Promise((resolve) => {
+ pending[sourceId] = { resolve: (body) => resolve([200, body]) }
+ })
+ },
+ },
+ })
+
+ logic.actions.loadSourceSchemas({ sourceId: 'source-a', sourceName: 'A' })
+ logic.actions.loadSourceSchemas({ sourceId: 'source-b', sourceName: 'B' })
+ await waitUntilPending(pending, 'source-a')
+ await waitUntilPending(pending, 'source-b')
+
+ // B (the later click) resolves first...
+ pending['source-b'].resolve({ schemas: [{ schema_id: 'b-schema' }] })
+ await expectLogic(logic).toDispatchActions(['loadSourceSchemasSuccess'])
+ // ...then A's slower response arrives after the user has already moved on to B.
+ pending['source-a'].resolve({ schemas: [{ schema_id: 'a-schema' }] })
+ await expectLogic(logic).toDispatchActions(['loadSourceSchemasSuccess'])
+
+ expect(logic.values.activeSource).toEqual({ sourceId: 'source-b', sourceName: 'B' })
+ expect(logic.values.sourceSchemas).toEqual([{ schema_id: 'b-schema' }])
+ })
+
+ it('clears schemas and flags an error when the active source fails to load', async () => {
+ useMocks({
+ get: {
+ '/api/projects/:team_id/data_warehouse/managed-warehouse-source-schemas/': () => [
+ 500,
+ { detail: 'boom' },
+ ],
+ },
+ })
+
+ await expectLogic(logic, () => {
+ logic.actions.loadSourceSchemas({ sourceId: 'stripe-1', sourceName: 'Stripe' })
+ }).toDispatchActions(['loadSourceSchemasSuccess'])
+
+ expect(logic.values.sourceSchemas).toEqual([])
+ expect(logic.values.sourceSchemasError).toBe(true)
+ })
+
+ it('does not error out the active source over a stale failure from a source already left', async () => {
+ const pending: Record<string, { resolve: (response: [number, unknown]) => void }> = {}
+ useMocks({
+ get: {
+ '/api/projects/:team_id/data_warehouse/managed-warehouse-source-schemas/': ({ request }) => {
+ const sourceId = new URL(request.url).searchParams.get('source_id') as string
+ return new Promise((resolve) => {
+ pending[sourceId] = { resolve }
+ })
+ },
+ },
+ })
+
+ logic.actions.loadSourceSchemas({ sourceId: 'source-a', sourceName: 'A' })
+ logic.actions.loadSourceSchemas({ sourceId: 'source-b', sourceName: 'B' })
+ await waitUntilPending(pending, 'source-a')
+ await waitUntilPending(pending, 'source-b')
+
+ // B (the currently active source) loads successfully...
+ pending['source-b'].resolve([200, { schemas: [{ schema_id: 'b-schema' }] }])
+ await expectLogic(logic).toDispatchActions(['loadSourceSchemasSuccess'])
+ // ...then A's request, for a source the user has already left, fails.
+ pending['source-a'].resolve([500, { detail: 'boom' }])
+ await expectLogic(logic).toDispatchActions(['loadSourceSchemasSuccess'])
+
+ expect(logic.values.activeSource).toEqual({ sourceId: 'source-b', sourceName: 'B' })
+ expect(logic.values.sourceSchemas).toEqual([{ schema_id: 'b-schema' }])
+ expect(logic.values.sourceSchemasError).toBe(false)
+ })
+})
diff --git a/frontend/src/scenes/data-warehouse/scene/sourceSchemasModalLogic.ts b/frontend/src/scenes/data-warehouse/scene/sourceSchemasModalLogic.ts
new file mode 100644
index 000000000000..4a6037a1da34
--- /dev/null
+++ b/frontend/src/scenes/data-warehouse/scene/sourceSchemasModalLogic.ts
@@ -0,0 +1,75 @@
+import { actions, kea, path, reducers } from 'kea'
+import { loaders } from 'kea-loaders'
+
+import { teamLogic } from 'scenes/teamLogic'
+
+import { dataWarehouseManagedWarehouseSourceSchemasRetrieve } from 'products/data_warehouse/frontend/generated/api'
+import type { ManagedWarehouseSourceTableStatusApi } from 'products/data_warehouse/frontend/generated/api.schemas'
+
+import type { sourceSchemasModalLogicType } from './sourceSchemasModalLogicType'
+
+export interface ActiveSource {
+ sourceId: string
+ sourceName: string
+}
+
+// A response (success or failure) is stale once the user has clicked a different source before it
+// settled — an in-flight request for the previous source can still resolve after a faster later
+// one, and must not be allowed to overwrite what's now on screen.
+function isStale(sourceId: string, activeSource: ActiveSource | null): boolean {
+ return activeSource?.sourceId !== sourceId
+}
+
+export const sourceSchemasModalLogic = kea<sourceSchemasModalLogicType>([
+ path(['scenes', 'data-warehouse', 'scene', 'sourceSchemasModalLogic']),
+ actions({
+ closeSourceSchemasModal: true,
+ setSourceSchemasError: (hasError: boolean) => ({ hasError }),
+ }),
+ loaders(({ values, actions }) => ({
+ sourceSchemas: [
+ [] as ManagedWarehouseSourceTableStatusApi[],
+ {
+ loadSourceSchemas: async ({ sourceId }: ActiveSource) => {
+ try {
+ const response = await dataWarehouseManagedWarehouseSourceSchemasRetrieve(
+ String(teamLogic.values.currentTeamId),
+ { source_id: sourceId }
+ )
+ if (isStale(sourceId, values.activeSource)) {
+ return values.sourceSchemas
+ }
+ actions.setSourceSchemasError(false)
+ return response.schemas
+ } catch {
+ if (isStale(sourceId, values.activeSource)) {
+ // A stale failure must not clear or error out whatever the currently
+ // active source is showing.
+ return values.sourceSchemas
+ }
+ actions.setSourceSchemasError(true)
+ return []
+ }
+ },
+ },
+ ],
+ })),
+ reducers({
+ // Doubles as the modal's open/closed state: isOpen={!!activeSource}. Set by the same
+ // action that triggers the fetch, so there's no separate "open" step to keep in sync.
+ activeSource: [
+ null as ActiveSource | null,
+ {
+ loadSourceSchemas: (_, source) => source,
+ closeSourceSchemasModal: () => null,
+ },
+ ],
+ sourceSchemasError: [
+ false,
+ {
+ loadSourceSchemas: () => false,
+ setSourceSchemasError: (_, { hasError }) => hasError,
+ },
+ ],
+ }),
+])
diff --git a/frontend/src/scenes/data-warehouse/scene/warehouseStatusDisplay.tsx b/frontend/src/scenes/data-warehouse/scene/warehouseStatusDisplay.tsx
new file mode 100644
index 000000000000..5c2191249724
--- /dev/null
+++ b/frontend/src/scenes/data-warehouse/scene/warehouseStatusDisplay.tsx
@@ -0,0 +1,88 @@
+import { LemonTableColumns } from 'lib/lemon-ui/LemonTable'
+import { LemonTag, LemonTagType } from 'lib/lemon-ui/LemonTag'
+import { humanFriendlyDetailedTime } from 'lib/utils/datetime'
+
+import type {
+ ManagedWarehouseReadinessStateEnumApi,
+ ManagedWarehouseSourceTableStatusApi,
+} from 'products/data_warehouse/frontend/generated/api.schemas'
+
+// Shared between the Overview tab's dataset/source cards and the per-source schema modal, so a
+// readiness state reads and ranks identically everywhere it appears.
+
+export const STATUS_LABELS: Record<ManagedWarehouseReadinessStateEnumApi, string> = {
+ not_configured: 'Not configured',
+ waiting: 'Waiting',
+ backfilling: 'Backfilling',
+ catching_up: 'Catching up',
+ up_to_date: 'Up to date',
+ needs_attention: 'Needs attention',
+ unknown: 'Status unavailable',
+}
+
+export const STATUS_TAG_TYPES: Record<ManagedWarehouseReadinessStateEnumApi, LemonTagType> = {
+ not_configured: 'muted',
+ waiting: 'warning',
+ backfilling: 'primary',
+ catching_up: 'primary',
+ up_to_date: 'success',
+ needs_attention: 'danger',
+ unknown: 'muted',
+}
+
+// Most severe first, matching the order the API returns sources/tables in.
+export const STATUS_SEVERITY: Record<ManagedWarehouseReadinessStateEnumApi, number> = {
+ needs_attention: 0,
+ backfilling: 1,
+ catching_up: 2,
+ waiting: 3,
+ unknown: 4,
+ up_to_date: 5,
+ not_configured: 6,
+}
+
+export function StatusTag({ readinessState }: { readinessState: ManagedWarehouseReadinessStateEnumApi }): JSX.Element {
+ return <LemonTag type={STATUS_TAG_TYPES[readinessState]}>{STATUS_LABELS[readinessState]}</LemonTag>
+}
+
+// Per-schema detail columns: used by the drill-down modal, scoped to one source's schemas.
+export const sourceSchemaColumns: LemonTableColumns<ManagedWarehouseSourceTableStatusApi> = [
+ {
+ title: 'Table',
+ dataIndex: 'table_name',
+ render: (tableName) => <code>{tableName}</code>,
+ sorter: (a, b) => a.table_name.localeCompare(b.table_name),
+ },
+ {
+ title: 'Warehouse status',
+ key: 'readiness_state',
+ render: (_, table) => (
+ <div className="space-y-1 max-w-96">
+ <StatusTag readinessState={table.readiness_state} />
+ <div className="text-xs text-muted">{table.detail}</div>
+ </div>
+ ),
+ sorter: (a, b) => STATUS_SEVERITY[a.readiness_state] - STATUS_SEVERITY[b.readiness_state],
+ },
+ {
+ title: 'Backfill',
+ key: 'backfill',
+ render: (_, table) =>
+ table.total_chunks ? `${table.completed_chunks} / ${table.total_chunks} chunks` : 'No active backfill',
+ },
+ {
+ title: 'Pending imports',
+ dataIndex: 'pending_batches',
+ render: (pendingBatches) =>
+ typeof pendingBatches === 'number' ? pendingBatches.toLocaleString() : 'Unavailable',
+ // Unavailable counts sort last rather than as zero, which would read as "nothing pending".
+ sorter: (a, b) => (a.pending_batches ?? -1) - (b.pending_batches ?? -1),
+ },
+ {
+ title: 'Last source import',
+ dataIndex: 'last_synced_at',
+ render: (lastSyncedAt) =>
+ typeof lastSyncedAt === 'string' ? humanFriendlyDetailedTime(lastSyncedAt) : 'Not synced yet',
+ sorter: (a, b) => new Date(a.last_synced_at ?? 0).getTime() - new Date(b.last_synced_at ?? 0).getTime(),
+ },
+]
diff --git a/products/data_warehouse/backend/facade/api.py b/products/data_warehouse/backend/facade/api.py
index 6600e36b57c0..0b48a750f28e 100644
--- a/products/data_warehouse/backend/facade/api.py
+++ b/products/data_warehouse/backend/facade/api.py
@@ -59,6 +59,7 @@ _LAZY = {
"WebhookConsumerConfig": "logic.webhook_consumer.config",
"WebhookS3Sink": "logic.webhook_consumer.consumer",
"get_managed_warehouse_data_status": "logic.managed_warehouse_data_status",
+ "get_source_schema_statuses": "logic.managed_warehouse_data_status",
"get_mysql_source_location": "mysql_helpers",
"reconcile_mysql_schemas": "mysql_helpers",
"reproject_direct_mysql_table": "mysql_helpers",
diff --git a/products/data_warehouse/backend/logic/managed_warehouse_data_status.py b/products/data_warehouse/backend/logic/managed_warehouse_data_status.py
index 851b35263c4a..70a043d1c6dd 100644
--- a/products/data_warehouse/backend/logic/managed_warehouse_data_status.py
+++ b/products/data_warehouse/backend/logic/managed_warehouse_data_status.py
@@ -62,6 +62,9 @@ class SourceTableStatus(TypedDict):
table_name: str
readiness_state: ReadinessState
detail: str
+ # Whether the one-time historical copy into the warehouse has completed (sink state PRIMED).
+ # Independent of readiness_state, which also folds in live-catchup and failure signals.
+ backfilled: bool
completed_chunks: int
total_chunks: int | None
pending_batches: int | None
@@ -70,10 +73,22 @@ class SourceTableStatus(TypedDict):
last_synced_at: datetime | None
+class SourceSummary(TypedDict):
+ source_id: str
+ source_name: str
+ source_type: str
+ readiness_state: ReadinessState
+ detail: str
+ total_schemas: int
+ backfilled_schemas: int
+ pending_batches: int | None
+ last_synced_at: datetime | None
+
+
class SourcesStatus(TypedDict):
readiness_state: ReadinessState
detail: str
- tables: list[SourceTableStatus]
+ sources: list[SourceSummary]
class ManagedWarehouseDataStatus(TypedDict):
@@ -274,24 +289,29 @@ def source_table_readiness(
return "up_to_date", "Imported data is up to date."
-def _sources_status(team_id: int) -> SourcesStatus:
+def _schema_table_statuses(team_id: int, *, source_id: str | None = None) -> list[SourceTableStatus]:
+ """Per-schema readiness, optionally scoped to one source.
+
+ Shared by the top-level rollup (all sources, for the Overview tab's summary card) and the
+ per-source detail lookup (one source's schemas, for the drill-down modal) so the readiness
+ computation and the visibility rules never drift between the two views.
+ """
states = list(DuckgresSinkSchemaState.objects.filter(team_id=team_id).order_by("schema_id"))
if not states:
- return {
- "readiness_state": "not_configured",
- "detail": "No imported source tables are configured for this warehouse.",
- "tables": [],
- }
+ return []
+
+ schema_filter: dict[str, object] = {
+ "team_id": team_id,
+ "id__in": [state.schema_id for state in states],
+ "should_sync": True,
+ "deleted": False,
+ "source__deleted": False,
+ }
+ if source_id is not None:
+ schema_filter["source_id"] = source_id
schema_by_id = {
- str(schema.id): schema
- for schema in ExternalDataSchema.objects.filter(
- team_id=team_id,
- id__in=[state.schema_id for state in states],
- should_sync=True,
- deleted=False,
- source__deleted=False,
- ).select_related("source")
+ str(schema.id): schema for schema in ExternalDataSchema.objects.filter(**schema_filter).select_related("source")
}
visible_states = [state for state in states if str(state.schema_id) in schema_by_id]
schema_ids = [str(state.schema_id) for state in visible_states]
@@ -313,6 +333,7 @@ def _sources_status(team_id: int) -> SourcesStatus:
"table_name": schema.name,
"readiness_state": readiness_state,
"detail": detail,
+ "backfilled": state.state == DuckgresSinkSchemaState.State.PRIMED,
"completed_chunks": state.chunks_applied,
"total_chunks": state.chunk_count,
"pending_batches": queue_status["pending_batches"] if queue_status is not None else None,
@@ -321,33 +342,69 @@ def _sources_status(team_id: int) -> SourcesStatus:
"last_synced_at": schema.last_synced_at,
}
)
+ return tables
- if not tables:
- return {
- "readiness_state": "not_configured",
- "detail": "No imported source tables are configured for this warehouse.",
- "tables": [],
- }
- tables = sort_source_tables(tables)
- readiness_state = _roll_up_state([table["readiness_state"] for table in tables])
- details: dict[ReadinessState, str] = {
- "needs_attention": "One or more imported tables need attention.",
- "backfilling": "Existing rows are being copied for one or more imported tables.",
- "catching_up": "Recent imports are still being applied to the warehouse.",
- "waiting": "One or more imported tables are waiting to start.",
- "unknown": "Some live import statuses are temporarily unavailable.",
- "up_to_date": "All imported source tables are up to date.",
- "not_configured": "No imported source tables are configured for this warehouse.",
- }
- return {"readiness_state": readiness_state, "detail": details[readiness_state], "tables": tables}
+def get_source_schema_statuses(team_id: int, source_id: str) -> list[SourceTableStatus]:
+ """Per-schema detail for one imported source — backs the Overview tab's drill-down modal."""
+ return sort_source_tables(_schema_table_statuses(team_id, source_id=source_id))
+
+
+_SOURCE_SUMMARY_DETAILS: dict[ReadinessState, str] = {
+ "needs_attention": "One or more schemas need attention.",
+ "backfilling": "Historical rows are being copied for one or more schemas.",
+ "catching_up": "Recent imports are still being applied for one or more schemas.",
+ "waiting": "One or more schemas are waiting to start.",
+ "unknown": "Live import status is temporarily unavailable for one or more schemas.",
+ "up_to_date": "All schemas are up to date.",
+ "not_configured": "No schemas are configured for this source.",
+}
+
+
+def _rollup_sources(tables: list[SourceTableStatus]) -> list[SourceSummary]:
+ grouped: dict[str, list[SourceTableStatus]] = {}
+ for table in tables:
+ grouped.setdefault(table["source_id"], []).append(table)
+
+ summaries: list[SourceSummary] = []
+ for source_id, rows in grouped.items():
+ readiness_state = _roll_up_state([row["readiness_state"] for row in rows])
+ # pending_batches is uniformly None (queue check failed) or uniformly an int across a
+ # team's rows, since _queue_tail_statuses either fails for all schemas or none.
+ pending_batches = (
+ None if rows[0]["pending_batches"] is None else sum(row["pending_batches"] or 0 for row in rows)
+ )
+ last_synced_at = max((row["last_synced_at"] for row in rows if row["last_synced_at"] is not None), default=None)
+ summaries.append(
+ {
+ "source_id": source_id,
+ "source_name": rows[0]["source_name"],
+ "source_type": rows[0]["source_type"],
+ "readiness_state": readiness_state,
+ "detail": _SOURCE_SUMMARY_DETAILS[readiness_state],
+ "total_schemas": len(rows),
+ "backfilled_schemas": sum(1 for row in rows if row["backfilled"]),
+ "pending_batches": pending_batches,
+ "last_synced_at": last_synced_at,
+ }
+ )
+ return sort_sources(summaries)
+
+
+def sort_sources(sources: list[SourceSummary]) -> list[SourceSummary]:
+ """Most severe first, then alphabetically by source name — same rationale as sort_source_tables."""
+ severity = {state: rank for rank, state in enumerate(READINESS_PRIORITY)}
+ return sorted(
+ sources,
+ key=lambda source: (severity.get(source["readiness_state"], len(severity)), source["source_name"].lower()),
+ )
def sort_source_tables(tables: list[SourceTableStatus]) -> list[SourceTableStatus]:
"""Most severe first, then alphabetically by source and table.
- A team can import dozens of tables and the UI paginates at 20, so the one table that has
- stalled has to land on the first page. Ordering by schema_id (a UUID) scattered it.
+ Used for the per-source schema detail list, where a source can still have dozens of tables
+ even after rolling sources up for the summary card — the one that's stalled should be first.
"""
severity = {state: rank for rank, state in enumerate(READINESS_PRIORITY)}
return sorted(
@@ -360,6 +417,29 @@ def sort_source_tables(tables: list[SourceTableStatus]) -> list[SourceTableStatu
)
+def _sources_status(team_id: int) -> SourcesStatus:
+ tables = _schema_table_statuses(team_id)
+ if not tables:
+ return {
+ "readiness_state": "not_configured",
+ "detail": "No imported source tables are configured for this warehouse.",
+ "sources": [],
+ }
+
+ sources = _rollup_sources(tables)
+ readiness_state = _roll_up_state([source["readiness_state"] for source in sources])
+ details: dict[ReadinessState, str] = {
+ "needs_attention": "One or more imported sources need attention.",
+ "backfilling": "Existing rows are being copied for one or more imported sources.",
+ "catching_up": "Recent imports are still being applied to the warehouse.",
+ "waiting": "One or more imported sources are waiting to start.",
+ "unknown": "Some live import statuses are temporarily unavailable.",
+ "up_to_date": "All imported sources are up to date.",
+ "not_configured": "No imported source tables are configured for this warehouse.",
+ }
+ return {"readiness_state": readiness_state, "detail": details[readiness_state], "sources": sources}
+
+
def _roll_up_state(states: list[ReadinessState]) -> ReadinessState:
for candidate in READINESS_PRIORITY:
if candidate in states:
diff --git a/products/data_warehouse/backend/presentation/managed_warehouse_data_status.py b/products/data_warehouse/backend/presentation/managed_warehouse_data_status.py
index 45dd9885514a..1ccba1afb16a 100644
--- a/products/data_warehouse/backend/presentation/managed_warehouse_data_status.py
+++ b/products/data_warehouse/backend/presentation/managed_warehouse_data_status.py
@@ -43,6 +43,9 @@ class ManagedWarehouseSourceTableStatusSerializer(serializers.Serializer):
choices=READINESS_STATE_CHOICES, help_text="User-facing warehouse readiness state for this table."
)
detail = serializers.CharField(help_text="Human-readable explanation of the table's readiness state.")
+ backfilled = serializers.BooleanField(
+ help_text="Whether the one-time historical copy into the warehouse has completed for this table."
+ )
completed_chunks = serializers.IntegerField(help_text="Backfill chunks already copied into the warehouse.")
total_chunks = serializers.IntegerField(
allow_null=True, help_text="Total backfill chunks, or null before the copy plan is ready."
@@ -61,13 +64,46 @@ class ManagedWarehouseSourceTableStatusSerializer(serializers.Serializer):
)
+class ManagedWarehouseSourceSummarySerializer(serializers.Serializer):
+ source_id = serializers.UUIDField(help_text="Imported source connection identifier.")
+ source_name = serializers.CharField(help_text="Display name for the imported source connection.")
+ source_type = serializers.CharField(help_text="Type of the imported source connection.")
+ readiness_state = serializers.ChoiceField(
+ choices=READINESS_STATE_CHOICES, help_text="Rolled-up warehouse readiness state across this source's schemas."
+ )
+ detail = serializers.CharField(help_text="Human-readable explanation of this source's readiness state.")
+ total_schemas = serializers.IntegerField(help_text="Number of this source's schemas visible to the warehouse.")
+ backfilled_schemas = serializers.IntegerField(
+ help_text="Number of schemas whose one-time historical copy into the warehouse has completed."
+ )
+ pending_batches = serializers.IntegerField(
+ allow_null=True,
+ help_text="Imported batches waiting to be applied across this source's schemas, or null when queue status is unavailable.",
+ )
+ last_synced_at = serializers.DateTimeField(
+ allow_null=True, help_text="Most recent upstream source import completion across this source's schemas."
+ )
+
+
class ManagedWarehouseSourcesStatusSerializer(serializers.Serializer):
readiness_state = serializers.ChoiceField(
- choices=READINESS_STATE_CHOICES, help_text="Rolled-up readiness state for imported source tables."
+ choices=READINESS_STATE_CHOICES, help_text="Rolled-up readiness state for imported sources."
)
detail = serializers.CharField(help_text="Human-readable explanation of imported source readiness.")
- tables = ManagedWarehouseSourceTableStatusSerializer(
- many=True, help_text="Per-table source backfill and live import application statuses."
+ sources = ManagedWarehouseSourceSummarySerializer(
+ many=True,
+ help_text="Per-source rollup of schema backfill and live import application statuses. Reflects only "
+ "warehouse source imports with sync enabled — manage sources at /data-management/sources.",
+ )
+
+
+class ManagedWarehouseSourceSchemasQuerySerializer(serializers.Serializer):
+ source_id = serializers.UUIDField(help_text="Imported source connection to fetch per-schema detail for.")
+
+
+class ManagedWarehouseSourceSchemasResponseSerializer(serializers.Serializer):
+ schemas = ManagedWarehouseSourceTableStatusSerializer(
+ many=True, help_text="Per-schema backfill and live import application status for the requested source."
)
diff --git a/products/data_warehouse/backend/presentation/views/data_warehouse.py b/products/data_warehouse/backend/presentation/views/data_warehouse.py
index 3b9315694df7..af0a3d07041c 100644
--- a/products/data_warehouse/backend/presentation/views/data_warehouse.py
+++ b/products/data_warehouse/backend/presentation/views/data_warehouse.py
@@ -8,7 +8,7 @@ from django.db.models.functions import TruncDate, TruncHour
import structlog
from dateutil import parser
-from drf_spectacular.utils import extend_schema, inline_serializer
+from drf_spectacular.utils import OpenApiResponse, extend_schema, inline_serializer
from opentelemetry import trace
from rest_framework import serializers, status, viewsets
from rest_framework.decorators import action
@@ -19,6 +19,7 @@ from posthog.hogql import ast
from posthog.hogql.query import execute_hogql_query
from posthog.api.documentation import _FallbackSerializer
+from posthog.api.mixins import validated_request
from posthog.api.property_value_metrics import PROPERTY_VALUES_DURATION
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.clickhouse.query_tagging import Feature, Product, tag_queries
@@ -31,10 +32,12 @@ from posthog.utils import convert_property_value, flatten
from products.batch_exports.backend.facade.models import BatchExportRun
from products.cdp.backend.facade.models import HogFunction, HogFunctionState, HogFunctionType
from products.data_modeling.backend.facade.models import DataModelingJob, DataWarehouseSavedQuery
-from products.data_warehouse.backend.facade.api import get_managed_warehouse_data_status
+from products.data_warehouse.backend.facade.api import get_managed_warehouse_data_status, get_source_schema_statuses
from products.data_warehouse.backend.facade.models import TeamDataWarehouseConfig
from products.data_warehouse.backend.presentation.managed_warehouse_data_status import (
ManagedWarehouseDataStatusResponseSerializer,
+ ManagedWarehouseSourceSchemasQuerySerializer,
+ ManagedWarehouseSourceSchemasResponseSerializer,
)
from products.data_warehouse.backend.presentation.views import managed_warehouse
from products.warehouse_sources.backend.facade.hogql import get_view_or_table_by_name
@@ -1012,6 +1015,23 @@ class DataWarehouseViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
"""Get events, persons, and imported source readiness for the managed warehouse."""
return Response(get_managed_warehouse_data_status(self.team_id))
+ @validated_request(
+ query_serializer=ManagedWarehouseSourceSchemasQuerySerializer,
+ responses={200: OpenApiResponse(response=ManagedWarehouseSourceSchemasResponseSerializer)},
+ summary="Get per-schema detail for one imported source",
+ description="Per-schema backfill and live import status for one source, for the Overview tab's "
+ "drill-down modal — the main status endpoint only returns a per-source rollup.",
+ )
+ @action(
+ methods=["GET"],
+ detail=False,
+ url_path="managed-warehouse-source-schemas",
+ required_scopes=["warehouse_view:read", "external_data_source:read"],
+ )
+ def managed_warehouse_source_schemas(self, request: Request, **kwargs) -> Response:
+ source_id = str(request.validated_query_data["source_id"])
+ return Response({"schemas": get_source_schema_statuses(self.team_id, source_id)})
+
@extend_schema(
responses={
200: inline_serializer(
diff --git a/products/data_warehouse/backend/tests/test_managed_warehouse_data_status.py b/products/data_warehouse/backend/tests/test_managed_warehouse_data_status.py
index 511b799b90d7..9019cb40bc5b 100644
--- a/products/data_warehouse/backend/tests/test_managed_warehouse_data_status.py
+++ b/products/data_warehouse/backend/tests/test_managed_warehouse_data_status.py
@@ -3,21 +3,25 @@ from uuid import uuid4
from freezegun import freeze_time
-from django.test import SimpleTestCase
+from django.test import SimpleTestCase, TestCase
from parameterized import parameterized
from posthog.ducklake.models import DuckgresServerTeam, DuckgresSinkSchemaState
+from posthog.models import Organization, Team
from products.data_warehouse.backend.logic.managed_warehouse_data_status import (
QueueTailStatus,
ReadinessState,
SourceTableStatus,
+ _rollup_sources,
dataset_status,
+ get_source_schema_statuses,
sort_source_tables,
source_table_readiness,
)
from products.data_warehouse.backend.models import ManagedWarehouseBackfillPartition
+from products.warehouse_sources.backend.facade.models import ExternalDataSchema, ExternalDataSource
Granularity = ManagedWarehouseBackfillPartition.Granularity
LifecycleState = ManagedWarehouseBackfillPartition.LifecycleState
@@ -162,31 +166,42 @@ class TestDatasetStatus(SimpleTestCase):
assert status["total_partitions"] is None
-class TestSortSourceTables(SimpleTestCase):
- def _table(self, *, source_name: str, table_name: str, readiness_state: ReadinessState) -> SourceTableStatus:
- return {
- "schema_id": str(uuid4()),
- "source_id": str(uuid4()),
- "source_name": source_name,
- "source_type": source_name,
- "table_name": table_name,
- "readiness_state": readiness_state,
- "detail": "",
- "completed_chunks": 0,
- "total_chunks": None,
- "pending_batches": None,
- "oldest_pending_at": None,
- "last_applied_at": None,
- "last_synced_at": None,
- }
+def _table(
+ *,
+ source_name: str,
+ table_name: str,
+ readiness_state: ReadinessState,
+ source_id: str | None = None,
+ backfilled: bool = True,
+ pending_batches: int | None = None,
+ last_synced_at: datetime | None = None,
+) -> SourceTableStatus:
+ return {
+ "schema_id": str(uuid4()),
+ "source_id": source_id or str(uuid4()),
+ "source_name": source_name,
+ "source_type": source_name,
+ "table_name": table_name,
+ "readiness_state": readiness_state,
+ "detail": "",
+ "backfilled": backfilled,
+ "completed_chunks": 0,
+ "total_chunks": None,
+ "pending_batches": pending_batches,
+ "oldest_pending_at": None,
+ "last_applied_at": None,
+ "last_synced_at": last_synced_at,
+ }
+
+class TestSortSourceTables(SimpleTestCase):
def test_a_stalled_table_among_dozens_lands_on_the_first_page(self) -> None:
# The table paginates at 20 rows. A team importing dozens of tables would otherwise have the
# one that needs attention scattered anywhere by schema_id (a UUID), with no way to find it.
tables = [
- self._table(source_name="Stripe", table_name=f"table_{i}", readiness_state="up_to_date") for i in range(30)
+ _table(source_name="Stripe", table_name=f"table_{i}", readiness_state="up_to_date") for i in range(30)
]
- tables.insert(25, self._table(source_name="Hubspot", table_name="contacts", readiness_state="needs_attention"))
+ tables.insert(25, _table(source_name="Hubspot", table_name="contacts", readiness_state="needs_attention"))
ordered = sort_source_tables(tables)
@@ -195,11 +210,11 @@ class TestSortSourceTables(SimpleTestCase):
def test_orders_by_severity_then_name(self) -> None:
tables = [
- self._table(source_name="Zendesk", table_name="tickets", readiness_state="up_to_date"),
- self._table(source_name="Stripe", table_name="charges", readiness_state="catching_up"),
- self._table(source_name="Hubspot", table_name="deals", readiness_state="needs_attention"),
- self._table(source_name="Amplitude", table_name="events", readiness_state="catching_up"),
- self._table(source_name="Salesforce", table_name="accounts", readiness_state="up_to_date"),
+ _table(source_name="Zendesk", table_name="tickets", readiness_state="up_to_date"),
+ _table(source_name="Stripe", table_name="charges", readiness_state="catching_up"),
+ _table(source_name="Hubspot", table_name="deals", readiness_state="needs_attention"),
+ _table(source_name="Amplitude", table_name="events", readiness_state="catching_up"),
+ _table(source_name="Salesforce", table_name="accounts", readiness_state="up_to_date"),
]
ordered = [(table["source_name"], table["readiness_state"]) for table in sort_source_tables(tables)]
@@ -211,3 +226,165 @@ class TestSortSourceTables(SimpleTestCase):
("Salesforce", "up_to_date"),
("Zendesk", "up_to_date"),
]
+
+
+class TestRollupSources(SimpleTestCase):
+ def test_counts_backfilled_schemas_independent_of_live_catch_up_state(self) -> None:
+ # A schema can be fully backfilled but still "catching_up" on live imports. The rollup's
+ # backfilled count must track the one-time historical copy, not the live readiness label,
+ # or a source with a slow live queue would undercount how much history actually landed.
+ stripe_id = str(uuid4())
+ tables = [
+ _table(
+ source_id=stripe_id,
+ source_name="Stripe",
+ table_name="charges",
+ readiness_state="up_to_date",
+ backfilled=True,
+ ),
+ _table(
+ source_id=stripe_id,
+ source_name="Stripe",
+ table_name="customers",
+ readiness_state="catching_up",
+ backfilled=True,
+ ),
+ _table(
+ source_id=stripe_id,
+ source_name="Stripe",
+ table_name="invoices",
+ readiness_state="waiting",
+ backfilled=False,
+ ),
+ ]
+
+ [summary] = _rollup_sources(tables)
+
+ assert summary["total_schemas"] == 3
+ assert summary["backfilled_schemas"] == 2
+ # catching_up outranks waiting in READINESS_PRIORITY, so it wins the rollup.
+ assert summary["readiness_state"] == "catching_up"
+
+ def test_groups_by_source_not_by_table(self) -> None:
+ stripe_id, postgres_id = str(uuid4()), str(uuid4())
+ tables = [
+ _table(source_id=stripe_id, source_name="Stripe", table_name="charges", readiness_state="up_to_date"),
+ _table(source_id=stripe_id, source_name="Stripe", table_name="customers", readiness_state="up_to_date"),
+ _table(
+ source_id=postgres_id, source_name="Postgres", table_name="orders", readiness_state="needs_attention"
+ ),
+ ]
+
+ summaries = _rollup_sources(tables)
+
+ assert {s["source_name"]: s["total_schemas"] for s in summaries} == {"Stripe": 2, "Postgres": 1}
+ # needs_attention outranks up_to_date, so Postgres sorts first despite the alphabet.
+ assert [s["source_name"] for s in summaries] == ["Postgres", "Stripe"]
+
+ def test_pending_batches_null_propagates_rather_than_undercounting(self) -> None:
+ # If the live queue check failed, reporting a partial sum (or zero) would read as "caught
+ # up" when the real answer is "unknown" — null must survive the aggregation.
+ source_id = str(uuid4())
+ tables = [
+ _table(
+ source_id=source_id,
+ source_name="Stripe",
+ table_name="charges",
+ readiness_state="unknown",
+ pending_batches=None,
+ ),
+ _table(
+ source_id=source_id,
+ source_name="Stripe",
+ table_name="customers",
+ readiness_state="unknown",
+ pending_batches=None,
+ ),
+ ]
+
+ [summary] = _rollup_sources(tables)
+
+ assert summary["pending_batches"] is None
+
+ def test_pending_batches_sums_across_schemas_when_queue_is_available(self) -> None:
+ source_id = str(uuid4())
+ tables = [
+ _table(
+ source_id=source_id,
+ source_name="Stripe",
+ table_name="charges",
+ readiness_state="catching_up",
+ pending_batches=3,
+ ),
+ _table(
+ source_id=source_id,
+ source_name="Stripe",
+ table_name="customers",
+ readiness_state="up_to_date",
+ pending_batches=0,
+ ),
+ ]
+
+ [summary] = _rollup_sources(tables)
+
+ assert summary["pending_batches"] == 3
+
+ def test_last_synced_at_is_the_most_recent_across_schemas(self) -> None:
+ source_id = str(uuid4())
+ older = datetime(2026, 6, 1, tzinfo=UTC)
+ newer = datetime(2026, 7, 1, tzinfo=UTC)
+ tables = [
+ _table(
+ source_id=source_id,
+ source_name="Stripe",
+ table_name="charges",
+ readiness_state="up_to_date",
+ last_synced_at=older,
+ ),
+ _table(
+ source_id=source_id,
+ source_name="Stripe",
+ table_name="customers",
+ readiness_state="up_to_date",
+ last_synced_at=newer,
+ ),
+ _table(
+ source_id=source_id,
+ source_name="Stripe",
+ table_name="invoices",
+ readiness_state="waiting",
+ last_synced_at=None,
+ ),
+ ]
+
+ [summary] = _rollup_sources(tables)
+
+ assert summary["last_synced_at"] == newer
+
+
+class TestGetSourceSchemaStatuses(TestCase):
+ # The queue-tail lookup reads SourceBatch, which lives in its own database.
+ databases = {"default", "warehouse_sources_queue_db_writer"}
+
+ def test_scopes_to_the_requested_source_only(self) -> None:
+ # The modal fetches one source's schemas on click; a filter bug here would leak every
+ # other connected source's tables into it.
+ team = Team.objects.create(organization=Organization.objects.create(name="org"), name="t")
+ source_a = ExternalDataSource.objects.create(
+ team=team, source_id="a", connection_id="ca", source_type="Stripe", status="Running"
+ )
+ source_b = ExternalDataSource.objects.create(
+ team=team, source_id="b", connection_id="cb", source_type="Postgres", status="Running"
+ )
+ schema_a = ExternalDataSchema.objects.create(team=team, name="charges", source=source_a)
+ schema_b = ExternalDataSchema.objects.create(team=team, name="orders", source=source_b)
+ DuckgresSinkSchemaState.objects.create(
+ team=team, schema_id=schema_a.id, state=DuckgresSinkSchemaState.State.PRIMED
+ )
+ DuckgresSinkSchemaState.objects.create(
+ team=team, schema_id=schema_b.id, state=DuckgresSinkSchemaState.State.PRIMED
+ )
+
+ result = get_source_schema_statuses(team.id, str(source_a.id))
+
+ assert [row["schema_id"] for row in result] == [str(schema_a.id)]
diff --git a/products/data_warehouse/frontend/generated/api.schemas.ts b/products/data_warehouse/frontend/generated/api.schemas.ts
index 57d8b513d69f..802436bcb221 100644
--- a/products/data_warehouse/frontend/generated/api.schemas.ts
+++ b/products/data_warehouse/frontend/generated/api.schemas.ts
@@ -154,18 +154,14 @@ export interface ManagedWarehouseDatasetStatusApi {
last_updated_at: string | null
}
-export interface ManagedWarehouseSourceTableStatusApi {
- /** Imported source schema identifier. */
- schema_id: string
+export interface ManagedWarehouseSourceSummaryApi {
/** Imported source connection identifier. */
source_id: string
/** Display name for the imported source connection. */
source_name: string
/** Type of the imported source connection. */
source_type: string
- /** Imported table name. */
- table_name: string
- /** User-facing warehouse readiness state for this table.
+ /** Rolled-up warehouse readiness state across this source's schemas.
*
* * `not_configured` - not_configured
* * `waiting` - waiting
@@ -175,39 +171,26 @@ export interface ManagedWarehouseSourceTableStatusApi {
* * `needs_attention` - needs_attention
* * `unknown` - unknown */
readiness_state: ManagedWarehouseReadinessStateEnumApi
- /** Human-readable explanation of the table's readiness state. */
+ /** Human-readable explanation of this source's readiness state. */
detail: string
- /** Backfill chunks already copied into the warehouse. */
- completed_chunks: number
- /**
- * Total backfill chunks, or null before the copy plan is ready.
- * @nullable
- */
- total_chunks: number | null
+ /** Number of this source's schemas visible to the warehouse. */
+ total_schemas: number
+ /** Number of schemas whose one-time historical copy into the warehouse has completed. */
+ backfilled_schemas: number
/**
- * Imported batches waiting to be applied, or null when queue status is unavailable.
+ * Imported batches waiting to be applied across this source's schemas, or null when queue status is unavailable.
* @nullable
*/
pending_batches: number | null
/**
- * Creation time of the oldest unapplied imported batch.
- * @nullable
- */
- oldest_pending_at: string | null
- /**
- * When an imported batch was most recently applied to the warehouse.
- * @nullable
- */
- last_applied_at: string | null
- /**
- * When PostHog most recently completed the upstream source import.
+ * Most recent upstream source import completion across this source's schemas.
* @nullable
*/
last_synced_at: string | null
}
export interface ManagedWarehouseSourcesStatusApi {
- /** Rolled-up readiness state for imported source tables.
+ /** Rolled-up readiness state for imported sources.
*
* * `not_configured` - not_configured
* * `waiting` - waiting
@@ -219,8 +202,8 @@ export interface ManagedWarehouseSourcesStatusApi {
readiness_state: ManagedWarehouseReadinessStateEnumApi
/** Human-readable explanation of imported source readiness. */
detail: string
- /** Per-table source backfill and live import application statuses. */
- tables: ManagedWarehouseSourceTableStatusApi[]
+ /** Per-source rollup of schema backfill and live import application statuses. Reflects only warehouse source imports with sync enabled — manage sources at /data-management/sources. */
+ sources: ManagedWarehouseSourceSummaryApi[]
}
export interface ManagedWarehouseDataStatusResponseApi {
@@ -244,6 +227,65 @@ export interface ManagedWarehouseDataStatusResponseApi {
generated_at: string
}
+export interface ManagedWarehouseSourceTableStatusApi {
+ /** Imported source schema identifier. */
+ schema_id: string
+ /** Imported source connection identifier. */
+ source_id: string
+ /** Display name for the imported source connection. */
+ source_name: string
+ /** Type of the imported source connection. */
+ source_type: string
+ /** Imported table name. */
+ table_name: string
+ /** User-facing warehouse readiness state for this table.
+ *
+ * * `not_configured` - not_configured
+ * * `waiting` - waiting
+ * * `backfilling` - backfilling
+ * * `catching_up` - catching_up
+ * * `up_to_date` - up_to_date
+ * * `needs_attention` - needs_attention
+ * * `unknown` - unknown */
+ readiness_state: ManagedWarehouseReadinessStateEnumApi
+ /** Human-readable explanation of the table's readiness state. */
+ detail: string
+ /** Whether the one-time historical copy into the warehouse has completed for this table. */
+ backfilled: boolean
+ /** Backfill chunks already copied into the warehouse. */
+ completed_chunks: number
+ /**
+ * Total backfill chunks, or null before the copy plan is ready.
+ * @nullable
+ */
+ total_chunks: number | null
+ /**
+ * Imported batches waiting to be applied, or null when queue status is unavailable.
+ * @nullable
+ */
+ pending_batches: number | null
+ /**
+ * Creation time of the oldest unapplied imported batch.
+ * @nullable
+ */
+ oldest_pending_at: string | null
+ /**
+ * When an imported batch was most recently applied to the warehouse.
+ * @nullable
+ */
+ last_applied_at: string | null
+ /**
+ * When PostHog most recently completed the upstream source import.
+ * @nullable
+ */
+ last_synced_at: string | null
+}
+
+export interface ManagedWarehouseSourceSchemasResponseApi {
+ /** Per-schema backfill and live import application status for the requested source. */
+ schemas: ManagedWarehouseSourceTableStatusApi[]
+}
+
export interface ProvisionWarehouseRequestApi {
/** Name for the new database */
database_name: string
@@ -2906,6 +2948,13 @@ export type DataWarehouseCheckDatabaseNameRetrieveParams = {
name: string
}
+export type DataWarehouseManagedWarehouseSourceSchemasRetrieveParams = {
+ /**
+ * Imported source connection to fetch per-schema detail for.
+ */
+ source_id: string
+}
+
export type FixHogqlListParams = {
/**
* Number of results to return per page.
diff --git a/products/data_warehouse/frontend/generated/api.ts b/products/data_warehouse/frontend/generated/api.ts
index f924d0970528..ae21822f8bec 100644
--- a/products/data_warehouse/frontend/generated/api.ts
+++ b/products/data_warehouse/frontend/generated/api.ts
@@ -13,6 +13,7 @@ import type {
DataModelingJobApi,
DataModelingJobsListParams,
DataWarehouseCheckDatabaseNameRetrieveParams,
+ DataWarehouseManagedWarehouseSourceSchemasRetrieveParams,
DataWarehouseModelPathApi,
DataWarehouseSavedQueryApi,
DataWarehouseSavedQueryColumnAnnotationApi,
@@ -26,6 +27,7 @@ import type {
InsightVariableApi,
InsightVariablesListParams,
ManagedWarehouseDataStatusResponseApi,
+ ManagedWarehouseSourceSchemasResponseApi,
PaginatedDataModelingJobListApi,
PaginatedDataWarehouseModelPathListApi,
PaginatedDataWarehouseSavedQueryColumnAnnotationListApi,
@@ -349,6 +351,43 @@ export const dataWarehouseManagedWarehouseDataStatusRetrieve = async (
)
}
+export const getDataWarehouseManagedWarehouseSourceSchemasRetrieveUrl = (
+ projectId: string,
+ params: DataWarehouseManagedWarehouseSourceSchemasRetrieveParams
+) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/data_warehouse/managed-warehouse-source-schemas/?${stringifiedParams}`
+ : `/api/projects/${projectId}/data_warehouse/managed-warehouse-source-schemas/`
+}
+
+/**
+ * Per-schema backfill and live import status for one source, for the Overview tab's drill-down modal — the main status endpoint only returns a per-source rollup.
+ * @summary Get per-schema detail for one imported source
+ */
+export const dataWarehouseManagedWarehouseSourceSchemasRetrieve = async (
+ projectId: string,
+ params: DataWarehouseManagedWarehouseSourceSchemasRetrieveParams,
+ options?: RequestInit
+): Promise<ManagedWarehouseSourceSchemasResponseApi> => {
+ return apiMutator<ManagedWarehouseSourceSchemasResponseApi>(
+ getDataWarehouseManagedWarehouseSourceSchemasRetrieveUrl(projectId, params),
+ {
+ ...options,
+ method: 'GET',
+ }
+ )
+}
+
export const getDataWarehousePropertyValuesRetrieveUrl = (projectId: string) => {
return `/api/projects/${projectId}/data_warehouse/property_values/`
}
diff --git a/products/data_warehouse/mcp/tools.yaml b/products/data_warehouse/mcp/tools.yaml
index 3853c0a706b9..f83c499fb220 100644
--- a/products/data_warehouse/mcp/tools.yaml
+++ b/products/data_warehouse/mcp/tools.yaml
@@ -48,6 +48,9 @@ tools:
data-warehouse-managed-warehouse-data-status-retrieve:
operation: data_warehouse_managed_warehouse_data_status_retrieve
enabled: false
+ data-warehouse-managed-warehouse-source-schemas-retrieve:
+ operation: data_warehouse_managed_warehouse_source_schemas_retrieve
+ enabled: false
data-warehouse-property-values-retrieve:
operation: data_warehouse_property_values_retrieve
enabled: false
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 2ed6b469f5d6..06e0ba8a63b2 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -33438,18 +33438,14 @@ export namespace Schemas {
last_updated_at: string | null;
}
- export interface ManagedWarehouseSourceTableStatus {
- /** Imported source schema identifier. */
- schema_id: string;
+ export interface ManagedWarehouseSourceSummary {
/** Imported source connection identifier. */
source_id: string;
/** Display name for the imported source connection. */
source_name: string;
/** Type of the imported source connection. */
source_type: string;
- /** Imported table name. */
- table_name: string;
- /** User-facing warehouse readiness state for this table.
+ /** Rolled-up warehouse readiness state across this source's schemas.
*
* * `not_configured` - not_configured
* * `waiting` - waiting
@@ -33459,39 +33455,26 @@ export namespace Schemas {
* * `needs_attention` - needs_attention
* * `unknown` - unknown */
readiness_state: ManagedWarehouseReadinessStateEnum;
- /** Human-readable explanation of the table's readiness state. */
+ /** Human-readable explanation of this source's readiness state. */
detail: string;
- /** Backfill chunks already copied into the warehouse. */
- completed_chunks: number;
- /**
- * Total backfill chunks, or null before the copy plan is ready.
- * @nullable
- */
- total_chunks: number | null;
+ /** Number of this source's schemas visible to the warehouse. */
+ total_schemas: number;
+ /** Number of schemas whose one-time historical copy into the warehouse has completed. */
+ backfilled_schemas: number;
/**
- * Imported batches waiting to be applied, or null when queue status is unavailable.
+ * Imported batches waiting to be applied across this source's schemas, or null when queue status is unavailable.
* @nullable
*/
pending_batches: number | null;
/**
- * Creation time of the oldest unapplied imported batch.
- * @nullable
- */
- oldest_pending_at: string | null;
- /**
- * When an imported batch was most recently applied to the warehouse.
- * @nullable
- */
- last_applied_at: string | null;
- /**
- * When PostHog most recently completed the upstream source import.
+ * Most recent upstream source import completion across this source's schemas.
* @nullable
*/
last_synced_at: string | null;
}
export interface ManagedWarehouseSourcesStatus {
- /** Rolled-up readiness state for imported source tables.
+ /** Rolled-up readiness state for imported sources.
*
* * `not_configured` - not_configured
* * `waiting` - waiting
@@ -33503,8 +33486,8 @@ export namespace Schemas {
readiness_state: ManagedWarehouseReadinessStateEnum;
/** Human-readable explanation of imported source readiness. */
detail: string;
- /** Per-table source backfill and live import application statuses. */
- tables: ManagedWarehouseSourceTableStatus[];
+ /** Per-source rollup of schema backfill and live import application statuses. Reflects only warehouse source imports with sync enabled — manage sources at /data-management/sources. */
+ sources: ManagedWarehouseSourceSummary[];
}
export interface ManagedWarehouseDataStatusResponse {
@@ -33528,6 +33511,65 @@ export namespace Schemas {
generated_at: string;
}
+ export interface ManagedWarehouseSourceTableStatus {
+ /** Imported source schema identifier. */
+ schema_id: string;
+ /** Imported source connection identifier. */
+ source_id: string;
+ /** Display name for the imported source connection. */
+ source_name: string;
+ /** Type of the imported source connection. */
+ source_type: string;
+ /** Imported table name. */
+ table_name: string;
+ /** User-facing warehouse readiness state for this table.
+ *
+ * * `not_configured` - not_configured
+ * * `waiting` - waiting
+ * * `backfilling` - backfilling
+ * * `catching_up` - catching_up
+ * * `up_to_date` - up_to_date
+ * * `needs_attention` - needs_attention
+ * * `unknown` - unknown */
+ readiness_state: ManagedWarehouseReadinessStateEnum;
+ /** Human-readable explanation of the table's readiness state. */
+ detail: string;
+ /** Whether the one-time historical copy into the warehouse has completed for this table. */
+ backfilled: boolean;
+ /** Backfill chunks already copied into the warehouse. */
+ completed_chunks: number;
+ /**
+ * Total backfill chunks, or null before the copy plan is ready.
+ * @nullable
+ */
+ total_chunks: number | null;
+ /**
+ * Imported batches waiting to be applied, or null when queue status is unavailable.
+ * @nullable
+ */
+ pending_batches: number | null;
+ /**
+ * Creation time of the oldest unapplied imported batch.
+ * @nullable
+ */
+ oldest_pending_at: string | null;
+ /**
+ * When an imported batch was most recently applied to the warehouse.
+ * @nullable
+ */
+ last_applied_at: string | null;
+ /**
+ * When PostHog most recently completed the upstream source import.
+ * @nullable
+ */
+ last_synced_at: string | null;
+ }
+
+ export interface ManagedWarehouseSourceSchemasResponse {
+ /** Per-schema backfill and live import application status for the requested source. */
+ schemas: ManagedWarehouseSourceTableStatus[];
+ }
+
export interface MarkToleratedInput {
/** UUID of the changed snapshot to mark as a known tolerated alternate. Future runs that produce the same alternate hash for this identifier will not be flagged as changes. */
snapshot_id: string;
@@ -62933,6 +62975,13 @@ export namespace Schemas {
name: string;
};
+ export type EnvironmentsDataWarehouseManagedWarehouseSourceSchemasRetrieveParams = {
+ /**
+ * Imported source connection to fetch per-schema detail for.
+ */
+ source_id: string;
+ };
+
export type EnvironmentsDatasetItemsListParams = {
/**
* Filter by dataset ID
@@ -69412,6 +69461,13 @@ export namespace Schemas {
name: string;
};
+ export type DataWarehouseManagedWarehouseSourceSchemasRetrieveParams = {
+ /**
+ * Imported source connection to fetch per-schema detail for.
+ */
+ source_id: string;
+ };
+
export type DatasetItemsListParams = {
/**
* Filter by dataset ID