Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(warehouse-suggestions): suggest unmaterializing rarely read views (#121460)

Thiago Salvatored0ece70b32c2
diff --git a/products/data_modeling/backend/facade/api.py b/products/data_modeling/backend/facade/api.py
index 69fb2ef3da0b..23379c43d052 100644
--- a/products/data_modeling/backend/facade/api.py
+++ b/products/data_modeling/backend/facade/api.py
@@ -52,6 +52,9 @@ _LAZY = {
"saved_query_definitions": "logic.saved_query_reads",
"saved_query_node_ids": "logic.saved_query_reads",
"upstream_table_refs": "logic.saved_query_reads",
+ "upstream_saved_query_ids": "logic.saved_query_reads",
+ "last_query_change_at": "logic.saved_query_reads",
+ "completed_full_refresh_workflow_ids": "logic.saved_query_reads",
"MaterializationFailedError": "facade.contracts",
"MaterializationForbiddenError": "facade.contracts",
"MaterializationRefusedError": "facade.contracts",
diff --git a/products/data_modeling/backend/facade/contracts.py b/products/data_modeling/backend/facade/contracts.py
index 431ac898d8c4..b1e313dc4d98 100644
--- a/products/data_modeling/backend/facade/contracts.py
+++ b/products/data_modeling/backend/facade/contracts.py
@@ -60,6 +60,8 @@ class SavedQueryDefinition:
is_managed: bool
origin: str | None
created_at: datetime
+ refreshes_incrementally: bool = False
+ calls_decision_functions: bool = False
@dataclass(frozen=True)
diff --git a/products/data_modeling/backend/logic/saved_query_reads.py b/products/data_modeling/backend/logic/saved_query_reads.py
index c224d874a609..29287a299b85 100644
--- a/products/data_modeling/backend/logic/saved_query_reads.py
+++ b/products/data_modeling/backend/logic/saved_query_reads.py
@@ -1,20 +1,38 @@
"""Contract-shaped reads of saved queries for consumers outside this product."""
from collections.abc import Collection, Iterable
+from datetime import datetime
from typing import TYPE_CHECKING
from uuid import UUID
from django.conf import settings
+from django.db.models import Max
+
+from posthog.hogql.errors import BaseHogQLError
+from posthog.hogql.functions.prompt_jev import DECISION_FUNCTIONS, PromptJevFinder
+from posthog.hogql.parser import parse_select
+
+from posthog.models.activity_logging.activity_log import ActivityLog
from ..facade.contracts import SavedQueryDefinition, SavedQuerySummary, UpstreamTableRef
+from ..models.data_modeling_job import (
+ DataModelingJob,
+ DataModelingJobEngine,
+ DataModelingJobRunMode,
+ DataModelingJobStatus,
+)
from ..models.datawarehouse_saved_query import DataWarehouseSavedQuery
from ..models.edge import Edge
from ..models.node import Node, NodeType
+from .incremental import get_incremental_config
from .saved_query_freshness import saved_query_materialized_at
from .tier_run_report import MATERIALIZING_TYPES
POSTHOG_TABLE_ORIGIN = "posthog"
WAREHOUSE_TABLE_ID_PROPERTY = "warehouse_table_id"
+SAVED_QUERY_ACTIVITY_SCOPE = "DataWarehouseSavedQuery"
+UPDATED_ACTIVITY = "updated"
+QUERY_FIELD = "query"
if TYPE_CHECKING:
from products.access_control.backend.facade.user_access_control import AccessControlLevel, UserAccessControl
@@ -105,7 +123,7 @@ def saved_query_definitions(team_id: int, *, ids: Collection[UUID] | None = None
saved_queries_in_team = saved_queries_in_team.filter(id__in=ids)
saved_queries = list(
saved_queries_in_team.exclude(deleted=True)
- .only("id", "name", "query", "is_test", "managed_viewset_id", "origin", "created_at")
+ .only("id", "name", "query", "is_test", "managed_viewset_id", "origin", "created_at", "incremental_config")
.order_by("created_at", "id")
)
materializing_ids = set(
@@ -115,19 +133,34 @@ def saved_query_definitions(team_id: int, *, ids: Collection[UUID] | None = None
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 "",
- 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
- ]
+ return [_definition(saved_query, materializes=saved_query.id in materializing_ids) for saved_query in saved_queries]
+
+
+def _definition(saved_query: DataWarehouseSavedQuery, *, materializes: bool) -> SavedQueryDefinition:
+ hogql = (saved_query.query or {}).get("query") or ""
+ return SavedQueryDefinition(
+ id=saved_query.id,
+ name=saved_query.name,
+ hogql=hogql,
+ materializes=materializes,
+ 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,
+ refreshes_incrementally=get_incremental_config(saved_query) is not None,
+ calls_decision_functions=calls_decision_functions(hogql),
+ )
+
+
+def calls_decision_functions(hogql: str) -> bool:
+ """Whether the query calls `jev()` or `decide()`, assuming it does when the query does not parse."""
+ lowered = hogql.lower()
+ if not any(name in lowered for name in DECISION_FUNCTIONS):
+ return False
+ try:
+ return PromptJevFinder.contains(parse_select(hogql))
+ except BaseHogQLError:
+ return True
def allowed_saved_query_ids(
@@ -348,3 +381,38 @@ def _upstream_table_nodes(team_id: int, saved_query_id: str) -> list[tuple[str,
def _warehouse_table_id(properties: dict[str, object]) -> str | None:
warehouse_table_id = properties.get(WAREHOUSE_TABLE_ID_PROPERTY)
return str(warehouse_table_id) if warehouse_table_id else None
+
+
+def upstream_saved_query_ids(team_id: int, saved_query_id: UUID | str) -> frozenset[UUID]:
+ """The saved queries this saved query reads from, directly or through other views in any DAG."""
+ start_node_ids = _node_ids_standing_for(team_id, {str(saved_query_id)})
+ reached = reachable_node_ids(team_id, start_node_ids, upstream=True, max_depth=None)
+ return frozenset(
+ Node.objects.filter(team_id=team_id, id__in=reached, saved_query_id__isnull=False)
+ .exclude(saved_query_id=saved_query_id)
+ .values_list("saved_query_id", flat=True)
+ )
+
+
+def last_query_change_at(team_id: int, saved_query_ids: Collection[UUID]) -> datetime | None:
+ """When someone last changed the query of any of these saved queries, per the activity log."""
+ return ActivityLog.objects.filter(
+ team_id=team_id,
+ scope=SAVED_QUERY_ACTIVITY_SCOPE,
+ item_id__in=[str(saved_query_id) for saved_query_id in saved_query_ids],
+ activity=UPDATED_ACTIVITY,
+ detail__changes__contains=[{"field": QUERY_FIELD}],
+ ).aggregate(changed_at=Max("created_at"))["changed_at"]
+
+
+def completed_full_refresh_workflow_ids(team_id: int, saved_query_id: UUID | str, *, since: datetime) -> frozenset[str]:
+ """The workflow ids of this saved query's ClickHouse full refreshes that completed and started at or after ``since``."""
+ workflow_ids = DataModelingJob.objects.filter(
+ team_id=team_id,
+ saved_query_id=saved_query_id,
+ engine=DataModelingJobEngine.CLICKHOUSE,
+ status=DataModelingJobStatus.COMPLETED,
+ run_mode=DataModelingJobRunMode.FULL_REFRESH,
+ created_at__gte=since,
+ ).values_list("workflow_id", flat=True)
+ return frozenset(workflow_id for workflow_id in workflow_ids if workflow_id is not None)
diff --git a/products/data_modeling/backend/test/test_saved_query_reads.py b/products/data_modeling/backend/test/test_saved_query_reads.py
index c59dbc8f7d0d..dc029bc48887 100644
--- a/products/data_modeling/backend/test/test_saved_query_reads.py
+++ b/products/data_modeling/backend/test/test_saved_query_reads.py
@@ -85,12 +85,13 @@ class TestSavedQueryReads(BaseTest):
name="orders",
query={"kind": "HogQLQuery", "query": "SELECT 1"},
is_materialized=False,
+ incremental_config={"enabled": True, "incremental_key": "day", "unique_key": ["day"]},
)
Node.objects.create(team=self.team, dag=dag, saved_query=live, type=NodeType.MAT_VIEW)
plain = DataWarehouseSavedQuery.objects.create(
team=self.team,
name="plain",
- query={"kind": "HogQLQuery", "query": "SELECT 2"},
+ query={"kind": "HogQLQuery", "query": "SELECT jev(event, 'Is this a purchase?') FROM events"},
is_materialized=True,
)
Node.objects.create(team=self.team, dag=dag, saved_query=plain, type=NodeType.VIEW)
@@ -108,16 +109,18 @@ class TestSavedQueryReads(BaseTest):
is_managed=False,
origin=None,
created_at=live.created_at,
+ refreshes_incrementally=True,
),
SavedQueryDefinition(
id=plain.id,
name="plain",
- hogql="SELECT 2",
+ hogql="SELECT jev(event, 'Is this a purchase?') FROM events",
materializes=False,
is_test=False,
is_managed=False,
origin=None,
created_at=plain.created_at,
+ calls_decision_functions=True,
),
]
diff --git a/products/warehouse_suggestions/backend/facade/contracts.py b/products/warehouse_suggestions/backend/facade/contracts.py
index 49ad6909e37d..8bd2785dbf53 100644
--- a/products/warehouse_suggestions/backend/facade/contracts.py
+++ b/products/warehouse_suggestions/backend/facade/contracts.py
@@ -62,7 +62,18 @@ class MaterializePayload:
refresh_interval_basis: WarehouseSuggestionRefreshIntervalBasis | None = None
-SuggestionPayload = CertifyPayload | DeprecatePayload | MaterializePayload
+@frozen
+class UnmaterializePayload:
+ subject_name: str
+ refresh_seconds_per_month: float
+ refresh_bytes_per_month: float
+ live_seconds_per_month: float
+ live_bytes_per_month: float
+ read_seconds: float
+ query_fingerprint: str
+
+
+SuggestionPayload = CertifyPayload | DeprecatePayload | MaterializePayload | UnmaterializePayload
@frozen
@@ -90,7 +101,7 @@ class MaterializeSuggestionPayload:
refresh_interval_basis: WarehouseSuggestionRefreshIntervalBasis | None = None
-SuggestionPayloadView = CertifyPayload | DeprecatePayload | MaterializeSuggestionPayload
+SuggestionPayloadView = CertifyPayload | DeprecatePayload | MaterializeSuggestionPayload | UnmaterializePayload
@frozen
@@ -168,7 +179,12 @@ class AcceptOptions:
keep_materialized: bool | None = None
-CreatedAsset = CertificationAsset | MaterializationAsset
+@frozen
+class UnmaterializationAsset:
+ saved_query_id: str
+
+
+CreatedAsset = CertificationAsset | MaterializationAsset | UnmaterializationAsset
@frozen
diff --git a/products/warehouse_suggestions/backend/facade/enums.py b/products/warehouse_suggestions/backend/facade/enums.py
index c449d9d0ba05..25a8ba1a8002 100644
--- a/products/warehouse_suggestions/backend/facade/enums.py
+++ b/products/warehouse_suggestions/backend/facade/enums.py
@@ -7,6 +7,7 @@ class WarehouseSuggestionKind(LabeledStrEnum):
CERTIFY = "certify"
DEPRECATE = "deprecate"
MATERIALIZE = "materialize"
+ UNMATERIALIZE = "unmaterialize"
class WarehouseSuggestionStatus(LabeledStrEnum):
diff --git a/products/warehouse_suggestions/backend/logic/accept.py b/products/warehouse_suggestions/backend/logic/accept.py
index 196a6a78b409..304c81fe7232 100644
--- a/products/warehouse_suggestions/backend/logic/accept.py
+++ b/products/warehouse_suggestions/backend/logic/accept.py
@@ -29,7 +29,11 @@ from products.data_modeling.backend.facade.api import (
saved_query_still_materializes,
)
from products.data_modeling.backend.facade.contracts import SavedQueryDefinition
-from products.warehouse_sources.backend.facade.api import get_queryable_table, saved_queries_feeding_consumers
+from products.warehouse_sources.backend.facade.api import (
+ direct_access_table_ids,
+ get_queryable_table,
+ saved_queries_feeding_consumers,
+)
from ..facade.contracts import (
AcceptFailedError,
@@ -46,6 +50,8 @@ from ..facade.contracts import (
SuggestionOutdatedError,
SuggestionPayload,
SuggestionSubjectGoneError,
+ UnmaterializationAsset,
+ UnmaterializePayload,
)
from ..facade.enums import (
WarehouseSuggestionKind,
@@ -55,6 +61,8 @@ from ..facade.enums import (
)
from ..models import WarehouseSuggestion
from .analytics import SuggestionOutcome, report_outcomes
+from .candidates.base import inlining_could_deny_a_reader, reads_direct_source
+from .candidates.unmaterialize import effective_definition
from .payloads import payload_from_json
from .suggestions import HUMAN_TRANSITIONS, Transitions, transition_to
@@ -88,6 +96,11 @@ KEEP_MATERIALIZED_FIELD = "keep_materialized"
WAREHOUSE_SUGGESTION_TRIGGER_JOB_TYPE = "warehouse_suggestion"
OTHER_VIEWS_READ_IT = "Other views now read from this view."
SYNCS_READ_IT = "This view now feeds person properties, account properties, a destination or a workflow."
+READS_DIRECT_SOURCE = "This view now reads a direct-connection source, whose reads are not logged."
+READERS_WOULD_LOSE_ACCESS = (
+ "Someone who can read this view may not be able to read the tables it reads from, "
+ "so they could lose access once it computes on read."
+)
@frozen
@@ -152,6 +165,10 @@ def stop_blocker(team_id: int, definition: SavedQueryDefinition) -> str | None:
return OTHER_VIEWS_READ_IT
if definition.id in saved_queries_feeding_consumers(team_id, [definition.id]):
return SYNCS_READ_IT
+ if reads_direct_source(team_id, definition.id, direct_access_table_ids(team_id)):
+ return READS_DIRECT_SOURCE
+ if inlining_could_deny_a_reader(team_id, definition.id):
+ return READERS_WOULD_LOSE_ACCESS
return None
@@ -180,6 +197,46 @@ def stop_materializing(suggestion: WarehouseSuggestion, request: AcceptRequest)
raise AcceptFailedError(str(error))
+NO_LONGER_MATERIALIZED = "This view is no longer materialized."
+NOW_REFRESHES_INCREMENTALLY = (
+ "This view now refreshes incrementally, so the suggestion's cost estimate no longer applies."
+)
+NOW_CALLS_DECISION_FUNCTIONS = "This view now calls jev() or decide(), which would run a model on every read."
+QUERY_CHANGED = (
+ "This view's query, or the query of a view it reads from, changed after the suggestion was made, "
+ "so its read time estimate no longer applies."
+)
+
+
+class UnmaterializeAcceptor(Acceptor):
+ def accept(
+ self, suggestion: WarehouseSuggestion, payload: SuggestionPayload, request: AcceptRequest
+ ) -> CreatedAsset:
+ definition = _definition(suggestion)
+ if definition is None:
+ raise SuggestionSubjectGoneError(WarehouseSuggestionSubjectKind.SAVED_QUERY)
+ if (
+ not isinstance(payload, UnmaterializePayload)
+ or payload.query_fingerprint != effective_definition(suggestion.team_id, definition).fingerprint
+ ):
+ raise SuggestionOutdatedError(QUERY_CHANGED)
+ blocker = _unmaterialize_blocker(suggestion.team_id, definition)
+ if blocker is not None:
+ raise SuggestionOutdatedError(blocker)
+ stop_materializing(suggestion, request)
+ return UnmaterializationAsset(saved_query_id=str(suggestion.subject_id))
+
+
+def _unmaterialize_blocker(team_id: int, definition: SavedQueryDefinition) -> str | None:
+ if not saved_query_still_materializes(team_id, definition.id):
+ return NO_LONGER_MATERIALIZED
+ if definition.refreshes_incrementally:
+ return NOW_REFRESHES_INCREMENTALLY
+ if definition.calls_decision_functions:
+ return NOW_CALLS_DECISION_FUNCTIONS
+ return stop_blocker(team_id, definition)
+
+
VIEW_CHANGED_SINCE_SUGGESTED = (
"This view changed after the suggestion was made, so it can no longer refresh incrementally on the suggested keys."
)
@@ -313,6 +370,7 @@ ACCEPTORS: Mapping[WarehouseSuggestionKind, Acceptor] = {
status=CertificationStatus.DEPRECATED, apply=deprecate, reuses_existing=True, stops_materialization=True
),
WarehouseSuggestionKind.MATERIALIZE: MaterializeAcceptor(),
+ WarehouseSuggestionKind.UNMATERIALIZE: UnmaterializeAcceptor(),
}
@@ -400,9 +458,7 @@ def _accept(team_id: int, suggestion_id: UUID, request: AcceptRequest) -> Accept
def refresh_savings(created_asset: CreatedAsset, payload: SuggestionPayload) -> RefreshSavings:
- if not isinstance(created_asset, CertificationAsset) or not created_asset.stopped_materialization:
- return NO_REFRESH_SAVINGS
- if not isinstance(payload, DeprecatePayload):
+ if not _stopped_materialization(created_asset) or not isinstance(payload, DeprecatePayload | UnmaterializePayload):
return NO_REFRESH_SAVINGS
return RefreshSavings(
stopped_materialization=True,
@@ -411,6 +467,12 @@ def refresh_savings(created_asset: CreatedAsset, payload: SuggestionPayload) ->
)
+def _stopped_materialization(created_asset: CreatedAsset) -> bool:
+ if isinstance(created_asset, UnmaterializationAsset):
+ return True
+ return isinstance(created_asset, CertificationAsset) and created_asset.stopped_materialization
+
+
def _refuse_options_the_kind_ignores(acceptor: Acceptor, kind: WarehouseSuggestionKind, options: AcceptOptions) -> None:
ignored = [name for name in chosen_fields(options) if name not in acceptor.option_fields]
if ignored:
diff --git a/products/warehouse_suggestions/backend/logic/candidates/base.py b/products/warehouse_suggestions/backend/logic/candidates/base.py
index 5f0fc65c568d..ecc0cabb6874 100644
--- a/products/warehouse_suggestions/backend/logic/candidates/base.py
+++ b/products/warehouse_suggestions/backend/logic/candidates/base.py
@@ -1,13 +1,20 @@
import hashlib
from abc import ABC, abstractmethod
-from collections.abc import Mapping
+from collections.abc import Collection, Mapping
from datetime import datetime
from math import ceil
-from typing import Any, ClassVar
+from typing import TYPE_CHECKING, Any, ClassVar
+from uuid import UUID
from posthog.dataclasses import frozen
+from posthog.scopes import APIScopeObject
+from products.access_control.backend.facade.api import (
+ every_member_has_resource_access,
+ object_ids_restricted_from_any_member,
+)
from products.data_catalog.backend.facade.enums import CertificationStatus
+from products.data_modeling.backend.facade.api import upstream_saved_query_ids, upstream_table_refs
from products.data_modeling.backend.facade.contracts import SavedQueryDefinition
from ...facade.contracts import PAYLOAD_VERSION, SuggestionDraft, SuggestionPayload
@@ -18,6 +25,52 @@ from ..rules import Rules, rules_version
DAYS_PER_MONTH = 30
MILLISECONDS_PER_SECOND = 1000
+DEPENDENTS_REJECTION = "other views read from it"
+FEEDS_CONSUMERS_REJECTION = "its refreshes feed person or account properties, a destination or a workflow"
+DIRECT_SOURCE_REJECTION = "reads a direct-connection source, whose reads are not logged"
+READER_ACCESS_REJECTION = "someone who can read it may not be able to read its sources once it computes on read"
+SYSTEM_TABLE_PREFIX = "system."
+READ_LEVEL: "AccessControlLevel" = "viewer"
+WAREHOUSE_RESOURCES: tuple[APIScopeObject, ...] = ("warehouse_objects", "external_data_source")
+
+if TYPE_CHECKING:
+ from products.access_control.backend.facade.user_access_control import AccessControlLevel
+
+
+def reads_direct_source(team_id: int, saved_query_id: UUID, direct_table_ids: Collection[UUID]) -> bool:
+ if not direct_table_ids:
+ return False
+ return any(
+ ref.warehouse_table_id is not None and UUID(ref.warehouse_table_id) in direct_table_ids
+ for ref in upstream_table_refs(team_id, saved_query_id)
+ )
+
+
+def inlining_could_deny_a_reader(team_id: int, saved_query_id: UUID) -> bool:
+ """Whether a person who reads the stored table could lack access to a source the inlined query reads."""
+ refs = upstream_table_refs(team_id, saved_query_id)
+ if any(ref.is_posthog_table and ref.name.startswith(SYSTEM_TABLE_PREFIX) for ref in refs):
+ return True
+ if not all(
+ every_member_has_resource_access(team_id=team_id, resource=resource, required_level=READ_LEVEL)
+ for resource in WAREHOUSE_RESOURCES
+ ):
+ return True
+ if object_ids_restricted_from_any_member(
+ team_id=team_id, resource="external_data_source", required_level=READ_LEVEL
+ ):
+ return True
+ restricted_tables = object_ids_restricted_from_any_member(
+ team_id=team_id, resource="warehouse_table", required_level=READ_LEVEL
+ )
+ if any(ref.warehouse_table_id in restricted_tables for ref in refs if ref.warehouse_table_id is not None):
+ return True
+ restricted_views = object_ids_restricted_from_any_member(
+ team_id=team_id, resource="warehouse_view", required_level=READ_LEVEL
+ )
+ return any(
+ str(upstream_id) in restricted_views for upstream_id in upstream_saved_query_ids(team_id, saved_query_id)
+ )
@frozen
@@ -27,6 +80,19 @@ class CandidateContext:
inventory: TeamInventory
rules: Rules
run_id: str
+ recent_accepts: Mapping[WarehouseSuggestionKind, frozenset[UUID]]
+
+ def accepted_recently(self, kind: WarehouseSuggestionKind, saved_query_id: UUID) -> bool:
+ return saved_query_id in self.recent_accepts.get(kind, frozenset())
+
+ def is_read(self, subject: Subject) -> bool:
+ reads = self.reads.reads_of(subject)
+ if reads is None:
+ return False
+ return self.rules.deprecate.counts_background_reads or reads.human_requests > 0
+
+ def reads_direct_source(self, saved_query_id: UUID) -> bool:
+ return reads_direct_source(self.team_id, saved_query_id, self.inventory.direct_table_ids)
@property
def days_observed(self) -> int:
diff --git a/products/warehouse_suggestions/backend/logic/candidates/deprecate.py b/products/warehouse_suggestions/backend/logic/candidates/deprecate.py
index 3418c842d253..d1c792edc8e1 100644
--- a/products/warehouse_suggestions/backend/logic/candidates/deprecate.py
+++ b/products/warehouse_suggestions/backend/logic/candidates/deprecate.py
@@ -1,8 +1,7 @@
from datetime import datetime
-from uuid import UUID
from products.data_catalog.backend.facade.enums import CertificationStatus
-from products.data_modeling.backend.facade.api import dependent_saved_query_ids, upstream_table_refs
+from products.data_modeling.backend.facade.api import dependent_saved_query_ids
from products.data_modeling.backend.facade.contracts import SavedQueryDefinition
from products.warehouse_sources.backend.facade.api import saved_queries_feeding_consumers
@@ -10,6 +9,9 @@ from ...facade.contracts import DeprecatePayload
from ...facade.enums import WarehouseSuggestionAssetOutcome, WarehouseSuggestionKind, WarehouseSuggestionSubjectKind
from ..reads import Subject
from .base import (
+ DEPENDENTS_REJECTION,
+ DIRECT_SOURCE_REJECTION,
+ FEEDS_CONSUMERS_REJECTION,
MILLISECONDS_PER_SECOND,
Candidate,
CandidateContext,
@@ -37,7 +39,7 @@ class DeprecateCandidate(Candidate):
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))
+ and not context.is_read(_subject(saved_query))
]
unread_ids = [saved_query.id for saved_query in unread]
dependents = dependent_saved_query_ids(context.team_id, unread_ids)
@@ -80,7 +82,7 @@ class DeprecateCandidate(Candidate):
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)
+ return saved_query is None or not saved_query.materializes or context.is_read(subject)
def _rejection(
self,
@@ -93,26 +95,13 @@ class DeprecateCandidate(Candidate):
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"
+ return DEPENDENTS_REJECTION
if feeds_consumers:
- return "its refreshes feed person or account properties, a destination or a workflow"
- if self._reads_direct_source(context, saved_query.id):
- return "reads a direct-connection source, whose reads are not logged"
+ return FEEDS_CONSUMERS_REJECTION
+ if context.reads_direct_source(saved_query.id):
+ return DIRECT_SOURCE_REJECTION
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.py
index a3757eb4de01..da220557dd30 100644
--- a/products/warehouse_suggestions/backend/logic/candidates/materialize.py
+++ b/products/warehouse_suggestions/backend/logic/candidates/materialize.py
@@ -143,6 +143,8 @@ class MaterializeCandidate(Candidate):
reads: SubjectReads,
incremental: _IncrementalProposer,
) -> _Proposal | str:
+ if context.accepted_recently(WarehouseSuggestionKind.UNMATERIALIZE, saved_query.id):
+ return f"was unmaterialized on a suggestion in the last {context.rules.lifecycle.flip_cooldown_days} days"
rejection = self._read_floor_rejection(context, reads)
if rejection is not None:
return rejection
diff --git a/products/warehouse_suggestions/backend/logic/candidates/registry.py b/products/warehouse_suggestions/backend/logic/candidates/registry.py
index fe3d19b12485..0ca0945556ed 100644
--- a/products/warehouse_suggestions/backend/logic/candidates/registry.py
+++ b/products/warehouse_suggestions/backend/logic/candidates/registry.py
@@ -5,11 +5,13 @@ from .base import Candidate, CandidateContext, CandidateResult
from .certify import CertifyCandidate
from .deprecate import DeprecateCandidate
from .materialize import MaterializeCandidate
+from .unmaterialize import UnmaterializeCandidate
CANDIDATES: Mapping[WarehouseSuggestionKind, Candidate] = {
WarehouseSuggestionKind.CERTIFY: CertifyCandidate(),
WarehouseSuggestionKind.DEPRECATE: DeprecateCandidate(),
WarehouseSuggestionKind.MATERIALIZE: MaterializeCandidate(),
+ WarehouseSuggestionKind.UNMATERIALIZE: UnmaterializeCandidate(),
}
diff --git a/products/warehouse_suggestions/backend/logic/candidates/unmaterialize.py b/products/warehouse_suggestions/backend/logic/candidates/unmaterialize.py
new file mode 100644
index 000000000000..ca62eb8c58e8
--- /dev/null
+++ b/products/warehouse_suggestions/backend/logic/candidates/unmaterialize.py
@@ -0,0 +1,230 @@
+import json
+import math
+import hashlib
+from collections.abc import Mapping, Sequence
+from datetime import datetime
+from statistics import mean
+from uuid import UUID
+
+from posthog.dataclasses import frozen
+
+from products.data_modeling.backend.facade.api import (
+ completed_full_refresh_workflow_ids,
+ dependent_saved_query_ids,
+ last_query_change_at,
+ saved_query_definitions,
+ upstream_saved_query_ids,
+)
+from products.data_modeling.backend.facade.contracts import SavedQueryDefinition
+from products.warehouse_sources.backend.facade.api import saved_queries_feeding_consumers
+
+from ...facade.contracts import UnmaterializePayload
+from ...facade.enums import WarehouseSuggestionAssetOutcome, WarehouseSuggestionKind, WarehouseSuggestionSubjectKind
+from ..reads import RefreshRun, Subject, SubjectReads
+from .base import (
+ DEPENDENTS_REJECTION,
+ DIRECT_SOURCE_REJECTION,
+ FEEDS_CONSUMERS_REJECTION,
+ MILLISECONDS_PER_SECOND,
+ READER_ACCESS_REJECTION,
+ Candidate,
+ CandidateContext,
+ CandidateResult,
+ Rejection,
+ inlining_could_deny_a_reader,
+)
+
+INCREMENTAL_REJECTION = "refreshes incrementally, so one refresh does not show what a full read costs"
+CALLS_DECISION_FUNCTIONS_REJECTION = "calls jev() or decide(), which would run a model on every read"
+READ_TIME_QUANTILE = 0.9
+
+
+@frozen
+class EffectiveDefinition:
+ fingerprint: str
+ changed_at: datetime | None
+
+
+@frozen
+class _Proposal:
+ saved_query: SavedQueryDefinition
+ payload: UnmaterializePayload
+ score: float
+
+
+class UnmaterializeCandidate(Candidate):
+ kind = WarehouseSuggestionKind.UNMATERIALIZE
+
+ def evaluate(self, context: CandidateContext) -> CandidateResult:
+ proposals: list[_Proposal] = []
+ rejections: list[Rejection] = []
+ for saved_query in context.inventory.saved_queries.values():
+ if not saved_query.materializes or not context.is_suggestible_view(saved_query):
+ continue
+ subject = _subject(saved_query)
+ reads = context.reads.reads_of(subject)
+ if reads is None or not context.is_read(subject):
+ continue
+ outcome = self._propose(context, saved_query, reads)
+ if isinstance(outcome, str):
+ rejections.append(Rejection(subject=subject, reason=outcome))
+ else:
+ proposals.append(outcome)
+ drafts = []
+ for proposal, reason in self._with_graph_rejections(context, proposals):
+ subject = _subject(proposal.saved_query)
+ if reason is not None:
+ rejections.append(Rejection(subject=subject, reason=reason))
+ continue
+ drafts.append(
+ self.draft(
+ context,
+ subject,
+ proposal.payload,
+ score=proposal.score,
+ score_inputs={
+ "refresh_seconds_per_month": proposal.payload.refresh_seconds_per_month,
+ "live_seconds_per_month": proposal.payload.live_seconds_per_month,
+ "refresh_bytes_per_month": proposal.payload.refresh_bytes_per_month,
+ "live_bytes_per_month": proposal.payload.live_bytes_per_month,
+ },
+ )
+ )
+ return CandidateResult(drafts=tuple(drafts), rejections=tuple(rejections))
+
+ def asset_outcome(
+ self, context: CandidateContext, subject: Subject, accepted_at: datetime | None
+ ) -> WarehouseSuggestionAssetOutcome:
+ saved_query = context.inventory.saved_queries.get(subject.id)
+ if saved_query is None:
+ return WarehouseSuggestionAssetOutcome.DELETED
+ if saved_query.materializes:
+ return WarehouseSuggestionAssetOutcome.UNUSED
+ return WarehouseSuggestionAssetOutcome.LIVE
+
+ 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
+
+ def _propose(
+ self, context: CandidateContext, saved_query: SavedQueryDefinition, reads: SubjectReads
+ ) -> _Proposal | str:
+ rules = context.rules.unmaterialize
+ if saved_query.refreshes_incrementally:
+ return INCREMENTAL_REJECTION
+ if saved_query.calls_decision_functions:
+ return CALLS_DECISION_FUNCTIONS_REJECTION
+ if context.accepted_recently(WarehouseSuggestionKind.MATERIALIZE, saved_query.id):
+ return f"was materialized on a suggestion in the last {context.rules.lifecycle.flip_cooldown_days} days"
+ definition = effective_definition(context.team_id, saved_query)
+ runs = context.reads.refresh_runs.get(saved_query.id, ())
+ current_runs = _current_definition_runs(context, saved_query.id, definition, runs)
+ if len(current_runs) < rules.min_runs:
+ return (
+ f"has {len(current_runs)} completed full refreshes of its current query, "
+ f"needs {rules.min_runs} to know its cost"
+ )
+ payload = _payload(context, saved_query, reads, runs, current_runs, definition)
+ seconds_saved = payload.refresh_seconds_per_month - payload.live_seconds_per_month
+ bytes_saved = payload.refresh_bytes_per_month - payload.live_bytes_per_month
+ clears_time = (
+ seconds_saved >= rules.min_seconds_saved
+ and seconds_saved >= rules.min_saved_share * payload.refresh_seconds_per_month
+ )
+ clears_bytes = (
+ bytes_saved >= rules.min_bytes_saved
+ and bytes_saved >= rules.min_saved_share * payload.refresh_bytes_per_month
+ )
+ if not clears_time and not clears_bytes:
+ return "computing it on each read would not save enough over refreshing it"
+ if payload.read_seconds > rules.max_read_seconds:
+ return f"a read could take {payload.read_seconds:.0f} seconds, over {rules.max_read_seconds:.0f}"
+ return _Proposal(
+ saved_query=saved_query,
+ payload=payload,
+ score=max(seconds_saved / rules.min_seconds_saved, bytes_saved / rules.min_bytes_saved),
+ )
+
+ def _with_graph_rejections(
+ self, context: CandidateContext, proposals: list[_Proposal]
+ ) -> list[tuple[_Proposal, str | None]]:
+ ids = [proposal.saved_query.id for proposal in proposals]
+ dependents = dependent_saved_query_ids(context.team_id, ids)
+ feeding_consumers = saved_queries_feeding_consumers(context.team_id, ids)
+ return [
+ (proposal, _graph_rejection(context, proposal.saved_query.id, dependents, feeding_consumers))
+ for proposal in proposals
+ ]
+
+
+def _graph_rejection(
+ context: CandidateContext,
+ saved_query_id: UUID,
+ dependents: Mapping[UUID, frozenset[UUID]],
+ feeding_consumers: frozenset[UUID],
+) -> str | None:
+ if dependents.get(saved_query_id):
+ return DEPENDENTS_REJECTION
+ if saved_query_id in feeding_consumers:
+ return FEEDS_CONSUMERS_REJECTION
+ if context.reads_direct_source(saved_query_id):
+ return DIRECT_SOURCE_REJECTION
+ if inlining_could_deny_a_reader(context.team_id, saved_query_id):
+ return READER_ACCESS_REJECTION
+ return None
+
+
+def effective_definition(team_id: int, saved_query: SavedQueryDefinition) -> EffectiveDefinition:
+ upstream_ids = upstream_saved_query_ids(team_id, saved_query.id)
+ upstream_queries = [upstream.hogql for upstream in saved_query_definitions(team_id, ids=upstream_ids)]
+ return EffectiveDefinition(
+ fingerprint=definition_fingerprint([saved_query.hogql, *upstream_queries]),
+ changed_at=last_query_change_at(team_id, {saved_query.id, *upstream_ids}),
+ )
+
+
+def definition_fingerprint(queries: Sequence[str]) -> str:
+ return hashlib.sha256(json.dumps(list(queries)).encode()).hexdigest()
+
+
+def _current_definition_runs(
+ context: CandidateContext, saved_query_id: UUID, definition: EffectiveDefinition, runs: Sequence[RefreshRun]
+) -> list[RefreshRun]:
+ since = context.reads.window.starts_at
+ if definition.changed_at is not None:
+ since = max(since, definition.changed_at)
+ workflow_ids = completed_full_refresh_workflow_ids(context.team_id, saved_query_id, since=since)
+ return [run for run in runs if run.workflow_id in workflow_ids]
+
+
+def _payload(
+ context: CandidateContext,
+ saved_query: SavedQueryDefinition,
+ reads: SubjectReads,
+ runs: Sequence[RefreshRun],
+ current_runs: Sequence[RefreshRun],
+ definition: EffectiveDefinition,
+) -> UnmaterializePayload:
+ scale = context.month_scale
+ reads_per_month = (reads.human_reads + reads.background_reads) * scale
+ runs_per_month = len(runs) * scale
+ seconds_per_run = mean(run.duration_ms for run in current_runs) / MILLISECONDS_PER_SECOND
+ bytes_per_run = mean(run.read_bytes for run in current_runs)
+ return UnmaterializePayload(
+ subject_name=saved_query.name,
+ refresh_seconds_per_month=runs_per_month * seconds_per_run,
+ refresh_bytes_per_month=runs_per_month * bytes_per_run,
+ live_seconds_per_month=reads_per_month * seconds_per_run,
+ live_bytes_per_month=reads_per_month * bytes_per_run,
+ read_seconds=_read_time_quantile_ms(current_runs) / MILLISECONDS_PER_SECOND,
+ query_fingerprint=definition.fingerprint,
+ )
+
+
+def _read_time_quantile_ms(runs: Sequence[RefreshRun]) -> int:
+ durations = sorted(run.duration_ms for run in runs)
+ return durations[math.ceil(READ_TIME_QUANTILE * len(durations)) - 1]
+
+
+def _subject(saved_query: SavedQueryDefinition) -> Subject:
+ return Subject(kind=WarehouseSuggestionSubjectKind.SAVED_QUERY, id=saved_query.id)
diff --git a/products/warehouse_suggestions/backend/logic/job.py b/products/warehouse_suggestions/backend/logic/job.py
index 1ef5998f78e8..d48f8e347410 100644
--- a/products/warehouse_suggestions/backend/logic/job.py
+++ b/products/warehouse_suggestions/backend/logic/job.py
@@ -1,5 +1,7 @@
-from datetime import date, datetime
+from collections import defaultdict
+from datetime import date, datetime, timedelta
from enum import StrEnum
+from uuid import UUID
from django.db import transaction
from django.utils import timezone
@@ -15,7 +17,7 @@ from .analytics import report_candidates
from .candidates.base import CandidateContext, CandidateResult
from .candidates.registry import evaluate_candidates
from .inventory import load_inventory
-from .lifecycle import LifecycleResult, apply_run
+from .lifecycle import FLIP_KINDS, LifecycleResult, apply_run
from .reads import ReadWindow, RollupDays, TeamReads, read_rollup_days, read_team_reads
from .rules import RULES, EligibilityRules, Rules
@@ -54,7 +56,7 @@ def run_team(
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)
+ context = build_context(team, reads, run_id=run_id, rules=rules, now=now)
drafts = _evaluate_and_report(context) if eligible else []
with transaction.atomic():
config = _locked_config(team_id)
@@ -69,7 +71,7 @@ def explain_team(
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)
+ context = build_context(team, reads, run_id="explain", rules=rules, now=timezone.now())
return context, evaluate_candidates(context)
@@ -84,8 +86,28 @@ 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 build_context(team: Team, reads: TeamReads, *, run_id: str, rules: Rules, now: datetime) -> CandidateContext:
+ return CandidateContext(
+ team_id=team.pk,
+ reads=reads,
+ inventory=load_inventory(team),
+ rules=rules,
+ run_id=run_id,
+ recent_accepts=_recent_flip_accepts(team.pk, rules, now),
+ )
+
+
+def _recent_flip_accepts(team_id: int, rules: Rules, now: datetime) -> dict[WarehouseSuggestionKind, frozenset[UUID]]:
+ since = now - timedelta(days=rules.lifecycle.flip_cooldown_days)
+ accepted = (
+ WarehouseSuggestion.objects.for_team(team_id)
+ .filter(status=WarehouseSuggestionStatus.ACCEPTED, kind__in=FLIP_KINDS, reviewed_at__gte=since)
+ .values_list("kind", "subject_id")
+ )
+ subject_ids: defaultdict[WarehouseSuggestionKind, set[UUID]] = defaultdict(set)
+ for kind, subject_id in accepted:
+ subject_ids[WarehouseSuggestionKind(kind)].add(subject_id)
+ return {kind: frozenset(ids) for kind, ids in subject_ids.items()}
def _has_suggestions_to_maintain(team_id: int) -> bool:
diff --git a/products/warehouse_suggestions/backend/logic/lifecycle.py b/products/warehouse_suggestions/backend/logic/lifecycle.py
index 6eebc3c8e6f0..50390fb925ec 100644
--- a/products/warehouse_suggestions/backend/logic/lifecycle.py
+++ b/products/warehouse_suggestions/backend/logic/lifecycle.py
@@ -1,5 +1,5 @@
from collections import Counter, defaultdict, deque
-from collections.abc import Collection, Iterable, Sequence
+from collections.abc import Collection, Iterable, Mapping, Sequence
from datetime import datetime, time, timedelta
from functools import partial
from typing import TYPE_CHECKING
@@ -23,7 +23,7 @@ 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
+from .suggestions import ALLOWED_TRANSITIONS, Transitions, transition_to, upsert_suggestions
if TYPE_CHECKING:
from posthog.models.team import Team
@@ -54,7 +54,7 @@ def apply_run(
) -> LifecycleResult:
"""Apply one run's drafts, show new suggestions when `surface` is set, and recheck accepted assets."""
fingerprints = {draft.fingerprint for draft in drafts}
- reopened = _reopen(context, drafts)
+ reopened = _reopen(context, drafts, now)
created = _upsert(context.team_id, drafts)
auto_resolved = _auto_resolve(context, fingerprints)
expired = _expire(context, fingerprints, now)
@@ -94,9 +94,11 @@ def _upsert(team_id: int, drafts: Sequence[SuggestionDraft]) -> list[WarehouseSu
REVIVABLE_STATUSES = (WarehouseSuggestionStatus.EXPIRED, WarehouseSuggestionStatus.AUTO_RESOLVED)
+FLIP_KINDS = frozenset({WarehouseSuggestionKind.MATERIALIZE, WarehouseSuggestionKind.UNMATERIALIZE})
+REOPEN_ACCEPTED: Transitions = {WarehouseSuggestionStatus.ACCEPTED: frozenset({WarehouseSuggestionStatus.PROPOSED})}
-def _reopen(context: CandidateContext, drafts: Sequence[SuggestionDraft]) -> Reopened:
+def _reopen(context: CandidateContext, drafts: Sequence[SuggestionDraft], now: datetime) -> 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)
@@ -111,6 +113,8 @@ def _reopen(context: CandidateContext, drafts: Sequence[SuggestionDraft]) -> Reo
revived.extend(_moved(row, context.team_id, WarehouseSuggestionStatus.PROPOSED))
elif _earns_reproposal(row, drafts_by_fingerprint[row.fingerprint], context.rules.lifecycle):
reproposed.extend(_moved(row, context.team_id, WarehouseSuggestionStatus.PROPOSED))
+ for row in _accepted_then_flipped_back(context, drafts_by_fingerprint, now):
+ reproposed.extend(_moved(row, context.team_id, WarehouseSuggestionStatus.PROPOSED, REOPEN_ACCEPTED))
reproposed_ids = [row.id for row in reproposed]
revived_ids = [row.id for row in revived]
suggestions.filter(id__in=reproposed_ids).update(reproposed_count=F("reproposed_count") + 1)
@@ -121,6 +125,21 @@ def _reopen(context: CandidateContext, drafts: Sequence[SuggestionDraft]) -> Reo
)
+def _accepted_then_flipped_back(
+ context: CandidateContext, drafts_by_fingerprint: Mapping[str, SuggestionDraft], now: datetime
+) -> list[WarehouseSuggestion]:
+ """Accepted materialize and unmaterialize suggestions drafted again, so their view flipped back, past the cooldown."""
+ cooled_down_before = now - timedelta(days=context.rules.lifecycle.flip_cooldown_days)
+ return list(
+ WarehouseSuggestion.objects.for_team(context.team_id).filter(
+ fingerprint__in=drafts_by_fingerprint,
+ status=WarehouseSuggestionStatus.ACCEPTED,
+ kind__in=FLIP_KINDS,
+ reviewed_at__lte=cooled_down_before,
+ )
+ )
+
+
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 (
@@ -237,10 +256,15 @@ def _move_all(
return [moved for row in rows for moved in _moved(row, team_id, status)]
-def _moved(row: WarehouseSuggestion, team_id: int, status: WarehouseSuggestionStatus) -> list[WarehouseSuggestion]:
+def _moved(
+ row: WarehouseSuggestion,
+ team_id: int,
+ status: WarehouseSuggestionStatus,
+ transitions: Transitions = ALLOWED_TRANSITIONS,
+) -> list[WarehouseSuggestion]:
"""The suggestion moved to `status` as the system, or nothing when a person already decided it."""
try:
- return [transition_to(row.id, team_id, status, user_id=None)]
+ return [transition_to(row.id, team_id, status, user_id=None, transitions=transitions)]
except SuggestionAlreadyDecidedError:
return []
diff --git a/products/warehouse_suggestions/backend/logic/payloads.py b/products/warehouse_suggestions/backend/logic/payloads.py
index fa2f8a617c29..8733e4e92a43 100644
--- a/products/warehouse_suggestions/backend/logic/payloads.py
+++ b/products/warehouse_suggestions/backend/logic/payloads.py
@@ -13,6 +13,7 @@ from ..facade.contracts import (
SourceRef,
SuggestionPayload,
SuggestionPayloadView,
+ UnmaterializePayload,
UnsupportedPayloadVersionError,
VisibleSources,
)
@@ -38,6 +39,8 @@ def payload_from_json(
return CertifyPayload(**data)
if kind == WarehouseSuggestionKind.DEPRECATE:
return DeprecatePayload(**data)
+ if kind == WarehouseSuggestionKind.UNMATERIALIZE:
+ return UnmaterializePayload(**data)
sources = {field: tuple(_source_ref(source) for source in data[field]) for field in SOURCE_FIELDS}
return MaterializePayload(**{**data, **sources, **_refresh_fields(data)})
diff --git a/products/warehouse_suggestions/backend/logic/reads.py b/products/warehouse_suggestions/backend/logic/reads.py
index 59ae3c6a4d79..2d342603d15a 100644
--- a/products/warehouse_suggestions/backend/logic/reads.py
+++ b/products/warehouse_suggestions/backend/logic/reads.py
@@ -64,6 +64,7 @@ class SubjectReads:
human_users: int
human_days: int
background_requests: int
+ background_reads: int
human_reads: int
human_duration_ms: int
human_read_bytes: int
@@ -87,6 +88,13 @@ class SubjectRefreshes:
read_bytes: int
+@frozen
+class RefreshRun:
+ workflow_id: str
+ duration_ms: int
+ read_bytes: int
+
+
@frozen
class TeamReads:
window: ReadWindow
@@ -97,6 +105,7 @@ class TeamReads:
view_reads: int
subjects: Mapping[Subject, SubjectReads]
refreshes: Mapping[UUID, SubjectRefreshes]
+ refresh_runs: Mapping[UUID, tuple[RefreshRun, ...]]
def reads_of(self, subject: Subject) -> SubjectReads | None:
return self.subjects.get(subject)
@@ -145,6 +154,7 @@ def read_team_reads(team_id: int, window: ReadWindow, rules: Rules, rollup_days:
view_reads=view_reads,
subjects=_subject_reads(SUBJECTS_SQL.format(human=human_sql), params, team_id, surface_counts),
refreshes=_refreshes(params, team_id),
+ refresh_runs=_refresh_runs(params, team_id),
)
@@ -209,6 +219,7 @@ SELECT
uniqMergeIf(users, is_human),
uniqIf(day, is_human),
uniqMergeIf(requests, NOT is_human),
+ sumIf(read_count, NOT is_human),
sumIf(read_count, is_human),
sumIf(duration_ms_sum, is_human),
sumIf(read_bytes_sum, is_human),
@@ -244,6 +255,21 @@ WHERE {WINDOW_FILTER}
GROUP BY subject_id
"""
+REFRESH_RUNS_SQL = f"""
+SELECT subject_id, workflow_id, sum(duration_ms_sum), sum(read_bytes_sum)
+FROM {WAREHOUSE_OBJECT_READS_DAILY_TABLE}
+WHERE {WINDOW_FILTER}
+ AND read_kind = %(refresh)s
+ AND subject_id IN (
+ SELECT subject_id
+ FROM {WAREHOUSE_OBJECT_READS_DAILY_TABLE}
+ WHERE {WINDOW_FILTER}
+ AND read_kind = %(read)s
+ AND subject_kind = %(saved_query)s
+ )
+GROUP BY subject_id, workflow_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)
@@ -278,15 +304,16 @@ def _subject_reads(
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]),
- alone_duration_ms_p90=float(row[12]),
- alone_read_bytes_p90=float(row[13]),
- last_read_at=row[14],
+ background_reads=row[6],
+ human_reads=row[7],
+ human_duration_ms=row[8],
+ human_read_bytes=row[9],
+ alone_reads=row[10],
+ alone_duration_ms_median=float(row[11]),
+ alone_read_bytes_median=float(row[12]),
+ alone_duration_ms_p90=float(row[13]),
+ alone_read_bytes_p90=float(row[14]),
+ last_read_at=row[15],
requests_by_surface=surface_counts.get(subject, {}),
)
return reads
@@ -299,3 +326,12 @@ def _refreshes(params: Mapping[str, Any], team_id: int) -> dict[UUID, SubjectRef
if subject is not None:
refreshes[subject.id] = SubjectRefreshes(runs=runs, duration_ms=duration_ms, read_bytes=read_bytes)
return refreshes
+
+
+def _refresh_runs(params: Mapping[str, Any], team_id: int) -> dict[UUID, tuple[RefreshRun, ...]]:
+ runs: defaultdict[UUID, list[RefreshRun]] = defaultdict(list)
+ for subject_id, workflow_id, duration_ms, read_bytes in _execute(REFRESH_RUNS_SQL, params, team_id):
+ subject = _subject(WarehouseSuggestionSubjectKind.SAVED_QUERY, subject_id)
+ if subject is not None:
+ runs[subject.id].append(RefreshRun(workflow_id=workflow_id, duration_ms=duration_ms, read_bytes=read_bytes))
+ return {subject_id: tuple(subject_runs) for subject_id, subject_runs in runs.items()}
diff --git a/products/warehouse_suggestions/backend/logic/rules.py b/products/warehouse_suggestions/backend/logic/rules.py
index 9a110781ec9c..80cbd21124b6 100644
--- a/products/warehouse_suggestions/backend/logic/rules.py
+++ b/products/warehouse_suggestions/backend/logic/rules.py
@@ -105,6 +105,15 @@ class MaterializeRules:
incremental_lookback_seconds: int
+@frozen
+class UnmaterializeRules:
+ min_runs: int
+ min_seconds_saved: float
+ min_bytes_saved: float
+ min_saved_share: float
+ max_read_seconds: float
+
+
@frozen
class RefreshRules:
max_interval: timedelta
@@ -119,6 +128,7 @@ class LifecycleRules:
max_open: int
max_open_per_kind: int
first_week_runs: int
+ flip_cooldown_days: int
kind_order: tuple[WarehouseSuggestionKind, ...]
first_week_kind_order: tuple[WarehouseSuggestionKind, ...]
@@ -133,6 +143,7 @@ class Rules:
certify: CertifyRules
deprecate: DeprecateRules
materialize: MaterializeRules
+ unmaterialize: UnmaterializeRules
refresh: RefreshRules
lifecycle: LifecycleRules
@@ -203,6 +214,13 @@ RULES = Rules(
min_saved_share=0.5,
incremental_lookback_seconds=int(timedelta(days=3).total_seconds()),
),
+ unmaterialize=UnmaterializeRules(
+ min_runs=3,
+ min_seconds_saved=600.0,
+ min_bytes_saved=float(TERABYTE),
+ min_saved_share=0.5,
+ max_read_seconds=10.0,
+ ),
refresh=RefreshRules(max_interval=timedelta(hours=24), min_read_day_share_below_max_interval=0.5),
lifecycle=LifecycleRules(
reproposal_score_multiple=3.0,
@@ -211,14 +229,17 @@ RULES = Rules(
max_open=15,
max_open_per_kind=3,
first_week_runs=2,
+ flip_cooldown_days=30,
kind_order=(
WarehouseSuggestionKind.MATERIALIZE,
WarehouseSuggestionKind.DEPRECATE,
+ WarehouseSuggestionKind.UNMATERIALIZE,
WarehouseSuggestionKind.CERTIFY,
),
first_week_kind_order=(
WarehouseSuggestionKind.CERTIFY,
WarehouseSuggestionKind.DEPRECATE,
+ WarehouseSuggestionKind.UNMATERIALIZE,
WarehouseSuggestionKind.MATERIALIZE,
),
),
diff --git a/products/warehouse_suggestions/backend/migrations/0003_warehouse_suggestion_unmaterialize_kind.py b/products/warehouse_suggestions/backend/migrations/0003_warehouse_suggestion_unmaterialize_kind.py
new file mode 100644
index 000000000000..612f0c7879c7
--- /dev/null
+++ b/products/warehouse_suggestions/backend/migrations/0003_warehouse_suggestion_unmaterialize_kind.py
@@ -0,0 +1,25 @@
+# Generated by Django 5.2.18 on 2026-10-21 17:50
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("warehouse_suggestions", "0002_warehousesuggestionteamconfig"),
+ ]
+
+ operations = [
+ migrations.AlterField(
+ model_name="warehousesuggestion",
+ name="kind",
+ field=models.CharField(
+ choices=[
+ ("certify", "Certify"),
+ ("deprecate", "Deprecate"),
+ ("materialize", "Materialize"),
+ ("unmaterialize", "Unmaterialize"),
+ ],
+ max_length=32,
+ ),
+ ),
+ ]
diff --git a/products/warehouse_suggestions/backend/migrations/max_migration.txt b/products/warehouse_suggestions/backend/migrations/max_migration.txt
index 96f2bf6707a2..6ab01f61df99 100644
--- a/products/warehouse_suggestions/backend/migrations/max_migration.txt
+++ b/products/warehouse_suggestions/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0002_warehousesuggestionteamconfig
+0003_warehouse_suggestion_unmaterialize_kind
diff --git a/products/warehouse_suggestions/backend/presentation/serializers.py b/products/warehouse_suggestions/backend/presentation/serializers.py
index 00513ce1111a..c39aa0d119b4 100644
--- a/products/warehouse_suggestions/backend/presentation/serializers.py
+++ b/products/warehouse_suggestions/backend/presentation/serializers.py
@@ -18,6 +18,7 @@ from ..facade.contracts import (
SuggestionPayloadView,
SuggestionReviewer,
SuggestionStatus,
+ UnmaterializePayload,
VisibleSources,
)
from ..facade.enums import (
@@ -127,10 +128,34 @@ class MaterializePayloadSerializer(DataclassSerializer):
}
+@extend_schema_serializer(component_name="WarehouseSuggestionUnmaterializePayload")
+class UnmaterializePayloadSerializer(DataclassSerializer):
+ class Meta:
+ dataclass = UnmaterializePayload
+ exclude = ["query_fingerprint"]
+ extra_kwargs = {
+ "subject_name": {"help_text": "Name of the rarely read materialized view to turn back into a plain view."},
+ "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."},
+ "live_seconds_per_month": {
+ "help_text": "Estimated time its reads would take in a month if each read computed the view, in "
+ "seconds. The estimate uses a full refresh per read, so it leans high."
+ },
+ "live_bytes_per_month": {
+ "help_text": "Estimated bytes its reads would scan in a month if each read computed the view."
+ },
+ "read_seconds": {
+ "help_text": "How long one read would take once the view is computed on read, in seconds. Nine in "
+ "ten of its refreshes finished within this time."
+ },
+ }
+
+
PAYLOAD_SERIALIZERS: dict[type, type[DataclassSerializer]] = {
CertifyPayload: CertifyPayloadSerializer,
DeprecatePayload: DeprecatePayloadSerializer,
MaterializeSuggestionPayload: MaterializePayloadSerializer,
+ UnmaterializePayload: UnmaterializePayloadSerializer,
}
@@ -205,7 +230,8 @@ class WarehouseSuggestionSerializer(DataclassSerializer):
)
kind = serializers.ChoiceField(
choices=WarehouseSuggestionKind.choices,
- help_text="What the suggestion proposes: certify, deprecate or materialize the subject.",
+ help_text="What the suggestion proposes: certify, deprecate, materialize or unmaterialize the subject. "
+ "unmaterialize turns a rarely read materialized view back into a plain view computed on read.",
)
subject_kind = serializers.ChoiceField(
choices=WarehouseSuggestionSubjectKind.choices,
diff --git a/products/warehouse_suggestions/backend/tests/factories.py b/products/warehouse_suggestions/backend/tests/factories.py
index 25f81f03de54..c8b3a6c4b1be 100644
--- a/products/warehouse_suggestions/backend/tests/factories.py
+++ b/products/warehouse_suggestions/backend/tests/factories.py
@@ -6,11 +6,12 @@ from uuid import UUID
from products.data_catalog.backend.facade.enums import CertificationStatus
from products.data_modeling.backend.facade.contracts import SavedQueryDefinition
-from products.warehouse_suggestions.backend.facade.enums import WarehouseSuggestionSubjectKind
+from products.warehouse_suggestions.backend.facade.enums import WarehouseSuggestionKind, 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,
+ RefreshRun,
Subject,
SubjectReads,
SubjectRefreshes,
@@ -36,6 +37,7 @@ def busy_reads(**overrides: Any) -> SubjectReads:
human_users=6,
human_days=25,
background_requests=0,
+ background_reads=0,
human_reads=200,
human_duration_ms=200 * 20_000,
human_read_bytes=200 * 10**9,
@@ -70,6 +72,7 @@ def team_reads(
days_with_data: int = 30,
recent_days_with_data: int = 7,
refreshes: Mapping[UUID, SubjectRefreshes] | None = None,
+ refresh_runs: Mapping[UUID, tuple[RefreshRun, ...]] | None = None,
readers: int = 10,
) -> TeamReads:
return TeamReads(
@@ -81,6 +84,7 @@ def team_reads(
view_reads=1000,
subjects=subjects,
refreshes=refreshes or {},
+ refresh_runs=refresh_runs or {},
)
@@ -93,6 +97,7 @@ def context(
direct_table_ids: frozenset[UUID] = frozenset(),
team_id: int = 1,
rules: Rules = RULES,
+ recent_accepts: Mapping[WarehouseSuggestionKind, frozenset[UUID]] | None = None,
) -> CandidateContext:
return CandidateContext(
team_id=team_id,
@@ -105,6 +110,7 @@ def context(
),
rules=rules,
run_id="run-1",
+ recent_accepts=recent_accepts or {},
)
diff --git a/products/warehouse_suggestions/backend/tests/test_accept.py b/products/warehouse_suggestions/backend/tests/test_accept.py
index 63a1e30dc009..b38eea597cbf 100644
--- a/products/warehouse_suggestions/backend/tests/test_accept.py
+++ b/products/warehouse_suggestions/backend/tests/test_accept.py
@@ -9,24 +9,28 @@ from unittest.mock import patch
from parameterized import parameterized
from rest_framework import status
+from posthog.constants import AvailableFeature
from posthog.models import Team, User
from posthog.models.activity_logging.activity_log import ActivityLog
from posthog.models.personal_api_key import PersonalAPIKey
from posthog.models.utils import generate_random_token_personal, hash_key_value
+from products.access_control.backend.facade.testing import create_access_control
from products.cdp.backend.models.hog_functions import HogFunction
from products.data_catalog.backend.facade.api import certifications_for_team, propose_certification
from products.data_catalog.backend.facade.enums import CertificationStatus
from products.data_modeling.backend.facade.api import get_declared_target, set_declared_target
from products.data_modeling.backend.facade.models import DAG, DataWarehouseSavedQuery, Edge, Node, NodeType
from products.data_tools.backend.facade.models import DataWarehouseJoin
-from products.warehouse_sources.backend.facade.models import DataWarehouseTable
+from products.warehouse_sources.backend.facade.models import DataWarehouseTable, ExternalDataSource
+from products.warehouse_sources.backend.facade.types import ExternalDataSourceType
from products.warehouse_suggestions.backend.facade.contracts import (
CertifyPayload,
DeprecatePayload,
MaterializePayload,
SuggestionAlreadyDecidedError,
SuggestionPayload,
+ UnmaterializePayload,
)
from products.warehouse_suggestions.backend.facade.enums import (
WarehouseSuggestionKind,
@@ -34,6 +38,7 @@ from products.warehouse_suggestions.backend.facade.enums import (
WarehouseSuggestionStatus,
)
from products.warehouse_suggestions.backend.logic.accept import CertificationAcceptor
+from products.warehouse_suggestions.backend.logic.candidates.unmaterialize import definition_fingerprint
from products.warehouse_suggestions.backend.logic.suggestions import HUMAN_TRANSITIONS, transition_to
from products.warehouse_suggestions.backend.models import WarehouseSuggestion
@@ -49,6 +54,8 @@ DAILY_COUNT_COLUMNS = {
"day": {"hogql": "DateTimeDatabaseField", "clickhouse": "DateTime64(6, 'UTC')"},
"c": {"hogql": "IntegerDatabaseField", "clickhouse": "UInt64"},
}
+ORDERS_SQL = "SELECT timestamp, event FROM events"
+UPSTREAM_SQL = "SELECT * FROM postgres_orders"
STORED_DAY_KEY = {"enabled": True, "incremental_key": "day", "unique_key": ["day"], "lookback_seconds": 0}
MATERIALIZE_PAYLOAD = MaterializePayload(
subject_name="orders",
@@ -66,12 +73,22 @@ INCREMENTAL_DAY_PAYLOAD = replace(
incremental_key="day",
unique_key=("day",),
)
+UNMATERIALIZE_PAYLOAD = UnmaterializePayload(
+ subject_name="orders",
+ refresh_seconds_per_month=3600,
+ refresh_bytes_per_month=10**9,
+ live_seconds_per_month=20,
+ live_bytes_per_month=10**6,
+ read_seconds=5,
+ query_fingerprint=definition_fingerprint([ORDERS_SQL]),
+)
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: MATERIALIZE_PAYLOAD,
+ WarehouseSuggestionKind.UNMATERIALIZE: UNMATERIALIZE_PAYLOAD,
}
@@ -79,7 +96,7 @@ def create_view_in_dag(team: Team, user: User) -> DataWarehouseSavedQuery:
view = DataWarehouseSavedQuery.objects.create(
team=team,
name="orders",
- query={"kind": "HogQLQuery", "query": "SELECT timestamp, event FROM events"},
+ query={"kind": "HogQLQuery", "query": ORDERS_SQL},
created_by=user,
)
Node.objects.create(
@@ -111,6 +128,90 @@ def add_dependent_view(view: DataWarehouseSavedQuery) -> None:
Edge.objects.create(team=view.team, dag=node.dag, source=node, target=dependent_node)
+def switch_to_incremental(view: DataWarehouseSavedQuery) -> None:
+ DataWarehouseSavedQuery.objects.filter(id=view.id).update(incremental_config=STORED_DAY_KEY)
+
+
+def add_an_upstream_view_over_postgres(view: DataWarehouseSavedQuery) -> list[str]:
+ node = Node.objects.get(saved_query=view)
+ source = ExternalDataSource.objects.create(
+ team=view.team,
+ source_id="postgres",
+ connection_id="postgres",
+ status="Completed",
+ source_type=ExternalDataSourceType.POSTGRES,
+ )
+ postgres_table = DataWarehouseTable.objects.create(
+ team=view.team, name="postgres_orders", format="Parquet", external_data_source=source
+ )
+ upstream_view = DataWarehouseSavedQuery.objects.create(
+ team=view.team, name="orders_source", query={"kind": "HogQLQuery", "query": UPSTREAM_SQL}
+ )
+ upstream_node = Node.objects.create(
+ team=view.team, dag=node.dag, name="orders_source", saved_query=upstream_view, type=NodeType.VIEW
+ )
+ table_node = Node.objects.create(
+ team=view.team,
+ dag=node.dag,
+ name="postgres_orders",
+ type=NodeType.TABLE,
+ properties={"warehouse_table_id": str(postgres_table.id)},
+ )
+ Edge.objects.create(team=view.team, dag=node.dag, source=table_node, target=upstream_node)
+ Edge.objects.create(team=view.team, dag=node.dag, source=upstream_node, target=node)
+ return [ORDERS_SQL, UPSTREAM_SQL]
+
+
+def make_the_postgres_source_direct(view: DataWarehouseSavedQuery) -> None:
+ ExternalDataSource.objects.filter(team=view.team, source_id="postgres").update(
+ access_method=ExternalDataSource.AccessMethod.DIRECT
+ )
+
+
+def change_the_upstream_query(view: DataWarehouseSavedQuery) -> None:
+ DataWarehouseSavedQuery.objects.filter(team=view.team, name="orders_source").update(
+ query={"kind": "HogQLQuery", "query": "SELECT * FROM postgres_orders WHERE 1 = 1"}
+ )
+
+
+def _restrict_table(view: DataWarehouseSavedQuery, table_name: str) -> None:
+ view.team.organization.available_product_features = [
+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL}
+ ]
+ view.team.organization.save()
+ table = DataWarehouseTable.objects.get(team=view.team, name=table_name)
+ create_access_control(
+ team_id=view.team_id, resource="warehouse_table", resource_id=str(table.id), access_level="none"
+ )
+
+
+def restrict_the_postgres_table(view: DataWarehouseSavedQuery) -> None:
+ _restrict_table(view, "postgres_orders")
+
+
+def restrict_an_unrelated_table(view: DataWarehouseSavedQuery) -> None:
+ DataWarehouseTable.objects.create(team=view.team, name="unrelated", format="Parquet")
+ _restrict_table(view, "unrelated")
+
+
+def read_a_system_table(view: DataWarehouseSavedQuery) -> None:
+ node = Node.objects.get(saved_query=view)
+ system_node = Node.objects.create(
+ team=view.team,
+ dag=node.dag,
+ name="system.feature_flags",
+ type=NodeType.TABLE,
+ properties={"origin": "posthog"},
+ )
+ Edge.objects.create(team=view.team, dag=node.dag, source=system_node, target=node)
+
+
+def change_query(view: DataWarehouseSavedQuery) -> None:
+ DataWarehouseSavedQuery.objects.filter(id=view.id).update(
+ query={"kind": "HogQLQuery", "query": "SELECT timestamp, event, properties FROM events"}
+ )
+
+
def add_destination(view: DataWarehouseSavedQuery) -> None:
HogFunction.objects.create(
team=view.team,
@@ -315,6 +416,77 @@ class TestAcceptSuggestion(APIBaseTest):
assert retried["created_asset"]["stopped_materialization"] is True, retried
assert (node.type, get_declared_target(node)) == (NodeType.VIEW, None)
+ @parameterized.expand(
+ [
+ ("stops_refreshes", None, None, status.HTTP_200_OK),
+ ("stops_refreshes_with_an_upstream_view", add_an_upstream_view_over_postgres, None, status.HTTP_200_OK),
+ ("a_view_was_built_on_it_since", None, add_dependent_view, status.HTTP_409_CONFLICT),
+ ("it_refreshes_incrementally_since", None, switch_to_incremental, status.HTTP_409_CONFLICT),
+ ("its_query_changed_since", None, change_query, status.HTTP_409_CONFLICT),
+ (
+ "an_upstream_query_changed_since",
+ add_an_upstream_view_over_postgres,
+ change_the_upstream_query,
+ status.HTTP_409_CONFLICT,
+ ),
+ (
+ "an_upstream_view_reads_a_direct_source_since",
+ add_an_upstream_view_over_postgres,
+ make_the_postgres_source_direct,
+ status.HTTP_409_CONFLICT,
+ ),
+ (
+ "an_upstream_table_was_restricted_since",
+ add_an_upstream_view_over_postgres,
+ restrict_the_postgres_table,
+ status.HTTP_409_CONFLICT,
+ ),
+ (
+ "stops_refreshes_when_only_an_unrelated_table_is_restricted",
+ add_an_upstream_view_over_postgres,
+ restrict_an_unrelated_table,
+ status.HTTP_200_OK,
+ ),
+ ("it_reads_a_system_table_since", None, read_a_system_table, status.HTTP_409_CONFLICT),
+ ]
+ )
+ def test_accepting_an_unmaterialize_suggestion_turns_the_view_back_into_a_plain_view(
+ self,
+ _name: str,
+ build_before: Callable[[DataWarehouseSavedQuery], list[str]] | None,
+ change_since: Callable[[DataWarehouseSavedQuery], None] | None,
+ expected_status: int,
+ ) -> None:
+ table = materialize_in_place(self.view)
+ queries = build_before(self.view) if build_before is not None else [ORDERS_SQL]
+ payload = replace(UNMATERIALIZE_PAYLOAD, query_fingerprint=definition_fingerprint(queries))
+ draft = make_draft(fingerprint="unmaterialize:orders", subject_id=self.view.id)
+ suggestion = ingest_surfaced(
+ self.team.id, replace(draft, kind=WarehouseSuggestionKind.UNMATERIALIZE, payload=payload)
+ )
+ if change_since is not None:
+ change_since(self.view)
+
+ with patch(REPORT) as report:
+ accepted = self._accept(suggestion.id)
+
+ table.refresh_from_db()
+ suggestion.refresh_from_db()
+ stopped = expected_status == status.HTTP_200_OK
+ assert accepted["http_status"] == expected_status, accepted
+ assert (
+ Node.objects.get(team=self.team, saved_query=self.view).type,
+ bool(table.deleted),
+ suggestion.status,
+ ) == (
+ (NodeType.VIEW, True, WarehouseSuggestionStatus.ACCEPTED)
+ if stopped
+ else (NodeType.MAT_VIEW, False, WarehouseSuggestionStatus.PROPOSED)
+ )
+ if stopped:
+ assert accepted["created_asset"] == {"saved_query_id": str(self.view.id)}
+ assert report.call_args.args[1]["refresh_seconds_per_month"] == 3600
+
def test_accepting_a_materialize_suggestion_materializes_the_view_on_the_chosen_interval(self) -> None:
suggestion = self._suggest(WarehouseSuggestionKind.MATERIALIZE)
diff --git a/products/warehouse_suggestions/backend/tests/test_api.py b/products/warehouse_suggestions/backend/tests/test_api.py
index f9b74f60ac23..aceb10f24cc9 100644
--- a/products/warehouse_suggestions/backend/tests/test_api.py
+++ b/products/warehouse_suggestions/backend/tests/test_api.py
@@ -25,6 +25,7 @@ from products.warehouse_suggestions.backend.facade.contracts import (
MaterializePayload,
SourceRef,
SuggestionDraft,
+ UnmaterializePayload,
)
from products.warehouse_suggestions.backend.facade.enums import (
WarehouseSuggestionDismissalReason,
@@ -131,11 +132,30 @@ 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)
+ unmaterialize = ingest_surfaced(
+ self.team.id,
+ replace(
+ make_draft(fingerprint="unmaterialize:orders", subject_id=self.view.id, score=5.0),
+ kind=WarehouseSuggestionKind.UNMATERIALIZE,
+ payload=UnmaterializePayload(
+ subject_name="orders",
+ refresh_seconds_per_month=3600.0,
+ refresh_bytes_per_month=0.0,
+ live_seconds_per_month=20.0,
+ live_bytes_per_month=0.0,
+ read_seconds=5.0,
+ query_fingerprint="fingerprint",
+ ),
+ ),
+ )
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()
- assert [row["id"] for row in listed.json()["results"]] == [str(high.id), str(low.id)]
+ rows = {row["id"]: row for row in listed.json()["results"]}
+ assert [row_id for row_id in rows if row_id != str(unmaterialize.id)] == [str(high.id), str(low.id)]
+ assert rows[str(unmaterialize.id)]["payload"]["read_seconds"] == 5.0
+ assert "query_fingerprint" not in rows[str(unmaterialize.id)]["payload"]
assert all(row["can_act"] for row in listed.json()["results"])
dismissed = self.client.post(
diff --git a/products/warehouse_suggestions/backend/tests/test_candidates.py b/products/warehouse_suggestions/backend/tests/test_candidates.py
index a5dac5993129..85b1d231ceed 100644
--- a/products/warehouse_suggestions/backend/tests/test_candidates.py
+++ b/products/warehouse_suggestions/backend/tests/test_candidates.py
@@ -1,5 +1,6 @@
from dataclasses import replace
from datetime import timedelta
+from typing import Any
from uuid import uuid4
from posthog.test.base import BaseTest
@@ -9,14 +10,27 @@ from django.test import SimpleTestCase
from parameterized import parameterized
+from posthog.models.activity_logging.activity_log import ActivityLog, Change, Detail, log_activity
+
from products.data_catalog.backend.facade.enums import CertificationStatus
-from products.data_modeling.backend.facade.models import DAG, DataWarehouseSavedQuery, Node, NodeType
-from products.warehouse_suggestions.backend.facade.contracts import CertifyPayload, MaterializePayload
+from products.data_modeling.backend.facade.models import DAG, DataModelingJob, DataWarehouseSavedQuery, Node, NodeType
+from products.warehouse_suggestions.backend.facade.contracts import (
+ CertifyPayload,
+ MaterializePayload,
+ UnmaterializePayload,
+)
from products.warehouse_suggestions.backend.facade.enums import (
WarehouseSuggestionAssetOutcome,
+ WarehouseSuggestionKind,
WarehouseSuggestionRefreshIntervalBasis,
WarehouseSuggestionRefreshMode,
)
+from products.warehouse_suggestions.backend.logic.candidates.base import (
+ DEPENDENTS_REJECTION,
+ FEEDS_CONSUMERS_REJECTION,
+ READER_ACCESS_REJECTION,
+ CandidateContext,
+)
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 (
@@ -26,11 +40,13 @@ from products.warehouse_suggestions.backend.logic.candidates.materialize import
interval_basis,
refresh_cost,
)
-from products.warehouse_suggestions.backend.logic.reads import SubjectRefreshes
+from products.warehouse_suggestions.backend.logic.candidates.unmaterialize import UnmaterializeCandidate
+from products.warehouse_suggestions.backend.logic.reads import RefreshRun, SubjectRefreshes
from products.warehouse_suggestions.backend.logic.rules import RULES, Surface
from products.warehouse_suggestions.backend.tests.factories import (
busy_reads,
context,
+ days_ago,
table_subject,
team_reads,
view,
@@ -331,5 +347,227 @@ class TestDeprecateBackgroundReads(BaseTest):
assert (result.drafts, [rejection.reason for rejection in result.rejections]) == (
(),
- ["its refreshes feed person or account properties, a destination or a workflow"],
+ [FEEDS_CONSUMERS_REJECTION],
+ )
+
+
+HOURLY_RUNS = 720
+FIVE_SECONDS_MS = 5_000
+TWENTY_SECONDS_MS = 20_000
+RARE_READS = {"human_requests": 4, "human_reads": 4, "background_reads": 0}
+UNMATERIALIZE_MODULE = "products.warehouse_suggestions.backend.logic.candidates.unmaterialize"
+
+
+def hourly_runs(
+ count: int = HOURLY_RUNS, *, duration_ms: int = FIVE_SECONDS_MS, prefix: str = "run"
+) -> tuple[RefreshRun, ...]:
+ return tuple(
+ RefreshRun(workflow_id=f"{prefix}-{index}", duration_ms=duration_ms, read_bytes=10**6) for index in range(count)
+ )
+
+
+def unmaterialize_context(
+ team_id: int,
+ *,
+ view_overrides: dict | None = None,
+ read_overrides: dict | None = None,
+ runs: tuple[RefreshRun, ...] | None = None,
+ recent_accepts: dict | None = None,
+) -> CandidateContext:
+ subject = view_subject(VIEW_ID)
+ return context(
+ team_reads(
+ {subject: busy_reads(**{**RARE_READS, **(read_overrides or {})})},
+ refresh_runs={VIEW_ID: hourly_runs() if runs is None else runs},
+ ),
+ views=[view(VIEW_ID, materializes=True, **(view_overrides or {}))],
+ team_id=team_id,
+ recent_accepts=recent_accepts,
+ )
+
+
+class TestUnmaterializeCandidate(BaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.saved_query = DataWarehouseSavedQuery.objects.create(
+ id=VIEW_ID, team=self.team, name="orders", query={"kind": "HogQLQuery", "query": "SELECT 1"}
+ )
+
+ def _record_jobs(self, runs: tuple[RefreshRun, ...], **job_fields: Any) -> None:
+ DataModelingJob.objects.bulk_create(
+ DataModelingJob(
+ team=self.team,
+ saved_query=self.saved_query,
+ workflow_id=run.workflow_id,
+ status=job_fields.get("status", DataModelingJob.Status.COMPLETED),
+ run_mode=job_fields.get("run_mode", DataModelingJob.RunMode.FULL_REFRESH),
+ engine=job_fields.get("engine", DataModelingJob.Engine.CLICKHOUSE),
+ )
+ for run in runs
+ )
+ if "created_at" in job_fields:
+ DataModelingJob.objects.filter(workflow_id__in=[run.workflow_id for run in runs]).update(
+ created_at=job_fields["created_at"]
+ )
+
+ def _log_query_change(self, at: Any) -> None:
+ with self.captureOnCommitCallbacks(execute=True):
+ log_activity(
+ organization_id=self.organization.id,
+ team_id=self.team.pk,
+ user=self.user,
+ was_impersonated=False,
+ item_id=VIEW_ID,
+ scope="DataWarehouseSavedQuery",
+ activity="updated",
+ detail=Detail(
+ name="orders",
+ changes=[
+ Change(type="DataWarehouseSavedQuery", action="changed", field="query", before="a", after="b")
+ ],
+ ),
+ )
+ ActivityLog.objects.filter(item_id=str(VIEW_ID)).update(created_at=at)
+
+ def test_proposes_a_rarely_read_view_with_refresh_cost_against_live_cost(self) -> None:
+ self._record_jobs(hourly_runs())
+
+ result = UnmaterializeCandidate().evaluate(unmaterialize_context(self.team.pk))
+
+ [draft] = result.drafts
+ assert isinstance(draft.payload, UnmaterializePayload)
+ assert replace(draft.payload, query_fingerprint="") == UnmaterializePayload(
+ subject_name="orders",
+ refresh_seconds_per_month=3600.0,
+ refresh_bytes_per_month=720.0 * 10**6,
+ live_seconds_per_month=20.0,
+ live_bytes_per_month=4.0 * 10**6,
+ read_seconds=5.0,
+ query_fingerprint="",
+ )
+
+ @parameterized.expand(
+ [
+ ("few_runs", {}, {}, hourly_runs(2), None, "has 2 completed full refreshes"),
+ ("incremental", {"refreshes_incrementally": True}, {}, None, None, "refreshes incrementally"),
+ (
+ "calls_a_decision_function",
+ {"calls_decision_functions": True},
+ {},
+ None,
+ None,
+ "calls jev() or decide()",
+ ),
+ (
+ "materialized_on_a_recent_suggestion",
+ {},
+ {},
+ None,
+ {WarehouseSuggestionKind.MATERIALIZE: frozenset({VIEW_ID})},
+ "was materialized on a suggestion",
+ ),
+ ("read_too_often", {}, {"human_reads": 600}, None, None, "would not save enough"),
+ ("background_reads_count", {}, {"background_reads": 600}, None, None, "would not save enough"),
+ (
+ "slow_tail",
+ {},
+ {},
+ hourly_runs(duration_ms=TWENTY_SECONDS_MS),
+ None,
+ "a read could take 20 seconds",
+ ),
+ ]
+ )
+ def test_rejects_a_view_that_would_cost_more_or_read_slowly_when_computed_on_read(
+ self,
+ _name: str,
+ view_overrides: dict,
+ read_overrides: dict,
+ runs: tuple[RefreshRun, ...] | None,
+ recent_accepts: dict | None,
+ expected_reason: str,
+ ) -> None:
+ self._record_jobs(runs or hourly_runs())
+ candidate_context = unmaterialize_context(
+ self.team.pk,
+ view_overrides=view_overrides,
+ read_overrides=read_overrides,
+ runs=runs,
+ recent_accepts=recent_accepts,
+ )
+
+ result = UnmaterializeCandidate().evaluate(candidate_context)
+
+ [rejection] = result.rejections
+ assert (result.drafts, expected_reason in rejection.reason) == ((), True), rejection.reason
+
+ @parameterized.expand(
+ [
+ ("failed", {"status": DataModelingJob.Status.FAILED}, False),
+ ("incremental", {"run_mode": DataModelingJob.RunMode.INCREMENTAL}, False),
+ ("another_engine", {"engine": DataModelingJob.Engine.LEGACY_DUCKGRES}, False),
+ ("before_the_query_changed", {"created_at": days_ago(10)}, True),
+ ]
+ )
+ def test_prices_only_completed_full_refreshes_of_the_current_query(
+ self, _name: str, fast_job_fields: dict, query_changed: bool
+ ) -> None:
+ slow = hourly_runs(10, duration_ms=TWENTY_SECONDS_MS, prefix="slow")
+ fast = hourly_runs(HOURLY_RUNS - 10, prefix="fast")
+ self._record_jobs(slow)
+ self._record_jobs(fast, **fast_job_fields)
+ if query_changed:
+ self._log_query_change(days_ago(5))
+
+ result = UnmaterializeCandidate().evaluate(unmaterialize_context(self.team.pk, runs=slow + fast))
+
+ assert (result.drafts, [rejection.reason for rejection in result.rejections]) == (
+ (),
+ ["a read could take 20 seconds, over 10"],
+ )
+
+ @parameterized.expand(
+ [
+ ("has_dependents", "dependent_saved_query_ids", {VIEW_ID: frozenset({uuid4()})}, DEPENDENTS_REJECTION),
+ (
+ "feeds_a_consumer",
+ "saved_queries_feeding_consumers",
+ frozenset({VIEW_ID}),
+ FEEDS_CONSUMERS_REJECTION,
+ ),
+ ("readers_could_lose_access", "inlining_could_deny_a_reader", True, READER_ACCESS_REJECTION),
+ ]
+ )
+ def test_rejects_a_view_others_rely_on(self, _name: str, lookup: str, found: object, expected_reason: str) -> None:
+ self._record_jobs(hourly_runs())
+ with patch(f"{UNMATERIALIZE_MODULE}.{lookup}", return_value=found):
+ result = UnmaterializeCandidate().evaluate(unmaterialize_context(self.team.pk))
+
+ assert (result.drafts, [rejection.reason for rejection in result.rejections]) == ((), [expected_reason])
+
+ def test_leaves_an_unread_view_to_deprecate(self) -> None:
+ candidate_context = context(
+ team_reads({}, refresh_runs={VIEW_ID: hourly_runs()}),
+ views=[view(VIEW_ID, materializes=True)],
+ team_id=self.team.pk,
+ )
+
+ result = UnmaterializeCandidate().evaluate(candidate_context)
+
+ assert (result.drafts, result.rejections) == ((), ())
+
+
+class TestMaterializeAfterUnmaterialize(SimpleTestCase):
+ def test_a_view_unmaterialized_on_a_recent_suggestion_is_not_proposed_again(self) -> None:
+ candidate_context = context(
+ team_reads({view_subject(VIEW_ID): busy_reads()}),
+ views=[view(VIEW_ID)],
+ recent_accepts={WarehouseSuggestionKind.UNMATERIALIZE: frozenset({VIEW_ID})},
+ )
+
+ result = MaterializeCandidate().evaluate(candidate_context)
+
+ assert (result.drafts, [rejection.reason for rejection in result.rejections]) == (
+ (),
+ ["was unmaterialized on a suggestion in the last 30 days"],
)
diff --git a/products/warehouse_suggestions/backend/tests/test_job.py b/products/warehouse_suggestions/backend/tests/test_job.py
index b97d54b26f57..e87f2d86f924 100644
--- a/products/warehouse_suggestions/backend/tests/test_job.py
+++ b/products/warehouse_suggestions/backend/tests/test_job.py
@@ -1,3 +1,4 @@
+from dataclasses import replace
from datetime import UTC, date, datetime, time, timedelta
from uuid import uuid4
@@ -11,10 +12,11 @@ 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.job import TeamRunStatus, build_context, 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.factories import team_reads
from products.warehouse_suggestions.backend.tests.rollup import RollupRead, seed_reads
from products.warehouse_suggestions.backend.tests.test_suggestions import ingest_one, make_draft
@@ -149,3 +151,23 @@ class TestRunTeam(ClickhouseTestMixin, BaseTest):
about_a_deleted_view.status,
about_a_deleted_view.asset_outcome,
) == (TeamRunStatus.NOT_ELIGIBLE, False, True, expected_status, expected_asset_outcome)
+
+
+class TestFlipCooldown(BaseTest):
+ def test_only_accepts_inside_the_cooldown_hold_off_the_opposite_kind(self) -> None:
+ recent, old = uuid4(), uuid4()
+ for subject_id, days_ago in [(recent, 10), (old, 40)]:
+ row = ingest_one(
+ self.team.pk,
+ replace(
+ make_draft(fingerprint=f"materialize:{subject_id}", subject_id=subject_id),
+ kind=WarehouseSuggestionKind.MATERIALIZE,
+ ),
+ )
+ WarehouseSuggestion.objects.for_team(self.team.pk).filter(id=row.id).update(
+ status=WarehouseSuggestionStatus.ACCEPTED, reviewed_at=NOW - timedelta(days=days_ago)
+ )
+
+ candidate_context = build_context(self.team, team_reads({}), run_id="run-1", rules=RULES, now=NOW)
+
+ assert candidate_context.recent_accepts == {WarehouseSuggestionKind.MATERIALIZE: frozenset({recent})}
diff --git a/products/warehouse_suggestions/backend/tests/test_lifecycle.py b/products/warehouse_suggestions/backend/tests/test_lifecycle.py
index 0816aaacab2b..3e9c0cdb7798 100644
--- a/products/warehouse_suggestions/backend/tests/test_lifecycle.py
+++ b/products/warehouse_suggestions/backend/tests/test_lifecycle.py
@@ -15,6 +15,7 @@ from products.warehouse_suggestions.backend.facade.contracts import (
MaterializePayload,
SuggestionDraft,
SuggestionPayload,
+ UnmaterializePayload,
)
from products.warehouse_suggestions.backend.facade.enums import (
WarehouseSuggestionAssetOutcome,
@@ -47,6 +48,15 @@ PAYLOADS: dict[WarehouseSuggestionKind, SuggestionPayload] = {
live_sources=(),
unknown_sources=(),
),
+ WarehouseSuggestionKind.UNMATERIALIZE: UnmaterializePayload(
+ subject_name="orders",
+ refresh_seconds_per_month=3600,
+ refresh_bytes_per_month=0,
+ live_seconds_per_month=20,
+ live_bytes_per_month=0,
+ read_seconds=5,
+ query_fingerprint="fingerprint",
+ ),
}
@@ -174,6 +184,41 @@ class TestApplyRun(BaseTest):
assert WarehouseSuggestion.objects.for_team(self.team.pk).get().status == expected
+ @parameterized.expand(
+ [
+ ("unmaterialized_by_a_suggestion", 60, True, WarehouseSuggestionStatus.PROPOSED, 1),
+ ("stopped_by_a_deprecate_or_a_manual_revert", 60, False, WarehouseSuggestionStatus.PROPOSED, 1),
+ ("accepted_inside_the_cooldown", 10, False, WarehouseSuggestionStatus.ACCEPTED, 0),
+ ]
+ )
+ def test_an_accepted_materialize_returns_when_drafted_again_after_the_cooldown(
+ self,
+ _name: str,
+ accepted_days_ago: int,
+ unmaterialized_by_a_suggestion: bool,
+ expected_status: WarehouseSuggestionStatus,
+ reproposed: int,
+ ) -> None:
+ view_id = uuid4()
+ ctx = self._context(view_id)
+ materialize = self._draft(ctx, WarehouseSuggestionKind.MATERIALIZE, view_id, 1)
+ first_run = [materialize]
+ if unmaterialized_by_a_suggestion:
+ first_run.append(self._draft(ctx, WarehouseSuggestionKind.UNMATERIALIZE, view_id, 1))
+ apply_run(ctx, self.team, first_run, NOW - timedelta(days=accepted_days_ago), surface=True)
+ suggestions = WarehouseSuggestion.objects.for_team(self.team.pk)
+ suggestions.filter(kind=WarehouseSuggestionKind.MATERIALIZE).update(
+ status=WarehouseSuggestionStatus.ACCEPTED, reviewed_at=NOW - timedelta(days=accepted_days_ago)
+ )
+ suggestions.filter(kind=WarehouseSuggestionKind.UNMATERIALIZE).update(
+ status=WarehouseSuggestionStatus.ACCEPTED, reviewed_at=NOW - timedelta(days=40)
+ )
+
+ apply_run(ctx, self.team, [materialize], NOW, surface=False)
+
+ row = suggestions.get(kind=WarehouseSuggestionKind.MATERIALIZE)
+ assert (row.status, row.reproposed_count) == (expected_status, reproposed)
+
@parameterized.expand(
[("expired", WarehouseSuggestionStatus.EXPIRED), ("auto_resolved", WarehouseSuggestionStatus.AUTO_RESOLVED)]
)
diff --git a/products/warehouse_suggestions/backend/tests/test_reads.py b/products/warehouse_suggestions/backend/tests/test_reads.py
index 0495e29afc9d..43244e35e196 100644
--- a/products/warehouse_suggestions/backend/tests/test_reads.py
+++ b/products/warehouse_suggestions/backend/tests/test_reads.py
@@ -5,7 +5,7 @@ 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 posthog.clickhouse.warehouse_object_reads import TRUNCATE_WAREHOUSE_OBJECT_READS_DAILY_TABLES_SQL, ReadKind
from products.warehouse_suggestions.backend.facade.enums import WarehouseSuggestionSubjectKind
from products.warehouse_suggestions.backend.logic.reads import (
@@ -69,8 +69,9 @@ class TestReadTeamReads(ClickhouseTestMixin, BaseTest):
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:
+ def test_counts_reads_people_days_costs_and_refreshes_inside_the_window(self) -> None:
view = uuid4()
+ unread_view = uuid4()
seed_reads(
self.team.pk + 1, [RollupRead(subject_id=uuid4(), day=TODAY - timedelta(days=3), request_id="other")]
)
@@ -82,6 +83,42 @@ class TestReadTeamReads(ClickhouseTestMixin, BaseTest):
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=view, day=YESTERDAY, request_id="warmup", user_id=0),
+ RollupRead(
+ subject_id=view,
+ day=YESTERDAY,
+ request_id="refresh-1",
+ read_kind=ReadKind.REFRESH,
+ workflow_id="run-1",
+ duration_ms=1000,
+ ),
+ RollupRead(
+ subject_id=view,
+ day=YESTERDAY,
+ request_id="refresh-2",
+ read_kind=ReadKind.REFRESH,
+ workflow_id="run-2",
+ duration_ms=3000,
+ ),
+ *(
+ RollupRead(
+ subject_id=view,
+ day=YESTERDAY,
+ request_id=f"refresh-2-describe-{statement}",
+ read_kind=ReadKind.REFRESH,
+ workflow_id="run-2",
+ duration_ms=10,
+ )
+ for statement in range(9)
+ ),
+ RollupRead(
+ subject_id=unread_view,
+ day=YESTERDAY,
+ request_id="unread-refresh",
+ read_kind=ReadKind.REFRESH,
+ workflow_id="unread-run",
+ duration_ms=500,
+ ),
RollupRead(
subject_id=uuid4(),
day=YESTERDAY,
@@ -99,6 +136,11 @@ class TestReadTeamReads(ClickhouseTestMixin, BaseTest):
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.background_reads == 1
+ refreshes = reads.refreshes[view]
+ assert (refreshes.runs, refreshes.duration_ms) == (2, 4090)
+ assert {run.workflow_id: run.duration_ms for run in reads.refresh_runs[view]} == {"run-1": 1000, "run-2": 3090}
+ assert unread_view in reads.refreshes and unread_view not in reads.refresh_runs
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 < view_reads.alone_duration_ms_p90 <= 300
assert view_reads.last_read_at == datetime.combine(YESTERDAY, time(hour=12), tzinfo=UTC)
diff --git a/products/warehouse_suggestions/frontend/generated/api.schemas.ts b/products/warehouse_suggestions/frontend/generated/api.schemas.ts
index 3907131e0b62..5bd3837bb6aa 100644
--- a/products/warehouse_suggestions/frontend/generated/api.schemas.ts
+++ b/products/warehouse_suggestions/frontend/generated/api.schemas.ts
@@ -99,10 +99,26 @@ export interface WarehouseSuggestionMaterializePayloadApi {
lookback_seconds?: number
}
+export interface WarehouseSuggestionUnmaterializePayloadApi {
+ /** Name of the rarely read materialized view to turn back into a plain view. */
+ 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
+ /** Estimated time its reads would take in a month if each read computed the view, in seconds. The estimate uses a full refresh per read, so it leans high. */
+ live_seconds_per_month: number
+ /** Estimated bytes its reads would scan in a month if each read computed the view. */
+ live_bytes_per_month: number
+ /** How long one read would take once the view is computed on read, in seconds. Nine in ten of its refreshes finished within this time. */
+ read_seconds: number
+}
+
export type WarehouseSuggestionPayloadApi =
| WarehouseSuggestionCertifyPayloadApi
| WarehouseSuggestionDeprecatePayloadApi
| WarehouseSuggestionMaterializePayloadApi
+ | WarehouseSuggestionUnmaterializePayloadApi
/**
* Queries people ran per place they ran them, such as sql_editor, dashboard, insight or mcp.
@@ -139,6 +155,7 @@ export interface WarehouseSuggestionReviewerApi {
* * `certify` - Certify
* * `deprecate` - Deprecate
* * `materialize` - Materialize
+ * * `unmaterialize` - Unmaterialize
*/
export type WarehouseSuggestionKindEnumApi =
(typeof WarehouseSuggestionKindEnumApi)[keyof typeof WarehouseSuggestionKindEnumApi]
@@ -147,6 +164,7 @@ export const WarehouseSuggestionKindEnumApi = {
Certify: 'certify',
Deprecate: 'deprecate',
Materialize: 'materialize',
+ Unmaterialize: 'unmaterialize',
} as const
/**
@@ -225,11 +243,12 @@ export interface WarehouseSuggestionApi {
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.
+ /** What the suggestion proposes: certify, deprecate, materialize or unmaterialize the subject. unmaterialize turns a rarely read materialized view back into a plain view computed on read.
*
* * `certify` - Certify
* * `deprecate` - Deprecate
- * * `materialize` - Materialize */
+ * * `materialize` - Materialize
+ * * `unmaterialize` - Unmaterialize */
kind: WarehouseSuggestionKindEnumApi
/** Whether the subject is a saved query (view) or a warehouse table.
*
@@ -364,6 +383,7 @@ export type WarehouseSuggestionsListParams = {
* * `certify` - Certify
* * `deprecate` - Deprecate
* * `materialize` - Materialize
+ * * `unmaterialize` - Unmaterialize
* @minLength 1
*/
kind?: WarehouseSuggestionsListKind
@@ -399,6 +419,7 @@ export const WarehouseSuggestionsListKind = {
Certify: 'certify',
Deprecate: 'deprecate',
Materialize: 'materialize',
+ Unmaterialize: 'unmaterialize',
} as const
export type WarehouseSuggestionsListStatus =
diff --git a/products/warehouse_suggestions/mcp/tools.yaml b/products/warehouse_suggestions/mcp/tools.yaml
index e2e9f7e15f38..46b2ae9f3586 100644
--- a/products/warehouse_suggestions/mcp/tools.yaml
+++ b/products/warehouse_suggestions/mcp/tools.yaml
@@ -26,20 +26,25 @@ tools:
stops its refreshes and deletes its stored table, so the view is computed when read; pass
keep_materialized=true to keep it refreshing. The view stays materialized when other views read from it or
its refreshes feed person properties, a destination or a workflow; `created_asset.stopped_materialization`
- says whether refreshes stopped. Materialize suggestions turn on materialization for the view on the proposed
- schedule, which adds a recurring compute cost; pass refresh_interval_seconds to use another schedule. They
- also apply the payload's refresh_mode: incremental refreshes read only new rows by incremental_key and
- update rows by unique_key, full refreshes rebuild the whole table. The payload is a starting point. To
- change it, pass any of refresh_interval_seconds, refresh_mode, incremental_key, unique_key and
- lookback_seconds; an omitted field keeps the suggested value. Check keys the person chose with
- view-check-incremental first. A 400 names the field the server refused and why. A 409 means the view changed
- since the suggestion was made and its suggested keys no longer apply. Requires human typed confirmation.
+ says whether refreshes stopped. Unmaterialize suggestions turn a rarely read materialized view back into a
+ plain view: its refreshes stop, its stored table is deleted, and each read computes the view, taking about
+ `read_seconds`. A 409 means the view changed since the suggestion was made, for example another view now
+ reads from it or it now refreshes incrementally. Materialize suggestions turn on materialization for the
+ view on the proposed schedule, which adds a recurring compute cost; pass refresh_interval_seconds to use
+ another schedule. They also apply the payload's refresh_mode: incremental refreshes read only new rows by
+ incremental_key and update rows by unique_key, full refreshes rebuild the whole table. The payload is a
+ starting point. To change it, pass any of refresh_interval_seconds, refresh_mode, incremental_key,
+ unique_key and lookback_seconds; an omitted field keeps the suggested value. Check keys the person chose
+ with view-check-incremental first. A 400 names the field the server refused and why. A 409 means the view
+ changed since the suggestion was made and its suggested keys no longer apply. Requires human typed
+ confirmation.
confirmed_action:
message: >
About to accept warehouse suggestion '{id}'. This applies the change it proposes to the view or table.
If it is a materialize suggestion, the view then refreshes on a schedule, which adds a recurring compute
cost. If it is a deprecate suggestion on a materialized view, its refreshes stop and its stored table is
- deleted, unless keep_materialized is true. Reply 'confirm' to proceed.
+ deleted, unless keep_materialized is true. If it is an unmaterialize suggestion, the view's refreshes
+ stop, its stored table is deleted, and each read computes the view instead. Reply 'confirm' to proceed.
action_label: accept warehouse suggestion
warehouse-suggestions-dismiss:
operation: warehouse_suggestions_dismiss_create
@@ -64,21 +69,24 @@ tools:
ran on its own, such as cache warming and alerts. `last_read_at` is the latest read of any kind, background
included. `days_with_data` is how many days of the window PostHog has read history for, not how active this
project is. A field is missing when the subject had no reads. Use these counts and the numbers in `payload`
- to explain to the user why a view or table should be certified, deprecated or materialized before accepting.
+ to explain to the user why a view or table should be certified, deprecated, materialized or unmaterialized
+ before accepting.
warehouse-suggestions-list:
operation: warehouse_suggestions_list
enabled: true
list: true
title: List warehouse suggestions
description: >
- Recommendations to certify, deprecate or materialize data warehouse views and tables, computed daily from
- how often the project reads them. Pass status=proposed for the suggestions still waiting for a decision.
- `payload` says what accepting would create or change. `can_act` says whether the caller can edit the view or
- table, which accept, dismiss and resume require. Accepting a certify or deprecate suggestion also requires
- edit access to the data catalog. Use warehouse-suggestions-get for the usage evidence behind one suggestion.
- If the list is empty, call warehouse-suggestions-status to learn why. Results come in priority order, the
- one most worth acting on first. Explain a suggestion to the user with the numbers in `payload`, the time and
- bytes saved or spent per month. For a certify suggestion, use the read counts in `evidence` from
+ Recommendations to certify, deprecate, materialize or unmaterialize data warehouse views and tables,
+ computed daily from how often the project reads them. Pass status=proposed for the suggestions still waiting
+ for a decision. `payload` says what accepting would create or change. `can_act` says whether the caller can
+ edit the view or table, which accept, dismiss and resume require. Accepting a certify or deprecate
+ suggestion also requires edit access to the data catalog. Use warehouse-suggestions-get for the usage
+ evidence behind one suggestion. If the list is empty, call warehouse-suggestions-status to learn why.
+ Results come in priority order, the one most worth acting on first. Explain a suggestion to the user with
+ the numbers in `payload`, the time and bytes saved or spent per month. For an unmaterialize suggestion,
+ compare refresh_seconds_per_month with live_seconds_per_month and say how long one read would take
+ (`read_seconds`). For a certify suggestion, use the read counts in `evidence` from
warehouse-suggestions-get.
response:
include:
diff --git a/products/warehouse_suggestions/skills/reviewing-warehouse-suggestions/SKILL.md b/products/warehouse_suggestions/skills/reviewing-warehouse-suggestions/SKILL.md
index 10cc5ba5a01e..8d2213a10a99 100644
--- a/products/warehouse_suggestions/skills/reviewing-warehouse-suggestions/SKILL.md
+++ b/products/warehouse_suggestions/skills/reviewing-warehouse-suggestions/SKILL.md
@@ -2,7 +2,7 @@
name: reviewing-warehouse-suggestions
description: >
Reviews PostHog's warehouse suggestions with a person and acts on them.
- Explains why a view should be materialized, certified or deprecated using the numbers in the suggestion,
+ Explains why a view should be materialized, unmaterialized, certified or deprecated using the numbers in the suggestion,
changes a materialize suggestion's refresh mode, keys or interval when the person wants something else,
then accepts or dismisses it.
Use when the user asks what PostHog suggests for their data warehouse, whether to materialize a view,
@@ -35,6 +35,12 @@ Do not invent a score or a confidence level.
- `freshness_today_seconds` and `freshness_after_seconds` say how old the data can be now and after.
- `refresh_interval_seconds` is the proposed interval. `refresh_interval_basis` says what kept it from being shorter: `source_sync` (the sources sync no faster), `fastest_schedule` (PostHog refreshes views no more often), `read_rate` (people read the view no more often) or `savings` (a shorter interval costs more than it saves).
- `refresh_mode` is `incremental` when each refresh can read only new rows, by `incremental_key`, and update rows by `unique_key`. Otherwise it is `full`, and each refresh rebuilds the whole table.
+- **unmaterialize**: this materialized view is read so rarely that refreshing it costs more than computing it on each read.
+ - `refresh_seconds_per_month` and `refresh_bytes_per_month` are what its refreshes cost now.
+ - `live_seconds_per_month` and `live_bytes_per_month` estimate what its reads would cost if each one computed the view. The estimate uses a full refresh per read, so it leans high.
+ - `read_seconds` is how long one read would take afterwards. Nine in ten of its refreshes finished within this time. Tell the user that reads get slower by about this much, and that each read sees current data instead of the last refresh.
+ - Accepting stops the refreshes and deletes the stored table. The view definition stays, so it can be materialized again later.
+ - A 409 on accept means the view changed since the suggestion was made, for example another view now reads from it. Explain the reason to the user and do not retry.
- **certify**: many people read this view or table, from several places. Use the read counts in `evidence`.
- **deprecate**: nobody reads this materialized view, but it still refreshes. `refresh_seconds_per_month` and `refresh_bytes_per_month` are that cost. Accepting marks it deprecated in the data catalog, stops its refreshes and deletes its stored table. The view definition stays, so it can be materialized again later. To keep it refreshing, pass `keep_materialized: true`. After accepting, `created_asset.stopped_materialization` says whether the refreshes stopped: they keep running when other views read from it or its refreshes feed person properties, a destination or a workflow.
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 62d07ad723fe..a0f88512fd4a 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -15854,7 +15854,7 @@
}
},
"warehouse-suggestions-accept-execute": {
- "description": "Step 2 of 2 for accept warehouse suggestion. Verifies the confirmation_hash from -prepare and the literal \"confirm\" string typed by the user, then performs the action. ONLY call this after the user has explicitly typed \"confirm\" in chat. Original action: Accept a proposed warehouse suggestion. Certify and deprecate suggestions mark the view or table as certified or deprecated in the data catalog. Accepting a deprecate suggestion on a materialized view also stops its refreshes and deletes its stored table, so the view is computed when read; pass keep_materialized=true to keep it refreshing. The view stays materialized when other views read from it or its refreshes feed person properties, a destination or a workflow; `created_asset.stopped_materialization` says whether refreshes stopped. Materialize suggestions turn on materialization for the view on the proposed schedule, which adds a recurring compute cost; pass refresh_interval_seconds to use another schedule. They also apply the payload's refresh_mode: incremental refreshes read only new rows by incremental_key and update rows by unique_key, full refreshes rebuild the whole table. The payload is a starting point. To change it, pass any of refresh_interval_seconds, refresh_mode, incremental_key, unique_key and lookback_seconds; an omitted field keeps the suggested value. Check keys the person chose with view-check-incremental first. A 400 names the field the server refused and why. A 409 means the view changed since the suggestion was made and its suggested keys no longer apply. Requires human typed confirmation.",
+ "description": "Step 2 of 2 for accept warehouse suggestion. Verifies the confirmation_hash from -prepare and the literal \"confirm\" string typed by the user, then performs the action. ONLY call this after the user has explicitly typed \"confirm\" in chat. Original action: Accept a proposed warehouse suggestion. Certify and deprecate suggestions mark the view or table as certified or deprecated in the data catalog. Accepting a deprecate suggestion on a materialized view also stops its refreshes and deletes its stored table, so the view is computed when read; pass keep_materialized=true to keep it refreshing. The view stays materialized when other views read from it or its refreshes feed person properties, a destination or a workflow; `created_asset.stopped_materialization` says whether refreshes stopped. Unmaterialize suggestions turn a rarely read materialized view back into a plain view: its refreshes stop, its stored table is deleted, and each read computes the view, taking about `read_seconds`. A 409 means the view changed since the suggestion was made, for example another view now reads from it or it now refreshes incrementally. Materialize suggestions turn on materialization for the view on the proposed schedule, which adds a recurring compute cost; pass refresh_interval_seconds to use another schedule. They also apply the payload's refresh_mode: incremental refreshes read only new rows by incremental_key and update rows by unique_key, full refreshes rebuild the whole table. The payload is a starting point. To change it, pass any of refresh_interval_seconds, refresh_mode, incremental_key, unique_key and lookback_seconds; an omitted field keeps the suggested value. Check keys the person chose with view-check-incremental first. A 400 names the field the server refused and why. A 409 means the view changed since the suggestion was made and its suggested keys no longer apply. Requires human typed confirmation.",
"category": "Warehouse suggestions",
"feature": "warehouse_suggestions",
"summary": "Accept a warehouse suggestion (execute)",
@@ -15870,7 +15870,7 @@
"feature_flag": "warehouse-suggestions"
},
"warehouse-suggestions-accept-prepare": {
- "description": "Step 1 of 2 for accept warehouse suggestion. Validates the arguments and returns a signed confirmation_hash plus a message to surface to the user. The user must reply with the literal word \"confirm\" before you call the matching -execute tool with the hash. Original action: Accept a proposed warehouse suggestion. Certify and deprecate suggestions mark the view or table as certified or deprecated in the data catalog. Accepting a deprecate suggestion on a materialized view also stops its refreshes and deletes its stored table, so the view is computed when read; pass keep_materialized=true to keep it refreshing. The view stays materialized when other views read from it or its refreshes feed person properties, a destination or a workflow; `created_asset.stopped_materialization` says whether refreshes stopped. Materialize suggestions turn on materialization for the view on the proposed schedule, which adds a recurring compute cost; pass refresh_interval_seconds to use another schedule. They also apply the payload's refresh_mode: incremental refreshes read only new rows by incremental_key and update rows by unique_key, full refreshes rebuild the whole table. The payload is a starting point. To change it, pass any of refresh_interval_seconds, refresh_mode, incremental_key, unique_key and lookback_seconds; an omitted field keeps the suggested value. Check keys the person chose with view-check-incremental first. A 400 names the field the server refused and why. A 409 means the view changed since the suggestion was made and its suggested keys no longer apply. Requires human typed confirmation.",
+ "description": "Step 1 of 2 for accept warehouse suggestion. Validates the arguments and returns a signed confirmation_hash plus a message to surface to the user. The user must reply with the literal word \"confirm\" before you call the matching -execute tool with the hash. Original action: Accept a proposed warehouse suggestion. Certify and deprecate suggestions mark the view or table as certified or deprecated in the data catalog. Accepting a deprecate suggestion on a materialized view also stops its refreshes and deletes its stored table, so the view is computed when read; pass keep_materialized=true to keep it refreshing. The view stays materialized when other views read from it or its refreshes feed person properties, a destination or a workflow; `created_asset.stopped_materialization` says whether refreshes stopped. Unmaterialize suggestions turn a rarely read materialized view back into a plain view: its refreshes stop, its stored table is deleted, and each read computes the view, taking about `read_seconds`. A 409 means the view changed since the suggestion was made, for example another view now reads from it or it now refreshes incrementally. Materialize suggestions turn on materialization for the view on the proposed schedule, which adds a recurring compute cost; pass refresh_interval_seconds to use another schedule. They also apply the payload's refresh_mode: incremental refreshes read only new rows by incremental_key and update rows by unique_key, full refreshes rebuild the whole table. The payload is a starting point. To change it, pass any of refresh_interval_seconds, refresh_mode, incremental_key, unique_key and lookback_seconds; an omitted field keeps the suggested value. Check keys the person chose with view-check-incremental first. A 400 names the field the server refused and why. A 409 means the view changed since the suggestion was made and its suggested keys no longer apply. Requires human typed confirmation.",
"category": "Warehouse suggestions",
"feature": "warehouse_suggestions",
"summary": "Accept a warehouse suggestion (prepare)",
@@ -15901,7 +15901,7 @@
"feature_flag": "warehouse-suggestions"
},
"warehouse-suggestions-get": {
- "description": "Get one warehouse suggestion by id, with the `evidence` behind it. Evidence counts reads between `evidence_window_start` and `evidence_window_end`. `human_requests` is the queries people ran on the view or table, `human_users` the distinct people, `human_days` the days with such reads, and `requests_by_surface` those queries per place, such as sql_editor, dashboard or mcp. `background_requests` is the queries PostHog ran on its own, such as cache warming and alerts. `last_read_at` is the latest read of any kind, background included. `days_with_data` is how many days of the window PostHog has read history for, not how active this project is. A field is missing when the subject had no reads. Use these counts and the numbers in `payload` to explain to the user why a view or table should be certified, deprecated or materialized before accepting.",
+ "description": "Get one warehouse suggestion by id, with the `evidence` behind it. Evidence counts reads between `evidence_window_start` and `evidence_window_end`. `human_requests` is the queries people ran on the view or table, `human_users` the distinct people, `human_days` the days with such reads, and `requests_by_surface` those queries per place, such as sql_editor, dashboard or mcp. `background_requests` is the queries PostHog ran on its own, such as cache warming and alerts. `last_read_at` is the latest read of any kind, background included. `days_with_data` is how many days of the window PostHog has read history for, not how active this project is. A field is missing when the subject had no reads. Use these counts and the numbers in `payload` to explain to the user why a view or table should be certified, deprecated, materialized or unmaterialized before accepting.",
"category": "Warehouse suggestions",
"feature": "warehouse_suggestions",
"summary": "Get a warehouse suggestion",
@@ -15917,7 +15917,7 @@
"feature_flag": "warehouse-suggestions"
},
"warehouse-suggestions-list": {
- "description": "Recommendations to certify, deprecate or materialize data warehouse views and tables, computed daily from how often the project reads them. Pass status=proposed for the suggestions still waiting for a decision. `payload` says what accepting would create or change. `can_act` says whether the caller can edit the view or table, which accept, dismiss and resume require. Accepting a certify or deprecate suggestion also requires edit access to the data catalog. Use warehouse-suggestions-get for the usage evidence behind one suggestion. If the list is empty, call warehouse-suggestions-status to learn why. Results come in priority order, the one most worth acting on first. Explain a suggestion to the user with the numbers in `payload`, the time and bytes saved or spent per month. For a certify suggestion, use the read counts in `evidence` from warehouse-suggestions-get.",
+ "description": "Recommendations to certify, deprecate, materialize or unmaterialize data warehouse views and tables, computed daily from how often the project reads them. Pass status=proposed for the suggestions still waiting for a decision. `payload` says what accepting would create or change. `can_act` says whether the caller can edit the view or table, which accept, dismiss and resume require. Accepting a certify or deprecate suggestion also requires edit access to the data catalog. Use warehouse-suggestions-get for the usage evidence behind one suggestion. If the list is empty, call warehouse-suggestions-status to learn why. Results come in priority order, the one most worth acting on first. Explain a suggestion to the user with the numbers in `payload`, the time and bytes saved or spent per month. For an unmaterialize suggestion, compare refresh_seconds_per_month with live_seconds_per_month and say how long one read would take (`read_seconds`). For a certify suggestion, use the read counts in `evidence` from warehouse-suggestions-get.",
"category": "Warehouse suggestions",
"feature": "warehouse_suggestions",
"summary": "List warehouse suggestions",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index e43702b29c29..22fa442f08e2 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -16600,7 +16600,7 @@
}
},
"warehouse-suggestions-accept-execute": {
- "description": "Step 2 of 2 for accept warehouse suggestion. Verifies the confirmation_hash from -prepare and the literal \"confirm\" string typed by the user, then performs the action. ONLY call this after the user has explicitly typed \"confirm\" in chat. Original action: Accept a proposed warehouse suggestion. Certify and deprecate suggestions mark the view or table as certified or deprecated in the data catalog. Accepting a deprecate suggestion on a materialized view also stops its refreshes and deletes its stored table, so the view is computed when read; pass keep_materialized=true to keep it refreshing. The view stays materialized when other views read from it or its refreshes feed person properties, a destination or a workflow; `created_asset.stopped_materialization` says whether refreshes stopped. Materialize suggestions turn on materialization for the view on the proposed schedule, which adds a recurring compute cost; pass refresh_interval_seconds to use another schedule. They also apply the payload's refresh_mode: incremental refreshes read only new rows by incremental_key and update rows by unique_key, full refreshes rebuild the whole table. The payload is a starting point. To change it, pass any of refresh_interval_seconds, refresh_mode, incremental_key, unique_key and lookback_seconds; an omitted field keeps the suggested value. Check keys the person chose with view-check-incremental first. A 400 names the field the server refused and why. A 409 means the view changed since the suggestion was made and its suggested keys no longer apply. Requires human typed confirmation.",
+ "description": "Step 2 of 2 for accept warehouse suggestion. Verifies the confirmation_hash from -prepare and the literal \"confirm\" string typed by the user, then performs the action. ONLY call this after the user has explicitly typed \"confirm\" in chat. Original action: Accept a proposed warehouse suggestion. Certify and deprecate suggestions mark the view or table as certified or deprecated in the data catalog. Accepting a deprecate suggestion on a materialized view also stops its refreshes and deletes its stored table, so the view is computed when read; pass keep_materialized=true to keep it refreshing. The view stays materialized when other views read from it or its refreshes feed person properties, a destination or a workflow; `created_asset.stopped_materialization` says whether refreshes stopped. Unmaterialize suggestions turn a rarely read materialized view back into a plain view: its refreshes stop, its stored table is deleted, and each read computes the view, taking about `read_seconds`. A 409 means the view changed since the suggestion was made, for example another view now reads from it or it now refreshes incrementally. Materialize suggestions turn on materialization for the view on the proposed schedule, which adds a recurring compute cost; pass refresh_interval_seconds to use another schedule. They also apply the payload's refresh_mode: incremental refreshes read only new rows by incremental_key and update rows by unique_key, full refreshes rebuild the whole table. The payload is a starting point. To change it, pass any of refresh_interval_seconds, refresh_mode, incremental_key, unique_key and lookback_seconds; an omitted field keeps the suggested value. Check keys the person chose with view-check-incremental first. A 400 names the field the server refused and why. A 409 means the view changed since the suggestion was made and its suggested keys no longer apply. Requires human typed confirmation.",
"category": "Warehouse suggestions",
"feature": "warehouse_suggestions",
"summary": "Accept a warehouse suggestion (execute)",
@@ -16616,7 +16616,7 @@
"feature_flag": "warehouse-suggestions"
},
"warehouse-suggestions-accept-prepare": {
- "description": "Step 1 of 2 for accept warehouse suggestion. Validates the arguments and returns a signed confirmation_hash plus a message to surface to the user. The user must reply with the literal word \"confirm\" before you call the matching -execute tool with the hash. Original action: Accept a proposed warehouse suggestion. Certify and deprecate suggestions mark the view or table as certified or deprecated in the data catalog. Accepting a deprecate suggestion on a materialized view also stops its refreshes and deletes its stored table, so the view is computed when read; pass keep_materialized=true to keep it refreshing. The view stays materialized when other views read from it or its refreshes feed person properties, a destination or a workflow; `created_asset.stopped_materialization` says whether refreshes stopped. Materialize suggestions turn on materialization for the view on the proposed schedule, which adds a recurring compute cost; pass refresh_interval_seconds to use another schedule. They also apply the payload's refresh_mode: incremental refreshes read only new rows by incremental_key and update rows by unique_key, full refreshes rebuild the whole table. The payload is a starting point. To change it, pass any of refresh_interval_seconds, refresh_mode, incremental_key, unique_key and lookback_seconds; an omitted field keeps the suggested value. Check keys the person chose with view-check-incremental first. A 400 names the field the server refused and why. A 409 means the view changed since the suggestion was made and its suggested keys no longer apply. Requires human typed confirmation.",
+ "description": "Step 1 of 2 for accept warehouse suggestion. Validates the arguments and returns a signed confirmation_hash plus a message to surface to the user. The user must reply with the literal word \"confirm\" before you call the matching -execute tool with the hash. Original action: Accept a proposed warehouse suggestion. Certify and deprecate suggestions mark the view or table as certified or deprecated in the data catalog. Accepting a deprecate suggestion on a materialized view also stops its refreshes and deletes its stored table, so the view is computed when read; pass keep_materialized=true to keep it refreshing. The view stays materialized when other views read from it or its refreshes feed person properties, a destination or a workflow; `created_asset.stopped_materialization` says whether refreshes stopped. Unmaterialize suggestions turn a rarely read materialized view back into a plain view: its refreshes stop, its stored table is deleted, and each read computes the view, taking about `read_seconds`. A 409 means the view changed since the suggestion was made, for example another view now reads from it or it now refreshes incrementally. Materialize suggestions turn on materialization for the view on the proposed schedule, which adds a recurring compute cost; pass refresh_interval_seconds to use another schedule. They also apply the payload's refresh_mode: incremental refreshes read only new rows by incremental_key and update rows by unique_key, full refreshes rebuild the whole table. The payload is a starting point. To change it, pass any of refresh_interval_seconds, refresh_mode, incremental_key, unique_key and lookback_seconds; an omitted field keeps the suggested value. Check keys the person chose with view-check-incremental first. A 400 names the field the server refused and why. A 409 means the view changed since the suggestion was made and its suggested keys no longer apply. Requires human typed confirmation.",
"category": "Warehouse suggestions",
"feature": "warehouse_suggestions",
"summary": "Accept a warehouse suggestion (prepare)",
@@ -16647,7 +16647,7 @@
"feature_flag": "warehouse-suggestions"
},
"warehouse-suggestions-get": {
- "description": "Get one warehouse suggestion by id, with the `evidence` behind it. Evidence counts reads between `evidence_window_start` and `evidence_window_end`. `human_requests` is the queries people ran on the view or table, `human_users` the distinct people, `human_days` the days with such reads, and `requests_by_surface` those queries per place, such as sql_editor, dashboard or mcp. `background_requests` is the queries PostHog ran on its own, such as cache warming and alerts. `last_read_at` is the latest read of any kind, background included. `days_with_data` is how many days of the window PostHog has read history for, not how active this project is. A field is missing when the subject had no reads. Use these counts and the numbers in `payload` to explain to the user why a view or table should be certified, deprecated or materialized before accepting.",
+ "description": "Get one warehouse suggestion by id, with the `evidence` behind it. Evidence counts reads between `evidence_window_start` and `evidence_window_end`. `human_requests` is the queries people ran on the view or table, `human_users` the distinct people, `human_days` the days with such reads, and `requests_by_surface` those queries per place, such as sql_editor, dashboard or mcp. `background_requests` is the queries PostHog ran on its own, such as cache warming and alerts. `last_read_at` is the latest read of any kind, background included. `days_with_data` is how many days of the window PostHog has read history for, not how active this project is. A field is missing when the subject had no reads. Use these counts and the numbers in `payload` to explain to the user why a view or table should be certified, deprecated, materialized or unmaterialized before accepting.",
"category": "Warehouse suggestions",
"feature": "warehouse_suggestions",
"summary": "Get a warehouse suggestion",
@@ -16663,7 +16663,7 @@
"feature_flag": "warehouse-suggestions"
},
"warehouse-suggestions-list": {
- "description": "Recommendations to certify, deprecate or materialize data warehouse views and tables, computed daily from how often the project reads them. Pass status=proposed for the suggestions still waiting for a decision. `payload` says what accepting would create or change. `can_act` says whether the caller can edit the view or table, which accept, dismiss and resume require. Accepting a certify or deprecate suggestion also requires edit access to the data catalog. Use warehouse-suggestions-get for the usage evidence behind one suggestion. If the list is empty, call warehouse-suggestions-status to learn why. Results come in priority order, the one most worth acting on first. Explain a suggestion to the user with the numbers in `payload`, the time and bytes saved or spent per month. For a certify suggestion, use the read counts in `evidence` from warehouse-suggestions-get.",
+ "description": "Recommendations to certify, deprecate, materialize or unmaterialize data warehouse views and tables, computed daily from how often the project reads them. Pass status=proposed for the suggestions still waiting for a decision. `payload` says what accepting would create or change. `can_act` says whether the caller can edit the view or table, which accept, dismiss and resume require. Accepting a certify or deprecate suggestion also requires edit access to the data catalog. Use warehouse-suggestions-get for the usage evidence behind one suggestion. If the list is empty, call warehouse-suggestions-status to learn why. Results come in priority order, the one most worth acting on first. Explain a suggestion to the user with the numbers in `payload`, the time and bytes saved or spent per month. For an unmaterialize suggestion, compare refresh_seconds_per_month with live_seconds_per_month and say how long one read would take (`read_seconds`). For a certify suggestion, use the read counts in `evidence` from warehouse-suggestions-get.",
"category": "Warehouse suggestions",
"feature": "warehouse_suggestions",
"summary": "List warehouse suggestions",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 4dc1ea767387..96104f1228c3 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -80168,7 +80168,22 @@ export namespace Schemas {
lookback_seconds?: number;
}
- export type WarehouseSuggestionPayload = WarehouseSuggestionCertifyPayload | WarehouseSuggestionDeprecatePayload | WarehouseSuggestionMaterializePayload;
+ export interface WarehouseSuggestionUnmaterializePayload {
+ /** Name of the rarely read materialized view to turn back into a plain view. */
+ 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;
+ /** Estimated time its reads would take in a month if each read computed the view, in seconds. The estimate uses a full refresh per read, so it leans high. */
+ live_seconds_per_month: number;
+ /** Estimated bytes its reads would scan in a month if each read computed the view. */
+ live_bytes_per_month: number;
+ /** How long one read would take once the view is computed on read, in seconds. Nine in ten of its refreshes finished within this time. */
+ read_seconds: number;
+ }
+
+ export type WarehouseSuggestionPayload = WarehouseSuggestionCertifyPayload | WarehouseSuggestionDeprecatePayload | WarehouseSuggestionMaterializePayload | WarehouseSuggestionUnmaterializePayload;
/**
* Queries people ran per place they ran them, such as sql_editor, dashboard, insight or mcp.
@@ -80205,6 +80220,7 @@ export namespace Schemas {
* * `certify` - Certify
* * `deprecate` - Deprecate
* * `materialize` - Materialize
+ * * `unmaterialize` - Unmaterialize
*/
export type WarehouseSuggestionKindEnum = typeof WarehouseSuggestionKindEnum[keyof typeof WarehouseSuggestionKindEnum];
@@ -80213,6 +80229,7 @@ export namespace Schemas {
Certify: 'certify',
Deprecate: 'deprecate',
Materialize: 'materialize',
+ Unmaterialize: 'unmaterialize',
} as const;
/**
@@ -80277,11 +80294,12 @@ export namespace Schemas {
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.
+ /** What the suggestion proposes: certify, deprecate, materialize or unmaterialize the subject. unmaterialize turns a rarely read materialized view back into a plain view computed on read.
*
* * `certify` - Certify
* * `deprecate` - Deprecate
- * * `materialize` - Materialize */
+ * * `materialize` - Materialize
+ * * `unmaterialize` - Unmaterialize */
kind: WarehouseSuggestionKindEnum;
/** Whether the subject is a saved query (view) or a warehouse table.
*
@@ -137315,6 +137333,7 @@ export namespace Schemas {
* * `certify` - Certify
* * `deprecate` - Deprecate
* * `materialize` - Materialize
+ * * `unmaterialize` - Unmaterialize
* @minLength 1
*/
kind?: WarehouseSuggestionsListKind;
@@ -137350,6 +137369,7 @@ export namespace Schemas {
Certify: 'certify',
Deprecate: 'deprecate',
Materialize: 'materialize',
+ Unmaterialize: 'unmaterialize',
} as const;
export type WarehouseSuggestionsListStatus = typeof WarehouseSuggestionsListStatus[keyof typeof WarehouseSuggestionsListStatus];
diff --git a/services/mcp/src/generated/warehouse_suggestions/api.ts b/services/mcp/src/generated/warehouse_suggestions/api.ts
index 88eb6b6b64b0..c84147903eac 100644
--- a/services/mcp/src/generated/warehouse_suggestions/api.ts
+++ b/services/mcp/src/generated/warehouse_suggestions/api.ts
@@ -18,10 +18,10 @@ export const WarehouseSuggestionsListParams = () => zod.object({
export const WarehouseSuggestionsListQueryParams = () => zod.object({
kind: zod
- .enum(['certify', 'deprecate', 'materialize'])
+ .enum(['certify', 'deprecate', 'materialize', 'unmaterialize'])
.optional()
.describe(
- 'Only return suggestions of this kind.\n\n\* `certify` - Certify\n\* `deprecate` - Deprecate\n\* `materialize` - Materialize'
+ 'Only return suggestions of this kind.\n\n\* `certify` - Certify\n\* `deprecate` - Deprecate\n\* `materialize` - Materialize\n\* `unmaterialize` - Unmaterialize'
),
limit: zod.number().optional().describe('Number of results to return per page.'),
offset: zod.number().optional().describe('The initial index from which to return the results.'),
diff --git a/services/mcp/src/tools/generated/warehouse_suggestions.ts b/services/mcp/src/tools/generated/warehouse_suggestions.ts
index 7ba84ba196cc..d5c6c139a001 100644
--- a/services/mcp/src/tools/generated/warehouse_suggestions.ts
+++ b/services/mcp/src/tools/generated/warehouse_suggestions.ts
@@ -41,7 +41,7 @@ const warehouseSuggestionsAcceptPrepare = (): ToolBase<
purpose: 'warehouse-suggestions-accept',
actionLabel: 'accept warehouse suggestion',
messageTemplate:
- "About to accept warehouse suggestion '{id}'. This applies the change it proposes to the view or table. If it is a materialize suggestion, the view then refreshes on a schedule, which adds a recurring compute cost. If it is a deprecate suggestion on a materialized view, its refreshes stop and its stored table is deleted, unless keep_materialized is true. Reply 'confirm' to proceed.\n",
+ "About to accept warehouse suggestion '{id}'. This applies the change it proposes to the view or table. If it is a materialize suggestion, the view then refreshes on a schedule, which adds a recurring compute cost. If it is a deprecate suggestion on a materialized view, its refreshes stop and its stored table is deleted, unless keep_materialized is true. If it is an unmaterialize suggestion, the view's refreshes stop, its stored table is deleted, and each read computes the view instead. Reply 'confirm' to proceed.\n",
codec: __runtime.codec,
stash: __runtime.stash,
boundScope: { projectId: String(__scopeProjectId) },
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/warehouse-suggestions-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/warehouse-suggestions-list.json
index 77dcaa7062f4..a7dba107d108 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/warehouse-suggestions-list.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/warehouse-suggestions-list.json
@@ -2,8 +2,8 @@
"$schema": "https://json-schema.org/draft/2020-12/schema",
"properties": {
"kind": {
- "description": "Only return suggestions of this kind.\n\n* `certify` - Certify\n* `deprecate` - Deprecate\n* `materialize` - Materialize",
- "enum": ["certify", "deprecate", "materialize"],
+ "description": "Only return suggestions of this kind.\n\n* `certify` - Certify\n* `deprecate` - Deprecate\n* `materialize` - Materialize\n* `unmaterialize` - Unmaterialize",
+ "enum": ["certify", "deprecate", "materialize", "unmaterialize"],
"type": "string"
},
"limit": {