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(workflows): add an add to static cohort workflow step (#120041)

Harley Alexander250b5130813b
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index bbff6e27b4fe..cc2f6e14c77c 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -595,6 +595,7 @@ export const FEATURE_FLAGS = {
WEB_ANALYTICS_TILE_TOGGLES: 'web-analytics-tile-toggles', // owner: @lricoy #team-web-analytics
WIZARD_RUN_SYNC: 'wizard-run-sync', // owner: #team-growth multivariate=wizard-session,wizard-run — selects the Wizard sync widget
WIZARD_UI_ENABLED: 'wizard-ui-enabled', // owner: @fercgomes #team-growth — gates the /wizard/runs interface
+ WORKFLOW_ADD_TO_STATIC_COHORT_ACTION: 'workflow-add-to-static-cohort-action', // owner: #team-workflows
WORKFLOW_AI_TASK_ACTION: 'workflow-ai-task-action', // owner: @mayteio #team-workflows
WORKFLOW_CLASSIFY_ACTION: 'workflow-classify-action', // owner: #team-workflows
WORKFLOWS_AI_EMAIL_DRAFT: 'workflows-ai-email-draft', // owner: @dmarchuk #team-workflows, AI first draft for cross-product entry points
diff --git a/nodejs/src/cdp/async-functions/add-to-static-cohort.ts b/nodejs/src/cdp/async-functions/add-to-static-cohort.ts
new file mode 100644
index 000000000000..31a9226f5194
--- /dev/null
+++ b/nodejs/src/cdp/async-functions/add-to-static-cohort.ts
@@ -0,0 +1,68 @@
+import { DateTime } from 'luxon'
+
+import { HogFlow } from '~/cdp/schema/hogflow'
+import { defaultConfig } from '~/common/config/config'
+
+import { registerAsyncFunction } from '../async-function-registry'
+import { PosthogJwtAudience } from '../utils/jwt-utils'
+import { ScopedServiceJwt } from '../utils/scoped-service-jwt'
+import { UUID_RE, callInternalApi } from './internal-api-call'
+
+let addToStaticCohortJwt: ScopedServiceJwt | undefined
+const getAddToStaticCohortJwt = (): ScopedServiceJwt =>
+ (addToStaticCohortJwt ??= new ScopedServiceJwt(
+ PosthogJwtAudience.WORKFLOW_ADD_TO_STATIC_COHORT,
+ defaultConfig.WORKFLOW_ADD_TO_STATIC_COHORT_JWT_SECRET
+ ))
+
+// Django waits up to 5 seconds for another run that adds the same person, then inserts.
+const ADD_TO_STATIC_COHORT_TIMEOUT_MS = 15_000
+
+// The step test panel mocks async functions by default, so `mock` runs these checks too.
+const parsePayload = (args: any[]): { cohort_id: number; person_uuid: string } => {
+ const [payload] = args as [{ cohort_id?: unknown; person_uuid?: unknown } | undefined]
+ const cohortId = payload?.cohort_id
+ if (typeof cohortId !== 'number' || !Number.isSafeInteger(cohortId) || cohortId < 1) {
+ throw new Error('Choose a static cohort')
+ }
+ if (typeof payload?.person_uuid !== 'string' || !UUID_RE.test(payload.person_uuid)) {
+ throw new Error('This workflow run has no person to add')
+ }
+ return { cohort_id: cohortId, person_uuid: payload.person_uuid }
+}
+
+registerAsyncFunction('postHogAddToStaticCohort', {
+ execute: async (args, context, result) => {
+ const payload = parsePayload(args)
+
+ const hogFlow = (context.invocation as { hogFlow?: HogFlow }).hogFlow
+ if (!hogFlow?.id) {
+ throw new Error('Add to static cohort only runs inside a workflow')
+ }
+
+ const jwt = getAddToStaticCohortJwt()
+ if (!jwt.enabled) {
+ throw new Error(
+ 'Add to static cohort is not configured. Set WORKFLOW_ADD_TO_STATIC_COHORT_JWT_SECRET on the worker and Django to matching keys.'
+ )
+ }
+ // Repeating the call is safe because Django skips a person who is already in the cohort.
+ await callInternalApi(context, result, {
+ jwt,
+ path: `/api/projects/${context.invocation.teamId}/workflow_static_cohort_members/`,
+ method: 'POST',
+ entityClaims: { hog_flow_id: hogFlow.id },
+ body: JSON.stringify(payload),
+ timeoutMs: ADD_TO_STATIC_COHORT_TIMEOUT_MS,
+ })
+ },
+ mock: (args, logs) => {
+ parsePayload(args)
+ logs.push({
+ level: 'info',
+ timestamp: DateTime.now(),
+ message: 'Add to static cohort was mocked. Nobody was added to the cohort.',
+ })
+ return { status: 200, body: { detail: 'The person is in the static cohort.' } }
+ },
+})
diff --git a/nodejs/src/cdp/async-functions/index.ts b/nodejs/src/cdp/async-functions/index.ts
index cd6f911f0611..f584e4725752 100644
--- a/nodejs/src/cdp/async-functions/index.ts
+++ b/nodejs/src/cdp/async-functions/index.ts
@@ -1,3 +1,4 @@
+import './add-to-static-cohort'
import './classify'
import './conversations'
import './create-customer-task'
diff --git a/nodejs/src/cdp/config.ts b/nodejs/src/cdp/config.ts
index cf973ce6788f..6f1eaff31f18 100644
--- a/nodejs/src/cdp/config.ts
+++ b/nodejs/src/cdp/config.ts
@@ -235,6 +235,8 @@ export type CdpConfig = ClickhouseConfig & {
// Scoped JWT keys signing the workflow engine's Replay Vision scan calls to Django. Its own key for the
// same reason as the run-scout one, with the same rotation and fail-closed-when-empty semantics.
WORKFLOW_VISION_REQUEST_JWT_SECRET: string
+ // Scoped JWT keys signing the workflow engine's "Add to static cohort" calls to Django. Its own key, for the same reason.
+ WORKFLOW_ADD_TO_STATIC_COHORT_JWT_SECRET: string
CYCLOTRON_NODE_RESCHEDULE_FLOOR_SECONDS: number
CYCLOTRON_NODE_RESCHEDULE_WAKE_RATE_PER_SECOND: number
CYCLOTRON_NODE_RESCHEDULE_MIN_WINDOW_SECONDS: number
@@ -447,6 +449,9 @@ export function getDefaultCdpConfig(): CdpConfig {
// Dev/test default must match Django's (posthog/settings/data_stores.py).
WORKFLOW_CLASSIFY_JWT_SECRET: isTestEnv() || isDevEnv() ? 'local-dev-workflow-classify-jwt' : '',
WORKFLOW_VISION_REQUEST_JWT_SECRET: isTestEnv() || isDevEnv() ? 'local-dev-workflow-vision-request-jwt' : '',
+ // Dev/test default must match Django's (posthog/settings/data_stores.py).
+ WORKFLOW_ADD_TO_STATIC_COHORT_JWT_SECRET:
+ isTestEnv() || isDevEnv() ? 'local-dev-workflow-add-to-static-cohort-jwt' : '',
CYCLOTRON_NODE_RESCHEDULE_FLOOR_SECONDS: 600,
CYCLOTRON_NODE_RESCHEDULE_WAKE_RATE_PER_SECOND: 200,
CYCLOTRON_NODE_RESCHEDULE_MIN_WINDOW_SECONDS: 300,
diff --git a/nodejs/src/cdp/templates/_destinations/posthog_workflows/posthog-add-to-static-cohort.template.ts b/nodejs/src/cdp/templates/_destinations/posthog_workflows/posthog-add-to-static-cohort.template.ts
new file mode 100644
index 000000000000..9dc2329d25da
--- /dev/null
+++ b/nodejs/src/cdp/templates/_destinations/posthog_workflows/posthog-add-to-static-cohort.template.ts
@@ -0,0 +1,40 @@
+import { HogFunctionTemplate } from '~/cdp/types'
+
+import { hogApiErrorMessageFn } from '../../hog-helpers'
+
+export const template: HogFunctionTemplate = {
+ free: true,
+ status: 'hidden',
+ type: 'destination',
+ id: 'template-posthog-add-to-static-cohort',
+ name: 'Add to static cohort',
+ description: 'Add the person to a static cohort.',
+ icon_url: '/static/posthog-icon.svg',
+ category: ['Custom'],
+ code_language: 'hog',
+ code: `
+${hogApiErrorMessageFn}
+
+let response := postHogAddToStaticCohort({
+ 'cohort_id': inputs.cohort_id,
+ 'person_uuid': person.id
+})
+
+if (response.status >= 400) {
+ throw Error(f'Could not add the person to the static cohort ({response.status}): {apiErrorMessage(response)}')
+}
+
+print(response.body.detail)
+`,
+ inputs_schema: [
+ {
+ key: 'cohort_id',
+ type: 'number',
+ label: 'Static cohort',
+ required: true,
+ // The callback compares this value with the cohorts the saved workflow names, so it can't be a template.
+ templating: false,
+ description: 'The static cohort to add the person to.',
+ },
+ ],
+}
diff --git a/nodejs/src/cdp/templates/index.ts b/nodejs/src/cdp/templates/index.ts
index e722d5bbd94d..ebafb94cc0b7 100644
--- a/nodejs/src/cdp/templates/index.ts
+++ b/nodejs/src/cdp/templates/index.ts
@@ -39,6 +39,7 @@ import { template as posthogUpdateAccountTemplate } from './_destinations/postho
import { template as posthogReplayVisionTemplate } from './_destinations/posthog_replay_vision/posthog-replay-vision.template'
import { template as posthogRunScoutTemplate } from './_destinations/posthog_signals/posthog-run-scout.template'
import { template as posthogCreateTaskTemplate } from './_destinations/posthog_tasks/posthog-create-task.template'
+import { template as posthogAddToStaticCohortTemplate } from './_destinations/posthog_workflows/posthog-add-to-static-cohort.template'
import { template as posthogClassifyTemplate } from './_destinations/posthog_workflows/posthog-classify.template'
import { template as posthogSetHogflowVariableTemplate } from './_destinations/posthog_workflows/posthog-set-variable.template'
import { template as pushTemplate } from './_destinations/push/push.template'
@@ -114,6 +115,7 @@ export const HOG_FUNCTION_TEMPLATES_DESTINATIONS: HogFunctionTemplate[] = [
posthogCreateTaskTemplate,
posthogRunScoutTemplate,
posthogClassifyTemplate,
+ posthogAddToStaticCohortTemplate,
posthogReplayVisionTemplate,
posthogCreateAccountTemplate,
posthogCreateCustomerTaskTemplate,
diff --git a/nodejs/src/cdp/utils/jwt-utils.ts b/nodejs/src/cdp/utils/jwt-utils.ts
index 2483297c32b0..8bde14e7ee5d 100644
--- a/nodejs/src/cdp/utils/jwt-utils.ts
+++ b/nodejs/src/cdp/utils/jwt-utils.ts
@@ -15,6 +15,8 @@ export enum PosthogJwtAudience {
WORKFLOW_CLASSIFY = 'posthog:workflows:classify',
// Must match PosthogJwtAudience.WORKFLOW_VISION_REQUEST in posthog/jwt.py exactly.
WORKFLOW_VISION_REQUEST = 'posthog:workflows:vision_request',
+ // Must match PosthogJwtAudience.WORKFLOW_ADD_TO_STATIC_COHORT in posthog/jwt.py exactly.
+ WORKFLOW_ADD_TO_STATIC_COHORT = 'posthog:workflows:add_to_static_cohort',
// Must match PosthogJwtAudience.CONVERSATIONS_TICKETS in posthog/jwt.py exactly.
CONVERSATIONS_TICKETS = 'posthog:conversations:tickets',
// Must match PosthogJwtAudience.CUSTOMER_ANALYTICS_ACCOUNTS in posthog/jwt.py exactly.
diff --git a/posthog/jwt.py b/posthog/jwt.py
index b7d3b7a600c4..e6321961bfb6 100644
--- a/posthog/jwt.py
+++ b/posthog/jwt.py
@@ -39,6 +39,7 @@ class PosthogJwtAudience(Enum):
WORKFLOW_SCOUT_RUN = "posthog:workflows:scout_run"
WORKFLOW_CLASSIFY = "posthog:workflows:classify"
WORKFLOW_VISION_REQUEST = "posthog:workflows:vision_request"
+ WORKFLOW_ADD_TO_STATIC_COHORT = "posthog:workflows:add_to_static_cohort"
CONVERSATIONS_TICKETS = "posthog:conversations:tickets"
CUSTOMER_ANALYTICS_ACCOUNTS = "posthog:customer_analytics:accounts"
SECURITY_HUB_RULES = "posthog:security_hub:rules"
diff --git a/posthog/settings/data_stores.py b/posthog/settings/data_stores.py
index a4a4f0659c68..65ee1d48aa99 100644
--- a/posthog/settings/data_stores.py
+++ b/posthog/settings/data_stores.py
@@ -640,6 +640,15 @@ WORKFLOW_VISION_REQUEST_JWT_SECRETS = get_list(
get_from_env("WORKFLOW_VISION_REQUEST_JWT_SECRET", "local-dev-workflow-vision-request-jwt" if DEBUG or TEST else "")
)
+# Signs the tokens a workflow's "Add to static cohort" step calls back with. The dev/test value
+# must match the plugin server's minting default.
+WORKFLOW_ADD_TO_STATIC_COHORT_JWT_SECRETS = get_list(
+ get_from_env(
+ "WORKFLOW_ADD_TO_STATIC_COHORT_JWT_SECRET",
+ "local-dev-workflow-add-to-static-cohort-jwt" if DEBUG or TEST else "",
+ )
+)
+
# Verifies the scoped JWTs the CDP worker's conversations ticket actions send to the internal
# ticket route (the worker mints, Django verifies; products/conversations/backend/api/internal.py).
# Comma-separated, newest first. Empty outside dev/test, so the internal route rejects every
diff --git a/posthog/tasks/calculate_cohort.py b/posthog/tasks/calculate_cohort.py
index fa2e89a34663..3dae3a43ce1c 100644
--- a/posthog/tasks/calculate_cohort.py
+++ b/posthog/tasks/calculate_cohort.py
@@ -4,6 +4,7 @@ from datetime import datetime, timedelta
from typing import Any, Optional
from django.conf import settings
+from django.core.cache import cache
from django.db import InterfaceError, OperationalError, transaction
from django.db.models import Case, DurationField, ExpressionWrapper, F, OuterRef, Q, QuerySet, Subquery, When
from django.utils import timezone
@@ -24,6 +25,7 @@ from posthog.clickhouse import query_tagging
from posthog.clickhouse.query_tagging import QueryTags, update_tags
from posthog.errors import CH_TRANSIENT_ERRORS, CHQueryErrorQueryWasCancelled
from posthog.exceptions_capture import capture_exception
+from posthog.models.scoping import with_team_scope
from posthog.models.team.team import Team
from posthog.models.user import User
from posthog.personhog_client.interceptor import is_transient_rpc_error
@@ -46,6 +48,7 @@ from products.cohorts.backend.models.util import (
COHORT_STATS_COLLECTION_DELAY_SECONDS,
CohortErrorCode,
close_open_population_attempts,
+ count_cohort_members,
get_all_cohort_dependencies,
get_all_cohort_dependents,
get_clickhouse_query_stats,
@@ -1111,6 +1114,41 @@ def insert_cohort_from_feature_flag(cohort_id: int, flag_key: str, team_id: int)
get_cohort_actors_for_feature_flag(cohort_id, flag_key, team_id, batchsize=2_000)
+STATIC_COHORT_COUNT_REFRESH_DELAY_SECONDS = 10
+
+
+def _static_cohort_count_refresh_key(cohort_id: int) -> str:
+ return f"static-cohort-count-refresh:{cohort_id}"
+
+
+def schedule_static_cohort_count_refresh(*, team_id: int, cohort_id: int) -> None:
+ """Recount a static cohort soon, at most once per delay, for callers that add members one at a time.
+
+ Call it after the insert. The task deletes the key before it counts, so an insert that finds the key
+ already set is still in the pending count.
+ """
+ key = _static_cohort_count_refresh_key(cohort_id)
+ if not cache.add(key, True, timeout=STATIC_COHORT_COUNT_REFRESH_DELAY_SECONDS * 10):
+ return
+ try:
+ refresh_static_cohort_count.apply_async(
+ kwargs={"team_id": team_id, "cohort_id": cohort_id},
+ countdown=STATIC_COHORT_COUNT_REFRESH_DELAY_SECONDS,
+ )
+ except Exception:
+ # No task is queued to delete the key, so leaving it set would block the next insert's recount.
+ cache.delete(key)
+ raise
+
+
+@shared_task(ignore_result=True, autoretry_for=(Exception,), retry_backoff=True, max_retries=5)
+@with_team_scope()
+def refresh_static_cohort_count(team_id: int, cohort_id: int) -> None:
+ cache.delete(_static_cohort_count_refresh_key(cohort_id))
+ count = count_cohort_members(team_id=team_id, cohort_id=cohort_id, consistency="strong")
+ Cohort.objects.filter(team_id=team_id, id=cohort_id, is_static=True).update(count=count)
+
+
def _collect_cohort_calculation_metrics(history: CohortCalculationHistory, start_time: datetime) -> None:
"""
Collect Prometheus metrics for cohort calculation based on the history record.
diff --git a/posthog/tasks/test/__snapshots__/test_task_registration.ambr b/posthog/tasks/test/__snapshots__/test_task_registration.ambr
index 5123f54f83a4..1264cd8737cc 100644
--- a/posthog/tasks/test/__snapshots__/test_task_registration.ambr
+++ b/posthog/tasks/test/__snapshots__/test_task_registration.ambr
@@ -21,6 +21,7 @@
'posthog.tasks.calculate_cohort.insert_cohort_from_filters',
'posthog.tasks.calculate_cohort.insert_cohort_from_query',
'posthog.tasks.calculate_cohort.publish_cohort_backfill_run_gauges',
+ 'posthog.tasks.calculate_cohort.refresh_static_cohort_count',
'posthog.tasks.calculate_cohort.trigger_cohort_backfill_run_task',
'posthog.tasks.comment_slack_sync.backfill_comment_slack_thread',
'posthog.tasks.comment_slack_sync.ingest_slack_discussion_reply',
diff --git a/posthog/tasks/test/test_calculate_cohort.py b/posthog/tasks/test/test_calculate_cohort.py
index 040c45c7855b..6eadc356bc6c 100644
--- a/posthog/tasks/test/test_calculate_cohort.py
+++ b/posthog/tasks/test/test_calculate_cohort.py
@@ -6,8 +6,9 @@ import time_machine
from posthog.test.base import APIBaseTest
from unittest.mock import MagicMock, patch
+from django.core.cache import cache
from django.db import InterfaceError, OperationalError
-from django.test import override_settings
+from django.test import SimpleTestCase, override_settings
from django.utils import timezone
import grpc
@@ -38,7 +39,9 @@ from posthog.tasks.calculate_cohort import (
increment_version_and_enqueue_calculate_cohort,
insert_cohort_from_filters,
insert_cohort_from_query,
+ refresh_static_cohort_count,
reset_stuck_cohorts,
+ schedule_static_cohort_count_refresh,
trigger_cohort_backfill_run_task,
update_cohort_metrics,
)
@@ -2279,3 +2282,18 @@ class TestCollectCohortQueryStats(APIBaseTest):
task.pop_request()
mock_logger.exception.assert_not_called()
+
+
+class TestScheduleStaticCohortCountRefresh(SimpleTestCase):
+ def test_a_failed_publish_lets_the_next_insert_schedule_the_recount(self) -> None:
+ cohort_id = 987654
+ self.addCleanup(cache.delete, f"static-cohort-count-refresh:{cohort_id}")
+
+ with patch.object(
+ refresh_static_cohort_count, "apply_async", side_effect=[ConnectionError("broker down"), None]
+ ) as publish:
+ with self.assertRaises(ConnectionError):
+ schedule_static_cohort_count_refresh(team_id=1, cohort_id=cohort_id)
+ schedule_static_cohort_count_refresh(team_id=1, cohort_id=cohort_id)
+
+ assert publish.call_count == 2
diff --git a/products/cdp/backend/flag_gated_templates.py b/products/cdp/backend/flag_gated_templates.py
index 7bc0f8a97c5f..0e6942b50835 100644
--- a/products/cdp/backend/flag_gated_templates.py
+++ b/products/cdp/backend/flag_gated_templates.py
@@ -15,6 +15,7 @@ logger = structlog.get_logger(__name__)
FLAG_GATED_TEMPLATE_IDS = {
"template-posthog-create-task": "workflow-ai-task-action",
"template-posthog-classify": "workflow-classify-action",
+ "template-posthog-add-to-static-cohort": "workflow-add-to-static-cohort-action",
}
diff --git a/products/cohorts/backend/facade/api.py b/products/cohorts/backend/facade/api.py
index 4df48091761e..189b3149e663 100644
--- a/products/cohorts/backend/facade/api.py
+++ b/products/cohorts/backend/facade/api.py
@@ -7,7 +7,10 @@ returns contract DTOs or primitives, never ORM instances or QuerySets.
from __future__ import annotations
-from products.cohorts.backend.models.cohort import Cohort
+from posthog.dataclasses import frozen
+from posthog.tasks.calculate_cohort import schedule_static_cohort_count_refresh
+
+from products.cohorts.backend.models.cohort import Cohort, ImportResolution
def cohort_exists_for_team(*, team_id: int, cohort_id: int) -> bool:
@@ -16,3 +19,45 @@ def cohort_exists_for_team(*, team_id: int, cohort_id: int) -> bool:
A soft-deleted cohort still counts, so a caller that holds a reference to one keeps it.
"""
return Cohort.objects.filter(team_id=team_id, id=cohort_id).exists()
+
+
+@frozen
+class CohortRef:
+ id: int
+ team_id: int
+ created_by_id: int | None
+ is_static: bool
+ deleted: bool
+
+
+def get_cohort_ref(*, team_id: int, cohort_id: int) -> CohortRef | None:
+ cohort = (
+ Cohort.objects.filter(team_id=team_id, id=cohort_id)
+ .only("id", "team_id", "created_by_id", "is_static", "deleted")
+ .first()
+ )
+ if cohort is None:
+ return None
+ return CohortRef(
+ id=cohort.id,
+ team_id=cohort.team_id,
+ created_by_id=cohort.created_by_id,
+ is_static=cohort.is_static,
+ deleted=cohort.deleted,
+ )
+
+
+def add_person_to_static_cohort(*, team_id: int, cohort_id: int, person_uuid: str) -> bool:
+ """Add one person to a static cohort. Returns False when the team has no person with that UUID.
+
+ A person who is already a member is not inserted again, but the check and the insert are separate
+ statements, so the caller must serialize concurrent calls for the same cohort and person.
+ """
+ cohort = Cohort.objects.get(team_id=team_id, id=cohort_id)
+ resolution = ImportResolution()
+ # save_state=False skips the full recount after each insert. The scheduled refresh updates the count.
+ cohort.insert_users_list_by_uuid([person_uuid], team_id=team_id, save_state=False, import_resolution=resolution)
+ if not resolution.matched_inputs:
+ return False
+ schedule_static_cohort_count_refresh(team_id=team_id, cohort_id=cohort_id)
+ return True
diff --git a/products/cohorts/backend/models/util.py b/products/cohorts/backend/models/util.py
index b16983cd986f..8a44371297ef 100644
--- a/products/cohorts/backend/models/util.py
+++ b/products/cohorts/backend/models/util.py
@@ -636,6 +636,11 @@ def _trim_trailing_settings(sql: str) -> str:
return sql[: sql.rfind("SETTINGS")]
+# Every INSERT creates a new part. Callers that add a few people per call, such as a workflow step that runs once
+# per person, would create one part per person, so ClickHouse buffers small inserts into shared parts instead.
+STATIC_COHORT_ASYNC_INSERT_MAX_ROWS = 100
+
+
def insert_static_cohort(person_uuids: Sequence[Optional[uuid.UUID]], cohort_id: int, *, team_id: int):
tag_queries(
product=ProductKey.COHORTS,
@@ -654,7 +659,12 @@ def insert_static_cohort(person_uuids: Sequence[Optional[uuid.UUID]], cohort_id:
}
for person_uuid in person_uuids
]
- sync_execute(INSERT_PERSON_STATIC_COHORT, persons)
+ # wait_for_async_insert returns only after the buffer is flushed, so a failed write still raises and a
+ # following membership read sees the row.
+ insert_settings = (
+ {"async_insert": 1, "wait_for_async_insert": 1} if len(persons) <= STATIC_COHORT_ASYNC_INSERT_MAX_ROWS else None
+ )
+ sync_execute(INSERT_PERSON_STATIC_COHORT, persons, settings=insert_settings)
def remove_person_from_static_cohort(person_uuid: uuid.UUID, cohort_id: int, *, team_id: int):
diff --git a/products/workflows/backend/facade/api.py b/products/workflows/backend/facade/api.py
index 4840094292de..a75309846cb8 100644
--- a/products/workflows/backend/facade/api.py
+++ b/products/workflows/backend/facade/api.py
@@ -25,6 +25,7 @@ from products.workflows.backend.facade.contracts import (
WorkflowVisionScanDailyLimits,
)
from products.workflows.backend.models import HogFlow, TeamWorkflowsConfig
+from products.workflows.backend.models.hog_flow.hog_flow import static_cohort_ids
from products.workflows.backend.services.batch_jobs import create_batch_job
from products.workflows.backend.services.default_email_sender import (
clear_default_email_sender,
@@ -142,6 +143,14 @@ def get_workflow_owner_id(*, team_id: int, workflow_id: UUID) -> int | None:
raise WorkflowNotFound() from None
+def get_workflow_static_cohort_ids(*, team_id: int, workflow_id: UUID) -> set[int]:
+ try:
+ actions = HogFlow.objects.values_list("actions", flat=True).get(team_id=team_id, id=workflow_id)
+ except HogFlow.DoesNotExist:
+ raise WorkflowNotFound() from None
+ return static_cohort_ids(actions)
+
+
def workflow_exists(*, team_id: int, workflow_id: UUID) -> bool:
return HogFlow.objects.filter(team_id=team_id, id=workflow_id).exists()
diff --git a/products/workflows/backend/facade/service_jwt.py b/products/workflows/backend/facade/service_jwt.py
index dabe5f89cab3..db781ddbb1d6 100644
--- a/products/workflows/backend/facade/service_jwt.py
+++ b/products/workflows/backend/facade/service_jwt.py
@@ -1,11 +1,12 @@
"""The scoped service JWT purposes that the workflow callback endpoints verify.
-The plugin server mints tokens for the "Create AI task", "Run scout", "Classify with AI" and
-"Replay Vision" workflow steps.
+The plugin server mints tokens for the "Create AI task", "Run scout", "Classify with AI",
+"Replay Vision" and "Add to static cohort" workflow steps.
"""
from products.workflows.backend.service_jwt import (
TASKS_CREATE_PURPOSE,
+ WORKFLOW_ADD_TO_STATIC_COHORT_PURPOSE,
WORKFLOW_CLASSIFY_PURPOSE,
WORKFLOW_SCOUT_RUN_PURPOSE,
WORKFLOW_VISION_REQUEST_PURPOSE,
@@ -13,6 +14,7 @@ from products.workflows.backend.service_jwt import (
__all__ = [
"TASKS_CREATE_PURPOSE",
+ "WORKFLOW_ADD_TO_STATIC_COHORT_PURPOSE",
"WORKFLOW_CLASSIFY_PURPOSE",
"WORKFLOW_SCOUT_RUN_PURPOSE",
"WORKFLOW_VISION_REQUEST_PURPOSE",
diff --git a/products/workflows/backend/facade/workflows.py b/products/workflows/backend/facade/workflows.py
index 7bf186c2d79f..089ac95c5acb 100644
--- a/products/workflows/backend/facade/workflows.py
+++ b/products/workflows/backend/facade/workflows.py
@@ -2,6 +2,7 @@
each with its secret inputs masked."""
from products.workflows.backend.models.hog_flow.hog_flow import (
+ ADD_TO_STATIC_COHORT_TEMPLATE_ID,
BILLABLE_ACTION_TYPES,
COHORT_TRIGGER_TRANSITIONS,
PERSON_DEPENDENT_ACTION_TYPES,
@@ -9,6 +10,8 @@ from products.workflows.backend.models.hog_flow.hog_flow import (
SUPPORTED_ACTION_TYPES,
TRIGGER_TYPES,
WORKFLOW_SAFE_INTERNAL_EVENTS,
+ literal_static_cohort_id,
+ static_cohort_ids,
)
from products.workflows.backend.services.hog_flow_reads import (
BROADCAST_STATUSES,
@@ -24,6 +27,7 @@ from products.workflows.backend.services.hog_flow_reads import (
)
__all__ = [
+ "ADD_TO_STATIC_COHORT_TEMPLATE_ID",
"BILLABLE_ACTION_TYPES",
"COHORT_TRIGGER_TRANSITIONS",
"PERSON_DEPENDENT_ACTION_TYPES",
@@ -31,6 +35,8 @@ __all__ = [
"SUPPORTED_ACTION_TYPES",
"TRIGGER_TYPES",
"WORKFLOW_SAFE_INTERNAL_EVENTS",
+ "literal_static_cohort_id",
+ "static_cohort_ids",
"BROADCAST_STATUSES",
"WORKFLOW_FIELD_FILTER_PARAMS",
"WORKFLOW_TYPES",
diff --git a/products/workflows/backend/models/hog_flow/hog_flow.py b/products/workflows/backend/models/hog_flow/hog_flow.py
index b0d1bc1a6f89..54e45b8269b4 100644
--- a/products/workflows/backend/models/hog_flow/hog_flow.py
+++ b/products/workflows/backend/models/hog_flow/hog_flow.py
@@ -1,4 +1,4 @@
-from typing import TYPE_CHECKING, Final
+from typing import TYPE_CHECKING, Any, Final
from django.db import models, transaction
from django.db.models.signals import post_delete, post_save
@@ -114,6 +114,37 @@ ROW_SCOPED_TRIGGER_TYPES: Final[set[str]] = {
}
+# The "Add to static cohort" step. Its template lives in the plugin server.
+ADD_TO_STATIC_COHORT_TEMPLATE_ID: Final[str] = "template-posthog-add-to-static-cohort"
+
+
+def literal_static_cohort_id(inputs: Any) -> int | None:
+ """The cohort id an "Add to static cohort" step names as a plain value, or None."""
+ cohort_input = inputs.get("cohort_id") if isinstance(inputs, dict) else None
+ cohort_id = cohort_input.get("value") if isinstance(cohort_input, dict) else None
+ if isinstance(cohort_id, bool) or not isinstance(cohort_id, int) or cohort_id < 1:
+ return None
+ return cohort_id
+
+
+def static_cohort_ids(actions: Any) -> set[int]:
+ """The cohorts that the "Add to static cohort" steps in these actions add people to.
+
+ Only function actions count, because the serializer checks cohort access for those alone.
+ """
+ cohort_ids: set[int] = set()
+ for action in actions if isinstance(actions, list) else []:
+ if not isinstance(action, dict) or action.get("type") != "function":
+ continue
+ config = action.get("config")
+ if not isinstance(config, dict) or config.get("template_id") != ADD_TO_STATIC_COHORT_TEMPLATE_ID:
+ continue
+ cohort_id = literal_static_cohort_id(config.get("inputs"))
+ if cohort_id is not None:
+ cohort_ids.add(cohort_id)
+ return cohort_ids
+
+
def hog_flow_origin_product_choices() -> list[tuple[str, str | Promise]]:
# Callable so growing the enum doesn't generate a no-op migration.
return list(HogFlow.OriginProduct.choices)
diff --git a/products/workflows/backend/presentation/views/hog_flow.py b/products/workflows/backend/presentation/views/hog_flow.py
index 80ca917cd575..4c62fbd49330 100644
--- a/products/workflows/backend/presentation/views/hog_flow.py
+++ b/products/workflows/backend/presentation/views/hog_flow.py
@@ -83,6 +83,7 @@ from posthog.synthetic_user import SyntheticUser
from posthog.user_permissions import UserPermissions
from posthog.utils import relative_date_parse_with_delta_mapping
+from products.access_control.backend.facade.contracts import ObjectAccessRef
from products.access_control.backend.facade.user_access_control import UserAccessControl, visible_teams_for_user
from products.access_control.backend.presentation.access_control import (
AccessControlViewSetMixin,
@@ -122,6 +123,7 @@ from products.cdp.backend.presentation.serializers import (
InputsSerializer,
require_viewer_access_to_added_actions,
)
+from products.cohorts.backend.facade.api import get_cohort_ref
from products.messaging.backend.presentation.views.serializers import DesignOperationSerializer
from products.notifications.backend.facade.api import publish_resource_edited
from products.replay_vision.backend.facade.api import (
@@ -285,6 +287,7 @@ from products.workflows.backend.facade.validation import (
realtime_cohort_cant_finish_error,
)
from products.workflows.backend.facade.workflows import (
+ ADD_TO_STATIC_COHORT_TEMPLATE_ID,
BILLABLE_ACTION_TYPES,
BROADCAST_STATUSES,
COHORT_TRIGGER_TRANSITIONS,
@@ -299,6 +302,8 @@ from products.workflows.backend.facade.workflows import (
get_workflow_edit_state,
get_workflow_ref,
list_workflows,
+ literal_static_cohort_id,
+ static_cohort_ids,
workflow_from_fields,
workflow_publish_impact,
)
@@ -1616,6 +1621,45 @@ class HogFlowActionSerializer(serializers.Serializer):
if error is not None:
raise serializers.ValidationError({"template_id": error})
+ def _validate_add_to_static_cohort_action(self, inputs: dict, *, strict: bool) -> None:
+ """The step adds people as a service, so whoever saves it must be able to edit the cohort it names.
+
+ Runs on lenient draft saves too. The callback endpoint accepts only cohorts the saved workflow names,
+ so this is the one check that guards every way to run the step."""
+ cohort_id = literal_static_cohort_id(inputs)
+ if cohort_id is None:
+ if strict:
+ raise serializers.ValidationError({"inputs": {"cohort_id": "Choose a static cohort."}})
+ return
+ # Someone already passed this check for a cohort the saved workflow names, so other editors can keep
+ # saving the workflow.
+ if cohort_id in (self.context.get("stored_static_cohort_ids") or set()):
+ return
+ get_team = self.context.get("get_team")
+ if get_team is None:
+ return
+ team = get_team()
+ cohort = get_cohort_ref(team_id=team.id, cohort_id=cohort_id)
+ if cohort is None or cohort.deleted or not cohort.is_static:
+ raise serializers.ValidationError({"inputs": {"cohort_id": "Choose a static cohort."}})
+
+ request = self.context.get("request")
+ scopes = get_authenticator_scopes(getattr(request, "successful_authenticator", None))
+ if scopes is not None and "*" not in scopes and "cohort:write" not in scopes:
+ raise serializers.ValidationError(
+ {"inputs": {"cohort_id": "Adding people to a cohort needs a key with the cohort:write scope."}}
+ )
+ user = getattr(request, "user", None)
+ if user is None or not user.is_authenticated or isinstance(user, SyntheticUser):
+ return
+ cohort_ref = ObjectAccessRef(
+ resource="cohort", id=str(cohort.id), team_id=cohort.team_id, created_by_id=cohort.created_by_id
+ )
+ if not UserAccessControl(user=user, team=team).check_access_level_for_ref(cohort_ref, "editor"):
+ raise serializers.ValidationError(
+ {"inputs": {"cohort_id": "You need edit access to this cohort to add people to it."}}
+ )
+
def _validate_run_scout_action(self) -> None:
"""Save-time check for the "Run scout" step: reject it in a child environment, matching
the runtime refusal in start_workflow_scout_run, so a broken step fails at save instead of
@@ -1852,6 +1896,10 @@ class HogFlowActionSerializer(serializers.Serializer):
get_team = self.context.get("get_team")
if get_team is not None:
_apply_email_template_content(config, get_team(), strict, self.context)
+ # Before template resolution, because a lenient save of a gated or unknown template skips input
+ # validation but still stores the cohort ID that the callback later trusts.
+ if data.get("type") == "function" and template_id == ADD_TO_STATIC_COHORT_TEMPLATE_ID:
+ self._validate_add_to_static_cohort_action(config.get("inputs") or {}, strict=strict)
template = get_function_template_schema(template_id)
gating_flag = FLAG_GATED_TEMPLATE_IDS.get(template_id)
already_stored = data.get("id") in (self.context.get("stored_gated_template_action_ids") or set())
@@ -3202,6 +3250,8 @@ class HogFlowSerializer(HogFlowMinimalSerializer):
and (action.get("config") or {}).get("template_id") in FLAG_GATED_TEMPLATE_IDS
}
+ self.context["stored_static_cohort_ids"] = static_cohort_ids(instance.actions if instance else None)
+
self.context["stored_cohort_triggers"] = {
action["id"]: {
"cohort_id": (action.get("config") or {}).get("cohort_id"),
@@ -3408,6 +3458,11 @@ class HogFlowSerializer(HogFlowMinimalSerializer):
for action in actions
if action.get("type") in PERSON_DEPENDENT_ACTION_TYPES
}
+ | {
+ ADD_TO_STATIC_COHORT_TEMPLATE_ID
+ for action in actions
+ if (action.get("config") or {}).get("template_id") == ADD_TO_STATIC_COHORT_TEMPLATE_ID
+ }
)
if offending_types:
raise serializers.ValidationError(
diff --git a/products/workflows/backend/presentation/views/workflow_static_cohort_members.py b/products/workflows/backend/presentation/views/workflow_static_cohort_members.py
new file mode 100644
index 000000000000..061a83d9997c
--- /dev/null
+++ b/products/workflows/backend/presentation/views/workflow_static_cohort_members.py
@@ -0,0 +1,112 @@
+import uuid
+from typing import Any, cast
+
+from drf_spectacular.utils import OpenApiResponse, extend_schema
+from redis.exceptions import LockError
+from rest_framework import serializers, status, viewsets
+from rest_framework.permissions import IsAuthenticated
+from rest_framework.request import Request
+from rest_framework.response import Response
+
+from posthog.auth import InternalAPIUser
+from posthog.redis import get_client
+
+from products.cohorts.backend.facade.api import add_person_to_static_cohort, get_cohort_ref
+from products.workflows.backend.facade.api import WorkflowNotFound, get_workflow_static_cohort_ids
+from products.workflows.backend.facade.service_jwt import WORKFLOW_ADD_TO_STATIC_COHORT_PURPOSE
+from products.workflows.backend.presentation.views.workflow_step_auth import WorkflowStepJWTAuthentication
+
+
+class WorkflowStaticCohortMemberJWTAuthentication(WorkflowStepJWTAuthentication):
+ purpose = WORKFLOW_ADD_TO_STATIC_COHORT_PURPOSE
+
+
+class WorkflowStaticCohortMemberRequestSerializer(serializers.Serializer):
+ cohort_id = serializers.IntegerField(min_value=1, help_text="ID of the static cohort to add the person to.")
+ person_uuid = serializers.UUIDField(help_text="UUID of the person the workflow run is for.")
+
+
+class WorkflowStaticCohortMemberResponseSerializer(serializers.Serializer):
+ detail = serializers.CharField(help_text="A short result message for the workflow log.")
+
+
+class WorkflowStaticCohortMemberViewSet(viewsets.GenericViewSet):
+ """Add the workflow run's person to a static cohort, for the workflow's "Add to static cohort" step.
+
+ Authenticated by a scoped service JWT the plugin server mints, never by a user credential. The write runs
+ as a service, so the endpoint only accepts a cohort that the saved workflow names. The workflow serializer
+ checks that the person who saves the step can edit that cohort. A test run or a draft sends its own copy of
+ the step, which can name any cohort, so the cohort id in the request is not enough on its own."""
+
+ authentication_classes = [WorkflowStaticCohortMemberJWTAuthentication]
+ permission_classes = [IsAuthenticated]
+ serializer_class = WorkflowStaticCohortMemberRequestSerializer
+
+ @extend_schema(
+ request=WorkflowStaticCohortMemberRequestSerializer,
+ responses={
+ 200: WorkflowStaticCohortMemberResponseSerializer,
+ 403: OpenApiResponse(
+ response=WorkflowStaticCohortMemberResponseSerializer,
+ description="The saved workflow doesn't add people to this cohort",
+ ),
+ 404: OpenApiResponse(
+ response=WorkflowStaticCohortMemberResponseSerializer,
+ description="The person doesn't exist in this project",
+ ),
+ 409: OpenApiResponse(
+ response=WorkflowStaticCohortMemberResponseSerializer,
+ description="The cohort was deleted or isn't static",
+ ),
+ 422: OpenApiResponse(
+ response=WorkflowStaticCohortMemberResponseSerializer, description="The workflow no longer exists"
+ ),
+ 503: OpenApiResponse(
+ response=WorkflowStaticCohortMemberResponseSerializer,
+ description="Another run is adding the same person. The caller retries.",
+ ),
+ },
+ summary="Add a workflow person to a static cohort",
+ )
+ def create(self, request: Request, **kwargs: Any) -> Response:
+ # Both come from the verified token, not the URL or body.
+ user = cast(InternalAPIUser, request.user)
+ team_id = cast(int, user.current_team_id)
+ hog_flow_id = cast(uuid.UUID, request.auth)
+
+ serializer = WorkflowStaticCohortMemberRequestSerializer(data=request.data)
+ serializer.is_valid(raise_exception=True)
+ cohort_id: int = serializer.validated_data["cohort_id"]
+ person_uuid = str(serializer.validated_data["person_uuid"])
+
+ try:
+ allowed_cohort_ids = get_workflow_static_cohort_ids(team_id=team_id, workflow_id=hog_flow_id)
+ except WorkflowNotFound:
+ return _respond("Workflow no longer exists.", status.HTTP_422_UNPROCESSABLE_ENTITY)
+ if cohort_id not in allowed_cohort_ids:
+ return _respond(
+ "The saved workflow doesn't add people to this cohort. Save or publish the workflow, then try again.",
+ status.HTTP_403_FORBIDDEN,
+ )
+
+ cohort = get_cohort_ref(team_id=team_id, cohort_id=cohort_id)
+ if cohort is None or cohort.deleted or not cohort.is_static:
+ return _respond("The cohort was deleted or isn't static.", status.HTTP_409_CONFLICT)
+
+ # The insert checks for an existing member and then writes, so two runs for the same person must not
+ # overlap. Otherwise both see no member and the person is stored twice.
+ lock = get_client().lock(
+ f"workflow-static-cohort-member:{team_id}:{cohort_id}:{person_uuid}", timeout=30, blocking_timeout=5
+ )
+ try:
+ with lock:
+ added = add_person_to_static_cohort(team_id=team_id, cohort_id=cohort_id, person_uuid=person_uuid)
+ except LockError:
+ return _respond("Another run is adding this person. Trying again.", status.HTTP_503_SERVICE_UNAVAILABLE)
+ if not added:
+ return _respond("This person doesn't have a profile yet, so they weren't added.", status.HTTP_404_NOT_FOUND)
+ return _respond("The person is in the static cohort.")
+
+
+def _respond(detail: str, http_status: int = status.HTTP_200_OK) -> Response:
+ return Response(WorkflowStaticCohortMemberResponseSerializer({"detail": detail}).data, status=http_status)
diff --git a/products/workflows/backend/routes.py b/products/workflows/backend/routes.py
index 583d61001597..af65ad870b57 100644
--- a/products/workflows/backend/routes.py
+++ b/products/workflows/backend/routes.py
@@ -15,6 +15,7 @@ from products.workflows.backend.presentation.views import (
workflow_scout_runs,
workflow_sending_rules,
workflow_setup,
+ workflow_static_cohort_members,
workflow_tasks,
workflow_vision_requests,
)
@@ -79,6 +80,12 @@ def register_routes(routers: RouterRegistry) -> None:
"project_workflow_vision_requests",
["team_id"],
)
+ routers.projects.register(
+ r"workflow_static_cohort_members",
+ workflow_static_cohort_members.WorkflowStaticCohortMemberViewSet,
+ "project_workflow_static_cohort_members",
+ ["team_id"],
+ )
routers.projects.register(
r"hog_flow_templates",
hog_flow_template.HogFlowTemplateViewSet,
diff --git a/products/workflows/backend/service_jwt.py b/products/workflows/backend/service_jwt.py
index cb3d88a57983..29f9bdd3dbf2 100644
--- a/products/workflows/backend/service_jwt.py
+++ b/products/workflows/backend/service_jwt.py
@@ -28,3 +28,9 @@ WORKFLOW_VISION_REQUEST_PURPOSE = ScopedServiceJwtPurpose(
audience=PosthogJwtAudience.WORKFLOW_VISION_REQUEST,
settings_name="WORKFLOW_VISION_REQUEST_JWT_SECRETS",
)
+
+# Its own key, for the same narrowest-scope reason as WORKFLOW_SCOUT_RUN_PURPOSE.
+WORKFLOW_ADD_TO_STATIC_COHORT_PURPOSE = ScopedServiceJwtPurpose(
+ audience=PosthogJwtAudience.WORKFLOW_ADD_TO_STATIC_COHORT,
+ settings_name="WORKFLOW_ADD_TO_STATIC_COHORT_JWT_SECRETS",
+)
diff --git a/products/workflows/backend/tests/api/test_hog_flow.py b/products/workflows/backend/tests/api/test_hog_flow.py
index b23d81a3ab76..33379d78f572 100644
--- a/products/workflows/backend/tests/api/test_hog_flow.py
+++ b/products/workflows/backend/tests/api/test_hog_flow.py
@@ -8136,3 +8136,150 @@ class TestClassifyActionValidation(APIBaseTest):
response = self._post_flow(categories, question, model)
assert response.status_code == expected, response.json()
+
+
+class TestAddToStaticCohortActionValidation(APIBaseTest):
+ def setUp(self):
+ super().setUp()
+ template = deepcopy(webhook_template)
+ template["id"] = "template-posthog-add-to-static-cohort"
+ template["name"] = "Add to static cohort"
+ template["inputs_schema"] = [
+ {"key": "cohort_id", "type": "number", "label": "Static cohort", "secret": False, "required": True}
+ ]
+ sync_template_to_db(template)
+ self.cohort = Cohort.objects.create(team=self.team, name="Onboarded", is_static=True)
+
+ def _step(self, cohort_id: int) -> dict:
+ return {
+ "id": "add_to_cohort",
+ "name": "add_to_cohort",
+ "type": "function",
+ "config": {
+ "template_id": "template-posthog-add-to-static-cohort",
+ "inputs": {"cohort_id": {"value": cohort_id}},
+ },
+ }
+
+ def _save(self, trigger: dict = _TRIGGER, status_: str = "draft", **extra: Any):
+ with patch("products.workflows.backend.presentation.views.hog_flow.gated_template_enabled", return_value=True):
+ return self.client.post(
+ f"/api/projects/{self.team.id}/hog_flows",
+ {
+ "name": "Onboarding",
+ "status": status_,
+ "actions": [trigger, self._step(self.cohort.id)],
+ "edges": [],
+ },
+ format="json",
+ HTTP_X_POSTHOG_CLIENT="mcp",
+ **extra,
+ )
+
+ def _restrict_cohort(self, *, resource_level: str | None, object_level: str | None) -> None:
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL}
+ ]
+ self.organization.save()
+ if resource_level:
+ AccessControl.objects.create(team=self.team, resource="cohort", access_level=resource_level)
+ if object_level:
+ AccessControl.objects.create(
+ team=self.team,
+ resource="cohort",
+ resource_id=str(self.cohort.id),
+ access_level=object_level,
+ organization_member=self.organization_membership,
+ )
+
+ @parameterized.expand(
+ [
+ ("cohort_editor", True, None, None, status.HTTP_201_CREATED),
+ ("dynamic_cohort", False, None, None, status.HTTP_400_BAD_REQUEST),
+ ("cohort_viewer", True, None, "viewer", status.HTTP_400_BAD_REQUEST),
+ ("editor_grant_on_a_viewer_resource", True, "viewer", "editor", status.HTTP_201_CREATED),
+ ]
+ )
+ def test_saving_the_step_needs_edit_access_to_a_static_cohort(
+ self, _name: str, is_static: bool, resource_level: str | None, object_level: str | None, expected: int
+ ) -> None:
+ Cohort.objects.filter(id=self.cohort.id).update(is_static=is_static)
+ self._restrict_cohort(resource_level=resource_level, object_level=object_level)
+
+ response = self._save()
+
+ assert response.status_code == expected, response.json()
+
+ @parameterized.expand(
+ [
+ ("without_cohort_write", ["hog_flow:write"], status.HTTP_400_BAD_REQUEST),
+ ("with_cohort_write", ["hog_flow:write", "cohort:write"], status.HTTP_201_CREATED),
+ ]
+ )
+ def test_an_api_key_needs_the_cohort_write_scope(self, _name: str, scopes: list[str], expected: int) -> None:
+ key = generate_random_token_personal()
+ PersonalAPIKey.objects.create(label="test", user=self.user, secure_value=hash_key_value(key), scopes=scopes)
+ self.client.logout()
+
+ response = self._save(headers={"authorization": f"Bearer {key}"})
+
+ assert response.status_code == expected, response.json()
+
+ def test_another_editor_can_keep_saving_a_workflow_that_already_adds_to_the_cohort(self) -> None:
+ flow = HogFlow.objects.create(
+ team=self.team,
+ name="Onboarding",
+ trigger=_TRIGGER["config"],
+ actions=[_TRIGGER, self._step(self.cohort.id)],
+ )
+ self._restrict_cohort(resource_level=None, object_level="viewer")
+
+ with patch("products.workflows.backend.presentation.views.hog_flow.gated_template_enabled", return_value=True):
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/hog_flows/{flow.id}",
+ {"name": "Renamed", "actions": [_TRIGGER, self._step(self.cohort.id)]},
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+
+ def test_a_trigger_without_a_person_cannot_use_the_step(self) -> None:
+ trigger = {
+ "id": "trigger_node",
+ "name": "trigger_1",
+ "type": "trigger",
+ "config": {"type": "data-warehouse-table", "table_name": "some_table", "filters": {"properties": []}},
+ }
+
+ response = self._save(trigger=trigger, status_="active")
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()
+ assert response.json()["attr"] == "actions", response.json()
+
+ def test_a_cohort_stored_on_a_non_function_action_is_still_checked(self) -> None:
+ exit_with_step_config = {**self._step(self.cohort.id), "type": "exit"}
+ flow = HogFlow.objects.create(
+ team=self.team, name="Onboarding", trigger=_TRIGGER["config"], actions=[_TRIGGER, exit_with_step_config]
+ )
+ self._restrict_cohort(resource_level=None, object_level="viewer")
+
+ with patch("products.workflows.backend.presentation.views.hog_flow.gated_template_enabled", return_value=True):
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/hog_flows/{flow.id}",
+ {"actions": [_TRIGGER, self._step(self.cohort.id)]},
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()
+
+ def test_a_lenient_draft_save_checks_the_cohort_while_the_flag_is_off(self) -> None:
+ self._restrict_cohort(resource_level=None, object_level="viewer")
+
+ with patch("products.workflows.backend.presentation.views.hog_flow.gated_template_enabled", return_value=False):
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/hog_flows",
+ {"name": "Onboarding", "actions": [_TRIGGER, self._step(self.cohort.id)], "edges": []},
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()
diff --git a/products/workflows/backend/tests/api/test_workflow_static_cohort_members_api.py b/products/workflows/backend/tests/api/test_workflow_static_cohort_members_api.py
new file mode 100644
index 000000000000..197799e0172d
--- /dev/null
+++ b/products/workflows/backend/tests/api/test_workflow_static_cohort_members_api.py
@@ -0,0 +1,99 @@
+from datetime import timedelta
+from typing import Any
+from uuid import uuid4
+
+from posthog.test.base import APIBaseTest, ClickhouseTestMixin
+
+from django.test import override_settings
+
+from parameterized import parameterized
+from rest_framework import status
+
+from posthog.jwt import PosthogJwtAudience, encode_jwt
+from posthog.test.authentication_checks import covers_authentication
+from posthog.test.persons import create_person
+
+from products.cohorts.backend.models.cohort import Cohort
+from products.cohorts.backend.models.util import count_cohort_members
+from products.workflows.backend.models import HogFlow
+from products.workflows.backend.presentation.views.workflow_static_cohort_members import (
+ WorkflowStaticCohortMemberJWTAuthentication,
+)
+
+SECRET = "test-workflow-add-to-static-cohort-jwt"
+
+
+def _step(cohort_id: int) -> dict[str, Any]:
+ return {
+ "id": "add_to_cohort",
+ "name": "add_to_cohort",
+ "type": "function",
+ "config": {
+ "template_id": "template-posthog-add-to-static-cohort",
+ "inputs": {"cohort_id": {"value": cohort_id}},
+ },
+ }
+
+
+@override_settings(WORKFLOW_ADD_TO_STATIC_COHORT_JWT_SECRETS=[SECRET])
+class TestWorkflowStaticCohortMembersAPI(ClickhouseTestMixin, APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.client.logout()
+ self.cohort = Cohort.objects.create(team=self.team, name="Onboarded", is_static=True)
+ self.person = create_person(team=self.team, distinct_ids=["d1"])
+ self.hog_flow = HogFlow.objects.create(
+ team=self.team,
+ name="Onboarding",
+ created_by=self.user,
+ trigger={"type": "manual"},
+ actions=[_step(self.cohort.id)],
+ )
+
+ def _post(self, *, cohort_id: int | None = None, person_uuid: str | None = None) -> Any:
+ token = encode_jwt(
+ {"team_id": self.team.id, "hog_flow_id": str(self.hog_flow.id)},
+ timedelta(minutes=5),
+ PosthogJwtAudience.WORKFLOW_ADD_TO_STATIC_COHORT,
+ signing_key=SECRET,
+ )
+ return self.client.post(
+ f"/api/projects/{self.team.id}/workflow_static_cohort_members/",
+ {"cohort_id": cohort_id or self.cohort.id, "person_uuid": person_uuid or str(self.person.uuid)},
+ format="json",
+ HTTP_AUTHORIZATION=f"Bearer {token}",
+ )
+
+ @covers_authentication(WorkflowStaticCohortMemberJWTAuthentication)
+ def test_a_repeated_add_keeps_one_membership_and_refreshes_the_count(self) -> None:
+ first = self._post()
+ second = self._post()
+
+ assert first.status_code == status.HTTP_200_OK, first.json()
+ assert second.status_code == status.HTTP_200_OK, second.json()
+ assert count_cohort_members(team_id=self.team.id, cohort_id=self.cohort.id, consistency="strong") == 1
+ self.cohort.refresh_from_db()
+ assert self.cohort.count == 1
+
+ @parameterized.expand(
+ [
+ ("cohort_not_on_the_saved_workflow", "other_cohort", None, status.HTTP_403_FORBIDDEN),
+ ("deleted_cohort", "deleted", None, status.HTTP_409_CONFLICT),
+ ("unknown_person", None, str(uuid4()), status.HTTP_404_NOT_FOUND),
+ ]
+ )
+ def test_refuses_without_adding_anyone(
+ self, _name: str, cohort_change: str | None, person_uuid: str | None, expected: int
+ ) -> None:
+ cohort_id = None
+ if cohort_change == "other_cohort":
+ cohort_id = Cohort.objects.create(team=self.team, name="Not on the workflow", is_static=True).id
+ elif cohort_change == "deleted":
+ Cohort.objects.filter(id=self.cohort.id).update(deleted=True)
+
+ response = self._post(cohort_id=cohort_id, person_uuid=person_uuid)
+
+ assert response.status_code == expected, response.json()
+ assert (
+ count_cohort_members(team_id=self.team.id, cohort_id=cohort_id or self.cohort.id, consistency="strong") == 0
+ )
diff --git a/products/workflows/frontend/Workflows/hogflows/steps/StepFunction.tsx b/products/workflows/frontend/Workflows/hogflows/steps/StepFunction.tsx
index 62b97960bd24..1ecb5f5b7fc3 100644
--- a/products/workflows/frontend/Workflows/hogflows/steps/StepFunction.tsx
+++ b/products/workflows/frontend/Workflows/hogflows/steps/StepFunction.tsx
@@ -1,6 +1,7 @@
import { useActions, useValues } from 'kea'
import { workflowLogic } from '../../workflowLogic'
+import { AddToStaticCohortConfiguration } from './components/AddToStaticCohortConfiguration'
import { AiTaskInstructionsCompare } from './components/AiTaskInstructionsCompare'
import { HogFlowFunctionConfiguration } from './components/HogFlowFunctionConfiguration'
import { StepSchemaErrors } from './components/StepSchemaErrors'
@@ -19,19 +20,27 @@ export function StepFunctionConfiguration({ node }: { node: StepFunctionNode }):
<>
<StepSchemaErrors />
{templateId === 'template-posthog-create-task' && <AiTaskInstructionsCompare actionId={node.id} />}
- <HogFlowFunctionConfiguration
- // Remount per node: the input renderer snapshots its values on mount, so switching to
- // another step of the same template must remount to show the newly selected node's inputs.
- key={node.id}
- templateId={templateId}
- inputs={inputs}
- setInputs={(inputs) => partialSetWorkflowActionConfig(node.id, { inputs })}
- mappings={mappings}
- setMappings={(mappings) => partialSetWorkflowActionConfig(node.id, { mappings })}
- errors={validationResult?.errors}
- warnings={validationResult?.warnings}
- emailFieldErrors={validationResult?.emailErrors}
- />
+ {templateId === 'template-posthog-add-to-static-cohort' ? (
+ <AddToStaticCohortConfiguration
+ inputs={inputs}
+ setInputs={(inputs) => partialSetWorkflowActionConfig(node.id, { inputs })}
+ error={validationResult?.errors?.cohort_id}
+ />
+ ) : (
+ <HogFlowFunctionConfiguration
+ // Remount per node: the input renderer snapshots its values on mount, so switching to
+ // another step of the same template must remount to show the newly selected node's inputs.
+ key={node.id}
+ templateId={templateId}
+ inputs={inputs}
+ setInputs={(inputs) => partialSetWorkflowActionConfig(node.id, { inputs })}
+ mappings={mappings}
+ setMappings={(mappings) => partialSetWorkflowActionConfig(node.id, { mappings })}
+ errors={validationResult?.errors}
+ warnings={validationResult?.warnings}
+ emailFieldErrors={validationResult?.emailErrors}
+ />
+ )}
</>
)
}
diff --git a/products/workflows/frontend/Workflows/hogflows/steps/components/AddToStaticCohortConfiguration.tsx b/products/workflows/frontend/Workflows/hogflows/steps/components/AddToStaticCohortConfiguration.tsx
new file mode 100644
index 000000000000..4d00f2b3fc15
--- /dev/null
+++ b/products/workflows/frontend/Workflows/hogflows/steps/components/AddToStaticCohortConfiguration.tsx
@@ -0,0 +1,48 @@
+import { useActions, useValues } from 'kea'
+import { useEffect } from 'react'
+
+import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
+import { TaxonomicPopover } from 'lib/components/TaxonomicPopover/TaxonomicPopover'
+import { LemonField } from 'lib/lemon-ui/LemonField'
+
+import { cohortsModel } from '~/models/cohortsModel'
+import { CyclotronJobInputType } from '~/types'
+
+export function AddToStaticCohortConfiguration({
+ inputs,
+ setInputs,
+ error,
+}: {
+ inputs: Record<string, CyclotronJobInputType>
+ setInputs: (inputs: Record<string, CyclotronJobInputType>) => void
+ error?: string
+}): JSX.Element {
+ const { cohortsById } = useValues(cohortsModel)
+ const { loadCohortsByIds } = useActions(cohortsModel)
+
+ const cohortId = typeof inputs.cohort_id?.value === 'number' ? inputs.cohort_id.value : null
+ const cohort = cohortId ? cohortsById[cohortId] : undefined
+
+ useEffect(() => {
+ if (cohortId) {
+ loadCohortsByIds({ ids: [cohortId] })
+ }
+ }, [cohortId, loadCohortsByIds])
+
+ return (
+ <LemonField.Pure
+ label="Static cohort"
+ info="Adds the workflow run's person. Nothing changes if they're already in the cohort."
+ error={error ?? (cohort && !cohort.is_static ? 'Choose a static cohort.' : undefined)}
+ >
+ <TaxonomicPopover
+ groupType={TaxonomicFilterGroupType.Cohorts}
+ value={cohortId}
+ onChange={(value) => setInputs({ ...inputs, cohort_id: { value: Number(value) } })}
+ renderValue={(value) => <>{cohortsById[value]?.name ?? `Cohort ${value}`}</>}
+ placeholder="Choose a static cohort"
+ data-attr="workflow-add-to-static-cohort-cohort"
+ />
+ </LemonField.Pure>
+ )
+}
diff --git a/products/workflows/frontend/Workflows/hogflows/workflowStepCatalog.ts b/products/workflows/frontend/Workflows/hogflows/workflowStepCatalog.ts
index 33cdd9f71c3d..bb7ad417e16f 100644
--- a/products/workflows/frontend/Workflows/hogflows/workflowStepCatalog.ts
+++ b/products/workflows/frontend/Workflows/hogflows/workflowStepCatalog.ts
@@ -184,6 +184,13 @@ const POSTHOG_NODES_TO_SHOW: CreateActionType[] = [
},
]
+const ADD_TO_STATIC_COHORT_ACTION_NODE: CreateActionType = {
+ type: 'function',
+ name: 'Add to static cohort',
+ description: 'Add the person to a static cohort.',
+ config: { template_id: 'template-posthog-add-to-static-cohort', inputs: {} },
+}
+
export interface StepCatalogContext {
featureFlags: FeatureFlagsSet
currentTeam: Pick<TeamPublicType | TeamType, 'id' | 'project_id'> | null
@@ -220,6 +227,13 @@ function aiSteps({ featureFlags, currentTeam }: StepCatalogContext): CreateActio
]
}
+function posthogSteps({ featureFlags }: StepCatalogContext): CreateActionType[] {
+ return [
+ ...POSTHOG_NODES_TO_SHOW,
+ ...(featureFlags[FEATURE_FLAGS.WORKFLOW_ADD_TO_STATIC_COHORT_ACTION] ? [ADD_TO_STATIC_COHORT_ACTION_NODE] : []),
+ ]
+}
+
const BETA_TEMPLATE_IDS = new Set(['template-posthog-create-task'])
export function isBetaStep(step: CreateActionType): boolean {
@@ -238,7 +252,7 @@ export function workflowStepSections(context: StepCatalogContext): StepCatalogSe
{ key: 'ai', title: 'AI', steps: aiSteps(context) },
{ key: 'delays', title: 'Delays', steps: forTrigger(DELAY_NODES_TO_SHOW, context.isRowScopedTrigger) },
{ key: 'split', title: 'Audience split', steps: forTrigger(LOGIC_NODES_TO_SHOW, context.isRowScopedTrigger) },
- { key: 'posthog', title: 'PostHog actions', steps: POSTHOG_NODES_TO_SHOW },
+ { key: 'posthog', title: 'PostHog actions', steps: posthogSteps(context) },
...getRegisteredActionNodeCategories(context.featureFlags).map((category) => ({
key: category.label,
title: category.label,