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(data-catalog): weekly email for the items awaiting catalog review (#103984)

Thiago Salvatore8475a79d76af
diff --git a/.github/workflows/container-images-cd.yml b/.github/workflows/container-images-cd.yml
index b1e081cf8c7a..93c8c221cd73 100644
--- a/.github/workflows/container-images-cd.yml
+++ b/.github/workflows/container-images-cd.yml
@@ -548,6 +548,9 @@ jobs:
weeklyDigest:
- 'posthog/temporal/weekly_digest/**'
+ - 'products/data_catalog/backend/**'
+ - 'posthog/tasks/email.py'
+ - 'posthog/models/organization_notification_lock.py'
- 'posthog/temporal/common/**'
- 'posthog/management/commands/start_temporal_worker.py'
- pyproject.toml
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 7761d6e4e692..ba954c5d48ef 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -11513,9 +11513,9 @@ snapshots:
scenes-app-settings-user--settings-user-navigation--light:
hash: v1.k794b7964.f472a9611f74c5cc61bde2b328bf70f507c3e7ab810f7fff84d5a7ad073add91.GUKjxOkcQwzja8QiApxYwXyyHFHtaXO6fZboZ7PvFQ0
scenes-app-settings-user--settings-user-notifications--dark:
- hash: v1.k794b7964.2204e0a2e6d5fadb35dbbe13c68b9af2fe4052473a34e9562299bddfb7687eb1.xG738ieu2EfqR-FhuyuG916gXJawaPw_aCHVcVvWGbc
+ hash: v1.k794b7964.1fc4163c567f18057b929328e07459c13277805442523070136233c17d5e633a.Tbp1Kb6RmIhrzsmp7CWml5LEnFyy9iY9-A-lTK-h76c
scenes-app-settings-user--settings-user-notifications--light:
- hash: v1.k794b7964.6dc077d049e7b4c5ce8c3a623b281a7d02f43647a2f3edcb7c624555296246eb.XJPMz9qmz5R2ocrf49XL8yyGAF2bRbZfPe9VTyyzK4w
+ hash: v1.k794b7964.1d238eb22fba4c223038a8a9be5d13ca4a7eb944f0ce07ed5402d270249923d9.HNm6rvMowebOKIqjSZORE_6aLQAHiqSd6DMw-Su8dYI
scenes-app-settings-user--settings-user-profile--dark:
hash: v1.k794b7964.5f1d9971d5da44a5868c6f1cfc633fa5e2f90d0f31e9ed651783f949512350ab.3b41GlzDKrj_9lsTioV2GDzEZDpVY2GAiAEmGjKdA9c
scenes-app-settings-user--settings-user-profile--light:
diff --git a/frontend/src/generated/core/api.schemas.ts b/frontend/src/generated/core/api.schemas.ts
index af627b4d6fbb..9885b11497dc 100644
--- a/frontend/src/generated/core/api.schemas.ts
+++ b/frontend/src/generated/core/api.schemas.ts
@@ -509,6 +509,7 @@ export interface OrganizationInviteDelegateApi {
}
/**
+ * * `data_catalog_weekly_digest` - data_catalog_weekly_digest
* * `discussions_mentioned` - discussions_mentioned
* * `error_tracking_issue_assigned` - error_tracking_issue_assigned
* * `error_tracking_weekly_digest_project_enabled` - error_tracking_weekly_digest_project_enabled
@@ -523,6 +524,7 @@ export interface OrganizationInviteDelegateApi {
export type SettingEnumApi = (typeof SettingEnumApi)[keyof typeof SettingEnumApi]
export const SettingEnumApi = {
+ DataCatalogWeeklyDigest: 'data_catalog_weekly_digest',
DiscussionsMentioned: 'discussions_mentioned',
ErrorTrackingIssueAssigned: 'error_tracking_issue_assigned',
ErrorTrackingWeeklyDigestProjectEnabled: 'error_tracking_weekly_digest_project_enabled',
@@ -538,6 +540,7 @@ export const SettingEnumApi = {
export interface OrganizationNotificationLockApi {
/** Notification setting this rule enforces.
*
+ * * `data_catalog_weekly_digest` - data_catalog_weekly_digest
* * `discussions_mentioned` - discussions_mentioned
* * `error_tracking_issue_assigned` - error_tracking_issue_assigned
* * `error_tracking_weekly_digest_project_enabled` - error_tracking_weekly_digest_project_enabled
@@ -579,6 +582,7 @@ export interface OrganizationNotificationLockChangeApi {
user_id: number
/** Notification setting to lock or unlock.
*
+ * * `data_catalog_weekly_digest` - data_catalog_weekly_digest
* * `discussions_mentioned` - discussions_mentioned
* * `error_tracking_issue_assigned` - error_tracking_issue_assigned
* * `error_tracking_weekly_digest_project_enabled` - error_tracking_weekly_digest_project_enabled
diff --git a/frontend/src/generated/core/api.zod.ts b/frontend/src/generated/core/api.zod.ts
index 7c8cf391bf3d..3539b1df5218 100644
--- a/frontend/src/generated/core/api.zod.ts
+++ b/frontend/src/generated/core/api.zod.ts
@@ -515,6 +515,7 @@ export const NotificationLocksBulkUpdateCreateBody = /* @__PURE__ */ zod.object(
user_id: zod.number().describe('Member this rule applies to.'),
setting: zod
.enum([
+ 'data_catalog_weekly_digest',
'discussions_mentioned',
'error_tracking_issue_assigned',
'error_tracking_weekly_digest_project_enabled',
@@ -527,10 +528,10 @@ export const NotificationLocksBulkUpdateCreateBody = /* @__PURE__ */ zod.object(
'web_analytics_weekly_digest_project_enabled',
])
.describe(
- '\* `discussions_mentioned` - discussions_mentioned\n\* `error_tracking_issue_assigned` - error_tracking_issue_assigned\n\* `error_tracking_weekly_digest_project_enabled` - error_tracking_weekly_digest_project_enabled\n\* `materialized_view_sync_failed` - materialized_view_sync_failed\n\* `materialized_view_sync_failed_daily` - materialized_view_sync_failed_daily\n\* `materialized_view_sync_failed_immediate` - materialized_view_sync_failed_immediate\n\* `organization_member_join_email_disabled` - organization_member_join_email_disabled\n\* `pipeline_notifications_disabled` - pipeline_notifications_disabled\n\* `project_weekly_digest_disabled` - project_weekly_digest_disabled\n\* `web_analytics_weekly_digest_project_enabled` - web_analytics_weekly_digest_project_enabled'
+ '\* `data_catalog_weekly_digest` - data_catalog_weekly_digest\n\* `discussions_mentioned` - discussions_mentioned\n\* `error_tracking_issue_assigned` - error_tracking_issue_assigned\n\* `error_tracking_weekly_digest_project_enabled` - error_tracking_weekly_digest_project_enabled\n\* `materialized_view_sync_failed` - materialized_view_sync_failed\n\* `materialized_view_sync_failed_daily` - materialized_view_sync_failed_daily\n\* `materialized_view_sync_failed_immediate` - materialized_view_sync_failed_immediate\n\* `organization_member_join_email_disabled` - organization_member_join_email_disabled\n\* `pipeline_notifications_disabled` - pipeline_notifications_disabled\n\* `project_weekly_digest_disabled` - project_weekly_digest_disabled\n\* `web_analytics_weekly_digest_project_enabled` - web_analytics_weekly_digest_project_enabled'
)
.describe(
- 'Notification setting to lock or unlock.\n\n\* `discussions_mentioned` - discussions_mentioned\n\* `error_tracking_issue_assigned` - error_tracking_issue_assigned\n\* `error_tracking_weekly_digest_project_enabled` - error_tracking_weekly_digest_project_enabled\n\* `materialized_view_sync_failed` - materialized_view_sync_failed\n\* `materialized_view_sync_failed_daily` - materialized_view_sync_failed_daily\n\* `materialized_view_sync_failed_immediate` - materialized_view_sync_failed_immediate\n\* `organization_member_join_email_disabled` - organization_member_join_email_disabled\n\* `pipeline_notifications_disabled` - pipeline_notifications_disabled\n\* `project_weekly_digest_disabled` - project_weekly_digest_disabled\n\* `web_analytics_weekly_digest_project_enabled` - web_analytics_weekly_digest_project_enabled'
+ 'Notification setting to lock or unlock.\n\n\* `data_catalog_weekly_digest` - data_catalog_weekly_digest\n\* `discussions_mentioned` - discussions_mentioned\n\* `error_tracking_issue_assigned` - error_tracking_issue_assigned\n\* `error_tracking_weekly_digest_project_enabled` - error_tracking_weekly_digest_project_enabled\n\* `materialized_view_sync_failed` - materialized_view_sync_failed\n\* `materialized_view_sync_failed_daily` - materialized_view_sync_failed_daily\n\* `materialized_view_sync_failed_immediate` - materialized_view_sync_failed_immediate\n\* `organization_member_join_email_disabled` - organization_member_join_email_disabled\n\* `pipeline_notifications_disabled` - pipeline_notifications_disabled\n\* `project_weekly_digest_disabled` - project_weekly_digest_disabled\n\* `web_analytics_weekly_digest_project_enabled` - web_analytics_weekly_digest_project_enabled'
),
scope_id: zod
.string()
diff --git a/frontend/src/scenes/settings/shared/notificationSettingDescriptors.ts b/frontend/src/scenes/settings/shared/notificationSettingDescriptors.ts
index 1c919efc6e8b..dfdac26aa44d 100644
--- a/frontend/src/scenes/settings/shared/notificationSettingDescriptors.ts
+++ b/frontend/src/scenes/settings/shared/notificationSettingDescriptors.ts
@@ -48,6 +48,13 @@ export const NOTIFICATION_CONCEPTS: NotificationConcept[] = [
description: 'A weekly summary of web traffic in a project.',
perProject: true,
},
+ {
+ setting: 'data_catalog_weekly_digest',
+ label: 'Data catalog weekly digest',
+ description: 'A weekly summary of the catalog items waiting for review.',
+ perProject: false,
+ note: NO_PROJECT_NOTE,
+ },
{
setting: 'error_tracking_issue_assigned',
label: 'Issue assigned',
diff --git a/frontend/src/scenes/settings/user/UpdateEmailPreferences.tsx b/frontend/src/scenes/settings/user/UpdateEmailPreferences.tsx
index 4356508ae5ac..92aad9139509 100644
--- a/frontend/src/scenes/settings/user/UpdateEmailPreferences.tsx
+++ b/frontend/src/scenes/settings/user/UpdateEmailPreferences.tsx
@@ -21,6 +21,7 @@ enum NotificationBlock {
IssueAssigned = 'issue-assigned',
EtWeeklyDigest = 'et-weekly-digest',
WaWeeklyDigest = 'wa-weekly-digest',
+ DataCatalogWeeklyDigest = 'data-catalog-weekly-digest',
CommentMentions = 'comment-mentions',
ApiKeyExposure = 'api-key-exposure',
MaterializedViewSync = 'materialized-view-sync',
@@ -49,6 +50,7 @@ const NOTIFICATION_DEFAULTS: BooleanNotificationSettings = {
materialized_view_sync_failed_daily: true,
materialized_view_sync_failed_immediate: false,
web_analytics_weekly_digest: true,
+ data_catalog_weekly_digest: true,
}
function ProjectDigestSelector({
@@ -545,6 +547,16 @@ export function UpdateEmailPreferences(): JSX.Element {
)}
</div>
),
+ [NotificationBlock.DataCatalogWeeklyDigest]: (
+ <div className="border rounded p-4">
+ <SimpleSwitch
+ setting="data_catalog_weekly_digest"
+ label="Data catalog weekly digest"
+ description="Get a weekly summary of the metrics, relationships, and certifications waiting for review in your projects"
+ dataAttr="data_catalog_weekly_digest_enabled"
+ />
+ </div>
+ ),
[NotificationBlock.CommentMentions]: (
<div className="border rounded p-4">
<SimpleSwitch
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index 555b686f400f..e57012a690ef 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -482,6 +482,7 @@ export interface NotificationSettings {
materialized_view_sync_failed_immediate?: boolean
web_analytics_weekly_digest: boolean
web_analytics_weekly_digest_project_enabled?: Record<string, boolean>
+ data_catalog_weekly_digest?: boolean
organization_member_join_email_disabled?: Record<string, boolean>
realtime_notifications_disabled?: Record<string, Record<string, boolean>>
pipeline_notifications_disabled?: Record<string, boolean>
diff --git a/posthog/api/test/test_user.py b/posthog/api/test/test_user.py
index 6671632f0e27..dc02e250c9ad 100644
--- a/posthog/api/test/test_user.py
+++ b/posthog/api/test/test_user.py
@@ -2473,6 +2473,7 @@ class TestUserAPI(APIBaseTest):
"materialized_view_sync_failed_daily": True,
"materialized_view_sync_failed_immediate": False,
"web_analytics_weekly_digest": True,
+ "data_catalog_weekly_digest": True,
"organization_member_join_email_disabled": {},
"realtime_notifications_disabled": {},
"pipeline_notifications_disabled": {},
@@ -2497,6 +2498,7 @@ class TestUserAPI(APIBaseTest):
"materialized_view_sync_failed_daily": True,
"materialized_view_sync_failed_immediate": False,
"web_analytics_weekly_digest": True,
+ "data_catalog_weekly_digest": True,
"organization_member_join_email_disabled": {},
"realtime_notifications_disabled": {},
"pipeline_notifications_disabled": {},
@@ -2769,6 +2771,7 @@ class TestUserAPI(APIBaseTest):
"materialized_view_sync_failed_daily": True, # Default value
"materialized_view_sync_failed_immediate": False, # Default value
"web_analytics_weekly_digest": True, # Default value
+ "data_catalog_weekly_digest": True, # Default value
"organization_member_join_email_disabled": {}, # Default value
"realtime_notifications_disabled": {}, # Default value
"pipeline_notifications_disabled": {}, # Default value
diff --git a/posthog/management/commands/execute_temporal_workflow.py b/posthog/management/commands/execute_temporal_workflow.py
index f9585134c95d..d66029466ad2 100644
--- a/posthog/management/commands/execute_temporal_workflow.py
+++ b/posthog/management/commands/execute_temporal_workflow.py
@@ -29,6 +29,7 @@ from posthog.temporal.usage_report import WORKFLOWS as USAGE_REPORTS_WORKFLOWS
from posthog.temporal.weekly_digest import WORKFLOWS as WEEKLY_DIGEST_WORKFLOWS
from products.batch_exports.backend.temporal import WORKFLOWS as BATCH_EXPORT_WORKFLOWS
+from products.data_catalog.backend.facade.temporal import WORKFLOWS as DATA_CATALOG_DIGEST_WORKFLOWS
from products.error_tracking.backend.facade.temporal import WORKFLOWS as ERROR_TRACKING_WORKFLOWS
from products.logs.backend.temporal.retention_entitlements import WORKFLOWS as LOGS_RETENTION_ENTITLEMENTS_WORKFLOWS
from products.posthog_ai.backend.temporal.backfill import WORKFLOWS as CONVERSATION_BACKFILL_WORKFLOWS
@@ -158,6 +159,7 @@ class Command(BaseCommand):
+ LOGS_RETENTION_ENTITLEMENTS_WORKFLOWS
+ RASTERIZE_RECORDING_WORKFLOWS
+ WA_DIGEST_WORKFLOWS
+ + DATA_CATALOG_DIGEST_WORKFLOWS
+ ERROR_TRACKING_WORKFLOWS
+ SURFACING_SCORING_SWEEP_WORKFLOWS
+ BACKFILL_GROUP_TYPE_CREATED_AT_WORKFLOWS
diff --git a/posthog/management/commands/start_temporal_worker.py b/posthog/management/commands/start_temporal_worker.py
index 3d5c531147ba..79ebf33a3c38 100644
--- a/posthog/management/commands/start_temporal_worker.py
+++ b/posthog/management/commands/start_temporal_worker.py
@@ -190,6 +190,10 @@ from products.customer_analytics.backend.facade.temporal import (
ACTIVITIES as CUSTOMER_ANALYTICS_ACTIVITIES,
WORKFLOWS as CUSTOMER_ANALYTICS_WORKFLOWS,
)
+from products.data_catalog.backend.facade.temporal import (
+ ACTIVITIES as DATA_CATALOG_DIGEST_ACTIVITIES,
+ WORKFLOWS as DATA_CATALOG_DIGEST_WORKFLOWS,
+)
from products.data_quality.backend.facade.temporal import (
ACTIVITIES as DATA_QUALITY_ACTIVITIES,
WORKFLOWS as DATA_QUALITY_WORKFLOWS,
@@ -512,8 +516,8 @@ _task_queue_specs = [
# workflows left, so a dedicated fleet for them isn't worth its reserved capacity.
(
settings.WEEKLY_DIGEST_TASK_QUEUE,
- WEEKLY_DIGEST_WORKFLOWS + WA_DIGEST_WORKFLOWS,
- WEEKLY_DIGEST_ACTIVITIES + WA_DIGEST_ACTIVITIES,
+ WEEKLY_DIGEST_WORKFLOWS + WA_DIGEST_WORKFLOWS + DATA_CATALOG_DIGEST_WORKFLOWS,
+ WEEKLY_DIGEST_ACTIVITIES + WA_DIGEST_ACTIVITIES + DATA_CATALOG_DIGEST_ACTIVITIES,
),
(
settings.LLMA_EVALS_TASK_QUEUE,
diff --git a/posthog/management/commands/start_temporal_workflow.py b/posthog/management/commands/start_temporal_workflow.py
index ad19107fba04..c12678fb4696 100644
--- a/posthog/management/commands/start_temporal_workflow.py
+++ b/posthog/management/commands/start_temporal_workflow.py
@@ -29,6 +29,7 @@ from posthog.temporal.usage_report import WORKFLOWS as USAGE_REPORTS_WORKFLOWS
from posthog.temporal.weekly_digest import WORKFLOWS as WEEKLY_DIGEST_WORKFLOWS
from products.batch_exports.backend.temporal import WORKFLOWS as BATCH_EXPORT_WORKFLOWS
+from products.data_catalog.backend.facade.temporal import WORKFLOWS as DATA_CATALOG_DIGEST_WORKFLOWS
from products.error_tracking.backend.facade.temporal import WORKFLOWS as ERROR_TRACKING_WORKFLOWS
from products.logs.backend.temporal.retention_entitlements import WORKFLOWS as LOGS_RETENTION_ENTITLEMENTS_WORKFLOWS
from products.posthog_ai.backend.temporal.backfill import WORKFLOWS as CONVERSATION_BACKFILL_WORKFLOWS
@@ -160,6 +161,7 @@ class Command(BaseCommand):
+ HEALTH_CHECK_WORKFLOWS
+ LOGS_RETENTION_ENTITLEMENTS_WORKFLOWS
+ WA_DIGEST_WORKFLOWS
+ + DATA_CATALOG_DIGEST_WORKFLOWS
+ ERROR_TRACKING_WORKFLOWS
+ SURFACING_SCORING_SWEEP_WORKFLOWS
)
diff --git a/posthog/management/commands/test/test_temporal_workflow_commands.py b/posthog/management/commands/test/test_temporal_workflow_commands.py
new file mode 100644
index 000000000000..5328aa36d77e
--- /dev/null
+++ b/posthog/management/commands/test/test_temporal_workflow_commands.py
@@ -0,0 +1,37 @@
+import dataclasses
+
+import pytest
+from unittest.mock import AsyncMock, MagicMock, patch
+
+from django.core.management import call_command
+
+
+ "command,client_method",
+ [
+ ("start_temporal_workflow", "start_workflow"),
+ ("execute_temporal_workflow", "execute_workflow"),
+ ],
+)
+ "workflow_name,inputs,expected_fields",
+ [
+ # dry_run defaults to True as a manual-run fail-safe, so an input-less CLI start is dry.
+ ("data-catalog-weekly-digest", [], {"dry_run": True}),
+ (
+ "data-catalog-weekly-digest-test",
+ ['{"email": "[email protected]"}'],
+ {"email": "[email protected]"},
+ ),
+ ],
+)
+def test_commands_resolve_data_catalog_digest_workflows(command, client_method, workflow_name, inputs, expected_fields):
+ mock_client = MagicMock()
+ setattr(mock_client, client_method, AsyncMock(return_value={"ok": True}))
+
+ with patch(f"posthog.management.commands.{command}.connect", new=AsyncMock(return_value=mock_client)):
+ call_command(command, workflow_name, *inputs, "--workflow-id=test-workflow-id")
+
+ call = getattr(mock_client, client_method).await_args
+ assert call.args[0] == workflow_name
+ assert expected_fields.items() <= dataclasses.asdict(call.args[1]).items()
diff --git a/posthog/models/organization_notification_lock.py b/posthog/models/organization_notification_lock.py
index 619df796f4a6..ee1dc69090a8 100644
--- a/posthog/models/organization_notification_lock.py
+++ b/posthog/models/organization_notification_lock.py
@@ -21,6 +21,7 @@ LOCKABLE_NOTIFICATION_SETTINGS: dict[str, str] = {
"materialized_view_sync_failed": "",
"materialized_view_sync_failed_daily": "",
"materialized_view_sync_failed_immediate": "",
+ "data_catalog_weekly_digest": "",
}
# Stored per pipeline but governed per project, so these cannot be merged into the stored map by
diff --git a/posthog/models/user.py b/posthog/models/user.py
index 7ed911e1b2a4..ab964e7dbb04 100644
--- a/posthog/models/user.py
+++ b/posthog/models/user.py
@@ -58,6 +58,7 @@ class Notifications(TypedDict, total=False):
materialized_view_sync_failed_immediate: bool # One email each time a view starts failing
web_analytics_weekly_digest: bool
web_analytics_weekly_digest_project_enabled: dict[str, bool]
+ data_catalog_weekly_digest: bool
organization_member_join_email_disabled: dict[
str, bool
] # Maps organization ID (str) to disabled status (True = do not email when a new member joins)
@@ -84,6 +85,7 @@ NOTIFICATION_DEFAULTS: Notifications = {
"materialized_view_sync_failed_daily": True, # Digest is the default delivery once failures are turned on
"materialized_view_sync_failed_immediate": False,
"web_analytics_weekly_digest": True, # Web analytics weekly digest enabled by default
+ "data_catalog_weekly_digest": True, # Data catalog pending-review digest enabled by default
"organization_member_join_email_disabled": {}, # No per-org opt-out until user configures
"realtime_notifications_disabled": {}, # No opt-outs by default
"pipeline_notifications_disabled": {}, # No per-pipeline opt-out until user configures
diff --git a/posthog/tasks/email.py b/posthog/tasks/email.py
index 877ed5d93465..8415c536238d 100644
--- a/posthog/tasks/email.py
+++ b/posthog/tasks/email.py
@@ -82,6 +82,7 @@ class NotificationSetting(Enum):
MATERIALIZED_VIEW_SYNC_FAILED_DAILY = "materialized_view_sync_failed_daily"
MATERIALIZED_VIEW_SYNC_FAILED_IMMEDIATE = "materialized_view_sync_failed_immediate"
WEB_ANALYTICS_WEEKLY_DIGEST = "web_analytics_weekly_digest"
+ DATA_CATALOG_WEEKLY_DIGEST = "data_catalog_weekly_digest"
NotificationSettingType = Literal[
@@ -96,6 +97,7 @@ NotificationSettingType = Literal[
"materialized_view_sync_failed_daily",
"materialized_view_sync_failed_immediate",
"web_analytics_weekly_digest",
+ "data_catalog_weekly_digest",
]
@@ -347,6 +349,9 @@ def should_send_notification(
elif notification_type == NotificationSetting.PROJECT_API_KEY_EXPOSED.value:
return settings.get(notification_type, True)
+ elif notification_type == NotificationSetting.DATA_CATALOG_WEEKLY_DIGEST.value:
+ return settings.get(notification_type, True)
+
elif notification_type == NotificationSetting.AI_EVALUATION_DISABLED.value:
return settings.get(notification_type, True)
diff --git a/posthog/temporal/schedule.py b/posthog/temporal/schedule.py
index 306b1f180628..f6a02809850f 100644
--- a/posthog/temporal/schedule.py
+++ b/posthog/temporal/schedule.py
@@ -92,6 +92,7 @@ from products.customer_analytics.backend.facade.temporal import (
create_calendar_sync_coordinator_schedule,
create_ownership_claims_coordinator_schedule,
)
+from products.data_catalog.backend.facade.temporal import create_data_catalog_weekly_digest_schedule
from products.data_quality.backend.facade.temporal import (
create_cleanup_data_quality_check_runs_schedule,
create_reconcile_metric_schedules_schedule,
@@ -941,6 +942,7 @@ schedules = [
create_error_tracking_weekly_digest_schedule,
create_wa_weekly_digest_schedule,
create_wa_digest_notification_schedule,
+ create_data_catalog_weekly_digest_schedule,
create_alerts_platform_tick_schedule,
create_logs_alert_check_schedule,
create_logs_volume_tick_schedule,
diff --git a/products/data_catalog/backend/facade/temporal.py b/products/data_catalog/backend/facade/temporal.py
new file mode 100644
index 000000000000..49c10b29d3e5
--- /dev/null
+++ b/products/data_catalog/backend/facade/temporal.py
@@ -0,0 +1,11 @@
+"""Facade re-exports for Temporal wiring.
+
+The worker bootstrap (`start_temporal_worker`) and the schedule bootstrap register the catalog's
+digest through these re-exports rather than importing ``backend.temporal`` directly.
+"""
+
+from ..temporal import (
+ ACTIVITIES as ACTIVITIES,
+ WORKFLOWS as WORKFLOWS,
+)
+from ..temporal.schedule import create_data_catalog_weekly_digest_schedule as create_data_catalog_weekly_digest_schedule
diff --git a/products/data_catalog/backend/logic/pending_review.py b/products/data_catalog/backend/logic/pending_review.py
index 1f6ec60ece86..3c769a66db77 100644
--- a/products/data_catalog/backend/logic/pending_review.py
+++ b/products/data_catalog/backend/logic/pending_review.py
@@ -98,18 +98,26 @@ def build_team_pending_review(team: Team, sample_size: int = DEFAULT_SAMPLE_SIZE
)
-def build_org_pending_reviews(
- teams: list[Team], sample_size: int = DEFAULT_SAMPLE_SIZE
-) -> dict[int, TeamPendingReview]:
- """Teams with something to review, keyed by team id. A team that raises is logged and left out."""
+@frozen
+class PendingReviewBuild:
+ reviews: dict[int, TeamPendingReview]
+ failed_team_ids: list[int]
+
+
+def build_org_pending_reviews(teams: list[Team], sample_size: int = DEFAULT_SAMPLE_SIZE) -> PendingReviewBuild:
+ """Teams with something to review, keyed by team id, and the teams that raised. Raises if all raised."""
reviews: dict[int, TeamPendingReview] = {}
+ failed_team_ids: list[int] = []
for team in teams:
try:
review = build_team_pending_review(team, sample_size)
except Exception as e:
logger.warning("failed to build data catalog pending review", team_id=team.id, error=str(e))
capture_exception(e, {"team_id": team.id})
+ failed_team_ids.append(team.id)
continue
if review is not None:
reviews[team.id] = review
- return reviews
+ if teams and len(failed_team_ids) == len(teams):
+ raise RuntimeError("Data catalog digest: no project's pending review could be built")
+ return PendingReviewBuild(reviews=reviews, failed_team_ids=failed_team_ids)
diff --git a/products/data_catalog/backend/templates/email/data_catalog_weekly_digest.html b/products/data_catalog/backend/templates/email/data_catalog_weekly_digest.html
new file mode 100644
index 000000000000..7362c523f60d
--- /dev/null
+++ b/products/data_catalog/backend/templates/email/data_catalog_weekly_digest.html
@@ -0,0 +1,111 @@
+{% extends "email/base.html" %}
+{% block head %}
+ <style type="text/css">body, .main { background-color: #f3f4f0 !important; }</style>
+{% endblock %}
+{% block preheader %}{{ total }} item{{ total|pluralize }} awaiting review in your data catalog{% endblock %}
+{% block main %}
+ <p style="font-size: 1.1em; color: #374151; margin: 0 0 24px 0;">
+ Your data catalog has <strong>{{ total }}</strong> item{{ total|pluralize }} waiting for review. Approving a
+ metric, a relationship, or a certification tells everyone which numbers and tables to trust.
+ </p>
+ {% for section in project_sections %}
+ <div style="margin-bottom: 40px;">
+ <table width="100%"
+ cellpadding="0"
+ cellspacing="0"
+ border="0"
+ style="margin-bottom: 12px">
+ <tr>
+ <td style="width: 50%; vertical-align: middle;">
+ <div style="height: 1px; background-color: #d1d5db;"></div>
+ </td>
+ <td style="white-space: nowrap; padding: 0 16px; vertical-align: middle;">
+ <a href="{{ section.project_url }}"
+ target="_blank"
+ style="font-size: 1.15em;
+ font-weight: 600;
+ color: #111827;
+ text-decoration: none">{{ section.team_name }}</a>
+ </td>
+ <td style="width: 50%; vertical-align: middle;">
+ <div style="height: 1px; background-color: #d1d5db;"></div>
+ </td>
+ </tr>
+ </table>
+ <div style="background-color: #ffffff;
+ border-radius: 8px;
+ padding: 20px;
+ margin-bottom: 12px">
+ <table width="100%"
+ cellpadding="0"
+ cellspacing="0"
+ border="0"
+ style="border-collapse: collapse">
+ {% for row in section.rows %}
+ <tr>
+ <td align="left"
+ style="padding: 12px 8px 12px 0;
+ {% if not forloop.first %}border-top: 1px solid #f3f4f6;
+ {% endif %} vertical-align: top;
+ text-align: left">
+ <span style="color: #111827; font-weight: 600; font-size: 0.95em;">{{ row.count }} {{ row.noun }}{{ row.count|pluralize }}</span>
+ <br />
+ <span style="color: #6b7280; font-size: 0.85em;">
+ {% for name in row.sample_names %}
+ {{ name|truncatechars:60 }}{% if not forloop.last %},{% endif %}
+ {% endfor %}
+ {% if row.omitted_count %}and {{ row.omitted_count }} more{% endif %}
+ </span>
+ </td>
+ <td align="right"
+ style="padding: 12px 0 12px 8px;
+ {% if not forloop.first %}border-top: 1px solid #f3f4f6;
+ {% endif %} vertical-align: top;
+ text-align: right;
+ white-space: nowrap">
+ <a href="{{ row.review_url }}"
+ target="_blank"
+ style="color: #111827;
+ font-weight: 600;
+ font-size: 0.85em">Review</a>
+ </td>
+ </tr>
+ {% endfor %}
+ </table>
+ </div>
+ <div style="text-align: center;">
+ <a href="{{ section.review_url }}"
+ target="_blank"
+ style="background-color: #111827;
+ border-radius: 6px;
+ color: #ffffff;
+ display: inline-block;
+ font-size: 0.9em;
+ font-weight: 600;
+ padding: 10px 20px;
+ text-decoration: none">Review pending items</a>
+ <a href="{{ section.create_metric_url }}"
+ target="_blank"
+ style="color: #6b7280;
+ font-size: 0.85em;
+ margin-left: 16px;
+ text-decoration: underline">Create a metric</a>
+ </div>
+ </div>
+ {% endfor %}
+ {% if omitted_project_count %}
+ <p style="font-size: 0.9em;
+ color: #6b7280;
+ margin: 0 0 24px 0;
+ text-align: center">
+ {{ omitted_project_count }} more project{{ omitted_project_count|pluralize }} also {{ omitted_project_count|pluralize:"has,have" }} items waiting for review.
+ </p>
+ {% endif %}
+ <div style="margin-bottom: 16px; text-align: center;">
+ <a href="{{ settings_url }}"
+ style="color: #6b7280;
+ font-size: 0.85em;
+ text-decoration: underline">Change notification settings</a>
+ </div>
+{% endblock %}
+{% block footer %}{% endblock %}
diff --git a/products/data_catalog/backend/temporal/__init__.py b/products/data_catalog/backend/temporal/__init__.py
new file mode 100644
index 000000000000..ab51a51067d0
--- /dev/null
+++ b/products/data_catalog/backend/temporal/__init__.py
@@ -0,0 +1,3 @@
+from .weekly_digest import ACTIVITIES, WORKFLOWS
+
+__all__ = ["ACTIVITIES", "WORKFLOWS"]
diff --git a/products/data_catalog/backend/temporal/schedule.py b/products/data_catalog/backend/temporal/schedule.py
new file mode 100644
index 000000000000..31b717b51487
--- /dev/null
+++ b/products/data_catalog/backend/temporal/schedule.py
@@ -0,0 +1,56 @@
+"""Cron schedule for the weekly pending-review digest, registered on the weekly digest queue."""
+
+from datetime import timedelta
+
+from django.conf import settings
+
+from temporalio import common
+from temporalio.client import (
+ Client,
+ Schedule,
+ ScheduleActionStartWorkflow,
+ ScheduleCalendarSpec,
+ ScheduleRange,
+ ScheduleSpec,
+)
+
+from posthog.temporal.common.schedule import a_create_schedule, a_schedule_exists, a_update_schedule
+
+from .weekly_digest.types import DataCatalogWeeklyDigestInput
+from .weekly_digest.workflows import WORKFLOW_NAME
+
+SCHEDULE_ID = "data-catalog-weekly-digest-schedule"
+
+
+async def create_data_catalog_weekly_digest_schedule(client: Client) -> None:
+ schedule = Schedule(
+ action=ScheduleActionStartWorkflow(
+ WORKFLOW_NAME,
+ # dry_run defaults to True as a manual-run fail-safe; the schedule is the one
+ # caller that must send for real.
+ DataCatalogWeeklyDigestInput(dry_run=False),
+ id=SCHEDULE_ID,
+ task_queue=settings.WEEKLY_DIGEST_TASK_QUEUE,
+ retry_policy=common.RetryPolicy(maximum_attempts=1),
+ # Overlap defaults to SKIP, so a run that never closes drops every later Tuesday and
+ # the digest stops for good. Nothing inside the workflow caps total duration: the page
+ # loop is unbounded and the activities set only start_to_close. A day is far above any
+ # expected run and far below the week, so a wedged run dies before the next one is due.
+ execution_timeout=timedelta(hours=24),
+ ),
+ spec=ScheduleSpec(
+ calendars=[
+ ScheduleCalendarSpec(
+ comment="Weekly at Tuesday 9 AM UTC",
+ hour=[ScheduleRange(start=9, end=9)],
+ day_of_week=[ScheduleRange(start=2, end=2)],
+ )
+ ],
+ time_zone_name="UTC",
+ ),
+ )
+
+ if await a_schedule_exists(client, SCHEDULE_ID):
+ await a_update_schedule(client, SCHEDULE_ID, schedule)
+ else:
+ await a_create_schedule(client, SCHEDULE_ID, schedule, trigger_immediately=False)
diff --git a/products/data_catalog/backend/temporal/weekly_digest/__init__.py b/products/data_catalog/backend/temporal/weekly_digest/__init__.py
new file mode 100644
index 000000000000..9c0e13df87b5
--- /dev/null
+++ b/products/data_catalog/backend/temporal/weekly_digest/__init__.py
@@ -0,0 +1,10 @@
+from .activities import get_org_batch_page, push_digest_metrics_activity, run_digest_batch, send_test_digest
+from .workflows import DataCatalogWeeklyDigestTestWorkflow, DataCatalogWeeklyDigestWorkflow
+
+WORKFLOWS = [DataCatalogWeeklyDigestWorkflow, DataCatalogWeeklyDigestTestWorkflow]
+ACTIVITIES = [
+ get_org_batch_page,
+ run_digest_batch,
+ push_digest_metrics_activity,
+ send_test_digest,
+]
diff --git a/products/data_catalog/backend/temporal/weekly_digest/activities.py b/products/data_catalog/backend/temporal/weekly_digest/activities.py
new file mode 100644
index 000000000000..98c741d0eccf
--- /dev/null
+++ b/products/data_catalog/backend/temporal/weekly_digest/activities.py
@@ -0,0 +1,456 @@
+import time
+from datetime import datetime, timedelta
+from itertools import batched
+
+from django.conf import settings
+from django.db import close_old_connections
+from django.db.models import Exists, OuterRef, QuerySet
+from django.utils import timezone
+
+import structlog
+import posthoganalytics
+from prometheus_client import Gauge
+from temporalio import activity
+from temporalio.exceptions import ApplicationError
+
+from posthog.email import EmailMessage, is_email_available
+from posthog.exceptions_capture import capture_exception
+from posthog.metrics import pushed_metrics_registry
+from posthog.models import Team
+from posthog.models.organization import Organization, OrganizationMembership
+from posthog.models.organization_notification_lock import GovernedSetting, notification_locks_for_users
+from posthog.models.user import User
+from posthog.sync import database_sync_to_async
+from posthog.tasks.email import NotificationSetting, should_send_notification
+from posthog.temporal.common.digest import OrgBatchPageResult, paginate_index, paginate_keyset
+from posthog.temporal.common.heartbeat import Heartbeater
+from posthog.user_permissions import UserPermissions
+
+from products.access_control.backend.facade.user_access_control import UserAccessControl
+
+from ...logic.pending_review import TeamPendingReview, build_org_pending_reviews
+from .email_context import build_subject, build_template_context
+from .types import (
+ DATA_CATALOG_DIGEST_EMAIL_UNAVAILABLE_TYPE,
+ DataCatalogWeeklyDigestInput,
+ DigestBatchInput,
+ DigestBatchResult,
+ DigestOutcome,
+ OrgBatchPageInput,
+ OrgDigestCounts,
+ SendTestDigestInput,
+)
+
+logger = structlog.get_logger(__name__)
+
+DIGEST_FLAG_KEY = "data-catalog-weekly-digest"
+EMAIL_TEMPLATE_NAME = "data_catalog_weekly_digest"
+
+
+def _get_org_queryset_for_digest(input: DataCatalogWeeklyDigestInput) -> tuple[QuerySet[Organization], datetime | None]:
+ qs = Organization.objects.all()
+ cutoff = None
+ if input.active_since_days is not None and input.active_since_days > 0:
+ cutoff = timezone.now() - timedelta(days=input.active_since_days)
+ qs = qs.filter(
+ Exists(
+ OrganizationMembership.objects.filter(
+ organization_id=OuterRef("id"),
+ user__last_login__gte=cutoff,
+ )
+ )
+ )
+ return qs, cutoff
+
+
+def _get_org_batch_page(input: OrgBatchPageInput) -> OrgBatchPageResult:
+ """Raises non-retryable `ApplicationError` when email is globally unavailable
+ — per-org skips would silently absorb the outage.
+ """
+ close_old_connections()
+
+ if not is_email_available(with_absolute_urls=True):
+ raise ApplicationError(
+ "Data catalog weekly digest: email service is unavailable",
+ type=DATA_CATALOG_DIGEST_EMAIL_UNAVAILABLE_TYPE,
+ non_retryable=True,
+ )
+
+ workflow_input = input.workflow_input
+ cutoff: datetime | None = None
+
+ if workflow_input.org_ids is not None:
+ page_org_ids, next_cursor = paginate_index(list(workflow_input.org_ids), input.cursor, input.page_size)
+ source = "configured"
+ else:
+ qs, cutoff = _get_org_queryset_for_digest(workflow_input)
+ page_org_ids, next_cursor = paginate_keyset(qs, input.cursor, input.page_size)
+ source = "keyset"
+
+ batches = [list(b) for b in batched(page_org_ids, workflow_input.batch_size, strict=False)]
+ logger.info(
+ "data catalog digest org batch page",
+ source=source,
+ count=len(page_org_ids),
+ batch_count=len(batches),
+ batch_size=workflow_input.batch_size,
+ cursor=input.cursor,
+ next_cursor=next_cursor,
+ active_since_days=workflow_input.active_since_days,
+ cutoff=cutoff.isoformat() if cutoff else None,
+ )
+ return OrgBatchPageResult(batches=batches, cursor=next_cursor)
+
+
[email protected](name="data-catalog-digest-get-org-batch-page")
+async def get_org_batch_page(input: OrgBatchPageInput) -> OrgBatchPageResult:
+ return await database_sync_to_async(_get_org_batch_page, thread_sensitive=False)(input)
+
+
+def _is_user_flag_enabled(user: User, org_id: str) -> bool:
+ try:
+ return bool(
+ posthoganalytics.feature_enabled(
+ DIGEST_FLAG_KEY,
+ distinct_id=str(user.distinct_id),
+ groups={"organization": org_id},
+ only_evaluate_locally=False,
+ send_feature_flag_events=False,
+ )
+ )
+ except Exception as e:
+ logger.warning(
+ "data catalog digest: flag eval failed, treating user as not enabled",
+ user_id=str(user.uuid),
+ org_id=org_id,
+ error=str(e),
+ )
+ capture_exception(e, {"user_id": str(user.uuid), "org_id": org_id})
+ return False
+
+
+def _send_digest_for_user(
+ *,
+ user: User,
+ org: Organization,
+ membership: OrganizationMembership,
+ reviews: dict[int, TeamPendingReview],
+ teams_by_id: dict[int, Team],
+ date_suffix: str,
+ locks: dict[GovernedSetting, bool] | None = None,
+ dry_run: bool = False,
+ test: bool = False,
+) -> DigestOutcome:
+ """`test=True` bypasses the notification opt-in and forces a unique campaign key so dedupe
+ never blocks delivery. Project access and catalog access are always enforced.
+ """
+ if not test and not should_send_notification(
+ user, NotificationSetting.DATA_CATALOG_WEEKLY_DIGEST.value, locks=locks
+ ):
+ return DigestOutcome.SKIPPED_OPTOUT
+
+ user_perms = UserPermissions(user)
+
+ def has_access(team: Team) -> bool:
+ if user_perms.team(team).effective_membership_level_for_parent_membership(org, membership) is None:
+ return False
+ return UserAccessControl(user=user, team=team).check_access_level_for_resource("data_catalog", "viewer")
+
+ accessible = [review for team_id, review in reviews.items() if has_access(teams_by_id[team_id])]
+ if not accessible:
+ return DigestOutcome.SKIPPED_NO_DATA
+
+ if dry_run:
+ return DigestOutcome.DRY_RUN
+
+ template_context = build_template_context(org, accessible)
+
+ campaign_key = f"data_catalog_weekly_digest_{org.id}_{user.uuid}_{date_suffix}"
+ if test:
+ campaign_key = f"{campaign_key}_test_{int(timezone.now().timestamp())}"
+
+ try:
+ message = EmailMessage(
+ campaign_key=campaign_key,
+ subject=build_subject(template_context["total"]),
+ template_name=EMAIL_TEMPLATE_NAME,
+ template_context=template_context,
+ )
+ message.add_user_recipient(user)
+ message.send()
+ except Exception as e:
+ if test:
+ raise
+ logger.warning(
+ "failed to send data catalog digest email",
+ org_id=str(org.id),
+ user_id=str(user.uuid),
+ error=str(e),
+ )
+ capture_exception(e, {"org_id": str(org.id), "user_id": str(user.uuid)})
+ return DigestOutcome.FAILED
+
+ return DigestOutcome.SENT
+
+
+def _project_teams(org_id: str) -> dict[int, Team]:
+ """Project-level teams only. A child environment resolves to its parent's catalog, so
+ including one would count the same proposals a second time.
+ """
+ teams = Team.objects.filter(organization_id=org_id, parent_team_id__isnull=True)
+ return {team.id: team for team in teams}
+
+
+def _build_and_send_for_org(org_id: str, dry_run: bool = False) -> OrgDigestCounts:
+ close_old_connections()
+
+ counts = OrgDigestCounts()
+
+ try:
+ org = Organization.objects.get(id=org_id)
+ except Organization.DoesNotExist:
+ logger.warning("Organization not found for data catalog weekly digest", org_id=org_id)
+ counts.skipped_reason = "org_not_found"
+ return counts
+
+ # The app and the API refuse a deactivated or pending-deletion organization, so mail must too:
+ # every link in the digest would land on the block page. Only an explicit False deactivates,
+ # because `is_active` is nullable and a null means the organization was never deactivated.
+ if org.is_pending_deletion or org.is_active is False:
+ counts.skipped_reason = "org_blocked"
+ return counts
+
+ teams_by_id = _project_teams(org_id)
+ if not teams_by_id:
+ counts.skipped_reason = "no_teams"
+ return counts
+
+ build_start = time.monotonic()
+ build = build_org_pending_reviews(list(teams_by_id.values()))
+ counts.build_duration = time.monotonic() - build_start
+ counts.team_count = len(build.reviews)
+ counts.teams_failed = len(build.failed_team_ids)
+ reviews = build.reviews
+
+ if not reviews:
+ counts.skipped_reason = "nothing_pending"
+ return counts
+
+ memberships = list(
+ OrganizationMembership.objects.select_related("user").filter(organization_id=org.id, user__is_active=True)
+ )
+ targeted_memberships = [m for m in memberships if _is_user_flag_enabled(m.user, str(org.id))]
+ if not targeted_memberships:
+ counts.skipped_reason = "no_targeted_memberships"
+ return counts
+
+ locks_by_user = notification_locks_for_users(
+ [membership.user_id for membership in targeted_memberships], organization_id=org.id
+ )
+ date_suffix = timezone.now().strftime("%Y-%W")
+
+ send_start = time.monotonic()
+ for membership in targeted_memberships:
+ outcome = _send_digest_for_user(
+ user=membership.user,
+ org=org,
+ membership=membership,
+ reviews=reviews,
+ teams_by_id=teams_by_id,
+ date_suffix=date_suffix,
+ locks=locks_by_user.get(membership.user_id, {}),
+ dry_run=dry_run,
+ )
+ if outcome in (DigestOutcome.SENT, DigestOutcome.DRY_RUN):
+ counts.sent += 1
+ elif outcome == DigestOutcome.SKIPPED_OPTOUT:
+ counts.skipped_optout += 1
+ elif outcome == DigestOutcome.SKIPPED_NO_DATA:
+ counts.skipped_no_data += 1
+ elif outcome == DigestOutcome.FAILED:
+ counts.failed += 1
+ counts.send_duration = time.monotonic() - send_start
+
+ logger.info(
+ "Sent data catalog weekly digest for org",
+ org_id=org_id,
+ sent_count=counts.sent,
+ skipped_optout=counts.skipped_optout,
+ skipped_no_data=counts.skipped_no_data,
+ failed=counts.failed,
+ team_count=counts.team_count,
+ teams_failed=counts.teams_failed,
+ )
+ return counts
+
+
+def _run_digest_batch(input: DigestBatchInput) -> DigestBatchResult:
+ close_old_connections()
+
+ totals = DigestBatchResult(batch_size=len(input.org_ids))
+
+ for org_id in input.org_ids:
+ try:
+ org_counts = _build_and_send_for_org(org_id, dry_run=input.dry_run)
+ except Exception as e:
+ logger.exception("Data catalog digest failed for org", org_id=org_id, error=str(e))
+ capture_exception(e, {"org_id": org_id})
+ totals.orgs_failed += 1
+ continue
+
+ if org_counts.skipped_reason is not None:
+ totals.orgs_skipped += 1
+ continue
+
+ totals.orgs_processed += 1
+ totals.emails_sent += org_counts.sent
+ totals.emails_skipped_optout += org_counts.skipped_optout
+ totals.emails_skipped_no_data += org_counts.skipped_no_data
+ totals.emails_failed += org_counts.failed
+ totals.teams_failed += org_counts.teams_failed
+ totals.build_duration += org_counts.build_duration
+ totals.send_duration += org_counts.send_duration
+
+ return totals
+
+
[email protected](name="data-catalog-digest-run-batch")
+async def run_digest_batch(input: DigestBatchInput) -> DigestBatchResult:
+ """Per-org failures are isolated (logged and counted) so one bad org never poisons the batch."""
+ async with Heartbeater():
+ return await database_sync_to_async(_run_digest_batch, thread_sensitive=False)(input)
+
+
+def _push_digest_metrics(totals: DigestBatchResult, success: bool) -> None:
+ if not settings.PROM_PUSHGATEWAY_ADDRESS:
+ return
+
+ try:
+ with pushed_metrics_registry("data_catalog_weekly_digest") as registry:
+ duration_gauge = Gauge(
+ "posthog_data_catalog_digest_duration_seconds",
+ "Time spent in each phase of the data catalog digest run (work time, summed across concurrent batches — not wall-clock)",
+ labelnames=["phase"],
+ registry=registry,
+ )
+ for phase, value in [
+ ("build", totals.build_duration),
+ ("send", totals.send_duration),
+ ("cumulative", totals.total_duration),
+ ]:
+ duration_gauge.labels(phase=phase).set(value)
+
+ orgs_gauge = Gauge(
+ "posthog_data_catalog_digest_orgs",
+ "Org outcomes for a data catalog digest run",
+ labelnames=["outcome"],
+ registry=registry,
+ )
+ for outcome, value in [
+ ("total", totals.batch_size),
+ ("processed", totals.orgs_processed),
+ ("skipped", totals.orgs_skipped),
+ ("failed", totals.orgs_failed),
+ ]:
+ orgs_gauge.labels(outcome=outcome).set(value)
+
+ emails_gauge = Gauge(
+ "posthog_data_catalog_digest_emails",
+ "Email outcomes for a data catalog digest run",
+ labelnames=["outcome"],
+ registry=registry,
+ )
+ for outcome, value in [
+ ("sent", totals.emails_sent),
+ ("skipped_optout", totals.emails_skipped_optout),
+ ("skipped_no_data", totals.emails_skipped_no_data),
+ ("failed", totals.emails_failed),
+ ]:
+ emails_gauge.labels(outcome=outcome).set(value)
+
+ teams_failed_gauge = Gauge(
+ "posthog_data_catalog_digest_teams_failed",
+ "Projects whose pending review could not be built in a data catalog digest run",
+ registry=registry,
+ )
+ teams_failed_gauge.set(totals.teams_failed)
+
+ success_gauge = Gauge(
+ "posthog_data_catalog_digest_success",
+ "1 if the data catalog digest run completed within failure threshold, else 0",
+ registry=registry,
+ )
+ success_gauge.set(1 if success else 0)
+
+ failure_rate_gauge = Gauge(
+ "posthog_data_catalog_digest_failure_rate",
+ "Fraction of orgs whose processing raised an exception in the data catalog digest",
+ registry=registry,
+ )
+ failure_rate_gauge.set(totals.failure_rate)
+
+ last_run_gauge = Gauge(
+ "posthog_data_catalog_digest_last_run_timestamp",
+ "Unix timestamp of the most recent data catalog digest run",
+ registry=registry,
+ )
+ last_run_gauge.set(time.time())
+ except Exception as e:
+ logger.warning("Failed to push data catalog digest metrics to Pushgateway", error=str(e))
+ capture_exception(e)
+
+
[email protected](name="data-catalog-digest-push-metrics")
+async def push_digest_metrics_activity(totals_dict: dict, success: bool) -> None:
+ totals = DigestBatchResult(**totals_dict)
+ await database_sync_to_async(_push_digest_metrics, thread_sensitive=False)(totals, success)
+
+
+def _send_test_digest(email: str) -> None:
+ """The recipient is the matched user's stored email, never the input string,
+ so this cannot be used to redirect a team's data to an arbitrary inbox.
+ """
+ close_old_connections()
+
+ if not is_email_available(with_absolute_urls=True):
+ raise RuntimeError("Email is not available — check EMAIL_HOST in instance settings")
+
+ user = User.objects.filter(email__iexact=email, is_active=True).first()
+ if not user:
+ raise ValueError(f"No active user found with email {email}")
+
+ memberships = list(OrganizationMembership.objects.select_related("organization").filter(user_id=user.id))
+ if not memberships:
+ raise ValueError(f"User {email} has no organization memberships")
+
+ date_suffix = timezone.now().strftime("%Y-%W")
+ sent_count = 0
+ for membership in memberships:
+ org = membership.organization
+ teams_by_id = _project_teams(str(org.id))
+ if not teams_by_id:
+ continue
+ reviews = build_org_pending_reviews(list(teams_by_id.values())).reviews
+ if not reviews:
+ continue
+ outcome = _send_digest_for_user(
+ user=user,
+ org=org,
+ membership=membership,
+ reviews=reviews,
+ teams_by_id=teams_by_id,
+ date_suffix=date_suffix,
+ test=True,
+ )
+ if outcome == DigestOutcome.SENT:
+ sent_count += 1
+
+ if sent_count == 0:
+ raise ValueError(f"User {email} has no accessible projects with anything awaiting review")
+
+ logger.info("Sent test data catalog digest", email=email, emails_sent=sent_count)
+
+
[email protected](name="data-catalog-digest-send-test")
+async def send_test_digest(input: SendTestDigestInput) -> None:
+ await database_sync_to_async(_send_test_digest, thread_sensitive=False)(input.email)
diff --git a/products/data_catalog/backend/temporal/weekly_digest/email_context.py b/products/data_catalog/backend/temporal/weekly_digest/email_context.py
new file mode 100644
index 000000000000..9eb277faaa0e
--- /dev/null
+++ b/products/data_catalog/backend/temporal/weekly_digest/email_context.py
@@ -0,0 +1,67 @@
+from urllib.parse import urlencode
+
+from django.conf import settings
+
+from posthog.helpers.email_utils import sanitize_display_name
+from posthog.models.organization import Organization
+
+from ...logic.pending_review import PendingGroup, PendingKind, TeamPendingReview
+
+UTM_PARAMS = {"utm_source": "data_catalog_weekly_digest", "utm_medium": "email"}
+
+SETTINGS_ANCHOR = "data-catalog-weekly-digest"
+
+MAX_PROJECT_SECTIONS = 10
+
+TEAM_NAME_FALLBACK = "Your project"
+
+
+def catalog_url(team_id: int, kind: PendingKind | None = None) -> str:
+ params = {"tab": kind.value, **UTM_PARAMS} if kind else dict(UTM_PARAMS)
+ return f"{settings.SITE_URL}/project/{team_id}/data-catalog?{urlencode(params)}"
+
+
+def settings_url() -> str:
+ return f"{settings.SITE_URL}/settings/user-notifications?highlight={SETTINGS_ANCHOR}"
+
+
+def build_project_section(review: TeamPendingReview) -> dict:
+ """One project block of the email: its queues, their links, and where the primary button goes."""
+ busiest = max(review.groups, key=lambda group: group.count)
+ return {
+ "team_name": sanitize_display_name(review.team_name, fallback=TEAM_NAME_FALLBACK),
+ "project_url": catalog_url(review.team_id),
+ "total": review.total,
+ "review_url": catalog_url(review.team_id, busiest.kind),
+ "create_metric_url": catalog_url(review.team_id, PendingKind.METRICS),
+ "rows": [_build_row(review.team_id, group) for group in review.groups],
+ }
+
+
+def _build_row(team_id: int, group: PendingGroup) -> dict:
+ sample_names = [name for name in group.sample_names if sanitize_display_name(name, fallback="")]
+ return {
+ "noun": group.noun,
+ "count": group.count,
+ "sample_names": sample_names,
+ "omitted_count": group.count - len(sample_names),
+ "review_url": catalog_url(team_id, group.kind),
+ }
+
+
+def build_template_context(organization: Organization, reviews: list[TeamPendingReview]) -> dict:
+ """The busiest projects first, capped so the email stays under the size mail clients clip at."""
+ busiest_first = sorted(reviews, key=lambda review: review.total, reverse=True)
+ shown = busiest_first[:MAX_PROJECT_SECTIONS]
+ return {
+ "organization": organization,
+ "total": sum(review.total for review in reviews),
+ "project_sections": [build_project_section(review) for review in shown],
+ "omitted_project_count": len(busiest_first) - len(shown),
+ "settings_url": settings_url(),
+ }
+
+
+def build_subject(total: int) -> str:
+ item_word = "item" if total == 1 else "items"
+ return f"{total} {item_word} awaiting review in your data catalog"
diff --git a/products/data_catalog/backend/temporal/weekly_digest/types.py b/products/data_catalog/backend/temporal/weekly_digest/types.py
new file mode 100644
index 000000000000..d31c32b756f2
--- /dev/null
+++ b/products/data_catalog/backend/temporal/weekly_digest/types.py
@@ -0,0 +1,88 @@
+import dataclasses
+from enum import StrEnum
+
+from posthog.temporal.common.digest import DigestBatchTotals
+
+
+class DigestOutcome(StrEnum):
+ """Outcome of attempting to send a single digest email to a single user."""
+
+ SENT = "sent"
+ DRY_RUN = "dry_run"
+ SKIPPED_OPTOUT = "skipped_optout"
+ SKIPPED_NO_DATA = "skipped_no_data"
+ FAILED = "failed"
+
+
[email protected](frozen=False)
+class OrgDigestCounts:
+ """`skipped_reason` is set when the org was skipped before any email attempt
+ (no teams, no targeted members, nothing to review), so the org counts as
+ skipped rather than processed.
+ """
+
+ sent: int = 0
+ skipped_optout: int = 0
+ skipped_no_data: int = 0
+ failed: int = 0
+ team_count: int = 0
+ teams_failed: int = 0
+ build_duration: float = 0.0
+ send_duration: float = 0.0
+ skipped_reason: str | None = None
+
+
[email protected](frozen=True)
+class DataCatalogWeeklyDigestInput:
+ # True so an input-less manual run, such as one started from the Temporal UI, cannot send real
+ # mail. The registered schedule is the one caller that passes False.
+ dry_run: bool = True
+ batch_size: int = 25
+ max_concurrent: int = 4
+ failure_threshold: float = 0.2
+ active_since_days: int | None = 30
+ org_ids: list[str] | None = None
+
+ # Pushgateway deletes every gauge already pushed under the job name, so a scoped or dry run
+ # would replace the week's numbers and advance the last-run timestamp. Only a full real run
+ # speaks for the week.
+ @property
+ def publishes_metrics(self) -> bool:
+ return self.org_ids is None and not self.dry_run
+
+
[email protected](frozen=True)
+class OrgBatchPageInput:
+ workflow_input: DataCatalogWeeklyDigestInput
+ cursor: str | None = None
+ page_size: int = 5000
+
+
[email protected](frozen=True)
+class DigestBatchInput:
+ org_ids: list[str]
+ dry_run: bool = False
+
+
[email protected](frozen=False)
+class DigestBatchResult(DigestBatchTotals):
+ emails_sent: int = 0
+ emails_skipped_optout: int = 0
+ emails_skipped_no_data: int = 0
+ emails_failed: int = 0
+
+
[email protected](frozen=True)
+class SendTestDigestInput:
+ """Input for the test activity.
+
+ Sends the user their real digest for every organization they belong to, bypassing the
+ notification setting and the feature flag. Organization membership and project access are
+ always enforced.
+ """
+
+ email: str
+
+
+DATA_CATALOG_DIGEST_THRESHOLD_EXCEEDED_TYPE = "DataCatalogDigestThresholdExceeded"
+DATA_CATALOG_DIGEST_EMAIL_UNAVAILABLE_TYPE = "DataCatalogDigestEmailUnavailable"
diff --git a/products/data_catalog/backend/temporal/weekly_digest/workflows.py b/products/data_catalog/backend/temporal/weekly_digest/workflows.py
new file mode 100644
index 000000000000..7ce70864e48e
--- /dev/null
+++ b/products/data_catalog/backend/temporal/weekly_digest/workflows.py
@@ -0,0 +1,152 @@
+import json
+import asyncio
+import dataclasses
+from datetime import timedelta
+
+from temporalio import common, workflow
+from temporalio.exceptions import ApplicationError
+
+from posthog.temporal.common.base import PostHogWorkflow
+
+with workflow.unsafe.imports_passed_through():
+ from posthog.temporal.common.digest import ACTIVITY_RETRY_POLICY
+
+ from .activities import get_org_batch_page, push_digest_metrics_activity, run_digest_batch, send_test_digest
+ from .types import (
+ DATA_CATALOG_DIGEST_THRESHOLD_EXCEEDED_TYPE,
+ DataCatalogWeeklyDigestInput,
+ DigestBatchInput,
+ DigestBatchResult,
+ OrgBatchPageInput,
+ SendTestDigestInput,
+ )
+
+WORKFLOW_NAME = "data-catalog-weekly-digest"
+TEST_WORKFLOW_NAME = "data-catalog-weekly-digest-test"
+
+
[email protected](name=WORKFLOW_NAME)
+class DataCatalogWeeklyDigestWorkflow(PostHogWorkflow):
+ # The base parse_inputs rejects a key that is not a field. A typo in the scope therefore fails
+ # the command, instead of dropping the scope and running over every organization.
+ inputs_cls = DataCatalogWeeklyDigestInput
+ inputs_optional = True
+
+ @workflow.run
+ async def run(self, input: DataCatalogWeeklyDigestInput | None = None) -> dict:
+ if input is None:
+ input = DataCatalogWeeklyDigestInput()
+
+ totals = DigestBatchResult()
+ failed_batches = 0
+ batch_count = 0
+ cursor: str | None = None
+ semaphore = asyncio.Semaphore(input.max_concurrent)
+
+ async def _run_batch(batch: list[str]) -> DigestBatchResult:
+ async with semaphore:
+ return await workflow.execute_activity(
+ run_digest_batch,
+ DigestBatchInput(org_ids=batch, dry_run=input.dry_run),
+ start_to_close_timeout=timedelta(minutes=30),
+ heartbeat_timeout=timedelta(minutes=5),
+ retry_policy=ACTIVITY_RETRY_POLICY,
+ )
+
+ while True:
+ page = await workflow.execute_activity(
+ get_org_batch_page,
+ OrgBatchPageInput(workflow_input=input, cursor=cursor),
+ start_to_close_timeout=timedelta(minutes=5),
+ retry_policy=ACTIVITY_RETRY_POLICY,
+ )
+
+ if page.batches:
+ workflow.logger.info(
+ "Fanning out data catalog digest page",
+ extra={
+ "batches": len(page.batches),
+ "orgs": page.org_count,
+ "cursor": cursor,
+ "next_cursor": page.cursor,
+ },
+ )
+
+ batch_count += len(page.batches)
+ results = await asyncio.gather(
+ *[_run_batch(b) for b in page.batches],
+ return_exceptions=True,
+ )
+
+ for batch, r in zip(page.batches, results):
+ if isinstance(r, BaseException):
+ failed_batches += 1
+ totals += DigestBatchResult(batch_size=len(batch), orgs_failed=len(batch))
+ workflow.logger.error("Data catalog digest batch failed: %s", str(r))
+ else:
+ totals += r
+
+ if page.cursor is None:
+ break
+ cursor = page.cursor
+
+ if batch_count == 0:
+ workflow.logger.info("No org batches for data catalog weekly digest")
+
+ threshold_exceeded = totals.batch_size > 0 and totals.failure_rate > input.failure_threshold
+
+ if input.publishes_metrics:
+ await workflow.execute_activity(
+ push_digest_metrics_activity,
+ args=[dataclasses.asdict(totals), not threshold_exceeded],
+ start_to_close_timeout=timedelta(minutes=2),
+ retry_policy=ACTIVITY_RETRY_POLICY,
+ )
+
+ if threshold_exceeded:
+ raise ApplicationError(
+ f"Data catalog weekly digest: {totals.orgs_failed:,}/{totals.batch_size:,} orgs failed "
+ f"({totals.failure_rate:.1%}), exceeds threshold {input.failure_threshold:.1%} "
+ f"(skipped={totals.orgs_skipped:,} not counted toward failure rate)",
+ type=DATA_CATALOG_DIGEST_THRESHOLD_EXCEEDED_TYPE,
+ non_retryable=True,
+ )
+
+ return {
+ "orgs": totals.batch_size,
+ "batches": batch_count,
+ "failed_batches": failed_batches,
+ "emails_sent": totals.emails_sent,
+ "emails_failed": totals.emails_failed,
+ "teams_failed": totals.teams_failed,
+ "cumulative_duration_seconds": totals.total_duration,
+ }
+
+
[email protected](name=TEST_WORKFLOW_NAME)
+class DataCatalogWeeklyDigestTestWorkflow(PostHogWorkflow):
+ """Send a test digest, bypassing the notification setting and the feature flag."""
+
+ @staticmethod
+ def parse_inputs(inputs: list[str]) -> SendTestDigestInput:
+ """Parse inputs from the management command CLI.
+
+ Usage:
+ manage.py start_temporal_workflow data-catalog-weekly-digest-test '{"email": "[email protected]"}'
+
+ Outside local development, add `--task-queue weekly-digest-task-queue`. The command
+ defaults to the general-purpose queue, which no worker polls for this workflow, so the run
+ waits instead of failing. Local runs need no flag, because every queue resolves to the
+ development queue there.
+ """
+ data = json.loads(inputs[0])
+ return SendTestDigestInput(email=data["email"])
+
+ @workflow.run
+ async def run(self, input: SendTestDigestInput) -> None:
+ await workflow.execute_activity(
+ send_test_digest,
+ input,
+ start_to_close_timeout=timedelta(minutes=10),
+ retry_policy=common.RetryPolicy(maximum_attempts=1),
+ )
diff --git a/products/data_catalog/backend/tests/test_pending_review.py b/products/data_catalog/backend/tests/test_pending_review.py
index 073f2e8e5209..f772ba66e9bf 100644
--- a/products/data_catalog/backend/tests/test_pending_review.py
+++ b/products/data_catalog/backend/tests/test_pending_review.py
@@ -1,12 +1,18 @@
+from collections.abc import Iterator
+from contextlib import contextmanager
from datetime import timedelta
+import pytest
from posthog.test.base import BaseTest
+from unittest.mock import patch
+from django.db.models import QuerySet
from django.utils import timezone
from posthog.models.team import Team
from products.data_catalog.backend.facade.enums import CertificationStatus, MetricStatus, RelationshipStatus
+from products.data_catalog.backend.logic.metrics import metrics_for_team
from products.data_catalog.backend.logic.pending_review import (
PendingKind,
build_org_pending_reviews,
@@ -15,6 +21,19 @@ from products.data_catalog.backend.logic.pending_review import (
from products.data_catalog.backend.models import Metric, RelationshipProposal, TableCertification
from products.data_modeling.backend.facade.models import DataWarehouseSavedQuery
+_PENDING_REVIEW = "products.data_catalog.backend.logic.pending_review"
+
+
+@contextmanager
+def _failing_build_for(broken_team: Team) -> Iterator[None]:
+ def metrics_for_team_failing_one_team(team: Team) -> QuerySet[Metric]:
+ if team.id == broken_team.id:
+ raise RuntimeError("catalog unavailable")
+ return metrics_for_team(team)
+
+ with patch(f"{_PENDING_REVIEW}.metrics_for_team", side_effect=metrics_for_team_failing_one_team):
+ yield
+
def _metric(team: Team, name: str, **kwargs) -> Metric:
return Metric.objects.unscoped().create(team=team, name=name, description="d", **kwargs)
@@ -107,7 +126,22 @@ class TestBuildOrgPendingReviews(BaseTest):
quiet_team = Team.objects.create(organization=self.organization, name="Quiet")
_metric(self.team, "proposed_one")
- reviews = build_org_pending_reviews([self.team, quiet_team])
+ build = build_org_pending_reviews([self.team, quiet_team])
+
+ assert list(build.reviews) == [self.team.id]
+ assert build.reviews[self.team.id].total == 1
+ assert build.failed_team_ids == []
+
+ def test_reports_a_team_whose_build_raised_and_keeps_the_others(self) -> None:
+ broken_team = Team.objects.create(organization=self.organization, name="Broken")
+ _metric(self.team, "proposed_one")
+
+ with _failing_build_for(broken_team):
+ build = build_org_pending_reviews([self.team, broken_team])
+
+ assert list(build.reviews) == [self.team.id]
+ assert build.failed_team_ids == [broken_team.id]
- assert list(reviews) == [self.team.id]
- assert reviews[self.team.id].total == 1
+ def test_raises_when_every_team_failed(self) -> None:
+ with _failing_build_for(self.team), pytest.raises(RuntimeError):
+ build_org_pending_reviews([self.team])
diff --git a/products/data_catalog/backend/tests/test_weekly_digest.py b/products/data_catalog/backend/tests/test_weekly_digest.py
new file mode 100644
index 000000000000..d61bb7f32353
--- /dev/null
+++ b/products/data_catalog/backend/tests/test_weekly_digest.py
@@ -0,0 +1,352 @@
+from datetime import timedelta
+
+import pytest
+from posthog.test.base import APIBaseTest
+from unittest import mock
+from unittest.mock import MagicMock, patch
+
+from django.conf import settings
+from django.test import SimpleTestCase, override_settings
+from django.utils import timezone
+
+from parameterized import parameterized
+from temporalio.client import Schedule, ScheduleActionStartWorkflow
+
+from posthog.constants import AvailableFeature
+from posthog.models import Organization, OrganizationMembership, Team
+from posthog.models.organization_notification_lock import OrganizationMemberNotificationLock
+
+from products.access_control.backend.models.access_control import AccessControl
+from products.data_catalog.backend.logic.pending_review import PendingGroup, PendingKind, TeamPendingReview
+from products.data_catalog.backend.models import Metric
+from products.data_catalog.backend.temporal.schedule import create_data_catalog_weekly_digest_schedule
+from products.data_catalog.backend.temporal.weekly_digest.activities import (
+ _build_and_send_for_org,
+ _get_org_batch_page,
+ _send_digest_for_user,
+)
+from products.data_catalog.backend.temporal.weekly_digest.email_context import (
+ MAX_PROJECT_SECTIONS,
+ build_project_section,
+ build_subject,
+ build_template_context,
+ catalog_url,
+)
+from products.data_catalog.backend.temporal.weekly_digest.types import (
+ DataCatalogWeeklyDigestInput,
+ DigestOutcome,
+ OrgBatchPageInput,
+)
+from products.data_catalog.backend.temporal.weekly_digest.workflows import DataCatalogWeeklyDigestWorkflow
+
+_ACTIVITIES = "products.data_catalog.backend.temporal.weekly_digest.activities"
+
+
+def _review(team: Team, metrics: int = 2, certifications: int = 1) -> TeamPendingReview:
+ groups = [
+ PendingGroup(kind=PendingKind.METRICS, noun="metric", count=metrics, sample_names=["revenue"]),
+ PendingGroup(
+ kind=PendingKind.CERTIFICATIONS,
+ noun="certification",
+ count=certifications,
+ sample_names=["customer_facts"],
+ ),
+ ]
+ return TeamPendingReview(
+ team_id=team.id,
+ team_name=team.name,
+ groups=groups,
+ total=metrics + certifications,
+ )
+
+
+def _pending_metrics(team_id: int, count: int, sample_names: list[str], team_name: str = "Acme") -> TeamPendingReview:
+ return TeamPendingReview(
+ team_id=team_id,
+ team_name=team_name,
+ groups=[PendingGroup(kind=PendingKind.METRICS, noun="metric", count=count, sample_names=sample_names)],
+ total=count,
+ )
+
+
+class TestEmailContext(SimpleTestCase):
+ @parameterized.expand(
+ [(1, "1 item awaiting review in your data catalog"), (4, "4 items awaiting review in your data catalog")]
+ )
+ def test_subject_counts_items(self, total: int, expected: str) -> None:
+ assert build_subject(total) == expected
+
+ def test_review_links_open_the_tab_that_holds_the_queue(self) -> None:
+ assert catalog_url(7, PendingKind.RELATIONSHIPS) == (
+ f"{settings.SITE_URL}/project/7/data-catalog"
+ "?tab=relationships&utm_source=data_catalog_weekly_digest&utm_medium=email"
+ )
+
+ def test_primary_button_opens_the_busiest_queue(self) -> None:
+ review = TeamPendingReview(
+ team_id=7,
+ team_name="Acme",
+ groups=[
+ PendingGroup(kind=PendingKind.METRICS, noun="metric", count=1, sample_names=["revenue"]),
+ PendingGroup(kind=PendingKind.RELATIONSHIPS, noun="relationship", count=9, sample_names=["a to b"]),
+ ],
+ total=10,
+ )
+
+ section = build_project_section(review)
+
+ assert "tab=relationships" in section["review_url"]
+ assert section["rows"][0]["omitted_count"] == 0
+ assert section["rows"][1]["omitted_count"] == 8
+
+ def test_url_shaped_names_never_reach_the_email(self) -> None:
+ review = _pending_metrics(
+ team_id=7, count=3, sample_names=["revenue", "https://phishing.example"], team_name="www.phishing.example"
+ )
+
+ section = build_project_section(review)
+
+ assert section["team_name"] == "Your project"
+ assert section["rows"][0]["sample_names"] == ["revenue"]
+ assert section["rows"][0]["omitted_count"] == 2
+
+ def test_lists_the_busiest_projects_and_counts_the_rest(self) -> None:
+ counts = range(1, MAX_PROJECT_SECTIONS + 2)
+ reviews = [_pending_metrics(team_id=count, count=count, sample_names=[]) for count in counts]
+
+ context = build_template_context(Organization(name="Acme"), reviews)
+
+ assert [section["total"] for section in context["project_sections"]] == sorted(counts, reverse=True)[
+ :MAX_PROJECT_SECTIONS
+ ]
+ assert context["omitted_project_count"] == 1
+ assert context["total"] == sum(counts)
+
+
+class TestSendDigestForUser(APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.is_email_patcher = patch(f"{_ACTIVITIES}.is_email_available", return_value=True)
+ self.is_email_patcher.start()
+ self.email_class_patcher = patch(f"{_ACTIVITIES}.EmailMessage")
+ self.mock_email_class = self.email_class_patcher.start()
+ self.mock_message = MagicMock()
+ self.mock_email_class.return_value = self.mock_message
+
+ def tearDown(self) -> None:
+ self.is_email_patcher.stop()
+ self.email_class_patcher.stop()
+ super().tearDown()
+
+ def _send(self, *, dry_run: bool = False, test: bool = False) -> DigestOutcome:
+ return _send_digest_for_user(
+ user=self.user,
+ org=self.organization,
+ membership=self.organization_membership,
+ reviews={self.team.id: _review(self.team)},
+ teams_by_id={self.team.id: self.team},
+ date_suffix="2026-15",
+ dry_run=dry_run,
+ test=test,
+ )
+
+ def test_sends_with_default_notification_settings(self) -> None:
+ outcome = self._send()
+
+ assert outcome == DigestOutcome.SENT
+ kwargs = self.mock_email_class.call_args.kwargs
+ assert kwargs["subject"] == "3 items awaiting review in your data catalog"
+ assert kwargs["template_context"]["total"] == 3
+ self.mock_message.add_user_recipient.assert_called_once_with(self.user)
+ self.mock_message.send.assert_called_once()
+
+ def test_skips_when_the_user_turned_the_digest_off(self) -> None:
+ self.user.partial_notification_settings = {"data_catalog_weekly_digest": False}
+ self.user.save()
+
+ assert self._send() == DigestOutcome.SKIPPED_OPTOUT
+ self.mock_email_class.assert_not_called()
+
+ def test_sends_anyway_in_test_mode_and_never_dedupes(self) -> None:
+ self.user.partial_notification_settings = {"data_catalog_weekly_digest": False}
+ self.user.save()
+
+ assert self._send(test=True) == DigestOutcome.SENT
+ assert "_test_" in self.mock_email_class.call_args.kwargs["campaign_key"]
+
+ def test_campaign_key_is_stable_within_a_week(self) -> None:
+ self._send()
+ first = self.mock_email_class.call_args.kwargs["campaign_key"]
+ self._send()
+ second = self.mock_email_class.call_args.kwargs["campaign_key"]
+
+ assert first == second
+ assert str(self.user.uuid) in first
+
+ def test_dry_run_sends_nothing(self) -> None:
+ assert self._send(dry_run=True) == DigestOutcome.DRY_RUN
+ self.mock_email_class.assert_not_called()
+
+ @parameterized.expand([("project", True), ("data_catalog", False)])
+ def test_skips_a_project_the_user_cannot_read(self, denied_resource: str, scoped_to_team: bool) -> None:
+ AccessControl.objects.create(
+ team=self.team,
+ resource=denied_resource,
+ resource_id=str(self.team.id) if scoped_to_team else None,
+ access_level="none",
+ )
+ self.organization.available_product_features = [{"key": AvailableFeature.ACCESS_CONTROL, "name": "access"}]
+ self.organization.save()
+ self.organization_membership.level = OrganizationMembership.Level.MEMBER
+ self.organization_membership.save()
+
+ assert self._send() == DigestOutcome.SKIPPED_NO_DATA
+ self.mock_email_class.assert_not_called()
+
+
+class TestBuildAndSendForOrg(APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.is_email_patcher = patch(f"{_ACTIVITIES}.is_email_available", return_value=True)
+ self.is_email_patcher.start()
+ self.email_class_patcher = patch(f"{_ACTIVITIES}.EmailMessage")
+ self.mock_email_class = self.email_class_patcher.start()
+ self.mock_email_class.return_value = MagicMock()
+ self.close_conn_patcher = patch(f"{_ACTIVITIES}.close_old_connections")
+ self.close_conn_patcher.start()
+ self.flag_patcher = patch(f"{_ACTIVITIES}._is_user_flag_enabled", return_value=True)
+ self.flag_patcher.start()
+ Metric.objects.unscoped().create(team=self.team, name="proposed_one", description="d")
+
+ def tearDown(self) -> None:
+ self.flag_patcher.stop()
+ self.close_conn_patcher.stop()
+ self.is_email_patcher.stop()
+ self.email_class_patcher.stop()
+ super().tearDown()
+
+ @parameterized.expand([(True, 1), (False, 0)])
+ def test_only_active_accounts_receive_the_digest(self, is_active: bool, expected_sent: int) -> None:
+ self.user.is_active = is_active
+ self.user.save()
+
+ counts = _build_and_send_for_org(str(self.organization.id))
+
+ assert counts.sent == expected_sent
+
+ @parameterized.expand(
+ [
+ ("open", {}, 1),
+ ("never_deactivated", {"is_active": None}, 1),
+ ("deactivated", {"is_active": False}, 0),
+ ("pending_deletion", {"is_pending_deletion": True}, 0),
+ ]
+ )
+ def test_an_organization_the_app_blocks_receives_nothing(self, _name, fields, expected_sent) -> None:
+ for field, value in fields.items():
+ setattr(self.organization, field, value)
+ self.organization.save()
+
+ counts = _build_and_send_for_org(str(self.organization.id))
+
+ assert counts.sent == expected_sent
+
+ @parameterized.expand([("this_org", 0), ("other_org", 1)])
+ def test_only_the_sending_organization_locks_its_own_digest(self, locking_org: str, expected_sent: int) -> None:
+ other_org = Organization.objects.create(name="Other")
+ other_membership = OrganizationMembership.objects.create(organization=other_org, user=self.user)
+ lock_membership = self.organization_membership if locking_org == "this_org" else other_membership
+ OrganizationMemberNotificationLock.objects.create(
+ organization=lock_membership.organization,
+ organization_membership=lock_membership,
+ setting="data_catalog_weekly_digest",
+ locked_value=False,
+ )
+
+ counts = _build_and_send_for_org(str(self.organization.id))
+
+ assert counts.sent == expected_sent
+
+
+class TestOrgBatchPage(APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.is_email_patcher = patch(f"{_ACTIVITIES}.is_email_available", return_value=True)
+ self.is_email_patcher.start()
+ self.close_conn_patcher = patch(f"{_ACTIVITIES}.close_old_connections")
+ self.close_conn_patcher.start()
+ self.user.last_login = timezone.now()
+ self.user.save()
+
+ def tearDown(self) -> None:
+ self.close_conn_patcher.stop()
+ self.is_email_patcher.stop()
+ super().tearDown()
+
+ def _page(self, org_ids: list[str] | None) -> list[str]:
+ result = _get_org_batch_page(OrgBatchPageInput(workflow_input=DataCatalogWeeklyDigestInput(org_ids=org_ids)))
+ return [org_id for batch in result.batches for org_id in batch]
+
+ def test_an_empty_target_list_selects_no_organizations(self) -> None:
+ assert self._page([]) == []
+
+ def test_no_target_list_discovers_active_organizations(self) -> None:
+ assert str(self.organization.id) in self._page(None)
+
+
+# The workflow is registered on WEEKLY_DIGEST_TASK_QUEUE by the worker bootstrap, but the schedule
+# names its queue in a different file. If the two drift the digest fires into a queue nobody polls,
+# and nothing surfaces it for a week, because the digest runs once a week. The schedule is also
+# the one caller that must send for real, since dry_run defaults to True as a manual-run fail-safe.
+@override_settings(WEEKLY_DIGEST_TASK_QUEUE="weekly-digest-task-queue-under-test")
+async def test_the_registered_schedule_is_live_on_the_weekly_digest_queue() -> None:
+ captured: list[Schedule] = []
+ schedule_module = "products.data_catalog.backend.temporal.schedule"
+
+ with (
+ mock.patch(f"{schedule_module}.a_schedule_exists", new=mock.AsyncMock(return_value=False)),
+ mock.patch(
+ f"{schedule_module}.a_create_schedule",
+ new=mock.AsyncMock(side_effect=lambda client, schedule_id, schedule, **kwargs: captured.append(schedule)),
+ ),
+ ):
+ await create_data_catalog_weekly_digest_schedule(mock.MagicMock())
+
+ action = captured[0].action
+ assert isinstance(action, ScheduleActionStartWorkflow)
+ assert action.task_queue == settings.WEEKLY_DIGEST_TASK_QUEUE
+ assert action.args == [DataCatalogWeeklyDigestInput(dry_run=False)]
+ # Overlap defaults to SKIP, so an unbounded run would drop every later Tuesday for good.
+ assert action.execution_timeout is not None
+ assert action.execution_timeout < timedelta(days=7)
+
+
+def test_an_inputless_manual_run_does_not_send() -> None:
+ assert DataCatalogWeeklyDigestWorkflow.parse_inputs([]).dry_run is True
+
+
+def test_a_mistyped_scope_key_fails_instead_of_widening_the_run() -> None:
+ with pytest.raises(TypeError):
+ DataCatalogWeeklyDigestWorkflow.parse_inputs(['{"org_idz": ["abc"], "dry_run": false}'])
+
+ parsed = DataCatalogWeeklyDigestWorkflow.parse_inputs(['{"org_ids": ["abc"], "dry_run": false}'])
+ assert parsed.org_ids == ["abc"]
+ assert parsed.dry_run is False
+
+
+# Pushgateway deletes every gauge already pushed under the digest's job name. A manual run that
+# published would stand in for the weekly result and advance the last-run timestamp, so a staleness
+# alert would read healthy through a week that sent nothing.
+ "workflow_input,publishes",
+ [
+ (DataCatalogWeeklyDigestInput(dry_run=False), True),
+ (DataCatalogWeeklyDigestInput(), False),
+ (DataCatalogWeeklyDigestInput(dry_run=False, org_ids=["abc"]), False),
+ ],
+)
+def test_only_the_full_real_run_publishes_metrics(
+ workflow_input: DataCatalogWeeklyDigestInput, publishes: bool
+) -> None:
+ assert workflow_input.publishes_metrics is publishes
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 338d5d849054..d46a99d62e13 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -62645,6 +62645,7 @@ export namespace Schemas {
}
/**
+ * * `data_catalog_weekly_digest` - data_catalog_weekly_digest
* * `discussions_mentioned` - discussions_mentioned
* * `error_tracking_issue_assigned` - error_tracking_issue_assigned
* * `error_tracking_weekly_digest_project_enabled` - error_tracking_weekly_digest_project_enabled
@@ -62660,6 +62661,7 @@ export namespace Schemas {
export const SettingEnum = {
+ DataCatalogWeeklyDigest: 'data_catalog_weekly_digest',
DiscussionsMentioned: 'discussions_mentioned',
ErrorTrackingIssueAssigned: 'error_tracking_issue_assigned',
ErrorTrackingWeeklyDigestProjectEnabled: 'error_tracking_weekly_digest_project_enabled',
@@ -62675,6 +62677,7 @@ export namespace Schemas {
export interface OrganizationNotificationLock {
/** Notification setting this rule enforces.
*
+ * * `data_catalog_weekly_digest` - data_catalog_weekly_digest
* * `discussions_mentioned` - discussions_mentioned
* * `error_tracking_issue_assigned` - error_tracking_issue_assigned
* * `error_tracking_weekly_digest_project_enabled` - error_tracking_weekly_digest_project_enabled
@@ -62697,6 +62700,7 @@ export namespace Schemas {
user_id: number;
/** Notification setting to lock or unlock.
*
+ * * `data_catalog_weekly_digest` - data_catalog_weekly_digest
* * `discussions_mentioned` - discussions_mentioned
* * `error_tracking_issue_assigned` - error_tracking_issue_assigned
* * `error_tracking_weekly_digest_project_enabled` - error_tracking_weekly_digest_project_enabled