:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(customer-analytics): pin the claim view to the sql that was bound (#106046)
Abhischeka22583f78017
diff --git a/products/customer_analytics/backend/logic/ownership_claims.py b/products/customer_analytics/backend/logic/ownership_claims.pyindex 73a9a8ce75db..09613267579f 100644--- a/products/customer_analytics/backend/logic/ownership_claims.py+++ b/products/customer_analytics/backend/logic/ownership_claims.py@@ -25,8 +25,22 @@ no outcome count; it carries no idempotency key, so no run could apply it safelya timezone are read as UTC, which is how Salesforce records them. Nothing is written back toSalesforce: accepted and released claims are visible on the account's relationships and audit trail,and every outcome is counted and logged here.++Binding pins the view, because anyone who can edit a view could otherwise make it return any+decision rows. The definition stores the SHA-256 of the view's SQL at binding. Each run executes+that text as a subquery instead of reading the view by name. A run refuses the view as+``misconfigured`` when its SQL no longer matches the pin. An edit therefore takes effect only after a+person reviews it, binds the view again and enables claims again.++The pin covers the view's own text only. A view that reads another saved query is refused, because+that query can be edited on its own. A view that reads a field through a join or a saved expression+is refused, because both are configured outside the view. These are refused at binding and on every+run. The pin does not cover the sources behind the view's table names: a person who can reconfigure+a warehouse source can change the rows. The claim rules still limit such rows to empty roles, active+organization members and allocations after the fence."""+import hashlibfrom collections import Counterfrom collections.abc import Callablefrom datetime import UTC, datetime@@ -41,8 +55,13 @@ import structlogfrom posthog.hogql import astfrom posthog.hogql.constants import MAX_SELECT_RETURNED_ROWS+from posthog.hogql.context import HogQLContext+from posthog.hogql.database.database import Databasefrom posthog.hogql.errors import ExposedHogQLError+from posthog.hogql.parser import parse_selectfrom posthog.hogql.query import execute_hogql_query+from posthog.hogql.resolver import resolve_types+from posthog.hogql.visitor import TraversingVisitorfrom posthog.clickhouse.client.connection import Workloadfrom posthog.clickhouse.query_tagging import Feature, Product, tags_context@@ -74,7 +93,8 @@ DECISION_COLUMNS = (class ClaimSourceMisconfigured(Exception):"""The claim binding cannot be made or used: no such definition or view, a definition that is not- controlled, or a view that does not answer one of the documented decision columns."""+ controlled, a view that does not answer one of the documented decision columns, a view whose SQL+ changed after binding, or a view that reads another saved query or a field defined outside it."""class SweepStopped(Exception):@@ -141,14 +161,103 @@ def _locked_definition(team_id: int, definition_id: UUID) -> AccountRelationshipreturn definition+def _sql_sha256(sql: str) -> str:+ return hashlib.sha256(sql.encode("utf-8")).hexdigest()+++class _OutsideFieldFinder(TraversingVisitor):+ """Collects the fields of a resolved query that are defined outside its text: joins and saved+ expressions, which people configure on a table."""++ def __init__(self) -> None:+ super().__init__()+ self.fields: set[str] = set()++ def visit_field_type(self, node: ast.FieldType) -> None:+ self.visit(node.table_type)++ def visit_lazy_join_type(self, node: ast.LazyJoinType) -> None:+ self.fields.add(node.field)+ super().visit_lazy_join_type(node)++ def visit_expression_field_type(self, node: ast.ExpressionFieldType) -> None:+ self.fields.add(node.name)+++def _claim_catalog(team: Team) -> Database:+ # The sweep and the binding command run without a user, and the check must see every table the+ # view names; the team still scopes the catalog.+ return Database.create_for(team=team, bypass_warehouse_access_control=True)+++def _refuse_outside_dependencies(team: Team, view_name: str, sql: str, database: Database) -> None:+ """Raise when the view reads something its pin does not cover: another saved query, or a field+ defined outside its text."""+ context = HogQLContext(team_id=team.pk, team=team, enable_select_queries=True, database=database)+ try:+ resolved = resolve_types(parse_select(sql), context, dialect="hogql")+ except ExposedHogQLError as error:+ raise ClaimSourceMisconfigured(f"View {view_name} cannot be resolved: {error}") from error+ _refuse_saved_queries(view_name, context)+ finder = _OutsideFieldFinder()+ finder.visit(resolved)+ if finder.fields:+ raise ClaimSourceMisconfigured(+ f"View {view_name} reads fields defined outside its SQL ({', '.join(sorted(finder.fields))}); "+ "a claim view must compute every column in its own SQL, because its pin covers only that text"+ )+++def _refuse_saved_queries(view_name: str, context: HogQLContext) -> None:+ """Raise when resolving or executing the view's SQL under this context reached a saved query."""+ if context.referenced_saved_query_ids:+ raise ClaimSourceMisconfigured(+ f"View {view_name} reads saved queries ({', '.join(sorted(context.referenced_saved_query_ids))}); "+ "a claim view must read source tables only, because its pin covers only its own SQL"+ )+++def _binding_changed(team_id: int, definition: AccountRelationshipDefinition) -> bool:+ """Lock the definition and tell whether its binding moved after the sweep read the view: to another+ definition, to a newly pinned text, or with claims switched off. Rows read under the old binding+ must not apply, and a claim under the old definition would leave the Task unable to fill the new+ one. Call inside ``transaction.atomic()``, before locking the account."""+ current = ownership.lock_definition(team_id, definition.id)+ return (+ current is None+ or not current.claims_enabled+ or current.claim_saved_query_id != definition.claim_saved_query_id+ or current.claim_saved_query_sha256 != definition.claim_saved_query_sha256+ )+++def _pinned_sql(team: Team, definition: AccountRelationshipDefinition, view_name: str, database: Database) -> str:+ """The bound view's SQL, only while it is the text that was pinned at binding. A binding without+ a pin never matches, so it is refused until the view is bound again."""+ sql = data_modeling_facade.get_saved_query_sql(team.id, definition.claim_saved_query_id)+ if sql is None or _sql_sha256(sql) != definition.claim_saved_query_sha256:+ raise ClaimSourceMisconfigured(+ f"View {view_name} does not match the SQL pinned at binding; review it, bind it again and enable claims"+ )+ # The text matches the pin, but a name in it can resolve to a saved query or a field defined after+ # binding.+ _refuse_outside_dependencies(team, view_name, sql, database)+ return sql++def bind_claim_view(team_id: int, definition_id: UUID, saved_query_id: UUID | None) -> AccountRelationshipDefinition:- """Bind the warehouse view whose rows fill the definition, or unbind it with None, which also- switches its sweep off. Only a controlled definition can take a view, because a claim fills only- a managed relationship; the view must answer every decision column; and a view feeds one- definition, because a Task id is unique per team and a second definition would only ever see- ``already_applied``."""+ """Bind the warehouse view whose rows fill the definition, or unbind it with None; either way the+ definition's sweep is switched off. Only a controlled definition can take a view, because a claim+ fills only a managed relationship; the view must answer every decision column; and a view feeds+ one definition, because a Task id is unique per team and a second definition would only ever see+ ``already_applied``.++ Binding pins the view's SQL as it is at that moment, and the sweep reads only that text. The+ pinned text runs only after a separate ``set_claims_enabled``, because an edit made between a+ person's review and the binding would otherwise go live unreviewed."""with transaction.atomic():definition = _locked_definition(team_id, definition_id)+ pin: str | None = Noneif saved_query_id is not None:if not definition.is_controlled:raise ClaimSourceMisconfigured(@@ -168,10 +277,16 @@ def bind_claim_view(team_id: int, definition_id: UUID, saved_query_id: UUID | Noraise ClaimSourceMisconfigured(f"View {view.name} already fills {elsewhere.name}; a view feeds one definition")+ sql = data_modeling_facade.get_saved_query_sql(team_id, saved_query_id)+ if sql is None:+ raise ClaimSourceMisconfigured(f"View {view.name} has no SQL to pin")+ team = Team.objects.get(id=team_id)+ _refuse_outside_dependencies(team, view.name, sql, _claim_catalog(team))+ pin = _sql_sha256(sql)definition.claim_saved_query_id = saved_query_id- if saved_query_id is None:- definition.claims_enabled = False- definition.save(update_fields=["claim_saved_query", "claims_enabled", "updated_at"])+ definition.claim_saved_query_sha256 = pin+ definition.claims_enabled = False+ definition.save(update_fields=["claim_saved_query", "claim_saved_query_sha256", "claims_enabled", "updated_at"])return definition@@ -184,6 +299,8 @@ def set_claims_enabled(team_id: int, definition_id: UUID, enabled: bool) -> Accoraise ClaimSourceMisconfigured(f"{definition.name} has no claim view bound; bind one before enabling claims")+ if enabled and definition.claim_saved_query_sha256 is None:+ raise ClaimSourceMisconfigured(f"{definition.name} has no pinned claim view; bind the view again")definition.claims_enabled = enableddefinition.save(update_fields=["claims_enabled", "updated_at"])return definition@@ -217,8 +334,12 @@ def reconcile_ownership_claims(team: Team, *, should_stop: Callable[[], bool] =# One unusable view must not stop the project's other definitions: it is counted, reported,# and read again next tick. A stop request is a different exception and still ends the sweep.try:+ # One catalog for the check and every page of the read, so a join or a saved expression+ # added after the check cannot shape the rows.+ database = _claim_catalog(team)+ sql = _pinned_sql(team, definition, view.name, database)check_decision_columns(view.name, data_modeling_facade.get_saved_query_columns(team.id, view.id))- rows = _read_decision_rows(team, view.name, should_stop)+ rows = _read_decision_rows(team, view.name, sql, database, should_stop)except ClaimSourceMisconfigured as error:capture_exception(error, {"team_id": team.id, "definition_id": str(definition.id)})logger.warning(@@ -248,7 +369,7 @@ def _apply_rows(# reads the view again.try:if decision.is_release:- result = release(team=team, decision=decision)+ result = release(team=team, definition=definition, decision=decision)else:result = claim(team=team, definition=definition, decision=decision)except IntegrityError as error:@@ -301,37 +422,45 @@ def _task_id(row: dict[str, Any]) -> str | None:return None-def _read_decision_rows(team: Team, view_name: str, should_stop: Callable[[], bool]) -> list[dict[str, Any]]:- """Every row of the view, keyed by column name, paged on ``task_id`` so a view of any size is read- to the end. The view runs as a userless system read, so user-scoped warehouse access control is- bypassed; tenant isolation still holds through the team."""+def _read_decision_rows(+ team: Team, view_name: str, sql: str, database: Database, should_stop: Callable[[], bool]+) -> list[dict[str, Any]]:+ """Every row the view's pinned SQL returns, keyed by column name, paged on ``task_id`` so a view of+ any size is read to the end. The SQL runs as a subquery rather than as the view's name, so neither+ a materialized copy of the view nor an edit made after the pin was checked can change what is read.+ It runs as a userless system read, so user-scoped warehouse access control is bypassed; tenant+ isolation still holds through the team. Every page runs against the catalog the pin was checked+ against, and a page is refused when its execution reached a saved query."""rows: list[dict[str, Any]] = []cursor = ""with tags_context(product=Product.CUSTOMER_ANALYTICS, feature=Feature.ACCOUNTS, team_id=team.pk):while True:if should_stop():raise SweepStopped()- query = ast.SelectQuery(- select=[ast.Field(chain=[column]) for column in DECISION_COLUMNS],- select_from=ast.JoinExpr(table=ast.Field(chain=[view_name])),- where=ast.CompareOperation(- op=ast.CompareOperationOp.Gt,- left=ast.Call(name="toString", args=[ast.Field(chain=["task_id"])]),- right=ast.Constant(value=cursor),- ),- order_by=[- ast.OrderExpr(expr=ast.Call(name="toString", args=[ast.Field(chain=["task_id"])]), order="ASC")- ],- limit=ast.Constant(value=DECISION_PAGE_SIZE),- )+ context = HogQLContext(team_id=team.pk, bypass_warehouse_access_control=True, database=database)try:+ # Parsed for every page, so each execution gets an AST of its own.+ query = ast.SelectQuery(+ select=[ast.Field(chain=[column]) for column in DECISION_COLUMNS],+ select_from=ast.JoinExpr(table=parse_select(sql)),+ where=ast.CompareOperation(+ op=ast.CompareOperationOp.Gt,+ left=ast.Call(name="toString", args=[ast.Field(chain=["task_id"])]),+ right=ast.Constant(value=cursor),+ ),+ order_by=[+ ast.OrderExpr(expr=ast.Call(name="toString", args=[ast.Field(chain=["task_id"])]), order="ASC")+ ],+ limit=ast.Constant(value=DECISION_PAGE_SIZE),+ )response = execute_hogql_query(- query, team=team, workload=Workload.OFFLINE, bypass_warehouse_access_control=True+ query, team=team, workload=Workload.OFFLINE, bypass_warehouse_access_control=True, context=context)except (ExposedHogQLError, ExposedCHQueryError) as error:# A view whose SQL no longer resolves (a dropped source table, a renamed column) is# the view's fault and is reported as such; infrastructure failures still propagate.raise ClaimSourceMisconfigured(f"View {view_name} cannot be read: {error}") from error+ _refuse_saved_queries(view_name, context)page = response.results or []if len(page) < DECISION_PAGE_SIZE:rows.extend(dict(zip(DECISION_COLUMNS, row)) for row in page)@@ -418,15 +547,8 @@ def claim(actor = relationships.Actor(source=AccountRelationshipSource.SALESFORCE_CLAIM)with transaction.atomic():# Definition before account, the order every writer takes. The view was read before this- # transaction, so the binding is checked again here: an operator may have moved the view- # to another definition or switched its sweep off in between, and a claim under the old- # definition would leave the Task unable to fill the new one.- current = ownership.lock_definition(team.id, definition.id)- if (- current is None- or not current.claims_enabled- or current.claim_saved_query_id != definition.claim_saved_query_id- ):+ # transaction, so the binding is checked again here.+ if _binding_changed(team.id, definition):return _claim_result("blocked", "binding_changed")try:locked_account = _lock_account_by_external_id(team.id, decision.organization_id)@@ -485,7 +607,9 @@ def claim(return _claim_result("accepted", None, relationship, fence)-def release(*, team: Team, decision: contracts.OwnershipClaimDecision) -> contracts.OwnershipClaimResult:+def release(+ *, team: Team, definition: AccountRelationshipDefinition, decision: contracts.OwnershipClaimDecision+) -> contracts.OwnershipClaimResult:"""End the relationship that this Task's accepted claim created, and nothing else.A release needs no time fence: identity to the Task's own claim is the guard, so it cannot clear@@ -497,6 +621,9 @@ def release(*, team: Team, decision: contracts.OwnershipClaimDecision) -> contraif held is None:return _claim_result("not_held", None)with transaction.atomic():+ # Definition before account, and the binding checked again, as for a claim.+ if _binding_changed(team.id, definition):+ return _claim_result("blocked", "binding_changed")# The claim names the account to lock, and is then read again under that lock: a person may# have ended it in between, which is exactly what makes the release a no-op. An account# deleted in between takes its claim row with it, so the account check only completes the type.diff --git a/products/customer_analytics/backend/management/commands/configure_account_ownership.py b/products/customer_analytics/backend/management/commands/configure_account_ownership.pyindex ed1a6e1ad8eb..4af924ab2dfe 100644--- a/products/customer_analytics/backend/management/commands/configure_account_ownership.py+++ b/products/customer_analytics/backend/management/commands/configure_account_ownership.py@@ -4,9 +4,15 @@ From then on, a person's change to a controlled relationship on a linked accountaccount under every controlled definition. ``adopt_account_ownership`` enrolls accounts in reviewedbatches. No path unenrolls an account, so control cannot end after the first enrollment.+Binding a claim view pins its SQL, switches its claims off and prints the SHA-256 of that text.+Enable claims in a separate call, after checking that the digest matches the SQL you reviewed, for+example with ``printf '%s' "$SQL" | shasum -a 256``; a file saved by an editor usually ends with a+newline that changes the digest. An edit to the view stops its sweep until the view is bound and+enabled again.+python manage.py configure_account_ownership --team-id 2 --control <definition uuid>- python manage.py configure_account_ownership --team-id 2 --claim-view <definition uuid> <view uuid> \\- --claims <definition uuid> enabled+ python manage.py configure_account_ownership --team-id 2 --claim-view <definition uuid> <view uuid>+ python manage.py configure_account_ownership --team-id 2 --claims <definition uuid> enabled"""from typing import Any@@ -54,8 +60,8 @@ class Command(BaseCommand):default=[],metavar=("DEFINITION_ID", "SAVED_QUERY_ID"),help=(- "Bind the warehouse view of decisions that fill this controlled definition; see "- "logic/ownership_claims.py. Repeatable."+ "Bind the warehouse view of decisions that fill this controlled definition and pin its SQL; "+ "see logic/ownership_claims.py. Bind again after any edit to the view. Repeatable."),)parser.add_argument(@@ -91,6 +97,16 @@ class Command(BaseCommand):raise CommandError(f"--claim-view and --clear-claim-view both name {', '.join(str(d) for d in sorted(contradicted))}")+ # Enabling in the binding call would run the pinned text before anyone compared its digest+ # with the SQL they reviewed.+ unreviewed = {definition_id for definition_id, _ in claim_views} & {+ definition_id for definition_id, enabled in switches if enabled+ }+ if unreviewed:+ raise CommandError(+ f"--claim-view and --claims enabled both name {', '.join(str(d) for d in sorted(unreviewed))}; "+ "bind, check the printed claim_view_sha256, then enable claims in a separate call"+ )# One transaction, so a refused change leaves the configuration as it was. Every definition# the call touches is locked first, by id, so two concurrent calls take their locks in one@@ -130,7 +146,8 @@ class Command(BaseCommand):f"team {team.id}: {definition.name} ({definition.id}) "f"controlled={'yes' if definition.is_controlled else 'no'} "f"claims={'enabled' if definition.claims_enabled else 'disabled'} "- f"claim_view={definition.claim_saved_query_id or '<unset>'}"+ f"claim_view={definition.claim_saved_query_id or '<unset>'} "+ f"claim_view_sha256={definition.claim_saved_query_sha256 or '<unset>'}")@staticmethoddiff --git a/products/customer_analytics/backend/migrations/0058_accountrelationshipdefinition_claim_saved_query_sha256.py b/products/customer_analytics/backend/migrations/0058_accountrelationshipdefinition_claim_saved_query_sha256.pynew file mode 100644index 000000000000..44ae392b8737--- /dev/null+++ b/products/customer_analytics/backend/migrations/0058_accountrelationshipdefinition_claim_saved_query_sha256.py@@ -0,0 +1,20 @@+# Generated by Django 5.2.17 on 2026-09-24 14:23++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ (+ "customer_analytics",+ "0057_team_customer_analytics_config_activity_event_default",+ )+ ]++ operations = [+ migrations.AddField(+ model_name="accountrelationshipdefinition",+ name="claim_saved_query_sha256",+ field=models.CharField(blank=True, max_length=64, null=True),+ ),+ ]diff --git a/products/customer_analytics/backend/migrations/max_migration.txt b/products/customer_analytics/backend/migrations/max_migration.txtindex c1da31c3bf35..590fa37f332c 100644--- a/products/customer_analytics/backend/migrations/max_migration.txt+++ b/products/customer_analytics/backend/migrations/max_migration.txt@@ -1 +1 @@-0057_team_customer_analytics_config_activity_event_default+0058_accountrelationshipdefinition_claim_saved_query_sha256diff --git a/products/customer_analytics/backend/models/relationship.py b/products/customer_analytics/backend/models/relationship.pyindex 2c9887d946f1..793b67185be2 100644--- a/products/customer_analytics/backend/models/relationship.py+++ b/products/customer_analytics/backend/models/relationship.py@@ -41,6 +41,10 @@ class AccountRelationshipDefinition(TeamScopedRootMixin, UUIDModel, CreatedMetaFclaim_saved_query = models.ForeignKey("data_modeling.DataWarehouseSavedQuery", on_delete=models.RESTRICT, null=True, blank=True, related_name="+")+ # SHA-256 of the view's SQL at binding. The sweep executes only that text and refuses the view+ # once its SQL differs, so an edit to a bound view takes effect only after it is bound and+ # enabled again.+ claim_saved_query_sha256 = models.CharField(max_length=64, null=True, blank=True)claims_enabled = models.BooleanField(default=False, db_default=False)class Meta:diff --git a/products/customer_analytics/backend/test/factories.py b/products/customer_analytics/backend/test/factories.pyindex 648767bd028c..3a61c0942963 100644--- a/products/customer_analytics/backend/test/factories.py+++ b/products/customer_analytics/backend/test/factories.py@@ -154,16 +154,17 @@ def create_custom_property_definition(def create_saved_query(- *, team_id: int, name: str = "enriched_users", is_materialized: bool = True, **kwargs: Any+ *, team_id: int, name: str = "enriched_users", is_materialized: bool = True, sql: str = "select 1", **kwargs: Any) -> DataWarehouseSavedQuery:"""Create a data-warehouse view for tests. Materialized by default, which is what a view-backedproperty source binds to."""return DataWarehouseSavedQuery.objects.create(- team_id=team_id, name=name, query={"query": "select 1"}, is_materialized=is_materialized, **kwargs+ team_id=team_id, name=name, query={"query": sql}, is_materialized=is_materialized, **kwargs)def saved_query_columns(names: Iterable[str]) -> dict[str, dict[str, str]]:"""Columns in the shape data_modeling stores after a run. Its facade drops a column with no- ``clickhouse`` type, so a bare ``{}`` entry would read back as missing."""- return {name: {"clickhouse": "String"} for name in names}+ ``clickhouse`` type, so a bare ``{}`` entry would read back as missing. Resolving a view's SQL+ builds a HogQL database, which needs the ``hogql`` type of every column."""+ return {name: {"clickhouse": "String", "hogql": "StringDatabaseField"} for name in names}diff --git a/products/customer_analytics/backend/test/test_account_ownership_commands.py b/products/customer_analytics/backend/test/test_account_ownership_commands.pyindex 4d0087ae92f3..ce12ee4c4153 100644--- a/products/customer_analytics/backend/test/test_account_ownership_commands.py+++ b/products/customer_analytics/backend/test/test_account_ownership_commands.py@@ -1,5 +1,6 @@import jsonimport shutil+import hashlibimport tempfilefrom io import StringIOfrom pathlib import Path@@ -57,19 +58,22 @@ class TestConfigureAccountOwnershipCommand(BaseTest):view = self._decision_view(self.team.id)definition_id = str(self.ae_definition.id)- self._configure(- "--control",- definition_id,- "--claim-view",- definition_id,- str(view.id),- "--claims",- definition_id,- "enabled",- )+ bound = self._configure("--control", definition_id, "--claim-view", definition_id, str(view.id))++ assert self._state(self.ae_definition) == (True, False, view.id)+ assert f"claim_view_sha256={hashlib.sha256(b'select 1').hexdigest()}" in bound++ self._configure("--claims", definition_id, "enabled")assert self._state(self.ae_definition) == (True, True, view.id)+ view.query = {"query": "select 2"}+ view.save(update_fields=["query"])+ rebound = self._configure("--claim-view", definition_id, str(view.id))++ assert self._state(self.ae_definition) == (True, False, view.id)+ assert f"claim_view_sha256={hashlib.sha256(b'select 2').hexdigest()}" in rebound+self._configure("--clear-claim-view", definition_id, "--uncontrol", definition_id)assert self._state(self.ae_definition) == (False, False, None)@@ -102,6 +106,9 @@ class TestConfigureAccountOwnershipCommand(BaseTest):("binding_a_view_that_fills_another_definition", True, False),("binding_and_clearing_in_one_call", True, False),("naming_a_definition_twice_with_different_views", True, False),+ ("binding_a_view_that_reads_another_saved_query", True, False),+ ("binding_and_enabling_in_one_call", True, False),+ ("enabling_a_binding_without_a_pin", True, True),])def test_a_claim_view_binding_is_refused(self, case, controlled, bound):@@ -129,6 +136,19 @@ class TestConfigureAccountOwnershipCommand(BaseTest):team_id=self.team.id, name="other_decisions", columns=saved_query_columns(DECISION_COLUMNS))args = ["--claim-view", definition_id, str(view.id), "--claim-view", definition_id, str(other.id)]+ elif case == "binding_a_view_that_reads_another_saved_query":+ create_saved_query(team_id=self.team.id, name="raw_decisions", columns=saved_query_columns(["task_id"]))+ view.query = {"query": "select task_id from raw_decisions"}+ view.save(update_fields=["query"])+ args = ["--claim-view", definition_id, str(view.id)]+ elif case == "binding_and_enabling_in_one_call":+ args = ["--claim-view", definition_id, str(view.id), "--claims", definition_id, "enabled"]+ elif case == "enabling_a_binding_without_a_pin":+ self._configure("--claim-view", definition_id, str(view.id))+ AccountRelationshipDefinition.objects.for_team(self.team.id).filter(id=self.ae_definition.id).update(+ claim_saved_query_sha256=None+ )+ args = ["--claims", definition_id, "enabled"]else:args = ["--claim-view", definition_id, str(view.id), "--clear-claim-view", definition_id]diff --git a/products/customer_analytics/backend/test/test_ownership_claims.py b/products/customer_analytics/backend/test/test_ownership_claims.pyindex 6fa35c056858..65d5f02866c2 100644--- a/products/customer_analytics/backend/test/test_ownership_claims.py+++ b/products/customer_analytics/backend/test/test_ownership_claims.py@@ -1,3 +1,4 @@+import hashlibfrom dataclasses import replacefrom datetime import UTC, datetime, timedeltafrom decimal import Decimal@@ -5,7 +6,7 @@ from types import SimpleNamespacefrom typing import Anyimport pytest-from posthog.test.base import BaseTest+from posthog.test.base import BaseTest, ClickhouseTestMixinfrom unittest.mock import AsyncMock, MagicMock, patchfrom django.db import IntegrityError, OperationalError, transaction@@ -19,7 +20,10 @@ from temporalio.common import WorkflowIDReusePolicyfrom temporalio.exceptions import WorkflowAlreadyStartedErrorfrom temporalio.workflow import ParentClosePolicy+from posthog.hogql.database.database import Database+from posthog.hogql.database.models import ExpressionFieldfrom posthog.hogql.errors import QueryError+from posthog.hogql.parser import parse_expr, parse_selectfrom posthog.models import Userfrom posthog.models.activity_logging.activity_log import ActivityLog@@ -65,11 +69,28 @@ class TestOwnershipClaims(BaseTest):self.human = relationships.Actor.human(self.user)def _claim_bound_definition(self, name: str, view_name: str) -> tuple[AccountRelationshipDefinition, Any]:- view = create_saved_query(team_id=self.team.id, name=view_name, columns=saved_query_columns(DECISION_COLUMNS))+ view = create_saved_query(+ team_id=self.team.id,+ name=view_name,+ sql=f"select '{view_name}' as source",+ columns=saved_query_columns(DECISION_COLUMNS),+ )definition = AccountRelationshipDefinition.objects.for_team(self.team.id).create(- team_id=self.team.id, name=name, is_controlled=True, claims_enabled=True, claim_saved_query=view+ team_id=self.team.id, name=name, is_controlled=True+ )+ ownership_claims.bind_claim_view(self.team.id, definition.id, view.id)+ return ownership_claims.set_claims_enabled(self.team.id, definition.id, True), view++ def _pin(self, sql: str) -> None:+ self.view.query = {"query": sql}+ self.view.save(update_fields=["query"])+ AccountRelationshipDefinition.objects.for_team(self.team.id).filter(id=self.ae_definition.id).update(+ claim_saved_query_sha256=hashlib.sha256(sql.encode()).hexdigest())- return definition, view++ @staticmethod+ def _reads(query: Any, view: Any) -> bool:+ return query.select_from.table == parse_select(view.query["query"])def _decision(self, **overrides) -> contracts.OwnershipClaimDecision:base = contracts.OwnershipClaimDecision(@@ -93,7 +114,9 @@ class TestOwnershipClaims(BaseTest):)def _release_claim(self, **overrides) -> contracts.OwnershipClaimResult:- return ownership_claims.release(team=self.team, decision=self._release(**overrides))+ return ownership_claims.release(+ team=self.team, definition=self.ae_definition, decision=self._release(**overrides)+ )def _active_ae(self) -> AccountRelationship | None:return (@@ -467,17 +490,43 @@ class TestOwnershipClaims(BaseTest):assert result.skipped is Trueread.assert_not_called()- @parameterized.expand(["missing_columns", "query_error"])- def test_one_unusable_view_is_counted_and_the_others_still_run(self, fault):+ @parameterized.expand(+ [+ ("missing_columns", 1),+ ("query_error", 2),+ ("edited_after_binding", 1),+ ("bound_before_pinning", 1),+ ("reads_another_saved_query", 1),+ ("reads_a_field_through_a_join", 1),+ ("execution_reads_a_saved_query", 2),+ ]+ )+ def test_one_unusable_view_is_counted_and_the_others_still_run(self, fault: str, reads: int) -> None:+if fault == "missing_columns":self.view.columns = saved_query_columns(["task_id"])self.view.save(update_fields=["columns"])+ elif fault == "edited_after_binding":+ self.view.query = {"query": "select 'edited' as source"}+ self.view.save(update_fields=["query"])+ elif fault == "bound_before_pinning":+ AccountRelationshipDefinition.objects.for_team(self.team.id).filter(id=self.ae_definition.id).update(+ claim_saved_query_sha256=None+ )+ elif fault == "reads_another_saved_query":+ create_saved_query(team_id=self.team.id, name="raw_decisions", columns=saved_query_columns(["task_id"]))+ self._pin("select task_id from raw_decisions")+ elif fault == "reads_a_field_through_a_join":+ self._pin("select pdi.person_id as task_id from events")csm_definition, _ = self._claim_bound_definition("CSM", "csm_decisions")enroll_account(self.account, csm_definition, controlled_at=FENCE)rows = self._view_rows(self._decision(source_ref="task-csm"))- def read_view(query, **_kwargs):- if query.select_from.table.chain[0] == self.view.name:+ def read_view(query, **kwargs):+ if self._reads(query, self.view):+ if fault == "execution_reads_a_saved_query":+ kwargs["context"].referenced_saved_query_ids.add("a-saved-query-created-after-the-check")+ return SimpleNamespace(results=rows)raise QueryError("Unknown table 'salesforce_task'")return SimpleNamespace(results=rows)@@ -488,33 +537,81 @@ class TestOwnershipClaims(BaseTest):result = ownership_claims.reconcile_ownership_claims(self.team)assert (result.decisions, result.outcomes, result.skipped) == (1, {"misconfigured": 1, "accepted": 1}, False)- assert read.call_count == (1 if fault == "missing_columns" else 2)+ assert read.call_count == readscaptured.assert_called_once()holder = AccountRelationship.objects.for_team(self.team.id).get(account=self.account, ended_at__isnull=True)assert (holder.definition_id, holder.source_ref) == (csm_definition.id, "task-csm")- def test_a_view_moved_mid_sweep_is_applied_under_its_new_definition_next_tick(self):+ @parameterized.expand(["moved_to_another_definition", "pinned_again_after_an_edit"])+ def test_a_view_rebound_mid_sweep_is_applied_under_its_new_binding_next_tick(self, case: str) -> None:csm_definition = AccountRelationshipDefinition.objects.for_team(self.team.id).create(team_id=self.team.id, name="CSM", is_controlled=True)enroll_account(self.account, csm_definition, controlled_at=FENCE)+ target = csm_definition if case == "moved_to_another_definition" else self.ae_definitionrows = self._view_rows(self._decision(source_ref="task-moved"))- def move_view_then_answer(query, **_kwargs):- ownership_claims.bind_claim_view(self.team.id, self.ae_definition.id, None)- ownership_claims.bind_claim_view(self.team.id, csm_definition.id, self.view.id)- ownership_claims.set_claims_enabled(self.team.id, csm_definition.id, True)+ def rebind_then_answer(query, **_kwargs):+ if case == "moved_to_another_definition":+ ownership_claims.bind_claim_view(self.team.id, self.ae_definition.id, None)+ else:+ self.view.query = {"query": "select 'edited' as source"}+ self.view.save(update_fields=["query"])+ ownership_claims.bind_claim_view(self.team.id, target.id, self.view.id)+ ownership_claims.set_claims_enabled(self.team.id, target.id, True)return SimpleNamespace(results=rows)- with patch.object(ownership_claims, "execute_hogql_query", side_effect=move_view_then_answer):- during_move = ownership_claims.reconcile_ownership_claims(self.team)+ with patch.object(ownership_claims, "execute_hogql_query", side_effect=rebind_then_answer):+ during_rebind = ownership_claims.reconcile_ownership_claims(self.team)with patch.object(ownership_claims, "execute_hogql_query", return_value=SimpleNamespace(results=rows)):next_tick = ownership_claims.reconcile_ownership_claims(self.team)- assert during_move.outcomes == {"binding_changed": 1}+ assert during_rebind.outcomes == {"binding_changed": 1}assert next_tick.outcomes == {"accepted": 1}holder = AccountRelationship.objects.for_team(self.team.id).get(account=self.account, ended_at__isnull=True)- assert (holder.definition_id, holder.source_ref) == (csm_definition.id, "task-moved")+ assert (holder.definition_id, holder.source_ref) == (target.id, "task-moved")++ def test_a_view_that_reads_a_saved_expression_is_refused_before_it_is_read(self) -> None:+ create_for = Database.create_for++ def with_a_saved_expression(*args, **kwargs):+ database = create_for(*args, **kwargs)+ database.get_table("numbers").fields["saved_task_id"] = ExpressionField(+ name="saved_task_id", expr=parse_expr("toString(number)")+ )+ return database++ self._pin("select saved_task_id as task_id from numbers(1)")++ with (+ patch.object(Database, "create_for", side_effect=with_a_saved_expression),+ patch.object(ownership_claims, "execute_hogql_query") as read,+ ):+ result = ownership_claims.reconcile_ownership_claims(self.team)++ assert result.outcomes == {"misconfigured": 1}+ read.assert_not_called()++ def test_a_release_read_before_a_rebind_is_applied_next_tick(self) -> None:+ self._claim()+ rows = self._view_rows(self._release())++ def rebind_then_answer(query, **_kwargs):+ self.view.query = {"query": "select 'edited' as source"}+ self.view.save(update_fields=["query"])+ ownership_claims.bind_claim_view(self.team.id, self.ae_definition.id, self.view.id)+ ownership_claims.set_claims_enabled(self.team.id, self.ae_definition.id, True)+ return SimpleNamespace(results=rows)++ with patch.object(ownership_claims, "execute_hogql_query", side_effect=rebind_then_answer):+ during_rebind = ownership_claims.reconcile_ownership_claims(self.team)+ held = self._active_ae()+ with patch.object(ownership_claims, "execute_hogql_query", return_value=SimpleNamespace(results=rows)):+ next_tick = ownership_claims.reconcile_ownership_claims(self.team)++ assert (during_rebind.outcomes, next_tick.outcomes) == ({"binding_changed": 1}, {"cleared": 1})+ assert held is not None and held.source_ref == TASK+ assert self._active_ae() is Nonedef test_a_bound_view_cannot_be_hard_deleted(self):with self.assertRaises(RestrictedError):@@ -541,13 +638,13 @@ class TestOwnershipClaims(BaseTest):def test_each_claim_bound_definition_reads_its_own_view(self):csm_definition, csm_view = self._claim_bound_definition("CSM", "csm_decisions")enroll_account(self.account, csm_definition, controlled_at=FENCE)- rows_by_view = {- self.view.name: self._view_rows(self._decision(source_ref="task-ae")),- csm_view.name: self._view_rows(self._decision(source_ref="task-csm")),- }+ rows_by_view = [+ (self.view, self._view_rows(self._decision(source_ref="task-ae"))),+ (csm_view, self._view_rows(self._decision(source_ref="task-csm"))),+ ]def read_view(query, **_kwargs):- return SimpleNamespace(results=rows_by_view[query.select_from.table.chain[0]])+ return SimpleNamespace(results=next(rows for view, rows in rows_by_view if self._reads(query, view)))with patch.object(ownership_claims, "execute_hogql_query", side_effect=read_view):result = ownership_claims.reconcile_ownership_claims(self.team)@@ -560,6 +657,40 @@ class TestOwnershipClaims(BaseTest):}+class TestOwnershipClaimViewRead(ClickhouseTestMixin, BaseTest):+ def test_the_pinned_sql_is_read_in_pages_through_hogql(self) -> None:+ account = create_account(team_id=self.team.id, name="Acme Corp", external_id="org-1")+ definition = AccountRelationshipDefinition.objects.for_team(self.team.id).create(+ team_id=self.team.id, name="Account executive", is_controlled=True+ )+ enroll_account(account, definition, controlled_at=FENCE)+ decision = (+ "select '{task}' as task_id, '{org}' as organization_id, 'us' as region, "+ f"{self.user.id} as assignee_user_id, 'example-salesforce-user-17' as source_assignee_id, "+ "'2026-01-02T00:00:00.000+0000' as allocated_at, null as released_at, null as source_releaser_id"+ )+ view = create_saved_query(+ team_id=self.team.id,+ name="ownership_decisions",+ is_materialized=False,+ sql=f"{decision.format(task='task-2', org='org-1')} union all {decision.format(task='task-1', org='org-none')}",+ columns=saved_query_columns(DECISION_COLUMNS),+ )+ ownership_claims.bind_claim_view(self.team.id, definition.id, view.id)+ ownership_claims.set_claims_enabled(self.team.id, definition.id, True)++ with (+ patch.object(ownership_claims, "DECISION_PAGE_SIZE", 1),+ patch.object(Database, "create_for", wraps=Database.create_for) as catalog_builds,+ ):+ result = ownership_claims.reconcile_ownership_claims(self.team)++ assert (result.decisions, result.outcomes) == (2, {"accepted": 1, "blocked:account_not_found": 1})+ assert catalog_builds.call_count == 1+ holder = AccountRelationship.objects.for_team(self.team.id).get(account=account, ended_at__isnull=True)+ assert (holder.user_id, holder.source_ref) == (self.user.id, "task-2")++@pytest.mark.asyncioasync def test_coordinator_starts_one_sweep_per_project_and_leaves_a_running_one_alone() -> None:team_ids = (11, 22, 33)diff --git a/products/data_modeling/backend/facade/api.py b/products/data_modeling/backend/facade/api.pyindex 636a6f466617..d2ceac3ec413 100644--- a/products/data_modeling/backend/facade/api.py+++ b/products/data_modeling/backend/facade/api.py@@ -38,6 +38,7 @@ _LAZY = {"get_saved_query_columns": "logic.saved_query_reads","get_saved_query_ids_for_nodes": "logic.saved_query_reads","get_saved_query_summary": "logic.saved_query_reads",+ "get_saved_query_sql": "logic.saved_query_reads","all_saved_query_columns": "logic.saved_query_reads","all_saved_query_names": "logic.saved_query_reads","allowed_saved_query_ids": "logic.saved_query_reads",diff --git a/products/data_modeling/backend/logic/saved_query_reads.py b/products/data_modeling/backend/logic/saved_query_reads.pyindex ddf1290309c8..917a71d4172a 100644--- a/products/data_modeling/backend/logic/saved_query_reads.py+++ b/products/data_modeling/backend/logic/saved_query_reads.py@@ -74,6 +74,19 @@ def all_saved_query_columns(team_id: int) -> dict[str, dict[str, str]]:}+def get_saved_query_sql(team_id: int, saved_query_id: UUID | str) -> str | None:+ """The HogQL text of the saved query exactly as stored, or None when it no longer resolves or+ stores no text. Soft-deleted rows are excluded for the reason ``get_saved_query_summary`` gives."""+ stored = (+ DataWarehouseSavedQuery.objects.filter(team_id=team_id, id=saved_query_id)+ .exclude(deleted=True)+ .values_list("query", flat=True)+ .first()+ )+ sql = stored.get("query") if isinstance(stored, dict) else None+ return sql if isinstance(sql, str) else None++def all_saved_query_names(team_id: int) -> dict[str, str]:"""The current name of every saved query in this team that still resolves. One query."""rows = DataWarehouseSavedQuery.objects.filter(team_id=team_id).exclude(deleted=True).values_list("id", "name")