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-modeling): show refresh mode in run history (#102881)

Jovan Sakovic55ca171c322b
diff --git a/frontend/src/scenes/data-warehouse/saved_queries/MaterializationStatusPanel.tsx b/frontend/src/scenes/data-warehouse/saved_queries/MaterializationStatusPanel.tsx
index f05f87819070..5ae505f2e457 100644
--- a/frontend/src/scenes/data-warehouse/saved_queries/MaterializationStatusPanel.tsx
+++ b/frontend/src/scenes/data-warehouse/saved_queries/MaterializationStatusPanel.tsx
@@ -463,14 +463,28 @@ export function MaterializationStatusPanel({
{
title: 'Refresh mode',
dataIndex: 'run_mode',
- isHidden:
- !showIncremental || !savedQuery.is_materialized || !jobsPageResults?.results?.length,
- render: (_, { run_mode }: DataModelingJobApi) =>
- run_mode === 'incremental'
- ? 'Incremental'
- : run_mode === 'full_refresh'
- ? 'Full refresh'
- : '-',
+ isHidden: !incrementalFlagOn || !savedQuery.has_incremental_history,
+ render: (_, { run_mode, full_refresh_reason }: DataModelingJobApi) => {
+ if (run_mode === 'incremental') {
+ return 'Incremental'
+ }
+ if (run_mode === 'full_refresh') {
+ return full_refresh_reason ? (
+ <Tooltip title={`Full refresh. Reason: ${full_refresh_reason}.`}>
+ <span
+ className="border-b border-dotted cursor-help"
+ tabIndex={0}
+ aria-label={`Full refresh. Reason: ${full_refresh_reason}.`}
+ >
+ Full refresh
+ </span>
+ </Tooltip>
+ ) : (
+ 'Full refresh'
+ )
+ }
+ return '-'
+ },
},
{
title: 'Error',
diff --git a/frontend/src/scenes/data-warehouse/saved_queries/materializationJobsLogic.test.ts b/frontend/src/scenes/data-warehouse/saved_queries/materializationJobsLogic.test.ts
index 64b9d03c348e..fc287d58cf5c 100644
--- a/frontend/src/scenes/data-warehouse/saved_queries/materializationJobsLogic.test.ts
+++ b/frontend/src/scenes/data-warehouse/saved_queries/materializationJobsLogic.test.ts
@@ -16,6 +16,7 @@ import { MaterializationRunActions } from 'products/data_warehouse/frontend/shar
import { dataWarehouseViewsLogic } from './dataWarehouseViewsLogic'
import { materializationJobsLogic } from './materializationJobsLogic'
+import { MaterializationStatusPanel } from './MaterializationStatusPanel'
const ELIGIBLE_CHECK = {
eligible: true,
@@ -95,6 +96,61 @@ describe('materializationJobsLogic', () => {
jest.useRealTimers()
})
+ it.each([
+ ['shows a first run with incremental settings', 'full_refresh', 'first run', true],
+ ['shows a completed incremental run', 'incremental', null, true],
+ ['hides full-refresh-only history', 'full_refresh', 'not configured for incremental materialization', false],
+ ])('%s', async (_name, runMode, fullRefreshReason, showsRefreshMode) => {
+ const mocks = apiMocks({
+ isMaterialized: true,
+ incremental: {
+ enabled: false,
+ unique_key: ['day'],
+ incremental_key: 'day',
+ },
+ savedQueryExtras: { has_incremental_history: showsRefreshMode },
+ })
+ mocks.get!['/api/projects/:team_id/data_modeling_jobs/'] = [
+ 200,
+ {
+ count: 1,
+ results: [
+ {
+ id: 'run-1',
+ status: 'Completed',
+ run_mode: runMode,
+ full_refresh_reason: fullRefreshReason,
+ rows_materialized: 20,
+ },
+ ],
+ },
+ ]
+ useMocks(mocks)
+ logic = materializationJobsLogic({ viewId: 'view-1' })
+ logic.mount()
+ await expectLogic(logic).toDispatchActions(['loadSavedQuerySuccess', 'loadDataModelingJobsSuccess'])
+
+ render(
+ createElement(MaterializationStatusPanel, {
+ viewId: 'view-1',
+ showRunActions: false,
+ showStatusSummary: false,
+ })
+ )
+
+ // The settings section carries the same heading text, so match the table header cell itself.
+ const showsRefreshModeColumn = Array.from(document.querySelectorAll('th')).some(
+ (header) => header.textContent?.trim() === 'Refresh mode'
+ )
+ expect(showsRefreshModeColumn).toBe(showsRefreshMode)
+ if (fullRefreshReason === 'first run') {
+ expect(screen.getByLabelText('Full refresh. Reason: first run.')).toBeTruthy()
+ }
+ if (runMode === 'incremental') {
+ expect(screen.getByText('Incremental')).toBeTruthy()
+ }
+ })
+
it('pages through older runs without changing the latest run or growing polling requests', async () => {
const mocks = apiMocks({ isMaterialized: true })
const requests: string[] = []
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index fd20e5e16cb8..b94785beaed7 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -6358,6 +6358,8 @@ export interface DataWarehouseSavedQuery {
user_access_level?: AccessControlLevel
incremental?: DataWarehouseSavedQueryIncremental | null
incremental_state?: DataWarehouseSavedQueryIncrementalState | null
+ /** Whether incremental settings participated in any materialization run. */
+ has_incremental_history?: boolean
}
export interface DataWarehouseSavedQueryIncremental {
diff --git a/posthog/temporal/data_modeling/activities/materialize_view.py b/posthog/temporal/data_modeling/activities/materialize_view.py
index 267200cd24bd..301beab97011 100644
--- a/posthog/temporal/data_modeling/activities/materialize_view.py
+++ b/posthog/temporal/data_modeling/activities/materialize_view.py
@@ -59,6 +59,7 @@ from products.data_modeling.backend.facade.api import (
get_incremental_config,
get_incremental_state,
inject_incremental_filter,
+ record_incremental_history,
set_incremental_state,
window_start,
)
@@ -1231,6 +1232,10 @@ async def materialize_view_activity(inputs: MaterializeViewInputs) -> Materializ
plan = dataclasses.replace(plan, incremental=False, reason="table missing")
await logger.ainfo(f"Materializing node {objects.node.name}: {plan.reason}")
+ # Record this before writing any rows. A failed first seed still belongs in mode history.
+ if plan.config is not None:
+ await database_sync_to_async_pool(record_incremental_history)(objects.saved_query)
+
# Recorded on the job so the runs UI can tell a rebuild's row count (the whole table) apart
# from an incremental run's (only the rows synced in its window).
objects.job.run_mode = (
diff --git a/posthog/temporal/tests/data_modeling/test_materialize_view_incremental.py b/posthog/temporal/tests/data_modeling/test_materialize_view_incremental.py
index 1546cbec77e7..0195b61f529c 100644
--- a/posthog/temporal/tests/data_modeling/test_materialize_view_incremental.py
+++ b/posthog/temporal/tests/data_modeling/test_materialize_view_incremental.py
@@ -158,6 +158,7 @@ class TestIncrementalMaterialization:
state = get_incremental_state(asaved_query)
assert state.last_run_mode == "full_refresh"
assert state.watermark is not None
+ assert state.has_incremental_history is True
# The runs UI reads the mode off the job to explain what its row count means.
await database_sync_to_async(ajob.refresh_from_db)()
@@ -506,7 +507,9 @@ class TestIncrementalMaterialization:
await _run(activity_environment, ateam, anode, ajob, adag, *batches)
await database_sync_to_async(asaved_query.refresh_from_db)()
- assert get_incremental_state(asaved_query).watermark is None
+ state = get_incremental_state(asaved_query)
+ assert state.watermark is None
+ assert state.has_incremental_history is True
async def test_lookback_shifts_the_second_runs_window(
self, activity_environment, ateam, anode, asaved_query, ajob, bucket_name, adag
diff --git a/products/data_modeling/backend/facade/api.py b/products/data_modeling/backend/facade/api.py
index 55aed962de41..7ff8f3b18298 100644
--- a/products/data_modeling/backend/facade/api.py
+++ b/products/data_modeling/backend/facade/api.py
@@ -74,6 +74,8 @@ _LAZY = {
"deserialize_watermark": "logic.incremental",
"get_incremental_config": "logic.incremental",
"get_incremental_state": "logic.incremental",
+ "has_incremental_history": "logic.incremental",
+ "record_incremental_history": "logic.incremental",
"set_incremental_state": "logic.incremental",
"window_start": "logic.incremental",
"IncrementalFilterError": "logic.incremental_filter",
diff --git a/products/data_modeling/backend/logic/incremental.py b/products/data_modeling/backend/logic/incremental.py
index 64dd8958a244..005f493d7370 100644
--- a/products/data_modeling/backend/logic/incremental.py
+++ b/products/data_modeling/backend/logic/incremental.py
@@ -62,6 +62,7 @@ class IncrementalState:
definition_fingerprint: Optional[str] = None
last_full_refresh_at: Optional[str] = None
last_run_mode: Optional[str] = None
+ has_incremental_history: bool = False
def get_incremental_config(saved_query) -> Optional[IncrementalConfig]:
@@ -101,9 +102,40 @@ def get_incremental_state(saved_query) -> IncrementalState:
definition_fingerprint=raw.get("definition_fingerprint"),
last_full_refresh_at=raw.get("last_full_refresh_at"),
last_run_mode=raw.get("last_run_mode"),
+ has_incremental_history=raw.get("has_incremental_history") is True,
)
+def has_incremental_history(saved_query) -> bool:
+ """Whether an incremental plan participated in a run.
+
+ The config fallback covers views that used the feature before the durable marker existed.
+ Current clients remove the config when they disable incremental materialization.
+ """
+ state = get_incremental_state(saved_query)
+ return (
+ state.has_incremental_history
+ or state.last_run_mode is not None
+ or isinstance(saved_query.incremental_config, dict)
+ )
+
+
+def record_incremental_history(saved_query) -> None:
+ """Persist the history marker once without overwriting concurrent state changes."""
+ if get_incremental_state(saved_query).has_incremental_history:
+ return
+
+ model = type(saved_query)
+ with transaction.atomic():
+ locked = model.objects.select_for_update().get(pk=saved_query.pk)
+ state = dict(locked.incremental_state or {})
+ if state.get("has_incremental_history") is not True:
+ state["has_incremental_history"] = True
+ locked.incremental_state = state
+ locked.save(update_fields=["incremental_state"])
+ saved_query.incremental_state = state
+
+
def definition_fingerprint(query: dict | None, config: IncrementalConfig) -> Optional[str]:
"""Hash the query's parsed shape plus its incremental config.
diff --git a/products/data_modeling/backend/test/test_incremental_config.py b/products/data_modeling/backend/test/test_incremental_config.py
index dd839368ebfd..b0a75f391334 100644
--- a/products/data_modeling/backend/test/test_incremental_config.py
+++ b/products/data_modeling/backend/test/test_incremental_config.py
@@ -14,6 +14,8 @@ from products.data_modeling.backend.logic.incremental import (
deserialize_watermark,
get_incremental_config,
get_incremental_state,
+ has_incremental_history,
+ record_incremental_history,
set_incremental_state,
window_start,
)
@@ -177,10 +179,11 @@ class TestIncrementalConfig(BaseTest):
assert get_incremental_config(saved_query) is not None
assert get_incremental_state(saved_query).watermark == 1
- def test_clearing_state_drops_progress_but_keeps_config(self) -> None:
+ def test_clearing_state_drops_progress_but_keeps_config_and_history(self) -> None:
saved_query = self._saved_query(
incremental_config={"enabled": True, "incremental_key": "day", "unique_key": ["day"]}
)
+ record_incremental_history(saved_query)
set_incremental_state(saved_query, watermark=5, fingerprint="abc", mode="incremental")
clear_incremental_state(saved_query)
@@ -189,8 +192,19 @@ class TestIncrementalConfig(BaseTest):
state = get_incremental_state(saved_query)
assert state.watermark is None
assert state.watermark_type is None
+ assert state.has_incremental_history is True
assert get_incremental_config(saved_query) is not None
+ def test_existing_incremental_config_is_history_evidence(self) -> None:
+ saved_query = self._saved_query(
+ incremental_config={"enabled": False, "incremental_key": "day", "unique_key": ["day"]}
+ )
+
+ assert has_incremental_history(saved_query) is True
+
+ saved_query.incremental_config = None
+ assert has_incremental_history(saved_query) is False
+
@parameterized.expand(
[
("no_watermark", None, None, 3600, None),
diff --git a/products/data_warehouse/backend/presentation/views/saved_query/editing.py b/products/data_warehouse/backend/presentation/views/saved_query/editing.py
index b3da7d87b19c..18f81a783e42 100644
--- a/products/data_warehouse/backend/presentation/views/saved_query/editing.py
+++ b/products/data_warehouse/backend/presentation/views/saved_query/editing.py
@@ -28,6 +28,7 @@ from posthog.models.activity_logging.activity_log import Change, Detail, changes
from posthog.rbac.query_access import assert_user_can_read_query
from products.access_control.backend.presentation.access_control import UserAccessControlSerializerMixin
+from products.data_modeling.backend.facade.api import has_incremental_history
from products.data_modeling.backend.facade.modeling import ResolutionCycleError, get_parents_from_model_query
from products.data_modeling.backend.facade.models import (
DataWarehouseSavedQuery,
@@ -156,6 +157,9 @@ class DataWarehouseSavedQuerySerializer(
help_text="How far incremental materialization has progressed. Null until the first run "
"records any. Written by the materialization run, not by this API.",
)
+ has_incremental_history = serializers.SerializerMethodField(
+ help_text="Whether incremental settings participated in any materialization run."
+ )
class Meta:
model = DataWarehouseSavedQuery
@@ -166,6 +170,7 @@ class DataWarehouseSavedQuerySerializer(
"query",
"incremental",
"incremental_state",
+ "has_incremental_history",
"created_by",
"created_at",
"updated_at",
@@ -197,6 +202,7 @@ class DataWarehouseSavedQuerySerializer(
"updated_at",
"columns",
"incremental_state",
+ "has_incremental_history",
"status",
"last_run_at",
"managed_viewset_kind",
@@ -233,6 +239,10 @@ class DataWarehouseSavedQuerySerializer(
saved_query=view, column_name=""
).delete()
+ @extend_schema_field(serializers.BooleanField())
+ def get_has_incremental_history(self, view: DataWarehouseSavedQuery) -> bool:
+ return has_incremental_history(view)
+
@extend_schema_field(
serializers.DictField(
child=view_state.SavedQuerySuspensionSerializer(),
diff --git a/products/data_warehouse/backend/tests/api/test_saved_query_incremental.py b/products/data_warehouse/backend/tests/api/test_saved_query_incremental.py
index 3a0582b5c5cb..77a02cc2398e 100644
--- a/products/data_warehouse/backend/tests/api/test_saved_query_incremental.py
+++ b/products/data_warehouse/backend/tests/api/test_saved_query_incremental.py
@@ -50,6 +50,26 @@ class TestSavedQueryIncremental(APIBaseTest):
assert response.status_code == 201, response.json()
+ def test_incremental_history_comes_from_saved_state(self):
+ created = self._create()
+ saved_query_id = created.json()["id"]
+ assert created.json()["has_incremental_history"] is False
+
+ saved_query = DataWarehouseSavedQuery.objects.get(id=saved_query_id)
+ saved_query.incremental_state = {"has_incremental_history": True}
+ saved_query.save(update_fields=["incremental_state"])
+
+ response = self.client.get(self._url(f"{saved_query_id}/"))
+
+ assert response.status_code == 200, response.json()
+ assert response.json()["has_incremental_history"] is True
+
+ def test_disabled_legacy_config_counts_as_incremental_history(self):
+ response = self._create(incremental={**CONFIG, "enabled": False})
+
+ assert response.status_code == 201, response.json()
+ assert response.json()["has_incremental_history"] is True
+
def test_incremental_state_is_read_only(self):
created = self._create(incremental=CONFIG)
saved_query_id = created.json()["id"]
diff --git a/products/data_warehouse/frontend/generated/api.schemas.ts b/products/data_warehouse/frontend/generated/api.schemas.ts
index e0cb9d38f972..2207b46a0eab 100644
--- a/products/data_warehouse/frontend/generated/api.schemas.ts
+++ b/products/data_warehouse/frontend/generated/api.schemas.ts
@@ -1446,6 +1446,8 @@ export interface DataWarehouseSavedQueryApi {
incremental?: IncrementalConfigApi | null
/** How far incremental materialization has progressed. Null until the first run records any. Written by the materialization run, not by this API. */
readonly incremental_state: IncrementalStateApi | null
+ /** Whether incremental settings participated in any materialization run. */
+ readonly has_incremental_history: boolean
readonly created_by: UserBasicApi
readonly created_at: string
/** @nullable */
@@ -1573,6 +1575,8 @@ export interface PatchedDataWarehouseSavedQueryApi {
incremental?: IncrementalConfigApi | null
/** How far incremental materialization has progressed. Null until the first run records any. Written by the materialization run, not by this API. */
readonly incremental_state?: IncrementalStateApi | null
+ /** Whether incremental settings participated in any materialization run. */
+ readonly has_incremental_history?: boolean
readonly created_by?: UserBasicApi
readonly created_at?: string
/** @nullable */
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 75402b604faa..bc1e245bc91c 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -24718,6 +24718,8 @@ export namespace Schemas {
incremental?: IncrementalConfig | null;
/** How far incremental materialization has progressed. Null until the first run records any. Written by the materialization run, not by this API. */
readonly incremental_state: IncrementalState | null;
+ /** Whether incremental settings participated in any materialization run. */
+ readonly has_incremental_history: boolean;
readonly created_by: UserBasic;
readonly created_at: string;
/** @nullable */
@@ -67229,6 +67231,8 @@ export namespace Schemas {
incremental?: IncrementalConfig | null;
/** How far incremental materialization has progressed. Null until the first run records any. Written by the materialization run, not by this API. */
readonly incremental_state?: IncrementalState | null;
+ /** Whether incremental settings participated in any materialization run. */
+ readonly has_incremental_history?: boolean;
readonly created_by?: UserBasic;
readonly created_at?: string;
/** @nullable */