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(nav): Flag dead projects in project switcher (#76967)

Michael Matloka01fa042dbad9
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index c5af2e2d888c..4eed29a6ceeb 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -24,6 +24,10 @@ snapshots:
hash: v1.k794b7964.ddbb5d27187cb1eb9341734e0b780c762cdfbc09aae81833c970369bd7ad4f32.3HNFMfb4Lflcg3uKD1-KNl09d3leMhmfuhR2WVLjLRE
components-account-project-switcher--no-pending-invite--light:
hash: v1.k794b7964.3f8d66ba04469cdf3e92d78483c58125e84531888eedde628469fde5e9e39a08.MhOzPyXhl7CeOLA5Em19cktkdgffO_BL7CojWkngtMQ
+ components-account-project-switcher--with-data-freshness--dark:
+ hash: v1.k794b7964.33311041a0feedba12322f5c99b05b91db51c7f26793b837fce7c0666c5ef6f5.EPYhVoP42oDcDI9m3qloUEuvND0yjchkisUylND2Y-s
+ components-account-project-switcher--with-data-freshness--light:
+ hash: v1.k794b7964.825e1ea3745d1f526c46a4d7b365778ce2d3307933461503fca588f68916a3a9.6Bpu71WRfMaGy8N4X06ixaXTIYkj-4jg44eVXhgWkCw
components-account-project-switcher--with-pending-invite--dark:
hash: v1.k794b7964.b0c1c0b0b8d1a0c77cd873a1cc0b391924cd64ff7de46b1b4d309a50d98eca8a.ddWvJC0f1_fBpYhfDKtUrKeuZSrY5xR8ViHWVdiIfqk
components-account-project-switcher--with-pending-invite--light:
diff --git a/frontend/src/lib/components/Account/ProjectFreshnessIndicator.tsx b/frontend/src/lib/components/Account/ProjectFreshnessIndicator.tsx
new file mode 100644
index 000000000000..6ca1318e78ae
--- /dev/null
+++ b/frontend/src/lib/components/Account/ProjectFreshnessIndicator.tsx
@@ -0,0 +1,106 @@
+import { useValues } from 'kea'
+
+import { dayjs } from 'lib/dayjs'
+import { Tooltip } from 'lib/lemon-ui/Tooltip'
+import { cn } from 'lib/utils/css-classes'
+import { capitalizeFirstLetter } from 'lib/utils/strings'
+import { availableOnboardingProducts, toSentenceCase } from 'scenes/onboarding/shared/utils'
+
+import type { OnboardingProduct } from '~/types'
+
+import type { DataFreshnessSourceApi } from 'products/platform_features/frontend/generated/api.schemas'
+
+import { projectDataFreshnessLogic } from './projectDataFreshnessLogic'
+
+/**
+ * `data_source` is a `ProductKey`, so onboarding's product catalog is the maintained name for
+ * it and a rename lands here for free. It's Title Case there, hence `toSentenceCase`, which
+ * also keeps short acronyms intact ("AI observability", not "Ai observability").
+ *
+ * Products the catalog doesn't list fall back to humanizing the key, which is right for the
+ * ones whose name is just the key ("Tracing").
+ */
+function dataSourceLabel(source: string): string {
+ const catalogued = (availableOnboardingProducts as Partial<Record<string, OnboardingProduct>>)[source]
+ return catalogued ? toSentenceCase(catalogued.name) : capitalizeFirstLetter(source.replace(/_/g, ' '))
+}
+
+function SourceBreakdown({
+ sources,
+ quietAfterDays,
+}: {
+ sources: DataFreshnessSourceApi[]
+ quietAfterDays: number
+}): JSX.Element | null {
+ if (!sources.length) {
+ return null
+ }
+ return (
+ <div className="flex flex-col gap-0.5 mt-1">
+ {sources.map((source) => {
+ const isStale = dayjs().diff(dayjs(source.last_data_at), 'day') >= quietAfterDays
+ return (
+ <div key={source.data_source} className="flex items-center justify-between gap-4">
+ <span>{dataSourceLabel(source.data_source)}</span>
+ <span className={cn('shrink-0', isStale && 'text-tertiary')}>
+ {dayjs(source.last_data_at).fromNow()}
+ </span>
+ </div>
+ )
+ })}
+ </div>
+ )
+}
+
+/**
+ * A warning on projects that have stopped receiving data, and nothing at all on the ones that
+ * haven't. The label says what the duration measures rather than leaving a bare `12d` for the
+ * reader to interpret, because there is no column header in a menu to explain it.
+ *
+ * A project that has never received anything is stated plainly rather than warned about: a
+ * project created a minute ago legitimately has no data, and amber on it would be wrong.
+ */
+export function ProjectFreshnessIndicator({ teamId }: { teamId: number }): JSX.Element | null {
+ const { dataFreshness, freshnessByTeamId } = useValues(projectDataFreshnessLogic)
+
+ const freshness = freshnessByTeamId[teamId]
+ if (!dataFreshness || !freshness || freshness.freshness === 'live') {
+ return null
+ }
+
+ let label: string
+ let headline: string
+
+ if (freshness.freshness === 'never') {
+ label = 'No data yet'
+ headline = 'This project has never received any data.'
+ } else if (!freshness.last_data_at) {
+ // Every probe is bounded to the lookback window, so this is as far back as we can see.
+ label = `No data for ${dataFreshness.lookback_days}d+`
+ headline = `No data of any kind has reached this project in over ${dataFreshness.lookback_days} days.`
+ } else {
+ label = `No data for ${dayjs().diff(dayjs(freshness.last_data_at), 'day')}d`
+ headline = `No data of any kind has reached this project since ${dayjs(freshness.last_data_at).fromNow()}.`
+ }
+
+ return (
+ <Tooltip
+ placement="right"
+ title={
+ <div className="max-w-xs">
+ <span>{headline}</span>
+ <SourceBreakdown sources={freshness.sources} quietAfterDays={dataFreshness.quiet_after_days} />
+ </div>
+ }
+ >
+ <span
+ className={cn(
+ 'text-xxs shrink-0 ml-1 whitespace-nowrap',
+ freshness.freshness === 'never' ? 'text-tertiary' : 'text-warning'
+ )}
+ >
+ {label}
+ </span>
+ </Tooltip>
+ )
+}
diff --git a/frontend/src/lib/components/Account/ProjectMenu.tsx b/frontend/src/lib/components/Account/ProjectMenu.tsx
index c78de397ac08..4e31700d28da 100644
--- a/frontend/src/lib/components/Account/ProjectMenu.tsx
+++ b/frontend/src/lib/components/Account/ProjectMenu.tsx
@@ -17,9 +17,9 @@ import { TeamBasicType } from '~/types'
import { pendingInvitesLogic } from './pendingInvitesLogic'
import { ProjectCombobox } from './ProjectCombobox'
-export function ProjectName({ team }: { team: TeamBasicType }): JSX.Element {
+export function ProjectName({ team, className }: { team: TeamBasicType; className?: string }): JSX.Element {
return (
- <div className="flex items-center max-w-full">
+ <div className={cn('flex items-center max-w-full', className)}>
<span className="truncate">{team.name}</span>
{team.is_demo ? <LemonSnack className="ml-2 text-xs shrink-0">Demo</LemonSnack> : null}
</div>
diff --git a/frontend/src/lib/components/Account/ProjectSwitcher.stories.tsx b/frontend/src/lib/components/Account/ProjectSwitcher.stories.tsx
index bc5b3ff61521..de82ae88c739 100644
--- a/frontend/src/lib/components/Account/ProjectSwitcher.stories.tsx
+++ b/frontend/src/lib/components/Account/ProjectSwitcher.stories.tsx
@@ -2,11 +2,13 @@ import { MOCK_DEFAULT_ORGANIZATION, MOCK_DEFAULT_TEAM, MOCK_DEFAULT_USER } from
import type { Meta, StoryObj } from '@storybook/react'
+import { dayjs } from 'lib/dayjs'
+
import { useStorybookMocks } from '~/mocks/browser'
import { ProjectSwitcher } from './ProjectSwitcher'
-type StoryProps = { hasPendingInvite: boolean }
+type StoryProps = { hasPendingInvite: boolean; hasDataFreshness?: boolean }
const PENDING_INVITE = {
id: '018f0000-0000-0000-0000-000000000001',
@@ -16,25 +18,89 @@ const PENDING_INVITE = {
created_at: '2026-04-17T12:00:00Z',
}
+// The case this feature exists for: a pile of similarly named leftovers around one product,
+// where only one is real and the names alone can't tell you which.
+const FRESHNESS_TEAMS = [
+ { ...MOCK_DEFAULT_TEAM, id: 1001, project_id: 1001, name: 'MockHog staging' },
+ { ...MOCK_DEFAULT_TEAM, id: 1002, project_id: 1002, name: 'MockHog test' },
+ { ...MOCK_DEFAULT_TEAM, id: 1003, project_id: 1003, name: 'MockHog test 2' },
+ { ...MOCK_DEFAULT_TEAM, id: 1004, project_id: 1004, name: 'MockHog dev sandbox' },
+ { ...MOCK_DEFAULT_TEAM, id: 1005, project_id: 1005, name: 'MockHog EU' },
+ { ...MOCK_DEFAULT_TEAM, id: 1006, project_id: 1006, name: 'MockHog old app' },
+]
+
+const LOOKBACK_DAYS = 30
+
+// Relative to now so the rendered durations stay stable as real time passes.
+const daysAgo = (days: number): string => dayjs().subtract(days, 'day').toISOString()
+
+/**
+ * `days` is capped at the lookback window on purpose: every probe is bounded to it, so the API
+ * cannot report a `last_data_at` older than that. Anything further back arrives as null, which
+ * is what `null` means here.
+ */
+const project = (
+ teamId: number,
+ freshness: string,
+ days: number | null,
+ sources: [string, number][] = []
+): Record<string, unknown> => ({
+ team_id: teamId,
+ freshness,
+ last_data_at: days === null ? null : daysAgo(days),
+ sources: sources.map(([data_source, sourceDays]) => ({ data_source, last_data_at: daysAgo(sourceDays) })),
+})
+
+const DATA_FRESHNESS = {
+ lookback_days: LOOKBACK_DAYS,
+ quiet_after_days: 7,
+ results: [
+ project(MOCK_DEFAULT_TEAM.id, 'live', 0, [
+ ['product_analytics', 0],
+ ['session_replay', 0],
+ ]),
+ project(1001, 'stale', 12, [['product_analytics', 12]]),
+ // Last saw data before the lookback window, so all we can say is "over 30 days".
+ project(1002, 'stale', null),
+ project(1003, 'never', null),
+ project(1004, 'stale', null),
+ // Still in use, just not the project you're currently in.
+ project(1005, 'live', 0, [
+ ['product_analytics', 0],
+ ['logs', 1],
+ ]),
+ project(1006, 'stale', 26, [['session_replay', 26]]),
+ ],
+}
+
const meta: Meta<(props: StoryProps) => JSX.Element> = {
title: 'Components/Account/Project Switcher',
parameters: {
layout: 'centered',
viewMode: 'story',
},
- render: ({ hasPendingInvite }: StoryProps) => {
+ render: ({ hasPendingInvite, hasDataFreshness }: StoryProps) => {
+ const organization = hasDataFreshness
+ ? { ...MOCK_DEFAULT_ORGANIZATION, teams: [MOCK_DEFAULT_TEAM, ...FRESHNESS_TEAMS] }
+ : MOCK_DEFAULT_ORGANIZATION
+
useStorybookMocks({
get: {
'/api/users/@me/': () => [
200,
{
...MOCK_DEFAULT_USER,
- organization: MOCK_DEFAULT_ORGANIZATION,
+ organization,
pending_invites: hasPendingInvite ? [PENDING_INVITE] : [],
},
],
+ '/api/organizations/@current/': () => [200, organization],
'/api/environments/@current/': () => [200, MOCK_DEFAULT_TEAM],
'/api/projects/@current/': () => [200, MOCK_DEFAULT_TEAM],
+ [`/api/organizations/${MOCK_DEFAULT_ORGANIZATION.id}/teams/data_freshness/`]: () => [
+ 200,
+ DATA_FRESHNESS,
+ ],
},
})
@@ -56,3 +122,7 @@ export const NoPendingInvite: Story = {
export const WithPendingInvite: Story = {
args: { hasPendingInvite: true },
}
+
+export const WithDataFreshness: Story = {
+ args: { hasPendingInvite: false, hasDataFreshness: true },
+}
diff --git a/frontend/src/lib/components/Account/ProjectSwitcher.tsx b/frontend/src/lib/components/Account/ProjectSwitcher.tsx
index e8f0039b1474..ce88fb62800d 100644
--- a/frontend/src/lib/components/Account/ProjectSwitcher.tsx
+++ b/frontend/src/lib/components/Account/ProjectSwitcher.tsx
@@ -22,6 +22,7 @@ import { AvailableFeature, TeamBasicType } from '~/types'
import { ScrollableShadows } from '../ScrollableShadows/ScrollableShadows'
import { newAccountMenuLogic } from './newAccountMenuLogic'
import { pendingInvitesLogic, PendingInviteForCurrentUser } from './pendingInvitesLogic'
+import { ProjectFreshnessIndicator } from './ProjectFreshnessIndicator'
import { ProjectName } from './ProjectMenu'
interface ProjectListItem {
@@ -255,7 +256,8 @@ export function ProjectSwitcher({ dialog = true }: { dialog?: boolean }): JSX.El
render={(props) => (
<ButtonPrimitive {...props} menuItem active className="flex-1" truncate>
<IconCheck className="text-tertiary" />
- <ProjectName team={item.team} />
+ <ProjectName team={item.team} className="flex-1 min-w-0" />
+ <ProjectFreshnessIndicator teamId={item.team.id} />
</ButtonPrimitive>
)}
/>
@@ -282,7 +284,8 @@ export function ProjectSwitcher({ dialog = true }: { dialog?: boolean }): JSX.El
hasSideActionRight
>
<IconBlank />
- <ProjectName team={item.team} />
+ <ProjectName team={item.team} className="flex-1 min-w-0" />
+ <ProjectFreshnessIndicator teamId={item.team.id} />
</ButtonPrimitive>
)}
/>
diff --git a/frontend/src/lib/components/Account/projectDataFreshnessLogic.ts b/frontend/src/lib/components/Account/projectDataFreshnessLogic.ts
new file mode 100644
index 000000000000..54f0b078f140
--- /dev/null
+++ b/frontend/src/lib/components/Account/projectDataFreshnessLogic.ts
@@ -0,0 +1,90 @@
+import { MakeLogicType, afterMount, connect, kea, listeners, path, selectors } from 'kea'
+import { loaders } from 'kea-loaders'
+
+import { organizationLogic } from 'scenes/organizationLogic'
+
+import type { OrganizationType } from '~/types'
+
+import { teamsDataFreshnessRetrieve } from 'products/platform_features/frontend/generated/api'
+import type {
+ DataFreshnessProjectApi,
+ OrganizationDataFreshnessApi,
+} from 'products/platform_features/frontend/generated/api.schemas'
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface projectDataFreshnessLogicValues {
+ currentOrganization: OrganizationType | null // organizationLogic
+ dataFreshness: OrganizationDataFreshnessApi | null
+ dataFreshnessLoading: boolean
+ freshnessByTeamId: Record<number, DataFreshnessProjectApi>
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface projectDataFreshnessLogicActions {
+ loadDataFreshness: () => any
+ loadDataFreshnessFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadDataFreshnessSuccess: (
+ dataFreshness: OrganizationDataFreshnessApi,
+ payload?: any
+ ) => {
+ dataFreshness: OrganizationDataFreshnessApi
+ payload?: any
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface projectDataFreshnessLogicMeta {
+ __keaTypeGenInternalSelectorTypes: {
+ freshnessByTeamId: (
+ dataFreshness: OrganizationDataFreshnessApi | null
+ ) => Record<number, DataFreshnessProjectApi>
+ }
+}
+
+export type projectDataFreshnessLogicType = MakeLogicType<
+ projectDataFreshnessLogicValues,
+ projectDataFreshnessLogicActions,
+ Record<string, any>,
+ projectDataFreshnessLogicMeta
+>
+
+export const projectDataFreshnessLogic = kea<projectDataFreshnessLogicType>([
+ path(['lib', 'components', 'Account', 'projectDataFreshnessLogic']),
+ connect(() => ({
+ values: [organizationLogic, ['currentOrganization']],
+ })),
+ loaders(({ values }) => ({
+ dataFreshness: [
+ null as OrganizationDataFreshnessApi | null,
+ {
+ loadDataFreshness: async (): Promise<OrganizationDataFreshnessApi> =>
+ await teamsDataFreshnessRetrieve(values.currentOrganization!.id),
+ },
+ ],
+ })),
+ selectors({
+ freshnessByTeamId: [
+ (s) => [s.dataFreshness],
+ (dataFreshness: OrganizationDataFreshnessApi | null): Record<number, DataFreshnessProjectApi> =>
+ Object.fromEntries((dataFreshness?.results ?? []).map((result) => [result.team_id, result])),
+ ],
+ }),
+ listeners(({ actions }) => ({
+ // The switcher can mount before the organization has loaded, and the endpoint is
+ // organization-scoped, so the load is gated on whichever of the two lands last.
+ [organizationLogic.actionTypes.loadCurrentOrganizationSuccess]: () => {
+ actions.loadDataFreshness()
+ },
+ })),
+ afterMount(({ actions, values }) => {
+ if (values.currentOrganization) {
+ actions.loadDataFreshness()
+ }
+ }),
+])
diff --git a/posthog/api/documentation.py b/posthog/api/documentation.py
index 032a5058a688..ceefec652866 100644
--- a/posthog/api/documentation.py
+++ b/posthog/api/documentation.py
@@ -22,6 +22,7 @@ from rest_framework.exceptions import PermissionDenied
from posthog.models.entity import MathType
from posthog.models.property import OperatorType, PropertyType
from posthog.permissions import APIScopePermission
+from posthog.products import is_product_module
from products.feature_flags.backend.types import PropertyFilterType
@@ -699,7 +700,7 @@ _PROJECT_ENVS_FINAL_RE = re.compile(r"^/api/projects/[^/]+/environments/")
def _get_product_from_module(module: str) -> str | None:
"""Extract product folder name from module path like 'products.batch_exports.backend.api'."""
- if module.startswith("products."):
+ if is_product_module(module):
parts = module.split(".")
if len(parts) >= 2:
return parts[1]
diff --git a/posthog/api/organization.py b/posthog/api/organization.py
index d3f04fbdf55d..6b1ea1f9a6d6 100644
--- a/posthog/api/organization.py
+++ b/posthog/api/organization.py
@@ -24,6 +24,7 @@ from posthog.caching.organization_serializer_cache import (
)
from posthog.cloud_utils import get_cached_instance_license, is_cloud
from posthog.constants import INTERNAL_BOT_EMAIL_SUFFIX, AvailableFeature
+from posthog.data_freshness import LOOKBACK_DAYS, QUIET_AFTER_DAYS, Freshness, get_organization_data_freshness
from posthog.event_usage import (
groups,
report_organization_action,
@@ -49,7 +50,7 @@ from posthog.permissions import (
from posthog.rate_limit import PostHogAIAccessRequestIPThrottle, PostHogAIAccessRequestUserThrottle
from posthog.rbac.migrations.rbac_feature_flag_migration import rbac_feature_flag_role_access_migration
from posthog.rbac.migrations.rbac_team_migration import rbac_team_access_control_migration
-from posthog.rbac.user_access_control import UserAccessControlSerializerMixin
+from posthog.rbac.user_access_control import UserAccessControl, UserAccessControlSerializerMixin, visible_teams_for_user
from posthog.tasks.email import send_posthog_ai_access_request
from posthog.user_permissions import UserPermissions, UserPermissionsSerializerMixin
from posthog.utils import get_safe_cache, safe_cache_set
@@ -256,16 +257,9 @@ class OrganizationSerializer(
return _cached_per_user_org("teams", user_id, str(instance.id), lambda: self._fetch_visible_teams(instance))
def _fetch_visible_teams(self, instance: Organization) -> list[dict[str, Any]]:
- # Support new access control system
- visible_teams = (
- self.user_access_control.filter_queryset_by_access_level(instance.teams.all(), include_all_if_admin=True)
- if self.user_access_control
- else instance.teams.none()
- )
- # Support old access control system
- visible_teams = visible_teams.filter(id__in=self.user_permissions.team_ids_visible_for_user).select_related(
- "project"
- )
+ visible_teams = visible_teams_for_user(
+ instance, self.user_access_control, self.user_permissions
+ ).select_related("project")
return list(TeamBasicSerializer(visible_teams, context=self.context, many=True).data)
@tracer.start_as_current_span("organization_serializer.projects")
@@ -409,6 +403,44 @@ class OrganizationAIAccessRequestResponseSerializer(serializers.Serializer):
)
+class DataFreshnessSourceSerializer(serializers.Serializer):
+ data_source = serializers.CharField(
+ help_text=(
+ "The product this timestamp is about, as a `ProductKey` (e.g. `session_replay`, `logs`). "
+ "Not an enum: products declare their own data sources, so the set grows without an API change."
+ )
+ )
+ last_data_at = serializers.DateTimeField(
+ help_text="When data of this kind last reached the project. Only sources with data inside the lookback window are listed."
+ )
+
+
+class DataFreshnessProjectSerializer(serializers.Serializer):
+ team_id = serializers.IntegerField(help_text="ID of the project this freshness verdict is for.")
+ freshness = serializers.ChoiceField(
+ choices=[(freshness.value, freshness.value) for freshness in Freshness],
+ help_text=(
+ "`live` if data of any kind arrived within `quiet_after_days`, `stale` if none did, "
+ "`never` if the project has never ingested anything at all."
+ ),
+ )
+ last_data_at = serializers.DateTimeField(
+ allow_null=True,
+ help_text="When data of any kind last reached the project, or null if nothing arrived within the lookback window.",
+ )
+ sources = DataFreshnessSourceSerializer(many=True, help_text="Per-source breakdown, most recently active first.")
+
+
+class OrganizationDataFreshnessSerializer(serializers.Serializer):
+ results = DataFreshnessProjectSerializer(many=True, help_text="One entry per project the requesting user can see.")
+ lookback_days = serializers.IntegerField(
+ help_text="How many days back the check looks. Data older than this is not visible to the check."
+ )
+ quiet_after_days = serializers.IntegerField(
+ help_text="How many days without data make a project or source count as quiet."
+ )
+
+
@extend_schema(extensions={"x-product": "platform_features"})
class OrganizationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
scope_object = "organization"
@@ -645,3 +677,27 @@ class OrganizationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
requesting_user_id=user.id,
)
return Response({"success": True})
+
+ @extend_schema(request=None, responses={200: OrganizationDataFreshnessSerializer})
+ @action(detail=True, methods=["GET"], url_path="teams/data_freshness", pagination_class=None)
+ def data_freshness(self, request: Request, **kwargs) -> Response:
+ """When each project in the organization last received data, broken down by kind of data."""
+ organization = self.organization
+ user = cast(User, request.user)
+ # `self.user_access_control` is scoped to the user's current organization, which on this route isn't
+ # necessarily the one being requested - so build one for the organization actually in the URL
+ visible_teams = visible_teams_for_user(
+ organization,
+ UserAccessControl(user=user, organization_id=str(organization.id)),
+ UserPermissions(user=user),
+ ).only("id", "project_id", "ingested_event")
+ results = get_organization_data_freshness(str(organization.id), list(visible_teams))
+ return Response(
+ OrganizationDataFreshnessSerializer(
+ {
+ "results": results,
+ "lookback_days": LOOKBACK_DAYS,
+ "quiet_after_days": QUIET_AFTER_DAYS,
+ }
+ ).data
+ )
diff --git a/posthog/api/rest_router.py b/posthog/api/rest_router.py
index 60b6c33a1d95..2a7a8dcc5c95 100644
--- a/posthog/api/rest_router.py
+++ b/posthog/api/rest_router.py
@@ -1,8 +1,3 @@
-import importlib
-import importlib.util
-
-from django.apps import apps
-
from rest_framework import decorators, exceptions
# Preload to work around circular imports in `ee.hogai.{core.agent_modes,chat_agent,tools}`.
@@ -15,6 +10,7 @@ from posthog.api.query_performance_proxy import QueryPerformanceProxyViewSet
from posthog.api.routing import DefaultRouterPlusPlus, RouterRegistry
from posthog.api.sdk_health import SdkHealthViewSet
from posthog.api.wizard import http as wizard
+from posthog.products import load_product_modules
from posthog.settings import EE_AVAILABLE
from ee.api.quota_limits import QuotaLimitsViewSet
@@ -594,14 +590,7 @@ projects_router.register(
# Accepted cost: routes are imported dynamically here, so the core->product import edges
# are not statically visible to import tooling (tach/grimp). Accepted on purpose — it
# removes the hand-maintained product list that duplicated PRODUCTS_APPS.
-for _app_config in apps.get_app_configs():
- if not _app_config.name.startswith("products."):
- continue
- _routes_module = f"{_app_config.name}.routes"
- # find_spec (not try/except ImportError) so a real ImportError inside a routes.py
- # surfaces instead of being silently swallowed as "no routes module".
- if importlib.util.find_spec(_routes_module) is None:
- continue
- _register_routes = getattr(importlib.import_module(_routes_module), "register_routes", None)
+for _routes_module in load_product_modules("routes"):
+ _register_routes = getattr(_routes_module, "register_routes", None)
if callable(_register_routes):
_register_routes(routers)
diff --git a/posthog/api/routing.py b/posthog/api/routing.py
index 47b88eb9d6a5..12dc9db8fd7f 100644
--- a/posthog/api/routing.py
+++ b/posthog/api/routing.py
@@ -37,6 +37,7 @@ from posthog.permissions import (
TeamMemberAccessPermission,
VerifiedDomainEnforcementPermission,
)
+from posthog.products import is_product_module
from posthog.rbac.user_access_control import UserAccessControl
from posthog.scopes import APIScopeObjectOrNotSupported
from posthog.user_permissions import UserPermissions
@@ -84,7 +85,7 @@ class RouterRegistry:
def _reject_product_caller(method: str) -> None:
# frame 0 = here, 1 = the public method, 2 = its caller
caller_module = sys._getframe(2).f_globals.get("__name__", "")
- if caller_module.startswith("products."):
+ if is_product_module(caller_module):
raise RuntimeError(
f"Parent routers are core-owned; {caller_module} must not call RouterRegistry.{method}(). "
"Products nest onto existing parents via routers.projects/organizations/root."
diff --git a/posthog/api/test/test_organization.py b/posthog/api/test/test_organization.py
index dfd737dc77b6..1d5d0f8f5405 100644
--- a/posthog/api/test/test_organization.py
+++ b/posthog/api/test/test_organization.py
@@ -1364,3 +1364,33 @@ class TestOrganizationRequestAIAccessAPI(APIBaseTest):
assert second.status_code == status.HTTP_429_TOO_MANY_REQUESTS, second.content
# Only the first request reached the task.
mock_task.delay.assert_called_once()
+
+
+class TestOrganizationDataFreshnessAPI(APIBaseTest):
+ def setUp(self):
+ super().setUp()
+ cache.clear()
+ self.other_organization = Organization.objects.create(name="Other org")
+ self.other_team = Team.objects.create(organization=self.other_organization, name="Other team")
+ self.user.join(organization=self.other_organization, level=OrganizationMembership.Level.MEMBER)
+ # Joining recomputes available features, so grant access control only once the user is in
+ self.other_organization.available_product_features = [
+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL}
+ ]
+ self.other_organization.save()
+
+ @patch("posthog.api.organization.get_organization_data_freshness")
+ def test_access_control_applies_to_the_requested_organization_not_the_current_one(self, mock_freshness):
+ mock_freshness.return_value = []
+ # Admin here, plain member in the organization actually being requested
+ self.organization_membership.level = OrganizationMembership.Level.ADMIN
+ self.organization_membership.save()
+ AccessControl.objects.create(
+ team=self.other_team, resource="project", resource_id=str(self.other_team.id), access_level="none"
+ )
+
+ response = self.client.get(f"/api/organizations/{self.other_organization.id}/teams/data_freshness")
+
+ assert response.status_code == status.HTTP_200_OK, response.content
+ mock_freshness.assert_called_once()
+ assert [team.id for team in mock_freshness.call_args.args[1]] == []
diff --git a/posthog/api/test/test_routing.py b/posthog/api/test/test_routing.py
index e426c2122605..8cbab7f9a0e2 100644
--- a/posthog/api/test/test_routing.py
+++ b/posthog/api/test/test_routing.py
@@ -7,7 +7,6 @@ from datetime import timedelta
import pytest
from posthog.test.base import APIBaseTest
-from django.apps import apps
from django.test import override_settings
from django.urls import include, path
from django.utils import timezone
@@ -27,6 +26,7 @@ from posthog.models.project import Project
from posthog.models.scoping import get_current_team_id
from posthog.models.team.team import Team
from posthog.permissions import APIScopePermission
+from posthog.products import product_app_names
from products.annotations.backend.api.annotation import AnnotationSerializer
from products.annotations.backend.models.annotation import Annotation
@@ -354,10 +354,8 @@ def test_router_registry_get_unknown_name_lists_known():
def _discover_product_route_modules():
modules = []
- for app_config in apps.get_app_configs():
- if not app_config.name.startswith("products."):
- continue
- module_name = f"{app_config.name}.routes"
+ for app_name in product_app_names():
+ module_name = f"{app_name}.routes"
if importlib.util.find_spec(module_name) is None:
continue
modules.append(importlib.import_module(module_name))
diff --git a/posthog/clickhouse/query_tagging.py b/posthog/clickhouse/query_tagging.py
index 24b798176433..3585cf725eae 100644
--- a/posthog/clickhouse/query_tagging.py
+++ b/posthog/clickhouse/query_tagging.py
@@ -125,6 +125,7 @@ class Feature(StrEnum):
# would be misleading; tagging by endpoint name keeps the signal honest.
EVENTS_VALUES_API = "events_values_api"
USAGE_REPORT = "usage_report"
+ DATA_FRESHNESS = "data_freshness" # "when did this project last receive data" probes
BILLING_ETL = "billing_etl"
QUOTA_LIMITING = "quota_limiting"
MIGRATION = "migration"
diff --git a/posthog/data_freshness.py b/posthog/data_freshness.py
new file mode 100644
index 000000000000..c3320babd24b
--- /dev/null
+++ b/posthog/data_freshness.py
@@ -0,0 +1,317 @@
+"""
+Per-project data freshness: is anything at all still reaching this project?
+
+Products declare what counts as their data in `products/<name>/backend/data_freshness.py`,
+discovered the same way `routes.py` is. This module only runs the shared queries and combines
+the answers.
+
+Runs on an interactive path, so declarations are grouped by datastore rather than by product:
+event-backed products fold into one query, `app_metrics2`-backed ones into a second, and only
+a product neither can answer brings its own probe.
+
+`last_data_at` is `None` for "nothing within `LOOKBACK_DAYS`", not "never" — `Freshness.NEVER`
+is the only claim made about all of time, and it leans on `Team.ingested_event`.
+"""
+
+import hashlib
+from collections.abc import Callable
+from dataclasses import dataclass, field
+from datetime import UTC, datetime, timedelta
+from enum import StrEnum
+from functools import lru_cache, partial
+from typing import Optional
+
+from django.db.models import BigIntegerField, Case, CharField, Max, Value, When
+from django.db.models.functions import Coalesce
+
+import structlog
+
+from posthog.exceptions_capture import capture_exception
+from posthog.models.team.team import Team
+from posthog.models.utils import execute_with_timeout
+from posthog.products import load_product_modules
+from posthog.schema_enums import ProductKey
+from posthog.utils import ensure_utc, get_safe_cache, safe_cache_set
+
+from products.event_definitions.backend.models.event_definition import EventDefinition
+
+logger = structlog.get_logger(__name__)
+
+LOOKBACK_DAYS = 30
+# Shorter than the lookback, so a stale project can still say roughly how long it has been quiet.
+QUIET_AFTER_DAYS = 7
+
+CACHE_TTL_SECONDS = 10 * 60
+# Bump when ProjectFreshness or SourceFreshness change shape: cached values are pickled, so old
+# entries would otherwise unpickle missing a field.
+_CACHE_SCHEMA_VERSION = 1
+
+# Backstops for a pathological org, not a latency budget. Postgres has no server-side
+# statement_timeout here, and the ClickHouse cluster's failure mode is concurrent IO-heavy
+# reads, so bytes are capped harder than time.
+POSTGRES_TIMEOUT_MS = 15_000
+CLICKHOUSE_SETTINGS = {"max_execution_time": 30, "max_bytes_to_read": 10_000_000_000}
+
+
+class Freshness(StrEnum):
+ """The project-level verdict, part of the API contract.
+
+ Three states on purpose: a project still receiving one kind of data is in use even if
+ another kind stopped, so per-source decay doesn't get its own verdict.
+ """
+
+ # Never ingested anything at all. Unstarted, not stale.
+ NEVER = "never"
+ LIVE = "live"
+ STALE = "stale"
+
+
+@dataclass(frozen=True, kw_only=True)
+class ProbeWindow:
+ """The time bounds every probe works within. Keyword-only because all three are datetimes."""
+
+ cutoff: datetime
+ # Data at least this recent makes a project live. Probes may answer this window first.
+ quiet_before: datetime
+ # Clock-skew ceiling, so one future-stamped row can't pin a dead project to "live".
+ horizon: datetime
+
+
+# Returns the last time each team received data, omitting teams with none.
+SourceProbe = Callable[[list[int], ProbeWindow], dict[int, datetime]]
+
+
+@dataclass(frozen=True, kw_only=True)
+class DataSourceSpec:
+ """How one product tells whether a project received its kind of data recently.
+
+ Declare as `DATA_SOURCES` in `products/<name>/backend/data_freshness.py`, picking the
+ cheapest that fits: `event_names`/`event_prefix` and `app_metrics_source` each fold into a
+ shared query, `probe` runs your own. `is_residual` claims every event name nobody else does.
+ """
+
+ product: ProductKey
+ event_names: tuple[str, ...] = ()
+ event_prefix: str = ""
+ app_metrics_source: str = ""
+ probe: Optional[SourceProbe] = None
+ is_residual: bool = False
+
+
+@dataclass(frozen=True, kw_only=True)
+class SourceFreshness:
+ data_source: ProductKey
+ last_data_at: datetime
+
+
+@dataclass(frozen=True, kw_only=True)
+class ProjectFreshness:
+ team_id: int
+ freshness: Freshness
+ last_data_at: Optional[datetime]
+ sources: list[SourceFreshness] = field(default_factory=list)
+
+
+# Probes never emit a null timestamp or a team they weren't given, so `_compute` trusts both.
+ProbeResult = list[tuple[int, ProductKey, datetime]]
+
+
+@lru_cache(maxsize=1)
+def discover_data_sources() -> tuple[DataSourceSpec, ...]:
+ """Collect every product's `DATA_SOURCES`."""
+ specs: list[DataSourceSpec] = []
+ for module in load_product_modules("data_freshness"):
+ specs.extend(getattr(module, "DATA_SOURCES", []))
+ return tuple(specs)
+
+
+def get_organization_data_freshness(organization_id: str, teams: list[Team]) -> list[ProjectFreshness]:
+ """Freshness for every passed team, cached per organization.
+
+ Keyed on the team set too, since access control means two members see different projects,
+ and a visibility change moves a team in or out of that set.
+ """
+ team_ids = sorted(team.id for team in teams)
+ fingerprint = hashlib.sha256(",".join(str(team_id) for team_id in team_ids).encode()).hexdigest()[:16]
+ cache_key = f"org_data_freshness:v{_CACHE_SCHEMA_VERSION}:{organization_id}:{fingerprint}"
+ cached = get_safe_cache(cache_key)
+ if cached is not None:
+ return cached
+
+ result = _compute(teams)
+ safe_cache_set(cache_key, result, CACHE_TTL_SECONDS)
+ return result
+
+
+def _compute(teams: list[Team]) -> list[ProjectFreshness]:
+ if not teams:
+ return []
+
+ now = datetime.now(UTC)
+ quiet_before = now - timedelta(days=QUIET_AFTER_DAYS)
+ window = ProbeWindow(
+ cutoff=now - timedelta(days=LOOKBACK_DAYS),
+ quiet_before=quiet_before,
+ horizon=now + timedelta(days=1),
+ )
+ specs = discover_data_sources()
+
+ degraded = False
+ by_team: dict[int, dict[ProductKey, datetime]] = {team.id: {} for team in teams}
+ for name, probe in _probes(specs, teams, window):
+ try:
+ for team_id, product, last_data_at in probe():
+ previous = by_team[team_id].get(product)
+ if previous is None or last_data_at > previous:
+ by_team[team_id][product] = last_data_at
+ except Exception as e:
+ # One unavailable store must not blank out every other source's verdict.
+ degraded = True
+ logger.warning("data_freshness_probe_failed", probe=name, error=str(e))
+ capture_exception(e)
+
+ return reportable([derive_freshness(team, by_team[team.id], quiet_before) for team in teams], degraded=degraded)
+
+
+def reportable(results: list[ProjectFreshness], *, degraded: bool) -> list[ProjectFreshness]:
+ """Drop verdicts a failed probe could have changed.
+
+ Finding recent data stays true whatever else broke, but finding none is indistinguishable
+ from not having been able to look, so those projects say nothing rather than warn wrongly.
+ """
+ if not degraded:
+ return results
+ return [result for result in results if result.freshness == Freshness.LIVE]
+
+
+def _probes(
+ specs: tuple[DataSourceSpec, ...], teams: list[Team], window: ProbeWindow
+) -> list[tuple[str, Callable[[], ProbeResult]]]:
+ """The two shared queries, plus one per product that brought its own. Isolated separately."""
+ return [
+ ("event_definitions", partial(_probe_event_definitions, specs, teams, window)),
+ ("app_metrics", partial(_probe_app_metrics, specs, teams, window)),
+ *(
+ (spec.product.value, partial(_run_source_probe, spec, teams, window))
+ for spec in specs
+ if spec.probe is not None
+ ),
+ ]
+
+
+def derive_freshness(team: Team, found: dict[ProductKey, datetime], quiet_before: datetime) -> ProjectFreshness:
+ sources = sorted(
+ (SourceFreshness(data_source=product, last_data_at=at) for product, at in found.items()),
+ key=lambda s: s.last_data_at,
+ reverse=True,
+ )
+ last_data_at = sources[0].last_data_at if sources else None
+
+ if last_data_at is None:
+ # The only unbounded signal available, so it's what separates never-started from
+ # data older than the lookback window.
+ freshness = Freshness.STALE if team.ingested_event else Freshness.NEVER
+ elif last_data_at < quiet_before:
+ freshness = Freshness.STALE
+ else:
+ freshness = Freshness.LIVE
+
+ return ProjectFreshness(
+ team_id=team.id,
+ freshness=freshness,
+ last_data_at=last_data_at,
+ sources=sources,
+ )
+
+
+def _probe_event_definitions(specs: tuple[DataSourceSpec, ...], teams: list[Team], window: ProbeWindow) -> ProbeResult:
+ """Every event-backed product, in one query over the event definition catalog.
+
+ `last_seen_at` is maintained by ingestion, so this is far cheaper than a windowed events
+ query. It's project-scoped though, so environments of one project share a verdict here.
+
+ Classifying in SQL rather than per product matters: splitting it would turn the prefix and
+ the residual bucket into full scans of every definition in scope.
+ """
+ scopes: dict[int, list[Team]] = {}
+ for team in teams:
+ scopes.setdefault(team.project_id or team.id, []).append(team)
+
+ # Exact names before prefixes, so a specific claim beats a prefix it sits under.
+ whens = [
+ *(When(name=name, then=Value(spec.product.value)) for spec in specs for name in spec.event_names),
+ *(
+ When(name__startswith=spec.event_prefix, then=Value(spec.product.value))
+ for spec in specs
+ if spec.event_prefix
+ ),
+ ]
+ if not whens:
+ return []
+ residual = next((spec.product.value for spec in specs if spec.is_residual), "")
+
+ queryset = (
+ EventDefinition.objects.annotate(
+ # Mirrors the table's `(coalesce(project_id, team_id), name)` unique index.
+ scope_id=Coalesce("project_id", "team_id", output_field=BigIntegerField()),
+ source=Case(*whens, default=Value(residual), output_field=CharField()),
+ )
+ .filter(scope_id__in=scopes.keys(), last_seen_at__gte=window.cutoff, last_seen_at__lte=window.horizon)
+ .values("scope_id", "source")
+ .annotate(last_seen=Max("last_seen_at"))
+ )
+
+ # Evaluated inside the block: the timeout is transaction-local, so a lazily-built queryset
+ # would escape it.
+ with execute_with_timeout(POSTGRES_TIMEOUT_MS):
+ rows = list(queryset)
+ return [
+ (team.id, ProductKey(row["source"]), row["last_seen"])
+ for row in rows
+ if row["source"] # empty when no product claims the residual
+ for team in scopes.get(row["scope_id"], [])
+ ]
+
+
+def _probe_app_metrics(specs: tuple[DataSourceSpec, ...], teams: list[Team], window: ProbeWindow) -> ProbeResult:
+ """Every `app_metrics2`-backed product, in one query.
+
+ That table is already a per-team, per-product activity ledger sorted on `team_id` first.
+ """
+ products_by_app_source = {spec.app_metrics_source: spec.product for spec in specs if spec.app_metrics_source}
+ if not products_by_app_source:
+ return []
+
+ # Kept off this module's import path, which product declaration modules pull in.
+ from posthog.clickhouse.client import sync_execute # noqa: PLC0415
+ from posthog.clickhouse.query_tagging import Feature, Product, tags_context # noqa: PLC0415
+
+ with tags_context(product=Product.PLATFORM_AND_SUPPORT, feature=Feature.DATA_FRESHNESS):
+ rows = sync_execute(
+ """
+ SELECT team_id, app_source, max(timestamp)
+ FROM app_metrics2
+ WHERE team_id IN %(team_ids)s
+ AND app_source IN %(app_sources)s
+ AND timestamp >= %(cutoff)s
+ AND timestamp <= %(horizon)s
+ GROUP BY team_id, app_source
+ """,
+ {
+ "team_ids": [team.id for team in teams],
+ "app_sources": list(products_by_app_source.keys()),
+ "cutoff": window.cutoff,
+ "horizon": window.horizon,
+ },
+ settings=CLICKHOUSE_SETTINGS,
+ )
+ return [
+ (team_id, products_by_app_source[app_source], ensure_utc(last_data_at))
+ for team_id, app_source, last_data_at in rows
+ ]
+
+
+def _run_source_probe(spec: DataSourceSpec, teams: list[Team], window: ProbeWindow) -> ProbeResult:
+ assert spec.probe is not None
+ found = spec.probe([team.id for team in teams], window)
+ return [(team_id, spec.product, last_data_at) for team_id, last_data_at in found.items()]
diff --git a/posthog/management/migration_analysis/policies.py b/posthog/management/migration_analysis/policies.py
index 0b8caae69be4..73d58a8a5051 100644
--- a/posthog/management/migration_analysis/policies.py
+++ b/posthog/management/migration_analysis/policies.py
@@ -12,6 +12,7 @@ from django.conf import settings
from django.db import models
from posthog.management.migration_analysis.operations import is_unmanaged_model
+from posthog.products import is_product_module
# Apps owned by PostHog where policies are enforced
POSTHOG_OWNED_APPS = ["posthog", "ee"]
@@ -31,7 +32,7 @@ def is_posthog_app(app_label: str, migration=None) -> bool:
# Check the migration's module path to detect product apps
if migration is not None:
module = getattr(migration, "__module__", "")
- if module.startswith("products."):
+ if is_product_module(module):
return True
return False
diff --git a/posthog/owners.yaml b/posthog/owners.yaml
index d270c9b28259..3fbbb498d3d1 100644
--- a/posthog/owners.yaml
+++ b/posthog/owners.yaml
@@ -7,6 +7,8 @@ rules:
owners: team-workflows
- match: '/clickhouse/hcl/'
owners: clickhouse
+ - match: '/data_freshness.py'
+ owners: team-platform-features
- match: '/email.py'
owners: team-platform-features
- match: '/heatmaps/'
diff --git a/posthog/products.py b/posthog/products.py
index 3e1098fc52e4..2810acef8442 100644
--- a/posthog/products.py
+++ b/posthog/products.py
@@ -1,12 +1,48 @@
import json
+import importlib
+import importlib.util
from collections import defaultdict
+from collections.abc import Iterator
from pathlib import Path
+from types import ModuleType
from typing import TYPE_CHECKING, Optional
+from django.apps import apps
from django.conf import settings
from posthog.schema_enums import ProductItemCategory, ProductKey
+# Products are Django apps under `products/`, installed as `products.<name>.backend`.
+PRODUCT_MODULE_PREFIX = "products."
+
+
+def is_product_module(module_name: str) -> bool:
+ """Whether a module path lives inside a product, e.g. `products.logs.backend.api`."""
+ return module_name.startswith(PRODUCT_MODULE_PREFIX)
+
+
+def product_app_names() -> list[str]:
+ """Names of the installed product apps, e.g. `products.logs.backend`."""
+ return [app_config.name for app_config in apps.get_app_configs() if is_product_module(app_config.name)]
+
+
+def load_product_modules(submodule: str) -> Iterator[ModuleType]:
+ """Import `<product app>.<submodule>` for every product that has one.
+
+ How core picks up per-product declarations (`routes`, `data_freshness`, ...) without a
+ hand-maintained list. `find_spec` rather than try/except so a real ImportError inside a
+ product's module surfaces instead of reading as "this product doesn't have one".
+
+ Products are imported dynamically here, so the core->product edges are invisible to import
+ tooling (tach/grimp). Accepted on purpose, as the alternative duplicates PRODUCTS_APPS.
+ """
+ for app_name in product_app_names():
+ module_name = f"{app_name}.{submodule}"
+ if importlib.util.find_spec(module_name) is None:
+ continue
+ yield importlib.import_module(module_name)
+
+
# This module loads at django.setup() via the file-system product list; posthog.schema
# (the pydantic models) is runtime-imported only when products.json is actually loaded.
if TYPE_CHECKING:
diff --git a/posthog/rbac/user_access_control.py b/posthog/rbac/user_access_control.py
index 50f66ccfa88d..ea2469bc6bb6 100644
--- a/posthog/rbac/user_access_control.py
+++ b/posthog/rbac/user_access_control.py
@@ -19,6 +19,7 @@ from posthog.settings import EE_AVAILABLE
if TYPE_CHECKING:
from posthog.models.file_system.file_system import FileSystem
+ from posthog.user_permissions import UserPermissions
from ee.models import AccessControl
@@ -1661,3 +1662,21 @@ class UserAccessControlSerializerMixin(serializers.Serializer):
)
return attrs
+
+
+def visible_teams_for_user(
+ organization: Organization,
+ user_access_control: Optional["UserAccessControl"],
+ user_permissions: "UserPermissions",
+) -> QuerySet[Team]:
+ """Teams in `organization` the user can see.
+
+ Both access control systems apply, and filtering on only one of them leaks projects the
+ other hides. Callers that need visible teams should use this rather than reimplementing it.
+ """
+ teams = (
+ user_access_control.filter_queryset_by_access_level(organization.teams.all(), include_all_if_admin=True)
+ if user_access_control
+ else organization.teams.none()
+ )
+ return teams.filter(id__in=user_permissions.team_ids_visible_for_user)
diff --git a/posthog/test/test_data_freshness.py b/posthog/test/test_data_freshness.py
new file mode 100644
index 000000000000..e75b23b78165
--- /dev/null
+++ b/posthog/test/test_data_freshness.py
@@ -0,0 +1,92 @@
+from datetime import UTC, datetime, timedelta
+
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+
+from posthog.data_freshness import Freshness, ProjectFreshness, derive_freshness, reportable
+from posthog.models.team.team import Team
+from posthog.schema_enums import ProductKey
+
+NOW = datetime(2026, 8, 3, 12, 0, tzinfo=UTC)
+QUIET_BEFORE = NOW - timedelta(days=7)
+
+
+def _ago(days: float) -> datetime:
+ return NOW - timedelta(days=days)
+
+
+class TestDeriveFreshness(SimpleTestCase):
+ @parameterized.expand(
+ [
+ (
+ "everything still arriving",
+ True,
+ {ProductKey.PRODUCT_ANALYTICS: _ago(0.1), ProductKey.SESSION_REPLAY: _ago(2)},
+ Freshness.LIVE,
+ ),
+ (
+ "one source silent while another keeps arriving is still in use",
+ True,
+ {ProductKey.PRODUCT_ANALYTICS: _ago(0.1), ProductKey.SESSION_REPLAY: _ago(11)},
+ Freshness.LIVE,
+ ),
+ (
+ "every source silent",
+ True,
+ {ProductKey.PRODUCT_ANALYTICS: _ago(9), ProductKey.LOGS: _ago(20)},
+ Freshness.STALE,
+ ),
+ (
+ "nothing in the window but the project has ingested before",
+ True,
+ {},
+ Freshness.STALE,
+ ),
+ (
+ "nothing in the window and the project never ingested",
+ False,
+ {},
+ Freshness.NEVER,
+ ),
+ ]
+ )
+ def test_verdict(
+ self,
+ _name: str,
+ ingested_event: bool,
+ found: dict[ProductKey, datetime],
+ expected: Freshness,
+ ) -> None:
+ team = Team(id=1, ingested_event=ingested_event)
+
+ result = derive_freshness(team, found, QUIET_BEFORE)
+
+ self.assertEqual(result.freshness, expected)
+
+ def test_reports_the_most_recent_source_first(self) -> None:
+ team = Team(id=1, ingested_event=True)
+
+ result = derive_freshness(
+ team,
+ {ProductKey.LOGS: _ago(5), ProductKey.SESSION_REPLAY: _ago(1), ProductKey.PRODUCT_ANALYTICS: _ago(3)},
+ QUIET_BEFORE,
+ )
+
+ self.assertEqual(
+ [source.data_source for source in result.sources],
+ [ProductKey.SESSION_REPLAY, ProductKey.PRODUCT_ANALYTICS, ProductKey.LOGS],
+ )
+ self.assertEqual(result.last_data_at, _ago(1))
+
+ def test_a_failed_probe_only_keeps_live_verdicts(self) -> None:
+ # A probe that failed can't be told apart from a product with no data, so a stale or
+ # never verdict might just be the missing probe. Warning on those would be wrong.
+ results = [
+ ProjectFreshness(team_id=1, freshness=Freshness.LIVE, last_data_at=_ago(0), sources=[]),
+ ProjectFreshness(team_id=2, freshness=Freshness.STALE, last_data_at=_ago(20), sources=[]),
+ ProjectFreshness(team_id=3, freshness=Freshness.NEVER, last_data_at=None, sources=[]),
+ ]
+
+ self.assertEqual(reportable(results, degraded=False), results)
+ self.assertEqual([r.team_id for r in reportable(results, degraded=True)], [1])
diff --git a/posthog/utils.py b/posthog/utils.py
index 6300d7abee59..98b73d06a172 100644
--- a/posthog/utils.py
+++ b/posthog/utils.py
@@ -1620,6 +1620,14 @@ def get_safe_cache(cache_key: str):
return None
+def ensure_utc(value: dt.datetime) -> dt.datetime:
+ """Treat a tz-naive datetime as UTC, so it can be compared against tz-aware values.
+
+ ClickHouse and some third-party APIs hand back naive datetimes that are UTC by contract.
+ """
+ return value if value.tzinfo else value.replace(tzinfo=dt.UTC)
+
+
def safe_cache_set(cache_key: str, value: Any, timeout: int | None = None) -> None:
"""Best-effort cache write. Logs a warning on failure so Redis blips
are visible during incidents without breaking the calling request."""
diff --git a/products/cdp/backend/data_freshness.py b/products/cdp/backend/data_freshness.py
new file mode 100644
index 000000000000..3b2b9b54b623
--- /dev/null
+++ b/products/cdp/backend/data_freshness.py
@@ -0,0 +1,6 @@
+from posthog.data_freshness import DataSourceSpec
+from posthog.schema_enums import ProductKey
+
+# Destination invocations, successful or not. A destination that is only erroring is still
+# a project doing something.
+DATA_SOURCES = [DataSourceSpec(product=ProductKey.PIPELINE_DESTINATIONS, app_metrics_source="hog_function")]
diff --git a/products/error_tracking/backend/data_freshness.py b/products/error_tracking/backend/data_freshness.py
new file mode 100644
index 000000000000..f0e242a9d052
--- /dev/null
+++ b/products/error_tracking/backend/data_freshness.py
@@ -0,0 +1,4 @@
+from posthog.data_freshness import DataSourceSpec
+from posthog.schema_enums import ProductKey
+
+DATA_SOURCES = [DataSourceSpec(product=ProductKey.ERROR_TRACKING, event_names=("$exception",))]
diff --git a/products/feature_flags/backend/data_freshness.py b/products/feature_flags/backend/data_freshness.py
new file mode 100644
index 000000000000..55dc348b313a
--- /dev/null
+++ b/products/feature_flags/backend/data_freshness.py
@@ -0,0 +1,6 @@
+from posthog.data_freshness import DataSourceSpec
+from posthog.schema_enums import ProductKey
+
+# Flag evaluations, not flag edits: a project with flags configured but nothing calling them
+# is not receiving data.
+DATA_SOURCES = [DataSourceSpec(product=ProductKey.FEATURE_FLAGS, event_names=("$feature_flag_called",))]
diff --git a/products/llm_analytics/backend/data_freshness.py b/products/llm_analytics/backend/data_freshness.py
new file mode 100644
index 000000000000..41bce30b1e94
--- /dev/null
+++ b/products/llm_analytics/backend/data_freshness.py
@@ -0,0 +1,9 @@
+from posthog.data_freshness import DataSourceSpec
+from posthog.schema_enums import ProductKey
+
+# A prefix rather than a list: the `$ai_*` family grows (generation, span, trace, evaluation,
+# tag), and any of them means the product is live.
+#
+# The key is still `llm_analytics`; the product now displays as "AI observability". The UI
+# reads that name from onboarding's catalog, so nothing here needs to know about the rename.
+DATA_SOURCES = [DataSourceSpec(product=ProductKey.LLM_ANALYTICS, event_prefix="$ai_")]
diff --git a/products/logs/backend/data_freshness.py b/products/logs/backend/data_freshness.py
new file mode 100644
index 000000000000..ac7b8aa46b6d
--- /dev/null
+++ b/products/logs/backend/data_freshness.py
@@ -0,0 +1,4 @@
+from posthog.data_freshness import DataSourceSpec
+from posthog.schema_enums import ProductKey
+
+DATA_SOURCES = [DataSourceSpec(product=ProductKey.LOGS, app_metrics_source="logs")]
diff --git a/products/platform_features/frontend/generated/api.schemas.ts b/products/platform_features/frontend/generated/api.schemas.ts
index 21174465129a..b2770463733d 100644
--- a/products/platform_features/frontend/generated/api.schemas.ts
+++ b/products/platform_features/frontend/generated/api.schemas.ts
@@ -251,6 +251,53 @@ export interface OrganizationAIAccessRequestResponseApi {
success: boolean
}
+/**
+ * * `never` - never
+ * * `live` - live
+ * * `stale` - stale
+ */
+export type FreshnessEnumApi = (typeof FreshnessEnumApi)[keyof typeof FreshnessEnumApi]
+
+export const FreshnessEnumApi = {
+ Never: 'never',
+ Live: 'live',
+ Stale: 'stale',
+} as const
+
+export interface DataFreshnessSourceApi {
+ /** The product this timestamp is about, as a `ProductKey` (e.g. `session_replay`, `logs`). Not an enum: products declare their own data sources, so the set grows without an API change. */
+ data_source: string
+ /** When data of this kind last reached the project. Only sources with data inside the lookback window are listed. */
+ last_data_at: string
+}
+
+export interface DataFreshnessProjectApi {
+ /** ID of the project this freshness verdict is for. */
+ team_id: number
+ /** `live` if data of any kind arrived within `quiet_after_days`, `stale` if none did, `never` if the project has never ingested anything at all.
+ *
+ * * `never` - never
+ * * `live` - live
+ * * `stale` - stale */
+ freshness: FreshnessEnumApi
+ /**
+ * When data of any kind last reached the project, or null if nothing arrived within the lookback window.
+ * @nullable
+ */
+ last_data_at: string | null
+ /** Per-source breakdown, most recently active first. */
+ sources: DataFreshnessSourceApi[]
+}
+
+export interface OrganizationDataFreshnessApi {
+ /** One entry per project the requesting user can see. */
+ results: DataFreshnessProjectApi[]
+ /** How many days back the check looks. Data older than this is not visible to the check. */
+ lookback_days: number
+ /** How many days without data make a project or source count as quiet. */
+ quiet_after_days: number
+}
+
/**
* * `engineering` - Engineering
* * `data` - Data
diff --git a/products/platform_features/frontend/generated/api.ts b/products/platform_features/frontend/generated/api.ts
index a1dd6e12e1a1..5fff14b6fab9 100644
--- a/products/platform_features/frontend/generated/api.ts
+++ b/products/platform_features/frontend/generated/api.ts
@@ -27,6 +27,7 @@ import type {
MembersListParams,
OrganizationAIAccessRequestResponseApi,
OrganizationApi,
+ OrganizationDataFreshnessApi,
OrganizationMemberApi,
OrganizationMemberGithubLoginApi,
PaginatedActivityLogListApi,
@@ -181,6 +182,23 @@ export const requestAiAccessCreate = async (
})
}
+export const getTeamsDataFreshnessRetrieveUrl = (id: string) => {
+ return `/api/organizations/${id}/teams/data_freshness/`
+}
+
+/**
+ * When each project in the organization last received data, broken down by kind of data.
+ */
+export const teamsDataFreshnessRetrieve = async (
+ id: string,
+ options?: RequestInit
+): Promise<OrganizationDataFreshnessApi> => {
+ return apiMutator<OrganizationDataFreshnessApi>(getTeamsDataFreshnessRetrieveUrl(id), {
+ ...options,
+ method: 'GET',
+ })
+}
+
export const getMembersListUrl = (organizationId: string, params?: MembersListParams) => {
const normalizedParams = new URLSearchParams()
diff --git a/products/platform_features/mcp/tools.yaml b/products/platform_features/mcp/tools.yaml
index 19be6debf1ec..db0206cd03b7 100644
--- a/products/platform_features/mcp/tools.yaml
+++ b/products/platform_features/mcp/tools.yaml
@@ -542,6 +542,9 @@ tools:
roles-update:
operation: roles_update
enabled: false
+ teams-data-freshness-retrieve:
+ operation: teams_data_freshness_retrieve
+ enabled: false
user-home-settings-get:
operation: user_home_settings_retrieve
enabled: true
diff --git a/products/product_analytics/backend/data_freshness.py b/products/product_analytics/backend/data_freshness.py
new file mode 100644
index 000000000000..c88a9be7af2c
--- /dev/null
+++ b/products/product_analytics/backend/data_freshness.py
@@ -0,0 +1,6 @@
+from posthog.data_freshness import DataSourceSpec
+from posthog.schema_enums import ProductKey
+
+# The residual: every event name no other product claims counts as product analytics, so a
+# project sending only its own custom events still reads as live.
+DATA_SOURCES = [DataSourceSpec(product=ProductKey.PRODUCT_ANALYTICS, is_residual=True)]
diff --git a/products/replay/backend/data_freshness.py b/products/replay/backend/data_freshness.py
new file mode 100644
index 000000000000..45fb6a6f9b40
--- /dev/null
+++ b/products/replay/backend/data_freshness.py
@@ -0,0 +1,44 @@
+from datetime import datetime
+
+from posthog.clickhouse.client import sync_execute
+from posthog.clickhouse.query_tagging import Feature, Product, tags_context
+from posthog.data_freshness import CLICKHOUSE_SETTINGS, DataSourceSpec, ProbeWindow
+from posthog.schema_enums import ProductKey
+from posthog.utils import ensure_utc
+
+
+def _max_between(team_ids: list[int], since: datetime, until: datetime) -> dict[int, datetime]:
+ with tags_context(product=Product.REPLAY, feature=Feature.DATA_FRESHNESS):
+ rows = sync_execute(
+ """
+ SELECT team_id, max(min_first_timestamp)
+ FROM session_replay_events
+ WHERE team_id IN %(team_ids)s
+ AND min_first_timestamp >= %(since)s
+ AND min_first_timestamp < %(until)s
+ GROUP BY team_id
+ """,
+ {"team_ids": team_ids, "since": since, "until": until},
+ settings=CLICKHOUSE_SETTINGS,
+ )
+ return {team_id: ensure_utc(last_data_at) for team_id, last_data_at in rows}
+
+
+def last_replay_at(team_ids: list[int], window: ProbeWindow) -> dict[int, datetime]:
+ """Ask for the recent window first, then only widen for teams that came back empty.
+
+ `session_replay_events` sorts on `(toDate(min_first_timestamp), team_id, session_id)`, so
+ unlike the shared queries its bytes scale with the window as well as the team count.
+ Splitting it means a busy team, which is where the bytes are, is answered from the short
+ window and its older tail is never read. The teams that do need the wider read are by
+ definition the ones with nothing recent.
+ """
+ found = _max_between(team_ids, window.quiet_before, window.horizon)
+
+ older = [team_id for team_id in team_ids if team_id not in found]
+ if older:
+ found |= _max_between(older, window.cutoff, window.quiet_before)
+ return found
+
+
+DATA_SOURCES = [DataSourceSpec(product=ProductKey.SESSION_REPLAY, probe=last_replay_at)]
diff --git a/products/surveys/backend/data_freshness.py b/products/surveys/backend/data_freshness.py
new file mode 100644
index 000000000000..a95186fca16b
--- /dev/null
+++ b/products/surveys/backend/data_freshness.py
@@ -0,0 +1,11 @@
+from posthog.data_freshness import DataSourceSpec
+from posthog.schema_enums import ProductKey
+
+from products.surveys.backend.util import SurveyEventName
+
+DATA_SOURCES = [
+ DataSourceSpec(
+ product=ProductKey.SURVEYS,
+ event_names=(SurveyEventName.SHOWN, SurveyEventName.DISMISSED, SurveyEventName.SENT),
+ )
+]
diff --git a/products/tracing/backend/data_freshness.py b/products/tracing/backend/data_freshness.py
new file mode 100644
index 000000000000..32690b77b198
--- /dev/null
+++ b/products/tracing/backend/data_freshness.py
@@ -0,0 +1,4 @@
+from posthog.data_freshness import DataSourceSpec
+from posthog.schema_enums import ProductKey
+
+DATA_SOURCES = [DataSourceSpec(product=ProductKey.TRACING, app_metrics_source="traces")]
diff --git a/products/warehouse_sources/backend/data_freshness.py b/products/warehouse_sources/backend/data_freshness.py
new file mode 100644
index 000000000000..7b573be1afd9
--- /dev/null
+++ b/products/warehouse_sources/backend/data_freshness.py
@@ -0,0 +1,33 @@
+from datetime import datetime
+
+from django.db.models import Max
+
+from posthog.data_freshness import POSTGRES_TIMEOUT_MS, DataSourceSpec, ProbeWindow
+from posthog.models.utils import execute_with_timeout
+from posthog.schema_enums import ProductKey
+
+from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
+
+
+def last_sync_at(team_ids: list[int], window: ProbeWindow) -> dict[int, datetime]:
+ """Read the per-schema sync stamp rather than aggregating job history.
+
+ `ExternalDataJob` is one row per schema per run and has no index serving a `finished_at`
+ range, so a windowed max over it reads a team's whole history. `ExternalDataSchema` holds
+ one row per schema off the team FK, and is what the rest of the codebase treats as "last
+ successful sync".
+ """
+ rows = (
+ ExternalDataSchema.objects.filter(
+ team_id__in=team_ids,
+ last_synced_at__gte=window.cutoff,
+ last_synced_at__lte=window.horizon,
+ )
+ .values("team_id")
+ .annotate(last_synced=Max("last_synced_at"))
+ )
+ with execute_with_timeout(POSTGRES_TIMEOUT_MS):
+ return {row["team_id"]: row["last_synced"] for row in rows}
+
+
+DATA_SOURCES = [DataSourceSpec(product=ProductKey.DATA_WAREHOUSE, probe=last_sync_at)]
diff --git a/products/workflows/backend/data_freshness.py b/products/workflows/backend/data_freshness.py
new file mode 100644
index 000000000000..9b30025ad90d
--- /dev/null
+++ b/products/workflows/backend/data_freshness.py
@@ -0,0 +1,4 @@
+from posthog.data_freshness import DataSourceSpec
+from posthog.schema_enums import ProductKey
+
+DATA_SOURCES = [DataSourceSpec(product=ProductKey.WORKFLOWS, app_metrics_source="hog_flow")]
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 60b10bff0aad..8d0104720467 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -17865,6 +17865,45 @@ export namespace Schemas {
readonly created_by: UserBasic;
}
+ /**
+ * * `never` - never
+ * * `live` - live
+ * * `stale` - stale
+ */
+ export type FreshnessEnum = typeof FreshnessEnum[keyof typeof FreshnessEnum];
+
+
+ export const FreshnessEnum = {
+ Never: 'never',
+ Live: 'live',
+ Stale: 'stale',
+ } as const;
+
+ export interface DataFreshnessSource {
+ /** The product this timestamp is about, as a `ProductKey` (e.g. `session_replay`, `logs`). Not an enum: products declare their own data sources, so the set grows without an API change. */
+ data_source: string;
+ /** When data of this kind last reached the project. Only sources with data inside the lookback window are listed. */
+ last_data_at: string;
+ }
+
+ export interface DataFreshnessProject {
+ /** ID of the project this freshness verdict is for. */
+ team_id: number;
+ /** `live` if data of any kind arrived within `quiet_after_days`, `stale` if none did, `never` if the project has never ingested anything at all.
+ *
+ * * `never` - never
+ * * `live` - live
+ * * `stale` - stale */
+ freshness: FreshnessEnum;
+ /**
+ * When data of any kind last reached the project, or null if nothing arrived within the lookback window.
+ * @nullable
+ */
+ last_data_at: string | null;
+ /** Per-source breakdown, most recently active first. */
+ sources: DataFreshnessSource[];
+ }
+
/**
* * `Cancelled` - Cancelled
* * `Completed` - Completed
@@ -45117,6 +45156,15 @@ export namespace Schemas {
is_pending_deletion?: boolean | null;
}
+ export interface OrganizationDataFreshness {
+ /** One entry per project the requesting user can see. */
+ results: DataFreshnessProject[];
+ /** How many days back the check looks. Data older than this is not visible to the check. */
+ lookback_days: number;
+ /** How many days without data make a project or source count as quiet. */
+ quiet_after_days: number;
+ }
+
export interface OrganizationDomain {
readonly id: string;
/** @maxLength 128 */