: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): add the suggestion model and review api (#112705)
Thiago Salvatoreb1844e0bc7d0
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yamlindex 62fe2cae41de..84069ef605e4 100644--- a/.semgrep/rules/security/idor-team-scoped-models.yaml+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml@@ -442,6 +442,7 @@ rules:|WikiPageProposal|WarehouseColumnAnnotation|WarehouseColumnStatistics+ |WarehouseSuggestion|WebAnalyticsAchievementProgress|WebAnalyticsFilterPreset|WebAnalyticsInteraction@@ -881,6 +882,7 @@ rules:|WikiPageProposal|WarehouseColumnAnnotation|WarehouseColumnStatistics+ |WarehouseSuggestion|WebAnalyticsAchievementProgress|WebAnalyticsFilterPreset|WebAnalyticsInteractiondiff --git a/frontend/package.json b/frontend/package.jsonindex 8c83698d2da5..4a8445ccd235 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -154,6 +154,7 @@"@posthog/products-tracing": "workspace:*","@posthog/products-visual-review": "workspace:*","@posthog/products-warehouse-sources": "workspace:*",+ "@posthog/products-warehouse-suggestions": "workspace:*","@posthog/products-web-analytics": "workspace:*","@posthog/products-webmcp": "workspace:*","@posthog/products-wizard": "workspace:*",diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex e23d4c6be512..284144c7bea4 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -863,6 +863,9 @@ importers:'@posthog/products-warehouse-sources':specifier: workspace:*version: link:../products/warehouse_sources+ '@posthog/products-warehouse-suggestions':+ specifier: workspace:*+ version: link:../products/warehouse_suggestions'@posthog/products-web-analytics':specifier: workspace:*version: link:../products/web_analytics@@ -5266,6 +5269,8 @@ importers:products/warehouse_sources_queue: {}+ products/warehouse_suggestions: {}+products/web_analytics:dependencies:'@posthog/brand':diff --git a/posthog/models/activity_logging/activity_log.py b/posthog/models/activity_logging/activity_log.pyindex 7f07b03e5637..157dff68727f 100644--- a/posthog/models/activity_logging/activity_log.py+++ b/posthog/models/activity_logging/activity_log.py@@ -130,6 +130,7 @@ ActivityScope = Literal["TableCertification","DataQualityCheck","DataQualityCheckSchedule",+ "WarehouseSuggestion","Billing","Loop","StamphogRepoConfig",@@ -360,6 +361,7 @@ common_field_exclusions = [field_with_masked_contents: dict[AuditableScope, list[str]] = {"AccountView": ["name", "content", "text_content"],+ "WarehouseSuggestion": ["dismissal_note"],"HogFunction": ["inputs","mappings",@@ -734,6 +736,11 @@ field_exclusions: dict[AuditableScope, list[str]] = {"saved_query","table",],+ "WarehouseSuggestion": [+ "evidence",+ "score_inputs",+ "payload",+ ],"Loop": [# FK relations are not JSON-serializable for the change detail (same reason# FeatureFlag/Subscription exclude theirs).diff --git a/posthog/settings/web.py b/posthog/settings/web.pyindex 56d1f8c84244..19f86f6c9501 100644--- a/posthog/settings/web.py+++ b/posthog/settings/web.py@@ -126,6 +126,7 @@ PRODUCTS_APPS = ["products.data_quality.backend.apps.DataQualityConfig","products.security.backend.apps.SecurityConfig","products.webmcp.backend.apps.WebmcpConfig",+ "products.warehouse_suggestions.backend.apps.WarehouseSuggestionsConfig",]INSTALLED_APPS = [@@ -691,6 +692,7 @@ SPECTACULAR_SETTINGS = {"TraceNodeKindEnum": "products.ai_observability.backend.facade.contracts.TRACE_NODE_KINDS","SignalSourceProduct": "products.signals.backend.enums.SIGNAL_SOURCE_PRODUCT_VALUES","SignalSourceType": "products.signals.backend.enums.SIGNAL_SOURCE_TYPE_VALUES",+ "DismissalReasonEnum": "products.signals.backend.views.SIGNAL_REPORT_DISMISSAL_REASON_CHOICES","ErrorTrackingIssueSeverityRuleEnum": ["low", "medium", "high", "critical"],## The choices come from a typing.Literal via get_args; there is no class.diff --git a/posthog/test/repo_invariants/setup_receivers_baseline.txt b/posthog/test/repo_invariants/setup_receivers_baseline.txtindex b7cb8207fe34..f88885bc6c16 100644--- a/posthog/test/repo_invariants/setup_receivers_baseline.txt+++ b/posthog/test/repo_invariants/setup_receivers_baseline.txt@@ -51,6 +51,7 @@ model_activity:products.tasks.backend.activity_logging.handle_loop_changemodel_activity:products.tracing.backend.activity_logging.handle_traces_retention_rule_activitymodel_activity:products.warehouse_sources.backend.activity_logging.handle_external_data_schema_changemodel_activity:products.warehouse_sources.backend.activity_logging.handle_external_data_source_change+model_activity:products.warehouse_suggestions.backend.activity_logging.handle_warehouse_suggestion_activitypost_delete:ee.vercel.receivers.delete_experiment_experimentation_itempost_delete:ee.vercel.receivers.delete_resource_experimentation_itempost_delete:posthog.caching.organization_serializer_cache._connect_invalidation.<locals>.receiver_fndiff --git a/posthog/test/repo_invariants/test_pagination_contract.py b/posthog/test/repo_invariants/test_pagination_contract.pyindex 7611d637b132..9448acbb7770 100644--- a/posthog/test/repo_invariants/test_pagination_contract.py+++ b/posthog/test/repo_invariants/test_pagination_contract.py@@ -252,6 +252,7 @@ EXISTING_CUSTOM_LIST_VIEWSETS = {"products.visual_review.backend.presentation.views.RunViewSet","products.warehouse_sources.backend.presentation.views.column_statistics.WarehouseColumnStatisticsViewSet","products.warehouse_sources.backend.presentation.views.public_source_configs.PublicSourceConfigViewSet",+ "products.warehouse_suggestions.backend.presentation.views.WarehouseSuggestionViewSet","products.web_analytics.backend.api.custom_bot_rules.CustomBotRuleViewSet","products.web_analytics.backend.api.heatmaps_api.HeatmapViewSet","products.web_analytics.backend.api.heatmaps_api.LegacyHeatmapViewSet",diff --git a/products/platform_features/frontend/generated/api.schemas.ts b/products/platform_features/frontend/generated/api.schemas.tsindex dce5b53d7f7e..4964d0a48144 100644--- a/products/platform_features/frontend/generated/api.schemas.ts+++ b/products/platform_features/frontend/generated/api.schemas.ts@@ -1453,6 +1453,7 @@ export type ActivityLogListParams = {* * `TableCertification` - TableCertification* * `DataQualityCheck` - DataQualityCheck* * `DataQualityCheckSchedule` - DataQualityCheckSchedule+ * * `WarehouseSuggestion` - WarehouseSuggestion* * `Billing` - Billing* * `Loop` - Loop* * `StamphogRepoConfig` - StamphogRepoConfig@@ -1557,6 +1558,7 @@ export const ActivityLogListScope = {TableCertification: 'TableCertification',DataQualityCheck: 'DataQualityCheck',DataQualityCheckSchedule: 'DataQualityCheckSchedule',+ WarehouseSuggestion: 'WarehouseSuggestion',Billing: 'Billing',Loop: 'Loop',StamphogRepoConfig: 'StamphogRepoConfig',@@ -1648,6 +1650,7 @@ export const ActivityLogListScope = {* * `TableCertification` - TableCertification* * `DataQualityCheck` - DataQualityCheck* * `DataQualityCheckSchedule` - DataQualityCheckSchedule+ * * `WarehouseSuggestion` - WarehouseSuggestion* * `Billing` - Billing* * `Loop` - Loop* * `StamphogRepoConfig` - StamphogRepoConfig@@ -1740,6 +1743,7 @@ export const ActivityLogListScopesItem = {TableCertification: 'TableCertification',DataQualityCheck: 'DataQualityCheck',DataQualityCheckSchedule: 'DataQualityCheckSchedule',+ WarehouseSuggestion: 'WarehouseSuggestion',Billing: 'Billing',Loop: 'Loop',StamphogRepoConfig: 'StamphogRepoConfig',diff --git a/products/warehouse_suggestions/__init__.py b/products/warehouse_suggestions/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/warehouse_suggestions/backend/__init__.py b/products/warehouse_suggestions/backend/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/warehouse_suggestions/backend/activity_logging.py b/products/warehouse_suggestions/backend/activity_logging.pynew file mode 100644index 000000000000..b8f232ab521a--- /dev/null+++ b/products/warehouse_suggestions/backend/activity_logging.py@@ -0,0 +1,33 @@+from typing import Any, Optional, cast++from posthog.models import User+from posthog.models.activity_logging.activity_log import AuditableScope, Detail, changes_between, log_activity+from posthog.models.signals import model_activity_signal, mutable_receiver++from .models import WarehouseSuggestion+++@mutable_receiver(model_activity_signal, sender=WarehouseSuggestion)+def handle_warehouse_suggestion_activity(+ sender: type,+ scope: str,+ before_update: Optional[WarehouseSuggestion],+ after_update: WarehouseSuggestion,+ activity: str,+ user: Optional[User],+ was_impersonated: bool = False,+ **kwargs: Any,+) -> None:+ log_activity(+ organization_id=None,+ team_id=after_update.team_id,+ user=user,+ was_impersonated=was_impersonated,+ item_id=str(after_update.id),+ scope=scope,+ activity=activity,+ detail=Detail(+ name=f"{after_update.kind} suggestion",+ changes=changes_between(cast(AuditableScope, scope), previous=before_update, current=after_update),+ ),+ )diff --git a/products/warehouse_suggestions/backend/apps.py b/products/warehouse_suggestions/backend/apps.pynew file mode 100644index 000000000000..a9a596e086cc--- /dev/null+++ b/products/warehouse_suggestions/backend/apps.py@@ -0,0 +1,10 @@+from django.apps import AppConfig+++class WarehouseSuggestionsConfig(AppConfig):+ name = "products.warehouse_suggestions.backend"+ label = "warehouse_suggestions"+ verbose_name = "Warehouse suggestions"++ def ready(self) -> None:+ from . import activity_logging # noqa: F401, PLC0415diff --git a/products/warehouse_suggestions/backend/facade/__init__.py b/products/warehouse_suggestions/backend/facade/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/warehouse_suggestions/backend/facade/api.py b/products/warehouse_suggestions/backend/facade/api.pynew file mode 100644index 000000000000..b171c6fd3626--- /dev/null+++ b/products/warehouse_suggestions/backend/facade/api.py@@ -0,0 +1,152 @@+"""Facade for warehouse_suggestions."""++from collections.abc import Sequence+from typing import TYPE_CHECKING+from uuid import UUID++from ..logic import suggestions+from ..logic.access import SubjectAccess, visible_suggestions+from ..logic.flags import is_warehouse_suggestions_enabled+from ..models import WarehouseSuggestion+from .contracts import (+ SubjectEditAccessRequiredError,+ Suggestion,+ SuggestionDraft,+ SuggestionNotFoundError,+ SuggestionPage,+ SuggestionReviewer,+)+from .enums import (+ WarehouseSuggestionAssetOutcome,+ WarehouseSuggestionDismissalReason,+ WarehouseSuggestionKind,+ WarehouseSuggestionStatus,+ WarehouseSuggestionSubjectKind,+)++if TYPE_CHECKING:+ from products.access_control.backend.facade.user_access_control import UserAccessControl++__all__ = [+ "dismiss_suggestion",+ "get_suggestion",+ "is_warehouse_suggestions_enabled",+ "list_suggestions",+ "resume_suggestion",+ "upsert_suggestions",+]+++def upsert_suggestions(team_id: int, drafts: Sequence[SuggestionDraft]) -> None:+ suggestions.upsert_suggestions(team_id, drafts)+++def list_suggestions(+ team_id: int,+ user_access_control: "UserAccessControl",+ *,+ kind: WarehouseSuggestionKind | None,+ status: WarehouseSuggestionStatus | None,+ limit: int,+ 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])+++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)+++def dismiss_suggestion(+ team_id: int,+ user_access_control: "UserAccessControl",+ suggestion_id: UUID,+ *,+ user_id: int,+ reason: WarehouseSuggestionDismissalReason,+ note: str | None,+) -> Suggestion:+ return _decide(+ team_id,+ user_access_control,+ suggestion_id,+ WarehouseSuggestionStatus.DISMISSED,+ user_id=user_id,+ reason=reason,+ note=note,+ )+++def resume_suggestion(+ team_id: int, user_access_control: "UserAccessControl", suggestion_id: UUID, *, user_id: int+) -> Suggestion:+ return _decide(team_id, user_access_control, suggestion_id, WarehouseSuggestionStatus.PROPOSED, user_id=user_id)+++def _decide(+ team_id: int,+ user_access_control: "UserAccessControl",+ suggestion_id: UUID,+ new_status: WarehouseSuggestionStatus,+ *,+ user_id: int,+ reason: WarehouseSuggestionDismissalReason | None = None,+ note: str | None = None,+) -> Suggestion:+ row, access = _visible_suggestion(team_id, user_access_control, suggestion_id)+ if not access.can_act_on(row):+ raise SubjectEditAccessRequiredError(WarehouseSuggestionSubjectKind(row.subject_kind))+ decided = suggestions.transition_to(+ row.id,+ team_id,+ new_status,+ user_id=user_id,+ reason=reason,+ note=note,+ transitions=suggestions.HUMAN_TRANSITIONS,+ )+ return _to_contract(decided, access)+++def _visible_suggestion(+ team_id: int, user_access_control: "UserAccessControl", suggestion_id: UUID+) -> tuple[WarehouseSuggestion, SubjectAccess]:+ visible, access = visible_suggestions(team_id, user_access_control, suggestion_id=suggestion_id)+ row = visible.first()+ if row is None:+ raise SuggestionNotFoundError(suggestion_id)+ return row, access+++def _to_contract(row: WarehouseSuggestion, access: SubjectAccess) -> 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_version=row.payload_version,+ evidence=row.evidence,+ evidence_window_start=row.evidence_window_start,+ evidence_window_end=row.evidence_window_end,+ last_seen_at=row.last_seen_at,+ score=row.score,+ status=WarehouseSuggestionStatus(row.status),+ surfaced_at=row.surfaced_at,+ reviewed_by=_to_reviewer(row),+ reviewed_at=row.reviewed_at,+ dismissal_reason=WarehouseSuggestionDismissalReason(row.dismissal_reason) if row.dismissal_reason else None,+ dismissal_note=row.dismissal_note,+ created_asset=row.created_asset,+ asset_outcome=WarehouseSuggestionAssetOutcome(row.asset_outcome) if row.asset_outcome else None,+ can_act=access.can_act_on(row),+ )+++def _to_reviewer(row: WarehouseSuggestion) -> SuggestionReviewer | None:+ if row.reviewed_by is None:+ return None+ return SuggestionReviewer(id=row.reviewed_by.id, first_name=row.reviewed_by.first_name, email=row.reviewed_by.email)diff --git a/products/warehouse_suggestions/backend/facade/contracts.py b/products/warehouse_suggestions/backend/facade/contracts.pynew file mode 100644index 000000000000..a73c52c559d5--- /dev/null+++ b/products/warehouse_suggestions/backend/facade/contracts.py@@ -0,0 +1,84 @@+"""Contract types for warehouse_suggestions."""++from datetime import datetime+from typing import Any+from uuid import UUID++from posthog.dataclasses import frozen++from .enums import (+ WarehouseSuggestionAssetOutcome,+ WarehouseSuggestionDismissalReason,+ WarehouseSuggestionKind,+ WarehouseSuggestionStatus,+ WarehouseSuggestionSubjectKind,+)+++@frozen+class SuggestionDraft:+ kind: WarehouseSuggestionKind+ fingerprint: str+ subject_kind: WarehouseSuggestionSubjectKind+ subject_id: UUID+ payload: dict[str, Any]+ payload_version: int+ rules_version: str+ evidence: dict[str, Any]+ evidence_window_start: datetime+ evidence_window_end: datetime+ score: float+ score_inputs: dict[str, Any]+ run_id: str+++@frozen+class SuggestionReviewer:+ id: int+ first_name: str+ email: str+++@frozen+class Suggestion:+ id: UUID+ kind: WarehouseSuggestionKind+ subject_kind: WarehouseSuggestionSubjectKind+ subject_id: UUID+ payload: dict[str, Any]+ payload_version: int+ evidence: dict[str, Any]+ evidence_window_start: datetime+ evidence_window_end: datetime+ last_seen_at: datetime+ score: float+ status: WarehouseSuggestionStatus+ surfaced_at: datetime | None+ reviewed_by: SuggestionReviewer | None+ reviewed_at: datetime | None+ dismissal_reason: WarehouseSuggestionDismissalReason | None+ dismissal_note: str | None+ created_asset: dict[str, Any] | None+ asset_outcome: WarehouseSuggestionAssetOutcome | None+ can_act: bool+++@frozen+class SuggestionPage:+ count: int+ results: list[Suggestion]+++class SuggestionNotFoundError(Exception):+ pass+++class SubjectEditAccessRequiredError(Exception):+ def __init__(self, subject_kind: WarehouseSuggestionSubjectKind) -> None:+ super().__init__(subject_kind)+ self.subject_kind = subject_kind+++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()}.")diff --git a/products/warehouse_suggestions/backend/facade/enums.py b/products/warehouse_suggestions/backend/facade/enums.pynew file mode 100644index 000000000000..3c1529d2b104--- /dev/null+++ b/products/warehouse_suggestions/backend/facade/enums.py@@ -0,0 +1,34 @@+"""Exported enums for warehouse_suggestions."""++from posthog.enums import LabeledStrEnum+++class WarehouseSuggestionKind(LabeledStrEnum):+ CERTIFY = "certify"+ DEPRECATE = "deprecate"+ MATERIALIZE = "materialize"+++class WarehouseSuggestionStatus(LabeledStrEnum):+ PROPOSED = "proposed"+ ACCEPTED = "accepted"+ DISMISSED = "dismissed"+ EXPIRED = "expired"+ AUTO_RESOLVED = ("auto_resolved", "Auto-resolved")+++class WarehouseSuggestionSubjectKind(LabeledStrEnum):+ SAVED_QUERY = ("saved_query", "Saved query")+ TABLE = "table"+++class WarehouseSuggestionDismissalReason(LabeledStrEnum):+ NOT_USEFUL = ("not_useful", "Not useful")+ NOT_NOW = ("not_now", "Not now")+ OTHER = "other"+++class WarehouseSuggestionAssetOutcome(LabeledStrEnum):+ LIVE = "live"+ DELETED = "deleted"+ UNUSED = "unused"diff --git a/products/warehouse_suggestions/backend/logic/__init__.py b/products/warehouse_suggestions/backend/logic/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/warehouse_suggestions/backend/logic/access.py b/products/warehouse_suggestions/backend/logic/access.pynew file mode 100644index 000000000000..dc07572a91b3--- /dev/null+++ b/products/warehouse_suggestions/backend/logic/access.py@@ -0,0 +1,98 @@+from collections import defaultdict+from collections.abc import Collection, Mapping+from typing import TYPE_CHECKING, Protocol+from uuid import UUID++from django.db.models import Q, QuerySet++from posthog.dataclasses import frozen++from products.data_modeling.backend.facade.api import allowed_saved_query_ids, backing_table_ids_by_saved_query+from products.warehouse_sources.backend.facade.api import allowed_table_ids++from ..facade.enums import WarehouseSuggestionKind, WarehouseSuggestionStatus, WarehouseSuggestionSubjectKind+from ..models import WarehouseSuggestion++if TYPE_CHECKING:+ from products.access_control.backend.facade.user_access_control import AccessControlLevel, UserAccessControl+++class AllowedSubjectIds(Protocol):+ def __call__(+ self,+ team_id: int,+ user_access_control: "UserAccessControl",+ *,+ required_level: "AccessControlLevel" = ...,+ ids: Collection[UUID] | None = ...,+ ) -> frozenset[UUID]: ...+++ALLOWED_SUBJECT_IDS: Mapping[WarehouseSuggestionSubjectKind, AllowedSubjectIds] = {+ WarehouseSuggestionSubjectKind.SAVED_QUERY: allowed_saved_query_ids,+ WarehouseSuggestionSubjectKind.TABLE: allowed_table_ids,+}+++@frozen+class SubjectAccess:+ readable: Mapping[WarehouseSuggestionSubjectKind, frozenset[UUID]]+ editable: Mapping[WarehouseSuggestionSubjectKind, frozenset[UUID]]++ def readable_q(self) -> Q:+ readable = Q(pk__in=[])+ for subject_kind, subject_ids in self.readable.items():+ readable |= Q(subject_kind=subject_kind, subject_id__in=subject_ids)+ return readable++ def can_act_on(self, suggestion: WarehouseSuggestion) -> bool:+ return suggestion.subject_id in self.editable.get(+ WarehouseSuggestionSubjectKind(suggestion.subject_kind), frozenset()+ )+++def visible_suggestions(+ team_id: int,+ user_access_control: "UserAccessControl",+ *,+ suggestion_id: UUID | None = None,+ kind: WarehouseSuggestionKind | None = None,+ status: WarehouseSuggestionStatus | None = None,+) -> tuple[QuerySet[WarehouseSuggestion], SubjectAccess]:+ suggestions = WarehouseSuggestion.objects.for_team(team_id)+ if suggestion_id is not None:+ suggestions = suggestions.filter(id=suggestion_id)+ if kind is not None:+ suggestions = suggestions.filter(kind=kind)+ 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")+ return visible, access+++def subject_access(+ team_id: int, user_access_control: "UserAccessControl", suggestions: QuerySet[WarehouseSuggestion]+) -> SubjectAccess:+ subject_ids: defaultdict[WarehouseSuggestionSubjectKind, set[UUID]] = defaultdict(set)+ for subject_kind, subject_id in suggestions.order_by().values_list("subject_kind", "subject_id").distinct():+ subject_ids[WarehouseSuggestionSubjectKind(subject_kind)].add(subject_id)+ table_ids = subject_ids[WarehouseSuggestionSubjectKind.TABLE]+ table_ids.difference_update(backing_table_ids_by_saved_query(team_id, table_ids=table_ids))+ readable = _allowed(team_id, user_access_control, "viewer", subject_ids)+ editable = _allowed(team_id, user_access_control, "editor", readable)+ return SubjectAccess(readable=readable, editable=editable)+++def _allowed(+ team_id: int,+ user_access_control: "UserAccessControl",+ required_level: "AccessControlLevel",+ subject_ids: Mapping[WarehouseSuggestionSubjectKind, Collection[UUID]],+) -> dict[WarehouseSuggestionSubjectKind, frozenset[UUID]]:+ return {+ subject_kind: allowed_ids(+ team_id, user_access_control, required_level=required_level, ids=subject_ids.get(subject_kind, ())+ )+ for subject_kind, allowed_ids in ALLOWED_SUBJECT_IDS.items()+ }diff --git a/products/warehouse_suggestions/backend/logic/flags.py b/products/warehouse_suggestions/backend/logic/flags.pynew file mode 100644index 000000000000..ea7f75a1be8d--- /dev/null+++ b/products/warehouse_suggestions/backend/logic/flags.py@@ -0,0 +1,25 @@+from typing import TYPE_CHECKING++from django.conf import settings++import posthoganalytics++if TYPE_CHECKING:+ from posthog.models.team import Team++WAREHOUSE_SUGGESTIONS_FEATURE_FLAG = "warehouse-suggestions"+++def is_warehouse_suggestions_enabled(team: "Team") -> bool:+ if settings.DEBUG or settings.E2E_TESTING:+ return True+ return (+ posthoganalytics.feature_enabled(+ WAREHOUSE_SUGGESTIONS_FEATURE_FLAG,+ str(team.organization_id),+ groups={"organization": str(team.organization_id)},+ group_properties={"organization": {"id": str(team.organization_id)}},+ send_feature_flag_events=False,+ )+ is True+ )diff --git a/products/warehouse_suggestions/backend/logic/suggestions.py b/products/warehouse_suggestions/backend/logic/suggestions.pynew file mode 100644index 000000000000..145059049f9f--- /dev/null+++ b/products/warehouse_suggestions/backend/logic/suggestions.py@@ -0,0 +1,135 @@+from collections.abc import Mapping, Sequence+from dataclasses import asdict+from datetime import datetime+from uuid import UUID++from django.db import transaction+from django.utils import timezone++from posthog.models.scoping.manager import resolve_effective_team_id++from ..facade.contracts import SuggestionAlreadyDecidedError, SuggestionDraft+from ..facade.enums import WarehouseSuggestionDismissalReason, WarehouseSuggestionStatus+from ..models import WarehouseSuggestion++Transitions = Mapping[WarehouseSuggestionStatus, frozenset[WarehouseSuggestionStatus]]++ALLOWED_TRANSITIONS: Transitions = {+ WarehouseSuggestionStatus.PROPOSED: frozenset(+ {+ WarehouseSuggestionStatus.ACCEPTED,+ WarehouseSuggestionStatus.DISMISSED,+ WarehouseSuggestionStatus.EXPIRED,+ WarehouseSuggestionStatus.AUTO_RESOLVED,+ }+ ),+ WarehouseSuggestionStatus.DISMISSED: frozenset({WarehouseSuggestionStatus.PROPOSED}),+ WarehouseSuggestionStatus.EXPIRED: frozenset({WarehouseSuggestionStatus.PROPOSED}),+}++HUMAN_TRANSITIONS: Transitions = {+ WarehouseSuggestionStatus.PROPOSED: frozenset(+ {WarehouseSuggestionStatus.ACCEPTED, WarehouseSuggestionStatus.DISMISSED}+ ),+ WarehouseSuggestionStatus.DISMISSED: frozenset({WarehouseSuggestionStatus.PROPOSED}),+}++HUMAN_DECISIONS = frozenset({WarehouseSuggestionStatus.ACCEPTED, WarehouseSuggestionStatus.DISMISSED})++DRAFT_FIELDS_UPDATED_ON_INGEST = (+ "payload",+ "payload_version",+ "rules_version",+ "evidence",+ "evidence_window_start",+ "evidence_window_end",+ "score",+ "score_inputs",+ "run_id",+)+++def transition_to(+ suggestion_id: UUID,+ team_id: int,+ new_status: WarehouseSuggestionStatus,+ *,+ user_id: int | None,+ reason: WarehouseSuggestionDismissalReason | None = None,+ note: str | None = None,+ transitions: Transitions = ALLOWED_TRANSITIONS,+) -> WarehouseSuggestion:+ with transaction.atomic():+ suggestion = WarehouseSuggestion.objects.for_team(team_id).select_for_update().get(id=suggestion_id)+ current = WarehouseSuggestionStatus(suggestion.status)+ if new_status not in transitions.get(current, frozenset()):+ raise SuggestionAlreadyDecidedError(current, new_status)+ suggestion.status = new_status+ if new_status == WarehouseSuggestionStatus.PROPOSED:+ _clear_review(suggestion)+ if new_status in HUMAN_DECISIONS:+ _record_review(suggestion, user_id)+ if new_status == WarehouseSuggestionStatus.DISMISSED:+ _record_dismissal(suggestion, reason, note)+ suggestion.save()+ return suggestion+++def _clear_review(suggestion: WarehouseSuggestion) -> None:+ suggestion.reviewed_by = None+ suggestion.reviewed_at = None+ suggestion.dismissal_reason = None+ suggestion.dismissal_note = None+ suggestion.dismissed_at_score = None+++def _record_review(suggestion: WarehouseSuggestion, user_id: int | None) -> None:+ suggestion.reviewed_by_id = user_id+ suggestion.reviewed_at = timezone.now()+++def _record_dismissal(+ suggestion: WarehouseSuggestion, reason: WarehouseSuggestionDismissalReason | None, note: str | None+) -> None:+ suggestion.dismissal_reason = reason+ suggestion.dismissal_note = note+ suggestion.dismissed_at_score = suggestion.score+++def upsert_suggestions(team_id: int, drafts: Sequence[SuggestionDraft]) -> None:+ team_id = resolve_effective_team_id(team_id)+ suggestions = WarehouseSuggestion.objects.for_team(team_id, canonical=True)+ seen_at = timezone.now()+ drafts_by_fingerprint = {draft.fingerprint: draft for draft in drafts}+ with transaction.atomic():+ suggestions.bulk_create(+ [_new_suggestion(team_id, draft, seen_at) for draft in drafts_by_fingerprint.values()],+ ignore_conflicts=True,+ )+ candidates = suggestions.select_for_update().filter(+ fingerprint__in=drafts_by_fingerprint,+ status=WarehouseSuggestionStatus.PROPOSED,+ last_seen_at__lt=seen_at,+ )+ refreshed = [+ _refresh(row, drafts_by_fingerprint[row.fingerprint], seen_at)+ for row in candidates+ if _is_refreshed_by(row, drafts_by_fingerprint[row.fingerprint])+ ]+ suggestions.bulk_update(refreshed, [*DRAFT_FIELDS_UPDATED_ON_INGEST, "last_seen_at"])+++def _is_refreshed_by(row: WarehouseSuggestion, draft: SuggestionDraft) -> bool:+ same_subject = (row.kind, row.subject_kind, row.subject_id) == (draft.kind, draft.subject_kind, draft.subject_id)+ return same_subject and draft.evidence_window_end >= row.evidence_window_end+++def _refresh(row: WarehouseSuggestion, draft: SuggestionDraft, seen_at: datetime) -> WarehouseSuggestion:+ for field in DRAFT_FIELDS_UPDATED_ON_INGEST:+ setattr(row, field, getattr(draft, field))+ row.last_seen_at = seen_at+ return row+++def _new_suggestion(team_id: int, draft: SuggestionDraft, seen_at: datetime) -> WarehouseSuggestion:+ return WarehouseSuggestion(team_id=team_id, last_seen_at=seen_at, **asdict(draft))diff --git a/products/warehouse_suggestions/backend/migrations/0001_initial.py b/products/warehouse_suggestions/backend/migrations/0001_initial.pynew file mode 100644index 000000000000..f3eff0e6ec8c--- /dev/null+++ b/products/warehouse_suggestions/backend/migrations/0001_initial.py@@ -0,0 +1,144 @@+# Generated by Django 5.2.17 on 2026-10-06 15:54++import django.db.models.deletion+from django.conf import settings+from django.db import migrations, models++import posthog.uuidt+++class Migration(migrations.Migration):+ initial = True++ dependencies = [+ ("posthog", "1392_organization_member_notice"),+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),+ ]++ operations = [+ migrations.CreateModel(+ name="WarehouseSuggestion",+ fields=[+ (+ "id",+ models.UUIDField(+ default=posthog.uuidt.uuid7,+ editable=False,+ primary_key=True,+ serialize=False,+ ),+ ),+ (+ "kind",+ models.CharField(+ choices=[+ ("certify", "Certify"),+ ("deprecate", "Deprecate"),+ ("materialize", "Materialize"),+ ],+ max_length=32,+ ),+ ),+ ("fingerprint", models.CharField(max_length=64)),+ (+ "subject_kind",+ models.CharField(+ choices=[("saved_query", "Saved query"), ("table", "Table")],+ max_length=16,+ ),+ ),+ ("subject_id", models.UUIDField()),+ ("payload", models.JSONField(default=dict)),+ ("payload_version", models.PositiveSmallIntegerField(default=1)),+ ("rules_version", models.CharField(max_length=32)),+ ("evidence", models.JSONField(default=dict)),+ ("evidence_window_start", models.DateTimeField()),+ ("evidence_window_end", models.DateTimeField()),+ ("last_seen_at", models.DateTimeField()),+ ("reproposed_count", models.PositiveIntegerField(default=0)),+ ("score", models.FloatField()),+ ("score_inputs", models.JSONField(default=dict)),+ (+ "status",+ models.CharField(+ choices=[+ ("proposed", "Proposed"),+ ("accepted", "Accepted"),+ ("dismissed", "Dismissed"),+ ("expired", "Expired"),+ ("auto_resolved", "Auto-resolved"),+ ],+ default="proposed",+ max_length=16,+ ),+ ),+ ("surfaced_at", models.DateTimeField(blank=True, null=True)),+ ("reviewed_at", models.DateTimeField(blank=True, null=True)),+ (+ "dismissal_reason",+ models.CharField(+ blank=True,+ choices=[+ ("not_useful", "Not useful"),+ ("not_now", "Not now"),+ ("other", "Other"),+ ],+ max_length=16,+ null=True,+ ),+ ),+ ("dismissal_note", models.TextField(blank=True, null=True)),+ ("dismissed_at_score", models.FloatField(blank=True, null=True)),+ ("created_asset", models.JSONField(blank=True, null=True)),+ (+ "asset_outcome",+ models.CharField(+ blank=True,+ choices=[+ ("live", "Live"),+ ("deleted", "Deleted"),+ ("unused", "Unused"),+ ],+ max_length=16,+ null=True,+ ),+ ),+ ("run_id", models.CharField(blank=True, max_length=255)),+ (+ "reviewed_by",+ models.ForeignKey(+ blank=True,+ db_constraint=False,+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ related_name="+",+ to=settings.AUTH_USER_MODEL,+ ),+ ),+ (+ "team",+ models.ForeignKey(+ db_constraint=False,+ on_delete=django.db.models.deletion.CASCADE,+ related_name="+",+ to="posthog.team",+ ),+ ),+ ],+ options={+ "indexes": [+ models.Index(+ fields=["team", "status", "kind"],+ name="warehouse_sugg_status_kind",+ ),+ models.Index(fields=["team", "last_seen_at"], name="warehouse_sugg_last_seen"),+ ],+ "constraints": [+ models.UniqueConstraint(+ fields=("team", "fingerprint"),+ name="warehouse_suggestion_unique_fingerprint",+ )+ ],+ },+ ),+ ]diff --git a/products/warehouse_suggestions/backend/migrations/__init__.py b/products/warehouse_suggestions/backend/migrations/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/warehouse_suggestions/backend/migrations/max_migration.txt b/products/warehouse_suggestions/backend/migrations/max_migration.txtnew file mode 100644index 000000000000..cbab66dde92a--- /dev/null+++ b/products/warehouse_suggestions/backend/migrations/max_migration.txt@@ -0,0 +1 @@+0001_initialdiff --git a/products/warehouse_suggestions/backend/models.py b/products/warehouse_suggestions/backend/models.pynew file mode 100644index 000000000000..3297d82dbddd--- /dev/null+++ b/products/warehouse_suggestions/backend/models.py@@ -0,0 +1,58 @@+from django.db import models++from posthog.models.activity_logging.model_activity import ModelActivityMixin+from posthog.models.scoping.root_mixin import TeamScopedRootMixin+from posthog.models.utils import UUIDModel++from .facade.enums import (+ WarehouseSuggestionAssetOutcome,+ WarehouseSuggestionDismissalReason,+ WarehouseSuggestionKind,+ WarehouseSuggestionStatus,+ WarehouseSuggestionSubjectKind,+)+++class WarehouseSuggestion(ModelActivityMixin, TeamScopedRootMixin, UUIDModel):+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, db_constraint=False, related_name="+")+ kind = models.CharField(max_length=32, choices=WarehouseSuggestionKind.choices)+ fingerprint = models.CharField(max_length=64)+ subject_kind = models.CharField(max_length=16, choices=WarehouseSuggestionSubjectKind.choices)+ subject_id = models.UUIDField()+ payload = models.JSONField(default=dict)+ payload_version = models.PositiveSmallIntegerField(default=1)+ rules_version = models.CharField(max_length=32)+ evidence = models.JSONField(default=dict)+ evidence_window_start = models.DateTimeField()+ evidence_window_end = models.DateTimeField()+ last_seen_at = models.DateTimeField()+ reproposed_count = models.PositiveIntegerField(default=0)+ score = models.FloatField()+ score_inputs = models.JSONField(default=dict)+ status = models.CharField(+ max_length=16, choices=WarehouseSuggestionStatus.choices, default=WarehouseSuggestionStatus.PROPOSED.value+ )+ surfaced_at = models.DateTimeField(null=True, blank=True)+ reviewed_by = models.ForeignKey(+ "posthog.User", on_delete=models.SET_NULL, null=True, blank=True, db_constraint=False, related_name="+"+ )+ reviewed_at = models.DateTimeField(null=True, blank=True)+ dismissal_reason = models.CharField(+ max_length=16, choices=WarehouseSuggestionDismissalReason.choices, null=True, blank=True+ )+ dismissal_note = models.TextField(null=True, blank=True)+ dismissed_at_score = models.FloatField(null=True, blank=True)+ created_asset = models.JSONField(null=True, blank=True)+ asset_outcome = models.CharField(+ max_length=16, choices=WarehouseSuggestionAssetOutcome.choices, null=True, blank=True+ )+ run_id = models.CharField(max_length=255, blank=True)++ class Meta:+ constraints = [+ models.UniqueConstraint(fields=["team", "fingerprint"], name="warehouse_suggestion_unique_fingerprint"),+ ]+ indexes = [+ models.Index(fields=["team", "status", "kind"], name="warehouse_sugg_status_kind"),+ models.Index(fields=["team", "last_seen_at"], name="warehouse_sugg_last_seen"),+ ]diff --git a/products/warehouse_suggestions/backend/presentation/__init__.py b/products/warehouse_suggestions/backend/presentation/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/warehouse_suggestions/backend/presentation/serializers.py b/products/warehouse_suggestions/backend/presentation/serializers.pynew file mode 100644index 000000000000..7e20731d6fa3--- /dev/null+++ b/products/warehouse_suggestions/backend/presentation/serializers.py@@ -0,0 +1,101 @@+"""DRF serializers for warehouse_suggestions."""++from drf_spectacular.types import OpenApiTypes+from drf_spectacular.utils import extend_schema_field, extend_schema_serializer+from rest_framework import serializers+from rest_framework_dataclasses.serializers import DataclassSerializer++from ..facade.contracts import Suggestion, SuggestionReviewer+from ..facade.enums import (+ WarehouseSuggestionAssetOutcome,+ WarehouseSuggestionDismissalReason,+ WarehouseSuggestionKind,+ WarehouseSuggestionStatus,+ WarehouseSuggestionSubjectKind,+)+++@extend_schema_field(OpenApiTypes.OBJECT)+class JsonObjectField(serializers.JSONField):+ pass+++@extend_schema_serializer(component_name="WarehouseSuggestionReviewer")+class WarehouseSuggestionReviewerSerializer(DataclassSerializer):+ class Meta:+ dataclass = SuggestionReviewer+ extra_kwargs = {+ "id": {"help_text": "User id."},+ "first_name": {"help_text": "User first name."},+ "email": {"help_text": "User email."},+ }+++@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.")+ 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."+ )+ reviewed_by = WarehouseSuggestionReviewerSerializer(+ allow_null=True, help_text="Who accepted or dismissed this suggestion. Null while it is open."+ )+ kind = serializers.ChoiceField(+ choices=WarehouseSuggestionKind.choices,+ help_text="What the suggestion proposes: certify, deprecate or materialize the subject.",+ )+ subject_kind = serializers.ChoiceField(+ choices=WarehouseSuggestionSubjectKind.choices,+ help_text="Whether the subject is a saved query (view) or a warehouse table.",+ )+ status = serializers.ChoiceField(+ choices=WarehouseSuggestionStatus.choices,+ help_text="proposed until someone accepts or dismisses it, or the job expires it.",+ )+ dismissal_reason = serializers.ChoiceField(+ choices=WarehouseSuggestionDismissalReason.choices,+ allow_null=True,+ help_text="Why the suggestion was dismissed.",+ )+ asset_outcome = serializers.ChoiceField(+ choices=WarehouseSuggestionAssetOutcome.choices,+ allow_null=True,+ help_text="What happened to the asset an accepted suggestion created.",+ )++ class Meta:+ dataclass = Suggestion+ extra_kwargs = {+ "id": {"help_text": "Suggestion identifier."},+ "subject_id": {"help_text": "Id of the view or table the suggestion is about."},+ "payload_version": {"help_text": "Version of the payload shape for this kind."},+ "evidence_window_start": {"help_text": "Start of the usage window the evidence covers."},+ "evidence_window_end": {"help_text": "End of the usage window the evidence covers."},+ "last_seen_at": {"help_text": "When the daily job last found evidence for this suggestion."},+ "score": {"help_text": "How strongly the evidence supports the suggestion. Higher comes first."},+ "surfaced_at": {"help_text": "When the suggestion was first shown. Null while it waits for a slot."},+ "reviewed_at": {"help_text": "When the suggestion was accepted or dismissed."},+ "dismissal_note": {"help_text": "Free-text note left when dismissing."},+ "can_act": {+ "help_text": "Whether the caller has edit access to the subject and so may accept, dismiss or resume."+ },+ }+++class WarehouseSuggestionListQuerySerializer(serializers.Serializer):+ kind = serializers.ChoiceField(+ choices=WarehouseSuggestionKind.choices, required=False, help_text="Only return suggestions of this kind."+ )+ status = serializers.ChoiceField(+ choices=WarehouseSuggestionStatus.choices, required=False, help_text="Only return suggestions in this status."+ )+++class DismissWarehouseSuggestionSerializer(serializers.Serializer):+ reason = serializers.ChoiceField(+ choices=WarehouseSuggestionDismissalReason.choices, help_text="Why the suggestion is dismissed."+ )+ note = serializers.CharField(+ required=False, allow_blank=True, max_length=1000, help_text="Optional note about the dismissal."+ )diff --git a/products/warehouse_suggestions/backend/presentation/views.py b/products/warehouse_suggestions/backend/presentation/views.pynew file mode 100644index 000000000000..17486be27e2e--- /dev/null+++ b/products/warehouse_suggestions/backend/presentation/views.py@@ -0,0 +1,138 @@+"""DRF views for warehouse_suggestions."""++from collections.abc import Callable+from typing import Any, cast+from uuid import UUID++from drf_spectacular.utils import OpenApiResponse, extend_schema+from rest_framework import viewsets+from rest_framework.exceptions import NotFound, PermissionDenied+from rest_framework.pagination import LimitOffsetPagination+from rest_framework.permissions import BasePermission, IsAuthenticated+from rest_framework.request import Request+from rest_framework.response import Response+from rest_framework.views import APIView++from posthog.api.mixins import ValidatedRequest, validated_request+from posthog.api.routing import TeamAndOrgViewSetMixin+from posthog.api.utils import action+from posthog.exceptions import Conflict+from posthog.models import User+from posthog.permissions import APIScopePermission, TeamMemberAccessPermission+from posthog.utils import UUID_REGEX++from ..facade import api+from ..facade.api import is_warehouse_suggestions_enabled+from ..facade.contracts import (+ SubjectEditAccessRequiredError,+ Suggestion,+ SuggestionAlreadyDecidedError,+ SuggestionNotFoundError,+ SuggestionPage,+)+from ..facade.enums import WarehouseSuggestionKind, WarehouseSuggestionStatus, WarehouseSuggestionSubjectKind+from .serializers import (+ DismissWarehouseSuggestionSerializer,+ WarehouseSuggestionListQuerySerializer,+ WarehouseSuggestionSerializer,+)++DEFAULT_PAGE_SIZE = 100+EDIT_ACCESS_REQUIRED = {+ WarehouseSuggestionSubjectKind.SAVED_QUERY: "You need edit access to this view to change its suggestion.",+ WarehouseSuggestionSubjectKind.TABLE: "You need edit access to this table to change its suggestion.",+}+++class SuggestionPagination(LimitOffsetPagination):+ default_limit = DEFAULT_PAGE_SIZE+ max_limit = DEFAULT_PAGE_SIZE++ def paginate(self, request: Request, fetch_page: Callable[[int, int], SuggestionPage]) -> Response:+ self.request = request+ self.limit = self.get_limit(request) or DEFAULT_PAGE_SIZE+ self.offset = self.get_offset(request)+ page = fetch_page(self.limit, self.offset)+ self.count = page.count+ return self.get_paginated_response(WarehouseSuggestionSerializer(page.results, many=True).data)+++class ProjectAccessPermission(BasePermission):+ def has_permission(self, request: Request, view: APIView) -> bool:+ viewset = cast("WarehouseSuggestionViewSet", view)+ return viewset.user_access_control.check_access_level_for_object(viewset.team, required_level="member")+++class WarehouseSuggestionViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):+ scope_object = "warehouse_objects"+ scope_object_read_actions = ["list", "retrieve"]+ scope_object_write_actions = ["dismiss", "resume"]+ pagination_class = SuggestionPagination+ lookup_value_regex = UUID_REGEX++ def dangerously_get_permissions(self) -> list[BasePermission]:+ return [IsAuthenticated(), APIScopePermission(), TeamMemberAccessPermission(), ProjectAccessPermission()]++ def initial(self, request: Request, *args: Any, **kwargs: Any) -> None:+ super().initial(request, *args, **kwargs)+ if not is_warehouse_suggestions_enabled(self.team):+ raise PermissionDenied("Warehouse suggestions are not enabled for this project.")++ @validated_request(+ query_serializer=WarehouseSuggestionListQuerySerializer,+ responses={200: OpenApiResponse(response=WarehouseSuggestionSerializer(many=True))},+ )+ def list(self, request: ValidatedRequest, **kwargs: Any) -> Response:+ kind = request.validated_query_data.get("kind")+ status = request.validated_query_data.get("status")+ return cast(SuggestionPagination, self.paginator).paginate(+ request,+ lambda limit, offset: api.list_suggestions(+ self.team_id,+ self.user_access_control,+ kind=WarehouseSuggestionKind(kind) if kind else None,+ status=WarehouseSuggestionStatus(status) if status else None,+ limit=limit,+ offset=offset,+ ),+ )++ @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)))++ @validated_request(+ request_serializer=DismissWarehouseSuggestionSerializer,+ responses={200: OpenApiResponse(response=WarehouseSuggestionSerializer)},+ )+ @action(detail=True, methods=["post"])+ def dismiss(self, request: ValidatedRequest, pk: str, **kwargs: Any) -> Response:+ return self._respond(+ lambda: api.dismiss_suggestion(+ self.team_id,+ self.user_access_control,+ UUID(pk),+ user_id=cast(User, request.user).id,+ reason=request.validated_data["reason"],+ note=request.validated_data.get("note") or None,+ )+ )++ @extend_schema(request=None, responses={200: WarehouseSuggestionSerializer})+ @action(detail=True, methods=["post"])+ def resume(self, request: Request, pk: str, **kwargs: Any) -> Response:+ return self._respond(+ lambda: api.resume_suggestion(+ self.team_id, self.user_access_control, UUID(pk), user_id=cast(User, request.user).id+ )+ )++ def _respond(self, decide_or_read: Callable[[], Suggestion]) -> Response:+ try:+ return Response(WarehouseSuggestionSerializer(decide_or_read()).data)+ except SuggestionNotFoundError:+ raise NotFound()+ except SubjectEditAccessRequiredError as error:+ raise PermissionDenied(EDIT_ACCESS_REQUIRED[error.subject_kind])+ except SuggestionAlreadyDecidedError as error:+ raise Conflict(str(error))diff --git a/products/warehouse_suggestions/backend/routes.py b/products/warehouse_suggestions/backend/routes.pynew file mode 100644index 000000000000..df64f1e1c3cf--- /dev/null+++ b/products/warehouse_suggestions/backend/routes.py@@ -0,0 +1,9 @@+from posthog.api.routing import RouterRegistry++from products.warehouse_suggestions.backend.presentation.views import WarehouseSuggestionViewSet+++def register_routes(routers: RouterRegistry) -> None:+ routers.projects.register(+ r"warehouse_suggestions", WarehouseSuggestionViewSet, "project_warehouse_suggestions", ["team_id"]+ )diff --git a/products/warehouse_suggestions/backend/tests/__init__.py b/products/warehouse_suggestions/backend/tests/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/warehouse_suggestions/backend/tests/test_api.py b/products/warehouse_suggestions/backend/tests/test_api.pynew file mode 100644index 000000000000..f7eef0d70e7b--- /dev/null+++ b/products/warehouse_suggestions/backend/tests/test_api.py@@ -0,0 +1,248 @@+import json+from uuid import UUID++from posthog.test.base import APIBaseTest+from unittest.mock import patch++from django.db import connection+from django.test.utils import CaptureQueriesContext++from parameterized import parameterized+from rest_framework import status++from posthog.constants import AvailableFeature+from posthog.models.activity_logging.activity_log import ActivityLog++from products.access_control.backend.models.access_control import AccessControl+from products.data_modeling.backend.facade.models import DataWarehouseSavedQuery+from products.warehouse_sources.backend.facade.models import DataWarehouseTable+from products.warehouse_suggestions.backend.facade.enums import (+ WarehouseSuggestionDismissalReason,+ WarehouseSuggestionKind,+ WarehouseSuggestionStatus,+ WarehouseSuggestionSubjectKind,+)+from products.warehouse_suggestions.backend.models import WarehouseSuggestion++from .test_suggestions import ingest_one, make_draft++REVIEW_FIELDS = ("reviewed_by_id", "reviewed_at", "dismissal_reason", "dismissal_note", "dismissed_at_score")+FLAG = "products.warehouse_suggestions.backend.presentation.views.is_warehouse_suggestions_enabled"+++class TestWarehouseSuggestionAPI(APIBaseTest):+ def setUp(self) -> None:+ super().setUp()+ self.enterContext(patch(FLAG, return_value=True))+ self.url = f"/api/projects/{self.team.id}/warehouse_suggestions"+ self.view = self._make_view("orders")+ self.table = DataWarehouseTable.objects.create(+ team=self.team,+ name="stripe_charges",+ format=DataWarehouseTable.TableFormat.Parquet,+ url_pattern="s3://bucket/stripe_charges",+ )++ def _make_view(self, name: str) -> DataWarehouseSavedQuery:+ return DataWarehouseSavedQuery.objects.create(+ team=self.team, name=name, query={"kind": "HogQLQuery", "query": "SELECT 1 AS id"}+ )++ def _materialize(self, view: DataWarehouseSavedQuery) -> DataWarehouseTable:+ backing_table = DataWarehouseTable.objects.create(+ team=self.team,+ name=view.name,+ format=DataWarehouseTable.TableFormat.Parquet,+ url_pattern=f"s3://bucket/{view.folder_path}/{view.normalized_name}",+ )+ DataWarehouseSavedQuery.objects.filter(id=view.id).update(table=backing_table, is_materialized=True)+ return backing_table++ def _suggest(+ self,+ subject_id: UUID,+ *,+ subject_kind: WarehouseSuggestionSubjectKind = WarehouseSuggestionSubjectKind.SAVED_QUERY,+ score: float = 1.0,+ ) -> WarehouseSuggestion:+ return ingest_one(+ self.team.id,+ make_draft(+ fingerprint=f"certify:{subject_id}", subject_kind=subject_kind, subject_id=subject_id, score=score+ ),+ )++ 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}+ ]+ self.organization.save(update_fields=["available_product_features"])+ AccessControl.objects.create(+ team=self.team,+ resource=resource,+ resource_id=str(resource_id) if resource_id else None,+ organization_member=self.organization_membership,+ access_level=access_level,+ )++ 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)++ listed = self.client.get(f"{self.url}/")+ assert listed.status_code == status.HTTP_200_OK, listed.json()+ assert [row["id"] for row in listed.json()["results"]] == [str(high.id), str(low.id)]+ assert all(row["can_act"] for row in listed.json()["results"])++ dismissed = self.client.post(+ f"{self.url}/{low.id}/dismiss/",+ {"reason": WarehouseSuggestionDismissalReason.OTHER, "note": "We sunset this view"},+ )+ assert dismissed.status_code == status.HTTP_200_OK, dismissed.json()+ low.refresh_from_db()+ assert low.status == WarehouseSuggestionStatus.DISMISSED+ assert low.reviewed_by_id == self.user.id+ assert low.reviewed_at is not None+ assert low.dismissal_reason == WarehouseSuggestionDismissalReason.OTHER+ assert low.dismissal_note == "We sunset this view"+ assert low.dismissed_at_score == 2.0++ resumed = self.client.post(f"{self.url}/{low.id}/resume/")+ assert resumed.status_code == status.HTTP_200_OK, resumed.json()+ low.refresh_from_db()+ assert low.status == WarehouseSuggestionStatus.PROPOSED+ assert {field: getattr(low, field) for field in REVIEW_FIELDS} == dict.fromkeys(REVIEW_FIELDS)+ logged = ActivityLog.objects.filter(team_id=self.team.id, scope="WarehouseSuggestion", item_id=str(low.id))+ assert logged.count() == 2+ assert "We sunset this view" not in json.dumps([entry.detail for entry in logged], default=str)++ @parameterized.expand(+ [+ ("dismiss_a_dismissed_one", WarehouseSuggestionStatus.DISMISSED, "dismiss"),+ ("resume_an_expired_one", WarehouseSuggestionStatus.EXPIRED, "resume"),+ ]+ )+ def test_a_move_people_may_not_make_conflicts(+ self, _name: str, current: WarehouseSuggestionStatus, action: str+ ) -> None:+ suggestion = self._suggest(self.view.id)+ WarehouseSuggestion.objects.for_team(self.team.id).filter(id=suggestion.id).update(status=current)++ response = self.client.post(+ f"{self.url}/{suggestion.id}/{action}/", {"reason": WarehouseSuggestionDismissalReason.NOT_NOW}+ )++ assert response.status_code == status.HTTP_409_CONFLICT, response.json()++ @parameterized.expand(+ [+ ("by_kind", "kind=deprecate", status.HTTP_200_OK, ["table"]),+ ("by_status", "status=dismissed", status.HTTP_200_OK, ["table"]),+ ("by_kind_and_status", "kind=certify&status=dismissed", status.HTTP_200_OK, []),+ ("unknown_status", "status=bogus", status.HTTP_400_BAD_REQUEST, None),+ ]+ )+ def test_list_filters(self, _name: str, query: str, expected_status: int, expected: list[str] | None) -> None:+ ids = {+ "view": self._suggest(self.view.id).id,+ "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+ )++ response = self.client.get(f"{self.url}/?{query}")++ assert response.status_code == expected_status, response.json()+ if expected is not None:+ assert response.json()["count"] == len(expected)+ assert [row["id"] for row in response.json()["results"]] == [str(ids[name]) for name in expected]++ def test_the_flag_off_forbids_the_endpoint(self) -> None:+ with patch(FLAG, return_value=False):+ response = self.client.get(f"{self.url}/")++ assert response.status_code == status.HTTP_403_FORBIDDEN++ 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)+ deleted_view = self._make_view("old_orders")+ about_deleted = self._suggest(deleted_view.id)+ DataWarehouseSavedQuery.objects.filter(id=deleted_view.id).update(deleted=True)+ about_backing_table = self._suggest(+ self._materialize(self.view).id, subject_kind=WarehouseSuggestionSubjectKind.TABLE+ )+ self._restrict("warehouse_view", self.view.id, "none")++ listed = self.client.get(f"{self.url}/")++ assert listed.json()["count"] == 1+ assert [row["id"] for row in listed.json()["results"]] == [str(visible.id)]+ for hidden in (denied_view, about_deleted, about_backing_table):+ assert self.client.get(f"{self.url}/{hidden.id}/").status_code == status.HTTP_404_NOT_FOUND+ for action in ("dismiss", "resume"):+ response = self.client.post(+ f"{self.url}/{hidden.id}/{action}/", {"reason": WarehouseSuggestionDismissalReason.NOT_NOW}+ )+ assert response.status_code == status.HTTP_404_NOT_FOUND++ @parameterized.expand(+ [+ ("warehouse_viewer_with_edit_on_the_view", "viewer", "editor", status.HTTP_200_OK),+ ("no_warehouse_access_with_view_on_the_view", "none", "viewer", status.HTTP_403_FORBIDDEN),+ ]+ )+ def test_a_grant_on_one_view_is_enough(+ self, _name: str, warehouse_level: str, view_level: str, expected_dismiss_status: int+ ) -> None:+ suggestion = self._suggest(self.view.id)+ self._restrict("warehouse_objects", None, warehouse_level)+ self._restrict("warehouse_view", self.view.id, view_level)++ listed = self.client.get(f"{self.url}/")+ dismissed = self.client.post(+ f"{self.url}/{suggestion.id}/dismiss/", {"reason": WarehouseSuggestionDismissalReason.NOT_NOW}+ )++ assert [row["id"] for row in listed.json()["results"]] == [str(suggestion.id)]+ assert dismissed.status_code == expected_dismiss_status, dismissed.json()++ def test_a_viewer_of_the_subject_cannot_dismiss_its_suggestion(self) -> None:+ suggestion = self._suggest(self.view.id)+ self._restrict("warehouse_view", self.view.id, "viewer")++ listed = self.client.get(f"{self.url}/")+ dismissed = self.client.post(+ f"{self.url}/{suggestion.id}/dismiss/", {"reason": WarehouseSuggestionDismissalReason.NOT_USEFUL}+ )++ assert listed.json()["results"][0]["can_act"] is False+ assert dismissed.status_code == status.HTTP_403_FORBIDDEN, dismissed.json()+ suggestion.refresh_from_db()+ assert suggestion.status == WarehouseSuggestionStatus.PROPOSED++ def test_pages_do_not_overlap_or_skip_rows_at_the_boundary(self) -> None:+ suggestions = [self._suggest(self._make_view(f"view_{index}").id, score=1.0) for index in range(5)]++ pages = [self.client.get(f"{self.url}/?limit=2&offset={offset}").json() for offset in (0, 2, 4)]++ assert [page["count"] for page in pages] == [5, 5, 5]+ assert [len(page["results"]) for page in pages] == [2, 2, 1]+ listed = [row["id"] for page in pages for row in page["results"]]+ assert listed == [str(row.id) for row in sorted(suggestions, key=lambda row: row.id)]++ def test_listing_runs_a_constant_number_of_queries(self) -> None:+ def count_list_queries() -> int:+ WarehouseSuggestion.objects.for_team(self.team.id).update(reviewed_by=self.user)+ with CaptureQueriesContext(connection) as queries:+ assert self.client.get(f"{self.url}/").status_code == status.HTTP_200_OK+ return len(queries)++ self._suggest(self.view.id)+ count_list_queries()+ one_row = count_list_queries()+ for index in range(4):+ self._suggest(self._make_view(f"view_{index}").id)++ assert count_list_queries() == one_rowdiff --git a/products/warehouse_suggestions/backend/tests/test_suggestions.py b/products/warehouse_suggestions/backend/tests/test_suggestions.pynew file mode 100644index 000000000000..7349ad47bec3--- /dev/null+++ b/products/warehouse_suggestions/backend/tests/test_suggestions.py@@ -0,0 +1,138 @@+from datetime import UTC, datetime, timedelta+from typing import Any+from uuid import UUID, uuid4++from posthog.test.base import BaseTest++from parameterized import parameterized++from posthog.models.activity_logging.activity_log import ActivityLog++from products.warehouse_suggestions.backend.facade.contracts import SuggestionAlreadyDecidedError, SuggestionDraft+from products.warehouse_suggestions.backend.facade.enums import (+ WarehouseSuggestionKind,+ WarehouseSuggestionStatus,+ WarehouseSuggestionSubjectKind,+)+from products.warehouse_suggestions.backend.logic.suggestions import transition_to, upsert_suggestions+from products.warehouse_suggestions.backend.models import WarehouseSuggestion++WINDOW_START = datetime(2026, 9, 1, tzinfo=UTC)+WINDOW_END = datetime(2026, 9, 30, tzinfo=UTC)+SUBJECT_ID = UUID("01a11171-0000-7000-8000-000000000001")+++def make_draft(+ *,+ fingerprint: str = "certify:orders",+ subject_kind: WarehouseSuggestionSubjectKind = WarehouseSuggestionSubjectKind.SAVED_QUERY,+ subject_id: UUID = SUBJECT_ID,+ score: float = 1.0,+ evidence_window_end: datetime = WINDOW_END,+) -> SuggestionDraft:+ return SuggestionDraft(+ kind=WarehouseSuggestionKind.CERTIFY,+ fingerprint=fingerprint,+ subject_kind=subject_kind,+ subject_id=subject_id,+ payload={"name": "orders"},+ payload_version=1,+ rules_version="abc123",+ evidence={"distinct_readers": 4},+ evidence_window_start=WINDOW_START,+ evidence_window_end=evidence_window_end,+ score=score,+ score_inputs={"readers": 4},+ run_id="run-1",+ )+++def ingest_one(team_id: int, draft: SuggestionDraft) -> WarehouseSuggestion:+ upsert_suggestions(team_id, [draft])+ return WarehouseSuggestion.objects.for_team(team_id).get(fingerprint=draft.fingerprint)+++class TestTransitions(BaseTest):+ @parameterized.expand(+ [+ ("proposed_to_accepted", WarehouseSuggestionStatus.PROPOSED, WarehouseSuggestionStatus.ACCEPTED, True),+ ("proposed_to_dismissed", WarehouseSuggestionStatus.PROPOSED, WarehouseSuggestionStatus.DISMISSED, True),+ ("proposed_to_expired", WarehouseSuggestionStatus.PROPOSED, WarehouseSuggestionStatus.EXPIRED, True),+ (+ "proposed_to_auto_resolved",+ WarehouseSuggestionStatus.PROPOSED,+ WarehouseSuggestionStatus.AUTO_RESOLVED,+ True,+ ),+ ("dismissed_to_proposed", WarehouseSuggestionStatus.DISMISSED, WarehouseSuggestionStatus.PROPOSED, True),+ ("expired_to_proposed", WarehouseSuggestionStatus.EXPIRED, WarehouseSuggestionStatus.PROPOSED, True),+ ("proposed_to_proposed", WarehouseSuggestionStatus.PROPOSED, WarehouseSuggestionStatus.PROPOSED, False),+ ("dismissed_to_accepted", WarehouseSuggestionStatus.DISMISSED, WarehouseSuggestionStatus.ACCEPTED, False),+ ("accepted_to_dismissed", WarehouseSuggestionStatus.ACCEPTED, WarehouseSuggestionStatus.DISMISSED, False),+ ("accepted_to_proposed", WarehouseSuggestionStatus.ACCEPTED, WarehouseSuggestionStatus.PROPOSED, False),+ (+ "auto_resolved_to_proposed",+ WarehouseSuggestionStatus.AUTO_RESOLVED,+ WarehouseSuggestionStatus.PROPOSED,+ False,+ ),+ ("expired_to_dismissed", WarehouseSuggestionStatus.EXPIRED, WarehouseSuggestionStatus.DISMISSED, False),+ ]+ )+ def test_status_moves(+ self, _name: str, start: WarehouseSuggestionStatus, target: WarehouseSuggestionStatus, allowed: bool+ ) -> None:+ suggestion = ingest_one(self.team.id, make_draft())+ WarehouseSuggestion.objects.for_team(self.team.id).filter(id=suggestion.id).update(status=start)++ if not allowed:+ with self.assertRaises(SuggestionAlreadyDecidedError):+ transition_to(suggestion.id, self.team.id, target, user_id=self.user.id)+ suggestion.refresh_from_db()+ assert suggestion.status == start+ return++ transition_to(suggestion.id, self.team.id, target, user_id=self.user.id)+ suggestion.refresh_from_db()+ assert suggestion.status == target+++class TestIngest(BaseTest):+ def test_ingest_inserts_new_drafts_and_refreshes_proposed_ones(self) -> None:+ first = ingest_one(self.team.id, make_draft(score=1.0))++ assert first.status == WarehouseSuggestionStatus.PROPOSED+ assert first.team_id == self.team.id++ refreshed = ingest_one(self.team.id, make_draft(score=7.5))++ assert refreshed.id == first.id+ assert refreshed.score == 7.5+ assert refreshed.last_seen_at > first.last_seen_at++ @parameterized.expand(+ [+ ("dismissed", {"status": WarehouseSuggestionStatus.DISMISSED}, {}),+ ("accepted", {"status": WarehouseSuggestionStatus.ACCEPTED}, {}),+ ("draft_with_older_evidence", {}, {"evidence_window_end": WINDOW_END - timedelta(days=1)}),+ ("draft_about_another_subject", {}, {"subject_id": uuid4()}),+ ]+ )+ def test_ingest_leaves_the_suggestion_untouched(+ self, _name: str, row_changes: dict[str, Any], draft_changes: dict[str, Any]+ ) -> None:+ suggestion = ingest_one(self.team.id, make_draft(score=1.0))+ WarehouseSuggestion.objects.for_team(self.team.id).filter(id=suggestion.id).update(**row_changes)++ after = ingest_one(self.team.id, make_draft(score=9.0, **draft_changes))++ assert (after.subject_id, after.score, after.last_seen_at) == (SUBJECT_ID, 1.0, suggestion.last_seen_at)++ def test_ingest_keeps_one_row_per_fingerprint_and_logs_no_activity(self) -> None:+ draft = make_draft()++ upsert_suggestions(self.team.id, [draft, draft])+ upsert_suggestions(self.team.id, [draft])++ assert WarehouseSuggestion.objects.for_team(self.team.id).count() == 1+ assert not ActivityLog.objects.filter(team_id=self.team.id, scope="WarehouseSuggestion").exists()diff --git a/products/warehouse_suggestions/frontend/generated/api.schemas.ts b/products/warehouse_suggestions/frontend/generated/api.schemas.tsnew file mode 100644index 000000000000..0583b985e089--- /dev/null+++ b/products/warehouse_suggestions/frontend/generated/api.schemas.ts@@ -0,0 +1,255 @@+/**+ * Auto-generated from the Django backend OpenAPI schema.+ * To modify these types, update the Django serializers or views, then run:+ * hogli build:openapi+ * Questions or issues? #team-devex on Slack+ *+ * PostHog API - generated+ * OpenAPI spec version: 1.0.0+ */+export interface WarehouseSuggestionReviewerApi {+ /** User id. */+ id: number+ /** User first name. */+ first_name: string+ /** User email. */+ email: string+}++/**+ * * `certify` - Certify+ * * `deprecate` - Deprecate+ * * `materialize` - Materialize+ */+export type WarehouseSuggestionKindEnumApi =+ (typeof WarehouseSuggestionKindEnumApi)[keyof typeof WarehouseSuggestionKindEnumApi]++export const WarehouseSuggestionKindEnumApi = {+ Certify: 'certify',+ Deprecate: 'deprecate',+ Materialize: 'materialize',+} as const++/**+ * * `saved_query` - Saved query+ * * `table` - Table+ */+export type WarehouseSuggestionSubjectKindEnumApi =+ (typeof WarehouseSuggestionSubjectKindEnumApi)[keyof typeof WarehouseSuggestionSubjectKindEnumApi]++export const WarehouseSuggestionSubjectKindEnumApi = {+ SavedQuery: 'saved_query',+ Table: 'table',+} as const++/**+ * * `proposed` - Proposed+ * * `accepted` - Accepted+ * * `dismissed` - Dismissed+ * * `expired` - Expired+ * * `auto_resolved` - Auto-resolved+ */+export type WarehouseSuggestionStatusEnumApi =+ (typeof WarehouseSuggestionStatusEnumApi)[keyof typeof WarehouseSuggestionStatusEnumApi]++export const WarehouseSuggestionStatusEnumApi = {+ Proposed: 'proposed',+ Accepted: 'accepted',+ Dismissed: 'dismissed',+ Expired: 'expired',+ AutoResolved: 'auto_resolved',+} as const++/**+ * * `not_useful` - Not useful+ * * `not_now` - Not now+ * * `other` - Other+ */+export type WarehouseSuggestionDismissalReasonEnumApi =+ (typeof WarehouseSuggestionDismissalReasonEnumApi)[keyof typeof WarehouseSuggestionDismissalReasonEnumApi]++export const WarehouseSuggestionDismissalReasonEnumApi = {+ NotUseful: 'not_useful',+ NotNow: 'not_now',+ Other: 'other',+} as const++/**+ * * `live` - Live+ * * `deleted` - Deleted+ * * `unused` - Unused+ */+export type WarehouseSuggestionAssetOutcomeEnumApi =+ (typeof WarehouseSuggestionAssetOutcomeEnumApi)[keyof typeof WarehouseSuggestionAssetOutcomeEnumApi]++export const WarehouseSuggestionAssetOutcomeEnumApi = {+ Live: 'live',+ Deleted: 'deleted',+ 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.+ */+export type WarehouseSuggestionApiEvidence = { [key: string]: unknown }++/**+ * What accepting this suggestion created. Null until accepted.+ * @nullable+ */+export type WarehouseSuggestionApiCreatedAsset = { [key: string]: unknown } | null++export interface WarehouseSuggestionApi {+ /** What accepting this suggestion would create or change. Shape depends on kind. */+ payload: WarehouseSuggestionApiPayload+ /** The usage numbers that led to this suggestion. */+ evidence: WarehouseSuggestionApiEvidence+ /**+ * What accepting this suggestion created. Null until accepted.+ * @nullable+ */+ created_asset: WarehouseSuggestionApiCreatedAsset+ /** Who accepted or dismissed this suggestion. Null while it is open. */+ reviewed_by: WarehouseSuggestionReviewerApi | null+ /** What the suggestion proposes: certify, deprecate or materialize the subject.+ *+ * * `certify` - Certify+ * * `deprecate` - Deprecate+ * * `materialize` - Materialize */+ kind: WarehouseSuggestionKindEnumApi+ /** Whether the subject is a saved query (view) or a warehouse table.+ *+ * * `saved_query` - Saved query+ * * `table` - Table */+ subject_kind: WarehouseSuggestionSubjectKindEnumApi+ /** proposed until someone accepts or dismisses it, or the job expires it.+ *+ * * `proposed` - Proposed+ * * `accepted` - Accepted+ * * `dismissed` - Dismissed+ * * `expired` - Expired+ * * `auto_resolved` - Auto-resolved */+ status: WarehouseSuggestionStatusEnumApi+ /** Why the suggestion was dismissed.+ *+ * * `not_useful` - Not useful+ * * `not_now` - Not now+ * * `other` - Other */+ dismissal_reason: WarehouseSuggestionDismissalReasonEnumApi | null+ /** What happened to the asset an accepted suggestion created.+ *+ * * `live` - Live+ * * `deleted` - Deleted+ * * `unused` - Unused */+ asset_outcome: WarehouseSuggestionAssetOutcomeEnumApi | null+ /** Suggestion identifier. */+ id: string+ /** Id of the view or table the suggestion is about. */+ subject_id: string+ /** Version of the payload shape for this kind. */+ payload_version: number+ /** Start of the usage window the evidence covers. */+ evidence_window_start: string+ /** End of the usage window the evidence covers. */+ evidence_window_end: string+ /** When the daily job last found evidence for this suggestion. */+ last_seen_at: string+ /** How strongly the evidence supports the suggestion. Higher comes first. */+ score: number+ /**+ * When the suggestion was first shown. Null while it waits for a slot.+ * @nullable+ */+ surfaced_at: string | null+ /**+ * When the suggestion was accepted or dismissed.+ * @nullable+ */+ reviewed_at: string | null+ /**+ * Free-text note left when dismissing.+ * @nullable+ */+ dismissal_note: string | null+ /** Whether the caller has edit access to the subject and so may accept, dismiss or resume. */+ can_act: boolean+}++export interface PaginatedWarehouseSuggestionListApi {+ count: number+ /** @nullable */+ next?: string | null+ /** @nullable */+ previous?: string | null+ results: WarehouseSuggestionApi[]+}++export interface DismissWarehouseSuggestionApi {+ /** Why the suggestion is dismissed.+ *+ * * `not_useful` - Not useful+ * * `not_now` - Not now+ * * `other` - Other */+ reason: WarehouseSuggestionDismissalReasonEnumApi+ /**+ * Optional note about the dismissal.+ * @maxLength 1000+ */+ note?: string+}++export type WarehouseSuggestionsListParams = {+ /**+ * Only return suggestions of this kind.+ *+ * * `certify` - Certify+ * * `deprecate` - Deprecate+ * * `materialize` - Materialize+ * @minLength 1+ */+ kind?: WarehouseSuggestionsListKind+ /**+ * Number of results to return per page.+ */+ limit?: number+ /**+ * The initial index from which to return the results.+ */+ offset?: number+ /**+ * Only return suggestions in this status.+ *+ * * `proposed` - Proposed+ * * `accepted` - Accepted+ * * `dismissed` - Dismissed+ * * `expired` - Expired+ * * `auto_resolved` - Auto-resolved+ * @minLength 1+ */+ status?: WarehouseSuggestionsListStatus+}++export type WarehouseSuggestionsListKind =+ (typeof WarehouseSuggestionsListKind)[keyof typeof WarehouseSuggestionsListKind]++export const WarehouseSuggestionsListKind = {+ Certify: 'certify',+ Deprecate: 'deprecate',+ Materialize: 'materialize',+} as const++export type WarehouseSuggestionsListStatus =+ (typeof WarehouseSuggestionsListStatus)[keyof typeof WarehouseSuggestionsListStatus]++export const WarehouseSuggestionsListStatus = {+ Proposed: 'proposed',+ Accepted: 'accepted',+ Dismissed: 'dismissed',+ Expired: 'expired',+ AutoResolved: 'auto_resolved',+} as constdiff --git a/products/warehouse_suggestions/frontend/generated/api.ts b/products/warehouse_suggestions/frontend/generated/api.tsnew file mode 100644index 000000000000..fe6ce2d36c3f--- /dev/null+++ b/products/warehouse_suggestions/frontend/generated/api.ts@@ -0,0 +1,91 @@+import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'+/**+ * Auto-generated from the Django backend OpenAPI schema.+ * To modify these types, update the Django serializers or views, then run:+ * hogli build:openapi+ * Questions or issues? #team-devex on Slack+ *+ * PostHog API - generated+ * OpenAPI spec version: 1.0.0+ */+import type {+ DismissWarehouseSuggestionApi,+ PaginatedWarehouseSuggestionListApi,+ WarehouseSuggestionApi,+ WarehouseSuggestionsListParams,+} from './api.schemas'++export const getWarehouseSuggestionsListUrl = (projectId: string, params?: WarehouseSuggestionsListParams) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : String(value))+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/warehouse_suggestions/?${stringifiedParams}`+ : `/api/projects/${projectId}/warehouse_suggestions/`+}++export const warehouseSuggestionsList = async (+ projectId: string,+ params?: WarehouseSuggestionsListParams,+ options?: RequestInit+): Promise<PaginatedWarehouseSuggestionListApi> => {+ return apiMutator<PaginatedWarehouseSuggestionListApi>(getWarehouseSuggestionsListUrl(projectId, params), {+ ...options,+ method: 'GET',+ })+}++export const getWarehouseSuggestionsRetrieveUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/warehouse_suggestions/${id}/`+}++export const warehouseSuggestionsRetrieve = async (+ projectId: string,+ id: string,+ options?: RequestInit+): Promise<WarehouseSuggestionApi> => {+ return apiMutator<WarehouseSuggestionApi>(getWarehouseSuggestionsRetrieveUrl(projectId, id), {+ ...options,+ method: 'GET',+ })+}++export const getWarehouseSuggestionsDismissCreateUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/warehouse_suggestions/${id}/dismiss/`+}++export const warehouseSuggestionsDismissCreate = async (+ projectId: string,+ id: string,+ dismissWarehouseSuggestionApi: DismissWarehouseSuggestionApi,+ options?: RequestInit+): Promise<WarehouseSuggestionApi> => {+ return apiMutator<WarehouseSuggestionApi>(getWarehouseSuggestionsDismissCreateUrl(projectId, id), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(dismissWarehouseSuggestionApi),+ })+}++export const getWarehouseSuggestionsResumeCreateUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/warehouse_suggestions/${id}/resume/`+}++export const warehouseSuggestionsResumeCreate = async (+ projectId: string,+ id: string,+ options?: RequestInit+): Promise<WarehouseSuggestionApi> => {+ return apiMutator<WarehouseSuggestionApi>(getWarehouseSuggestionsResumeCreateUrl(projectId, id), {+ ...options,+ method: 'POST',+ })+}diff --git a/products/warehouse_suggestions/frontend/generated/api.zod.ts b/products/warehouse_suggestions/frontend/generated/api.zod.tsnew file mode 100644index 000000000000..96595298ef7d--- /dev/null+++ b/products/warehouse_suggestions/frontend/generated/api.zod.ts@@ -0,0 +1,26 @@+/**+ * Auto-generated Zod validation schemas from the Django backend OpenAPI schema.+ * To modify these schemas, update the Django serializers or views, then run:+ * hogli build:openapi+ * Questions or issues? #team-devex on Slack+ *+ * PostHog API - generated+ * OpenAPI spec version: 1.0.0+ */+import * as zod from 'zod'++export const warehouseSuggestionsDismissCreateBodyNoteMax = 1000++export const WarehouseSuggestionsDismissCreateBody = /* @__PURE__ */ zod.object({+ reason: zod+ .enum(['not_useful', 'not_now', 'other'])+ .describe('\* `not_useful` - Not useful\n\* `not_now` - Not now\n\* `other` - Other')+ .describe(+ 'Why the suggestion is dismissed.\n\n\* `not_useful` - Not useful\n\* `not_now` - Not now\n\* `other` - Other'+ ),+ note: zod+ .string()+ .max(warehouseSuggestionsDismissCreateBodyNoteMax)+ .optional()+ .describe('Optional note about the dismissal.'),+})diff --git a/products/warehouse_suggestions/manifest.tsx b/products/warehouse_suggestions/manifest.tsxnew file mode 100644index 000000000000..36651f32d6db--- /dev/null+++ b/products/warehouse_suggestions/manifest.tsx@@ -0,0 +1,23 @@+/**+ * Product manifest for warehouse_suggestions.+ *+ * Defines scenes, routes, URLs, and navigation for this product.+ */+import { ProductManifest } from '../../frontend/src/types'++export const manifest: ProductManifest = {+ name: 'WarehouseSuggestions',+ scenes: {+ // Define scenes here+ },+ routes: {+ // Define routes here+ },+ redirects: {},+ urls: {+ // Define URL helpers here+ },+ fileSystemTypes: {},+ treeItemsNew: [],+ treeItemsProducts: [],+}diff --git a/products/warehouse_suggestions/package.json b/products/warehouse_suggestions/package.jsonnew file mode 100644index 000000000000..4cf69165c228--- /dev/null+++ b/products/warehouse_suggestions/package.json@@ -0,0 +1,7 @@+{+ "name": "@posthog/products-warehouse-suggestions",+ "scripts": {+ "backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/tests -v --tb=short",+ "backend:contract-check": "echo 'Contract files unchanged'"+ }+}diff --git a/products/warehouse_suggestions/product.yaml b/products/warehouse_suggestions/product.yamlnew file mode 100644index 000000000000..09402ad298d7--- /dev/null+++ b/products/warehouse_suggestions/product.yaml@@ -0,0 +1,3 @@+name: Warehouse suggestions+owners:+ - team-data-modelingdiff --git a/products/warehouse_suggestions/tsconfig.json b/products/warehouse_suggestions/tsconfig.jsonnew file mode 100644index 000000000000..fe425d6fcba8--- /dev/null+++ b/products/warehouse_suggestions/tsconfig.json@@ -0,0 +1,6 @@+{+ "extends": "../../tsconfig.json",+ "compilerOptions": {+ "composite": true+ }+}diff --git a/products/warehouse_suggestions/turbo.json b/products/warehouse_suggestions/turbo.jsonnew file mode 100644index 000000000000..2473b86b299b--- /dev/null+++ b/products/warehouse_suggestions/turbo.json@@ -0,0 +1,17 @@+{+ "extends": ["//"],+ "tasks": {+ "backend:contract-check": {+ "inputs": [+ "backend/facade/**",+ "backend/presentation/**",+ "backend/routes.py",+ "backend/webhook_consumers.py",+ "backend/models.py",+ "backend/migrations/**"+ ],+ "outputs": [],+ "cache": true+ }+ }+}diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex a6369ad4817a..7a1a0b437541 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -36431,6 +36431,34 @@ export namespace Schemas {readonly icon_path: string | null;}+ /**+ * * `not_useful` - Not useful+ * * `not_now` - Not now+ * * `other` - Other+ */+ export type WarehouseSuggestionDismissalReasonEnum = typeof WarehouseSuggestionDismissalReasonEnum[keyof typeof WarehouseSuggestionDismissalReasonEnum];+++ export const WarehouseSuggestionDismissalReasonEnum = {+ NotUseful: 'not_useful',+ NotNow: 'not_now',+ Other: 'other',+ } as const;++ export interface DismissWarehouseSuggestion {+ /** Why the suggestion is dismissed.+ *+ * * `not_useful` - Not useful+ * * `not_now` - Not now+ * * `other` - Other */+ reason: WarehouseSuggestionDismissalReasonEnum;+ /**+ * Optional note about the dismissal.+ * @maxLength 1000+ */+ note?: string;+ }+/*** * `already_fixed` - Already fixed* * `report_unclear` - Report is unclear to me@@ -74363,6 +74391,174 @@ export namespace Schemas {results: WarehouseColumnStatistics[];}+ export interface WarehouseSuggestionReviewer {+ /** User id. */+ id: number;+ /** User first name. */+ first_name: string;+ /** User email. */+ email: string;+ }++ /**+ * * `certify` - Certify+ * * `deprecate` - Deprecate+ * * `materialize` - Materialize+ */+ export type WarehouseSuggestionKindEnum = typeof WarehouseSuggestionKindEnum[keyof typeof WarehouseSuggestionKindEnum];+++ export const WarehouseSuggestionKindEnum = {+ Certify: 'certify',+ Deprecate: 'deprecate',+ Materialize: 'materialize',+ } as const;++ /**+ * * `saved_query` - Saved query+ * * `table` - Table+ */+ export type WarehouseSuggestionSubjectKindEnum = typeof WarehouseSuggestionSubjectKindEnum[keyof typeof WarehouseSuggestionSubjectKindEnum];+++ export const WarehouseSuggestionSubjectKindEnum = {+ SavedQuery: 'saved_query',+ Table: 'table',+ } as const;++ /**+ * * `proposed` - Proposed+ * * `accepted` - Accepted+ * * `dismissed` - Dismissed+ * * `expired` - Expired+ * * `auto_resolved` - Auto-resolved+ */+ export type WarehouseSuggestionStatusEnum = typeof WarehouseSuggestionStatusEnum[keyof typeof WarehouseSuggestionStatusEnum];+++ export const WarehouseSuggestionStatusEnum = {+ Proposed: 'proposed',+ Accepted: 'accepted',+ Dismissed: 'dismissed',+ Expired: 'expired',+ AutoResolved: 'auto_resolved',+ } as const;++ /**+ * * `live` - Live+ * * `deleted` - Deleted+ * * `unused` - Unused+ */+ export type WarehouseSuggestionAssetOutcomeEnum = typeof WarehouseSuggestionAssetOutcomeEnum[keyof typeof WarehouseSuggestionAssetOutcomeEnum];+++ export const WarehouseSuggestionAssetOutcomeEnum = {+ Live: 'live',+ Deleted: 'deleted',+ 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.+ */+ export type WarehouseSuggestionEvidence = { [key: string]: unknown };++ /**+ * What accepting this suggestion created. Null until accepted.+ * @nullable+ */+ export type WarehouseSuggestionCreatedAsset = { [key: string]: unknown } | null;++ export interface WarehouseSuggestion {+ /** What accepting this suggestion would create or change. Shape depends on kind. */+ payload: WarehouseSuggestionPayload;+ /** The usage numbers that led to this suggestion. */+ evidence: WarehouseSuggestionEvidence;+ /**+ * What accepting this suggestion created. Null until accepted.+ * @nullable+ */+ created_asset: WarehouseSuggestionCreatedAsset;+ /** Who accepted or dismissed this suggestion. Null while it is open. */+ reviewed_by: WarehouseSuggestionReviewer | null;+ /** What the suggestion proposes: certify, deprecate or materialize the subject.+ *+ * * `certify` - Certify+ * * `deprecate` - Deprecate+ * * `materialize` - Materialize */+ kind: WarehouseSuggestionKindEnum;+ /** Whether the subject is a saved query (view) or a warehouse table.+ *+ * * `saved_query` - Saved query+ * * `table` - Table */+ subject_kind: WarehouseSuggestionSubjectKindEnum;+ /** proposed until someone accepts or dismisses it, or the job expires it.+ *+ * * `proposed` - Proposed+ * * `accepted` - Accepted+ * * `dismissed` - Dismissed+ * * `expired` - Expired+ * * `auto_resolved` - Auto-resolved */+ status: WarehouseSuggestionStatusEnum;+ /** Why the suggestion was dismissed.+ *+ * * `not_useful` - Not useful+ * * `not_now` - Not now+ * * `other` - Other */+ dismissal_reason: WarehouseSuggestionDismissalReasonEnum | null;+ /** What happened to the asset an accepted suggestion created.+ *+ * * `live` - Live+ * * `deleted` - Deleted+ * * `unused` - Unused */+ asset_outcome: WarehouseSuggestionAssetOutcomeEnum | null;+ /** Suggestion identifier. */+ id: string;+ /** Id of the view or table the suggestion is about. */+ subject_id: string;+ /** Version of the payload shape for this kind. */+ payload_version: number;+ /** Start of the usage window the evidence covers. */+ evidence_window_start: string;+ /** End of the usage window the evidence covers. */+ evidence_window_end: string;+ /** When the daily job last found evidence for this suggestion. */+ last_seen_at: string;+ /** How strongly the evidence supports the suggestion. Higher comes first. */+ score: number;+ /**+ * When the suggestion was first shown. Null while it waits for a slot.+ * @nullable+ */+ surfaced_at: string | null;+ /**+ * When the suggestion was accepted or dismissed.+ * @nullable+ */+ reviewed_at: string | null;+ /**+ * Free-text note left when dismissing.+ * @nullable+ */+ dismissal_note: string | null;+ /** Whether the caller has edit access to the subject and so may accept, dismiss or resume. */+ can_act: boolean;+ }++ export interface PaginatedWarehouseSuggestionList {+ count: number;+ /** @nullable */+ next?: string | null;+ /** @nullable */+ previous?: string | null;+ results: WarehouseSuggestion[];+ }+export interface WebAnalyticsFilterPreset {readonly id: string;readonly short_id: string;@@ -114659,6 +114855,7 @@ export namespace Schemas {* * `TableCertification` - TableCertification* * `DataQualityCheck` - DataQualityCheck* * `DataQualityCheckSchedule` - DataQualityCheckSchedule+ * * `WarehouseSuggestion` - WarehouseSuggestion* * `Billing` - Billing* * `Loop` - Loop* * `StamphogRepoConfig` - StamphogRepoConfig@@ -114764,6 +114961,7 @@ export namespace Schemas {TableCertification: 'TableCertification',DataQualityCheck: 'DataQualityCheck',DataQualityCheckSchedule: 'DataQualityCheckSchedule',+ WarehouseSuggestion: 'WarehouseSuggestion',Billing: 'Billing',Loop: 'Loop',StamphogRepoConfig: 'StamphogRepoConfig',@@ -114855,6 +115053,7 @@ export namespace Schemas {* * `TableCertification` - TableCertification* * `DataQualityCheck` - DataQualityCheck* * `DataQualityCheckSchedule` - DataQualityCheckSchedule+ * * `WarehouseSuggestion` - WarehouseSuggestion* * `Billing` - Billing* * `Loop` - Loop* * `StamphogRepoConfig` - StamphogRepoConfig@@ -114948,6 +115147,7 @@ export namespace Schemas {TableCertification: 'TableCertification',DataQualityCheck: 'DataQualityCheck',DataQualityCheckSchedule: 'DataQualityCheckSchedule',+ WarehouseSuggestion: 'WarehouseSuggestion',Billing: 'Billing',Loop: 'Loop',StamphogRepoConfig: 'StamphogRepoConfig',@@ -126729,6 +126929,57 @@ export namespace Schemas {offset?: number;};+ export type WarehouseSuggestionsListParams = {+ /**+ * Only return suggestions of this kind.+ *+ * * `certify` - Certify+ * * `deprecate` - Deprecate+ * * `materialize` - Materialize+ * @minLength 1+ */+ kind?: WarehouseSuggestionsListKind;+ /**+ * Number of results to return per page.+ */+ limit?: number;+ /**+ * The initial index from which to return the results.+ */+ offset?: number;+ /**+ * Only return suggestions in this status.+ *+ * * `proposed` - Proposed+ * * `accepted` - Accepted+ * * `dismissed` - Dismissed+ * * `expired` - Expired+ * * `auto_resolved` - Auto-resolved+ * @minLength 1+ */+ status?: WarehouseSuggestionsListStatus;+ };++ export type WarehouseSuggestionsListKind = typeof WarehouseSuggestionsListKind[keyof typeof WarehouseSuggestionsListKind];+++ export const WarehouseSuggestionsListKind = {+ Certify: 'certify',+ Deprecate: 'deprecate',+ Materialize: 'materialize',+ } as const;++ export type WarehouseSuggestionsListStatus = typeof WarehouseSuggestionsListStatus[keyof typeof WarehouseSuggestionsListStatus];+++ export const WarehouseSuggestionsListStatus = {+ Proposed: 'proposed',+ Accepted: 'accepted',+ Dismissed: 'dismissed',+ Expired: 'expired',+ AutoResolved: 'auto_resolved',+ } as const;+export type WarehouseTablesListParams = {/*** Number of results to return per page.diff --git a/tach.toml b/tach.tomlindex d7a8eeb9851c..e3cdaf6fe371 100644--- a/tach.toml+++ b/tach.toml@@ -1654,3 +1654,22 @@ expose = [from = ["products.cross_project_dashboards",]++[[modules]]+path = "products.warehouse_suggestions"+depends_on = [+ "posthog",+ "products.access_control",+ "products.data_modeling",+ "products.warehouse_sources",+]+layer = "modules"++[[interfaces]]+expose = [+ "backend\\.facade.*",+ "backend\\.presentation\\.views.*",+]+from = [+ "products.warehouse_suggestions",+]