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(customer-analytics): add account churn state (#83203)

Arthur Moreira de Deuscf11bd9cda03
diff --git a/ee/hogai/context/account/context.py b/ee/hogai/context/account/context.py
index a9d9f01c03d5..d028c96c4385 100644
--- a/ee/hogai/context/account/context.py
+++ b/ee/hogai/context/account/context.py
@@ -72,6 +72,7 @@ class AccountContext:
account_id=str(account.id),
external_id=account.external_id or "Not set",
created_at=account.created_at.isoformat() if account.created_at else "Unknown",
+ churned_at=account.churned_at.isoformat() if account.churned_at else "Not churned",
roles_section=self._roles_section(account),
external_ids_section=self._external_ids_section(account),
tags_section=self._tags_section(account),
diff --git a/ee/hogai/context/account/prompts.py b/ee/hogai/context/account/prompts.py
index cbbc0634a9e5..c0284af4ca68 100644
--- a/ee/hogai/context/account/prompts.py
+++ b/ee/hogai/context/account/prompts.py
@@ -4,6 +4,7 @@ ACCOUNT_CONTEXT_TEMPLATE = """
**ID:** {account_id}
**External ID:** {external_id}
**Created:** {created_at}
+**Churned:** {churned_at}
{roles_section}
{external_ids_section}
{tags_section}
diff --git a/ee/hogai/context/account/test/test_context.py b/ee/hogai/context/account/test/test_context.py
index da2d05baa938..b864ede8c717 100644
--- a/ee/hogai/context/account/test/test_context.py
+++ b/ee/hogai/context/account/test/test_context.py
@@ -1,4 +1,5 @@
import uuid
+from datetime import UTC, datetime
from typing import TYPE_CHECKING
from posthog.test.base import NonAtomicBaseTest
@@ -83,6 +84,20 @@ class TestAccountContext(NonAtomicBaseTest):
assert "**External ID:** Not set" in result
+ async def test_format_includes_churn_status(self):
+ active = await self._create_account(name="Active")
+ churned = await self._create_account(name="Churned", churned_at=datetime(2026, 8, 1, 12, 30, tzinfo=UTC))
+
+ active_result = await AccountContext(
+ team=self.team, user=self.user, account_id=str(active.id)
+ ).execute_and_format()
+ churned_result = await AccountContext(
+ team=self.team, user=self.user, account_id=str(churned.id)
+ ).execute_and_format()
+
+ assert "**Churned:** Not churned" in active_result
+ assert "**Churned:** 2026-08-01T12:30:00+00:00" in churned_result
+
async def test_format_includes_relationships(self):
account = await self._create_account(name="Acme Corp")
definition = await AccountRelationshipDefinition.objects.unscoped().acreate(team=self.team, name="CSM")
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index 80803acaca1c..99ff092bedb7 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -245,6 +245,7 @@
"external_id",
"created_at",
"updated_at",
+ "churned_at",
"stripe_customer_id",
"hubspot_deal_id",
"billing_id",
@@ -553,6 +554,10 @@
},
"type": "array"
},
+ "includeChurned": {
+ "description": "Include churned accounts. Churned accounts are hidden by default.",
+ "type": "boolean"
+ },
"kind": {
"const": "AccountsTableQuery",
"type": "string"
diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.ts
index 736ac41cd6b7..6342b4ed9272 100644
--- a/frontend/src/queries/schema/schema-general.ts
+++ b/frontend/src/queries/schema/schema-general.ts
@@ -2813,6 +2813,7 @@ export enum AccountsTableAccountField {
ExternalId = 'external_id',
CreatedAt = 'created_at',
UpdatedAt = 'updated_at',
+ ChurnedAt = 'churned_at',
StripeCustomerId = 'stripe_customer_id',
HubspotDealId = 'hubspot_deal_id',
BillingId = 'billing_id',
@@ -3034,6 +3035,8 @@ export interface AccountsTableQueryResponse extends AnalyticsQueryResponseBase {
export interface AccountsTableQuery extends DataNode<AccountsTableQueryResponse> {
kind: NodeKind.AccountsTableQuery
+ /** Include churned accounts. Churned accounts are hidden by default. */
+ includeChurned?: boolean
/** Columns to load for each account. Account identity fields are always returned. */
columns: AccountsTableColumn[]
/** Filters are combined with AND. Values within tag and assignment filters use OR. */
diff --git a/posthog/hogql/database/test/__snapshots__/test_database.ambr b/posthog/hogql/database/test/__snapshots__/test_database.ambr
index 85b934c3408b..916cd5025e76 100644
--- a/posthog/hogql/database/test/__snapshots__/test_database.ambr
+++ b/posthog/hogql/database/test/__snapshots__/test_database.ambr
@@ -2758,6 +2758,16 @@
"table": null,
"type": "datetime"
},
+ "churned_at": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "churned_at",
+ "id": null,
+ "name": "churned_at",
+ "schema_valid": true,
+ "table": null,
+ "type": "datetime"
+ },
"tags": {
"chain": null,
"fields": [
@@ -12978,6 +12988,16 @@
"table": null,
"type": "datetime"
},
+ "churned_at": {
+ "chain": null,
+ "fields": null,
+ "hogql_value": "churned_at",
+ "id": null,
+ "name": "churned_at",
+ "schema_valid": true,
+ "table": null,
+ "type": "datetime"
+ },
"tags": {
"chain": null,
"fields": [
diff --git a/posthog/schema.py b/posthog/schema.py
index 0140d6150887..47537fcab76d 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -24431,6 +24431,10 @@ class AccountsTableQuery(BaseModel):
default=None,
description=("Filters are combined with AND. Values within tag and assignment filters use OR."),
)
+ includeChurned: bool | None = Field(
+ default=None,
+ description="Include churned accounts. Churned accounts are hidden by default.",
+ )
kind: Literal["AccountsTableQuery"] = "AccountsTableQuery"
limit: conint(ge=1) | None = None
metrics: (
diff --git a/posthog/schema_enums.py b/posthog/schema_enums.py
index d7aba1e74d1e..e3b60377bde7 100644
--- a/posthog/schema_enums.py
+++ b/posthog/schema_enums.py
@@ -35,6 +35,7 @@ class AccountsTableAccountField(StrEnum):
EXTERNAL_ID = "external_id"
CREATED_AT = "created_at"
UPDATED_AT = "updated_at"
+ CHURNED_AT = "churned_at"
STRIPE_CUSTOMER_ID = "stripe_customer_id"
HUBSPOT_DEAL_ID = "hubspot_deal_id"
BILLING_ID = "billing_id"
diff --git a/products/customer_analytics/backend/facade/api.py b/products/customer_analytics/backend/facade/api.py
index 6625326ad4a2..3978fb557548 100644
--- a/products/customer_analytics/backend/facade/api.py
+++ b/products/customer_analytics/backend/facade/api.py
@@ -220,6 +220,7 @@ def get_account_context_data(
name=account.name,
external_id=account.external_id,
created_at=account.created_at,
+ churned_at=account.churned_at,
properties=_to_account_properties(account.properties),
tags=_account_tags(account),
notes=_account_notes(account),
@@ -359,8 +360,8 @@ def _to_external_account(account: Account) -> contracts.ExternalAccount:
"""Map an account to the verbatim external wire shape.
``properties`` is the exact ``model_dump(mode="json")`` of the validated
- pydantic properties and ``tags`` the sorted tag names — byte-identical to
- what the CDP worker consumed before this moved behind the facade.
+ pydantic properties, ``tags`` the sorted tag names, and ``churned_at`` the
+ account lifecycle timestamp.
``custom_properties`` includes every team definition keyed by name, with the
account's active value (scalar) or ``None`` when unset, so workflow result
@@ -394,6 +395,7 @@ def _to_external_account(account: Account) -> contracts.ExternalAccount:
id=str(account.id),
external_id=account.external_id,
name=account.name,
+ churned_at=account.churned_at,
properties=account.properties.model_dump(mode="json"),
tags=sorted(account.tagged_items.values_list("tag__name", flat=True)),
relationships=relationships,
@@ -566,6 +568,7 @@ def list_external_accounts(
contracts.ExternalAccountListItem(
external_id=cast(str, account.external_id),
name=account.name,
+ churned_at=account.churned_at,
relationships=relationships_by_account.get(account.id, {}),
)
for account in accounts
@@ -656,13 +659,15 @@ def update_external_account(
relationship_assignments: dict[str, int | None],
tags: list[str] | None,
tags_mode: str,
+ churned_at: datetime | None = None,
+ churned_at_provided: bool = False,
workflow_id: str | None = None,
) -> contracts.ExternalAccountUpdateResult:
- """Apply relationship assignments and tags to an account, transactionally, for the
- external API.
+ """Apply relationship assignments, tags, and churn state to an account,
+ transactionally, for the external API.
- Assignments and tags are all-or-nothing — a tag failure must not leave the
- relationship changes committed. Returns a result the view maps to the exact HTTP
+ All changes are all-or-nothing — a tag failure must not leave relationship or churn
+ changes committed. Returns a result the view maps to the exact HTTP
status/body: not found, a per-assignment failure (unknown definition, non-member
user), a generic write failure, or success carrying the re-serialized account.
"""
@@ -684,6 +689,8 @@ def update_external_account(
return error_result
if tags is not None:
_apply_external_tags(account, tags, tags_mode, workflow_id=workflow_id)
+ if churned_at_provided:
+ update_account(account, churned_at=churned_at)
except Exception as e:
capture_exception(e, {"team_id": team_id, "external_id": external_id, "account_id": str(account.id)})
return contracts.ExternalAccountUpdateResult(error=contracts.ExternalAccountUpdateError.UPDATE_FAILED)
@@ -2200,6 +2207,7 @@ def _to_account_view(account: Account) -> contracts.AccountView:
tags=_account_view_tags(account),
notebooks=_account_view_notebooks(account),
slack_summary_cadence=account.slack_summary_cadence,
+ churned_at=account.churned_at,
created_at=account.created_at,
created_by=account.created_by_id,
updated_at=account.updated_at,
@@ -2228,6 +2236,8 @@ def _account_table_field_values(
values[field] = account.created_at.isoformat() if account.created_at else None
case contracts.AccountTableField.UPDATED_AT:
values[field] = account.updated_at.isoformat() if account.updated_at else None
+ case contracts.AccountTableField.CHURNED_AT:
+ values[field] = account.churned_at.isoformat() if account.churned_at else None
case contracts.AccountTableField.STRIPE_CUSTOMER_ID:
values[field] = properties.stripe_customer_id
case contracts.AccountTableField.HUBSPOT_DEAL_ID:
@@ -2491,6 +2501,7 @@ def _apply_account_table_sort(
contracts.AccountTableField.EXTERNAL_ID: "external_id",
contracts.AccountTableField.CREATED_AT: "created_at",
contracts.AccountTableField.UPDATED_AT: "updated_at",
+ contracts.AccountTableField.CHURNED_AT: "churned_at",
}
if direct_field := direct_fields.get(sort.account_field):
queryset = queryset.annotate(_account_table_sort=F(direct_field))
@@ -2573,6 +2584,7 @@ def query_accounts_metrics(
user_access_control: "UserAccessControl",
filters: tuple[contracts.AccountTableFilter, ...],
metrics: tuple[contracts.AccountTableMetric, ...],
+ include_churned: bool = False,
) -> list[float | int | None]:
definition_ids = frozenset(
metric.definition_id
@@ -2589,8 +2601,11 @@ def query_accounts_metrics(
if DATA_TYPE_BY_DISPLAY_TYPE[custom_property_display_types[definition_id]] != DataType.NUMERIC:
raise InvalidAccountTableColumn("Account table metrics require numeric custom properties.")
+ accounts = _accounts_queryset(team_id, user_access_control)
+ if not include_churned:
+ accounts = accounts.filter(churned_at__isnull=True)
accounts = _apply_account_table_filters(
- _accounts_queryset(team_id, user_access_control),
+ accounts,
team_id=team_id,
filters=filters,
custom_property_display_types=custom_property_display_types,
@@ -2654,6 +2669,7 @@ def query_accounts_table(
sort: contracts.AccountTableSort | None,
offset: int,
limit: int,
+ include_churned: bool = False,
) -> contracts.AccountTablePage:
custom_property_display_types = _validate_account_table_definitions(
team_id=team_id,
@@ -2662,8 +2678,11 @@ def query_accounts_table(
sort=sort,
)
+ queryset = _accounts_queryset(team_id, user_access_control)
+ if not include_churned:
+ queryset = queryset.filter(churned_at__isnull=True)
queryset = _apply_account_table_filters(
- _accounts_queryset(team_id, user_access_control),
+ queryset,
team_id=team_id,
filters=filters,
custom_property_display_types=custom_property_display_types,
@@ -2786,6 +2805,7 @@ def list_accounts_for_view(
search: str | None = None,
tags: list[str] | None = None,
all_roles_unassigned: bool = False,
+ include_churned: bool = False,
ordering: str | None = None,
) -> tuple[list[contracts.AccountView], int]:
"""The accounts list endpoint, behind the facade: team + object-level access filtering,
@@ -2797,6 +2817,9 @@ def list_accounts_for_view(
Prefetch("tagged_items", queryset=TaggedItem.objects.select_related("tag"), to_attr="prefetched_tags"),
)
+ if not include_churned:
+ queryset = queryset.filter(churned_at__isnull=True)
+
if search:
queryset = queryset.filter(Q(name__icontains=search) | Q(external_id__icontains=search))
@@ -2858,6 +2881,7 @@ def update_account(
external_id: str | None | _Unset = _UNSET,
properties: "dict | _ModelAccountProperties | _Unset" = _UNSET,
slack_summary_cadence: "str | None | _Unset" = _UNSET,
+ churned_at: "datetime | None | _Unset" = _UNSET,
allow_matching_updates: bool = False,
) -> Account:
"""Field-write primitive shared by every account update path. Only the fields passed are
@@ -2887,6 +2911,9 @@ def update_account(
if not isinstance(slack_summary_cadence, _Unset):
account.slack_summary_cadence = slack_summary_cadence
update_fields.append("slack_summary_cadence")
+ if not isinstance(churned_at, _Unset):
+ account.churned_at = churned_at
+ update_fields.append("churned_at")
if update_fields:
account.save(update_fields=update_fields)
if matching_expanded:
@@ -2903,6 +2930,7 @@ def create_account(
properties: "dict | _ModelAccountProperties | None" = None,
tags: list[str] | None = None,
slack_summary_cadence: str | None = None,
+ churned_at: datetime | None = None,
was_impersonated: bool = False,
trigger: Trigger | None = None,
) -> Account:
@@ -2920,6 +2948,7 @@ def create_account(
external_id=_cap_to_field_length("external_id", external_id) if external_id is not None else None,
_properties=validated.model_dump(mode="json", exclude_unset=True),
slack_summary_cadence=slack_summary_cadence,
+ churned_at=churned_at,
)
_set_tags(tags, account, actor=created_by)
except PydanticValidationError as exc:
@@ -2955,6 +2984,7 @@ def create_account_for_view(
properties=input.properties,
tags=input.tags,
slack_summary_cadence=input.slack_summary_cadence,
+ churned_at=input.churned_at,
was_impersonated=was_impersonated,
)
return _to_account_view(account)
@@ -2985,6 +3015,8 @@ def update_account_for_view(
update_kwargs["properties"] = input.properties if input.properties is not None else {}
if input.slack_summary_cadence_provided:
update_kwargs["slack_summary_cadence"] = input.slack_summary_cadence
+ if input.churned_at_provided:
+ update_kwargs["churned_at"] = input.churned_at
update_kwargs["allow_matching_updates"] = allow_matching_updates
try:
diff --git a/products/customer_analytics/backend/facade/contracts.py b/products/customer_analytics/backend/facade/contracts.py
index 6a3784ff0e45..ca12fb0bbf30 100644
--- a/products/customer_analytics/backend/facade/contracts.py
+++ b/products/customer_analytics/backend/facade/contracts.py
@@ -184,6 +184,7 @@ class AccountTableField(str, Enum):
EXTERNAL_ID = "external_id"
CREATED_AT = "created_at"
UPDATED_AT = "updated_at"
+ CHURNED_AT = "churned_at"
STRIPE_CUSTOMER_ID = "stripe_customer_id"
HUBSPOT_DEAL_ID = "hubspot_deal_id"
BILLING_ID = "billing_id"
@@ -369,6 +370,7 @@ class AccountContextData:
name: str
external_id: str | None
created_at: datetime | None
+ churned_at: datetime | None
properties: AccountProperties
tags: list[str] = field(default_factory=list)
notes: list[AccountNote] = field(default_factory=list)
@@ -380,10 +382,9 @@ class ExternalAccount:
"""The account shape the external (CDP worker) API serializes verbatim.
``properties`` is carried as a plain dict set to exactly
- ``account.properties.model_dump(mode="json")`` so the JSON the CDP worker
- consumes stays byte-identical to the pre-facade response — a validated
- pydantic pass-through, not a re-typed projection. ``id`` is the stringified
- UUID, matching the wire shape.
+ ``account.properties.model_dump(mode="json")`` — a validated pydantic
+ pass-through, not a re-typed projection. ``id`` is the stringified UUID,
+ and ``churned_at`` carries the account lifecycle timestamp.
``custom_properties`` contains every team-defined custom property definition
keyed by definition name, with the account's current scalar value (or ``None``
@@ -394,6 +395,7 @@ class ExternalAccount:
id: str
external_id: str | None
name: str
+ churned_at: datetime | None
properties: dict
tags: list[str] = field(default_factory=list)
relationships: dict[str, list[dict]] = field(default_factory=dict)
@@ -416,11 +418,12 @@ class ExternalAccountAssignment:
@dataclass(frozen=True)
class ExternalAccountListItem:
- """One account row on the external list wire shape, with active relationship
- assignments to current organization members keyed by definition name."""
+ """One account row on the external list wire shape, with its churn timestamp and
+ active relationship assignments to current organization members keyed by definition name."""
external_id: str
name: str
+ churned_at: datetime | None
relationships: dict[str, list[ExternalAccountAssignment]] = field(default_factory=dict)
@@ -517,6 +520,7 @@ class AccountView:
tags: list[str] = field(default_factory=list)
notebooks: list[str] = field(default_factory=list)
slack_summary_cadence: str | None = None
+ churned_at: datetime | None = None
created_at: datetime | None = None
created_by: int | None = None
updated_at: datetime | None = None
@@ -761,6 +765,7 @@ class CreateAccountInput:
properties: dict = field(default_factory=dict)
tags: list[str] | None = None
slack_summary_cadence: str | None = None
+ churned_at: datetime | None = None
@dataclass(frozen=True)
@@ -777,10 +782,12 @@ class UpdateAccountInput:
properties: dict | None = None
tags: list[str] | None = None
slack_summary_cadence: str | None = None
- # Distinguishes "external_id omitted" from "external_id explicitly set to null".
+ churned_at: datetime | None = None
+ # Distinguishes omitted fields from fields explicitly set to null.
external_id_provided: bool = False
properties_provided: bool = False
slack_summary_cadence_provided: bool = False
+ churned_at_provided: bool = False
@dataclass(frozen=True)
diff --git a/products/customer_analytics/backend/facade/hogql.py b/products/customer_analytics/backend/facade/hogql.py
index 425b5646dc6a..560f0ce9ab59 100644
--- a/products/customer_analytics/backend/facade/hogql.py
+++ b/products/customer_analytics/backend/facade/hogql.py
@@ -671,6 +671,9 @@ accounts: PostgresTable = PostgresTable(
"updated_at": DateTimeDatabaseField(
name="updated_at", nullable=True, description="When the account record was last updated."
),
+ "churned_at": DateTimeDatabaseField(
+ name="churned_at", nullable=True, description="When the account churned; NULL if it has not churned."
+ ),
"tags": account_tags_lazy_join,
"notebooks": account_notebooks_lazy_join,
"custom_properties": account_custom_properties_lazy_join,
diff --git a/products/customer_analytics/backend/hogql_queries/accounts_table_query_runner.py b/products/customer_analytics/backend/hogql_queries/accounts_table_query_runner.py
index dcf874a806a6..06876f5407ac 100644
--- a/products/customer_analytics/backend/hogql_queries/accounts_table_query_runner.py
+++ b/products/customer_analytics/backend/hogql_queries/accounts_table_query_runner.py
@@ -232,6 +232,7 @@ class AccountsTableQueryRunner(AnalyticsQueryRunner[AccountsTableQueryResponse])
user_access_control=user_access_control,
filters=filters,
metrics=self._metrics(),
+ include_churned=bool(self.query.includeChurned),
)
return AccountsTableQueryResponse(
results=[],
@@ -248,6 +249,7 @@ class AccountsTableQueryRunner(AnalyticsQueryRunner[AccountsTableQueryResponse])
sort=self._sort(),
offset=offset,
limit=limit,
+ include_churned=bool(self.query.includeChurned),
)
except api.InvalidAccountTableColumn as error:
raise ValidationError(str(error)) from error
diff --git a/products/customer_analytics/backend/hogql_queries/test/test_accounts_table_query_runner.py b/products/customer_analytics/backend/hogql_queries/test/test_accounts_table_query_runner.py
index 0094fdd1b057..8cf0614e0926 100644
--- a/products/customer_analytics/backend/hogql_queries/test/test_accounts_table_query_runner.py
+++ b/products/customer_analytics/backend/hogql_queries/test/test_accounts_table_query_runner.py
@@ -79,6 +79,7 @@ class TestAccountsTableQueryRunner(BaseTest):
team_id=self.team.id,
name="Acme",
external_id="acme-1",
+ churned_at=datetime(2026, 1, 1, 10, 0, tzinfo=UTC),
_properties={"stripe_customer_id": "cus_123"},
)
@@ -132,6 +133,7 @@ class TestAccountsTableQueryRunner(BaseTest):
AccountsTableQuery(
columns=[
AccountsTableAccountFieldColumn(field=AccountsTableAccountField.STRIPE_CUSTOMER_ID),
+ AccountsTableAccountFieldColumn(field=AccountsTableAccountField.CHURNED_AT),
AccountsTableTagsColumn(),
AccountsTableNoteCountColumn(),
AccountsTableRelationshipColumn(definitionId=str(relationship_definition.id)),
@@ -143,12 +145,16 @@ class TestAccountsTableQueryRunner(BaseTest):
),
],
filters=[],
+ includeChurned=True,
)
)
rows = {row.id: row for row in response.results}
full_row = rows[str(account.id)]
- assert full_row.accountFields == {"stripe_customer_id": "cus_123"}
+ assert full_row.accountFields == {
+ "stripe_customer_id": "cus_123",
+ "churned_at": "2026-01-01T10:00:00+00:00",
+ }
assert full_row.tags == ["enterprise", "priority"]
assert full_row.noteCount == 1
assert full_row.relationships == {str(relationship_definition.id): [self.user.id]}
@@ -159,6 +165,7 @@ class TestAccountsTableQueryRunner(BaseTest):
assert [point.value for point in full_row.customPropertyHistory[str(numeric_definition.id)]] == [10.0, 20.0]
empty_row = rows[str(empty_account.id)]
+ assert empty_row.accountFields == {"stripe_customer_id": None, "churned_at": None}
assert empty_row.tags == []
assert empty_row.noteCount == 0
assert empty_row.relationships == {str(relationship_definition.id): []}
@@ -168,6 +175,31 @@ class TestAccountsTableQueryRunner(BaseTest):
}
assert empty_row.customPropertyHistory == {str(numeric_definition.id): []}
+ @parameterized.expand(
+ [
+ ("default", False, ["Active"], 1),
+ ("include_churned", True, ["Active", "Churned"], 2),
+ ]
+ )
+ def test_churned_account_visibility(
+ self, _name: str, include_churned: bool, expected_names: list[str], expected_count: int
+ ) -> None:
+ create_account(team_id=self.team.id, name="Active")
+ create_account(team_id=self.team.id, name="Churned", churned_at=datetime(2026, 1, 1, tzinfo=UTC))
+
+ rows = self._run(AccountsTableQuery(columns=[], filters=[], includeChurned=include_churned)).results
+ metrics = self._run(
+ AccountsTableQuery(
+ columns=[],
+ filters=[],
+ metrics=[AccountsTableCountMetric()],
+ includeChurned=include_churned,
+ )
+ ).metricsResults
+
+ assert sorted(row.name for row in rows) == expected_names
+ assert metrics == [expected_count]
+
def test_calculates_typed_metrics_against_the_filtered_account_set(self) -> None:
definition = create_custom_property_definition(
team_id=self.team.id,
diff --git a/products/customer_analytics/backend/migrations/0032_account_churned_at.py b/products/customer_analytics/backend/migrations/0032_account_churned_at.py
new file mode 100644
index 000000000000..18c6094115a3
--- /dev/null
+++ b/products/customer_analytics/backend/migrations/0032_account_churned_at.py
@@ -0,0 +1,15 @@
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("customer_analytics", "0031_featurerequest_featurerequestproductarea_and_more"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="account",
+ name="churned_at",
+ field=models.DateTimeField(blank=True, null=True),
+ ),
+ ]
diff --git a/products/customer_analytics/backend/migrations/max_migration.txt b/products/customer_analytics/backend/migrations/max_migration.txt
index f219f1a5cd83..41c3e389e825 100644
--- a/products/customer_analytics/backend/migrations/max_migration.txt
+++ b/products/customer_analytics/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0031_featurerequest_featurerequestproductarea_and_more
+0032_account_churned_at
diff --git a/products/customer_analytics/backend/models/account.py b/products/customer_analytics/backend/models/account.py
index c5747c7c9eb6..9f1163f25727 100644
--- a/products/customer_analytics/backend/models/account.py
+++ b/products/customer_analytics/backend/models/account.py
@@ -62,6 +62,7 @@ class Account(TeamScopedRootMixin, UUIDModel, CreatedMetaFields, UpdatedMetaFiel
external_id = models.CharField(max_length=400, null=True, blank=True)
name = models.CharField(max_length=400)
+ churned_at = models.DateTimeField(null=True, blank=True)
_properties = JSONField(default=dict, db_column="properties")
# NULL = periodic Slack channel summaries off for this account.
slack_summary_cadence = models.CharField(max_length=10, choices=SlackSummaryCadence.choices, null=True, blank=True)
diff --git a/products/customer_analytics/backend/presentation/views/external.py b/products/customer_analytics/backend/presentation/views/external.py
index 5839ddb4f09e..ec33cde8bc5f 100644
--- a/products/customer_analytics/backend/presentation/views/external.py
+++ b/products/customer_analytics/backend/presentation/views/external.py
@@ -190,6 +190,7 @@ def _external_account_body(account: contracts.ExternalAccount) -> dict[str, Any]
"id": account.id,
"external_id": account.external_id,
"name": account.name,
+ "churned_at": account.churned_at,
"properties": account.properties,
"tags": account.tags,
"relationships": account.relationships,
@@ -250,6 +251,11 @@ class ExternalAccountUpdateSerializer(serializers.Serializer):
default="add",
help_text="How to apply tags: add to, replace, or remove from the existing set.",
)
+ churned_at = serializers.DateTimeField(
+ required=False,
+ allow_null=True,
+ help_text="When the account churned. Set to null to mark it as active again.",
+ )
def validate_relationships(self, value: dict[str, Any]) -> dict[str, int | None]:
return {name: self._normalize_assignee(name, assignee) for name, assignee in value.items()}
@@ -291,6 +297,10 @@ class ExternalAccountSerializer(serializers.Serializer):
allow_null=True, help_text="External account key — the group key the account is linked to."
)
name = serializers.CharField(help_text="Human-readable account name.")
+ churned_at = serializers.DateTimeField(
+ allow_null=True,
+ help_text="When the account churned, or null if it has not churned.",
+ )
properties = serializers.DictField(
child=serializers.JSONField(help_text="Property value: a string or null."),
help_text="Typed account properties: external-system ids. Role assignments live under `relationships`.",
@@ -319,7 +329,7 @@ class ExternalAccountView(APIView):
"""
GET /api/customer_analytics/external/account?external_id=<external_id> — Fetch account data
POST /api/customer_analytics/external/account — Create an account (no-op if it already exists)
- PATCH /api/customer_analytics/external/account — Update an account's role contacts and tags
+ PATCH /api/customer_analytics/external/account — Update an account's relationships, tags, and churn state
Authenticated via Bearer token (team secret_api_token) in Authorization header.
"""
@@ -414,6 +424,8 @@ class ExternalAccountView(APIView):
relationship_assignments=data.get("relationships") or {},
tags=data["tags"] if "tags" in data else None,
tags_mode=data.get("tags_mode", "add"),
+ churned_at=data.get("churned_at"),
+ churned_at_provided="churned_at" in data,
workflow_id=_workflow_id_from_request(request),
)
if result.account is None:
@@ -470,6 +482,10 @@ class ExternalAccountListAssignmentSerializer(serializers.Serializer):
class ExternalAccountListItemSerializer(serializers.Serializer):
external_id = serializers.CharField(help_text="External account key used by downstream systems.")
name = serializers.CharField(help_text="Human-readable account name.")
+ churned_at = serializers.DateTimeField(
+ allow_null=True,
+ help_text="When the account churned, or null if it has not churned.",
+ )
relationships = serializers.DictField(
child=ExternalAccountListAssignmentSerializer(many=True),
help_text=(
@@ -538,7 +554,7 @@ class ExternalAccountListView(APIView):
},
summary="List external customer analytics accounts",
description=(
- "List accounts with external IDs and their active relationship assignments. "
+ "List accounts with external IDs, churn timestamps, and active relationship assignments. "
"Requires a project secret API key with the `account:read` scope."
),
)
diff --git a/products/customer_analytics/backend/presentation/views/serializers.py b/products/customer_analytics/backend/presentation/views/serializers.py
index 71ae0a33ca08..531f932b75e9 100644
--- a/products/customer_analytics/backend/presentation/views/serializers.py
+++ b/products/customer_analytics/backend/presentation/views/serializers.py
@@ -308,6 +308,11 @@ class AccountSerializer(DataclassSerializer):
"(daily, weekly, or monthly). Null means summaries are off."
),
)
+ churned_at = serializers.DateTimeField(
+ required=False,
+ allow_null=True,
+ help_text="When the account churned. Null means the account has not churned.",
+ )
created_at = serializers.DateTimeField(read_only=True)
created_by = serializers.IntegerField(read_only=True, allow_null=True)
updated_at = serializers.DateTimeField(read_only=True, allow_null=True)
@@ -323,6 +328,7 @@ class AccountSerializer(DataclassSerializer):
"tags",
"notebooks",
"slack_summary_cadence",
+ "churned_at",
"created_at",
"created_by",
"updated_at",
diff --git a/products/customer_analytics/backend/presentation/views/views.py b/products/customer_analytics/backend/presentation/views/views.py
index 8bed37824c77..5d36d0f8d783 100644
--- a/products/customer_analytics/backend/presentation/views/views.py
+++ b/products/customer_analytics/backend/presentation/views/views.py
@@ -1088,6 +1088,14 @@ class AccountViewSet(
required=False,
description="When true, returns only accounts where no user actively holds any relationship.",
),
+ OpenApiParameter(
+ name="include_churned",
+ type=OpenApiTypes.BOOL,
+ location=OpenApiParameter.QUERY,
+ required=False,
+ default=False,
+ description="Include churned accounts. Churned accounts are hidden by default.",
+ ),
OpenApiParameter(
name="ordering",
type=OpenApiTypes.STR,
@@ -1112,6 +1120,7 @@ class AccountViewSet(
search=request.query_params.get("search", "").strip() or None,
tags=tags,
all_roles_unassigned=request.query_params.get("all_roles_unassigned", "").lower() == "true",
+ include_churned=request.query_params.get("include_churned", "").lower() == "true",
ordering=ordering,
),
AccountSerializer,
@@ -1204,6 +1213,7 @@ class AccountViewSet(
properties=data.properties or {},
tags=_account_tags_input(serializer),
slack_summary_cadence=data.slack_summary_cadence,
+ churned_at=data.churned_at,
),
user=cast(User, request.user),
was_impersonated=is_impersonated(request),
@@ -1237,6 +1247,8 @@ class AccountViewSet(
if "slack_summary_cadence" in request.data
else None,
slack_summary_cadence_provided="slack_summary_cadence" in request.data,
+ churned_at=data.churned_at if "churned_at" in request.data else None,
+ churned_at_provided="churned_at" in request.data,
),
user_access_control=self.user_access_control,
required_level=_object_required_level(request, write=True),
diff --git a/products/customer_analytics/backend/test/test_external.py b/products/customer_analytics/backend/test/test_external.py
index 79503d395c4c..e5eefbfcd1ec 100644
--- a/products/customer_analytics/backend/test/test_external.py
+++ b/products/customer_analytics/backend/test/test_external.py
@@ -121,12 +121,16 @@ class TestExternalAccountAPI(APIBaseTest):
self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
def test_get_account_returns_fields(self):
+ self.account.churned_at = datetime(2026, 8, 1, 12, 30, tzinfo=UTC)
+ self.account.save(update_fields=["churned_at"])
+
response = self._get()
self.assertEqual(response.status_code, status.HTTP_200_OK)
data = response.json()
self.assertEqual(data["id"], str(self.account.id))
self.assertEqual(data["external_id"], "acme-1")
self.assertEqual(data["name"], "Acme Corp")
+ self.assertEqual(data["churned_at"], "2026-08-01T12:30:00Z")
self.assertEqual(data["relationships"], {})
def test_get_account_returns_active_relationships(self):
@@ -179,6 +183,22 @@ class TestExternalAccountAPI(APIBaseTest):
response = self.client.patch(self.url, data={"external_id": "acme-1"}, format="json")
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
+ def test_patch_sets_and_clears_churned_at(self):
+ response = self._patch({"external_id": "acme-1", "churned_at": "2026-08-02T09:00:00Z"})
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.json()["churned_at"], "2026-08-02T09:00:00Z")
+ self.account.refresh_from_db()
+ assert self.account.churned_at is not None
+ self.assertEqual(self.account.churned_at.isoformat(), "2026-08-02T09:00:00+00:00")
+
+ response = self._patch({"external_id": "acme-1", "churned_at": None})
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertIsNone(response.json()["churned_at"])
+ self.account.refresh_from_db()
+ self.assertIsNone(self.account.churned_at)
+
def test_patch_requires_external_id(self):
response = self._patch({"tags": ["enterprise"]})
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
diff --git a/products/customer_analytics/backend/test/test_external_list.py b/products/customer_analytics/backend/test/test_external_list.py
index 62b31810d298..28e5ba865cda 100644
--- a/products/customer_analytics/backend/test/test_external_list.py
+++ b/products/customer_analytics/backend/test/test_external_list.py
@@ -170,7 +170,12 @@ class TestExternalAccountListAPI(APIBaseTest):
self.user.save(update_fields=["first_name", "last_name"])
colleague = User.objects.create_and_join(self.organization, "[email protected]", None)
ae_definition = self._create_definition("Account executive", is_single_holder=False)
- account = create_account(team_id=self.team.id, name="Acme", external_id="org-1")
+ account = create_account(
+ team_id=self.team.id,
+ name="Acme",
+ external_id="org-1",
+ churned_at=datetime(2026, 8, 1, 12, 30, tzinfo=UTC),
+ )
self._assign(account, self.user)
self._assign(account, self.user, definition=ae_definition)
self._assign(account, colleague, definition=ae_definition)
@@ -184,6 +189,7 @@ class TestExternalAccountListAPI(APIBaseTest):
row = data["results"][0]
self.assertEqual(row["external_id"], "org-1")
self.assertEqual(row["name"], "Acme")
+ self.assertEqual(row["churned_at"], "2026-08-01T12:30:00Z")
self.assertEqual(
row["relationships"],
{
@@ -228,6 +234,7 @@ class TestExternalAccountListAPI(APIBaseTest):
{
"external_id": "org-1",
"name": "Acme",
+ "churned_at": None,
"relationships": {},
}
],
diff --git a/products/customer_analytics/backend/test/test_views.py b/products/customer_analytics/backend/test/test_views.py
index a4dbcd16c543..d968b3d89542 100644
--- a/products/customer_analytics/backend/test/test_views.py
+++ b/products/customer_analytics/backend/test/test_views.py
@@ -458,6 +458,20 @@ class TestAccountViewSet(APIBaseTest):
self.assertEqual(data["name"], "Bare Account")
self.assertIsNone(data["external_id"])
self.assertEqual(data["properties"], {})
+ self.assertIsNone(data["churned_at"])
+
+ def test_create_with_churned_at(self):
+ response = self.client.post(
+ self.endpoint_base,
+ {"name": "Former customer", "churned_at": "2026-08-01T12:30:00Z"},
+ format="json",
+ )
+
+ self.assertEqual(status.HTTP_201_CREATED, response.status_code, response.json())
+ self.assertEqual(response.json()["churned_at"], "2026-08-01T12:30:00Z")
+ account = Account.objects.unscoped().get(id=response.json()["id"]) # nosemgrep: idor-lookup-without-team
+ assert account.churned_at is not None
+ self.assertEqual(account.churned_at.isoformat(), "2026-08-01T12:30:00+00:00")
def test_list(self):
a1 = self._create_account(name="Account 1")
@@ -474,6 +488,21 @@ class TestAccountViewSet(APIBaseTest):
ids = {r["id"] for r in data["results"]}
self.assertEqual(ids, {str(a1.id), str(a2.id)})
+ @parameterized.expand(
+ [
+ ("default", {}, {"Active"}),
+ ("include_churned", {"include_churned": "true"}, {"Active", "Churned"}),
+ ]
+ )
+ def test_list_churned_visibility(self, _name: str, params: dict[str, str], expected_names: set[str]) -> None:
+ self._create_account(name="Active")
+ self._create_account(name="Churned", churned_at=timezone.now())
+
+ response = self.client.get(self.endpoint_base, data=params)
+
+ self.assertEqual(status.HTTP_200_OK, response.status_code)
+ self.assertEqual({account["name"] for account in response.json()["results"]}, expected_names)
+
def test_retrieve(self):
account = self._create_account(
external_id="ext-1",
@@ -517,6 +546,24 @@ class TestAccountViewSet(APIBaseTest):
self.assertEqual(account.name, "Renamed")
self.assertEqual(account.properties.sfdc_id, "001xx")
+ def test_update_and_clear_churned_at(self):
+ account = self._create_account()
+ url = f"{self.endpoint_base}{account.id}/"
+
+ response = self.client.patch(url, {"churned_at": "2026-08-02T09:00:00Z"}, format="json")
+
+ self.assertEqual(status.HTTP_200_OK, response.status_code, response.json())
+ self.assertEqual(response.json()["churned_at"], "2026-08-02T09:00:00Z")
+ account.refresh_from_db()
+ self.assertEqual(account.churned_at.isoformat(), "2026-08-02T09:00:00+00:00")
+
+ response = self.client.patch(url, {"churned_at": None}, format="json")
+
+ self.assertEqual(status.HTTP_200_OK, response.status_code, response.json())
+ self.assertIsNone(response.json()["churned_at"])
+ account.refresh_from_db()
+ self.assertIsNone(account.churned_at)
+
@parameterized.expand(
[
("member", OrganizationMembership.Level.MEMBER, status.HTTP_403_FORBIDDEN),
diff --git a/products/customer_analytics/frontend/components/Accounts/accountsTableQuery.test.ts b/products/customer_analytics/frontend/components/Accounts/accountsTableQuery.test.ts
index 6436dbeb7eaa..bc35078f0506 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountsTableQuery.test.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountsTableQuery.test.ts
@@ -133,6 +133,7 @@ describe('accountsTableQuery', () => {
)
expect(plan?.query.filters).toEqual([{ kind: 'account_id', accountId: RELATIONSHIP_ID }])
+ expect(plan?.query.includeChurned).toBe(true)
})
it('drops unsupported columns instead of changing runners', () => {
diff --git a/products/customer_analytics/frontend/components/Accounts/accountsTableQuery.ts b/products/customer_analytics/frontend/components/Accounts/accountsTableQuery.ts
index 5dc661b4a096..c0278eae2ef5 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountsTableQuery.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountsTableQuery.ts
@@ -266,6 +266,7 @@ export function buildAccountsTableQueryPlan(input: BuildAccountsTableQueryPlanIn
kind: NodeKind.AccountsTableQuery,
columns: columns.map(({ column }) => column),
filters,
+ includeChurned: input.accountIdFilter !== null,
sort,
tags: { ...CUSTOMER_ANALYTICS_DEFAULT_QUERY_TAGS, name: 'customer_analytics_accounts_list' },
},
diff --git a/products/customer_analytics/frontend/generated/api.schemas.ts b/products/customer_analytics/frontend/generated/api.schemas.ts
index d75f6cbacb3e..2324c85d4f63 100644
--- a/products/customer_analytics/frontend/generated/api.schemas.ts
+++ b/products/customer_analytics/frontend/generated/api.schemas.ts
@@ -29,6 +29,11 @@ export interface ExternalAccountListItemApi {
external_id: string
/** Human-readable account name. */
name: string
+ /**
+ * When the account churned, or null if it has not churned.
+ * @nullable
+ */
+ churned_at: string | null
/** Active relationship assignments to current organization members, keyed by relationship definition name (e.g. 'CSM', 'Account executive'). Definitions with no active assignment are omitted. */
relationships: ExternalAccountListItemApiRelationships
}
@@ -267,6 +272,11 @@ export interface AccountApi {
* * `weekly` - weekly
* * `monthly` - monthly */
slack_summary_cadence?: SlackSummaryCadenceEnumApi | null
+ /**
+ * When the account churned. Null means the account has not churned.
+ * @nullable
+ */
+ churned_at?: string | null
readonly created_at: string
/** @nullable */
readonly created_by: number | null
@@ -439,6 +449,11 @@ export interface PatchedAccountApi {
* * `weekly` - weekly
* * `monthly` - monthly */
slack_summary_cadence?: SlackSummaryCadenceEnumApi | null
+ /**
+ * When the account churned. Null means the account has not churned.
+ * @nullable
+ */
+ churned_at?: string | null
readonly created_at?: string
/** @nullable */
readonly created_by?: number | null
@@ -1676,6 +1691,10 @@ export type AccountsListParams = {
* When true, returns only accounts where no user actively holds any relationship.
*/
all_roles_unassigned?: boolean
+ /**
+ * Include churned accounts. Churned accounts are hidden by default.
+ */
+ include_churned?: boolean
/**
* Number of results to return per page.
*/
diff --git a/products/customer_analytics/frontend/generated/api.ts b/products/customer_analytics/frontend/generated/api.ts
index ad4b023db945..5a9c3b04d33e 100644
--- a/products/customer_analytics/frontend/generated/api.ts
+++ b/products/customer_analytics/frontend/generated/api.ts
@@ -116,7 +116,7 @@ export const getCustomerAnalyticsExternalAccountsRetrieveUrl = (
}
/**
- * List accounts with external IDs and their active relationship assignments. Requires a project secret API key with the `account:read` scope.
+ * List accounts with external IDs, churn timestamps, and active relationship assignments. Requires a project secret API key with the `account:read` scope.
* @summary List external customer analytics accounts
*/
export const customerAnalyticsExternalAccountsRetrieve = async (
diff --git a/products/customer_analytics/frontend/generated/api.zod.ts b/products/customer_analytics/frontend/generated/api.zod.ts
index b56be425cd18..602648c3fc93 100644
--- a/products/customer_analytics/frontend/generated/api.zod.ts
+++ b/products/customer_analytics/frontend/generated/api.zod.ts
@@ -139,6 +139,10 @@ export const AccountsCreateBody = /* @__PURE__ */ zod
.describe(
"How often to generate an AI summary of the account's bound Slack channel (daily, weekly, or monthly). Null means summaries are off.\n\n\* `daily` - daily\n\* `weekly` - weekly\n\* `monthly` - monthly"
),
+ churned_at: zod.iso
+ .datetime({ offset: true })
+ .nullish()
+ .describe('When the account churned. Null means the account has not churned.'),
})
.describe('A Customer Analytics account — a logical grouping used to assign customer-success ownership.')
@@ -224,6 +228,10 @@ export const AccountsUpdateBody = /* @__PURE__ */ zod
.describe(
"How often to generate an AI summary of the account's bound Slack channel (daily, weekly, or monthly). Null means summaries are off.\n\n\* `daily` - daily\n\* `weekly` - weekly\n\* `monthly` - monthly"
),
+ churned_at: zod.iso
+ .datetime({ offset: true })
+ .nullish()
+ .describe('When the account churned. Null means the account has not churned.'),
})
.describe('A Customer Analytics account — a logical grouping used to assign customer-success ownership.')
@@ -285,6 +293,10 @@ export const AccountsPartialUpdateBody = /* @__PURE__ */ zod
.describe(
"How often to generate an AI summary of the account's bound Slack channel (daily, weekly, or monthly). Null means summaries are off.\n\n\* `daily` - daily\n\* `weekly` - weekly\n\* `monthly` - monthly"
),
+ churned_at: zod.iso
+ .datetime({ offset: true })
+ .nullish()
+ .describe('When the account churned. Null means the account has not churned.'),
})
.describe('A Customer Analytics account — a logical grouping used to assign customer-success ownership.')
diff --git a/products/customer_analytics/mcp/tools.yaml b/products/customer_analytics/mcp/tools.yaml
index b3ab15a690f8..16befc780af3 100644
--- a/products/customer_analytics/mcp/tools.yaml
+++ b/products/customer_analytics/mcp/tools.yaml
@@ -113,8 +113,9 @@ tools:
Create a new Customer Analytics account. An account is a logical container for assigning ownership across
the customer-success org. Provide `name` (required), optional `external_id` (CRM ID or similar), optional
`properties` to set external system identifiers (`stripe_customer_id`, `hubspot_deal_id`, `billing_id`,
- `sfdc_id`, `zendesk_id`), and optional `tags` to categorize the account. To assign users (CSM, account
- executive, ...), use `accounts-relationships-create` after creating the account.
+ `sfdc_id`, `zendesk_id`), optional `tags` to categorize the account, and optional `churned_at` as an
+ ISO-8601 timestamp (null means not churned). To assign users (CSM, account executive, ...), use
+ `accounts-relationships-create` after creating the account.
param_overrides:
properties:
description: >
@@ -191,18 +192,21 @@ tools:
description: >
List Customer Analytics accounts in the project, ordered by most recently created. Each result includes the
account `id`, `name`, `external_id`, typed `properties` (external identifiers stripe_customer_id,
- hubspot_deal_id, billing_id, sfdc_id, zendesk_id), `tags`, and creation/update metadata. User assignments
- (CSM, account executive, ...) live on account relationships — see `accounts-relationships-list`. Pass `tags`
- (JSON-encoded array, e.g. `["enterprise","priority"]`) to filter to accounts that have any of the listed
- tags. Use `accounts-retrieve` for a single account by id. The `properties` above are the built-in fields
- only; teams also define their own typed attributes as custom properties, which do not appear here. Call
- `custom-property-definitions-list` first to see what a team actually tracks on its accounts, rather than
- assuming the built-ins are the whole schema or guessing at property names. To link a user to a specific
- account rather than the bare list, deep-link it with the path `/customer_analytics/accounts/<id>/<tab>`
- (using the account `id`; tab is optional — one of notes/users/usage/spend, e.g.
- `/customer_analytics/accounts/<id>/usage`). This filters the list to that account, expands it, and opens the
- tab.
+ hubspot_deal_id, billing_id, sfdc_id, zendesk_id), `tags`, `churned_at` (null if not churned), and
+ creation/update metadata. User assignments (CSM, account executive, ...) live on account relationships — see
+ `accounts-relationships-list`. Pass `tags` (JSON-encoded array, e.g. `["enterprise","priority"]`) to filter
+ to accounts that have any of the listed tags. Use `accounts-retrieve` for a single account by id. The
+ `properties` above are the built-in fields only; teams also define their own typed attributes as custom
+ properties, which do not appear here. Call `custom-property-definitions-list` first to see what a team
+ actually tracks on its accounts, rather than assuming the built-ins are the whole schema or guessing at
+ property names. To link a user to a specific account rather than the bare list, deep-link it with the path
+ `/customer_analytics/accounts/<id>/<tab>` (using the account `id`; tab is optional — one of
+ notes/users/usage/spend, e.g. `/customer_analytics/accounts/<id>/usage`). This filters the list to that
+ account, expands it, and opens the tab. Churned accounts are hidden by default. Set `include_churned` to
+ true to include them.
param_overrides:
+ include_churned:
+ description: Include churned accounts. Churned accounts are hidden by default.
tags:
description: >
JSON-encoded array of tag names to filter by, e.g. `["enterprise","priority"]`. Returns accounts
@@ -284,7 +288,8 @@ tools:
title: Update account
description: >
Update fields on an existing Customer Analytics account. Accepts a subset of fields; unspecified fields are
- left unchanged. Pass `tags` to replace the full set of tags on the account.
+ left unchanged. Pass `tags` to replace the full set of tags. Set `churned_at` to an ISO-8601 timestamp to
+ mark the account as churned, or null to mark it as active again.
param_overrides:
properties:
description: >
@@ -364,13 +369,14 @@ tools:
title: Get account
description: >
Fetch a single Customer Analytics account by id. Returns the full account including typed `properties`
- (stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id external identifiers) and `tags`. User
- assignments (CSM, account executive, ...) live on account relationships — see `accounts-relationships-list`.
- These are the built-in fields only; a team's own typed attributes are custom properties and are not returned
- here. Call `custom-property-definitions-list` to see what the team tracks, then
- `accounts-custom-property-values-list` for this account's values. To link a user to this account rather than
- the bare list, deep-link it with the path `/customer_analytics/accounts/<id>/<tab>` (using the account `id`;
- tab is optional — one of notes/users/usage/spend, e.g. `/customer_analytics/accounts/<id>/usage`).
+ (stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id external identifiers), `tags`, and
+ `churned_at` (null if the account has not churned). User assignments (CSM, account executive, ...) live on
+ account relationships — see `accounts-relationships-list`. These are the built-in fields only; a team's own
+ typed attributes are custom properties and are not returned here. Call `custom-property-definitions-list` to
+ see what the team tracks, then `accounts-custom-property-values-list` for this account's values. To link a
+ user to this account rather than the bare list, deep-link it with the path
+ `/customer_analytics/accounts/<id>/<tab>` (using the account `id`; tab is optional — one of
+ notes/users/usage/spend, e.g. `/customer_analytics/accounts/<id>/usage`).
feature_flag: customer-analytics-csp
accounts-summaries-list:
operation: accounts_summaries_list
diff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.ts
index 56438d7acf9b..3731509d061c 100644
--- a/products/dashboards/frontend/generated/api.schemas.ts
+++ b/products/dashboards/frontend/generated/api.schemas.ts
@@ -8029,6 +8029,7 @@ export const AccountsTableAccountFieldApi = {
ExternalId: 'external_id',
CreatedAt: 'created_at',
UpdatedAt: 'updated_at',
+ ChurnedAt: 'churned_at',
StripeCustomerId: 'stripe_customer_id',
HubspotDealId: 'hubspot_deal_id',
BillingId: 'billing_id',
@@ -8245,6 +8246,8 @@ export interface AccountsTableQueryApi {
| AccountsTableCustomPropertyFilterApi
)[]
| null
+ /** Include churned accounts. Churned accounts are hidden by default. */
+ includeChurned?: boolean | null
kind?: 'AccountsTableQuery'
limit?: number | null
/** Aggregates to evaluate against the filtered account set. A metrics query skips row loading. */
diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.ts
index b4eeca15320b..e19882b296db 100644
--- a/products/product_analytics/frontend/generated/api.schemas.ts
+++ b/products/product_analytics/frontend/generated/api.schemas.ts
@@ -7268,6 +7268,7 @@ export const AccountsTableAccountFieldApi = {
ExternalId: 'external_id',
CreatedAt: 'created_at',
UpdatedAt: 'updated_at',
+ ChurnedAt: 'churned_at',
StripeCustomerId: 'stripe_customer_id',
HubspotDealId: 'hubspot_deal_id',
BillingId: 'billing_id',
@@ -7484,6 +7485,8 @@ export interface AccountsTableQueryApi {
| AccountsTableCustomPropertyFilterApi
)[]
| null
+ /** Include churned accounts. Churned accounts are hidden by default. */
+ includeChurned?: boolean | null
kind?: 'AccountsTableQuery'
limit?: number | null
/** Aggregates to evaluate against the filtered account set. A metrics query skips row loading. */
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index a3ae754eea2c..fc40d3b46fca 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -75,7 +75,7 @@
"feature_flag": "customer-analytics-csp"
},
"accounts-create": {
- "description": "Create a new Customer Analytics account. An account is a logical container for assigning ownership across the customer-success org. Provide `name` (required), optional `external_id` (CRM ID or similar), optional `properties` to set external system identifiers (`stripe_customer_id`, `hubspot_deal_id`, `billing_id`, `sfdc_id`, `zendesk_id`), and optional `tags` to categorize the account. To assign users (CSM, account executive, ...), use `accounts-relationships-create` after creating the account.",
+ "description": "Create a new Customer Analytics account. An account is a logical container for assigning ownership across the customer-success org. Provide `name` (required), optional `external_id` (CRM ID or similar), optional `properties` to set external system identifiers (`stripe_customer_id`, `hubspot_deal_id`, `billing_id`, `sfdc_id`, `zendesk_id`), optional `tags` to categorize the account, and optional `churned_at` as an ISO-8601 timestamp (null means not churned). To assign users (CSM, account executive, ...), use `accounts-relationships-create` after creating the account.",
"category": "Customer analytics",
"feature": "customer_analytics",
"summary": "Create account",
@@ -135,7 +135,7 @@
"feature_flag": "customer-analytics-csp"
},
"accounts-list": {
- "description": "List Customer Analytics accounts in the project, ordered by most recently created. Each result includes the account `id`, `name`, `external_id`, typed `properties` (external identifiers stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id), `tags`, and creation/update metadata. User assignments (CSM, account executive, ...) live on account relationships — see `accounts-relationships-list`. Pass `tags` (JSON-encoded array, e.g. `[\"enterprise\",\"priority\"]`) to filter to accounts that have any of the listed tags. Use `accounts-retrieve` for a single account by id. The `properties` above are the built-in fields only; teams also define their own typed attributes as custom properties, which do not appear here. Call `custom-property-definitions-list` first to see what a team actually tracks on its accounts, rather than assuming the built-ins are the whole schema or guessing at property names. To link a user to a specific account rather than the bare list, deep-link it with the path `/customer_analytics/accounts/<id>/<tab>` (using the account `id`; tab is optional — one of notes/users/usage/spend, e.g. `/customer_analytics/accounts/<id>/usage`). This filters the list to that account, expands it, and opens the tab.",
+ "description": "List Customer Analytics accounts in the project, ordered by most recently created. Each result includes the account `id`, `name`, `external_id`, typed `properties` (external identifiers stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id), `tags`, `churned_at` (null if not churned), and creation/update metadata. User assignments (CSM, account executive, ...) live on account relationships — see `accounts-relationships-list`. Pass `tags` (JSON-encoded array, e.g. `[\"enterprise\",\"priority\"]`) to filter to accounts that have any of the listed tags. Use `accounts-retrieve` for a single account by id. The `properties` above are the built-in fields only; teams also define their own typed attributes as custom properties, which do not appear here. Call `custom-property-definitions-list` first to see what a team actually tracks on its accounts, rather than assuming the built-ins are the whole schema or guessing at property names. To link a user to a specific account rather than the bare list, deep-link it with the path `/customer_analytics/accounts/<id>/<tab>` (using the account `id`; tab is optional — one of notes/users/usage/spend, e.g. `/customer_analytics/accounts/<id>/usage`). This filters the list to that account, expands it, and opens the tab. Churned accounts are hidden by default. Set `include_churned` to true to include them.",
"category": "Customer analytics",
"feature": "customer_analytics",
"summary": "List accounts",
@@ -210,7 +210,7 @@
"feature_flag": "customer-analytics-csp"
},
"accounts-partial-update": {
- "description": "Update fields on an existing Customer Analytics account. Accepts a subset of fields; unspecified fields are left unchanged. Pass `tags` to replace the full set of tags on the account.",
+ "description": "Update fields on an existing Customer Analytics account. Accepts a subset of fields; unspecified fields are left unchanged. Pass `tags` to replace the full set of tags. Set `churned_at` to an ISO-8601 timestamp to mark the account as churned, or null to mark it as active again.",
"category": "Customer analytics",
"feature": "customer_analytics",
"summary": "Update account",
@@ -270,7 +270,7 @@
"feature_flag": "customer-analytics-csp"
},
"accounts-retrieve": {
- "description": "Fetch a single Customer Analytics account by id. Returns the full account including typed `properties` (stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id external identifiers) and `tags`. User assignments (CSM, account executive, ...) live on account relationships — see `accounts-relationships-list`. These are the built-in fields only; a team's own typed attributes are custom properties and are not returned here. Call `custom-property-definitions-list` to see what the team tracks, then `accounts-custom-property-values-list` for this account's values. To link a user to this account rather than the bare list, deep-link it with the path `/customer_analytics/accounts/<id>/<tab>` (using the account `id`; tab is optional — one of notes/users/usage/spend, e.g. `/customer_analytics/accounts/<id>/usage`).",
+ "description": "Fetch a single Customer Analytics account by id. Returns the full account including typed `properties` (stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id external identifiers), `tags`, and `churned_at` (null if the account has not churned). User assignments (CSM, account executive, ...) live on account relationships — see `accounts-relationships-list`. These are the built-in fields only; a team's own typed attributes are custom properties and are not returned here. Call `custom-property-definitions-list` to see what the team tracks, then `accounts-custom-property-values-list` for this account's values. To link a user to this account rather than the bare list, deep-link it with the path `/customer_analytics/accounts/<id>/<tab>` (using the account `id`; tab is optional — one of notes/users/usage/spend, e.g. `/customer_analytics/accounts/<id>/usage`).",
"category": "Customer analytics",
"feature": "customer_analytics",
"summary": "Get account",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index b79e3f3e0d7c..c2c5467189be 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -75,7 +75,7 @@
"feature_flag": "customer-analytics-csp"
},
"accounts-create": {
- "description": "Create a new Customer Analytics account. An account is a logical container for assigning ownership across the customer-success org. Provide `name` (required), optional `external_id` (CRM ID or similar), optional `properties` to set external system identifiers (`stripe_customer_id`, `hubspot_deal_id`, `billing_id`, `sfdc_id`, `zendesk_id`), and optional `tags` to categorize the account. To assign users (CSM, account executive, ...), use `accounts-relationships-create` after creating the account.",
+ "description": "Create a new Customer Analytics account. An account is a logical container for assigning ownership across the customer-success org. Provide `name` (required), optional `external_id` (CRM ID or similar), optional `properties` to set external system identifiers (`stripe_customer_id`, `hubspot_deal_id`, `billing_id`, `sfdc_id`, `zendesk_id`), optional `tags` to categorize the account, and optional `churned_at` as an ISO-8601 timestamp (null means not churned). To assign users (CSM, account executive, ...), use `accounts-relationships-create` after creating the account.",
"category": "Customer analytics",
"feature": "customer_analytics",
"summary": "Create account",
@@ -135,7 +135,7 @@
"feature_flag": "customer-analytics-csp"
},
"accounts-list": {
- "description": "List Customer Analytics accounts in the project, ordered by most recently created. Each result includes the account `id`, `name`, `external_id`, typed `properties` (external identifiers stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id), `tags`, and creation/update metadata. User assignments (CSM, account executive, ...) live on account relationships — see `accounts-relationships-list`. Pass `tags` (JSON-encoded array, e.g. `[\"enterprise\",\"priority\"]`) to filter to accounts that have any of the listed tags. Use `accounts-retrieve` for a single account by id. The `properties` above are the built-in fields only; teams also define their own typed attributes as custom properties, which do not appear here. Call `custom-property-definitions-list` first to see what a team actually tracks on its accounts, rather than assuming the built-ins are the whole schema or guessing at property names. To link a user to a specific account rather than the bare list, deep-link it with the path `/customer_analytics/accounts/<id>/<tab>` (using the account `id`; tab is optional — one of notes/users/usage/spend, e.g. `/customer_analytics/accounts/<id>/usage`). This filters the list to that account, expands it, and opens the tab.",
+ "description": "List Customer Analytics accounts in the project, ordered by most recently created. Each result includes the account `id`, `name`, `external_id`, typed `properties` (external identifiers stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id), `tags`, `churned_at` (null if not churned), and creation/update metadata. User assignments (CSM, account executive, ...) live on account relationships — see `accounts-relationships-list`. Pass `tags` (JSON-encoded array, e.g. `[\"enterprise\",\"priority\"]`) to filter to accounts that have any of the listed tags. Use `accounts-retrieve` for a single account by id. The `properties` above are the built-in fields only; teams also define their own typed attributes as custom properties, which do not appear here. Call `custom-property-definitions-list` first to see what a team actually tracks on its accounts, rather than assuming the built-ins are the whole schema or guessing at property names. To link a user to a specific account rather than the bare list, deep-link it with the path `/customer_analytics/accounts/<id>/<tab>` (using the account `id`; tab is optional — one of notes/users/usage/spend, e.g. `/customer_analytics/accounts/<id>/usage`). This filters the list to that account, expands it, and opens the tab. Churned accounts are hidden by default. Set `include_churned` to true to include them.",
"category": "Customer analytics",
"feature": "customer_analytics",
"summary": "List accounts",
@@ -210,7 +210,7 @@
"feature_flag": "customer-analytics-csp"
},
"accounts-partial-update": {
- "description": "Update fields on an existing Customer Analytics account. Accepts a subset of fields; unspecified fields are left unchanged. Pass `tags` to replace the full set of tags on the account.",
+ "description": "Update fields on an existing Customer Analytics account. Accepts a subset of fields; unspecified fields are left unchanged. Pass `tags` to replace the full set of tags. Set `churned_at` to an ISO-8601 timestamp to mark the account as churned, or null to mark it as active again.",
"category": "Customer analytics",
"feature": "customer_analytics",
"summary": "Update account",
@@ -270,7 +270,7 @@
"feature_flag": "customer-analytics-csp"
},
"accounts-retrieve": {
- "description": "Fetch a single Customer Analytics account by id. Returns the full account including typed `properties` (stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id external identifiers) and `tags`. User assignments (CSM, account executive, ...) live on account relationships — see `accounts-relationships-list`. These are the built-in fields only; a team's own typed attributes are custom properties and are not returned here. Call `custom-property-definitions-list` to see what the team tracks, then `accounts-custom-property-values-list` for this account's values. To link a user to this account rather than the bare list, deep-link it with the path `/customer_analytics/accounts/<id>/<tab>` (using the account `id`; tab is optional — one of notes/users/usage/spend, e.g. `/customer_analytics/accounts/<id>/usage`).",
+ "description": "Fetch a single Customer Analytics account by id. Returns the full account including typed `properties` (stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id external identifiers), `tags`, and `churned_at` (null if the account has not churned). User assignments (CSM, account executive, ...) live on account relationships — see `accounts-relationships-list`. These are the built-in fields only; a team's own typed attributes are custom properties and are not returned here. Call `custom-property-definitions-list` to see what the team tracks, then `accounts-custom-property-values-list` for this account's values. To link a user to this account rather than the bare list, deep-link it with the path `/customer_analytics/accounts/<id>/<tab>` (using the account `id`; tab is optional — one of notes/users/usage/spend, e.g. `/customer_analytics/accounts/<id>/usage`).",
"category": "Customer analytics",
"feature": "customer_analytics",
"summary": "Get account",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 65468a0063b7..299ac3d03b5a 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -214,6 +214,11 @@ export namespace Schemas {
* * `weekly` - weekly
* * `monthly` - monthly */
slack_summary_cadence?: SlackSummaryCadenceEnum | null;
+ /**
+ * When the account churned. Null means the account has not churned.
+ * @nullable
+ */
+ churned_at?: string | null;
readonly created_at: string;
/** @nullable */
readonly created_by: number | null;
@@ -834,6 +839,7 @@ export namespace Schemas {
ExternalId: 'external_id',
CreatedAt: 'created_at',
UpdatedAt: 'updated_at',
+ ChurnedAt: 'churned_at',
StripeCustomerId: 'stripe_customer_id',
HubspotDealId: 'hubspot_deal_id',
BillingId: 'billing_id',
@@ -1074,6 +1080,8 @@ export namespace Schemas {
columns: (AccountsTableAccountFieldColumn | AccountsTableTagsColumn | AccountsTableNoteCountColumn | AccountsTableRelationshipColumn | AccountsTableCustomPropertyColumn | AccountsTableCustomPropertyHistoryColumn)[];
/** Filters are combined with AND. Values within tag and assignment filters use OR. */
filters?: (AccountsTableSearchFilter | AccountsTableTagsFilter | AccountsTableAssignedToFilter | AccountsTableUnassignedFilter | AccountsTableAccountIdFilter | AccountsTableCustomPropertyFilter)[] | null;
+ /** Include churned accounts. Churned accounts are hidden by default. */
+ includeChurned?: boolean | null;
kind?: 'AccountsTableQuery';
limit?: number | null;
/** Aggregates to evaluate against the filtered account set. A metrics query skips row loading. */
@@ -32310,6 +32318,11 @@ export namespace Schemas {
external_id: string;
/** Human-readable account name. */
name: string;
+ /**
+ * When the account churned, or null if it has not churned.
+ * @nullable
+ */
+ churned_at: string | null;
/** Active relationship assignments to current organization members, keyed by relationship definition name (e.g. 'CSM', 'Account executive'). Definitions with no active assignment are omitted. */
relationships: ExternalAccountListItemRelationships;
}
@@ -53900,6 +53913,11 @@ export namespace Schemas {
* * `weekly` - weekly
* * `monthly` - monthly */
slack_summary_cadence?: SlackSummaryCadenceEnum | null;
+ /**
+ * When the account churned. Null means the account has not churned.
+ * @nullable
+ */
+ churned_at?: string | null;
readonly created_at?: string;
/** @nullable */
readonly created_by?: number | null;
@@ -81709,6 +81727,10 @@ export namespace Schemas {
* When true, returns only accounts where no user actively holds any relationship.
*/
all_roles_unassigned?: boolean;
+ /**
+ * Include churned accounts. Churned accounts are hidden by default.
+ */
+ include_churned?: boolean;
/**
* Number of results to return per page.
*/
diff --git a/services/mcp/src/generated/customer_analytics/api.ts b/services/mcp/src/generated/customer_analytics/api.ts
index f72b1cc273f1..9eff45df67a7 100644
--- a/services/mcp/src/generated/customer_analytics/api.ts
+++ b/services/mcp/src/generated/customer_analytics/api.ts
@@ -113,11 +113,17 @@ export const AccountsListParams = /* @__PURE__ */ zod.object({
),
})
+export const accountsListQueryIncludeChurnedDefault = false
+
export const AccountsListQueryParams = /* @__PURE__ */ zod.object({
all_roles_unassigned: zod
.boolean()
.optional()
.describe('When true, returns only accounts where no user actively holds any relationship.'),
+ include_churned: zod
+ .boolean()
+ .default(accountsListQueryIncludeChurnedDefault)
+ .describe('Include churned accounts. Churned accounts are hidden by default.'),
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.'),
ordering: zod.string().optional().describe("Sort order. Defaults to '-created_at'."),
@@ -192,6 +198,10 @@ export const AccountsCreateBody = /* @__PURE__ */ zod
.describe(
"How often to generate an AI summary of the account's bound Slack channel (daily, weekly, or monthly). Null means summaries are off.\n\n\* `daily` - daily\n\* `weekly` - weekly\n\* `monthly` - monthly"
),
+ churned_at: zod.iso
+ .datetime({ offset: true })
+ .nullish()
+ .describe('When the account churned. Null means the account has not churned.'),
})
.describe('A Customer Analytics account — a logical grouping used to assign customer-success ownership.')
@@ -397,6 +407,10 @@ export const AccountsPartialUpdateBody = /* @__PURE__ */ zod
.describe(
"How often to generate an AI summary of the account's bound Slack channel (daily, weekly, or monthly). Null means summaries are off.\n\n\* `daily` - daily\n\* `weekly` - weekly\n\* `monthly` - monthly"
),
+ churned_at: zod.iso
+ .datetime({ offset: true })
+ .nullish()
+ .describe('When the account churned. Null means the account has not churned.'),
})
.describe('A Customer Analytics account — a logical grouping used to assign customer-success ownership.')
diff --git a/services/mcp/src/tools/generated/customer_analytics.ts b/services/mcp/src/tools/generated/customer_analytics.ts
index a0fce73c4947..97247976c87c 100644
--- a/services/mcp/src/tools/generated/customer_analytics.ts
+++ b/services/mcp/src/tools/generated/customer_analytics.ts
@@ -230,6 +230,9 @@ const accountsCreate = (): ToolBase<typeof AccountsCreateSchema, Schemas.Account
if (params.slack_summary_cadence !== undefined) {
body['slack_summary_cadence'] = params.slack_summary_cadence
}
+ if (params.churned_at !== undefined) {
+ body['churned_at'] = params.churned_at
+ }
const result = await context.api.request<Schemas.Account>({
method: 'POST',
path: `/api/projects/${encodeURIComponent(String(projectId))}/accounts/`,
@@ -301,6 +304,9 @@ const accountsDestroy = (): ToolBase<typeof AccountsDestroySchema, unknown> => (
})
const AccountsListSchema = AccountsListQueryParams.extend({
+ include_churned: AccountsListQueryParams.shape['include_churned'].describe(
+ 'Include churned accounts. Churned accounts are hidden by default.'
+ ),
tags: AccountsListQueryParams.shape['tags'].describe(
'JSON-encoded array of tag names to filter by, e.g. `["enterprise","priority"]`. Returns accounts that have any of the listed tags.'
),
@@ -316,6 +322,7 @@ const accountsList = (): ToolBase<typeof AccountsListSchema, WithPostHogUrl<Sche
path: `/api/projects/${encodeURIComponent(String(projectId))}/accounts/`,
query: {
all_roles_unassigned: params.all_roles_unassigned,
+ include_churned: params.include_churned,
limit: params.limit,
offset: params.offset,
ordering: params.ordering,
@@ -443,6 +450,9 @@ const accountsPartialUpdate = (): ToolBase<typeof AccountsPartialUpdateSchema, S
if (params.slack_summary_cadence !== undefined) {
body['slack_summary_cadence'] = params.slack_summary_cadence
}
+ if (params.churned_at !== undefined) {
+ body['churned_at'] = params.churned_at
+ }
const result = await context.api.request<Schemas.Account>({
method: 'PATCH',
path: `/api/projects/${encodeURIComponent(String(projectId))}/accounts/${encodeURIComponent(String(params.id))}/`,