: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(warehouse-suggestions): rules, candidates and the daily schedule (#113443)
Thiago Salvatore67b0dcc50700
diff --git a/.github/scripts/check-idor-model-coverage.py b/.github/scripts/check-idor-model-coverage.pyindex 359b408a0ff8..7fa95a744072 100644--- a/.github/scripts/check-idor-model-coverage.py+++ b/.github/scripts/check-idor-model-coverage.py@@ -226,6 +226,7 @@ def get_scoped_models() -> tuple[dict[str, set[str]], set[str], set[str], set[st# no endpoint looks it up by a user-supplied ID."TeamReplayVisionConfig","TeamTracingConfig",+ "WarehouseSuggestionTeamConfig","TeamJsSnippetConfig","TeamProvisioningConfig",# --- User preferences with no IDOR risk (read own data only) ---diff --git a/.github/workflows/container-images-cd.yml b/.github/workflows/container-images-cd.ymlindex 8c7d7af8e856..9ab480fafe0e 100644--- a/.github/workflows/container-images-cd.yml+++ b/.github/workflows/container-images-cd.yml@@ -708,6 +708,7 @@ jobs:- 'products/data_quality/**'- 'products/data_modeling/**'- 'products/data_warehouse/**'+ - 'products/warehouse_suggestions/**'- 'posthog/management/commands/**'- 'posthog/clickhouse/migrations/**'- pyproject.tomldiff --git a/posthog/clickhouse/query_tagging.py b/posthog/clickhouse/query_tagging.pyindex be155f1c23f7..e6c521b38e22 100644--- a/posthog/clickhouse/query_tagging.py+++ b/posthog/clickhouse/query_tagging.py@@ -54,6 +54,7 @@ class Product(StrEnum):CONVERSATIONS = "conversations"CUSTOMER_ANALYTICS = "customer_analytics"DATA_CATALOG = "data_catalog"+ DATA_MODELING = "data_modeling"DATA_QUALITY = "data_quality"ENDPOINTS = "endpoints"ENGINEERING_ANALYTICS = "engineering_analytics"@@ -108,6 +109,7 @@ class Feature(StrEnum):DASHBOARD = "dashboard"CACHE_WARMUP = "cache_warmup"DATA_MODELING = "data_modeling"+ WAREHOUSE_SUGGESTIONS = "warehouse_suggestions"HEALTH_CHECK = "health_check"IMPORT_PIPELINE = "import_pipeline"INGESTION_WARNINGS = "ingestion_warnings"diff --git a/posthog/management/commands/start_temporal_worker.py b/posthog/management/commands/start_temporal_worker.pyindex d1a758c0c641..71dab6c2096d 100644--- a/posthog/management/commands/start_temporal_worker.py+++ b/posthog/management/commands/start_temporal_worker.py@@ -312,6 +312,10 @@ from products.warehouse_sources.backend.facade.temporal import (WORKFLOWS as DATA_SYNC_WORKFLOWS,load_all_sources,)+from products.warehouse_suggestions.backend.facade.temporal import (+ ACTIVITIES as WAREHOUSE_SUGGESTIONS_ACTIVITIES,+ WORKFLOWS as WAREHOUSE_SUGGESTIONS_WORKFLOWS,+)from products.web_analytics.backend.temporal import (ACTIVITIES as WA_DIGEST_ACTIVITIES,WORKFLOWS as WA_DIGEST_WORKFLOWS,@@ -359,8 +363,8 @@ _task_queue_specs = [),(settings.DATA_MODELING_TASK_QUEUE,- DATA_MODELING_WORKFLOWS + DATA_QUALITY_WORKFLOWS,- DATA_MODELING_ACTIVITIES + DATA_QUALITY_ACTIVITIES,+ DATA_MODELING_WORKFLOWS + DATA_QUALITY_WORKFLOWS + WAREHOUSE_SUGGESTIONS_WORKFLOWS,+ DATA_MODELING_ACTIVITIES + DATA_QUALITY_ACTIVITIES + WAREHOUSE_SUGGESTIONS_ACTIVITIES,),(settings.GENERAL_PURPOSE_TASK_QUEUE,diff --git a/posthog/temporal/schedule.py b/posthog/temporal/schedule.pyindex c54a2ca8167d..f0e11eac96aa 100644--- a/posthog/temporal/schedule.py+++ b/posthog/temporal/schedule.py@@ -141,6 +141,7 @@ from products.signals.backend.temporal.agentic.schedule import (create_signals_scout_coordinator_schedule,)from products.today.backend.facade.temporal import create_today_briefing_schedule+from products.warehouse_suggestions.backend.facade.temporal import create_warehouse_suggestions_schedulefrom products.web_analytics.backend.temporal.digest_notification.types import WADigestNotificationInputfrom products.web_analytics.backend.temporal.weekly_digest.types import WAWeeklyDigestInput@@ -989,6 +990,7 @@ schedules = [create_ci_signals_coordinator_schedule,create_cleanup_data_quality_check_runs_schedule,create_reconcile_metric_schedules_schedule,+ create_warehouse_suggestions_schedule,create_sync_access_rules_schedule,]diff --git a/products/data_modeling/backend/facade/api.py b/products/data_modeling/backend/facade/api.pyindex 7dba507d7977..07a0951d2d22 100644--- a/products/data_modeling/backend/facade/api.py+++ b/products/data_modeling/backend/facade/api.py@@ -69,6 +69,7 @@ _LAZY = {"get_declared_target": "logic.node_frequency","set_declared_target": "logic.node_frequency","saved_query_target_bounds": "logic.node_frequency",+ "SavedQueryFrequencyBounds": "logic.node_frequency","clear_node_suspension": "logic.node_suspension","is_node_suspended": "logic.node_suspension","mark_node_suspended": "logic.node_suspension",diff --git a/products/data_modeling/backend/facade/contracts.py b/products/data_modeling/backend/facade/contracts.pyindex b7d186c3fb99..bdb73d83b0f3 100644--- a/products/data_modeling/backend/facade/contracts.py+++ b/products/data_modeling/backend/facade/contracts.py@@ -50,15 +50,15 @@ class SavedQuerySummary:@dataclass(frozen=True)class SavedQueryDefinition:- """A saved query with its HogQL and materialization settings."""+ """A saved query with its HogQL and whether its DAG node materializes."""id: UUIDname: strhogql: str- is_materialized: bool- sync_frequency_interval: timedelta | None+ materializes: boolis_test: boolis_managed: bool+ origin: str | Nonecreated_at: datetime@@ -77,6 +77,7 @@ class Dependent:class UpstreamTableRef:name: strwarehouse_table_id: str | None = None+ is_posthog_table: bool = False@dataclass(frozen=True)diff --git a/products/data_modeling/backend/logic/freshness.py b/products/data_modeling/backend/logic/freshness.pyindex fc13f8227ee5..de0a1679e21c 100644--- a/products/data_modeling/backend/logic/freshness.py+++ b/products/data_modeling/backend/logic/freshness.py@@ -188,6 +188,29 @@ def _finest(bounds: list[Bound]) -> Bound:return min(bounds, key=_bound_sort_key)+def max_data_age(+ node_id: str,+ edges: list[tuple[str, str]],+ source_intervals: dict[str, timedelta],+ declared_targets: dict[str, timedelta],+) -> timedelta:+ """The oldest data `node_id` can serve when read live: its slowest chain of upstream syncs and refreshes."""+ adj = _adjacency(edges)+ all_ids = set(source_intervals) | {node for edge in edges for node in edge}+ in_degree = {node: len(adj.parents.get(node, [])) for node in all_ids}+ queue = deque(node for node in all_ids if in_degree[node] == 0)+ age: dict[str, timedelta] = {}+ while queue:+ node = queue.popleft()+ upstream_age = max((age[parent] for parent in adj.parents.get(node, [])), default=STREAMING)+ age[node] = upstream_age + source_intervals.get(node, declared_targets.get(node, STREAMING))+ for child in adj.children.get(node, []):+ in_degree[child] -= 1+ if in_degree[child] == 0:+ queue.append(child)+ return max((age[parent] for parent in adj.parents.get(node_id, []) if parent in age), default=STREAMING)++def ancestors_of(node_id: str, edges: list[tuple[str, str]]) -> set[str]:"""Every node upstream of `node_id`, however far — the cone whose delivery it inherits."""parents: dict[str, list[str]] = defaultdict(list)diff --git a/products/data_modeling/backend/logic/node_frequency.py b/products/data_modeling/backend/logic/node_frequency.pyindex c7afd948055e..31c461f459f2 100644--- a/products/data_modeling/backend/logic/node_frequency.py+++ b/products/data_modeling/backend/logic/node_frequency.py@@ -23,6 +23,7 @@ from products.data_modeling.backend.logic.freshness import (ancestors_of,compute_target_bounds,intersect_target_bounds,+ max_data_age,normalize_seed_target,)from products.data_modeling.backend.logic.node_suspension import merged_suspension_state@@ -296,6 +297,7 @@ class SavedQueryFrequencyBounds:names: dict[str, str] # node id -> display name, covering every blocker the bounds referenceidentities: dict[str, NodeIdentity] # node id -> the resource its name belongs tobest_effort_source_ids: set[str] # upstream sources with no schedule, so the floor is a guess+ max_data_age: timedeltadef saved_query_target_bounds(team_id: int, saved_query_id: str | uuid.UUID) -> SavedQueryFrequencyBounds | None:@@ -315,6 +317,7 @@ def saved_query_target_bounds(team_id: int, saved_query_id: str | uuid.UUID) ->names: dict[str, str] = {}identities: dict[str, NodeIdentity] = {}best_effort: set[str] = set()+ data_ages: list[timedelta] = []graphs: dict[str, FrequencyGraph] = {}for node in nodes:# a saved query can hold two nodes in one DAG, and that DAG's graph is the same for both@@ -334,12 +337,14 @@ def saved_query_target_bounds(team_id: int, saved_query_id: str | uuid.UUID) ->identities.update(graph.identities)# a best-effort source elsewhere in the DAG says nothing about this node's freshnessbest_effort |= graph.best_effort_source_ids & ancestors_of(str(node.id), graph.edges)+ data_ages.append(max_data_age(str(node.id), graph.edges, graph.source_intervals, graph.declared_targets))return SavedQueryFrequencyBounds(bounds=intersect_target_bounds(per_dag),names=names,identities=identities,best_effort_source_ids=best_effort,+ max_data_age=max(data_ages),)diff --git a/products/data_modeling/backend/logic/saved_query_reads.py b/products/data_modeling/backend/logic/saved_query_reads.pyindex 75bd2a98ea00..e2a28e5ac605 100644--- a/products/data_modeling/backend/logic/saved_query_reads.py+++ b/products/data_modeling/backend/logic/saved_query_reads.py@@ -11,8 +11,8 @@ from ..facade.contracts import SavedQueryDefinition, SavedQuerySummary, Upstreamfrom ..models.datawarehouse_saved_query import DataWarehouseSavedQueryfrom ..models.edge import Edgefrom ..models.node import Node, NodeType-from .node_frequency import declared_targets_by_saved_queryfrom .saved_query_freshness import saved_query_materialized_at+from .tier_run_report import MATERIALIZING_TYPESPOSTHOG_TABLE_ORIGIN = "posthog"PROXY_SAVED_QUERY_ID_PROPERTY = "saved_query_id"@@ -98,23 +98,29 @@ def all_saved_query_names(team_id: int) -> dict[str, str]:def saved_query_definitions(team_id: int) -> list[SavedQueryDefinition]:- """Every saved query in this team that still resolves, with its HogQL, materialization and DAG node interval."""+ """Every saved query in this team that still resolves, with its HogQL and whether its DAG node materializes."""saved_queries = list(DataWarehouseSavedQuery.objects.filter(team_id=team_id).exclude(deleted=True)- .only("id", "name", "query", "is_materialized", "is_test", "managed_viewset_id", "created_at")+ .only("id", "name", "query", "is_test", "managed_viewset_id", "origin", "created_at").order_by("created_at", "id"))- intervals = declared_targets_by_saved_query(team_id, [saved_query.id for saved_query in saved_queries])+ materializing_ids = set(+ Node.objects.filter(+ team_id=team_id,+ saved_query_id__in=[saved_query.id for saved_query in saved_queries],+ type__in=MATERIALIZING_TYPES,+ ).values_list("saved_query_id", flat=True)+ )return [SavedQueryDefinition(id=saved_query.id,name=saved_query.name,hogql=(saved_query.query or {}).get("query") or "",- is_materialized=bool(saved_query.is_materialized),- sync_frequency_interval=intervals.get(str(saved_query.id)),+ materializes=saved_query.id in materializing_ids,is_test=saved_query.is_test,is_managed=saved_query.managed_viewset_id is not None,+ origin=saved_query.origin,created_at=saved_query.created_at,)for saved_query in saved_queries@@ -316,7 +322,11 @@ def reachable_node_ids(team_id: int, start_node_ids: set[str], *, upstream: booldef upstream_table_refs(team_id: int, saved_query_id: UUID | str) -> frozenset[UpstreamTableRef]:"""The tables this saved query reads from, directly or through other views in any DAG."""return frozenset(- UpstreamTableRef(name=name, warehouse_table_id=_warehouse_table_id(properties))+ UpstreamTableRef(+ name=name,+ warehouse_table_id=_warehouse_table_id(properties),+ is_posthog_table=properties.get("origin") == POSTHOG_TABLE_ORIGIN,+ )for name, properties in _upstream_table_nodes(team_id, str(saved_query_id))if _proxied_saved_query_id(properties) is None)diff --git a/products/data_modeling/backend/test/test_freshness.py b/products/data_modeling/backend/test/test_freshness.pyindex 7f4e1707f6a9..7acd9a3e8321 100644--- a/products/data_modeling/backend/test/test_freshness.py+++ b/products/data_modeling/backend/test/test_freshness.py@@ -17,6 +17,7 @@ from products.data_modeling.backend.logic.freshness import (compute_target_bounds,find_invalid_targets,intersect_target_bounds,+ max_data_age,normalize_seed_target,validate_declared_target,)@@ -253,6 +254,25 @@ class TestComputeTargetBounds(TestCase):self.assertFalse(bounds.satisfiable)+class TestMaxDataAge(TestCase):+ @parameterized.expand(+ [+ ("slowest_of_two_sources", [("hourly", "v"), ("daily", "v")], {"hourly": H1, "daily": DAY}, {}, DAY),+ ("fast_source_still_counts", [("src", "v")], {"src": M5}, {}, M5),+ ("streaming_only", [("events", "v")], {"events": STREAMING}, {}, STREAMING),+ ("refresh_adds_to_its_sources", [("src", "mat"), ("mat", "v")], {"src": H6}, {"mat": H12}, H6 + H12),+ ("own_target_does_not_count", [("src", "v")], {"src": H1}, {"v": DAY}, H1),+ ]+ )+ def test_takes_the_slowest_chain_of_syncs_and_refreshes(self, _name, edges, intervals, targets, expected):+ self.assertEqual(max_data_age("v", edges, intervals, targets), expected)++ def test_deep_chain_does_not_overflow(self):+ depth = 5000+ edges = [(f"n{i}", f"n{i + 1}") for i in range(depth - 1)]+ self.assertEqual(max_data_age(f"n{depth - 1}", edges, {"n0": H1}, {}), H1)++class TestIntersectTargetBounds(TestCase):# the same saved query has a node in two DAGs: one bounded by a 6h source, the other by a# 12h consumer. The save path validates against both, so the picker has to as well.diff --git a/products/data_modeling/backend/test/test_saved_query_reads.py b/products/data_modeling/backend/test/test_saved_query_reads.pyindex 734a5a6ad884..a84a8f93cb6b 100644--- a/products/data_modeling/backend/test/test_saved_query_reads.py+++ b/products/data_modeling/backend/test/test_saved_query_reads.py@@ -1,4 +1,3 @@-from datetime import timedeltafrom uuid import uuid4from posthog.test.base import BaseTest@@ -13,7 +12,6 @@ from products.access_control.backend.facade.user_access_control import AccessConfrom products.access_control.backend.models.access_control import AccessControlfrom products.data_modeling.backend.facade import apifrom products.data_modeling.backend.facade.contracts import SavedQueryDefinition, UpstreamTableRef-from products.data_modeling.backend.logic.node_frequency import set_declared_targetfrom products.data_modeling.backend.logic.saved_query_reads import POSTHOG_TABLE_ORIGINfrom products.data_modeling.backend.models.dag import DAGfrom products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQuery@@ -80,21 +78,22 @@ class TestSavedQueryReads(BaseTest):{readable.id, editable.id, ungranted.id, owned.id})- def test_saved_query_definitions_lists_live_views_with_their_node_interval(self) -> None:+ def test_saved_query_definitions_lists_live_views_with_their_node_type(self) -> None:+ dag = DAG.objects.create(team=self.team, name="Default")live = DataWarehouseSavedQuery.objects.create(team=self.team,name="orders",query={"kind": "HogQLQuery", "query": "SELECT 1"},- is_materialized=True,+ is_materialized=False,)- node = Node.objects.create(+ Node.objects.create(team=self.team, dag=dag, saved_query=live, type=NodeType.MAT_VIEW)+ plain = DataWarehouseSavedQuery.objects.create(team=self.team,- dag=DAG.objects.create(team=self.team, name="Default"),- saved_query=live,- type=NodeType.MAT_VIEW,+ name="plain",+ query={"kind": "HogQLQuery", "query": "SELECT 2"},+ is_materialized=True,)- set_declared_target(node, timedelta(hours=6))- node.save()+ Node.objects.create(team=self.team, dag=dag, saved_query=plain, type=NodeType.VIEW)DataWarehouseSavedQuery.objects.create(team=self.team, name="gone", deleted=True)other_team = Team.objects.create(organization=self.organization)DataWarehouseSavedQuery.objects.create(team=other_team, name="elsewhere")@@ -104,12 +103,22 @@ class TestSavedQueryReads(BaseTest):id=live.id,name="orders",hogql="SELECT 1",- is_materialized=True,- sync_frequency_interval=timedelta(hours=6),+ materializes=True,is_test=False,is_managed=False,+ origin=None,created_at=live.created_at,- )+ ),+ SavedQueryDefinition(+ id=plain.id,+ name="plain",+ hogql="SELECT 2",+ materializes=False,+ is_test=False,+ is_managed=False,+ origin=None,+ created_at=plain.created_at,+ ),]def test_dependent_saved_query_ids_follows_every_node_of_the_source(self) -> None:@@ -155,6 +164,7 @@ class TestSavedQueryReads(BaseTest):self.team, dag, "revenue", {"origin": "cross_dag_view", "saved_query_id": str(revenue.saved_query_id)})persons = table_node(self.team, dag, "persons", {"origin": POSTHOG_TABLE_ORIGIN})+ legacy = table_node(self.team, dag, "legacy_orders", {})middle = saved_query_node(self.team, dag, "middle", NodeType.VIEW)target = saved_query_node(self.team, dag, "target", NodeType.VIEW)downstream = saved_query_node(self.team, dag, "downstream", NodeType.VIEW)@@ -162,6 +172,7 @@ class TestSavedQueryReads(BaseTest):(charges, middle),(events, middle),(proxy, middle),+ (legacy, middle),(middle, target),(target, downstream),(persons, downstream),@@ -171,7 +182,8 @@ class TestSavedQueryReads(BaseTest):assert api.upstream_table_refs(self.team.id, target.saved_query_id) == frozenset({UpstreamTableRef(name="stripe_charges", warehouse_table_id=warehouse_table_id),- UpstreamTableRef(name="events"),- UpstreamTableRef(name="invoices"),+ UpstreamTableRef(name="events", is_posthog_table=True),+ UpstreamTableRef(name="invoices", is_posthog_table=True),+ UpstreamTableRef(name="legacy_orders"),})diff --git a/products/warehouse_suggestions/backend/facade/api.py b/products/warehouse_suggestions/backend/facade/api.pyindex b171c6fd3626..e4133454fd7f 100644--- a/products/warehouse_suggestions/backend/facade/api.py+++ b/products/warehouse_suggestions/backend/facade/api.py@@ -5,16 +5,20 @@ from typing import TYPE_CHECKINGfrom uuid import UUIDfrom ..logic import suggestions-from ..logic.access import SubjectAccess, visible_suggestions+from ..logic.access import SubjectAccess, readable_table_ids, visible_suggestionsfrom ..logic.flags import is_warehouse_suggestions_enabled-from ..models import WarehouseSuggestion+from ..logic.payloads import payload_from_json, payload_view, source_table_ids+from ..logic.rules import RULES+from ..models import WarehouseSuggestion, WarehouseSuggestionTeamConfigfrom .contracts import (SubjectEditAccessRequiredError,Suggestion,SuggestionDraft,SuggestionNotFoundError,SuggestionPage,+ SuggestionPayloadView,SuggestionReviewer,+ SuggestionStatus,)from .enums import (WarehouseSuggestionAssetOutcome,@@ -33,6 +37,7 @@ __all__ = ["is_warehouse_suggestions_enabled","list_suggestions","resume_suggestion",+ "suggestion_status","upsert_suggestions",]@@ -51,13 +56,26 @@ def list_suggestions(offset: int,) -> SuggestionPage:visible, access = visible_suggestions(team_id, user_access_control, kind=kind, status=status)- page = visible[offset : offset + limit]- return SuggestionPage(count=visible.count(), results=[_to_contract(row, access) for row in page])+ page = list(visible[offset : offset + limit])+ return SuggestionPage(count=visible.count(), results=_to_contracts(team_id, user_access_control, page, access))+++def suggestion_status(team_id: int) -> SuggestionStatus:+ config = WarehouseSuggestionTeamConfig.objects.filter(team_id=team_id).first() or WarehouseSuggestionTeamConfig()+ return SuggestionStatus(+ enabled=config.enabled,+ eligible=config.eligible,+ days_with_data=config.days_with_data,+ window_days=RULES.window_days,+ paused_reason=config.paused_reason,+ refreshed_at=config.last_run_at,+ )def get_suggestion(team_id: int, user_access_control: "UserAccessControl", suggestion_id: UUID) -> Suggestion:row, access = _visible_suggestion(team_id, user_access_control, suggestion_id)- return _to_contract(row, access)+ (suggestion,) = _to_contracts(team_id, user_access_control, [row], access)+ return suggestiondef dismiss_suggestion(@@ -108,7 +126,8 @@ def _decide(note=note,transitions=suggestions.HUMAN_TRANSITIONS,)- return _to_contract(decided, access)+ (suggestion,) = _to_contracts(team_id, user_access_control, [decided], access)+ return suggestiondef _visible_suggestion(@@ -121,13 +140,26 @@ def _visible_suggestion(return row, access-def _to_contract(row: WarehouseSuggestion, access: SubjectAccess) -> Suggestion:+def _to_contracts(+ team_id: int,+ user_access_control: "UserAccessControl",+ rows: list[WarehouseSuggestion],+ access: SubjectAccess,+) -> list[Suggestion]:+ stored = {+ row.id: payload_from_json(WarehouseSuggestionKind(row.kind), row.payload_version, row.payload) for row in rows+ }+ readable = readable_table_ids(team_id, user_access_control, source_table_ids(stored.values()))+ return [_to_contract(row, access, payload_view(stored[row.id], readable)) for row in rows]+++def _to_contract(row: WarehouseSuggestion, access: SubjectAccess, payload: SuggestionPayloadView) -> Suggestion:return Suggestion(id=row.id,kind=WarehouseSuggestionKind(row.kind),subject_kind=WarehouseSuggestionSubjectKind(row.subject_kind),subject_id=row.subject_id,- payload=row.payload,+ payload=payload,payload_version=row.payload_version,evidence=row.evidence,evidence_window_start=row.evidence_window_start,diff --git a/products/warehouse_suggestions/backend/facade/contracts.py b/products/warehouse_suggestions/backend/facade/contracts.pyindex a73c52c559d5..e4f3214c672e 100644--- a/products/warehouse_suggestions/backend/facade/contracts.py+++ b/products/warehouse_suggestions/backend/facade/contracts.py@@ -14,6 +14,66 @@ from .enums import (WarehouseSuggestionSubjectKind,)+PAYLOAD_VERSION = 1+++@frozen+class SourceRef:+ name: str+ warehouse_table_id: UUID | None+++@frozen+class CertifyPayload:+ subject_name: str+++@frozen+class DeprecatePayload:+ subject_name: str+ refresh_seconds_per_month: float+ refresh_bytes_per_month: float+++@frozen+class MaterializePayload:+ """The stored materialize payload, with the warehouse table id of each source."""++ subject_name: str+ refresh_interval_seconds: int+ saves_seconds_per_month: float+ saves_bytes_per_month: float+ freshness_today_seconds: int | None+ freshness_after_seconds: int+ live_sources: tuple[SourceRef, ...]+ unknown_sources: tuple[SourceRef, ...]+++SuggestionPayload = CertifyPayload | DeprecatePayload | MaterializePayload+++@frozen+class VisibleSources:+ names: tuple[str, ...]+ hidden_count: int+++@frozen+class MaterializeSuggestionPayload:+ """The materialize payload a caller sees: the source names they can read, and a count of the others."""++ subject_name: str+ refresh_interval_seconds: int+ saves_seconds_per_month: float+ saves_bytes_per_month: float+ freshness_today_seconds: int | None+ freshness_after_seconds: int+ live_sources: VisibleSources+ unknown_sources: VisibleSources+++SuggestionPayloadView = CertifyPayload | DeprecatePayload | MaterializeSuggestionPayload+@frozenclass SuggestionDraft:@@ -21,7 +81,7 @@ class SuggestionDraft:fingerprint: strsubject_kind: WarehouseSuggestionSubjectKindsubject_id: UUID- payload: dict[str, Any]+ payload: SuggestionPayloadpayload_version: intrules_version: strevidence: dict[str, Any]@@ -45,7 +105,7 @@ class Suggestion:kind: WarehouseSuggestionKindsubject_kind: WarehouseSuggestionSubjectKindsubject_id: UUID- payload: dict[str, Any]+ payload: SuggestionPayloadViewpayload_version: intevidence: dict[str, Any]evidence_window_start: datetime@@ -63,6 +123,16 @@ class Suggestion:can_act: bool+@frozen+class SuggestionStatus:+ enabled: bool+ eligible: bool+ days_with_data: int+ window_days: int+ paused_reason: str | None+ refreshed_at: datetime | None++@frozenclass SuggestionPage:count: int@@ -82,3 +152,8 @@ class SubjectEditAccessRequiredError(Exception):class SuggestionAlreadyDecidedError(Exception):def __init__(self, current: WarehouseSuggestionStatus, requested: WarehouseSuggestionStatus) -> None:super().__init__(f"This suggestion is {current.label.lower()} and cannot become {requested.label.lower()}.")+++class UnsupportedPayloadVersionError(Exception):+ def __init__(self, payload_version: int) -> None:+ super().__init__(f"Suggestion payload version {payload_version} is not supported.")diff --git a/products/warehouse_suggestions/backend/facade/temporal.py b/products/warehouse_suggestions/backend/facade/temporal.pynew file mode 100644index 000000000000..093d9a807fad--- /dev/null+++ b/products/warehouse_suggestions/backend/facade/temporal.py@@ -0,0 +1,7 @@+"""Facade re-exports for Temporal wiring."""++from ..temporal import (+ ACTIVITIES as ACTIVITIES,+ WORKFLOWS as WORKFLOWS,+)+from ..temporal.schedule import create_warehouse_suggestions_schedule as create_warehouse_suggestions_schedulediff --git a/products/warehouse_suggestions/backend/logic/access.py b/products/warehouse_suggestions/backend/logic/access.pyindex dc07572a91b3..7e882a83ad73 100644--- a/products/warehouse_suggestions/backend/logic/access.py+++ b/products/warehouse_suggestions/backend/logic/access.py@@ -1,9 +1,9 @@from collections import defaultdict-from collections.abc import Collection, Mapping+from collections.abc import Collection, Mapping, Sequencefrom typing import TYPE_CHECKING, Protocolfrom uuid import UUID-from django.db.models import Q, QuerySet+from django.db.models import Case, IntegerField, Q, QuerySet, Value, Whenfrom posthog.dataclasses import frozen@@ -12,6 +12,7 @@ from products.warehouse_sources.backend.facade.api import allowed_table_idsfrom ..facade.enums import WarehouseSuggestionKind, WarehouseSuggestionStatus, WarehouseSuggestionSubjectKindfrom ..models import WarehouseSuggestion+from .rules import RULESif TYPE_CHECKING:from products.access_control.backend.facade.user_access_control import AccessControlLevel, UserAccessControl@@ -59,7 +60,9 @@ def visible_suggestions(kind: WarehouseSuggestionKind | None = None,status: WarehouseSuggestionStatus | None = None,) -> tuple[QuerySet[WarehouseSuggestion], SubjectAccess]:- suggestions = WarehouseSuggestion.objects.for_team(team_id)+ suggestions = WarehouseSuggestion.objects.for_team(team_id).exclude(+ status=WarehouseSuggestionStatus.PROPOSED, surfaced_at__isnull=True+ )if suggestion_id is not None:suggestions = suggestions.filter(id=suggestion_id)if kind is not None:@@ -67,7 +70,12 @@ def visible_suggestions(if status is not None:suggestions = suggestions.filter(status=status)access = subject_access(team_id, user_access_control, suggestions)- visible = suggestions.filter(access.readable_q()).select_related("reviewed_by").order_by("-score", "id")+ visible = (+ suggestions.filter(access.readable_q())+ .select_related("reviewed_by")+ .annotate(kind_position=_kind_position(RULES.lifecycle.kind_order))+ .order_by("kind_position", "-score", "id")+ )return visible, access@@ -96,3 +104,17 @@ def _allowed()for subject_kind, allowed_ids in ALLOWED_SUBJECT_IDS.items()}+++def readable_table_ids(+ team_id: int, user_access_control: "UserAccessControl", table_ids: Collection[UUID]+) -> frozenset[UUID]:+ return ALLOWED_SUBJECT_IDS[WarehouseSuggestionSubjectKind.TABLE](team_id, user_access_control, ids=table_ids)+++def _kind_position(kind_order: Sequence[WarehouseSuggestionKind]) -> Case:+ return Case(+ *(When(kind=kind, then=Value(position)) for position, kind in enumerate(kind_order)),+ default=Value(len(kind_order)),+ output_field=IntegerField(),+ )diff --git a/products/warehouse_suggestions/backend/logic/candidates/__init__.py b/products/warehouse_suggestions/backend/logic/candidates/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/warehouse_suggestions/backend/logic/candidates/base.py b/products/warehouse_suggestions/backend/logic/candidates/base.pynew file mode 100644index 000000000000..af1ad8430251--- /dev/null+++ b/products/warehouse_suggestions/backend/logic/candidates/base.py@@ -0,0 +1,112 @@+import hashlib+from abc import ABC, abstractmethod+from collections.abc import Mapping+from math import ceil+from typing import Any, ClassVar++from posthog.dataclasses import frozen++from products.data_modeling.backend.facade.contracts import SavedQueryDefinition++from ...facade.contracts import PAYLOAD_VERSION, SuggestionDraft, SuggestionPayload+from ...facade.enums import WarehouseSuggestionKind+from ..inventory import TeamInventory+from ..reads import Subject, TeamReads+from ..rules import Rules, rules_version++DAYS_PER_MONTH = 30+MILLISECONDS_PER_SECOND = 1000+++@frozen+class CandidateContext:+ team_id: int+ reads: TeamReads+ inventory: TeamInventory+ rules: Rules+ run_id: str++ @property+ def days_observed(self) -> int:+ return max(1, min(self.reads.days_with_data, self.rules.window_days))++ @property+ def month_scale(self) -> float:+ return DAYS_PER_MONTH / self.days_observed++ def scaled_floor(self, floor: int) -> int:+ return max(1, ceil(floor * self.days_observed / self.rules.window_days))++ def is_suggestible_view(self, saved_query: SavedQueryDefinition) -> bool:+ return (+ not saved_query.is_test+ and not saved_query.is_managed+ and saved_query.origin not in self.rules.subjects.excluded_view_origins+ )+++@frozen+class Rejection:+ subject: Subject+ reason: str+++@frozen+class CandidateResult:+ drafts: tuple[SuggestionDraft, ...]+ rejections: tuple[Rejection, ...]+ skipped_reason: str | None = None+++class Candidate(ABC):+ kind: ClassVar[WarehouseSuggestionKind]++ @abstractmethod+ def evaluate(self, context: CandidateContext) -> CandidateResult: ...++ @abstractmethod+ def is_resolved(self, context: CandidateContext, subject: Subject) -> bool: ...++ def draft(+ self,+ context: CandidateContext,+ subject: Subject,+ payload: SuggestionPayload,+ *,+ score: float,+ score_inputs: Mapping[str, float],+ ) -> SuggestionDraft:+ return SuggestionDraft(+ kind=self.kind,+ fingerprint=fingerprint(self.kind, subject),+ subject_kind=subject.kind,+ subject_id=subject.id,+ payload=payload,+ payload_version=PAYLOAD_VERSION,+ rules_version=rules_version(context.rules),+ evidence=evidence_of(context, subject),+ evidence_window_start=context.reads.window.starts_at,+ evidence_window_end=context.reads.window.ends_at,+ score=score,+ score_inputs=dict(score_inputs),+ run_id=context.run_id,+ )+++def fingerprint(kind: WarehouseSuggestionKind, subject: Subject) -> str:+ return hashlib.sha256(f"{kind}:{subject.kind}:{subject.id}".encode()).hexdigest()+++def evidence_of(context: CandidateContext, subject: Subject) -> dict[str, Any]:+ reads = context.reads.reads_of(subject)+ if reads is None:+ return {"days_with_data": context.reads.days_with_data, "human_requests": 0, "human_users": 0}+ return {+ "days_with_data": context.reads.days_with_data,+ "human_requests": reads.human_requests,+ "human_users": reads.human_users,+ "human_days": reads.human_days,+ "background_requests": reads.background_requests,+ "requests_by_surface": {surface.value: count for surface, count in reads.requests_by_surface.items()},+ "last_read_at": reads.last_read_at.isoformat(),+ }diff --git a/products/warehouse_suggestions/backend/logic/candidates/certify.py b/products/warehouse_suggestions/backend/logic/candidates/certify.pynew file mode 100644index 000000000000..caf329bcf1c2--- /dev/null+++ b/products/warehouse_suggestions/backend/logic/candidates/certify.py@@ -0,0 +1,68 @@+from ...facade.contracts import CertifyPayload+from ...facade.enums import WarehouseSuggestionKind, WarehouseSuggestionSubjectKind+from ..reads import Subject, SubjectReads+from .base import Candidate, CandidateContext, CandidateResult, Rejection+++class CertifyCandidate(Candidate):+ kind = WarehouseSuggestionKind.CERTIFY++ def evaluate(self, context: CandidateContext) -> CandidateResult:+ ranked = sorted(+ (+ (subject, reads)+ for subject, reads in context.reads.subjects.items()+ if reads.human_requests > 0 and self._is_certifiable(context, subject)+ ),+ key=lambda item: (_traffic(item[1]), str(item[0].id)),+ reverse=True,+ )+ top_count = max(1, round(len(ranked) * context.rules.certify.top_share)) if ranked else 0+ drafts = []+ rejections = []+ for position, (subject, reads) in enumerate(ranked):+ reason = self._rejection(context, subject, reads, in_top_share=position < top_count)+ if reason is not None:+ rejections.append(Rejection(subject=subject, reason=reason))+ continue+ drafts.append(+ self.draft(+ context,+ subject,+ CertifyPayload(subject_name=context.inventory.name_of(subject) or ""),+ score=float(_traffic(reads)),+ score_inputs={"human_requests": reads.human_requests, "human_users": reads.human_users},+ )+ )+ return CandidateResult(drafts=tuple(drafts), rejections=tuple(rejections))++ def is_resolved(self, context: CandidateContext, subject: Subject) -> bool:+ return context.inventory.name_of(subject) is None or subject in context.inventory.certified++ def _is_certifiable(self, context: CandidateContext, subject: Subject) -> bool:+ if subject.kind == WarehouseSuggestionSubjectKind.TABLE:+ return subject.id in context.inventory.table_names+ saved_query = context.inventory.saved_queries.get(subject.id)+ return saved_query is not None and context.is_suggestible_view(saved_query)++ def _rejection(+ self, context: CandidateContext, subject: Subject, reads: SubjectReads, *, in_top_share: bool+ ) -> str | None:+ rules = context.rules.certify+ min_days = context.scaled_floor(rules.min_days)+ if not in_top_share:+ return f"outside the top {rules.top_share:.0%} by requests times people"+ if subject in context.inventory.certified:+ return "already has a certification"+ users_needed = rules.users_needed(context.reads.readers)+ if reads.human_users < users_needed:+ return f"read by {reads.human_users} people, needs {users_needed}"+ if reads.human_days < min_days:+ return f"read on {reads.human_days} days, needs {min_days}"+ if len(reads.surfaces) < rules.min_surfaces:+ return f"read from {len(reads.surfaces)} surfaces, needs {rules.min_surfaces}"+ return None+++def _traffic(reads: SubjectReads) -> int:+ return reads.human_requests * reads.human_usersdiff --git a/products/warehouse_suggestions/backend/logic/candidates/deprecate.py b/products/warehouse_suggestions/backend/logic/candidates/deprecate.pynew file mode 100644index 000000000000..5021eed3c15e--- /dev/null+++ b/products/warehouse_suggestions/backend/logic/candidates/deprecate.py@@ -0,0 +1,89 @@+from uuid import UUID++from products.data_modeling.backend.facade.api import dependent_saved_query_ids, upstream_table_refs+from products.data_modeling.backend.facade.contracts import SavedQueryDefinition++from ...facade.contracts import DeprecatePayload+from ...facade.enums import WarehouseSuggestionKind, WarehouseSuggestionSubjectKind+from ..reads import Subject+from .base import MILLISECONDS_PER_SECOND, Candidate, CandidateContext, CandidateResult, Rejection+++class DeprecateCandidate(Candidate):+ kind = WarehouseSuggestionKind.DEPRECATE++ def evaluate(self, context: CandidateContext) -> CandidateResult:+ rules = context.rules.deprecate+ if context.reads.days_with_data < rules.min_days_with_data:+ return CandidateResult(+ drafts=(),+ rejections=(),+ skipped_reason=(+ f"needs {rules.min_days_with_data} days of read data, has {context.reads.days_with_data}"+ ),+ )+ unread = [+ saved_query+ for saved_query in context.inventory.saved_queries.values()+ if saved_query.materializes+ and context.is_suggestible_view(saved_query)+ and not _is_read(context, _subject(saved_query))+ ]+ dependents = dependent_saved_query_ids(context.team_id, [saved_query.id for saved_query in unread])+ drafts = []+ rejections = []+ for saved_query in unread:+ subject = _subject(saved_query)+ reason = self._rejection(context, saved_query, has_dependents=bool(dependents.get(saved_query.id)))+ if reason is not None:+ rejections.append(Rejection(subject=subject, reason=reason))+ continue+ refreshes = context.reads.refreshes.get(saved_query.id)+ seconds = refreshes.duration_ms / MILLISECONDS_PER_SECOND * context.month_scale if refreshes else 0.0+ read_bytes = refreshes.read_bytes * context.month_scale if refreshes else 0.0+ drafts.append(+ self.draft(+ context,+ subject,+ DeprecatePayload(+ subject_name=saved_query.name,+ refresh_seconds_per_month=seconds,+ refresh_bytes_per_month=read_bytes,+ ),+ score=max(seconds / rules.seconds_floor, read_bytes / rules.bytes_floor),+ score_inputs={"refresh_seconds_per_month": seconds, "refresh_bytes_per_month": read_bytes},+ )+ )+ return CandidateResult(drafts=tuple(drafts), rejections=tuple(rejections))++ def is_resolved(self, context: CandidateContext, subject: Subject) -> bool:+ saved_query = context.inventory.saved_queries.get(subject.id)+ return saved_query is None or not saved_query.materializes or _is_read(context, subject)++ def _rejection(+ self, context: CandidateContext, saved_query: SavedQueryDefinition, *, has_dependents: bool+ ) -> str | None:+ if saved_query.created_at > context.reads.window.starts_at:+ return "created after the read window started"+ if has_dependents:+ return "other views read from it"+ if self._reads_direct_source(context, saved_query.id):+ return "reads a direct-connection source, whose reads are not logged"+ return None++ def _reads_direct_source(self, context: CandidateContext, saved_query_id: UUID) -> bool:+ return any(+ ref.warehouse_table_id is not None and UUID(ref.warehouse_table_id) in context.inventory.direct_table_ids+ for ref in upstream_table_refs(context.team_id, saved_query_id)+ )+++def _is_read(context: CandidateContext, subject: Subject) -> bool:+ reads = context.reads.reads_of(subject)+ if reads is None:+ return False+ return context.rules.deprecate.counts_background_reads or reads.human_requests > 0+++def _subject(saved_query: SavedQueryDefinition) -> Subject:+ return Subject(kind=WarehouseSuggestionSubjectKind.SAVED_QUERY, id=saved_query.id)diff --git a/products/warehouse_suggestions/backend/logic/candidates/materialize.py b/products/warehouse_suggestions/backend/logic/candidates/materialize.pynew file mode 100644index 000000000000..b7cdba52b8cf--- /dev/null+++ b/products/warehouse_suggestions/backend/logic/candidates/materialize.py@@ -0,0 +1,198 @@+from collections.abc import Iterable+from datetime import timedelta+from uuid import UUID++from posthog.dataclasses import frozen+from posthog.exceptions_capture import capture_exception++from products.data_modeling.backend.facade.api import (+ MissingDagNodeError,+ SavedQueryFrequencyBounds,+ check_incremental_eligibility,+ saved_query_target_bounds,+ upstream_table_refs,+)+from products.data_modeling.backend.facade.contracts import SavedQueryDefinition++from ...facade.contracts import MaterializePayload, SourceRef+from ...facade.enums import WarehouseSuggestionKind, WarehouseSuggestionSubjectKind+from ..reads import Subject, SubjectReads+from .base import DAYS_PER_MONTH, MILLISECONDS_PER_SECOND, Candidate, CandidateContext, CandidateResult, Rejection++SECONDS_PER_MONTH = DAYS_PER_MONTH * 24 * 60 * 60+++@frozen+class SavingsEstimate:+ interval: timedelta+ seconds_saved: float+ bytes_saved: float+ clears_a_floor: bool+ score: float+++@frozen+class ClassifiedSources:+ live: tuple[SourceRef, ...]+ unknown: tuple[SourceRef, ...]+++@frozen+class _Proposal:+ payload: MaterializePayload+ estimate: SavingsEstimate+++class MaterializeCandidate(Candidate):+ kind = WarehouseSuggestionKind.MATERIALIZE++ def evaluate(self, context: CandidateContext) -> CandidateResult:+ drafts = []+ rejections = []+ for saved_query in context.inventory.saved_queries.values():+ subject = Subject(kind=WarehouseSuggestionSubjectKind.SAVED_QUERY, id=saved_query.id)+ reads = context.reads.reads_of(subject)+ if reads is None or reads.human_requests == 0 or not self._is_unmaterialized(context, saved_query):+ continue+ outcome = self._propose(context, saved_query, reads)+ if isinstance(outcome, str):+ rejections.append(Rejection(subject=subject, reason=outcome))+ continue+ drafts.append(+ self.draft(+ context,+ subject,+ outcome.payload,+ score=outcome.estimate.score,+ score_inputs={+ "seconds_saved_per_month": outcome.estimate.seconds_saved,+ "bytes_saved_per_month": outcome.estimate.bytes_saved,+ "refresh_interval_seconds": outcome.estimate.interval.total_seconds(),+ },+ )+ )+ return CandidateResult(drafts=tuple(drafts), rejections=tuple(rejections))++ def is_resolved(self, context: CandidateContext, subject: Subject) -> bool:+ saved_query = context.inventory.saved_queries.get(subject.id)+ return saved_query is None or saved_query.materializes++ def _is_unmaterialized(self, context: CandidateContext, saved_query: SavedQueryDefinition) -> bool:+ return not saved_query.materializes and context.is_suggestible_view(saved_query)++ def _propose(+ self, context: CandidateContext, saved_query: SavedQueryDefinition, reads: SubjectReads+ ) -> _Proposal | str:+ rejection = self._read_floor_rejection(context, reads)+ if rejection is not None:+ return rejection+ if context.rules.materialize.require_incremental_eligibility and not _can_refresh_incrementally(+ saved_query.hogql+ ):+ return "its query cannot refresh incrementally"+ frequency = saved_query_target_bounds(context.team_id, saved_query.id)+ if frequency is None:+ capture_exception(MissingDagNodeError(f"Saved query {saved_query.id} has no DAG node"))+ return "it has no node in a DAG"+ intervals = allowed_intervals(context, frequency.bounds.allowed, reads)+ if not intervals:+ return f"its sources allow no refresh interval up to {context.rules.refresh.max_interval}"+ estimate = next(+ (+ estimate+ for estimate in (estimate_savings(context, reads, interval) for interval in intervals)+ if estimate.clears_a_floor+ ),+ None,+ )+ if estimate is None:+ return "savings stay under the floors at every allowed refresh interval"+ sources = _classify_sources(context, saved_query.id, frequency)+ freshness_today = int(frequency.max_data_age.total_seconds()) or None+ interval_seconds = int(estimate.interval.total_seconds())+ return _Proposal(+ payload=MaterializePayload(+ subject_name=saved_query.name,+ refresh_interval_seconds=interval_seconds,+ saves_seconds_per_month=estimate.seconds_saved,+ saves_bytes_per_month=estimate.bytes_saved,+ freshness_today_seconds=freshness_today,+ freshness_after_seconds=interval_seconds + (freshness_today or 0),+ live_sources=sources.live,+ unknown_sources=sources.unknown,+ ),+ estimate=estimate,+ )++ def _read_floor_rejection(self, context: CandidateContext, reads: SubjectReads) -> str | None:+ rules = context.rules.materialize+ min_days = context.scaled_floor(rules.min_days)+ min_requests = context.scaled_floor(rules.min_requests)+ if reads.human_days < min_days:+ return f"read on {reads.human_days} days, needs {min_days}"+ if reads.human_requests < min_requests:+ return f"read {reads.human_requests} times, needs {min_requests}"+ if max(reads.human_users, len(reads.surfaces)) < rules.min_users_or_surfaces:+ return f"read by too few people or surfaces, needs {rules.min_users_or_surfaces}"+ if reads.alone_reads < rules.min_alone_reads:+ return f"read on its own {reads.alone_reads} times, needs {rules.min_alone_reads} to know its cost"+ return None+++def _can_refresh_incrementally(hogql: str) -> bool:+ eligibility = check_incremental_eligibility(hogql, None)+ return eligibility.eligible and bool(eligibility.key_candidates) and bool(eligibility.unique_key_candidates)+++def allowed_intervals(context: CandidateContext, allowed: Iterable[timedelta], reads: SubjectReads) -> list[timedelta]:+ refresh = context.rules.refresh+ intervals = sorted(interval for interval in allowed if interval <= refresh.max_interval)+ read_day_share = reads.human_days / context.days_observed+ if read_day_share < refresh.min_read_day_share_below_max_interval:+ return [interval for interval in intervals if interval >= refresh.max_interval]+ return intervals+++def estimate_savings(context: CandidateContext, reads: SubjectReads, interval: timedelta) -> SavingsEstimate:+ rules = context.rules.materialize+ scale = context.month_scale+ refreshes_per_month = SECONDS_PER_MONTH / interval.total_seconds()+ body_seconds = reads.alone_duration_ms_median / MILLISECONDS_PER_SECOND+ read_seconds = reads.human_duration_ms / MILLISECONDS_PER_SECOND * scale+ read_bytes = reads.human_read_bytes * scale+ seconds_saved = min(read_seconds, reads.human_reads * body_seconds * scale) - refreshes_per_month * body_seconds+ bytes_saved = (+ min(read_bytes, reads.human_reads * reads.alone_read_bytes_median * scale)+ - refreshes_per_month * reads.alone_read_bytes_median+ )+ clears_time = seconds_saved >= rules.min_seconds_saved and seconds_saved >= rules.min_saved_share * read_seconds+ clears_bytes = bytes_saved >= rules.min_bytes_saved and bytes_saved >= rules.min_saved_share * read_bytes+ return SavingsEstimate(+ interval=interval,+ seconds_saved=seconds_saved,+ bytes_saved=bytes_saved,+ clears_a_floor=clears_time or clears_bytes,+ score=max(seconds_saved / rules.min_seconds_saved, bytes_saved / rules.min_bytes_saved),+ )+++def _classify_sources(+ context: CandidateContext, saved_query_id: UUID, frequency: SavedQueryFrequencyBounds+) -> ClassifiedSources:+ best_effort_table_ids = {+ identity.warehouse_table_id+ for node_id in frequency.best_effort_source_ids+ if (identity := frequency.identities.get(node_id)) is not None and identity.warehouse_table_id is not None+ }+ live = []+ unknown = []+ for ref in sorted(upstream_table_refs(context.team_id, saved_query_id), key=lambda ref: ref.name):+ table_id = UUID(ref.warehouse_table_id) if ref.warehouse_table_id else None+ if table_id is None and not ref.is_posthog_table:+ continue+ source = SourceRef(name=ref.name, warehouse_table_id=table_id)+ if table_id is None or table_id in context.inventory.direct_table_ids:+ live.append(source)+ elif ref.warehouse_table_id in best_effort_table_ids:+ unknown.append(source)+ return ClassifiedSources(live=tuple(live), unknown=tuple(unknown))diff --git a/products/warehouse_suggestions/backend/logic/candidates/registry.py b/products/warehouse_suggestions/backend/logic/candidates/registry.pynew file mode 100644index 000000000000..fe3d19b12485--- /dev/null+++ b/products/warehouse_suggestions/backend/logic/candidates/registry.py@@ -0,0 +1,17 @@+from collections.abc import Mapping++from ...facade.enums import WarehouseSuggestionKind+from .base import Candidate, CandidateContext, CandidateResult+from .certify import CertifyCandidate+from .deprecate import DeprecateCandidate+from .materialize import MaterializeCandidate++CANDIDATES: Mapping[WarehouseSuggestionKind, Candidate] = {+ WarehouseSuggestionKind.CERTIFY: CertifyCandidate(),+ WarehouseSuggestionKind.DEPRECATE: DeprecateCandidate(),+ WarehouseSuggestionKind.MATERIALIZE: MaterializeCandidate(),+}+++def evaluate_candidates(context: CandidateContext) -> dict[WarehouseSuggestionKind, CandidateResult]:+ return {kind: candidate.evaluate(context) for kind, candidate in CANDIDATES.items()}diff --git a/products/warehouse_suggestions/backend/logic/inventory.py b/products/warehouse_suggestions/backend/logic/inventory.pynew file mode 100644index 000000000000..1fc792dec4ca--- /dev/null+++ b/products/warehouse_suggestions/backend/logic/inventory.py@@ -0,0 +1,51 @@+from collections.abc import Mapping+from typing import TYPE_CHECKING+from uuid import UUID++from posthog.dataclasses import frozen++from products.data_catalog.backend.facade.api import certifications_for_team+from products.data_modeling.backend.facade.api import backing_table_ids_by_saved_query, saved_query_definitions+from products.data_modeling.backend.facade.contracts import SavedQueryDefinition+from products.warehouse_sources.backend.facade.api import all_queryable_table_names, direct_access_table_ids++from ..facade.enums import WarehouseSuggestionSubjectKind+from .reads import Subject++if TYPE_CHECKING:+ from posthog.models.team import Team+++@frozen+class TeamInventory:+ saved_queries: Mapping[UUID, SavedQueryDefinition]+ table_names: Mapping[UUID, str]+ certified: frozenset[Subject]+ direct_table_ids: frozenset[UUID]++ def name_of(self, subject: Subject) -> str | None:+ if subject.kind == WarehouseSuggestionSubjectKind.SAVED_QUERY:+ saved_query = self.saved_queries.get(subject.id)+ return saved_query.name if saved_query else None+ return self.table_names.get(subject.id)+++def load_inventory(team: "Team") -> TeamInventory:+ table_names = all_queryable_table_names(team.pk)+ backing_table_ids = backing_table_ids_by_saved_query(team.pk, table_ids=table_names.keys())+ return TeamInventory(+ saved_queries={saved_query.id: saved_query for saved_query in saved_query_definitions(team.pk)},+ table_names={table_id: name for table_id, name in table_names.items() if table_id not in backing_table_ids},+ certified=frozenset(_certified_subjects(team)),+ direct_table_ids=frozenset(direct_access_table_ids(team.pk)),+ )+++def _certified_subjects(team: "Team") -> list[Subject]:+ subjects = []+ for saved_query_id, table_id in certifications_for_team(team).values_list("saved_query_id", "table_id"):+ if saved_query_id is not None:+ subjects.append(Subject(kind=WarehouseSuggestionSubjectKind.SAVED_QUERY, id=saved_query_id))+ if table_id is not None:+ subjects.append(Subject(kind=WarehouseSuggestionSubjectKind.TABLE, id=table_id))+ return subjectsdiff --git a/products/warehouse_suggestions/backend/logic/job.py b/products/warehouse_suggestions/backend/logic/job.pynew file mode 100644index 000000000000..6260c25601c3--- /dev/null+++ b/products/warehouse_suggestions/backend/logic/job.py@@ -0,0 +1,94 @@+from datetime import date, datetime+from enum import StrEnum++from django.db import transaction+from django.utils import timezone++from posthog.dataclasses import frozen+from posthog.models.team import Team+from posthog.models.team.extensions import get_or_create_team_extension++from ..facade.enums import WarehouseSuggestionKind, WarehouseSuggestionStatus+from ..models import WarehouseSuggestion, WarehouseSuggestionTeamConfig+from .candidates.base import CandidateContext, CandidateResult+from .candidates.registry import evaluate_candidates+from .inventory import load_inventory+from .lifecycle import LifecycleResult, apply_run+from .reads import ReadWindow, RollupDays, TeamReads, read_rollup_days, read_team_reads+from .rules import RULES, EligibilityRules, Rules+++class TeamRunStatus(StrEnum):+ DISABLED = "disabled"+ NOT_ELIGIBLE = "not_eligible"+ PROCESSED = "processed"+++@frozen+class TeamRunResult:+ team_id: int+ status: TeamRunStatus+ drafts: int = 0+ lifecycle: LifecycleResult | None = None+++def run_team(+ team_id: int,+ *,+ run_id: str,+ today: date,+ rollup_days: RollupDays,+ now: datetime | None = None,+ rules: Rules = RULES,+) -> TeamRunResult:+ now = now or timezone.now()+ team = Team.objects.get(id=team_id)+ if not get_or_create_team_extension(team, WarehouseSuggestionTeamConfig).enabled:+ return TeamRunResult(team_id=team_id, status=TeamRunStatus.DISABLED)+ reads = read_team_reads(team_id, ReadWindow.ending(today, rules), rules, rollup_days)+ eligible = is_eligible(reads, rules.eligibility)+ status = TeamRunStatus.PROCESSED if eligible else TeamRunStatus.NOT_ELIGIBLE+ if not eligible and not _has_open_suggestions(team_id):+ with transaction.atomic():+ _record_run(_locked_config(team_id), reads, eligible=False, now=now)+ return TeamRunResult(team_id=team_id, status=status)+ context = build_context(team, reads, run_id=run_id, rules=rules)+ drafts = [draft for result in evaluate_candidates(context).values() for draft in result.drafts] if eligible else []+ with transaction.atomic():+ config = _locked_config(team_id)+ _record_run(config, reads, eligible=eligible, now=now)+ lifecycle = apply_run(context, drafts, now, surface=eligible and config.paused_reason is None)+ return TeamRunResult(team_id=team_id, status=status, drafts=len(drafts), lifecycle=lifecycle)+++def explain_team(+ team_id: int, *, today: date, rules: Rules = RULES+) -> tuple[CandidateContext, dict[WarehouseSuggestionKind, CandidateResult]]:+ team = Team.objects.get(id=team_id)+ window = ReadWindow.ending(today, rules)+ reads = read_team_reads(team_id, window, rules, read_rollup_days(window))+ context = build_context(team, reads, run_id="explain", rules=rules)+ return context, evaluate_candidates(context)+++def is_eligible(reads: TeamReads, rules: EligibilityRules) -> bool:+ return reads.view_reads >= rules.min_view_reads or bool(reads.refreshes)+++def build_context(team: Team, reads: TeamReads, *, run_id: str, rules: Rules) -> CandidateContext:+ return CandidateContext(team_id=team.pk, reads=reads, inventory=load_inventory(team), rules=rules, run_id=run_id)+++def _has_open_suggestions(team_id: int) -> bool:+ return WarehouseSuggestion.objects.for_team(team_id).filter(status=WarehouseSuggestionStatus.PROPOSED).exists()+++def _locked_config(team_id: int) -> WarehouseSuggestionTeamConfig:+ return WarehouseSuggestionTeamConfig.objects.select_for_update().get(team_id=team_id)+++def _record_run(config: WarehouseSuggestionTeamConfig, reads: TeamReads, *, eligible: bool, now: datetime) -> None:+ config.eligible = eligible+ config.days_with_data = reads.days_with_data+ config.last_run_at = now+ config.save(update_fields=["eligible", "days_with_data", "last_run_at"])diff --git a/products/warehouse_suggestions/backend/logic/lifecycle.py b/products/warehouse_suggestions/backend/logic/lifecycle.pynew file mode 100644index 000000000000..4149d6330c09--- /dev/null+++ b/products/warehouse_suggestions/backend/logic/lifecycle.py@@ -0,0 +1,188 @@+from collections import Counter, defaultdict, deque+from collections.abc import Collection, Sequence+from datetime import datetime, time, timedelta+from uuid import UUID++from django.db.models import F++from posthog.dataclasses import frozen++from ..facade.contracts import SuggestionAlreadyDecidedError, SuggestionDraft+from ..facade.enums import (+ WarehouseSuggestionDismissalReason,+ WarehouseSuggestionKind,+ WarehouseSuggestionStatus,+ WarehouseSuggestionSubjectKind,+)+from ..models import WarehouseSuggestion+from .candidates.base import CandidateContext+from .candidates.registry import CANDIDATES+from .reads import Subject+from .rules import LifecycleRules, kind_position+from .suggestions import transition_to, upsert_suggestions+++@frozen+class LifecycleResult:+ reproposed: int+ revived: int+ auto_resolved: int+ expired: int+ surfaced: int+++@frozen+class Reopened:+ reproposed: int+ revived: int+++def apply_run(+ context: CandidateContext, drafts: Sequence[SuggestionDraft], now: datetime, *, surface: bool+) -> LifecycleResult:+ """Apply one run's drafts to the stored suggestions, then show new ones when `surface` is set."""+ fingerprints = {draft.fingerprint for draft in drafts}+ reopened = _reopen(context, drafts)+ upsert_suggestions(context.team_id, drafts)+ auto_resolved = _auto_resolve(context, fingerprints)+ expired = _expire(context, fingerprints, now)+ surfaced = _surface(context.team_id, context.rules.lifecycle, now) if surface else 0+ return LifecycleResult(+ reproposed=reopened.reproposed,+ revived=reopened.revived,+ auto_resolved=auto_resolved,+ expired=expired,+ surfaced=surfaced,+ )+++REVIVABLE_STATUSES = (WarehouseSuggestionStatus.EXPIRED, WarehouseSuggestionStatus.AUTO_RESOLVED)+++def _reopen(context: CandidateContext, drafts: Sequence[SuggestionDraft]) -> Reopened:+ """Move closed suggestions that match a draft back to proposed and unshown, dismissed ones only if they earn it."""+ drafts_by_fingerprint = {draft.fingerprint: draft for draft in drafts}+ suggestions = WarehouseSuggestion.objects.for_team(context.team_id)+ closed = suggestions.filter(+ fingerprint__in=drafts_by_fingerprint,+ status__in=[WarehouseSuggestionStatus.DISMISSED, *REVIVABLE_STATUSES],+ )+ reproposed: list[UUID] = []+ revived: list[UUID] = []+ for row in closed:+ if row.status in REVIVABLE_STATUSES:+ if _move(row, context.team_id, WarehouseSuggestionStatus.PROPOSED):+ revived.append(row.id)+ elif _earns_reproposal(row, drafts_by_fingerprint[row.fingerprint], context.rules.lifecycle):+ if _move(row, context.team_id, WarehouseSuggestionStatus.PROPOSED):+ reproposed.append(row.id)+ suggestions.filter(id__in=reproposed).update(reproposed_count=F("reproposed_count") + 1)+ suggestions.filter(id__in=[*reproposed, *revived]).update(surfaced_at=None)+ return Reopened(reproposed=len(reproposed), revived=len(revived))+++def _earns_reproposal(row: WarehouseSuggestion, draft: SuggestionDraft, rules: LifecycleRules) -> bool:+ """Whether a not-now dismissal now scores above, and at least `reproposal_score_multiple` times, its old score."""+ return (+ row.dismissal_reason == WarehouseSuggestionDismissalReason.NOT_NOW+ and row.dismissed_at_score is not None+ and draft.score > row.dismissed_at_score+ and draft.score >= rules.reproposal_score_multiple * row.dismissed_at_score+ )+++def _auto_resolve(context: CandidateContext, refreshed_fingerprints: Collection[str]) -> int:+ """Auto-resolve proposed suggestions with no draft this run whose subject no longer needs them."""+ open_rows = (+ WarehouseSuggestion.objects.for_team(context.team_id)+ .filter(status=WarehouseSuggestionStatus.PROPOSED)+ .exclude(fingerprint__in=refreshed_fingerprints)+ )+ return sum(+ _move(row, context.team_id, WarehouseSuggestionStatus.AUTO_RESOLVED)+ for row in open_rows+ if CANDIDATES[WarehouseSuggestionKind(row.kind)].is_resolved(context, _subject(row))+ )+++def _expire(context: CandidateContext, refreshed_fingerprints: Collection[str], now: datetime) -> int:+ """Expire proposed suggestions with no draft for `expire_after_days`, unless the read data is too short to tell."""+ rules = context.rules.lifecycle+ if context.reads.recent_days_with_data < rules.expire_after_days:+ return 0+ stale = (+ WarehouseSuggestion.objects.for_team(context.team_id)+ .filter(+ status=WarehouseSuggestionStatus.PROPOSED, last_seen_at__lt=now - timedelta(days=rules.expire_after_days)+ )+ .exclude(fingerprint__in=refreshed_fingerprints)+ )+ return sum(_move(row, context.team_id, WarehouseSuggestionStatus.EXPIRED) for row in stale)+++def _surface(team_id: int, rules: LifecycleRules, now: datetime) -> int:+ """Show waiting suggestions within the daily, open and per-kind limits, and return how many were shown."""+ suggestions = WarehouseSuggestion.objects.for_team(team_id)+ start_of_day = datetime.combine(now.date(), time.min, tzinfo=now.tzinfo)+ open_kinds = Counter(+ suggestions.filter(status=WarehouseSuggestionStatus.PROPOSED, surfaced_at__isnull=False).values_list(+ "kind", flat=True+ )+ )+ slots = min(+ rules.max_surfaced_per_day - suggestions.filter(surfaced_at__gte=start_of_day).count(),+ rules.max_open - open_kinds.total(),+ )+ if slots <= 0:+ return 0+ first_week = not suggestions.filter(+ surfaced_at__lt=start_of_day - timedelta(days=rules.first_week_runs - 1)+ ).exists()+ waiting = suggestions.filter(status=WarehouseSuggestionStatus.PROPOSED, surfaced_at__isnull=True).only(+ "id", "kind", "score"+ )+ chosen = _pick_in_turns(+ list(waiting),+ rules.first_week_kind_order if first_week else rules.kind_order,+ slots,+ open_kinds,+ rules.max_open_per_kind,+ )+ return suggestions.filter(id__in=chosen).update(surfaced_at=now)+++def _pick_in_turns(+ waiting: Sequence[WarehouseSuggestion],+ kind_order: Sequence[WarehouseSuggestionKind],+ slots: int,+ open_kinds: Counter[str],+ max_open_per_kind: int,+) -> list[UUID]:+ """Pick up to `slots` suggestions in turns across `kind_order`, highest score first, skipping full kinds."""+ queues: defaultdict[str, deque[WarehouseSuggestion]] = defaultdict(deque)+ for row in sorted(waiting, key=lambda row: (-row.score, str(row.id))):+ queues[row.kind].append(row)+ turns = sorted(queues, key=lambda kind: (kind_position(kind_order, kind), kind))+ open_now = Counter(open_kinds)+ chosen: list[UUID] = []+ while len(chosen) < slots:+ ready = [kind for kind in turns if queues[kind] and open_now[kind] < max_open_per_kind]+ if not ready:+ break+ for kind in ready[: slots - len(chosen)]:+ chosen.append(queues[kind].popleft().id)+ open_now[kind] += 1+ return chosen+++def _move(row: WarehouseSuggestion, team_id: int, status: WarehouseSuggestionStatus) -> bool:+ """Move a suggestion to `status` as the system, and return False when a person already decided it."""+ try:+ transition_to(row.id, team_id, status, user_id=None)+ except SuggestionAlreadyDecidedError:+ return False+ return True+++def _subject(row: WarehouseSuggestion) -> Subject:+ return Subject(kind=WarehouseSuggestionSubjectKind(row.subject_kind), id=row.subject_id)diff --git a/products/warehouse_suggestions/backend/logic/payloads.py b/products/warehouse_suggestions/backend/logic/payloads.pynew file mode 100644index 000000000000..a759816541ea--- /dev/null+++ b/products/warehouse_suggestions/backend/logic/payloads.py@@ -0,0 +1,77 @@+import json+from collections.abc import Collection, Iterable, Mapping+from dataclasses import asdict+from typing import Any+from uuid import UUID++from ..facade.contracts import (+ PAYLOAD_VERSION,+ CertifyPayload,+ DeprecatePayload,+ MaterializePayload,+ MaterializeSuggestionPayload,+ SourceRef,+ SuggestionPayload,+ SuggestionPayloadView,+ UnsupportedPayloadVersionError,+ VisibleSources,+)+from ..facade.enums import WarehouseSuggestionKind++SOURCE_FIELDS = ("live_sources", "unknown_sources")+++def payload_to_json(payload: SuggestionPayload) -> dict[str, Any]:+ return json.loads(json.dumps(asdict(payload), default=str))+++def payload_from_json(+ kind: WarehouseSuggestionKind, payload_version: int, data: Mapping[str, Any]+) -> SuggestionPayload:+ if payload_version != PAYLOAD_VERSION:+ raise UnsupportedPayloadVersionError(payload_version)+ if kind == WarehouseSuggestionKind.CERTIFY:+ return CertifyPayload(**data)+ if kind == WarehouseSuggestionKind.DEPRECATE:+ return DeprecatePayload(**data)+ sources = {field: tuple(_source_ref(source) for source in data[field]) for field in SOURCE_FIELDS}+ return MaterializePayload(**{**data, **sources})+++def source_table_ids(payloads: Iterable[SuggestionPayload]) -> set[UUID]:+ return {+ source.warehouse_table_id+ for payload in payloads+ if isinstance(payload, MaterializePayload)+ for source in (*payload.live_sources, *payload.unknown_sources)+ if source.warehouse_table_id is not None+ }+++def payload_view(payload: SuggestionPayload, readable_table_ids: Collection[UUID]) -> SuggestionPayloadView:+ if not isinstance(payload, MaterializePayload):+ return payload+ return MaterializeSuggestionPayload(+ subject_name=payload.subject_name,+ refresh_interval_seconds=payload.refresh_interval_seconds,+ saves_seconds_per_month=payload.saves_seconds_per_month,+ saves_bytes_per_month=payload.saves_bytes_per_month,+ freshness_today_seconds=payload.freshness_today_seconds,+ freshness_after_seconds=payload.freshness_after_seconds,+ live_sources=_visible_sources(payload.live_sources, readable_table_ids),+ unknown_sources=_visible_sources(payload.unknown_sources, readable_table_ids),+ )+++def _visible_sources(sources: tuple[SourceRef, ...], readable_table_ids: Collection[UUID]) -> VisibleSources:+ names = tuple(+ source.name+ for source in sources+ if source.warehouse_table_id is None or source.warehouse_table_id in readable_table_ids+ )+ return VisibleSources(names=names, hidden_count=len(sources) - len(names))+++def _source_ref(source: Mapping[str, Any]) -> SourceRef:+ table_id = source["warehouse_table_id"]+ return SourceRef(name=source["name"], warehouse_table_id=UUID(table_id) if table_id else None)diff --git a/products/warehouse_suggestions/backend/logic/reads.py b/products/warehouse_suggestions/backend/logic/reads.pynew file mode 100644index 000000000000..92ca275bca3a--- /dev/null+++ b/products/warehouse_suggestions/backend/logic/reads.py@@ -0,0 +1,294 @@+from collections import defaultdict+from collections.abc import Mapping+from datetime import UTC, date, datetime, time, timedelta+from typing import Any+from uuid import UUID++from posthog.clickhouse.client import sync_execute+from posthog.clickhouse.query_tagging import Feature, Product, tag_queries+from posthog.clickhouse.warehouse_object_reads import WAREHOUSE_OBJECT_READS_DAILY_TABLE, ReadKind+from posthog.dataclasses import frozen++from ..facade.enums import WarehouseSuggestionSubjectKind+from .rules import Rules, Surface, SurfaceRules, TrafficRules++READS_QUERY_SETTINGS = {"max_execution_time": 30, "max_threads": 2}+FIRST_QUANTILE = 1++DAYS_FILTER = """day >= %(window_start)s+ AND day < %(window_end)s"""++WINDOW_FILTER = f"""team_id = %(team_id)s+ AND {DAYS_FILTER}"""+++@frozen+class Subject:+ kind: WarehouseSuggestionSubjectKind+ id: UUID+++@frozen+class ReadWindow:+ start: date+ end: date+ recent_start: date++ @classmethod+ def ending(cls, today: date, rules: Rules) -> "ReadWindow":+ return cls(+ start=today - timedelta(days=rules.window_days),+ end=today,+ recent_start=today - timedelta(days=rules.lifecycle.expire_after_days),+ )++ @property+ def starts_at(self) -> datetime:+ return datetime.combine(self.start, time.min, tzinfo=UTC)++ @property+ def ends_at(self) -> datetime:+ return datetime.combine(self.end, time.min, tzinfo=UTC)+++@frozen+class RollupDays:+ days_with_data: int+ recent_days_with_data: int+++@frozen+class SubjectReads:+ human_requests: int+ human_users: int+ human_days: int+ background_requests: int+ human_reads: int+ human_duration_ms: int+ human_read_bytes: int+ alone_reads: int+ alone_duration_ms_median: float+ alone_read_bytes_median: float+ last_read_at: datetime+ requests_by_surface: Mapping[Surface, int]++ @property+ def surfaces(self) -> frozenset[Surface]:+ return frozenset(surface for surface in self.requests_by_surface if surface != Surface.UNKNOWN)+++@frozen+class SubjectRefreshes:+ runs: int+ duration_ms: int+ read_bytes: int+++@frozen+class TeamReads:+ window: ReadWindow+ days_with_data: int+ recent_days_with_data: int+ readers: int+ view_readers: int+ view_reads: int+ subjects: Mapping[Subject, SubjectReads]+ refreshes: Mapping[UUID, SubjectRefreshes]++ def reads_of(self, subject: Subject) -> SubjectReads | None:+ return self.subjects.get(subject)+++def read_rollup_days(window: ReadWindow) -> RollupDays:+ tag_queries(+ product=Product.DATA_MODELING, feature=Feature.WAREHOUSE_SUGGESTIONS, name="warehouse_suggestions_rollup_days"+ )+ days_with_data, recent_days_with_data = sync_execute(+ ROLLUP_DAYS_SQL,+ {"window_start": window.start, "window_end": window.end, "recent_start": window.recent_start},+ settings=READS_QUERY_SETTINGS,+ )[0]+ return RollupDays(days_with_data=days_with_data, recent_days_with_data=recent_days_with_data)+++def read_team_reads(team_id: int, window: ReadWindow, rules: Rules, rollup_days: RollupDays) -> TeamReads:+ tag_queries(+ product=Product.DATA_MODELING,+ feature=Feature.WAREHOUSE_SUGGESTIONS,+ team_id=team_id,+ name="warehouse_suggestions_reads",+ )+ params: dict[str, Any] = {+ "team_id": team_id,+ "window_start": window.start,+ "window_end": window.end,+ "recent_start": window.recent_start,+ "read": ReadKind.READ.value,+ "refresh": ReadKind.REFRESH.value,+ "saved_query": WarehouseSuggestionSubjectKind.SAVED_QUERY.value,+ }+ human_sql, human_params = human_condition(rules.traffic)+ surface_sql, surface_params = surface_expression(rules.surfaces)+ params.update(human_params)+ params.update(surface_params)+ readers, view_readers, view_reads = _execute(TEAM_SQL.format(human=human_sql), params, team_id)[0]+ surface_counts = _surface_counts(SURFACES_SQL.format(human=human_sql, surface=surface_sql), params, team_id)+ return TeamReads(+ window=window,+ days_with_data=rollup_days.days_with_data,+ recent_days_with_data=rollup_days.recent_days_with_data,+ readers=readers,+ view_readers=view_readers,+ view_reads=view_reads,+ subjects=_subject_reads(SUBJECTS_SQL.format(human=human_sql), params, team_id, surface_counts),+ refreshes=_refreshes(params, team_id),+ )+++def human_condition(traffic: TrafficRules) -> tuple[str, dict[str, Any]]:+ conditions = []+ params: dict[str, Any] = {}+ if traffic.requires_user_id:+ conditions.append("has_user_id")+ if traffic.background_features:+ conditions.append("lc_feature NOT IN %(background_features)s")+ params["background_features"] = tuple(sorted(traffic.background_features))+ if traffic.background_kinds:+ conditions.append("lc_kind NOT IN %(background_kinds)s")+ params["background_kinds"] = tuple(sorted(traffic.background_kinds))+ return f"({' AND '.join(conditions) or 'true'})", params+++def surface_expression(surfaces: SurfaceRules) -> tuple[str, dict[str, Any]]:+ branches = []+ params: dict[str, Any] = {}+ for position, rule in enumerate(surfaces.rules):+ surface_param = f"surface_{position}"+ params[surface_param] = rule.surface.value+ if rule.values is None:+ condition = f"{rule.field.value} != ''"+ elif rule.values:+ values_param = f"surface_values_{position}"+ params[values_param] = tuple(sorted(rule.values))+ condition = f"{rule.field.value} IN %({values_param})s"+ else:+ continue+ branches.append(f"{condition}, %({surface_param})s")+ params["surface_unknown"] = Surface.UNKNOWN.value+ if not branches:+ return "%(surface_unknown)s", params+ return f"multiIf({', '.join(branches)}, %(surface_unknown)s)", params+++ROLLUP_DAYS_SQL = f"""+SELECT uniq(day), uniqIf(day, day >= %(recent_start)s)+FROM {WAREHOUSE_OBJECT_READS_DAILY_TABLE}+WHERE {DAYS_FILTER}+"""++TEAM_SQL = f"""+SELECT+ uniqMergeIf(users, is_human_read),+ uniqMergeIf(users, is_human_read AND subject_kind = %(saved_query)s),+ uniqMergeIf(requests, is_human_read AND subject_kind = %(saved_query)s)+FROM (+ SELECT *, read_kind = %(read)s AND {{human}} AS is_human_read+ FROM {WAREHOUSE_OBJECT_READS_DAILY_TABLE}+ WHERE {WINDOW_FILTER}+)+"""++SUBJECTS_SQL = f"""+SELECT+ subject_kind,+ subject_id,+ uniqMergeIf(requests, is_human),+ uniqMergeIf(users, is_human),+ uniqIf(day, is_human),+ uniqMergeIf(requests, NOT is_human),+ sumIf(read_count, is_human),+ sumIf(duration_ms_sum, is_human),+ sumIf(read_bytes_sum, is_human),+ sumIf(read_count, read_alone),+ quantilesMergeIf(0.5, 0.9)(duration_ms_quantiles, read_alone)[{FIRST_QUANTILE}],+ quantilesMergeIf(0.5, 0.9)(read_bytes_quantiles, read_alone)[{FIRST_QUANTILE}],+ max(max_event_time)+FROM (+ SELECT *, {{human}} AS is_human+ FROM {WAREHOUSE_OBJECT_READS_DAILY_TABLE}+ WHERE {WINDOW_FILTER}+ AND read_kind = %(read)s+)+GROUP BY subject_kind, subject_id+"""++SURFACES_SQL = f"""+SELECT subject_kind, subject_id, {{surface}} AS surface, uniqMerge(requests)+FROM {WAREHOUSE_OBJECT_READS_DAILY_TABLE}+WHERE {WINDOW_FILTER}+ AND read_kind = %(read)s+ AND {{human}}+GROUP BY subject_kind, subject_id, surface+"""++REFRESHES_SQL = f"""+SELECT subject_id, uniq(workflow_id), sum(duration_ms_sum), sum(read_bytes_sum)+FROM {WAREHOUSE_OBJECT_READS_DAILY_TABLE}+WHERE {WINDOW_FILTER}+ AND read_kind = %(refresh)s+GROUP BY subject_id+"""+++def _execute(sql: str, params: Mapping[str, Any], team_id: int) -> list[tuple[Any, ...]]:+ return sync_execute(sql, params, settings=READS_QUERY_SETTINGS, team_id=team_id)+++def _subject(subject_kind: str, subject_id: str) -> Subject | None:+ try:+ return Subject(kind=WarehouseSuggestionSubjectKind(subject_kind), id=UUID(subject_id))+ except ValueError:+ return None+++def _surface_counts(sql: str, params: Mapping[str, Any], team_id: int) -> dict[Subject, dict[Surface, int]]:+ counts: defaultdict[Subject, dict[Surface, int]] = defaultdict(dict)+ for subject_kind, subject_id, surface, requests in _execute(sql, params, team_id):+ subject = _subject(subject_kind, subject_id)+ if subject is not None:+ counts[subject][Surface(surface)] = requests+ return counts+++def _subject_reads(+ sql: str, params: Mapping[str, Any], team_id: int, surface_counts: Mapping[Subject, dict[Surface, int]]+) -> dict[Subject, SubjectReads]:+ reads: dict[Subject, SubjectReads] = {}+ for row in _execute(sql, params, team_id):+ subject = _subject(row[0], row[1])+ if subject is None:+ continue+ reads[subject] = SubjectReads(+ human_requests=row[2],+ human_users=row[3],+ human_days=row[4],+ background_requests=row[5],+ human_reads=row[6],+ human_duration_ms=row[7],+ human_read_bytes=row[8],+ alone_reads=row[9],+ alone_duration_ms_median=float(row[10]),+ alone_read_bytes_median=float(row[11]),+ last_read_at=row[12],+ requests_by_surface=surface_counts.get(subject, {}),+ )+ return reads+++def _refreshes(params: Mapping[str, Any], team_id: int) -> dict[UUID, SubjectRefreshes]:+ refreshes: dict[UUID, SubjectRefreshes] = {}+ for subject_id, runs, duration_ms, read_bytes in _execute(REFRESHES_SQL, params, team_id):+ subject = _subject(WarehouseSuggestionSubjectKind.SAVED_QUERY, subject_id)+ if subject is not None:+ refreshes[subject.id] = SubjectRefreshes(runs=runs, duration_ms=duration_ms, read_bytes=read_bytes)+ return refreshesdiff --git a/products/warehouse_suggestions/backend/logic/rules.py b/products/warehouse_suggestions/backend/logic/rules.pynew file mode 100644index 000000000000..c6c38c978ab0--- /dev/null+++ b/products/warehouse_suggestions/backend/logic/rules.py@@ -0,0 +1,242 @@+import json+import hashlib+from collections.abc import Sequence+from dataclasses import asdict+from datetime import timedelta+from enum import StrEnum+from math import ceil+from typing import Any++from posthog.clickhouse.query_tagging import AccessMethod, Feature, Product+from posthog.dataclasses import frozen+from posthog.event_usage import EventSource+from posthog.schema_enums import DataWarehouseSavedQueryOrigin++from ..facade.enums import WarehouseSuggestionKind++TERABYTE = 10**12+TEMPORAL_QUERY_KIND = "temporal"+DAGSTER_QUERY_KIND = "dagster"+RULES_VERSION_LENGTH = 12+++class Surface(StrEnum):+ MCP = "mcp"+ POSTHOG_AI = "posthog_ai"+ DESKTOP = "desktop"+ ENDPOINTS = "endpoints"+ DASHBOARD = "dashboard"+ INSIGHT = "insight"+ SQL_EDITOR = "sql_editor"+ NOTEBOOK = "notebook"+ API = "api"+ APP = "app"+ UNKNOWN = "unknown"+++class TagField(StrEnum):+ KIND = "lc_kind"+ PRODUCT = "lc_product"+ FEATURE = "lc_feature"+ ACCESS_METHOD = "lc_access_method"+ SOURCE = "source"+ SCENE = "scene"+++@frozen+class SurfaceRule:+ surface: Surface+ field: TagField+ values: frozenset[str] | None+++@frozen+class TrafficRules:+ background_features: frozenset[str]+ background_kinds: frozenset[str]+ requires_user_id: bool+++@frozen+class SurfaceRules:+ rules: tuple[SurfaceRule, ...]+++@frozen+class SubjectRules:+ excluded_view_origins: frozenset[str]+++@frozen+class EligibilityRules:+ min_view_reads: int+++@frozen+class CertifyRules:+ top_share: float+ min_users: int+ min_users_floor: int+ min_user_share: float+ min_days: int+ min_surfaces: int++ def users_needed(self, team_readers: int) -> int:+ return max(self.min_users_floor, min(self.min_users, ceil(team_readers * self.min_user_share)))+++@frozen+class DeprecateRules:+ min_days_with_data: int+ seconds_floor: float+ bytes_floor: float+ counts_background_reads: bool+++@frozen+class MaterializeRules:+ min_days: int+ min_requests: int+ min_users_or_surfaces: int+ min_alone_reads: int+ min_seconds_saved: float+ min_bytes_saved: float+ min_saved_share: float+ require_incremental_eligibility: bool+++@frozen+class RefreshRules:+ max_interval: timedelta+ min_read_day_share_below_max_interval: float+++@frozen+class LifecycleRules:+ reproposal_score_multiple: float+ expire_after_days: int+ max_surfaced_per_day: int+ max_open: int+ max_open_per_kind: int+ first_week_runs: int+ kind_order: tuple[WarehouseSuggestionKind, ...]+ first_week_kind_order: tuple[WarehouseSuggestionKind, ...]+++@frozen+class Rules:+ window_days: int+ traffic: TrafficRules+ surfaces: SurfaceRules+ subjects: SubjectRules+ eligibility: EligibilityRules+ certify: CertifyRules+ deprecate: DeprecateRules+ materialize: MaterializeRules+ refresh: RefreshRules+ lifecycle: LifecycleRules+++RULES = Rules(+ window_days=30,+ traffic=TrafficRules(+ background_features=frozenset(+ {+ Feature.CACHE_WARMUP,+ Feature.ALERTING,+ Feature.DATA_QUALITY_CHECK,+ Feature.MANAGEMENT_COMMAND,+ Feature.SCHEMA_INTROSPECTION,+ Feature.BILLING_ETL,+ }+ ),+ background_kinds=frozenset({TEMPORAL_QUERY_KIND, DAGSTER_QUERY_KIND}),+ requires_user_id=True,+ ),+ surfaces=SurfaceRules(+ rules=(+ SurfaceRule(+ surface=Surface.MCP, field=TagField.SOURCE, values=frozenset({EventSource.MCP, EventSource.CLI})+ ),+ SurfaceRule(surface=Surface.POSTHOG_AI, field=TagField.SOURCE, values=frozenset({EventSource.POSTHOG_AI})),+ SurfaceRule(surface=Surface.DESKTOP, field=TagField.SOURCE, values=frozenset({EventSource.DESKTOP})),+ SurfaceRule(+ surface=Surface.ENDPOINTS, field=TagField.FEATURE, values=frozenset({Feature.ENDPOINT_EXECUTION})+ ),+ SurfaceRule(surface=Surface.ENDPOINTS, field=TagField.PRODUCT, values=frozenset({Product.ENDPOINTS})),+ SurfaceRule(surface=Surface.DASHBOARD, field=TagField.SCENE, values=frozenset({"Dashboard"})),+ SurfaceRule(surface=Surface.INSIGHT, field=TagField.FEATURE, values=frozenset({Feature.INSIGHT})),+ SurfaceRule(surface=Surface.INSIGHT, field=TagField.SCENE, values=frozenset({"Insight", "SavedInsights"})),+ SurfaceRule(surface=Surface.SQL_EDITOR, field=TagField.PRODUCT, values=frozenset({Product.SQL_EDITOR})),+ SurfaceRule(surface=Surface.SQL_EDITOR, field=TagField.SCENE, values=frozenset({"SQLEditor"})),+ SurfaceRule(surface=Surface.NOTEBOOK, field=TagField.PRODUCT, values=frozenset({Product.NOTEBOOKS})),+ SurfaceRule(surface=Surface.NOTEBOOK, field=TagField.SCENE, values=frozenset({"Notebook"})),+ SurfaceRule(+ surface=Surface.API,+ field=TagField.ACCESS_METHOD,+ values=frozenset(+ {AccessMethod.PERSONAL_API_KEY, AccessMethod.OAUTH, AccessMethod.PROJECT_SECRET_API_KEY}+ ),+ ),+ SurfaceRule(surface=Surface.APP, field=TagField.SCENE, values=None),+ )+ ),+ subjects=SubjectRules(+ excluded_view_origins=frozenset(+ {DataWarehouseSavedQueryOrigin.ENDPOINT, DataWarehouseSavedQueryOrigin.MANAGED_VIEWSET}+ )+ ),+ eligibility=EligibilityRules(min_view_reads=50),+ certify=CertifyRules(+ top_share=0.10, min_users=5, min_users_floor=2, min_user_share=0.5, min_days=20, min_surfaces=2+ ),+ deprecate=DeprecateRules(+ min_days_with_data=30, seconds_floor=600.0, bytes_floor=float(TERABYTE), counts_background_reads=True+ ),+ materialize=MaterializeRules(+ min_days=10,+ min_requests=50,+ min_users_or_surfaces=2,+ min_alone_reads=3,+ min_seconds_saved=600.0,+ min_bytes_saved=float(TERABYTE),+ min_saved_share=0.5,+ require_incremental_eligibility=True,+ ),+ refresh=RefreshRules(max_interval=timedelta(hours=24), min_read_day_share_below_max_interval=0.5),+ lifecycle=LifecycleRules(+ reproposal_score_multiple=3.0,+ expire_after_days=7,+ max_surfaced_per_day=5,+ max_open=15,+ max_open_per_kind=3,+ first_week_runs=2,+ kind_order=(+ WarehouseSuggestionKind.MATERIALIZE,+ WarehouseSuggestionKind.DEPRECATE,+ WarehouseSuggestionKind.CERTIFY,+ ),+ first_week_kind_order=(+ WarehouseSuggestionKind.CERTIFY,+ WarehouseSuggestionKind.DEPRECATE,+ WarehouseSuggestionKind.MATERIALIZE,+ ),+ ),+)+++def kind_position(kind_order: Sequence[str], kind: str) -> int:+ return kind_order.index(kind) if kind in kind_order else len(kind_order)+++def rules_version(rules: Rules) -> str:+ serialized = json.dumps(asdict(rules), sort_keys=True, default=_json_value)+ return hashlib.sha256(serialized.encode()).hexdigest()[:RULES_VERSION_LENGTH]+++def _json_value(value: Any) -> Any:+ if isinstance(value, frozenset):+ return sorted(value)+ if isinstance(value, timedelta):+ return value.total_seconds()+ raise TypeError(f"Cannot serialize {type(value).__name__} in rules")diff --git a/products/warehouse_suggestions/backend/logic/rules_diff.py b/products/warehouse_suggestions/backend/logic/rules_diff.pynew file mode 100644index 000000000000..a23a8166970d--- /dev/null+++ b/products/warehouse_suggestions/backend/logic/rules_diff.py@@ -0,0 +1,94 @@+from collections.abc import Mapping, Sequence+from dataclasses import replace+from datetime import timedelta+from typing import Any++from posthog.dataclasses import frozen++from ..facade.enums import WarehouseSuggestionKind+from .candidates.base import CandidateContext, CandidateResult+from .job import is_eligible+from .rules import Rules+++class InvalidRuleOverrideError(ValueError):+ pass+++@frozen+class KindDiff:+ added: tuple[str, ...]+ removed: tuple[str, ...]+ reranked: tuple[str, ...]+++def override_rules(rules: Rules, assignments: Sequence[str]) -> Rules:+ for assignment in assignments:+ path, separator, raw_value = assignment.partition("=")+ section_name, _, field_name = path.partition(".")+ if not separator or not field_name or not hasattr(rules, section_name):+ raise InvalidRuleOverrideError(f"Expected section.field=value, got {assignment!r}")+ section = getattr(rules, section_name)+ if not hasattr(section, field_name):+ raise InvalidRuleOverrideError(f"{section_name} has no rule named {field_name!r}")+ value = _parse_like(getattr(section, field_name), raw_value)+ rules = replace(rules, **{section_name: replace(section, **{field_name: value})})+ return rules+++def results_the_job_would_keep(+ context: CandidateContext, results: Mapping[WarehouseSuggestionKind, CandidateResult]+) -> dict[WarehouseSuggestionKind, CandidateResult]:+ if is_eligible(context.reads, context.rules.eligibility):+ return dict(results)+ return {kind: CandidateResult(drafts=(), rejections=()) for kind in results}+++def diff_candidates(+ before: Mapping[WarehouseSuggestionKind, CandidateResult],+ after: Mapping[WarehouseSuggestionKind, CandidateResult],+) -> dict[WarehouseSuggestionKind, KindDiff]:+ return {kind: _diff(before[kind], after[kind]) for kind in before}+++def _diff(before: CandidateResult, after: CandidateResult) -> KindDiff:+ before_ranked, after_ranked = _ranked(before), _ranked(after)+ names = {draft.fingerprint: draft.payload.subject_name for draft in (*before.drafts, *after.drafts)}+ kept_before = [fingerprint for fingerprint in before_ranked if fingerprint in after_ranked]+ kept_after = [fingerprint for fingerprint in after_ranked if fingerprint in before_ranked]+ return KindDiff(+ added=tuple(names[fingerprint] for fingerprint in after_ranked if fingerprint not in before_ranked),+ removed=tuple(names[fingerprint] for fingerprint in before_ranked if fingerprint not in after_ranked),+ reranked=tuple(+ names[fingerprint]+ for position, fingerprint in enumerate(kept_after)+ if kept_before[position] != fingerprint+ ),+ )+++def _ranked(result: CandidateResult) -> list[str]:+ return [draft.fingerprint for draft in sorted(result.drafts, key=lambda draft: draft.score, reverse=True)]+++def _parse_like(current: Any, raw_value: str) -> Any:+ if isinstance(current, bool):+ return raw_value.lower() in ("true", "1", "yes")+ if isinstance(current, int):+ return int(raw_value)+ if isinstance(current, float):+ return float(raw_value)+ if isinstance(current, timedelta):+ return timedelta(seconds=float(raw_value))+ if isinstance(current, tuple) and current:+ return _parse_items(type(current[0]), raw_value)+ raise InvalidRuleOverrideError(+ f"Only numbers, booleans, durations and ordered lists can be overridden, not {current!r}"+ )+++def _parse_items(item_type: type, raw_value: str) -> tuple[Any, ...]:+ try:+ return tuple(item_type(item.strip()) for item in raw_value.split(","))+ except ValueError as error:+ raise InvalidRuleOverrideError(str(error)) from errordiff --git a/products/warehouse_suggestions/backend/logic/suggestions.py b/products/warehouse_suggestions/backend/logic/suggestions.pyindex 145059049f9f..b4689ade8ffc 100644--- a/products/warehouse_suggestions/backend/logic/suggestions.py+++ b/products/warehouse_suggestions/backend/logic/suggestions.py@@ -1,6 +1,7 @@from collections.abc import Mapping, Sequence-from dataclasses import asdict+from dataclasses import fieldsfrom datetime import datetime+from typing import Anyfrom uuid import UUIDfrom django.db import transaction@@ -11,6 +12,7 @@ from posthog.models.scoping.manager import resolve_effective_team_idfrom ..facade.contracts import SuggestionAlreadyDecidedError, SuggestionDraftfrom ..facade.enums import WarehouseSuggestionDismissalReason, WarehouseSuggestionStatusfrom ..models import WarehouseSuggestion+from .payloads import payload_to_jsonTransitions = Mapping[WarehouseSuggestionStatus, frozenset[WarehouseSuggestionStatus]]@@ -25,6 +27,7 @@ ALLOWED_TRANSITIONS: Transitions = {),WarehouseSuggestionStatus.DISMISSED: frozenset({WarehouseSuggestionStatus.PROPOSED}),WarehouseSuggestionStatus.EXPIRED: frozenset({WarehouseSuggestionStatus.PROPOSED}),+ WarehouseSuggestionStatus.AUTO_RESOLVED: frozenset({WarehouseSuggestionStatus.PROPOSED}),}HUMAN_TRANSITIONS: Transitions = {@@ -125,11 +128,19 @@ def _is_refreshed_by(row: WarehouseSuggestion, draft: SuggestionDraft) -> bool:def _refresh(row: WarehouseSuggestion, draft: SuggestionDraft, seen_at: datetime) -> WarehouseSuggestion:+ values = _draft_values(draft)for field in DRAFT_FIELDS_UPDATED_ON_INGEST:- setattr(row, field, getattr(draft, field))+ setattr(row, field, values[field])row.last_seen_at = seen_atreturn rowdef _new_suggestion(team_id: int, draft: SuggestionDraft, seen_at: datetime) -> WarehouseSuggestion:- return WarehouseSuggestion(team_id=team_id, last_seen_at=seen_at, **asdict(draft))+ return WarehouseSuggestion(team_id=team_id, last_seen_at=seen_at, **_draft_values(draft))+++def _draft_values(draft: SuggestionDraft) -> dict[str, Any]:+ return {+ field.name: payload_to_json(draft.payload) if field.name == "payload" else getattr(draft, field.name)+ for field in fields(draft)+ }diff --git a/products/warehouse_suggestions/backend/management/__init__.py b/products/warehouse_suggestions/backend/management/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/warehouse_suggestions/backend/management/commands/__init__.py b/products/warehouse_suggestions/backend/management/commands/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/warehouse_suggestions/backend/management/commands/warehouse_suggestions_explain.py b/products/warehouse_suggestions/backend/management/commands/warehouse_suggestions_explain.pynew file mode 100644index 000000000000..67f37709757f--- /dev/null+++ b/products/warehouse_suggestions/backend/management/commands/warehouse_suggestions_explain.py@@ -0,0 +1,31 @@+from typing import Any++from django.core.management.base import BaseCommand, CommandParser+from django.utils import timezone++from ...logic.job import explain_team, is_eligible+++class Command(BaseCommand):+ help = "Print a team's read window, eligibility, and each suggestion kind's candidates and rejections."++ def add_arguments(self, parser: CommandParser) -> None:+ parser.add_argument("--team", type=int, required=True, help="Team id to explain.")++ def handle(self, *args: Any, **options: Any) -> None:+ context, results = explain_team(options["team"], today=timezone.now().date())+ reads = context.reads+ self.stdout.write(+ f"window {reads.window.start}..{reads.window.end}: {reads.days_with_data} days with data, "+ f"{reads.view_readers} view readers, {reads.view_reads} view reads, "+ f"eligible={is_eligible(reads, context.rules.eligibility)}"+ )+ for kind, result in results.items():+ self.stdout.write(f"\n{kind}: {len(result.drafts)} candidates")+ if result.skipped_reason:+ self.stdout.write(f" skipped: {result.skipped_reason}")+ for draft in sorted(result.drafts, key=lambda draft: draft.score, reverse=True):+ self.stdout.write(f" + {draft.payload.subject_name} score={draft.score:.2f} {draft.score_inputs}")+ for rejection in result.rejections:+ name = context.inventory.name_of(rejection.subject) or rejection.subject.id+ self.stdout.write(f" - {name}: {rejection.reason}")diff --git a/products/warehouse_suggestions/backend/management/commands/warehouse_suggestions_rules_diff.py b/products/warehouse_suggestions/backend/management/commands/warehouse_suggestions_rules_diff.pynew file mode 100644index 000000000000..981850407756--- /dev/null+++ b/products/warehouse_suggestions/backend/management/commands/warehouse_suggestions_rules_diff.py@@ -0,0 +1,39 @@+from typing import Any++from django.core.management.base import BaseCommand, CommandParser+from django.utils import timezone++from ...logic.job import explain_team, is_eligible+from ...logic.rules import RULES+from ...logic.rules_diff import diff_candidates, override_rules, results_the_job_would_keep+++class Command(BaseCommand):+ help = "Show how a rules change would add, remove or re-rank a team's suggestion candidates."++ def add_arguments(self, parser: CommandParser) -> None:+ parser.add_argument("--team", type=int, required=True, help="Team id to compare.")+ parser.add_argument(+ "--set",+ action="append",+ required=True,+ dest="assignments",+ help="A rule to change, as section.field=value, for example materialize.min_seconds_saved=300.",+ )++ def handle(self, *args: Any, **options: Any) -> None:+ today = timezone.now().date()+ proposed = override_rules(RULES, options["assignments"])+ current_context, current_results = explain_team(options["team"], today=today, rules=RULES)+ proposed_context, proposed_results = explain_team(options["team"], today=today, rules=proposed)+ self.stdout.write(+ f"eligible: {is_eligible(current_context.reads, RULES.eligibility)} -> "+ f"{is_eligible(proposed_context.reads, proposed.eligibility)}"+ )+ before = results_the_job_would_keep(current_context, current_results)+ after = results_the_job_would_keep(proposed_context, proposed_results)+ for kind, diff in diff_candidates(before, after).items():+ self.stdout.write(f"{kind}: +{len(diff.added)} -{len(diff.removed)} ~{len(diff.reranked)}")+ for label, names in (("added", diff.added), ("removed", diff.removed), ("re-ranked", diff.reranked)):+ for name in names:+ self.stdout.write(f" {label}: {name}")diff --git a/products/warehouse_suggestions/backend/migrations/0002_warehousesuggestionteamconfig.py b/products/warehouse_suggestions/backend/migrations/0002_warehousesuggestionteamconfig.pynew file mode 100644index 000000000000..ab460f006dbc--- /dev/null+++ b/products/warehouse_suggestions/backend/migrations/0002_warehousesuggestionteamconfig.py@@ -0,0 +1,38 @@+# Generated by Django 5.2.18 on 2026-10-07 14:09++import django.db.models.deletion+from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("posthog", "1394_backfill_secret_tokens_to_psak"),+ ("warehouse_suggestions", "0001_initial"),+ ]++ operations = [+ migrations.CreateModel(+ name="WarehouseSuggestionTeamConfig",+ fields=[+ (+ "team",+ models.OneToOneField(+ db_constraint=False,+ on_delete=django.db.models.deletion.CASCADE,+ primary_key=True,+ related_name="+",+ serialize=False,+ to="posthog.team",+ ),+ ),+ ("enabled", models.BooleanField(default=True)),+ (+ "paused_reason",+ models.CharField(blank=True, max_length=32, null=True),+ ),+ ("eligible", models.BooleanField(default=False)),+ ("days_with_data", models.PositiveSmallIntegerField(default=0)),+ ("last_run_at", models.DateTimeField(blank=True, null=True)),+ ],+ ),+ ]diff --git a/products/warehouse_suggestions/backend/migrations/max_migration.txt b/products/warehouse_suggestions/backend/migrations/max_migration.txtindex cbab66dde92a..96f2bf6707a2 100644--- a/products/warehouse_suggestions/backend/migrations/max_migration.txt+++ b/products/warehouse_suggestions/backend/migrations/max_migration.txt@@ -1 +1 @@-0001_initial+0002_warehousesuggestionteamconfigdiff --git a/products/warehouse_suggestions/backend/models.py b/products/warehouse_suggestions/backend/models.pyindex 3297d82dbddd..a16d62542ed7 100644--- a/products/warehouse_suggestions/backend/models.py+++ b/products/warehouse_suggestions/backend/models.py@@ -56,3 +56,14 @@ class WarehouseSuggestion(ModelActivityMixin, TeamScopedRootMixin, UUIDModel):models.Index(fields=["team", "status", "kind"], name="warehouse_sugg_status_kind"),models.Index(fields=["team", "last_seen_at"], name="warehouse_sugg_last_seen"),]+++class WarehouseSuggestionTeamConfig(models.Model):+ team = models.OneToOneField(+ "posthog.Team", on_delete=models.CASCADE, primary_key=True, db_constraint=False, related_name="+"+ )+ enabled = models.BooleanField(default=True)+ paused_reason = models.CharField(max_length=32, null=True, blank=True)+ eligible = models.BooleanField(default=False)+ days_with_data = models.PositiveSmallIntegerField(default=0)+ last_run_at = models.DateTimeField(null=True, blank=True)diff --git a/products/warehouse_suggestions/backend/presentation/serializers.py b/products/warehouse_suggestions/backend/presentation/serializers.pyindex 7e20731d6fa3..8a210b505125 100644--- a/products/warehouse_suggestions/backend/presentation/serializers.py+++ b/products/warehouse_suggestions/backend/presentation/serializers.py@@ -1,11 +1,20 @@"""DRF serializers for warehouse_suggestions."""from drf_spectacular.types import OpenApiTypes-from drf_spectacular.utils import extend_schema_field, extend_schema_serializer+from drf_spectacular.utils import PolymorphicProxySerializer, extend_schema_field, extend_schema_serializerfrom rest_framework import serializersfrom rest_framework_dataclasses.serializers import DataclassSerializer-from ..facade.contracts import Suggestion, SuggestionReviewer+from ..facade.contracts import (+ CertifyPayload,+ DeprecatePayload,+ MaterializeSuggestionPayload,+ Suggestion,+ SuggestionPayloadView,+ SuggestionReviewer,+ SuggestionStatus,+ VisibleSources,+)from ..facade.enums import (WarehouseSuggestionAssetOutcome,WarehouseSuggestionDismissalReason,@@ -31,9 +40,95 @@ class WarehouseSuggestionReviewerSerializer(DataclassSerializer):}+@extend_schema_serializer(component_name="WarehouseSuggestionVisibleSources")+class VisibleSourcesSerializer(DataclassSerializer):+ class Meta:+ dataclass = VisibleSources+ extra_kwargs = {+ "names": {"help_text": "Names of the sources the caller may see."},+ "hidden_count": {"help_text": "How many more sources exist that the caller may not see."},+ }+++@extend_schema_serializer(component_name="WarehouseSuggestionCertifyPayload")+class CertifyPayloadSerializer(DataclassSerializer):+ class Meta:+ dataclass = CertifyPayload+ extra_kwargs = {"subject_name": {"help_text": "Name of the view or table to certify."}}+++@extend_schema_serializer(component_name="WarehouseSuggestionDeprecatePayload")+class DeprecatePayloadSerializer(DataclassSerializer):+ class Meta:+ dataclass = DeprecatePayload+ extra_kwargs = {+ "subject_name": {"help_text": "Name of the unread view to deprecate."},+ "refresh_seconds_per_month": {"help_text": "Time its refreshes take in a month, in seconds."},+ "refresh_bytes_per_month": {"help_text": "Bytes its refreshes read in a month."},+ }+++@extend_schema_serializer(component_name="WarehouseSuggestionMaterializePayload")+class MaterializePayloadSerializer(DataclassSerializer):+ live_sources = VisibleSourcesSerializer(+ help_text="Sources that are always current, such as PostHog tables and direct connections."+ )+ unknown_sources = VisibleSourcesSerializer(+ help_text="Sources with no sync schedule, so their freshness is unknown."+ )++ class Meta:+ dataclass = MaterializeSuggestionPayload+ extra_kwargs = {+ "subject_name": {"help_text": "Name of the view to materialize."},+ "refresh_interval_seconds": {"help_text": "Proposed refresh interval, in seconds."},+ "saves_seconds_per_month": {"help_text": "Query time materializing saves in a month, in seconds."},+ "saves_bytes_per_month": {"help_text": "Bytes materializing saves from scanning in a month."},+ "freshness_today_seconds": {+ "help_text": "How old the view's data can be today, in seconds. Null when its sources are live."+ },+ "freshness_after_seconds": {"help_text": "How old the data can be once materialized, in seconds."},+ }+++PAYLOAD_SERIALIZERS: dict[type, type[DataclassSerializer]] = {+ CertifyPayload: CertifyPayloadSerializer,+ DeprecatePayload: DeprecatePayloadSerializer,+ MaterializeSuggestionPayload: MaterializePayloadSerializer,+}+++@extend_schema_field(+ PolymorphicProxySerializer(+ component_name="WarehouseSuggestionPayload",+ serializers=list(PAYLOAD_SERIALIZERS.values()),+ resource_type_field_name=None,+ )+)+class SuggestionPayloadField(serializers.Field):+ def to_representation(self, value: SuggestionPayloadView) -> dict:+ return PAYLOAD_SERIALIZERS[type(value)](value).data+++@extend_schema_serializer(component_name="WarehouseSuggestionStatus")+class WarehouseSuggestionStatusSerializer(DataclassSerializer):+ class Meta:+ dataclass = SuggestionStatus+ extra_kwargs = {+ "enabled": {"help_text": "False when the project turned suggestions off."},+ "eligible": {"help_text": "Whether the project reads its views often enough to get suggestions."},+ "days_with_data": {"help_text": "Days of read history the last run had, up to the window."},+ "window_days": {"help_text": "Days of read history a full window holds."},+ "paused_reason": {"help_text": "Why new suggestions stopped showing. Null while they show."},+ "refreshed_at": {"help_text": "When the daily job last ran for this project."},+ }++@extend_schema_serializer(component_name="WarehouseSuggestion")class WarehouseSuggestionSerializer(DataclassSerializer):- payload = JsonObjectField(help_text="What accepting this suggestion would create or change. Shape depends on kind.")+ payload = SuggestionPayloadField(+ read_only=True, help_text="What accepting this suggestion would create or change. Shape depends on kind."+ )evidence = JsonObjectField(help_text="The usage numbers that led to this suggestion.")created_asset = JsonObjectField(allow_null=True, help_text="What accepting this suggestion created. Null until accepted."diff --git a/products/warehouse_suggestions/backend/presentation/views.py b/products/warehouse_suggestions/backend/presentation/views.pyindex 17486be27e2e..04c427604aa8 100644--- a/products/warehouse_suggestions/backend/presentation/views.py+++ b/products/warehouse_suggestions/backend/presentation/views.py@@ -35,6 +35,7 @@ from .serializers import (DismissWarehouseSuggestionSerializer,WarehouseSuggestionListQuerySerializer,WarehouseSuggestionSerializer,+ WarehouseSuggestionStatusSerializer,)DEFAULT_PAGE_SIZE = 100@@ -65,7 +66,7 @@ class ProjectAccessPermission(BasePermission):class WarehouseSuggestionViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):scope_object = "warehouse_objects"- scope_object_read_actions = ["list", "retrieve"]+ scope_object_read_actions = ["list", "retrieve", "status"]scope_object_write_actions = ["dismiss", "resume"]pagination_class = SuggestionPaginationlookup_value_regex = UUID_REGEX@@ -97,6 +98,11 @@ class WarehouseSuggestionViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet),)+ @extend_schema(responses={200: WarehouseSuggestionStatusSerializer})+ @action(detail=False, methods=["get"], pagination_class=None)+ def status(self, request: Request, **kwargs: Any) -> Response:+ return Response(WarehouseSuggestionStatusSerializer(api.suggestion_status(self.team_id)).data)+@extend_schema(responses={200: WarehouseSuggestionSerializer})def retrieve(self, request: Request, pk: str, **kwargs: Any) -> Response:return self._respond(lambda: api.get_suggestion(self.team_id, self.user_access_control, UUID(pk)))diff --git a/products/warehouse_suggestions/backend/temporal/__init__.py b/products/warehouse_suggestions/backend/temporal/__init__.pynew file mode 100644index 000000000000..45b1a20aaa21--- /dev/null+++ b/products/warehouse_suggestions/backend/temporal/__init__.py@@ -0,0 +1,15 @@+"""Temporal wiring for warehouse_suggestions. Registered on the data-modeling task queue."""++from collections.abc import Callable+from typing import Any++from posthog.temporal.common.base import PostHogWorkflow++from .activities import generate_warehouse_suggestions, get_warehouse_suggestion_team_batches+from .workflows import WarehouseSuggestionsWorkflow++WORKFLOWS: list[type[PostHogWorkflow]] = [WarehouseSuggestionsWorkflow]++ACTIVITIES: list[Callable[..., Any]] = [get_warehouse_suggestion_team_batches, generate_warehouse_suggestions]++__all__ = ["ACTIVITIES", "WORKFLOWS"]diff --git a/products/warehouse_suggestions/backend/temporal/activities.py b/products/warehouse_suggestions/backend/temporal/activities.pynew file mode 100644index 000000000000..85eedf3c726e--- /dev/null+++ b/products/warehouse_suggestions/backend/temporal/activities.py@@ -0,0 +1,85 @@+from collections import Counter+from itertools import batched++from django.utils import timezone++from temporalio import activity++from posthog.clickhouse.client import sync_execute+from posthog.clickhouse.client.execute import KillSwitchLevel, get_kill_switch_level+from posthog.clickhouse.query_tagging import Feature, Product, tag_queries+from posthog.clickhouse.warehouse_object_reads import WAREHOUSE_OBJECT_READS_DAILY_TABLE+from posthog.models.team import Team+from posthog.sync import database_sync_to_async_pool+from posthog.temporal.common.heartbeat import Heartbeater+from posthog.temporal.common.logger import get_logger+from posthog.temporal.common.rollout import filter_ids_for_rollout++from ..logic.flags import is_warehouse_suggestions_enabled+from ..logic.job import TeamRunStatus, run_team+from ..logic.reads import ReadWindow, read_rollup_days+from ..logic.rules import RULES+from .contracts import BatchOutcome, WarehouseSuggestionsInputs++LOGGER = get_logger(__name__)+FULL_ROLLOUT = 1.0++TEAMS_WITH_READS_SQL = f"""+SELECT DISTINCT team_id+FROM {WAREHOUSE_OBJECT_READS_DAILY_TABLE}+WHERE day >= today() - %(window_days)s+"""+++def team_batches(inputs: WarehouseSuggestionsInputs) -> list[list[int]]:+ if get_kill_switch_level() != KillSwitchLevel.OFF:+ LOGGER.info("warehouse_suggestions.skipped_by_kill_switch")+ return []+ candidate_ids = inputs.team_ids if inputs.team_ids is not None else _teams_with_reads()+ teams = (+ Team.objects.filter(+ id__in=candidate_ids, is_demo=False, parent_team__isnull=True, organization__for_internal_metrics=False+ )+ .select_related("organization")+ .order_by("id")+ )+ team_ids = [team.pk for team in teams if is_warehouse_suggestions_enabled(team)]+ if inputs.rollout_percentage < FULL_ROLLOUT:+ team_ids = filter_ids_for_rollout(team_ids, inputs.rollout_percentage)+ return [list(batch) for batch in batched(team_ids, inputs.batch_size, strict=False)]+++def run_batch(team_ids: list[int], run_id: str) -> BatchOutcome:+ today = timezone.now().date()+ rollup_days = read_rollup_days(ReadWindow.ending(today, RULES))+ outcomes: Counter[str] = Counter()+ for team_id in team_ids:+ try:+ outcomes[run_team(team_id, run_id=run_id, today=today, rollup_days=rollup_days).status] += 1+ except Exception:+ LOGGER.exception("warehouse_suggestions.team_failed", team_id=team_id)+ outcomes["failed"] += 1+ return BatchOutcome(+ processed=outcomes[TeamRunStatus.PROCESSED],+ not_eligible=outcomes[TeamRunStatus.NOT_ELIGIBLE],+ disabled=outcomes[TeamRunStatus.DISABLED],+ failed=outcomes["failed"],+ )+++def _teams_with_reads() -> list[int]:+ tag_queries(+ product=Product.DATA_MODELING, feature=Feature.WAREHOUSE_SUGGESTIONS, name="warehouse_suggestions_teams"+ )+ return [team_id for (team_id,) in sync_execute(TEAMS_WITH_READS_SQL, {"window_days": RULES.window_days})]+++async def get_warehouse_suggestion_team_batches(inputs: WarehouseSuggestionsInputs) -> list[list[int]]:+ return await database_sync_to_async_pool(team_batches)(inputs)+++async def generate_warehouse_suggestions(team_ids: list[int], run_id: str) -> BatchOutcome:+ async with Heartbeater():+ return await database_sync_to_async_pool(run_batch)(team_ids, run_id)diff --git a/products/warehouse_suggestions/backend/temporal/contracts.py b/products/warehouse_suggestions/backend/temporal/contracts.pynew file mode 100644index 000000000000..c6c55112120e--- /dev/null+++ b/products/warehouse_suggestions/backend/temporal/contracts.py@@ -0,0 +1,19 @@+from dataclasses import dataclass++WAREHOUSE_SUGGESTIONS_WORKFLOW_NAME = "warehouse-suggestions"+++@dataclass(frozen=True, kw_only=True)+class WarehouseSuggestionsInputs:+ batch_size: int = 25+ max_concurrent: int = 1+ rollout_percentage: float = 1.0+ team_ids: list[int] | None = None+++@dataclass(frozen=True, kw_only=True)+class BatchOutcome:+ processed: int = 0+ not_eligible: int = 0+ disabled: int = 0+ failed: int = 0diff --git a/products/warehouse_suggestions/backend/temporal/schedule.py b/products/warehouse_suggestions/backend/temporal/schedule.pynew file mode 100644index 000000000000..2cd206dd6235--- /dev/null+++ b/products/warehouse_suggestions/backend/temporal/schedule.py@@ -0,0 +1,40 @@+import datetime as dt++from django.conf import settings++from temporalio.client import (+ Client,+ Schedule,+ ScheduleActionStartWorkflow,+ ScheduleOverlapPolicy,+ SchedulePolicy,+ ScheduleSpec,+ ScheduleState,+)++from posthog.temporal.common.schedule import a_create_schedule, a_schedule_exists, a_update_schedule++from .contracts import WAREHOUSE_SUGGESTIONS_WORKFLOW_NAME, WarehouseSuggestionsInputs++WAREHOUSE_SUGGESTIONS_SCHEDULE_ID = "warehouse-suggestions-schedule"+CRON_AFTER_THE_DAILY_ROLLUP = "30 8 * * *"+PAUSED_ON_CREATE_NOTE = "Created paused. Resume once the warehouse object reads rollup is backfilled."+++async def create_warehouse_suggestions_schedule(client: Client) -> None:+ schedule = Schedule(+ action=ScheduleActionStartWorkflow(+ WAREHOUSE_SUGGESTIONS_WORKFLOW_NAME,+ WarehouseSuggestionsInputs(),+ id=WAREHOUSE_SUGGESTIONS_SCHEDULE_ID,+ task_queue=settings.DATA_MODELING_TASK_QUEUE,+ execution_timeout=dt.timedelta(hours=3),+ ),+ spec=ScheduleSpec(cron_expressions=[CRON_AFTER_THE_DAILY_ROLLUP]),+ policy=SchedulePolicy(overlap=ScheduleOverlapPolicy.SKIP),+ )+ if await a_schedule_exists(client, WAREHOUSE_SUGGESTIONS_SCHEDULE_ID):+ await a_update_schedule(client, WAREHOUSE_SUGGESTIONS_SCHEDULE_ID, schedule, keep_paused=True)+ return+ schedule.state = ScheduleState(paused=True, note=PAUSED_ON_CREATE_NOTE)+ await a_create_schedule(client, WAREHOUSE_SUGGESTIONS_SCHEDULE_ID, schedule, trigger_immediately=False)diff --git a/products/warehouse_suggestions/backend/temporal/workflows.py b/products/warehouse_suggestions/backend/temporal/workflows.pynew file mode 100644index 000000000000..bdecd6cf4657--- /dev/null+++ b/products/warehouse_suggestions/backend/temporal/workflows.py@@ -0,0 +1,58 @@+import asyncio+import datetime as dt+import dataclasses++from temporalio import workflow+from temporalio.common import RetryPolicy++from posthog.temporal.common.base import PostHogWorkflow++from .activities import generate_warehouse_suggestions, get_warehouse_suggestion_team_batches+from .contracts import WAREHOUSE_SUGGESTIONS_WORKFLOW_NAME, BatchOutcome, WarehouseSuggestionsInputs++RETRY_POLICY = RetryPolicy(+ maximum_attempts=3,+ initial_interval=dt.timedelta(seconds=30),+ backoff_coefficient=2.0,+ maximum_interval=dt.timedelta(minutes=5),+)++[email protected](name=WAREHOUSE_SUGGESTIONS_WORKFLOW_NAME)+class WarehouseSuggestionsWorkflow(PostHogWorkflow):+ inputs_cls = WarehouseSuggestionsInputs+ inputs_optional = True++ @workflow.run+ async def run(self, inputs: WarehouseSuggestionsInputs) -> BatchOutcome:+ batches = await workflow.execute_activity(+ get_warehouse_suggestion_team_batches,+ inputs,+ start_to_close_timeout=dt.timedelta(minutes=5),+ retry_policy=RETRY_POLICY,+ )+ semaphore = asyncio.Semaphore(inputs.max_concurrent)+ run_id = workflow.info().run_id++ async def run_batch(team_ids: list[int]) -> BatchOutcome:+ async with semaphore:+ return await workflow.execute_activity(+ generate_warehouse_suggestions,+ args=[team_ids, run_id],+ start_to_close_timeout=dt.timedelta(minutes=30),+ heartbeat_timeout=dt.timedelta(minutes=5),+ retry_policy=RETRY_POLICY,+ )++ outcomes = await asyncio.gather(*(run_batch(batch) for batch in batches), return_exceptions=True)+ total = BatchOutcome()+ for batch, outcome in zip(batches, outcomes):+ if isinstance(outcome, BaseException):+ outcome = BatchOutcome(failed=len(batch))+ total = BatchOutcome(+ **{+ field.name: getattr(total, field.name) + getattr(outcome, field.name)+ for field in dataclasses.fields(BatchOutcome)+ }+ )+ return totaldiff --git a/products/warehouse_suggestions/backend/tests/factories.py b/products/warehouse_suggestions/backend/tests/factories.pynew file mode 100644index 000000000000..09cce957ae72--- /dev/null+++ b/products/warehouse_suggestions/backend/tests/factories.py@@ -0,0 +1,109 @@+from collections.abc import Mapping, Sequence+from dataclasses import replace+from datetime import UTC, date, datetime, timedelta+from typing import Any+from uuid import UUID++from products.data_modeling.backend.facade.contracts import SavedQueryDefinition+from products.warehouse_suggestions.backend.facade.enums import WarehouseSuggestionSubjectKind+from products.warehouse_suggestions.backend.logic.candidates.base import CandidateContext+from products.warehouse_suggestions.backend.logic.inventory import TeamInventory+from products.warehouse_suggestions.backend.logic.reads import (+ ReadWindow,+ Subject,+ SubjectReads,+ SubjectRefreshes,+ TeamReads,+)+from products.warehouse_suggestions.backend.logic.rules import RULES, Rules, Surface++TODAY = date(2026, 10, 7)+CREATED_AT = datetime(2026, 8, 1, tzinfo=UTC)+++def view_subject(view_id: UUID) -> Subject:+ return Subject(kind=WarehouseSuggestionSubjectKind.SAVED_QUERY, id=view_id)+++def table_subject(table_id: UUID) -> Subject:+ return Subject(kind=WarehouseSuggestionSubjectKind.TABLE, id=table_id)+++def busy_reads(**overrides: Any) -> SubjectReads:+ reads = SubjectReads(+ human_requests=200,+ human_users=6,+ human_days=25,+ background_requests=0,+ human_reads=200,+ human_duration_ms=200 * 20_000,+ human_read_bytes=200 * 10**9,+ alone_reads=10,+ alone_duration_ms_median=10_000.0,+ alone_read_bytes_median=float(10**9),+ last_read_at=datetime(2026, 10, 6, tzinfo=UTC),+ requests_by_surface={Surface.SQL_EDITOR: 120, Surface.DASHBOARD: 80},+ )+ return replace(reads, **overrides)+++def view(view_id: UUID, name: str = "orders", **overrides: Any) -> SavedQueryDefinition:+ definition = SavedQueryDefinition(+ id=view_id,+ name=name,+ hogql="SELECT timestamp, event FROM events",+ materializes=False,+ is_test=False,+ is_managed=False,+ origin=None,+ created_at=CREATED_AT,+ )+ return replace(definition, **overrides)+++def team_reads(+ subjects: Mapping[Subject, SubjectReads],+ *,+ days_with_data: int = 30,+ recent_days_with_data: int = 7,+ refreshes: Mapping[UUID, SubjectRefreshes] | None = None,+ readers: int = 10,+) -> TeamReads:+ return TeamReads(+ window=ReadWindow.ending(TODAY, RULES),+ days_with_data=days_with_data,+ recent_days_with_data=recent_days_with_data,+ readers=readers,+ view_readers=10,+ view_reads=1000,+ subjects=subjects,+ refreshes=refreshes or {},+ )+++def context(+ reads: TeamReads,+ *,+ views: Sequence[SavedQueryDefinition] = (),+ table_names: Mapping[UUID, str] | None = None,+ certified: frozenset[Subject] = frozenset(),+ direct_table_ids: frozenset[UUID] = frozenset(),+ team_id: int = 1,+ rules: Rules = RULES,+) -> CandidateContext:+ return CandidateContext(+ team_id=team_id,+ reads=reads,+ inventory=TeamInventory(+ saved_queries={saved_query.id: saved_query for saved_query in views},+ table_names=table_names or {},+ certified=certified,+ direct_table_ids=direct_table_ids,+ ),+ rules=rules,+ run_id="run-1",+ )+++def days_ago(count: int) -> datetime:+ return datetime.combine(TODAY, datetime.min.time(), tzinfo=UTC) - timedelta(days=count)diff --git a/products/warehouse_suggestions/backend/tests/rollup.py b/products/warehouse_suggestions/backend/tests/rollup.pynew file mode 100644index 000000000000..55fc5fb91818--- /dev/null+++ b/products/warehouse_suggestions/backend/tests/rollup.py@@ -0,0 +1,71 @@+from datetime import date, datetime, time+from uuid import UUID++from posthog.clickhouse.client import sync_execute+from posthog.clickhouse.warehouse_object_reads import SHARDED_WAREHOUSE_OBJECT_READS_DAILY_TABLE, ReadKind+from posthog.dataclasses import frozen++from products.warehouse_suggestions.backend.facade.enums import WarehouseSuggestionSubjectKind++INSERT_READ_SQL = f"""+INSERT INTO {SHARDED_WAREHOUSE_OBJECT_READS_DAILY_TABLE}+SELECT+ %(team_id)s, %(day)s, %(read_kind)s, %(subject_kind)s, %(subject_id)s, %(workflow_id)s,+ %(lc_kind)s, %(lc_product)s, %(lc_feature)s, %(lc_access_method)s, %(source)s, %(scene)s,+ %(user_id)s > 0, %(read_alone)s,+ initializeAggregation('uniqState', %(request_id)s),+ initializeAggregation('uniqState', toInt64(%(user_id)s)),+ 1,+ toUInt64(%(duration_ms)s),+ toUInt64(%(read_bytes)s),+ initializeAggregation('quantilesState(0.5, 0.9)', toUInt64(%(duration_ms)s)),+ initializeAggregation('quantilesState(0.5, 0.9)', toUInt64(%(read_bytes)s)),+ toDateTime(%(event_time)s)+"""+++@frozen+class RollupRead:+ subject_id: UUID+ day: date+ request_id: str+ user_id: int = 1+ subject_kind: WarehouseSuggestionSubjectKind = WarehouseSuggestionSubjectKind.SAVED_QUERY+ read_kind: ReadKind = ReadKind.READ+ workflow_id: str = ""+ lc_kind: str = ""+ lc_product: str = ""+ lc_feature: str = ""+ lc_access_method: str = ""+ source: str = ""+ scene: str = "SQLEditor"+ read_alone: bool = False+ duration_ms: int = 1000+ read_bytes: int = 1000+++def seed_reads(team_id: int, reads: list[RollupRead]) -> None:+ for read in reads:+ sync_execute(+ INSERT_READ_SQL,+ {+ "team_id": team_id,+ "day": read.day,+ "read_kind": read.read_kind.value,+ "subject_kind": read.subject_kind.value,+ "subject_id": str(read.subject_id),+ "workflow_id": read.workflow_id,+ "lc_kind": read.lc_kind,+ "lc_product": read.lc_product,+ "lc_feature": read.lc_feature,+ "lc_access_method": read.lc_access_method,+ "source": read.source,+ "scene": read.scene,+ "user_id": read.user_id,+ "read_alone": read.read_alone,+ "request_id": read.request_id,+ "duration_ms": read.duration_ms,+ "read_bytes": read.read_bytes,+ "event_time": datetime.combine(read.day, time(hour=12)),+ },+ )diff --git a/products/warehouse_suggestions/backend/tests/test_api.py b/products/warehouse_suggestions/backend/tests/test_api.pyindex f7eef0d70e7b..da5e8d30afac 100644--- a/products/warehouse_suggestions/backend/tests/test_api.py+++ b/products/warehouse_suggestions/backend/tests/test_api.py@@ -1,4 +1,5 @@import json+from dataclasses import replacefrom uuid import UUIDfrom posthog.test.base import APIBaseTest@@ -6,6 +7,7 @@ from unittest.mock import patchfrom django.db import connectionfrom django.test.utils import CaptureQueriesContext+from django.utils import timezonefrom parameterized import parameterizedfrom rest_framework import status@@ -16,13 +18,20 @@ from posthog.models.activity_logging.activity_log import ActivityLogfrom products.access_control.backend.models.access_control import AccessControlfrom products.data_modeling.backend.facade.models import DataWarehouseSavedQueryfrom products.warehouse_sources.backend.facade.models import DataWarehouseTable+from products.warehouse_suggestions.backend.facade.contracts import (+ DeprecatePayload,+ MaterializePayload,+ SourceRef,+ SuggestionDraft,+)from products.warehouse_suggestions.backend.facade.enums import (WarehouseSuggestionDismissalReason,WarehouseSuggestionKind,WarehouseSuggestionStatus,WarehouseSuggestionSubjectKind,)-from products.warehouse_suggestions.backend.models import WarehouseSuggestion+from products.warehouse_suggestions.backend.logic.payloads import payload_to_json+from products.warehouse_suggestions.backend.models import WarehouseSuggestion, WarehouseSuggestionTeamConfigfrom .test_suggestions import ingest_one, make_draft@@ -30,6 +39,13 @@ REVIEW_FIELDS = ("reviewed_by_id", "reviewed_at", "dismissal_reason", "dismissalFLAG = "products.warehouse_suggestions.backend.presentation.views.is_warehouse_suggestions_enabled"+def ingest_surfaced(team_id: int, draft: SuggestionDraft) -> WarehouseSuggestion:+ suggestion = ingest_one(team_id, draft)+ WarehouseSuggestion.objects.for_team(team_id).filter(id=suggestion.id).update(surfaced_at=timezone.now())+ suggestion.refresh_from_db()+ return suggestion++class TestWarehouseSuggestionAPI(APIBaseTest):def setUp(self) -> None:super().setUp()@@ -65,13 +81,38 @@ class TestWarehouseSuggestionAPI(APIBaseTest):subject_kind: WarehouseSuggestionSubjectKind = WarehouseSuggestionSubjectKind.SAVED_QUERY,score: float = 1.0,) -> WarehouseSuggestion:- return ingest_one(+ return ingest_surfaced(self.team.id,make_draft(fingerprint=f"certify:{subject_id}", subject_kind=subject_kind, subject_id=subject_id, score=score),)+ def _suggest_materialize(+ self,+ *,+ score: float = 1.0,+ live_sources: tuple[SourceRef, ...] = (),+ unknown_sources: tuple[SourceRef, ...] = (),+ ) -> WarehouseSuggestion:+ return ingest_surfaced(+ self.team.id,+ replace(+ make_draft(fingerprint="materialize:orders", subject_id=self.view.id, score=score),+ kind=WarehouseSuggestionKind.MATERIALIZE,+ payload=MaterializePayload(+ subject_name="orders",+ refresh_interval_seconds=86400,+ saves_seconds_per_month=900.0,+ saves_bytes_per_month=0.0,+ freshness_today_seconds=None,+ freshness_after_seconds=86400,+ live_sources=live_sources,+ unknown_sources=unknown_sources,+ ),+ ),+ )+def _restrict(self, resource: str, resource_id: UUID | None, access_level: str) -> None:self.organization.available_product_features = [{"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL}@@ -88,6 +129,7 @@ class TestWarehouseSuggestionAPI(APIBaseTest):def test_list_dismiss_and_resume(self) -> None:low = self._suggest(self.view.id, score=2.0)high = self._suggest(self.table.id, subject_kind=WarehouseSuggestionSubjectKind.TABLE, score=9.0)+ ingest_one(self.team.id, make_draft(fingerprint="certify:waiting", subject_id=self.view.id, score=99.0))listed = self.client.get(f"{self.url}/")assert listed.status_code == status.HTTP_200_OK, listed.json()@@ -148,7 +190,11 @@ class TestWarehouseSuggestionAPI(APIBaseTest):"table": self._suggest(self.table.id, subject_kind=WarehouseSuggestionSubjectKind.TABLE).id,}WarehouseSuggestion.objects.for_team(self.team.id).filter(id=ids["table"]).update(- kind=WarehouseSuggestionKind.DEPRECATE, status=WarehouseSuggestionStatus.DISMISSED+ kind=WarehouseSuggestionKind.DEPRECATE,+ status=WarehouseSuggestionStatus.DISMISSED,+ payload=payload_to_json(+ DeprecatePayload(subject_name="stripe_charges", refresh_seconds_per_month=0, refresh_bytes_per_month=0)+ ),)response = self.client.get(f"{self.url}/?{query}")@@ -164,6 +210,50 @@ class TestWarehouseSuggestionAPI(APIBaseTest):assert response.status_code == status.HTTP_403_FORBIDDEN+ def test_lists_materialize_before_certify_whatever_their_scores(self) -> None:+ certify = self._suggest(self.table.id, subject_kind=WarehouseSuggestionSubjectKind.TABLE, score=900.0)+ materialize = self._suggest_materialize(score=1.0)++ listed = self.client.get(f"{self.url}/").json()["results"]++ assert [row["id"] for row in listed] == [str(materialize.id), str(certify.id)]++ def test_a_materialize_suggestion_hides_the_names_of_source_tables_the_reader_cannot_see(self) -> None:+ denied_table = DataWarehouseTable.objects.create(+ team=self.team,+ name="secret_payments",+ format=DataWarehouseTable.TableFormat.Parquet,+ url_pattern="s3://bucket/secret_payments",+ )+ self._suggest_materialize(+ live_sources=(SourceRef(name="events", warehouse_table_id=None),),+ unknown_sources=(+ SourceRef(name="stripe_charges", warehouse_table_id=self.table.id),+ SourceRef(name="secret_payments", warehouse_table_id=denied_table.id),+ ),+ )+ self._restrict("warehouse_table", denied_table.id, "none")++ payload = self.client.get(f"{self.url}/").json()["results"][0]["payload"]++ assert (payload["live_sources"], payload["unknown_sources"]) == (+ {"names": ["events"], "hidden_count": 0},+ {"names": ["stripe_charges"], "hidden_count": 1},+ )++ def test_status_reports_the_last_daily_run(self) -> None:+ before_any_run = self.client.get(f"{self.url}/status/").json()+ WarehouseSuggestionTeamConfig.objects.create(team=self.team, eligible=True, days_with_data=12)++ after_a_run = self.client.get(f"{self.url}/status/").json()++ assert (before_any_run["eligible"], before_any_run["days_with_data"], before_any_run["window_days"]) == (+ False,+ 0,+ 30,+ )+ assert (after_a_run["enabled"], after_a_run["eligible"], after_a_run["days_with_data"]) == (True, True, 12)+def test_a_member_sees_nothing_about_subjects_they_cannot_read(self) -> None:visible = self._suggest(self.table.id, subject_kind=WarehouseSuggestionSubjectKind.TABLE)denied_view = self._suggest(self.view.id)diff --git a/products/warehouse_suggestions/backend/tests/test_candidates.py b/products/warehouse_suggestions/backend/tests/test_candidates.pynew file mode 100644index 000000000000..8ffa8af12fd8--- /dev/null+++ b/products/warehouse_suggestions/backend/tests/test_candidates.py@@ -0,0 +1,175 @@+from dataclasses import replace+from datetime import timedelta+from uuid import uuid4++from posthog.test.base import BaseTest++from django.test import SimpleTestCase++from parameterized import parameterized++from products.warehouse_suggestions.backend.facade.contracts import CertifyPayload+from products.warehouse_suggestions.backend.logic.candidates.certify import CertifyCandidate+from products.warehouse_suggestions.backend.logic.candidates.deprecate import DeprecateCandidate+from products.warehouse_suggestions.backend.logic.candidates.materialize import (+ MaterializeCandidate,+ allowed_intervals,+ estimate_savings,+)+from products.warehouse_suggestions.backend.logic.rules import RULES, Surface+from products.warehouse_suggestions.backend.tests.factories import (+ busy_reads,+ context,+ table_subject,+ team_reads,+ view,+ view_subject,+)++VIEW_ID = uuid4()+AT_CERTIFY_FLOORS = {"human_users": 5, "human_days": 20}+HOUR = timedelta(hours=1)+DAY = timedelta(hours=24)+++class TestCertifyCandidate(SimpleTestCase):+ @parameterized.expand(+ [+ ("at_every_floor", {}, 30, False, True),+ ("one_person_short", {"human_users": 4}, 30, False, False),+ ("one_day_short", {"human_days": 19}, 30, False, False),+ ("one_surface", {"requests_by_surface": {Surface.SQL_EDITOR: 200}}, 30, False, False),+ (+ "unknown_surface_does_not_count",+ {"requests_by_surface": {Surface.SQL_EDITOR: 100, Surface.UNKNOWN: 100}},+ 30,+ False,+ False,+ ),+ ("day_floor_scales_while_warming_up", {"human_days": 10}, 15, False, True),+ ("already_certified", {}, 30, True, False),+ ]+ )+ def test_floors(+ self, _name: str, overrides: dict, days_with_data: int, certified: bool, expect_draft: bool+ ) -> None:+ subject = view_subject(VIEW_ID)+ reads = team_reads({subject: busy_reads(**{**AT_CERTIFY_FLOORS, **overrides})}, days_with_data=days_with_data)++ result = CertifyCandidate().evaluate(+ context(reads, views=[view(VIEW_ID)], certified=frozenset({subject}) if certified else frozenset())+ )++ assert [draft.subject_id for draft in result.drafts] == ([VIEW_ID] if expect_draft else [])++ @parameterized.expand(+ [+ ("two_person_team_read_by_both", 2, 2, True),+ ("solo_team", 1, 1, False),+ ("small_team_read_by_half", 6, 3, True),+ ("small_team_read_by_fewer_than_half", 6, 2, False),+ ("large_team_caps_at_five", 100, 5, True),+ ]+ )+ def test_people_floor_follows_team_size(+ self, _name: str, team_readers: int, human_users: int, expect_draft: bool+ ) -> None:+ reads = team_reads(+ {view_subject(VIEW_ID): busy_reads(**{**AT_CERTIFY_FLOORS, "human_users": human_users})},+ readers=team_readers,+ )++ result = CertifyCandidate().evaluate(context(reads, views=[view(VIEW_ID)]))++ assert [draft.subject_id for draft in result.drafts] == ([VIEW_ID] if expect_draft else [])++ def test_only_the_top_share_by_requests_times_people_is_proposed(self) -> None:+ views = [view(uuid4(), name=f"view_{position}") for position in range(10)]+ reads = team_reads(+ {view_subject(v.id): busy_reads(human_requests=100 + position) for position, v in enumerate(views)}+ )++ result = CertifyCandidate().evaluate(context(reads, views=views))++ assert [draft.subject_id for draft in result.drafts] == [views[-1].id]++ def test_proposes_warehouse_tables_but_not_backing_tables_of_materialized_views(self) -> None:+ table_id, backing_table_id = uuid4(), uuid4()+ reads = team_reads({table_subject(table_id): busy_reads(), table_subject(backing_table_id): busy_reads()})++ result = CertifyCandidate().evaluate(context(reads, table_names={table_id: "stripe_charges"}))++ assert [(draft.subject_id, draft.payload) for draft in result.drafts] == [+ (table_id, CertifyPayload(subject_name="stripe_charges"))+ ]+++class TestMaterializeRules(SimpleTestCase):+ @parameterized.expand(+ [+ ("read_most_days", 25, [HOUR, timedelta(hours=6), DAY]),+ ("read_on_few_days", 10, [DAY]),+ ]+ )+ def test_read_cadence_sets_the_shortest_interval(self, _name: str, human_days: int, expected: list) -> None:+ reads = busy_reads(human_days=human_days)++ intervals = allowed_intervals(+ context(team_reads({})), [HOUR, timedelta(hours=6), DAY, timedelta(days=7)], reads+ )++ assert intervals == expected++ @parameterized.expand([("at_floor", 90, True), ("one_read_short", 89, False)])+ def test_time_saved_floor(self, _name: str, human_reads: int, expect_clear: bool) -> None:+ reads = busy_reads(+ human_reads=human_reads,+ human_duration_ms=human_reads * 10_000,+ alone_duration_ms_median=10_000.0,+ human_read_bytes=human_reads,+ alone_read_bytes_median=1.0,+ )++ estimate = estimate_savings(context(team_reads({})), reads, DAY)++ assert estimate.clears_a_floor is expect_clear++ @parameterized.expand(+ [+ ("limited", "SELECT timestamp, event FROM events ORDER BY timestamp DESC LIMIT 10"),+ ("no_key_column", "SELECT count() FROM events"),+ ]+ )+ def test_a_view_that_cannot_refresh_incrementally_is_not_proposed(self, _name: str, hogql: str) -> None:+ reads = team_reads({view_subject(VIEW_ID): busy_reads()})+ not_incremental = view(VIEW_ID, hogql=hogql)++ result = MaterializeCandidate().evaluate(context(reads, views=[not_incremental]))++ assert result.drafts == ()+ assert [rejection.reason for rejection in result.rejections] == ["its query cannot refresh incrementally"]+++class TestDeprecateCandidate(SimpleTestCase):+ def test_waits_for_a_full_window_of_read_data(self) -> None:+ materialized = view(VIEW_ID, materializes=True)++ result = DeprecateCandidate().evaluate(context(team_reads({}, days_with_data=29), views=[materialized]))++ assert (result.drafts, result.skipped_reason) == ((), "needs 30 days of read data, has 29")+++class TestDeprecateBackgroundReads(BaseTest):+ @parameterized.expand([("background_reads_count", True, []), ("only_people_count", False, [VIEW_ID])])+ def test_a_view_read_only_by_background_traffic(+ self, _name: str, counts_background_reads: bool, expected_subjects: list+ ) -> None:+ rules = replace(RULES, deprecate=replace(RULES.deprecate, counts_background_reads=counts_background_reads))+ reads = team_reads(+ {view_subject(VIEW_ID): busy_reads(human_requests=0, human_users=0, human_days=0, background_requests=40)}+ )+ candidate_context = context(reads, views=[view(VIEW_ID, materializes=True)], team_id=self.team.pk, rules=rules)++ result = DeprecateCandidate().evaluate(candidate_context)++ assert [draft.subject_id for draft in result.drafts] == expected_subjectsdiff --git a/products/warehouse_suggestions/backend/tests/test_job.py b/products/warehouse_suggestions/backend/tests/test_job.pynew file mode 100644index 000000000000..e5ed202510d5--- /dev/null+++ b/products/warehouse_suggestions/backend/tests/test_job.py@@ -0,0 +1,105 @@+from datetime import UTC, date, datetime, time, timedelta+from uuid import uuid4++from posthog.test.base import BaseTest, ClickhouseTestMixin++from products.data_modeling.backend.facade.models import DAG, DataWarehouseSavedQuery, Edge, Node, NodeType+from products.warehouse_suggestions.backend.facade.enums import WarehouseSuggestionKind, WarehouseSuggestionStatus+from products.warehouse_suggestions.backend.logic.job import TeamRunStatus, run_team+from products.warehouse_suggestions.backend.logic.reads import RollupDays+from products.warehouse_suggestions.backend.logic.rules import RULES+from products.warehouse_suggestions.backend.models import WarehouseSuggestion, WarehouseSuggestionTeamConfig+from products.warehouse_suggestions.backend.tests.rollup import RollupRead, seed_reads+from products.warehouse_suggestions.backend.tests.test_suggestions import ingest_one, make_draft++TODAY = date.today()+NOW = datetime.combine(TODAY, time(hour=9), tzinfo=UTC)+BEFORE_THE_WINDOW = NOW - timedelta(days=2 * RULES.window_days)+SCENES = ("SQLEditor", "Dashboard")+FULL_ROLLUP = RollupDays(days_with_data=RULES.window_days, recent_days_with_data=RULES.lifecycle.expire_after_days)+++class TestRunTeam(ClickhouseTestMixin, BaseTest):+ def _view(+ self, name: str, dag: DAG, *, materialized: bool = False, created_at: datetime = BEFORE_THE_WINDOW+ ) -> tuple[DataWarehouseSavedQuery, Node]:+ saved_query = DataWarehouseSavedQuery.objects.create(+ team=self.team,+ name=name,+ query={"kind": "HogQLQuery", "query": "SELECT timestamp, event FROM events"},+ )+ DataWarehouseSavedQuery.objects.filter(id=saved_query.id).update(created_at=created_at)+ node = Node.objects.create(+ team=self.team,+ dag=dag,+ name=name,+ saved_query=saved_query,+ type=NodeType.MAT_VIEW if materialized else NodeType.VIEW,+ )+ return saved_query, node++ def test_proposes_each_kind_from_a_month_of_reads_and_surfaces_them(self) -> None:+ dag = DAG.objects.create(team=self.team, name="Default")+ busy, busy_node = self._view("busy_orders", dag)+ for name, properties in [("events", {"origin": "posthog"}), ("legacy_orders", {})]:+ table = Node.objects.create(team=self.team, dag=dag, name=name, type=NodeType.TABLE, properties=properties)+ Edge.objects.create(team=self.team, dag=dag, source=table, target=busy_node)+ unread, _ = self._view("old_rollup", dag, materialized=True)+ feeds_another, source_node = self._view("feeds_another", dag, materialized=True)+ _, dependent_node = self._view("reads_feeds_another", dag)+ created_today, _ = self._view("new_rollup", dag, materialized=True, created_at=NOW)+ Edge.objects.create(team=self.team, dag=dag, source=source_node, target=dependent_node)+ seed_reads(+ self.team.pk,+ [+ RollupRead(+ subject_id=busy.id,+ day=TODAY - timedelta(days=day),+ request_id=f"{day}-{request}",+ user_id=1 + (day + request) % 6,+ scene=SCENES[request],+ read_alone=True,+ duration_ms=30_000,+ )+ for day in range(1, 31)+ for request in range(2)+ ],+ )++ result = run_team(self.team.pk, run_id="run-1", today=TODAY, rollup_days=FULL_ROLLUP, now=NOW)++ assert result.status == TeamRunStatus.PROCESSED+ assert sorted(+ WarehouseSuggestion.objects.for_team(self.team.pk).values_list("kind", "subject_id", "status")+ ) == sorted(+ [+ (WarehouseSuggestionKind.CERTIFY, busy.id, WarehouseSuggestionStatus.PROPOSED),+ (WarehouseSuggestionKind.MATERIALIZE, busy.id, WarehouseSuggestionStatus.PROPOSED),+ (WarehouseSuggestionKind.DEPRECATE, unread.id, WarehouseSuggestionStatus.PROPOSED),+ ]+ )+ assert not (+ WarehouseSuggestion.objects.for_team(self.team.pk)+ .filter(subject_id__in=[feeds_another.id, created_today.id])+ .exists()+ )+ assert not WarehouseSuggestion.objects.for_team(self.team.pk).filter(surfaced_at__isnull=True).exists()+ materialize = WarehouseSuggestion.objects.for_team(self.team.pk).get(kind=WarehouseSuggestionKind.MATERIALIZE)+ assert (materialize.payload["refresh_interval_seconds"], materialize.run_id) == (24 * 60 * 60, "run-1")+ assert [source["name"] for source in materialize.payload["live_sources"]] == ["events"]++ def test_a_team_without_view_reads_is_recorded_as_not_eligible_and_its_open_suggestions_still_resolve(+ self,+ ) -> None:+ about_a_deleted_view = ingest_one(self.team.pk, make_draft(subject_id=uuid4()))++ result = run_team(self.team.pk, run_id="run-1", today=TODAY, rollup_days=FULL_ROLLUP, now=NOW)++ config = WarehouseSuggestionTeamConfig.objects.get(team_id=self.team.pk)+ about_a_deleted_view.refresh_from_db()+ assert (result.status, config.eligible, config.last_run_at is not None, about_a_deleted_view.status) == (+ TeamRunStatus.NOT_ELIGIBLE,+ False,+ True,+ WarehouseSuggestionStatus.AUTO_RESOLVED,+ )diff --git a/products/warehouse_suggestions/backend/tests/test_lifecycle.py b/products/warehouse_suggestions/backend/tests/test_lifecycle.pynew file mode 100644index 000000000000..cbed4671eeda--- /dev/null+++ b/products/warehouse_suggestions/backend/tests/test_lifecycle.py@@ -0,0 +1,213 @@+from collections import Counter+from datetime import UTC, datetime, timedelta+from uuid import UUID, uuid4++from posthog.test.base import BaseTest++from django.test import SimpleTestCase++from parameterized import parameterized++from products.warehouse_suggestions.backend.facade.contracts import (+ CertifyPayload,+ DeprecatePayload,+ MaterializePayload,+ SuggestionDraft,+ SuggestionPayload,+)+from products.warehouse_suggestions.backend.facade.enums import (+ WarehouseSuggestionDismissalReason,+ WarehouseSuggestionKind,+ WarehouseSuggestionStatus,+)+from products.warehouse_suggestions.backend.logic.candidates.base import CandidateContext+from products.warehouse_suggestions.backend.logic.candidates.registry import CANDIDATES+from products.warehouse_suggestions.backend.logic.lifecycle import _pick_in_turns, apply_run+from products.warehouse_suggestions.backend.logic.suggestions import transition_to+from products.warehouse_suggestions.backend.models import WarehouseSuggestion+from products.warehouse_suggestions.backend.tests.factories import context, team_reads, view, view_subject++NOW = datetime(2026, 10, 7, 9, tzinfo=UTC)+PAYLOADS: dict[WarehouseSuggestionKind, SuggestionPayload] = {+ WarehouseSuggestionKind.CERTIFY: CertifyPayload(subject_name="orders"),+ WarehouseSuggestionKind.DEPRECATE: DeprecatePayload(+ subject_name="orders", refresh_seconds_per_month=0, refresh_bytes_per_month=0+ ),+ WarehouseSuggestionKind.MATERIALIZE: MaterializePayload(+ subject_name="orders",+ refresh_interval_seconds=86400,+ saves_seconds_per_month=900,+ saves_bytes_per_month=0,+ freshness_today_seconds=None,+ freshness_after_seconds=86400,+ live_sources=(),+ unknown_sources=(),+ ),+}+++class TestApplyRun(BaseTest):+ def _context(self, *view_ids: UUID, recent_days_with_data: int = 7) -> CandidateContext:+ return context(+ team_reads({}, recent_days_with_data=recent_days_with_data),+ views=[view(view_id, materializes=True) for view_id in view_ids],+ team_id=self.team.pk,+ )++ def _draft(+ self, ctx: CandidateContext, kind: WarehouseSuggestionKind, view_id: UUID, score: float+ ) -> SuggestionDraft:+ return CANDIDATES[kind].draft(ctx, view_subject(view_id), PAYLOADS[kind], score=score, score_inputs={})++ def _surfaced_kinds(self) -> Counter[str]:+ return Counter(+ WarehouseSuggestion.objects.for_team(self.team.pk)+ .filter(surfaced_at__isnull=False)+ .values_list("kind", flat=True)+ )++ @parameterized.expand(+ [+ ("first_week_puts_certify_first", False, {"certify": 3, "materialize": 2}),+ ("later_weeks_put_materialize_first_despite_a_lower_score", True, {"materialize": 3, "certify": 2}),+ ]+ )+ def test_surfaces_five_a_day_at_most_three_per_kind(+ self, _name: str, surfaced_before: bool, expected: dict[str, int]+ ) -> None:+ if surfaced_before:+ old_id = uuid4()+ apply_run(+ self._context(old_id),+ [self._draft(self._context(old_id), WarehouseSuggestionKind.DEPRECATE, old_id, 1)],+ NOW - timedelta(days=10),+ surface=True,+ )+ WarehouseSuggestion.objects.for_team(self.team.pk).update(status=WarehouseSuggestionStatus.ACCEPTED)+ view_ids = [uuid4() for _ in range(8)]+ ctx = self._context(*view_ids)+ drafts = [+ *(self._draft(ctx, WarehouseSuggestionKind.CERTIFY, view_id, 1000) for view_id in view_ids[:4]),+ *(self._draft(ctx, WarehouseSuggestionKind.MATERIALIZE, view_id, 1) for view_id in view_ids[4:]),+ ]++ apply_run(ctx, drafts, NOW, surface=True)+ apply_run(ctx, drafts, NOW + timedelta(hours=1), surface=True)++ surfaced = self._surfaced_kinds()+ if surfaced_before:+ surfaced.pop(WarehouseSuggestionKind.DEPRECATE)+ assert surfaced == expected++ @parameterized.expand(+ [+ ("not_now_below_three_times", WarehouseSuggestionDismissalReason.NOT_NOW, 10.0, 29.0, False),+ ("not_now_at_three_times", WarehouseSuggestionDismissalReason.NOT_NOW, 10.0, 30.0, True),+ ("not_now_zero_stays_zero", WarehouseSuggestionDismissalReason.NOT_NOW, 0.0, 0.0, False),+ ("not_useful_never_returns", WarehouseSuggestionDismissalReason.NOT_USEFUL, 10.0, 1000.0, False),+ ]+ )+ def test_reproposes_a_dismissal_only_when_the_score_triples_after_not_now(+ self,+ _name: str,+ reason: WarehouseSuggestionDismissalReason,+ dismissed_score: float,+ new_score: float,+ expect_reproposed: bool,+ ) -> None:+ view_id = uuid4()+ ctx = self._context(view_id)+ apply_run(+ ctx, [self._draft(ctx, WarehouseSuggestionKind.CERTIFY, view_id, dismissed_score)], NOW, surface=False+ )+ row = WarehouseSuggestion.objects.for_team(self.team.pk).get()+ transition_to(row.id, self.team.pk, WarehouseSuggestionStatus.DISMISSED, user_id=self.user.id, reason=reason)++ apply_run(ctx, [self._draft(ctx, WarehouseSuggestionKind.CERTIFY, view_id, new_score)], NOW, surface=False)++ row.refresh_from_db()+ assert (row.status, row.reproposed_count) == (+ (WarehouseSuggestionStatus.PROPOSED, 1) if expect_reproposed else (WarehouseSuggestionStatus.DISMISSED, 0)+ )++ @parameterized.expand(+ [+ ("seven_days_unseen_with_data", 7, WarehouseSuggestionStatus.EXPIRED),+ ("a_missing_day_does_not_count", 6, WarehouseSuggestionStatus.PROPOSED),+ ]+ )+ def test_expires_after_seven_days_without_evidence(+ self, _name: str, recent_days_with_data: int, expected: WarehouseSuggestionStatus+ ) -> None:+ view_id = uuid4()+ ctx = self._context(view_id, recent_days_with_data=recent_days_with_data)+ apply_run(ctx, [self._draft(ctx, WarehouseSuggestionKind.DEPRECATE, view_id, 1)], NOW, surface=False)+ WarehouseSuggestion.objects.for_team(self.team.pk).update(last_seen_at=NOW - timedelta(days=8))++ apply_run(ctx, [], NOW, surface=False)++ assert WarehouseSuggestion.objects.for_team(self.team.pk).get().status == expected++ @parameterized.expand(+ [("expired", WarehouseSuggestionStatus.EXPIRED), ("auto_resolved", WarehouseSuggestionStatus.AUTO_RESOLVED)]+ )+ def test_a_closed_suggestion_revives_into_the_queue_when_its_evidence_returns(+ self, _name: str, closed_status: WarehouseSuggestionStatus+ ) -> None:+ view_id = uuid4()+ ctx = self._context(view_id)+ draft = self._draft(ctx, WarehouseSuggestionKind.DEPRECATE, view_id, 1)+ apply_run(ctx, [draft], NOW - timedelta(days=10), surface=True)+ WarehouseSuggestion.objects.for_team(self.team.pk).update(status=closed_status)++ apply_run(ctx, [draft], NOW, surface=False)++ revived = WarehouseSuggestion.objects.for_team(self.team.pk).get()+ assert (revived.status, revived.surfaced_at) == (WarehouseSuggestionStatus.PROPOSED, None)++ def test_auto_resolves_when_the_view_is_gone_or_already_handled(self) -> None:+ deleted_id, materialized_id = uuid4(), uuid4()+ ctx = self._context(deleted_id, materialized_id)+ apply_run(+ ctx,+ [+ self._draft(ctx, WarehouseSuggestionKind.CERTIFY, deleted_id, 1),+ self._draft(ctx, WarehouseSuggestionKind.MATERIALIZE, materialized_id, 1),+ ],+ NOW,+ surface=False,+ )++ apply_run(self._context(materialized_id), [], NOW, surface=False)++ assert set(WarehouseSuggestion.objects.for_team(self.team.pk).values_list("status", flat=True)) == {+ WarehouseSuggestionStatus.AUTO_RESOLVED+ }+++CERTIFY = WarehouseSuggestionKind.CERTIFY+DEPRECATE = WarehouseSuggestionKind.DEPRECATE+MATERIALIZE = WarehouseSuggestionKind.MATERIALIZE+WAITING = [+ WarehouseSuggestion(id=UUID(int=1), kind=CERTIFY, score=5.0),+ WarehouseSuggestion(id=UUID(int=2), kind=CERTIFY, score=900.0),+ WarehouseSuggestion(id=UUID(int=3), kind=DEPRECATE, score=1.0),+ WarehouseSuggestion(id=UUID(int=4), kind=MATERIALIZE, score=2.0),+ WarehouseSuggestion(id=UUID(int=5), kind=MATERIALIZE, score=3.0),+]+++class TestPickInTurns(SimpleTestCase):+ @parameterized.expand(+ [+ ("one_of_each_kind_per_turn_best_score_first", 5, {}, [5, 3, 2, 4, 1]),+ ("a_kind_at_its_cap_is_skipped", 5, {MATERIALIZE: 3}, [3, 2, 1]),+ ("slots_run_out_mid_turn", 2, {}, [5, 3]),+ ]+ )+ def test_picks_kinds_in_order_and_rows_by_score_within_a_kind(+ self, _name: str, slots: int, already_open: dict[str, int], expected_ids: list[int]+ ) -> None:+ chosen = _pick_in_turns(WAITING, (MATERIALIZE, DEPRECATE, CERTIFY), slots, Counter(already_open), 3)++ assert chosen == [UUID(int=row_id) for row_id in expected_ids]diff --git a/products/warehouse_suggestions/backend/tests/test_reads.py b/products/warehouse_suggestions/backend/tests/test_reads.pynew file mode 100644index 000000000000..121470d533bd--- /dev/null+++ b/products/warehouse_suggestions/backend/tests/test_reads.py@@ -0,0 +1,111 @@+from collections.abc import Mapping+from datetime import date, timedelta+from uuid import UUID, uuid4++from posthog.test.base import BaseTest, ClickhouseTestMixin++from posthog.clickhouse.client import sync_execute+from posthog.clickhouse.warehouse_object_reads import TRUNCATE_WAREHOUSE_OBJECT_READS_DAILY_TABLES_SQL++from products.warehouse_suggestions.backend.facade.enums import WarehouseSuggestionSubjectKind+from products.warehouse_suggestions.backend.logic.reads import (+ ReadWindow,+ RollupDays,+ Subject,+ SubjectReads,+ read_rollup_days,+ read_team_reads,+)+from products.warehouse_suggestions.backend.logic.rules import RULES, Surface+from products.warehouse_suggestions.backend.tests.rollup import RollupRead, seed_reads++TODAY = date.today()+YESTERDAY = TODAY - timedelta(days=1)+WINDOW = ReadWindow.ending(TODAY, RULES)+FULL_ROLLUP = RollupDays(days_with_data=RULES.window_days, recent_days_with_data=RULES.lifecycle.expire_after_days)++HUMAN = True+BACKGROUND = False++TAG_CASES: list[tuple[str, dict[str, str | int], bool, Surface | None]] = [+ ("mcp", {"source": "mcp"}, HUMAN, Surface.MCP),+ ("cli", {"source": "cli", "scene": ""}, HUMAN, Surface.MCP),+ ("posthog_ai", {"source": "posthog_ai"}, HUMAN, Surface.POSTHOG_AI),+ ("desktop", {"source": "desktop", "scene": "Dashboard"}, HUMAN, Surface.DESKTOP),+ ("endpoint_execution", {"lc_feature": "endpoint_execution", "scene": ""}, HUMAN, Surface.ENDPOINTS),+ ("endpoints_product", {"lc_product": "endpoints", "scene": ""}, HUMAN, Surface.ENDPOINTS),+ ("dashboard", {"scene": "Dashboard"}, HUMAN, Surface.DASHBOARD),+ ("insight_feature", {"lc_feature": "insight", "scene": ""}, HUMAN, Surface.INSIGHT),+ ("saved_insights_scene", {"scene": "SavedInsights"}, HUMAN, Surface.INSIGHT),+ ("sql_editor_product", {"lc_product": "sql_editor", "scene": ""}, HUMAN, Surface.SQL_EDITOR),+ ("notebook", {"lc_product": "notebooks", "scene": ""}, HUMAN, Surface.NOTEBOOK),+ ("api_key", {"lc_access_method": "personal_api_key", "scene": ""}, HUMAN, Surface.API),+ ("other_scene", {"scene": "DataWarehouse"}, HUMAN, Surface.APP),+ ("untagged", {"scene": ""}, HUMAN, Surface.UNKNOWN),+ ("cache_warmup", {"lc_feature": "cache_warmup"}, BACKGROUND, None),+ ("temporal", {"lc_kind": "temporal"}, BACKGROUND, None),+ ("no_user", {"user_id": 0}, BACKGROUND, None),+]+++class TestReadTeamReads(ClickhouseTestMixin, BaseTest):+ def setUp(self) -> None:+ super().setUp()+ for truncate_sql in TRUNCATE_WAREHOUSE_OBJECT_READS_DAILY_TABLES_SQL():+ sync_execute(truncate_sql)++ def test_rules_classify_each_tag_combination_as_human_or_background_and_by_surface(self) -> None:+ subjects = {name: uuid4() for name, *_ in TAG_CASES}+ seed_reads(+ self.team.pk,+ [+ RollupRead(subject_id=subjects[name], day=YESTERDAY, request_id=name, **tags) # type: ignore[arg-type]+ for name, tags, *_ in TAG_CASES+ ],+ )++ reads = read_team_reads(self.team.pk, WINDOW, RULES, FULL_ROLLUP)++ classified = {name: _classification(reads.subjects, subjects[name]) for name, *_ in TAG_CASES}+ assert classified == {name: (human, surface) for name, _, human, surface in TAG_CASES}++ def test_counts_requests_people_days_and_median_cost_of_reads_alone_inside_the_window(self) -> None:+ view = uuid4()+ seed_reads(+ self.team.pk + 1, [RollupRead(subject_id=uuid4(), day=TODAY - timedelta(days=3), request_id="other")]+ )+ seed_reads(+ self.team.pk,+ [+ RollupRead(subject_id=view, day=YESTERDAY, request_id="a", user_id=1, read_alone=True, duration_ms=100),+ RollupRead(subject_id=view, day=YESTERDAY, request_id="a", user_id=1, read_alone=True, duration_ms=300),+ RollupRead(subject_id=view, day=TODAY - timedelta(days=2), request_id="b", user_id=2, duration_ms=900),+ RollupRead(subject_id=view, day=TODAY - timedelta(days=40), request_id="old", user_id=3),+ RollupRead(subject_id=view, day=TODAY, request_id="today", user_id=4),+ RollupRead(+ subject_id=uuid4(),+ day=YESTERDAY,+ request_id="table",+ user_id=5,+ subject_kind=WarehouseSuggestionSubjectKind.TABLE,+ ),+ ],+ )++ rollup_days = read_rollup_days(WINDOW)+ reads = read_team_reads(self.team.pk, WINDOW, RULES, rollup_days)+ view_reads = reads.subjects[Subject(kind=WarehouseSuggestionSubjectKind.SAVED_QUERY, id=view)]++ assert rollup_days == RollupDays(days_with_data=3, recent_days_with_data=3)+ assert (reads.readers, reads.view_readers, reads.view_reads) == (3, 2, 2)+ assert (view_reads.human_requests, view_reads.human_users, view_reads.human_days) == (2, 2, 2)+ assert (view_reads.human_reads, view_reads.human_duration_ms, view_reads.alone_reads) == (3, 1300, 2)+ assert 100 <= view_reads.alone_duration_ms_median <= 300+++def _classification(subjects: Mapping[Subject, SubjectReads], subject_id: UUID) -> tuple[bool, Surface | None]:+ reads = subjects[Subject(kind=WarehouseSuggestionSubjectKind.SAVED_QUERY, id=subject_id)]+ if reads.human_requests == 0:+ return BACKGROUND, None+ (surface,) = reads.requests_by_surface+ return HUMAN, surfacediff --git a/products/warehouse_suggestions/backend/tests/test_rules_diff.py b/products/warehouse_suggestions/backend/tests/test_rules_diff.pynew file mode 100644index 000000000000..99c42e9be78f--- /dev/null+++ b/products/warehouse_suggestions/backend/tests/test_rules_diff.py@@ -0,0 +1,86 @@+from uuid import uuid4++from django.test import SimpleTestCase++from parameterized import parameterized++from products.warehouse_suggestions.backend.facade.enums import WarehouseSuggestionKind+from products.warehouse_suggestions.backend.logic.candidates.certify import CertifyCandidate+from products.warehouse_suggestions.backend.logic.rules import RULES, rules_version+from products.warehouse_suggestions.backend.logic.rules_diff import (+ InvalidRuleOverrideError,+ KindDiff,+ diff_candidates,+ override_rules,+ results_the_job_would_keep,+)+from products.warehouse_suggestions.backend.tests.factories import busy_reads, context, team_reads, view, view_subject+++class TestRulesDiff(SimpleTestCase):+ def test_a_raised_floor_reports_the_candidates_it_removes(self) -> None:+ busy, quiet = view(uuid4(), name="busy"), view(uuid4(), name="quiet")+ reads = team_reads(+ {+ view_subject(busy.id): busy_reads(human_requests=500, human_users=9),+ view_subject(quiet.id): busy_reads(human_requests=400, human_users=6),+ }+ )+ proposed = override_rules(RULES, ["certify.top_share=1", "certify.min_users=7", "certify.min_user_share=1"])+ current = override_rules(RULES, ["certify.top_share=1"])++ diff = diff_candidates(+ {+ WarehouseSuggestionKind.CERTIFY: CertifyCandidate().evaluate(+ context(reads, views=[busy, quiet], rules=current)+ )+ },+ {+ WarehouseSuggestionKind.CERTIFY: CertifyCandidate().evaluate(+ context(reads, views=[busy, quiet], rules=proposed)+ )+ },+ )++ assert diff[WarehouseSuggestionKind.CERTIFY] == KindDiff(added=(), removed=("quiet",), reranked=())++ def test_an_eligibility_floor_the_team_no_longer_meets_removes_every_candidate(self) -> None:+ busy = view(uuid4(), name="busy")+ reads = team_reads({view_subject(busy.id): busy_reads()})+ current, proposed = (+ context(reads, views=[busy], rules=override_rules(RULES, ["certify.top_share=1", *extra]))+ for extra in ([], ["eligibility.min_view_reads=1001"])+ )++ diff = diff_candidates(+ results_the_job_would_keep(+ current, {WarehouseSuggestionKind.CERTIFY: CertifyCandidate().evaluate(current)}+ ),+ results_the_job_would_keep(+ proposed, {WarehouseSuggestionKind.CERTIFY: CertifyCandidate().evaluate(proposed)}+ ),+ )++ assert diff[WarehouseSuggestionKind.CERTIFY] == KindDiff(added=(), removed=("busy",), reranked=())++ def test_a_new_kind_order_changes_the_rules_version(self) -> None:+ reordered = override_rules(RULES, ["lifecycle.kind_order=certify, deprecate, materialize"])++ assert reordered.lifecycle.kind_order == (+ WarehouseSuggestionKind.CERTIFY,+ WarehouseSuggestionKind.DEPRECATE,+ WarehouseSuggestionKind.MATERIALIZE,+ )+ assert rules_version(reordered) != rules_version(RULES)++ @parameterized.expand(+ [+ ("no_section", "min_users=7"),+ ("unknown_rule", "certify.min_people=7"),+ ("not_a_number_rule", "traffic.background_kinds=temporal"),+ ("unknown_kind_in_an_order", "lifecycle.kind_order=certify,nope"),+ ]+ )+ def test_rejects_an_override_it_cannot_apply(self, _name: str, assignment: str) -> None:+ with self.assertRaises(InvalidRuleOverrideError):+ override_rules(RULES, [assignment])diff --git a/products/warehouse_suggestions/backend/tests/test_suggestions.py b/products/warehouse_suggestions/backend/tests/test_suggestions.pyindex 7349ad47bec3..30a3e76762c9 100644--- a/products/warehouse_suggestions/backend/tests/test_suggestions.py+++ b/products/warehouse_suggestions/backend/tests/test_suggestions.py@@ -8,7 +8,11 @@ from parameterized import parameterizedfrom posthog.models.activity_logging.activity_log import ActivityLog-from products.warehouse_suggestions.backend.facade.contracts import SuggestionAlreadyDecidedError, SuggestionDraft+from products.warehouse_suggestions.backend.facade.contracts import (+ CertifyPayload,+ SuggestionAlreadyDecidedError,+ SuggestionDraft,+)from products.warehouse_suggestions.backend.facade.enums import (WarehouseSuggestionKind,WarehouseSuggestionStatus,@@ -35,7 +39,7 @@ def make_draft(fingerprint=fingerprint,subject_kind=subject_kind,subject_id=subject_id,- payload={"name": "orders"},+ payload=CertifyPayload(subject_name="orders"),payload_version=1,rules_version="abc123",evidence={"distinct_readers": 4},@@ -74,7 +78,7 @@ class TestTransitions(BaseTest):"auto_resolved_to_proposed",WarehouseSuggestionStatus.AUTO_RESOLVED,WarehouseSuggestionStatus.PROPOSED,- False,+ True,),("expired_to_dismissed", WarehouseSuggestionStatus.EXPIRED, WarehouseSuggestionStatus.DISMISSED, False),]diff --git a/products/warehouse_suggestions/backend/tests/test_temporal.py b/products/warehouse_suggestions/backend/tests/test_temporal.pynew file mode 100644index 000000000000..cf4ce6cec358--- /dev/null+++ b/products/warehouse_suggestions/backend/tests/test_temporal.py@@ -0,0 +1,85 @@+import uuid++from posthog.test.base import BaseTest+from unittest.mock import patch++from parameterized import parameterized+from temporalio.testing import WorkflowEnvironment+from temporalio.worker import UnsandboxedWorkflowRunner, Worker++from posthog.clickhouse.client.execute import KillSwitchLevel+from posthog.models.team import Team++from products.warehouse_suggestions.backend.logic.job import TeamRunResult, TeamRunStatus+from products.warehouse_suggestions.backend.logic.reads import RollupDays+from products.warehouse_suggestions.backend.temporal import (+ ACTIVITIES as WAREHOUSE_SUGGESTIONS_ACTIVITIES,+ WORKFLOWS,+)+from products.warehouse_suggestions.backend.temporal.activities import team_batches+from products.warehouse_suggestions.backend.temporal.contracts import (+ WAREHOUSE_SUGGESTIONS_WORKFLOW_NAME,+ BatchOutcome,+ WarehouseSuggestionsInputs,+)++ACTIVITIES = "products.warehouse_suggestions.backend.temporal.activities"+++class TestTeamBatches(BaseTest):+ @parameterized.expand(+ [+ ("kill_switch_off", KillSwitchLevel.OFF, True),+ ("kill_switch_on", KillSwitchLevel.LIGHT, False),+ ]+ )+ def test_picks_flagged_main_environments_skips_demo_teams_and_stops_under_the_kill_switch(+ self, _name: str, kill_switch: KillSwitchLevel, expect_team: bool+ ) -> None:+ demo_team = Team.objects.create(organization=self.organization, is_demo=True)+ unflagged_team = Team.objects.create(organization=self.organization)+ child_environment = Team.objects.create(+ organization=self.organization, project=self.project, parent_team=self.team+ )+ flagged = {self.team.pk, demo_team.pk, child_environment.pk}++ with (+ patch(f"{ACTIVITIES}.get_kill_switch_level", return_value=kill_switch),+ patch(f"{ACTIVITIES}.is_warehouse_suggestions_enabled", side_effect=lambda team: team.pk in flagged),+ ):+ batches = team_batches(+ WarehouseSuggestionsInputs(+ team_ids=[self.team.pk, demo_team.pk, unflagged_team.pk, child_environment.pk]+ )+ )++ assert batches == ([[self.team.pk]] if expect_team else [])+++async def test_a_worker_runs_a_nonempty_batch_without_failing_a_team() -> None:+ task_queue = str(uuid.uuid4())+ with (+ patch(f"{ACTIVITIES}.team_batches", return_value=[[1, 2]]),+ patch(f"{ACTIVITIES}.read_rollup_days", return_value=RollupDays(days_with_data=30, recent_days_with_data=7)),+ patch(+ f"{ACTIVITIES}.run_team",+ side_effect=lambda team_id, **_: TeamRunResult(team_id=team_id, status=TeamRunStatus.PROCESSED),+ ),+ ):+ async with await WorkflowEnvironment.start_time_skipping() as environment:+ async with Worker(+ environment.client,+ task_queue=task_queue,+ workflows=WORKFLOWS,+ activities=WAREHOUSE_SUGGESTIONS_ACTIVITIES,+ workflow_runner=UnsandboxedWorkflowRunner(),+ ):+ outcome = await environment.client.execute_workflow(+ WAREHOUSE_SUGGESTIONS_WORKFLOW_NAME,+ WarehouseSuggestionsInputs(),+ id=str(uuid.uuid4()),+ task_queue=task_queue,+ result_type=BatchOutcome,+ )++ assert outcome == BatchOutcome(processed=2)diff --git a/products/warehouse_suggestions/frontend/generated/api.schemas.ts b/products/warehouse_suggestions/frontend/generated/api.schemas.tsindex 0583b985e089..806ed43467b3 100644--- a/products/warehouse_suggestions/frontend/generated/api.schemas.ts+++ b/products/warehouse_suggestions/frontend/generated/api.schemas.ts@@ -7,6 +7,54 @@* PostHog API - generated* OpenAPI spec version: 1.0.0*/+export interface WarehouseSuggestionCertifyPayloadApi {+ /** Name of the view or table to certify. */+ subject_name: string+}++export interface WarehouseSuggestionDeprecatePayloadApi {+ /** Name of the unread view to deprecate. */+ subject_name: string+ /** Time its refreshes take in a month, in seconds. */+ refresh_seconds_per_month: number+ /** Bytes its refreshes read in a month. */+ refresh_bytes_per_month: number+}++export interface WarehouseSuggestionVisibleSourcesApi {+ /** Names of the sources the caller may see. */+ names: string[]+ /** How many more sources exist that the caller may not see. */+ hidden_count: number+}++export interface WarehouseSuggestionMaterializePayloadApi {+ /** Sources that are always current, such as PostHog tables and direct connections. */+ live_sources: WarehouseSuggestionVisibleSourcesApi+ /** Sources with no sync schedule, so their freshness is unknown. */+ unknown_sources: WarehouseSuggestionVisibleSourcesApi+ /** Name of the view to materialize. */+ subject_name: string+ /** Proposed refresh interval, in seconds. */+ refresh_interval_seconds: number+ /** Query time materializing saves in a month, in seconds. */+ saves_seconds_per_month: number+ /** Bytes materializing saves from scanning in a month. */+ saves_bytes_per_month: number+ /**+ * How old the view's data can be today, in seconds. Null when its sources are live.+ * @nullable+ */+ freshness_today_seconds: number | null+ /** How old the data can be once materialized, in seconds. */+ freshness_after_seconds: number+}++export type WarehouseSuggestionPayloadApi =+ | WarehouseSuggestionCertifyPayloadApi+ | WarehouseSuggestionDeprecatePayloadApi+ | WarehouseSuggestionMaterializePayloadApi+export interface WarehouseSuggestionReviewerApi {/** User id. */id: number@@ -88,11 +136,6 @@ export const WarehouseSuggestionAssetOutcomeEnumApi = {Unused: 'unused',} as const-/**- * What accepting this suggestion would create or change. Shape depends on kind.- */-export type WarehouseSuggestionApiPayload = { [key: string]: unknown }-/*** The usage numbers that led to this suggestion.*/@@ -106,7 +149,7 @@ export type WarehouseSuggestionApiCreatedAsset = { [key: string]: unknown } | nuexport interface WarehouseSuggestionApi {/** What accepting this suggestion would create or change. Shape depends on kind. */- payload: WarehouseSuggestionApiPayload+ readonly payload: WarehouseSuggestionPayloadApi/** The usage numbers that led to this suggestion. */evidence: WarehouseSuggestionApiEvidence/**@@ -203,6 +246,27 @@ export interface DismissWarehouseSuggestionApi {note?: string}+export interface WarehouseSuggestionStatusApi {+ /** False when the project turned suggestions off. */+ enabled: boolean+ /** Whether the project reads its views often enough to get suggestions. */+ eligible: boolean+ /** Days of read history the last run had, up to the window. */+ days_with_data: number+ /** Days of read history a full window holds. */+ window_days: number+ /**+ * Why new suggestions stopped showing. Null while they show.+ * @nullable+ */+ paused_reason: string | null+ /**+ * When the daily job last ran for this project.+ * @nullable+ */+ refreshed_at: string | null+}+export type WarehouseSuggestionsListParams = {/*** Only return suggestions of this kind.diff --git a/products/warehouse_suggestions/frontend/generated/api.ts b/products/warehouse_suggestions/frontend/generated/api.tsindex fe6ce2d36c3f..33434707628a 100644--- a/products/warehouse_suggestions/frontend/generated/api.ts+++ b/products/warehouse_suggestions/frontend/generated/api.ts@@ -12,6 +12,7 @@ import type {DismissWarehouseSuggestionApi,PaginatedWarehouseSuggestionListApi,WarehouseSuggestionApi,+ WarehouseSuggestionStatusApi,WarehouseSuggestionsListParams,} from './api.schemas'@@ -89,3 +90,17 @@ export const warehouseSuggestionsResumeCreate = async (method: 'POST',})}++export const getWarehouseSuggestionsStatusRetrieveUrl = (projectId: string) => {+ return `/api/projects/${projectId}/warehouse_suggestions/status/`+}++export const warehouseSuggestionsStatusRetrieve = async (+ projectId: string,+ options?: RequestInit+): Promise<WarehouseSuggestionStatusApi> => {+ return apiMutator<WarehouseSuggestionStatusApi>(getWarehouseSuggestionsStatusRetrieveUrl(projectId), {+ ...options,+ method: 'GET',+ })+}diff --git a/products/warehouse_suggestions/turbo.json b/products/warehouse_suggestions/turbo.jsonindex 2473b86b299b..9243871fd478 100644--- a/products/warehouse_suggestions/turbo.json+++ b/products/warehouse_suggestions/turbo.json@@ -8,7 +8,8 @@"backend/routes.py","backend/webhook_consumers.py","backend/models.py",- "backend/migrations/**"+ "backend/migrations/**",+ "backend/temporal/**"],"outputs": [],"cache": truediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 5833a09ff32b..4fdd2e29c48f 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -74965,6 +74965,51 @@ export namespace Schemas {results: WarehouseColumnStatistics[];}+ export interface WarehouseSuggestionCertifyPayload {+ /** Name of the view or table to certify. */+ subject_name: string;+ }++ export interface WarehouseSuggestionDeprecatePayload {+ /** Name of the unread view to deprecate. */+ subject_name: string;+ /** Time its refreshes take in a month, in seconds. */+ refresh_seconds_per_month: number;+ /** Bytes its refreshes read in a month. */+ refresh_bytes_per_month: number;+ }++ export interface WarehouseSuggestionVisibleSources {+ /** Names of the sources the caller may see. */+ names: string[];+ /** How many more sources exist that the caller may not see. */+ hidden_count: number;+ }++ export interface WarehouseSuggestionMaterializePayload {+ /** Sources that are always current, such as PostHog tables and direct connections. */+ live_sources: WarehouseSuggestionVisibleSources;+ /** Sources with no sync schedule, so their freshness is unknown. */+ unknown_sources: WarehouseSuggestionVisibleSources;+ /** Name of the view to materialize. */+ subject_name: string;+ /** Proposed refresh interval, in seconds. */+ refresh_interval_seconds: number;+ /** Query time materializing saves in a month, in seconds. */+ saves_seconds_per_month: number;+ /** Bytes materializing saves from scanning in a month. */+ saves_bytes_per_month: number;+ /**+ * How old the view's data can be today, in seconds. Null when its sources are live.+ * @nullable+ */+ freshness_today_seconds: number | null;+ /** How old the data can be once materialized, in seconds. */+ freshness_after_seconds: number;+ }++ export type WarehouseSuggestionPayload = WarehouseSuggestionCertifyPayload | WarehouseSuggestionDeprecatePayload | WarehouseSuggestionMaterializePayload;+export interface WarehouseSuggestionReviewer {/** User id. */id: number;@@ -75032,11 +75077,6 @@ export namespace Schemas {Unused: 'unused',} as const;- /**- * What accepting this suggestion would create or change. Shape depends on kind.- */- export type WarehouseSuggestionPayload = { [key: string]: unknown };-/*** The usage numbers that led to this suggestion.*/@@ -75050,7 +75090,7 @@ export namespace Schemas {export interface WarehouseSuggestion {/** What accepting this suggestion would create or change. Shape depends on kind. */- payload: WarehouseSuggestionPayload;+ readonly payload: WarehouseSuggestionPayload;/** The usage numbers that led to this suggestion. */evidence: WarehouseSuggestionEvidence;/**@@ -109640,6 +109680,27 @@ export namespace Schemas {schema_name: string | null;}+ export interface WarehouseSuggestionStatus {+ /** False when the project turned suggestions off. */+ enabled: boolean;+ /** Whether the project reads its views often enough to get suggestions. */+ eligible: boolean;+ /** Days of read history the last run had, up to the window. */+ days_with_data: number;+ /** Days of read history a full window holds. */+ window_days: number;+ /**+ * Why new suggestions stopped showing. Null while they show.+ * @nullable+ */+ paused_reason: string | null;+ /**+ * When the daily job last ran for this project.+ * @nullable+ */+ refreshed_at: string | null;+ }+/*** * `user_created` - user_created* * `posthog_ai` - posthog_aidiff --git a/tach.toml b/tach.tomlindex 4e43dacf635c..a4b5f7585454 100644--- a/tach.toml+++ b/tach.toml@@ -143,6 +143,7 @@ depends_on = ["products.today","products.tracing","products.visual_review",+ "products.warehouse_suggestions","products.mcp_analytics","products.mcp_registry","products.web_analytics",@@ -1657,6 +1658,7 @@ path = "products.warehouse_suggestions"depends_on = ["posthog","products.access_control",+ "products.data_catalog","products.data_modeling","products.warehouse_sources",]