: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-modeling): stamp the endpoint version on its model node (#101785)
Jovan Sakovicf8c8110d90e2
diff --git a/frontend/src/scenes/data-management/database/databaseTableListLogic.ts b/frontend/src/scenes/data-management/database/databaseTableListLogic.tsindex 5333c6c92366..6619296c02b4 100644--- a/frontend/src/scenes/data-management/database/databaseTableListLogic.ts+++ b/frontend/src/scenes/data-management/database/databaseTableListLogic.ts@@ -16,6 +16,8 @@ import {} from '~/queries/schema/schema-general'import { setLatestVersionsOnQuery } from '~/queries/utils'+import { parseEndpointModelName } from 'products/data_modeling/frontend/endpointModelName'+const toMapByName = <T extends { name: string }>(items: T[]): Record<string, T> =>items.reduce((acc, cur) => {@@ -492,26 +494,18 @@ export const databaseTableListLogic = kea<databaseTableListLogicType>([latestEndpointTables: [(s) => [s.endpointTables],(endpointTables: DatabaseSchemaEndpointTable[]): DatabaseSchemaEndpointTable[] => {- const grouped: Record<string, DatabaseSchemaEndpointTable> = {}+ const grouped: Record<string, { table: DatabaseSchemaEndpointTable; version: number }> = {}for (const table of endpointTables) {- const match = table.name.match(/^(.+)_v(\d+)$/)- if (!match) {+ const parsed = parseEndpointModelName(table.name)+ if (!parsed) {continue}- const [, baseName, versionStr] = match- const version = parseInt(versionStr, 10)- const existing = grouped[baseName]- if (!existing) {- grouped[baseName] = table- } else {- const existingMatch = existing.name.match(/_v(\d+)$/)- const existingVersion = existingMatch ? parseInt(existingMatch[1], 10) : 0- if (version > existingVersion) {- grouped[baseName] = table- }+ const existing = grouped[parsed.endpointName]+ if (!existing || parsed.version > existing.version) {+ grouped[parsed.endpointName] = { table, version: parsed.version }}}- return Object.values(grouped)+ return Object.values(grouped).map(({ table }) => table)},{ resultEqualityCheck: objectsEqual },],diff --git a/frontend/src/scenes/data-warehouse/editor/sidebar/QueryDatabase.tsx b/frontend/src/scenes/data-warehouse/editor/sidebar/QueryDatabase.tsxindex c80ab60f48a8..0757b56dc69f 100644--- a/frontend/src/scenes/data-warehouse/editor/sidebar/QueryDatabase.tsx+++ b/frontend/src/scenes/data-warehouse/editor/sidebar/QueryDatabase.tsx@@ -60,6 +60,7 @@ import { DatabaseSerializedFieldType } from '~/queries/schema/schema-general'import { escapeDottedHogQLIdentifier, escapePropertyAsHogQLIdentifier } from '~/queries/utils'import { AccessControlLevel, AccessControlResourceType } from '~/types'+import { endpointModelUrl } from 'products/data_modeling/frontend/endpointModelName'import { sourceManagementLogic } from 'products/data_warehouse/frontend/shared/logics/sourceManagementLogic'import { buildSelectAllQuery } from 'products/data_warehouse/frontend/utils'import { ExternalDataSourceTypeEnumApi } from 'products/warehouse_sources/frontend/generated/api.schemas'@@ -369,16 +370,7 @@ export const QueryDatabase = ({router.actions.push(url)}- const getEndpointUrl = (item: TreeDataItem): string => {- const endpointName = item.record?.table?.name ?? item.name- const versionMatch = endpointName.match(/^(.+)_v(\d+)$/)-- if (versionMatch) {- return urls.endpoint(versionMatch[1], parseInt(versionMatch[2], 10))- }-- return urls.endpoint(item.name)- }+ const getEndpointUrl = (item: TreeDataItem): string => endpointModelUrl(item.record?.table?.name ?? item.name)const treeRef = useRef<LemonTreeRef>(null)useEffect(() => {diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex 9d20c606650b..fbfd789f14fb 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -82,7 +82,7 @@ import type {import { QueryContext } from '~/queries/types'import { AlertType } from 'products/alerts/frontend/types'-import type { NodeApiSuspended } from 'products/data_modeling/frontend/generated/api.schemas'+import type { NodeApiSuspended, NodeEndpointApi } from 'products/data_modeling/frontend/generated/api.schemas'import type {DataWarehouseSavedQueryApi,DataWarehouseSavedQueryApiSuspended,@@ -6300,6 +6300,8 @@ export interface DataModelingNode {last_run_error?: string | nullsync_interval?: DataModelingSyncIntervalsuspended?: NodeApiSuspended+ /** Set on endpoint nodes stamped at materialization enable; older nodes carry only the name */+ endpoint?: NodeEndpointApi | null}export interface DataModelingEdge {diff --git a/products/data_modeling/backend/facade/api.py b/products/data_modeling/backend/facade/api.pyindex 5c1b6b2fe674..7ce8dbb56bd1 100644--- a/products/data_modeling/backend/facade/api.py+++ b/products/data_modeling/backend/facade/api.py@@ -19,6 +19,8 @@ _LAZY = {"promote_view_nodes_to_matview": "logic.saved_query_dag_sync","sync_saved_query_to_dag": "logic.saved_query_dag_sync","update_node_type": "logic.saved_query_dag_sync",+ "link_endpoint_nodes": "logic.node_endpoint",+ "endpoint_link": "logic.node_endpoint","SavedQueryNotFoundError": "logic.node_materialization","SavedQueryNotOnV2ScheduleError": "logic.node_materialization","is_saved_query_on_v2_schedule": "logic.node_materialization",diff --git a/products/data_modeling/backend/logic/node_endpoint.py b/products/data_modeling/backend/logic/node_endpoint.pynew file mode 100644index 000000000000..d334aee85d24--- /dev/null+++ b/products/data_modeling/backend/logic/node_endpoint.py@@ -0,0 +1,51 @@+"""The endpoint version whose materialization a node's saved query backs.++Endpoints depends on data modeling, not the reverse, so nothing here can reach EndpointVersion.+The endpoints enable path stamps the link onto the node and the node serializer reads it back.+"""++from typing import Any+from uuid import UUID++from django.db import transaction++from posthog.dataclasses import frozen++from products.data_modeling.backend.models.node import Node++ENDPOINT_PROPERTY = "endpoint"+++@frozen+class EndpointLink:+ name: str+ version: int+++def link_endpoint_nodes(*, team_id: int, saved_query_id: UUID, endpoint_name: str, version: int) -> int:+ """Stamp every node of the saved query with the endpoint version it materializes. Returns the count.++ `properties` is one JSON blob, so this takes the row lock every other writer of the field takes —+ without it the stamp would drop suspension state a concurrent materialization committed to the+ same row after this read.+ """+ with transaction.atomic():+ nodes = list(Node.objects.select_for_update().filter(team_id=team_id, saved_query_id=saved_query_id))+ for node in nodes:+ properties = node.properties or {}+ properties[ENDPOINT_PROPERTY] = {"name": endpoint_name, "version": version}+ node.properties = properties+ node.save(update_fields=["properties"])+ return len(nodes)+++def endpoint_link(properties: dict[str, Any] | None) -> EndpointLink | None:+ """`properties` is an unvalidated JSON blob, so a malformed stamp reads as "not an endpoint"+ rather than failing the node serializer and with it the whole list response."""+ link = (properties or {}).get(ENDPOINT_PROPERTY)+ if not isinstance(link, dict):+ return None+ name, version = link.get("name"), link.get("version")+ if not isinstance(name, str) or not isinstance(version, int) or isinstance(version, bool):+ return None+ return EndpointLink(name=name, version=version)diff --git a/products/data_modeling/backend/presentation/views/node.py b/products/data_modeling/backend/presentation/views/node.pyindex 5528f514c9f2..98bb212b064c 100644--- a/products/data_modeling/backend/presentation/views/node.py+++ b/products/data_modeling/backend/presentation/views/node.py@@ -26,7 +26,12 @@ from posthog.temporal.common.client import sync_connectfrom posthog.temporal.data_modeling.workflows.execute_dag import ExecuteDAGInputsfrom products.access_control.backend.facade.user_access_control import AccessControlLevel-from products.data_modeling.backend.facade.api import get_declared_target, suspension_state, unsuspend_nodes+from products.data_modeling.backend.facade.api import (+ endpoint_link,+ get_declared_target,+ suspension_state,+ unsuspend_nodes,+)from products.data_modeling.backend.facade.models import (DAG,DataModelingJob,@@ -49,8 +54,14 @@ class NodeResumeSerializer(serializers.Serializer):resumed = serializers.BooleanField(help_text="False when the node was not suspended to begin with.")+class NodeEndpointSerializer(serializers.Serializer):+ name = serializers.CharField(help_text="Name of the endpoint this node's materialization backs.")+ version = serializers.IntegerField(help_text="Endpoint version this node's materialization backs.")++class NodeSerializer(serializers.ModelSerializer):suspended = serializers.SerializerMethodField(read_only=True)+ endpoint = serializers.SerializerMethodField(read_only=True)upstream_count = serializers.SerializerMethodField(read_only=True)downstream_count = serializers.SerializerMethodField(read_only=True)last_run_at = serializers.SerializerMethodField(read_only=True)@@ -81,9 +92,11 @@ class NodeSerializer(serializers.ModelSerializer):"user_tag","sync_interval","suspended",+ "endpoint",]read_only_fields = ["suspended",+ "endpoint","upstream_count","downstream_count","last_run_at",@@ -104,6 +117,16 @@ class NodeSerializer(serializers.ModelSerializer):def get_suspended(self, node: Node) -> dict[str, Any]:return {engine: NodeSuspensionSerializer(entry).data for engine, entry in suspension_state(node).items()}+ @extend_schema_field(+ NodeEndpointSerializer(+ allow_null=True,+ help_text="The endpoint version this node's materialization backs, or null for nodes that are not endpoints.",+ )+ )+ def get_endpoint(self, node: Node) -> dict[str, Any] | None:+ link = endpoint_link(node.properties)+ return NodeEndpointSerializer(link).data if link else None+def get_upstream_count(self, node: Node) -> int:counts = self.context.get("node_counts")if counts and str(node.id) in counts:diff --git a/products/data_modeling/frontend/ModelNameLink.tsx b/products/data_modeling/frontend/ModelNameLink.tsxindex f74845fcb26d..0096e369f00c 100644--- a/products/data_modeling/frontend/ModelNameLink.tsx+++ b/products/data_modeling/frontend/ModelNameLink.tsx@@ -5,16 +5,16 @@ import { urls } from 'scenes/urls'import { DataModelingNode } from '~/types'-import { endpointModelUrl, parseEndpointModelName } from './endpointModelName'+import { nodeEndpointModel, nodeEndpointUrl } from './endpointModelName'export function ModelNameLink({ node }: { node: DataModelingNode }): JSX.Element {- const endpointModel = node.type === 'endpoint' ? parseEndpointModelName(node.name) : null+ const endpointModel = nodeEndpointModel(node)if (!endpointModel) {return <LemonTableLink to={urls.nodeDetail(node.id)} title={node.name} />}return (<LemonTableLink- to={endpointModelUrl(node.name)}+ to={nodeEndpointUrl(node)}title={<><span className="whitespace-nowrap">{endpointModel.endpointName}</span>diff --git a/products/data_modeling/frontend/endpointModelName.test.ts b/products/data_modeling/frontend/endpointModelName.test.tsindex 3dc119e1cb90..150d3634f09f 100644--- a/products/data_modeling/frontend/endpointModelName.test.ts+++ b/products/data_modeling/frontend/endpointModelName.test.ts@@ -1,13 +1,34 @@-import { parseEndpointModelName } from './endpointModelName'--describe('parseEndpointModelName', () => {- test.each([- ['weekly-active-users_v5', { endpointName: 'weekly-active-users', version: 5 }],- ['usage_v2_daily_v13', { endpointName: 'usage_v2_daily', version: 13 }],- ['plain_view', null],- ['trailing_v', null],- ['_v3', null],- ])('%s', (name, expected) => {- expect(parseEndpointModelName(name)).toEqual(expected)+import { nodeEndpointModel, parseEndpointModelName } from './endpointModelName'++describe('endpointModelName', () => {+ describe('parseEndpointModelName', () => {+ test.each([+ ['weekly-active-users_v5', { endpointName: 'weekly-active-users', version: 5 }],+ ['usage_v2_daily_v13', { endpointName: 'usage_v2_daily', version: 13 }],+ ['plain_view', null],+ ['trailing_v', null],+ ['_v3', null],+ ])('%s', (name, expected) => {+ expect(parseEndpointModelName(name)).toEqual(expected)+ })+ })++ describe('nodeEndpointModel', () => {+ it('prefers the stamped link over the name', () => {+ expect(+ nodeEndpointModel({ type: 'endpoint', name: 'renamed_v9', endpoint: { name: 'signups', version: 2 } })+ ).toEqual({ endpointName: 'signups', version: 2 })+ })++ it('falls back to the name for nodes enabled before the link was stamped', () => {+ expect(nodeEndpointModel({ type: 'endpoint', name: 'signups_v2', endpoint: null })).toEqual({+ endpointName: 'signups',+ version: 2,+ })+ })++ it('ignores non-endpoint nodes whatever their name', () => {+ expect(nodeEndpointModel({ type: 'matview', name: 'signups_v2', endpoint: null })).toBeNull()+ })})})diff --git a/products/data_modeling/frontend/endpointModelName.ts b/products/data_modeling/frontend/endpointModelName.tsindex 4d9218779294..b647c85a9e34 100644--- a/products/data_modeling/frontend/endpointModelName.ts+++ b/products/data_modeling/frontend/endpointModelName.ts@@ -1,12 +1,14 @@import { urls } from 'scenes/urls'+import { DataModelingNode } from '~/types'+export interface EndpointModelName {endpointName: stringversion: number}-// Matches EndpointVersion.saved_query_name. Endpoints depends on data modeling, not the reverse,-// so the name is the only link from a model back to its endpoint that this product can read.+// Matches EndpointVersion.saved_query_name. Nodes enabled since the link was stamped carry it in+// `endpoint`; saved-query rows, schema tables and older nodes still have only the name to go on.const ENDPOINT_MODEL_NAME = /^(.+)_v(\d+)$/export function parseEndpointModelName(name: string): EndpointModelName | null {@@ -18,3 +20,20 @@ export function endpointModelUrl(name: string): string {const parsed = parseEndpointModelName(name)return parsed ? urls.endpoint(parsed.endpointName, parsed.version) : urls.endpoint(name)}++type EndpointNodeLike = Pick<DataModelingNode, 'type' | 'name' | 'endpoint'>++export function nodeEndpointModel(node: EndpointNodeLike): EndpointModelName | null {+ if (node.type !== 'endpoint') {+ return null+ }+ if (node.endpoint) {+ return { endpointName: node.endpoint.name, version: node.endpoint.version }+ }+ return parseEndpointModelName(node.name)+}++export function nodeEndpointUrl(node: EndpointNodeLike): string {+ const model = nodeEndpointModel(node)+ return model ? urls.endpoint(model.endpointName, model.version) : urls.endpoint(node.name)+}diff --git a/products/data_modeling/frontend/generated/api.schemas.ts b/products/data_modeling/frontend/generated/api.schemas.tsindex 8bc764fe82cc..23b009351491 100644--- a/products/data_modeling/frontend/generated/api.schemas.ts+++ b/products/data_modeling/frontend/generated/api.schemas.ts@@ -113,6 +113,13 @@ export interface NodeSuspensionApi {job_id: string}+export interface NodeEndpointApi {+ /** Name of the endpoint this node's materialization backs. */+ name: string+ /** Endpoint version this node's materialization backs. */+ version: number+}+/*** Engines this node is suspended for after repeated materialization failures. Suspended engines are skipped by scheduled DAG runs until the node is resumed.*/@@ -153,6 +160,8 @@ export interface NodeApi {readonly sync_interval: string | null/** Engines this node is suspended for after repeated materialization failures. Suspended engines are skipped by scheduled DAG runs until the node is resumed. */readonly suspended: NodeApiSuspended+ /** The endpoint version this node's materialization backs, or null for nodes that are not endpoints. */+ readonly endpoint: NodeEndpointApi | null}export interface PaginatedNodeListApi {@@ -204,6 +213,8 @@ export interface PatchedNodeApi {readonly sync_interval?: string | null/** Engines this node is suspended for after repeated materialization failures. Suspended engines are skipped by scheduled DAG runs until the node is resumed. */readonly suspended?: PatchedNodeApiSuspended+ /** The endpoint version this node's materialization backs, or null for nodes that are not endpoints. */+ readonly endpoint?: NodeEndpointApi | null}export interface NodeResumeApi {diff --git a/products/data_modeling/frontend/nodeDetail/NodeDetailActions.tsx b/products/data_modeling/frontend/nodeDetail/NodeDetailActions.tsxindex dfddaf0deb59..524663caefc0 100644--- a/products/data_modeling/frontend/nodeDetail/NodeDetailActions.tsx+++ b/products/data_modeling/frontend/nodeDetail/NodeDetailActions.tsx@@ -8,7 +8,7 @@ import { urls } from 'scenes/urls'import { AccessControlLevel, AccessControlResourceType, DataModelingNode, DataWarehouseSavedQuery } from '~/types'-import { endpointModelUrl } from 'products/data_modeling/frontend/endpointModelName'+import { nodeEndpointUrl } from 'products/data_modeling/frontend/endpointModelName'import { MaterializationRunActions } from 'products/data_warehouse/frontend/shared/components/MaterializationRunActions'export function NodeDetailActions({@@ -24,7 +24,7 @@ export function NodeDetailActions({return (<>{node.type === 'endpoint' ? (- <LemonButton type="secondary" size="small" to={endpointModelUrl(node.name)}>+ <LemonButton type="secondary" size="small" to={nodeEndpointUrl(node)}>Open endpoint</LemonButton>) : (diff --git a/products/endpoints/backend/logic/materialization.py b/products/endpoints/backend/logic/materialization.pyindex 3dd1d31dcc1c..d480411668dd 100644--- a/products/endpoints/backend/logic/materialization.py+++ b/products/endpoints/backend/logic/materialization.py@@ -34,6 +34,7 @@ from products.data_modeling.backend.facade.api import (delete_node_from_dag,is_materialization_fresh,latest_saved_query_materialization_job,+ link_endpoint_nodes,saved_query_materialized_at,sync_saved_query_to_dag,)@@ -250,6 +251,12 @@ class EndpointMaterializationService:sync_error: Exception | None = Nonetry:sync_saved_query_to_dag(saved_query)+ link_endpoint_nodes(+ team_id=saved_query.team_id,+ saved_query_id=saved_query.id,+ endpoint_name=endpoint.name,+ version=version.version,+ )except Exception as e:sync_error = elogger.exception(diff --git a/products/endpoints/backend/tests/test_endpoint_materialization.py b/products/endpoints/backend/tests/test_endpoint_materialization.pyindex 06843f14626a..184f93944034 100644--- a/products/endpoints/backend/tests/test_endpoint_materialization.py+++ b/products/endpoints/backend/tests/test_endpoint_materialization.py@@ -1631,7 +1631,11 @@ class TestEndpointMaterialization(ClickhouseTestMixin, APIBaseTest):assert version.saved_query is not Nonenode = Node.objects.filter(team=self.team, saved_query=version.saved_query).first()- self.assertIsNotNone(node)+ assert node is not None++ node_response = self.client.get(f"/api/environments/{self.team.id}/data_modeling_nodes/{node.id}/")+ self.assertEqual(node_response.status_code, status.HTTP_200_OK, node_response.json())+ self.assertEqual(node_response.json()["endpoint"], {"name": endpoint.name, "version": version.version})def test_disable_materialization_removes_dag_node(self):endpoint = create_endpoint_with_version(diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 10782f8c4a3e..dcbc15befdcb 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -55125,6 +55125,13 @@ export namespace Schemas {Endpoint: 'endpoint',} as const;+ export interface NodeEndpoint {+ /** Name of the endpoint this node's materialization backs. */+ name: string;+ /** Endpoint version this node's materialization backs. */+ version: number;+ }+export interface Node {readonly id: string;/** @maxLength 2048 */@@ -55160,6 +55167,8 @@ export namespace Schemas {readonly sync_interval: string | null;/** Engines this node is suspended for after repeated materialization failures. Suspended engines are skipped by scheduled DAG runs until the node is resumed. */readonly suspended: NodeSuspended;+ /** The endpoint version this node's materialization backs, or null for nodes that are not endpoints. */+ readonly endpoint: NodeEndpoint | null;}export interface NodeResume {@@ -68727,6 +68736,8 @@ export namespace Schemas {readonly sync_interval?: string | null;/** Engines this node is suspended for after repeated materialization failures. Suspended engines are skipped by scheduled DAG runs until the node is resumed. */readonly suspended?: PatchedNodeSuspended;+ /** The endpoint version this node's materialization backs, or null for nodes that are not endpoints. */+ readonly endpoint?: NodeEndpoint | null;}/**